File: GSNibLoading.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 (2493 lines) | stat: -rw-r--r-- 61,946 bytes parent folder | download | duplicates (2)
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
/** <title>GSNibLoading</title>

   <abstract>
   These are templates for use with OSX Nib files.  These classes are the
   templates and other things which are needed for reading/writing nib files.
   </abstract>

   Copyright (C) 1997, 1999 Free Software Foundation, Inc.

   Author: Gregory John Casamento
   Date: 2003, 2005
   Author: Fred Kiefer
   Date: 2003, 2010

   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.
*/ 

#define EXPOSE_NSKeyedUnarchiver_IVARS

#import <Foundation/NSArchiver.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSBundle.h>
#import <Foundation/NSByteOrder.h>
#import <Foundation/NSCoder.h>
#import <Foundation/NSData.h>
#import <Foundation/NSDecimalNumber.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSDebug.h>
#import <Foundation/NSEnumerator.h>
#import <Foundation/NSException.h>
#import <Foundation/NSKeyedArchiver.h>
#import <Foundation/NSKeyValueCoding.h>
#import <Foundation/NSObjCRuntime.h>
#import <Foundation/NSSet.h>
#import <Foundation/NSString.h>

#import "GNUstepGUI/GSNibLoading.h"
#import "AppKit/NSApplication.h"
#import "AppKit/NSImage.h"
#import "AppKit/NSMenuItem.h"
#import "AppKit/NSMenuView.h"
#import "AppKit/NSNib.h"
#import "AppKit/NSScreen.h"
#import "AppKit/NSSound.h"
#import "AppKit/NSToolbar.h"
#import "GNUstepGUI/GSInstantiator.h"
#import "GSGuiPrivate.h"

static BOOL _isInInterfaceBuilder = NO;

@interface NSKeyedUnarchiver (NSClassSwapperPrivate)
- (Class) replacementClassForClassName: (NSString *)className;
@end

@interface NSApplication (NibCompatibility)
- (void) _setMainMenu: (NSMenu*)aMenu;
@end

@interface NSView (NibCompatibility)
- (void) _fixSubviews;
@end

/* Correct some instances where the ":" is missing from the method name in the label */
@interface NSNibControlConnector (NibCompatibility)
- (void) instantiateWithInstantiator: (id<GSInstantiator>)instantiator;
@end

@interface NSNibConnector (NibCompatibility)
- (void) instantiateWithInstantiator: (id<GSInstantiator>)instantiator;
@end

@interface NSDecimalNumberPlaceholder : NSObject
@end

@interface _NSCornerView : NSView
@end

@interface NSMenu (NibCompatibility)
- (void) _setMain: (BOOL)isMain;
@end
@interface NSMenu (GNUstepPrivate)
- (void) _setGeometry;
- (BOOL) _isMainMenu;
@end

@implementation NSMenu (NibCompatibility)
// FIXME: Why can't this be merged with setMain: ?
- (void) _setMain: (BOOL)isMain
{
  if (isMain)
    {
      NSMenuView	*oldRep;
      NSInterfaceStyle	oldStyle;
      NSInterfaceStyle	newStyle;
      NSString          *processName;

      if ([self numberOfItems] == 0)
        return;

      oldRep = [self menuRepresentation];
      oldStyle = [oldRep interfaceStyle];
      newStyle = NSInterfaceStyleForKey(@"NSMenuInterfaceStyle", nil);
      processName = [[NSProcessInfo processInfo] processName];

      /*
       * If necessary, rebuild menu for (different) style
       */
      if (oldStyle != newStyle)
        {
	  NSMenuView	*newRep;

	  newRep = [[NSMenuView alloc] initWithFrame: NSZeroRect];
	  if (newStyle == NSMacintoshInterfaceStyle
	    || newStyle == NSWindows95InterfaceStyle)
	    {
	      [newRep setHorizontal: YES];
	    }
	  else
	    {
	      [newRep setHorizontal: NO];
	    }
	  [newRep setInterfaceStyle: newStyle];
	  [self setMenuRepresentation: newRep];
	  RELEASE(newRep);
	}

      [[self window] setTitle: processName];
      [[self window] setLevel: NSMainMenuWindowLevel];

      // if it's a standard menu, transform it to be more NeXT'ish/GNUstep-like
      if (_menu.horizontal == NO)
        {
          NSMenuItem *appItem;
	  NSMenu *sub;
	  SEL	sel = @selector(terminate:);
          
	  /* The title of the main menu should be the process name.
	   */
          [self setTitle: processName];

	  /* If there is no 'quite' item (one which sends a -terminate:
	   * actions) we add one.
	   */
	  if ([self indexOfItemWithTarget: nil andAction: sel] < 0
	    && [self indexOfItemWithTarget: NSApp andAction: sel] < 0)
	    {
	      NSString *quitString;
	      NSMenuItem *quitItem;

	      quitString = [NSString stringWithFormat: @"%@ %@", 
		NSLocalizedString (@"Quit", @"Quit"), processName];
	      quitItem = [[NSMenuItem alloc] initWithTitle: quitString
		action: @selector(terminate:)
		keyEquivalent: @"q"];
              [self addItem: quitItem];
	    }

	  /* An OSX main menu has the first item pointing to a submenu
	   * whose contents are much the same as a GNUstep info menu.
	   */
          appItem = (NSMenuItem*)[self itemAtIndex: 0]; // Info item.
	  sub = [appItem submenu];
	  if (sub != nil)
	    {
              NSString	*infoString;
	      NSInteger	index;

	      infoString = NSLocalizedString (@"Info", @"Info");
	      [appItem setTitle: infoString];
	      [sub setTitle: infoString];
	      /* The submenu may contain a 'quit' item ... if so we need to
	       * remove it as we already added one to the main menu.
	       */
	      index = [sub indexOfItemWithTarget: nil andAction: sel];
	      if (index < 0)
		{
	          index = [sub indexOfItemWithTarget: NSApp andAction: sel];
		}
	      if (index >= 0)
		{
		  [sub removeItemAtIndex: index];
		}
	    }
        }

      [self _setGeometry];
      [self sizeToFit];

      if ([NSApp isActive])
        {
	  [self display];
	}
    }
  else 
    {
      [self close];
      [[self window] setLevel: NSSubmenuWindowLevel];
    }
}
@end

@implementation NSApplication (NibCompatibility)
- (void) _setMainMenu: (NSMenu*)aMenu
{
  if (_main_menu == aMenu)
    {
      return;
    }

  if (_main_menu != nil)
    {
      [_main_menu setMain: NO];
    }

  ASSIGN(_main_menu, aMenu);

  if (_main_menu != nil)
    {
      [_main_menu _setMain: YES];
    }
}
@end

@implementation NSView (NibCompatibility)
- (void) _setWindow: (id) w
{
  _window = w;
}

- (void) _fixSubviews
{
  NSEnumerator *en = [[self subviews] objectEnumerator];
  id v = nil;
  while ((v = [en nextObject]) != nil)
    {
      if ([v window] != [self window] ||
         [v superview] != self)
        {
          [v _setWindow: [self window]];
          RETAIN(v);
          [_sub_views removeObject: v];
          [self addSubview: v];
          RELEASE(v);
        }
      [v _fixSubviews];
    }
}
@end

/**
 * NSWindowTemplate
 *
 * Instances of this class take the place of all windows in the nib file.
 */
@implementation NSWindowTemplate
+ (void) initialize
{
  if (self == [NSWindowTemplate class]) 
    { 
      [self setVersion: 0];
    }
}

- (void) dealloc
{
  RELEASE(_title);
  RELEASE(_viewClass);
  RELEASE(_windowClass);
  RELEASE(_view);
  RELEASE(_autosaveName);
  RELEASE(_realObject);
  [super dealloc];
}

/**
 * Designated initializer for NSWindowTemplate.
 */
- (id) initWithWindow: (NSWindow *)window
            className: (NSString *)windowClass
           isDeferred: (BOOL) deferred
            isOneShot: (BOOL) oneShot
            isVisible: (BOOL) visible
       wantsToBeColor: (BOOL) wantsToBeColor
     autoPositionMask: (int) autoPositionMask
{
  if ((self = [super init]) != nil)
    {
      if (window != nil)
        {
          // object members
          ASSIGN(_title, [window title]);
          ASSIGN(_viewClass, NSStringFromClass([[window contentView] class]));
          ASSIGN(_windowClass, windowClass);
          ASSIGN(_view, [window contentView]);
          ASSIGN(_autosaveName, [window frameAutosaveName]);
          
          // style & size
          _windowStyle = [window styleMask];
          _backingStoreType = [window backingType];
          //_maxSize = [window maxSize];
          //_minSize = [window minSize];
          _maxSize = [window contentMaxSize];
          _minSize = [window contentMinSize];
          _windowRect = [window frame];
          _screenRect = [[NSScreen mainScreen] frame];
          
          // flags
          _flags.isHiddenOnDeactivate = [window hidesOnDeactivate];
          _flags.isNotReleasedOnClose = (![window isReleasedWhenClosed]);
          _flags.isDeferred = deferred;
          _flags.isOneShot = oneShot;
          _flags.isVisible = visible;
          _flags.wantsToBeColor = wantsToBeColor;
          _flags.dynamicDepthLimit = [window hasDynamicDepthLimit];
          _flags.autoPositionMask = autoPositionMask;
          _flags.savePosition = YES; // not yet implemented.
        }
    }
  return self;
}

- (id) initWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      if ([coder containsValueForKey: @"NSViewClass"])
        {
          ASSIGN(_viewClass, [coder decodeObjectForKey: @"NSViewClass"]);
        }
      if ([coder containsValueForKey: @"NSWindowClass"])
        {
          ASSIGN(_windowClass, [coder decodeObjectForKey: @"NSWindowClass"]);
        }
      if ([coder containsValueForKey: @"NSWindowStyleMask"])
        {
          _windowStyle = [coder decodeIntForKey: @"NSWindowStyleMask"];
        }
      if ([coder containsValueForKey: @"NSWindowBacking"])
        {
          _backingStoreType = [coder decodeIntForKey: @"NSWindowBacking"];
        }
      if ([coder containsValueForKey: @"NSWindowView"])
        {
          ASSIGN(_view, [coder decodeObjectForKey: @"NSWindowView"]);
        }
      if ([coder containsValueForKey: @"NSWTFlags"])
        {
          unsigned long flags = [coder decodeIntForKey: @"NSWTFlags"];
          memcpy((void *)&_flags,(void *)&flags,sizeof(struct _GSWindowTemplateFlags));
        }

      if ([coder containsValueForKey: @"NSWindowContentMinSize"])
        {
          _minSize = [coder decodeSizeForKey: @"NSWindowContentMinSize"];
        }
      else if ([coder containsValueForKey: @"NSMinSize"])
        {
          NSRect rect = NSZeroRect;
          rect.size = [coder decodeSizeForKey: @"NSMinSize"];
          rect = [NSWindow contentRectForFrameRect: rect
                                         styleMask: _windowStyle];
          _minSize = rect.size;
        }

      if ([coder containsValueForKey: @"NSWindowContentMaxSize"])
        {
          _maxSize = [coder decodeSizeForKey: @"NSWindowContentMaxSize"];
        }
      else if ([coder containsValueForKey: @"NSMaxSize"])
        {
          NSRect rect = NSZeroRect;
          rect.size = [coder decodeSizeForKey: @"NSMaxSize"];
          rect = [NSWindow contentRectForFrameRect: rect
                                         styleMask: _windowStyle];
          _maxSize = rect.size;
        }
      else
        {
          _maxSize = NSMakeSize (10e4, 10e4);
        }

      if ([coder containsValueForKey: @"NSWindowRect"])
        {
          _windowRect = [coder decodeRectForKey: @"NSWindowRect"];
        }
      if ([coder containsValueForKey: @"NSFrameAutosaveName"])
        {
	  ASSIGN(_autosaveName, [coder decodeObjectForKey: @"NSFrameAutosaveName"]);
        }
      if ([coder containsValueForKey: @"NSWindowTitle"])
        {
          ASSIGN(_title, [coder decodeObjectForKey: @"NSWindowTitle"]);
          _windowStyle |= NSTitledWindowMask;
        }

      _baseWindowClass = [NSWindow class];
    }
  else
    {
      [NSException raise: NSInvalidArgumentException 
                   format: @"Can't decode %@ with %@.",NSStringFromClass([self class]),
                   NSStringFromClass([coder class])];
    }
  return self;
}

- (void) encodeWithCoder: (NSCoder *)aCoder
{
  if ([aCoder allowsKeyedCoding])
    {
      unsigned long flags = 0; 
      NSRect rect = [NSWindow contentRectForFrameRect: _windowRect
                              styleMask: _windowStyle];
      memcpy((void *)&flags,(void *)&_flags,sizeof(unsigned long));

      [aCoder encodeObject: _viewClass forKey: @"NSViewClass"];
      [aCoder encodeObject: _windowClass forKey: @"NSWindowClass"];
      [aCoder encodeInt: _windowStyle forKey: @"NSWindowStyleMask"];
      [aCoder encodeInt: _backingStoreType forKey: @"NSWindowBacking"];
      [aCoder encodeObject: _view forKey: @"NSWindowView"];
      [aCoder encodeInt: flags forKey: @"NSWTFlags"];
      [aCoder encodeSize: _minSize forKey: @"NSWindowContentMinSize"];
      [aCoder encodeSize: _maxSize forKey: @"NSWindowContentMaxSize"];
      [aCoder encodeRect: rect forKey: @"NSWindowRect"];
      [aCoder encodeObject: _title forKey: @"NSWindowTitle"];
      [aCoder encodeObject: _autosaveName forKey: @"NSFrameAutosaveName"];
    }
}

/**
 * This method is used to get the real object when connections are established.
 */
- (id) nibInstantiate
{
  if (_realObject == nil)
    {
      Class aClass;

      if ([NSClassSwapper isInInterfaceBuilder])
        {
          aClass = [self baseWindowClass];
        }
      else
        {
          aClass = NSClassFromString(_windowClass);      
        }

      if (aClass == nil)
        {
          [NSException raise: NSInternalInconsistencyException
                       format: @"Unable to find class '%@'", _windowClass];
        }
      
      _realObject = [[aClass allocWithZone: NSDefaultMallocZone()]
                      initWithContentRect: _windowRect
                      styleMask: _windowStyle
                      backing: _backingStoreType
                      defer: _flags.isDeferred];
      
      // set flags...
      [_realObject setHidesOnDeactivate: _flags.isHiddenOnDeactivate];
      [_realObject setReleasedWhenClosed: !(_flags.isNotReleasedOnClose)];
      [_realObject setOneShot: _flags.isOneShot];
      // [_realObject setVisible: _flags.isVisible]; // this is determined by whether it's in the visible windows array...
      // [_realObject setWantsToBeColor: _flags.wantsToBeColor]; // not applicable on GNUstep.
      [_realObject setAutodisplay: YES];
      [_realObject setDynamicDepthLimit: _flags.dynamicDepthLimit];
      // [_realObject setAutoPositionMask: _flags.autoPositionMask]; // currently not implemented for nibs
      // [_realObject setAutoPosition: _flags.autoPosition];
      [_realObject setDynamicDepthLimit: _flags.dynamicDepthLimit];
      // [_realObject setFrameAutosaveName: _autosaveName]; // done after setting the min/max sizes

      // reset attributes...
      [_realObject setContentView: _view];
      //[_realObject setMinSize: _minSize];
      //[_realObject setMaxSize: _maxSize];
      [_realObject setTitle: _title];

      if ([_viewClass isKindOfClass: [NSToolbar class]])
	{
          // FIXME: No idea what is going on here
	  [_realObject setToolbar: (NSToolbar*)_viewClass];
	}

      [_realObject setContentMinSize: _minSize];
      [_realObject setContentMaxSize: _maxSize];
	  
      [_view _fixSubviews];

      // FIXME What is the point of calling -setFrame:display: here? It looks
      // like an effective no op to me.
      // resize the window...
      [_realObject setFrame: [NSWindow frameRectForContentRect: [self windowRect] 
                                       styleMask: [self windowStyle]]
                   display: NO];
      [_realObject setFrameAutosaveName: _autosaveName];
    } 
  return _realObject;
}

// setters and getters
/**
 * sets the type of backing store the window uses.
 */
- (void) setBackingStoreType: (NSBackingStoreType)type
{
  _backingStoreType = type;
}

/**
 * Returns the type of backing store which is used.
 */
- (NSBackingStoreType) backingStoreType
{
  return _backingStoreType;
}

/**
 * Sets whether or not the window is deferred.
 */
- (void) setDeferred: (BOOL)flag
{
  _flags.isDeferred = flag;
}

/**
 * Returns YES, if the window is deferred, NO otherwise.
 */
- (BOOL) isDeferred
{
  return _flags.isDeferred;
}

/**
 * Sets the maximum size of the window.
 */
- (void) setMaxSize: (NSSize)maxSize
{
  _maxSize = maxSize;
}

/**
 * Returns the maximum size of the window.
 */
- (NSSize) maxSize
{
  return _maxSize;
}

/**
 * Sets the minimum size of the window.
 */
- (void) setMinSize: (NSSize)minSize
{
  _minSize = minSize;
}

/**
 * Returns the maximum size of the window.
 */
- (NSSize) minSize
{
  return _minSize;
}

/**
 * Sets the window style.
 */
- (void) setWindowStyle: (unsigned)style
{
  _windowStyle = style;
}

/** 
 * Returns the window style.
 */
- (unsigned) windowStyle
{
  return _windowStyle;
}

/**
 * Sets the window title.
 */
- (void) setTitle: (NSString *) title
{
  ASSIGN(_title, title);
}

/**
 * Returns the window style.
 */
- (NSString *)title;
{
  return _title;
}

/**
 * Sets the class used for the content view.
 */
- (void) setViewClass: (NSString *)viewClass
{
  ASSIGN(_viewClass,viewClass);
}

/**
 * Returns the name of the class used for the content view.
 */
- (NSString *)viewClass
{
  return _viewClass;
}

/**
 * Sets the window rect.
 */
- (void) setWindowRect: (NSRect)rect
{
  _windowRect = rect;
}

/**
 * Returns the window rect.
 */
- (NSRect)windowRect
{
  return _windowRect;
}

/**
 * Sets the screen rect.
 */
- (void) setScreenRect: (NSRect)rect
{
  _screenRect = rect;
}

/**
 * Returns the screen rect.
 */
- (NSRect) screenRect
{
  return _screenRect;
}

/**
 * Sets the instantiated object/real object.
 */
- (void) setRealObject: (id)o
{
  ASSIGN(_realObject,o);
}

/**
 * Returns the real object represented by this template.
 */
- (id) realObject
{
  return _realObject;
}

/**
 * Sets the view instance.
 */ 
- (void) setView: (id)view
{
  ASSIGN(_view,view);
}

/** 
 * Gets the view instance.
 */
- (id) view
{
  return _view;
}

/**
 * sets the class name to be used when unarchiving the window.
 */
- (void) setClassName: (NSString *)name
{
  ASSIGN(_windowClass, name);
}

/**
 * Returns the class instance.
 */
- (NSString *)className
{
  return _windowClass;
}

/**
 * Returns the base window class.   This is usually NSWindow, but this method
 * is overriden in the editor so that a different class may be used to take the
 * place of the window.   In the case of Gorm, this is GormNSWindow.
 */
- (Class) baseWindowClass
{
  return _baseWindowClass;
}
@end

/*
 * NSViewTemplate
 *
 * Template for any classes which derive from NSView
 */
@implementation NSViewTemplate
+ (void) initialize
{
  if (self == [NSViewTemplate class]) 
    {
      [self setVersion: 0];
    }
}

- (void) dealloc
{
  RELEASE(_className);
  RELEASE(_realObject);
  [super dealloc];
}

/**
 * Designated initializer for NSViewTemplate.
 */
- (id) initWithObject: (id)o
	    className: (NSString *)name
{
  if ((self = [super init]) != nil)
    {
      [self setRealObject: o];
      [self setClassName: name];
    }
  return self;
}

- (id) initWithCoder: (NSCoder *)coder
{
  self = [super initWithCoder: coder];
  if (self != nil)
    {
      if ([coder allowsKeyedCoding])
        {
          _className = [coder decodeObjectForKey: @"NSClassName"];
        }

      if (_realObject == nil)
	{
	  Class aClass = NSClassFromString(_className);
	  if (aClass == nil)
	    {
	      [NSException raise: NSInternalInconsistencyException
			   format: @"Unable to find class '%@'", _className];
	    }
	  else
	    {
	      ASSIGN(_realObject, [[aClass allocWithZone: NSDefaultMallocZone()] initWithCoder: coder]);
	      [[self superview] replaceSubview: self with: _realObject]; // replace the old view...
	    }
	}

      AUTORELEASE(self);
      return _realObject;
    }
  else
    {
      [NSException raise: NSInvalidArgumentException 
                   format: @"Can't decode %@ with %@.",NSStringFromClass([self class]),
                   NSStringFromClass([coder class])];
    }
  return nil;
}

- (void) encodeWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      [coder encodeObject: (id)_className forKey: @"NSClassName"];
      [_realObject encodeWithCoder: coder];
    }
  else
    {
      [NSException raise: NSInvalidArgumentException 
                   format: @"Can't encode %@ with %@.",NSStringFromClass([self class]),
                   NSStringFromClass([coder class])];
    }
}

// setters and getters
/**
 * Set the class name to be used by the NSView subclass.
 */
- (void) setClassName: (NSString *)name
{
  ASSIGN(_className, name);
}

/**
 * Returns the classname.
 */
- (NSString *)className
{
  return _className;
}

/**
 * Set the real object of the template.
 */
- (void) setRealObject: (id)o
{
  ASSIGN(_realObject, o);
}

/**
 * Get the real object represented by the template.
 */
- (id) realObject
{
  return _realObject;
}
@end

// Template for any classes which derive from NSText
@implementation NSTextTemplate
+ (void) initialize
{
  if (self == [NSTextTemplate class]) 
    {
      [self setVersion: 0];
    }
}
@end

/**
 * NSTextViewTemplate 
 *
 * Template for any classes which derive from NSTextView
 */
@implementation NSTextViewTemplate
+ (void) initialize
{
  if (self == [NSTextViewTemplate class]) 
    {
      [self setVersion: 0];
    }
}
@end

// Template for any classes which derive from NSMenu.
@implementation NSMenuTemplate
+ (void) initialize
{
  if (self == [NSMenuTemplate class]) 
    {
      [self setVersion: 0];
    }
}

- (void) dealloc
{
  RELEASE(_menuClass);
  RELEASE(_realObject);
  [super dealloc];
}

- (id) initWithCoder: (NSCoder *)aCoder
{
  RELEASE(self);
  return nil;
}

- (void) encodeWithCoder: (NSCoder *)aCoder
{
}

- (void) setClassName: (NSString *)className
{
  ASSIGN(_menuClass, className);
}

- (NSString *)className
{
  return _menuClass;
}

- (void) setRealObject: (id)o
{
  ASSIGN(_realObject,o);
}

- (id) realObject
{
  return _realObject;
}
@end

@implementation NSCustomObject
- (void) setClassName: (NSString *)name
{
  ASSIGNCOPY(_className, name);
}

- (NSString *)className
{
  return _className;
}

- (void) setExtension: (NSString *)name
{
  ASSIGNCOPY(_extension, name);
}

- (NSString *)extension
{
  return _extension;
}

- (void) setRealObject: (id)obj
{
  ASSIGN(_object, obj);
}

- (id) realObject
{
  return _object;
}

- (id) initWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      ASSIGN(_className, [coder decodeObjectForKey: @"NSClassName"]);
      ASSIGN(_extension, [coder decodeObjectForKey: @"NSExtension"]);
      ASSIGN(_object, [coder decodeObjectForKey: @"NSObject"]);
    }
  else
    {
      [NSException raise: NSInvalidArgumentException 
                   format: @"Can't decode %@ with %@.",NSStringFromClass([self class]),
                   NSStringFromClass([coder class])];
    }
  return self;
}

- (void) encodeWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      [coder encodeObject: (id)_className forKey: @"NSClassName"];
      [coder encodeConditionalObject: (id)_extension forKey: @"NSExtension"];
      [coder encodeConditionalObject: (id)_object forKey: @"NSObject"];
    }
  else
    {
      [NSException raise: NSInvalidArgumentException
                   format: @"Keyed coding not implemented for %@.", 
                   NSStringFromClass([self class])];
    }
  
}

- (id) nibInstantiate
{
  if (_object == nil)
    {
      Class aClass;
      
      if ([NSClassSwapper isInInterfaceBuilder])
        {
          aClass = [self class];
        }
      else
        {
          aClass = NSClassFromString(_className);
        }

      if (aClass == nil)
        {
          [NSException raise: NSInternalInconsistencyException
                       format: @"Unable to find class '%@'", _className];
        }

      if (GSObjCIsKindOf(aClass, [NSApplication class]) || 
	 [_className isEqual: @"NSApplication"])
	{
	  _object = RETAIN([aClass sharedApplication]);
	}
      else
	{
	  _object = [[aClass allocWithZone: NSDefaultMallocZone()] init];
	}      
    }
  return _object;
}

- (void) awakeFromNib
{
  NSDebugLog(@"Called awakeFromNib on an NSCustomObject instance: %@", self);
  if ([_object respondsToSelector: @selector(awakeFromNib)])
    {
      [_object awakeFromNib];
    }
}

- (NSString *) description
{
  return [NSString stringWithFormat: @"<%s: %lx> = <<className: %@, object: %@>>",
		   GSClassNameFromObject(self), 
		   (unsigned long)self,
		   _className,_object];
}

- (void) dealloc
{
  RELEASE(_className);
  RELEASE(_extension);
  RELEASE(_object);
  [super dealloc];
}
@end

@implementation NSCustomView
- (void) setClassName: (NSString *)name
{
  ASSIGNCOPY(_className, name);
}

- (NSString *)className
{
  return _className;
}
- (void) setExtension: (NSString *)ext;
{
  ASSIGNCOPY(_extension, ext);
}

- (NSString *)extension
{
  return _extension;
}

- (id) nibInstantiate
{
  if ([NSClassSwapper isInInterfaceBuilder])
    {
      _view = self;
      return self;
    }

  if (_view == nil)
    {
      Class aClass;
  
      // If the class name is nil, assume NSView.
      if (_className == nil)
        {
          aClass = [NSView class];
        }
      else
        {
          aClass = NSClassFromString(_className);
        }
  
      if (aClass == nil)
        {
          [NSException raise: NSInternalInconsistencyException
                      format: @"Unable to find class '%@'", _className];
        }
      else
        {
          _view = [[aClass allocWithZone: NSDefaultMallocZone()] initWithFrame: [self frame]];
        }
    }

  return _view;
}

- (id) nibInstantiateWithCoder: (NSCoder *)coder
{
  if ([NSClassSwapper isInInterfaceBuilder])
    {
      return _view;
    }
  else if ([coder allowsKeyedCoding])
    {
      NSArray *subs = nil;
      id nextKeyView = nil;
      id prevKeyView = nil;
      NSEnumerator *en = nil;
      id v = nil;

      // Tell the decoder that the object gets replaced before decoding subviews
      [(NSKeyedUnarchiver *)coder replaceObject: self withObject: _view];

      prevKeyView = [coder decodeObjectForKey: @"NSPreviousKeyView"];
      nextKeyView = [coder decodeObjectForKey: @"NSNextKeyView"];
      if (nextKeyView != nil)
        {
          [_view setNextKeyView: nextKeyView];
        }
      if (prevKeyView != nil)
        {
          [_view setPreviousKeyView: prevKeyView];
        }      
      if ([coder containsValueForKey: @"NSvFlags"])
	{
	  int vFlags = [coder decodeIntForKey: @"NSvFlags"];
	  [_view setAutoresizingMask: vFlags & 0x3F];
	  [_view setAutoresizesSubviews: ((vFlags & 0x100) == 0x100)];
	  [_view setHidden: ((vFlags & 0x80000000) == 0x80000000)];
	}
      /*
      if ([coder containsValueForKey: @"NSNextResponder"])
	{
	  [_view setNextResponder: [coder decodeObjectForKey: @"NSNextResponder"]];
	}      
      */

      // reset the bounds...
      // [_view setBounds: [_view frame]];

      subs = [coder decodeObjectForKey: @"NSSubviews"];
      en = [subs objectEnumerator];
      while((v = [en nextObject]) != nil)
	{
	  [_view addSubview: v];
	}
    }
  else
    {
      [NSException raise: NSInternalInconsistencyException
		   format: @"Called NSCustomView awakeAfterUsingCoder with non-keyed archiver."];
    }

  return _view;
}

- (id) initWithCoder: (NSCoder *)coder
{
  // if in interface builder, then initialize as normal.
  if ([NSClassSwapper isInInterfaceBuilder])
    {
      self = [super initWithCoder: coder];
      if (self == nil)
        {
          return nil;
        }
    }

  if ([coder allowsKeyedCoding])
    {
      // get the super stuff without calling super...
      if ([coder containsValueForKey: @"NSFrame"])
        {
          _frame = [coder decodeRectForKey: @"NSFrame"];
        }
      else
        {
          _frame = NSZeroRect;
          if ([coder containsValueForKey: @"NSFrameSize"])
            {
              _frame.size = [coder decodeSizeForKey: @"NSFrameSize"];
            }
        }
      
      ASSIGN(_className, [coder decodeObjectForKey: @"NSClassName"]);
      ASSIGN(_extension, [coder decodeObjectForKey: @"NSExtension"]);
      
      if ([self nibInstantiate] != nil)
        {
          [self nibInstantiateWithCoder: coder];
        }
      
      if (self != _view)
        {
          AUTORELEASE(self);
        }
    }
  else
    {
      [NSException raise: NSInvalidArgumentException 
                  format: @"Can't decode %@ with %@.",NSStringFromClass([self class]),
                   NSStringFromClass([coder class])];
    }

  return (id)_view;
}

- (void) encodeWithCoder: (NSCoder *)coder
{
  [super encodeWithCoder: coder];
  if ([coder allowsKeyedCoding])
    {
      [coder encodeObject: _className forKey: @"NSClassName"];
      [coder encodeObject: _extension forKey: @"NSExtension"];
    }
  else
    {
      [NSException raise: NSInvalidArgumentException 
                   format: @"Can't encode %@ with %@.",NSStringFromClass([self class]),
                   NSStringFromClass([coder class])];
    }
}
@end

/**
 * This class represents an image or a sound which is referenced by the nib file.
 */
@implementation NSCustomResource
- (void) setClassName: (NSString *)className
{
  ASSIGNCOPY(_className, className);
}

- (NSString *)className
{
  return _className;
}

- (void) setResourceName: (NSString *)resourceName
{
  ASSIGNCOPY(_resourceName, resourceName);
}

- (NSString *)resourceName
{
  return _resourceName;
}

- (id) initWithCoder: (NSCoder *)coder
{
  id realObject = nil;
  if ([coder allowsKeyedCoding])
    {
      ASSIGN(_className, [coder decodeObjectForKey: @"NSClassName"]);
      ASSIGN(_resourceName, [coder decodeObjectForKey: @"NSResourceName"]);

      // FIXME: this is a hack, but for now it should do.
      if ([_className isEqual: @"NSSound"])
        {
          realObject = RETAIN([NSSound soundNamed: _resourceName]);
        }
      else if ([_className isEqual: @"NSImage"])
        {
          realObject = RETAIN([NSImage imageNamed: _resourceName]);
        }

      if (realObject == nil)
        {
          NSLog(@"Could not load NSCustomResource %@ for class %@", _resourceName, _className);
          // Use a default instead of the missing object
          if ([_className isEqual: @"NSSound"])
            {
              realObject = RETAIN([NSSound soundNamed: @"Ping"]);
            }
          else if ([_className isEqual: @"NSImage"])
            {
              realObject  = RETAIN([NSImage imageNamed: @"GNUstep"]);
            }
        }
      // The object has been substituted, release the placeholder.
      RELEASE(self);
    }
  else
    {
      [NSException raise: NSInvalidArgumentException 
                   format: @"Can't decode %@ with %@.",NSStringFromClass([self class]),
                   NSStringFromClass([coder class])];
    }

  return realObject;
}

- (void) encodeWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      [coder encodeObject: (id)_className forKey: @"NSClassName"];
      [coder encodeObject: (id)_resourceName forKey: @"NSResourceName"];
    }
}
@end

/**
 * Category to add methods to NSKeyedUnarchiver which are needed during
 * nib reading.
 */
@implementation NSKeyedUnarchiver (NSClassSwapperPrivate)
/**
 * This method returns the class which replaces the class named
 * by className.   It uses the classes map to do this.
 */
- (Class) replacementClassForClassName: (NSString *)className
{
  Class aClass;
  if ((aClass = [self classForClassName: className]) == nil)
    {
      if ((aClass = [[self class] classForClassName: className]) == nil)
        {
          aClass = NSClassFromString(className);
          if (aClass == nil)
            {
              [NSException raise: NSInternalInconsistencyException
                          format: @"NSClassSwapper unable to find class '%@'", className];
            }
        }
    }
  return aClass;
}
@end

/**
 * NSClassSwapper
 *
 * This class is used to stand-in for objects which need to be replaced by another object.  
 * When this class is loaded in the live application, it unarchives and immediately replaces
 * itself with the instance of the object requested.   This is necessary since IB/Gorm does 
 * have objects this is used for in palettes, so there is no "live" or actual instance saved
 * in the gorm file... only this object as a stand in.
 */
@implementation NSClassSwapper
- (id) initWithObject: (id)object 
        withClassName: (NSString *)className
    originalClassName: (NSString *)origClassName
{
  if ((self = [super init]) != nil)
    {
      [self setTemplate: object];
      [self setClassName: className];
      [self setOriginalClassName: origClassName];
    }
  return self;
}

/**
 * This class method keeps track of whether or not we are operating within IB/Gorm.   
 * When unarchiving in IB/Gorm some behavior may need to be surpressed for some objects
 * or it 
 */
+ (void) setIsInInterfaceBuilder: (BOOL)flag
{
  _isInInterfaceBuilder = flag;
}

/**
 * returns YES, if we are currently in IB/Gorm.
 */
+ (BOOL) isInInterfaceBuilder
{
  return _isInInterfaceBuilder;
}

/**
 * Sets the template represented by temp.
 */
- (void) setTemplate: (id)temp
{
  ASSIGN(_template, temp);
}

/**
 * Returns the template.
 */
- (id) template
{
  return _template;
}

/**
 * Sets the class name.
 */
- (void) setClassName: (NSString *)className
{
  ASSIGNCOPY(_className, className);
}

/**
 * Returns the class name.
 */
- (NSString *)className
{
  return _className;
}

/**
 * Sets the original class name.
 */
- (void) setOriginalClassName: (NSString *)className
{
  ASSIGNCOPY(_originalClassName, className);
}

/**
 * Returns the original class name.
 */
- (NSString *)originalClassName
{
  return _originalClassName;
}

/** 
 * Instantiates the real object using className.
 */
- (void) instantiateRealObject: (NSCoder *)coder withClassName: (NSString *)className
{
  Class newClass = nil;
  id object = nil;
  NSKeyedUnarchiver *decoder = (NSKeyedUnarchiver *)coder;

  if ([NSClassSwapper isInInterfaceBuilder] == YES)
    {
      newClass = [decoder replacementClassForClassName: _originalClassName];
    }
  else
    {
      newClass = [decoder replacementClassForClassName: className];
    }

  // swap the class...
  object = [newClass allocWithZone: NSDefaultMallocZone()];
  [decoder setDelegate: self]; // set the delegate...
  [decoder replaceObject: self withObject: object];
  [self setTemplate: [object initWithCoder: decoder]];
  if (object != _template)
    {
      [decoder replaceObject: object withObject: _template];
    }
  [decoder setDelegate: nil]; // unset the delegate...
}

/**
 * This delegate method makes the proper substitution for cellClass
 * when the object needs to have it's own cell.   An example of this
 * is NSSecureTextField/NSSecureTextFieldCell.
 */
- (id) unarchiver: (NSKeyedUnarchiver *)coder
  didDecodeObject: (id)obj
{
  Class newClass = nil; 
  id result = obj;

  // if we are in an interface builder, then return the original object.
  if ([NSClassSwapper isInInterfaceBuilder] == YES)
    {
      newClass = [coder replacementClassForClassName: _originalClassName];
    }
  else
    {
      newClass = [coder replacementClassForClassName: _className];
    }

  // if this is a class which uses cells, override with the new cellClass, if the 
  // subclass responds to cellClass.
  if ([obj isKindOfClass: [NSCell class]] &&
      [newClass respondsToSelector: @selector(cellClass)] && 
      [_className isEqualToString: _originalClassName] == NO)
    {
      Class newCellClass = [newClass cellClass];
      if (newCellClass != [NSCell class])
        {
          RELEASE(obj);
          result = [[newCellClass alloc] initWithCoder: coder];      
        }
    }

  return result;
}

/**
 * Decode NSClassSwapper.
 */
- (id) initWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      ASSIGN(_className, [coder decodeObjectForKey: @"NSClassName"]);  
      ASSIGN(_originalClassName, [coder decodeObjectForKey: @"NSOriginalClassName"]);  

      // build the real object...
      if ([NSClassSwapper isInInterfaceBuilder] == YES)
        {
          [self instantiateRealObject: coder withClassName: _originalClassName];
        }
      else
        {
          [self instantiateRealObject: coder withClassName: _className];
        }
      
      {
        id object;

        object = RETAIN(_template);
        RELEASE(self);
        return AUTORELEASE(object);
      }
    }
  else
    {
      [NSException raise: NSInvalidArgumentException 
                   format: @"Can't decode %@ with %@.",NSStringFromClass([self class]),
                   NSStringFromClass([coder class])];
    }

  return self;
}

/**
 * Encode NSClassSwapper.
 */
- (void) encodeWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      [coder encodeObject: _originalClassName forKey: @"NSOriginalClassName"];
      [coder encodeObject: _className forKey: @"NSClassName"];
      [_template encodeWithCoder: coder]; // encode the actual object;
    }
  else
    {
      [NSException raise: NSInvalidArgumentException 
                   format: @"Can't encode %@ with %@.",NSStringFromClass([self class]),
                   NSStringFromClass([coder class])];
    }
}

/**
 * Deallocate NSClassSwapper instance.
 */
- (void) dealloc
{
  RELEASE(_className);
  RELEASE(_originalClassName);
  RELEASE(_template);
  [super dealloc];
}
@end

@implementation NSNibConnector (NibCompatibility)
/**
 * This method causes the connection to instantiate the objects in it's source
 * and destination.   The instantiator is the object which holds any custom
 * class information which might be needed to do the proprer substitution of
 * objects based on the contents of the maps.
 */
- (void) instantiateWithInstantiator: (id<GSInstantiator>)instantiator
{
  [self setSource: [instantiator instantiateObject: _src]];
  [self setDestination: [instantiator instantiateObject: _dst]];
}

- (id) nibInstantiate
{
  if ([_src respondsToSelector: @selector(nibInstantiate)])
    {
      [self setSource: [_src nibInstantiate]];
    }
  if ([_dst respondsToSelector: @selector(nibInstantiate)])
    {
      [self setDestination: [_dst nibInstantiate]];
    }
  return self;
}

@end

@implementation NSNibControlConnector (NibCompatibility)
/**
 * This method overrides the default implementation of instantiate with
 * instantiator.   It also corrects a common issue in some nib files
 * by adding a colon to the end if none was given.   It then calls the
 * superclass with the corrected label.
 */
- (void) instantiateWithInstantiator: (id<GSInstantiator>)instantiator
{
  NSRange colonRange = [_tag rangeOfString: @":"];
  NSUInteger location = colonRange.location;
  
  if (location == NSNotFound)
    {
      NSString *newTag = [NSString stringWithFormat: @"%@:",_tag];
      [self setLabel: (id)newTag];
    }

  [super instantiateWithInstantiator: instantiator];
}
@end

/**
 * NSIBObjectData
 *
 * This class is the container for all of the nib data.  It contains several maps.
 * The maps are the following:
 * 
 *     name -> object (name table)
 *     object -> name (name table reverse lookup)
 *     classes -> object (for custom class storage)
 *     oids -> object (for relating the oid to each object)
 *     accessibilityOids -> object 
 *
 * The maps are stored in the nib itself as a set of synchronized 
 * arrays one array containing the keys and the other the values.  This is why, in the
 * initWithCoder: and encodeWithCoder: methods they are saved as arrays and then 
 * loaded into NSMapTables.   
 */
@implementation NSIBObjectData
/**
 * Get the values from the map in the same order as the keys.
 */
- (NSArray *) _valuesForKeys: (NSArray *)keys inMap: (NSMapTable *)map
{
  NSMutableArray *result = [NSMutableArray array];
  NSEnumerator *en = [keys objectEnumerator];
  id key = nil;
  while ((key = [en nextObject]) != nil)
    {
      id value = (id)NSMapGet(map,key);
      [result addObject: value];
    }
  return result;
}

/**
 * Build a map with two arrays of keys and values.
 */
- (void) _buildMap: (NSMapTable *)mapTable 
          withKeys: (NSArray *)keys 
         andValues: (NSArray *)values
{
  NSEnumerator *ken = [keys objectEnumerator];
  NSEnumerator *ven = [values objectEnumerator];
  id key = nil;
  id value = nil;
  
  while ((key = [ken nextObject]) != nil && (value = [ven nextObject]) != nil)
    {
      NSMapInsert(mapTable, key, value);
      if (value == nil)
	{
	  NSLog(@"==> WARNING: Value for key %@ is %@",key , value);
	}
    }
}

/**
 * Encode the NSIBObjectData container
 */
- (void) encodeWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      NSArray *accessibilityOidsKeys = (NSArray *)NSAllMapTableKeys(_accessibilityOids);
      NSArray *accessibilityOidsValues = [self _valuesForKeys: accessibilityOidsKeys inMap: _accessibilityOids];
      NSArray *classKeys = (NSArray *)NSAllMapTableKeys(_classes);
      NSArray *classValues = [self _valuesForKeys: classKeys inMap: _classes];
      NSArray *nameKeys = (NSArray *)NSAllMapTableKeys(_names);
      NSArray *nameValues = [self _valuesForKeys: nameKeys inMap: _names];
      NSArray *objectsKeys = (NSArray *)NSAllMapTableKeys(_objects);
      NSArray *objectsValues = [self _valuesForKeys: objectsKeys inMap: _objects];
      NSArray *oidsKeys = (NSArray *)NSAllMapTableKeys(_oids);
      NSArray *oidsValues = [self _valuesForKeys: oidsKeys inMap: _oids];

      [(NSKeyedArchiver *)coder setClassName: @"_NSCornerView" forClass: NSClassFromString(@"GSTableCornerView")];

      [coder encodeObject: (id)_accessibilityConnectors forKey: @"NSAccessibilityConnectors"];
      [coder encodeObject: (id) accessibilityOidsKeys forKey: @"NSAccessibilityOidsKeys"];
      [coder encodeObject: (id) accessibilityOidsValues forKey: @"NSAccessibilityOidsValues"];
      [coder encodeObject: (id) classKeys forKey: @"NSClassesKeys"];
      [coder encodeObject: (id) classValues forKey: @"NSClassesValues"];
      [coder encodeObject: (id) nameKeys forKey: @"NSNamesKeys"];
      [coder encodeObject: (id) nameValues forKey: @"NSNamesValues"];
      [coder encodeObject: (id) objectsKeys forKey: @"NSObjectsKeys"];
      [coder encodeObject: (id) objectsValues forKey: @"NSObjectsValues"];
      [coder encodeObject: (id) oidsKeys forKey: @"NSOidsKeys"];
      [coder encodeObject: (id) oidsValues forKey: @"NSOidsValues"];
      [coder encodeObject: (id) _connections forKey: @"NSConnections"];
      [coder encodeObject: (id) _fontManager forKey: @"NSFontManager"];
      [coder encodeObject: (id) _framework forKey: @"NSFramework"];
      [coder encodeObject: (id) _visibleWindows forKey: @"NSVisibleWindows"];
      [coder encodeInt: _nextOid forKey: @"NSNextOid"];
      [coder encodeConditionalObject: (id) _root forKey: @"NSRoot"];
    }
  else
    {
      [NSException raise: NSInvalidArgumentException 
                   format: @"Can't encode %@ with %@.",NSStringFromClass([self class]),
                   NSStringFromClass([coder class])];
    }
}

/**
 * Decode the NSIBObjectData container.
 */
- (id) initWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      NSArray *nameKeys = nil;
      NSArray *nameValues = nil;
      NSArray *classKeys = nil;
      NSArray *classValues = nil;
      NSArray *objectsKeys = nil;
      NSArray *objectsValues = nil;
      NSArray *oidsKeys = nil;
      NSArray *oidsValues = nil;
      NSArray *accessibilityOidsKeys = nil;
      NSArray *accessibilityOidsValues = nil;

      [(NSKeyedUnarchiver *)coder setClass: NSClassFromString(@"GSTableCornerView")
			      forClassName: @"_NSCornerView"];

      //
      // Get root, font, framwork and oid. 
      // Retain objects since NSKeyedUnarchiver autoreleases unarchived objects.
      //
      ASSIGN(_root, [coder decodeObjectForKey: @"NSRoot"]);
      ASSIGN(_fontManager, [coder decodeObjectForKey: @"NSFontManager"]);
      ASSIGN(_framework, [coder decodeObjectForKey: @"NSFramework"]);
      _nextOid = [coder decodeIntForKey: @"NSNextOid"];

      // get connections.
      ASSIGN(_connections, (NSMutableArray *)
	[coder decodeObjectForKey: @"NSConnections"]);
      ASSIGN(_accessibilityConnectors, (NSMutableArray *)
	[coder decodeObjectForKey: @"NSAccessibilityConnectors"]);

      // get visible windows
      ASSIGN(_visibleWindows, (NSMutableArray *)
	[coder decodeObjectForKey: @"NSVisibleWindows"]);

      // instantiate the maps..
      _classes = NSCreateMapTable(NSObjectMapKeyCallBacks,
				  NSObjectMapValueCallBacks, 2);
      _names = NSCreateMapTable(NSObjectMapKeyCallBacks,
				NSObjectMapValueCallBacks, 2);
      _objects = NSCreateMapTable(NSObjectMapKeyCallBacks,
				  NSObjectMapValueCallBacks, 2);
      _oids = NSCreateMapTable(NSObjectMapKeyCallBacks,
			       NSObjectMapValueCallBacks, 2);

      // 
      // Get the maps.  There is no need to retain these, 
      // since they are going to be placed into the NSMapTable
      // structures anyway.
      //
      nameKeys = (NSArray *)
	[coder decodeObjectForKey: @"NSNamesKeys"];
      nameValues = (NSArray *)
	[coder decodeObjectForKey: @"NSNamesValues"];
      classKeys = (NSArray *)
	[coder decodeObjectForKey: @"NSClassesKeys"];
      classValues = (NSArray *)
	[coder decodeObjectForKey: @"NSClassesValues"];
      objectsKeys = (NSArray *)
	[coder decodeObjectForKey: @"NSObjectsKeys"];
      objectsValues = (NSArray *)
	[coder decodeObjectForKey: @"NSObjectsValues"];
      oidsKeys = (NSArray *)
	[coder decodeObjectForKey: @"NSOidsKeys"];
      oidsValues = (NSArray *)
	[coder decodeObjectForKey: @"NSOidsValues"];

      // Fill in the maps...
      [self _buildMap: _classes 
	    withKeys: classKeys 
	    andValues: classValues];
      [self _buildMap: _names 
	    withKeys: nameKeys 
	    andValues: nameValues];
      [self _buildMap: _objects 
	    withKeys: objectsKeys 
	    andValues: objectsValues];
      [self _buildMap: _oids 
	    withKeys: oidsKeys 
	    andValues: oidsValues];
      
      //
      // Only get these maps when in the editor.  They
      // aren't useful outside of it and only waste memory if
      // unarchived in the live application.
      //
      if ([NSClassSwapper isInInterfaceBuilder])
	{
	  // Only get these when in the editor...
	  accessibilityOidsKeys = (NSArray *)
	    [coder decodeObjectForKey: @"NSAccessibilityOidsKeys"];
	  accessibilityOidsValues = (NSArray *)
	    [coder decodeObjectForKey: @"NSAccessibilityOidsValues"];      

	  _accessibilityOids = NSCreateMapTable(NSObjectMapKeyCallBacks,
						NSObjectMapValueCallBacks, 2);	  
	  [self _buildMap: _accessibilityOids 
		withKeys: accessibilityOidsKeys 
		andValues: accessibilityOidsValues];
	}

      // instantiate...
      _topLevelObjects = [[NSMutableSet alloc] init];
    }
  else
    {
      [NSException raise: NSInvalidArgumentException 
                   format: @"Can't decode %@ with %@.",NSStringFromClass([self class]),
                   NSStringFromClass([coder class])];
    }
 
  return self;
}

/**
 * Initialize a new NSIBObjectData.
 */
- (id) init
{
  if ((self = [super init]) != nil)
    {
      // instantiate the maps..
      _objects = NSCreateMapTable(NSObjectMapKeyCallBacks,
                                  NSObjectMapValueCallBacks, 2);
      _names = NSCreateMapTable(NSObjectMapKeyCallBacks,
                                NSObjectMapValueCallBacks, 2);
      _oids = NSCreateMapTable(NSObjectMapKeyCallBacks,
                               NSObjectMapValueCallBacks, 2);
      _classes = NSCreateMapTable(NSObjectMapKeyCallBacks,
                                  NSObjectMapValueCallBacks, 2);
      _accessibilityOids = NSCreateMapTable(NSObjectMapKeyCallBacks,
                                            NSObjectMapValueCallBacks, 2);  

      // initialize the objects...
      _accessibilityConnectors = [[NSMutableArray alloc] init];
      _connections = [[NSMutableArray alloc] init];
      _visibleWindows = [[NSMutableArray alloc] init];
      _framework = nil;
      _fontManager = nil;
      _root = nil;
      _nextOid = 0;
    }
  return self;
}

/**
 * Deallocate NSIBObjectData.
 */
- (void) dealloc
{
  // free the maps.
  NSFreeMapTable(_objects);
  NSFreeMapTable(_names);
  NSFreeMapTable(_classes);
  NSFreeMapTable(_oids);
  // these are not allocated when not in interface builder.
  if ([NSClassSwapper isInInterfaceBuilder])
    {
      NSFreeMapTable(_accessibilityOids);
    }

  // free other objects.
  RELEASE(_accessibilityConnectors);
  RELEASE(_connections);
  RELEASE(_fontManager);
  RELEASE(_framework);
  RELEASE(_visibleWindows);
  RELEASE(_root);
  RELEASE(_topLevelObjects);
  [super dealloc];
}

/**
 * Call nibInstantiate on an object, if it responds to the nibInstantiate selector.
 */
- (id)instantiateObject: (id)obj
{
  id newObject = obj;
  if ([obj respondsToSelector: @selector(nibInstantiate)])
    {
      newObject = [obj nibInstantiate];
    }
  return newObject;
}

/**
 * Instantiate all of the objects in the nib file.
 */
- (void) nibInstantiateWithOwner: (id)owner topLevelObjects: (NSMutableArray *)topLevelObjects
{
  NSEnumerator *en;
  NSArray *objs;
  id obj = nil;
  id menu = nil;

  // set the new root object.
  [_root setRealObject: owner];

  // iterate over all objects, instantiate them and fill in top level array.
  /* Note: We instantiate all objects before establishing any connections
     between them, so that any shared instances defined in the nib are
     initialized before being used. This sequence is important when, e.g.,
     the nib defines a shared document controller that is an instance of a
     subclass of NSDocumentController. */
  objs = NSAllMapTableKeys(_objects);
  en = [objs objectEnumerator];
  while ((obj = [en nextObject]) != nil)
    {
      id v = NSMapGet(_objects, obj);
      NSInteger oid = [(id)NSMapGet(_oids, obj) intValue];

      obj = [self instantiateObject: obj];
      // Object is top level if it isn't the owner but points to it.
      /* Don't record proxy objects in the top level array. The only
	 reliable way to identify proxy objects seems to look at their
	 object ID. Apparently, Apple is using fixed negative IDs for
	 proxy objects (-1 = File's Owner, -2 = First Responder,
	 -3 = NSApplication). */
      if (oid >= 0)
	{
	  if ((v == owner || v == _root) && (obj != owner) && (obj != _root))
	    {
	      [topLevelObjects addObject: obj];
	      // All top level objects must be released by the caller to avoid
	      // leaking, unless they are going to be released by other nib
	      // objects on behalf of the owner.
	      RETAIN(obj);
	    }
          if ([obj isKindOfClass: [NSMenu class]] &&
              [obj _isMainMenu])
            {
              [NSApp _setMainMenu: obj];
            }
        }
    }

  // iterate over connections, instantiate and then establish them.
  en = [_connections objectEnumerator];
  while ((obj = [en nextObject]) != nil)
    {
      if ([obj respondsToSelector: @selector(instantiateWithInstantiator:)])
        {
          [obj instantiateWithInstantiator: self];          
          [obj establishConnection];
        }
      else
        {
          if ([obj respondsToSelector: @selector(instantiateWithObjectInstantiator:)])
            {
              [obj instantiateWithObjectInstantiator: self];          
              [obj establishConnection];
            }
        }
    }

  // awaken all objects except proxy objects.
  objs = NSAllMapTableKeys(_objects);
  en = [objs objectEnumerator];
  while ((obj = [en nextObject]) != nil)
    {
      NSInteger oid = [(id)NSMapGet(_oids, obj) intValue];
      if (oid >= 0)
        {
          if ([obj respondsToSelector: @selector(realObject)])
            {
              obj = [obj realObject];
            }
          if ([obj respondsToSelector: @selector(awakeFromNib)])
            {
              [obj awakeFromNib];
            }
        }
    }

  // awaken the owner
  if ([owner respondsToSelector: @selector(awakeFromNib)])
    {
      [owner awakeFromNib];
    }

  // bring visible windows to front...
  en = [_visibleWindows objectEnumerator];
  while ((obj = [en nextObject]) != nil)
    {
      id w = [obj realObject];
      [w orderFront: self];
    }

  // add the menu...
  menu = [self objectForName: @"MainMenu"];
  if (menu != nil)
    {
      menu = [self instantiateObject: menu];
      [NSApp _setMainMenu: menu];
    }
}

/**
 * Awake after loading the nib and extract the top level and owner for nib instantiation,
 * then call nibInstantateWithOwner:topLevelObjects:
 */
- (void) awakeWithContext: (NSDictionary *)context
{
  NSMutableArray *tlo = [context objectForKey: NSNibTopLevelObjects];
  id owner = [context objectForKey: NSNibOwner];

  // instantiate...
  [self nibInstantiateWithOwner: owner topLevelObjects: tlo];
}

/**
 * Retrieve an object by name from the map.
 */
- (id) objectForName: (NSString *)name
{
  NSArray *nameKeys = (NSArray *)NSAllMapTableKeys(_names);
  NSArray *nameValues = (NSArray *)NSAllMapTableValues(_names);
  NSUInteger i = [nameValues indexOfObject: name];
  id result = nil;

  if (i != NSNotFound)
    {
      result = [nameKeys objectAtIndex: i];
    }

  return result;
}

/**
 * Get the name for an object.
 */
- (NSString *) nameForObject: (id)obj
{
  NSArray *nameKeys = (NSArray *)NSAllMapTableKeys(_names);
  NSArray *nameValues = (NSArray *)NSAllMapTableValues(_names);
  int i = [nameKeys indexOfObject: obj];
  NSString *result = [nameValues objectAtIndex: i];
  return result;
}

/**
 * Set the root object.
 */
- (void) setRoot: (id) root
{
  ASSIGN(_root, root);
}

/**
 * Return the root object.
 */
- (id) root
{
  return _root;
}

/**
 * Set the value of the next available oid.
 */
- (void) setNextOid: (int)noid
{
  _nextOid = noid;
}

/**
 * Get the value of the next available oid.
 */
- (int) nextOid
{
  return _nextOid;
}

/**
 * Connections between objects.
 */
- (NSMutableArray *) connections
{
  return _connections;
}

/**
 * Set of top level objects.
 */
- (NSMutableSet *) topLevelObjects
{
  return _topLevelObjects;
}

/**
 * Names to objects
 */
- (NSMutableDictionary *) nameTable
{
  return nil;
}

/**
 * Set of all visible windows.
 */
- (NSMutableArray *) visibleWindows
{
  return _visibleWindows;
}

/**
 * Objects to names table.
 */
- (NSMapTable *) objects
{
  return _objects;
}

/**
 * Names to objects table.
 */
- (NSMapTable *) names
{
  return _names;
}

/**
 * Classes to objects table.
 */
- (NSMapTable *) classes
{
  return _classes;
}

/**
 * Oids to objects table.
 */ 
- (NSMapTable *) oids
{
  return _oids;
}
@end

/**
 * NSButtonImageSource
 * 
 * This class is used by buttons to pull the correct image based on a given state.
 */
@implementation NSButtonImageSource
- (id) initWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      ASSIGN(imageName, [coder decodeObjectForKey: @"NSImageName"]);
    }
  else
    {
      [NSException raise: NSInvalidArgumentException 
                   format: @"Can't decode %@ with %@.",NSStringFromClass([self class]),
                   NSStringFromClass([coder class])];
    }

  AUTORELEASE(self);
  return RETAIN([NSImage imageNamed: imageName]);
}

- (void) encodeWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      [coder encodeObject: imageName forKey: @"NSImageName"];
    }
  else
    {
      [NSException raise: NSInvalidArgumentException 
                   format: @"Can't encode %@ with %@.",NSStringFromClass([self class]),
                   NSStringFromClass([coder class])];
    }
}

/**
 * Initializes with image name.
 */
- (id) initWithImageNamed: (NSString *)name
{
  if ((self = [super init]) != nil)
    {
      ASSIGN(imageName,name);
    }
  return self;
}

/**
 * Returns imageName.
 */
- (NSString *)imageName
{
  return imageName;
}

- (void) dealloc
{
  RELEASE(imageName);
  [super dealloc];
}
@end

@implementation NSIBHelpConnector
- (id) init
{
  if ((self = [super init]) != nil)
    {
      _file = nil;
      ASSIGN(_marker, @"NSToolTipHelpKey");
    }
  return self;
}

- (void) dealloc
{
  RELEASE(_file);
  RELEASE(_marker);
  [super dealloc];
}

- (id) initWithCoder: (NSCoder *)coder
{
  if ((self = [super initWithCoder: coder]) != nil)
    {
      if ([coder allowsKeyedCoding])
        {
          if ([coder containsValueForKey: @"NSFile"])
            {
              ASSIGN(_file, [coder decodeObjectForKey: @"NSFile"]);
            }
          if ([coder containsValueForKey: @"NSMarker"])
            {
              ASSIGN(_marker, [coder decodeObjectForKey: @"NSMarker"]);
            }
        }
      else
        {
          ASSIGN(_file, [coder decodeObject]);
          ASSIGN(_marker, [coder decodeObject]);
        }
    }
  return self;
}

- (void) encodeWithCoder: (NSCoder *)coder
{
  [super encodeWithCoder: coder];
  if ([coder allowsKeyedCoding])
    {
      if (_file != nil)
        {
          [coder encodeObject: _file forKey: @"NSFile"];
        }
      if (_marker != nil)
        {
          [coder encodeObject: _marker forKey: @"NSMarker"];
        }      
    }
  else
    {
      [coder encodeObject: _file];
      [coder encodeObject: _marker];
    }
}

- (void) establishConnection
{
  if ([_dst respondsToSelector: @selector(setToolTip:)])
    {
      [_dst setToolTip: _marker];
    }
}

- (void) setFile: (id)file
{
  ASSIGN(_file, file);
}

- (id) file
{
  return _file;
}

- (void) setMarker: (id)marker
{
  ASSIGN(_marker, marker);
}

- (id) marker
{
  return _marker;
}
@end

@implementation NSDecimalNumberPlaceholder
- (id) initWithCoder: (NSCoder *)coder
{
  NSDecimalNumber *dn = nil;
  if ([coder allowsKeyedCoding])
    {
      NSUInteger len = 0;
      short exponent = (short)[coder decodeIntForKey: @"NS.exponent"];
      NSByteOrder bo = [coder decodeIntForKey: @"NS.mantissa.bo"];
      BOOL negative = [coder decodeBoolForKey: @"NS.negative"];
      void *mantissaBytes = (void *)[coder decodeBytesForKey: @"NS.mantissa" returnedLength: &len];
      unsigned long long unswapped = 0; 
      unsigned long long mantissa = 0;

      // BOOL compact = [coder decodeBoolForKey: @"NS.compact"];
      // int length = [coder decodeIntForKey: @"NS.length"];

      memcpy((void *)&unswapped, (void *)mantissaBytes, sizeof(unsigned long long));

      switch(bo)
        {
        case NS_BigEndian:
          mantissa = NSSwapBigLongLongToHost(unswapped);
          break;
        case NS_LittleEndian:
          mantissa = NSSwapLittleLongLongToHost(unswapped);
          break;
        default:
          break;
        }

      dn = [[NSDecimalNumber alloc] initWithMantissa: mantissa
                                    exponent: exponent
                                    isNegative: negative];
    }

  RELEASE(self);
  return (id)dn;
}

@end

/**
 * NSCornerView
 *
 * Overridden in NSTableView to be GSTableCornerView, 
 * but the class needs to be present to be overridden.
 * 
 * Currently this is a place-holder class.
 */
@implementation _NSCornerView
@end

/**
 * NSPSMatrix.
 *
 * This class is needed for nib encoding/decoding by transforms.  
 * Currently it's only referenced in the NSProgressIndicator,
 * as far as I can tell.
 *
 * Place holder class.
 */
@implementation NSPSMatrix
- (void) encodeWithCoder: (NSCoder *)coder
{
  // do nothing... just encoding the presence of the class.
}

- (id) initWithCoder: (NSCoder *)coder
{
  return self;
}
@end

@implementation NSIBUserDefinedRuntimeAttributesConnector
- (void) setObject: (id)object
{
  ASSIGN(_object, object);
}

- (id) object
{
  return _object;
}

- (void) setValues: (id)values
{
  ASSIGN(_values, values);
}

- (id) values
{
  return _values;
}

- (void) setKeyPaths: (id)keyPaths
{
  ASSIGN(_keyPaths, keyPaths);
}

- (id) keyPaths
{
  return _keyPaths;
}

- (void) dealloc
{
  RELEASE(_object);
  RELEASE(_keyPaths);
  RELEASE(_values);
  [super dealloc];
}

- (void) encodeWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      if (_object != nil)
        {
          [coder encodeObject: _object forKey: @"NSObject"];
        }
      if (_keyPaths != nil)
        {
          [coder encodeObject: _keyPaths forKey: @"NSKeyPaths"];
        }      
      if (_values != nil)
        {
          [coder encodeObject: _values forKey: @"NSValues"];
        }      
    }
  else
    {
      [coder encodeObject: _object];
      [coder encodeObject: _keyPaths];
      [coder encodeObject: _values];
    }
}

- (id) initWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      if ([coder containsValueForKey: @"NSObject"])
        {
          ASSIGN(_object, [coder decodeObjectForKey: @"NSObject"]);
        }
      if ([coder containsValueForKey: @"NSKeyPaths"])
        {
          ASSIGN(_keyPaths, [coder decodeObjectForKey: @"NSKeyPaths"]);
        }
      if ([coder containsValueForKey: @"NSValues"])
        {
          ASSIGN(_values, [coder decodeObjectForKey: @"NSValues"]);
        }
    }
  else
    {
      ASSIGN(_object, [coder decodeObject]);
      ASSIGN(_keyPaths, [coder decodeObject]);
      ASSIGN(_values, [coder decodeObject]);
    }
  
  return self;
}

- (void) establishConnection
{
  // Loop over key paths and values and use KVC on object
  NSEnumerator *keyEn = [_keyPaths objectEnumerator];
  NSEnumerator *valEn = [_values objectEnumerator];
  id key;

  while ((key = [keyEn nextObject]) != nil)
    {
      id val = [valEn nextObject];

      [_object setValue: val forKeyPath: key];
    }
}

- (void) instantiateWithObjectInstantiator: (id)instantiator
{
  [self setObject: [(id<GSInstantiator>)instantiator instantiateObject: _object]];
  // FIXME Should handle values too
}

@end