File: NSOutlineView.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 (2311 lines) | stat: -rw-r--r-- 65,858 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
/** <title>NSOutlineView</title>

   <abstract>
   This class is a subclass of NSTableView which provides the user with a way
   to display tree structured data in an outline format.
   It is particularly useful for show hierarchical data such as a
   class inheritance tree or any other set of relationships.<br />
   NB. While it its illegal to have the same item in the view more than once,
   it is possible to have multiple equal items since tests for pointer
   equality are used rather than calls to the -isEqual: method.
   </abstract>

   Copyright (C) 2001 Free Software Foundation, Inc.

   Author:  Gregory John Casamento <greg_casamento@yahoo.com>
   Date: October 2001

   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 <Foundation/NSArray.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSEnumerator.h>
#import <Foundation/NSException.h>
#import <Foundation/NSIndexSet.h>
#import <Foundation/NSMapTable.h>
#import <Foundation/NSNotification.h>
#import <Foundation/NSNull.h>
#import <Foundation/NSSet.h>
#import <Foundation/NSUserDefaults.h>
#import <Foundation/NSValue.h>

#import "AppKit/NSApplication.h"
#import "AppKit/NSBezierPath.h"
#import "AppKit/NSCell.h"
#import "AppKit/NSClipView.h"
#import "AppKit/NSColor.h"
#import "AppKit/NSEvent.h"
#import "AppKit/NSGraphics.h"
#import "AppKit/NSImage.h"
#import "AppKit/NSOutlineView.h"
#import "AppKit/NSScroller.h"
#import "AppKit/NSTableColumn.h"
#import "AppKit/NSTableHeaderView.h"
#import "AppKit/NSText.h"
#import "AppKit/NSTextFieldCell.h"
#import "AppKit/NSWindow.h"

#import "GSGuiPrivate.h"
#include <math.h>

static NSMapTableKeyCallBacks keyCallBacks;
static NSNotificationCenter *nc = nil;
static const int current_version = 1;

const int NSOutlineViewDropOnItemIndex = -1;

static int lastVerticalQuarterPosition;
static int lastHorizontalHalfPosition;
static NSDragOperation dragOperation;

static NSRect oldDraggingRect;
static id oldDropItem;
static id currentDropItem;
static int oldDropIndex;
static int currentDropIndex;

static NSMutableSet *autoExpanded = nil;
static NSDate	*lastDragUpdate = nil;
static NSDate	*lastDragChange = nil;


// Cache the arrow images...
static NSImage *collapsed = nil;
static NSImage *expanded  = nil;
static NSImage *unexpandable  = nil;

@interface NSOutlineView (NotificationRequestMethods)
- (void) _postSelectionIsChangingNotification;
- (void) _postSelectionDidChangeNotification;
- (void) _postColumnDidMoveNotificationWithOldIndex: (int) oldIndex
                                           newIndex: (int) newIndex;
// FIXME: There is a method with a similar name.but this is never called
//- (void) _postColumnDidResizeNotification;
- (BOOL) _shouldSelectTableColumn: (NSTableColumn *)tableColumn;
- (BOOL) _shouldSelectRow: (int)rowIndex;
- (BOOL) _shouldSelectionChange;
- (BOOL) _shouldEditTableColumn: (NSTableColumn *)tableColumn
                            row: (int) rowIndex;
- (void) _willDisplayCell: (NSCell*)cell
           forTableColumn: (NSTableColumn *)tb
                      row: (int)index;
- (BOOL) _writeRows: (NSIndexSet *)rows
       toPasteboard: (NSPasteboard *)pboard;
- (BOOL) _isDraggingSource;
- (id) _objectValueForTableColumn: (NSTableColumn *)tb
                              row: (int)index;
- (void) _setObjectValue: (id)value
          forTableColumn: (NSTableColumn *)tb
                     row: (int) index;
- (int) _numRows;
@end

// These methods are private...
@interface NSOutlineView (TableViewInternalPrivate)
- (void) _initOutlineDefaults;
- (void) _autosaveExpandedItems;
- (void) _autoloadExpandedItems;
- (void) _collectItemsStartingWith: (id)startitem
                              into: (NSMutableArray *)allChildren;
- (void) _loadDictionaryStartingWith: (id) startitem
                             atLevel: (int) level;
- (void) _openItem: (id)item;
- (void) _closeItem: (id)item;
- (void) _removeChildren: (id)startitem;
- (void) _noteNumberOfRowsChangedBelowItem: (id)item by: (int)n;
@end

@interface	NSOutlineView (Private)
- (void) _autoCollapse;
@end

@implementation NSOutlineView

// Initialize the class when it is loaded
+ (void) initialize
{
  if (self == [NSOutlineView class])
    {
      [self setVersion: current_version];
      nc = [NSNotificationCenter defaultCenter];
      /* We need special map table callbacks, to check for identical
       * objects rather than merely equal objects.
       */
      keyCallBacks = NSObjectMapKeyCallBacks;
      keyCallBacks.isEqual = NSOwnedPointerMapKeyCallBacks.isEqual;
#if 0
/* Old Interface Builder style. */
      collapsed    = [NSImage imageNamed: @"common_outlineCollapsed"];
      expanded     = [NSImage imageNamed: @"common_outlineExpanded"];
      unexpandable = [NSImage imageNamed: @"common_outlineUnexpandable"];
#else
/* Current OSX style images. */
// FIXME ... better ones?
      collapsed    = [NSImage imageNamed: @"common_ArrowRightH"];
      expanded     = [NSImage imageNamed: @"common_ArrowDownH"];
      unexpandable = [[NSImage alloc] initWithSize: [expanded size]];
#endif
      autoExpanded = [NSMutableSet new];
    }
}

// Instance methods

/**
 *  Initalizes the outline view with the given frame.   Invokes
 * the superclass method initWithFrame: as well to initialize the object.
 *
 */
- (id) initWithFrame: (NSRect)frame
{
 self = [super initWithFrame: frame];

 if (self != nil)
   {
     [self _initOutlineDefaults];
     //_outlineTableColumn = nil;
   }

  return self;
}

- (void) dealloc
{
  RELEASE(_items);
  RELEASE(_expandedItems);

  NSFreeMapTable(_itemDict);
  NSFreeMapTable(_levelOfItems);

  if (_autosaveExpandedItems)
    {
      // notify when an item expands...
      [nc removeObserver: self
          name: NSOutlineViewItemDidExpandNotification
          object: self];

      // notify when an item collapses...
      [nc removeObserver: self
          name: NSOutlineViewItemDidCollapseNotification
          object: self];
    }

  [super dealloc];
}

/**
 * Causes the outline column, the column containing the expand/collapse
 * gadget, to resize based on the amount of space needed by widest content.
 */
- (BOOL) autoResizesOutlineColumn
{
  return _autoResizesOutlineColumn;
}

/**
 * Causes the outline column, the column containing the expand/collapse
 * gadget, to resize based on the amount of space needed by widest content.
 */
- (BOOL) autosaveExpandedItems
{
  return _autosaveExpandedItems;
}

/**
 * Collapses the given item only.  This is the equivalent of calling
 * [NSOutlineView-collapseItem:collapseChildren:] with NO.
 */
- (void) collapseItem: (id)item
{
  [self collapseItem: item collapseChildren: NO];
}

/**
 * Collapses the specified item.  If collapseChildren is set to YES,
 * then all of the expandable children of this item all also collapsed
 * in a recursive fashion (i.e. all children, grandchildren and etc).
 */
- (void) collapseItem: (id)item collapseChildren: (BOOL)collapseChildren
{
  const SEL shouldSelector = @selector(outlineView:shouldCollapseItem:);
  BOOL canCollapse = YES;

  if ([_delegate respondsToSelector: shouldSelector])
    {
      canCollapse = [_delegate outlineView: self shouldCollapseItem: item];
    }

  if ([self isExpandable: item] && [self isItemExpanded: item] && canCollapse)
    {
      NSMutableDictionary *infoDict = [NSMutableDictionary dictionary];

      [infoDict setObject: item forKey: @"NSObject"];

      // Send out the notification to let observers know that this is about
      // to occur.
      [nc postNotificationName: NSOutlineViewItemWillCollapseNotification
          object: self
          userInfo: infoDict];

      // recursively find all children and call this method to close them.
      // Note: The children must be collapsed before their parent item so
      // that the selected row indexes are properly updated (and in particular
      // are valid when we post our notifications).
      if (collapseChildren) // collapse all
        {
          int index, numChildren;
          NSMutableArray *allChildren;
          id sitem = (item == nil) ? (id)[NSNull null] : (id)item;

          allChildren = NSMapGet(_itemDict, sitem);
          numChildren = [allChildren count];

          for (index = 0; index < numChildren; index++)
            {
              id child = [allChildren objectAtIndex: index];

              if ([self isExpandable: child])
                {
                  [self collapseItem: child collapseChildren: collapseChildren];
                }
            }
        }

      // collapse...
      [self _closeItem: item];

      // Send out the notification to let observers know that this has
      // occurred.
      [nc postNotificationName: NSOutlineViewItemDidCollapseNotification
          object: self
          userInfo: infoDict];

      // Should only mark the rect below the closed item for redraw
      [self setNeedsDisplay: YES];
    }
}

/**
 * Expands the given item only.  This is the equivalent of calling
 * [NSOutlineView-expandItem:expandChildren:] with NO.
 */
- (void) expandItem: (id)item
{
  [self expandItem: item expandChildren: NO];
}

/**
 * Expands the specified item.  If expandChildren is set to YES, then all
 * of the expandable children of this item all also expanded in a recursive
 * fashion (i.e.  all children, grandchildren and etc).
 */
- (void) expandItem: (id)item expandChildren: (BOOL)expandChildren
{
  const SEL shouldExpandSelector = @selector(outlineView:shouldExpandItem:);
  BOOL canExpand = YES;

  if ([_delegate respondsToSelector: shouldExpandSelector])
    {
      canExpand = [_delegate outlineView: self shouldExpandItem: item];
    }

  // if the item is expandable
  if ([self isExpandable: item])
    {
      // if it is not already expanded and it can be expanded, then expand
      if (![self isItemExpanded: item] && canExpand)
        {
          NSMutableDictionary *infoDict = [NSMutableDictionary dictionary];

          [infoDict setObject: item forKey: @"NSObject"];

          // Send out the notification to let observers know that this is about
          // to occur.
          [nc postNotificationName: NSOutlineViewItemWillExpandNotification
              object: self
              userInfo: infoDict];

          // insert the root element, if necessary otherwise insert the
          // actual object.
          [self _openItem: item];

          // Send out the notification to let observers know that this has
          // occurred.
          [nc postNotificationName: NSOutlineViewItemDidExpandNotification
              object: self
              userInfo: infoDict];
        }

      // recursively find all children and call this method to open them.
      if (expandChildren) // expand all
        {
          int index, numChildren;
          NSMutableArray *allChildren;
          id sitem = (item == nil) ? (id)[NSNull null] : (id)item;

          allChildren = NSMapGet(_itemDict, sitem);
          numChildren = [allChildren count];

          for (index = 0; index < numChildren; index++)
            {
              id child = [allChildren objectAtIndex: index];

              if ([self isExpandable: child])
                {
                  [self expandItem: child expandChildren: expandChildren];
                }
            }
        }

      // Should only mark the rect below the expanded item for redraw
      [self setNeedsDisplay: YES];
    }
}

- (NSRect) frameOfOutlineCellAtRow: (NSInteger)row
{
  NSRect frameRect;

  if (![self isExpandable: [self itemAtRow: row]])
    return NSZeroRect;

  frameRect = [self frameOfCellAtColumn: 0
                                    row: row];
  
  if (_indentationMarkerFollowsCell)
    {
      frameRect.origin.x += _indentationPerLevel * [self levelForRow: row];
    }

  return frameRect;
}

/**
 * Returns whether or not the indentation marker or "knob" is indented
 * along with the content inside the cell.
 */
- (BOOL) indentationMarkerFollowsCell
{
  return _indentationMarkerFollowsCell;
}

/**
 * Returns the amount of indentation, in points, for each level
 * of the tree represented by the outline view.
 */
- (CGFloat) indentationPerLevel
{
  return _indentationPerLevel;
}

/**
 * Returns YES, if the item is able to be expanded, NO otherwise.
 *
 * Returns NO when the item is nil (as Cocoa does).
 */
- (BOOL) isExpandable: (id)item
{
  if (item == nil)
    {
      return NO;
    }
  return [_dataSource outlineView: self isItemExpandable: item];
}

/**
 * Returns YES if the item is expanded or open, NO otherwise.
 *
 * Returns YES when the item is nil (as Cocoa does).
 */
- (BOOL) isItemExpanded: (id)item
{
  if (item == nil)
    {
      return YES;
    }
  // Check the array to determine if it is expanded.
  if ([_expandedItems indexOfObjectIdenticalTo: item] == NSNotFound)
    {
      return NO;
    }
  return YES;
}

/**
 * Returns the item at a given row. If no item exists for the given row,
 * returns nil.
 */
- (id) itemAtRow: (NSInteger)row
{
  if ((row >= [_items count]) || (row < 0))
    {
      return nil;
    }
  return [_items objectAtIndex: row];
}

/**
 * Returns the level for a given item.
 */
- (NSInteger) levelForItem: (id)item
{
  if (item != nil)
    {
      id object = NSMapGet(_levelOfItems, item);
      return [object integerValue];
    }

  return -1;
}

/**
 * Returns the level for the given row.
 */
- (NSInteger) levelForRow: (NSInteger)row
{
  return [self levelForItem: [self itemAtRow: row]];
}

/**
 * Returns the outline table column.
 */
- (NSTableColumn *) outlineTableColumn
{
  return _outlineTableColumn;
}

/**
 * Returns the parent of the given item or nil if the item is not found.
 */
- (id) parentForItem: (id)item
{
  NSArray *allKeys = NSAllMapTableKeys(_itemDict);
  NSEnumerator *en = [allKeys objectEnumerator];
  NSInteger index;
  id parent;

  while ((parent = [en nextObject]))
    {
      NSMutableArray *childArray = NSMapGet(_itemDict, parent);

      if ((index = [childArray indexOfObjectIdenticalTo: item]) != NSNotFound)
        {
          return (parent == [NSNull null]) ? (id)nil : (id)parent;
        }
    }

  return nil;
}

/**
 * Causes an item to be reloaded.  This is the equivalent of calling
 * [NSOutlineView-reloadItem:reloadChildren:] with reloadChildren set to NO.
 */
- (void) reloadItem: (id)item
{
  [self reloadItem: item reloadChildren: NO];
}

/**
 * Causes an item and all of it's children to be reloaded if reloadChildren is
 * set to YES, if it's set to NO, then only the item itself is refreshed
 * from the datasource.
 */
- (void) reloadItem: (id)item reloadChildren: (BOOL)reloadChildren
{
  NSInteger index;
  id parent;
  BOOL expanded;
  id dsobj = nil;
  id object = (item == nil) ? (id)[NSNull null] : (id)item;
  NSArray *allKeys = NSAllMapTableKeys(_itemDict);
  NSEnumerator *en = [allKeys objectEnumerator];

  expanded = [self isItemExpanded: item];

  // find the parent of the item
  while ((parent = [en nextObject]))
    {
      NSMutableArray *childArray = NSMapGet(_itemDict, parent);

      if ((index = [childArray indexOfObjectIdenticalTo: object]) != NSNotFound)
        {
          parent = (parent == [NSNull null]) ? (id)nil : (id)parent;
          dsobj = [_dataSource outlineView: self
                               child: index
                               ofItem: parent];

          if (dsobj != item)
            {
              [childArray replaceObjectAtIndex: index withObject: dsobj];
              // FIXME We need to correct _items, _itemDict, _levelOfItems,
              // _expandedItems and _selectedItems
            }
          break;
        }
    }

  if (reloadChildren)
    {
      [self _removeChildren: dsobj];
      [self _loadDictionaryStartingWith: dsobj
            atLevel: [self levelForItem: dsobj]];

      if (expanded)
        {
          [self _openItem: dsobj];
        }
    }
  [self setNeedsDisplay: YES];
}

/**
 * Returns the corresponding row in the outline view for the given item.
 * Returns -1 if item is nil or not found.
 */
- (NSInteger) rowForItem: (id)item
{
  NSInteger row;
  if (item == nil)
    return -1;

  row = [_items indexOfObjectIdenticalTo: item];
  return (row == NSNotFound) ? -1 : row;
}

/**
 * When set to YES this causes the outline column, the column containing
 * the expand/collapse gadget, to resize based on the amount of space
 * needed by widest content.
 */
- (void) setAutoresizesOutlineColumn: (BOOL)resize
{
  _autoResizesOutlineColumn = resize;
}

/**
 * When set to YES, the outline view will save the state of all expanded or
 * collapsed items in the view to the users defaults for the application the
 * outline view is running in.
 */
- (void) setAutosaveExpandedItems: (BOOL)flag
{
  if (flag == _autosaveExpandedItems)
    {
      return;
    }

  _autosaveExpandedItems = flag;
  if (flag)
    {
      [self _autoloadExpandedItems];
      // notify when an item expands...
      [nc addObserver: self
          selector: @selector(_autosaveExpandedItems)
          name: NSOutlineViewItemDidExpandNotification
          object: self];

      // notify when an item collapses...
      [nc addObserver: self
          selector: @selector(_autosaveExpandedItems)
          name: NSOutlineViewItemDidCollapseNotification
          object: self];
    }
  else
    {
      // notify when an item expands...
      [nc removeObserver: self
          name: NSOutlineViewItemDidExpandNotification
          object: self];

      // notify when an item collapses...
      [nc removeObserver: self
          name: NSOutlineViewItemDidCollapseNotification
          object: self];
    }
}

/**
 * If set to YES, the indentation marker will follow the content at each level.
 * Otherwise, the indentation marker will remain at the left most position of
 * the view regardless of how many levels in the content is indented.
 */
- (void) setIndentationMarkerFollowsCell: (BOOL)followsCell
{
  _indentationMarkerFollowsCell = followsCell;
}

/**
 * Sets the amount, in points, that each level is to be indented by.
 */
- (void) setIndentationPerLevel: (CGFloat)newIndentLevel
{
  _indentationPerLevel = newIndentLevel;
}

/**
 * Sets the outline table column in which to place the indentation marker.
 */
- (void)setOutlineTableColumn: (NSTableColumn *)outlineTableColumn
{
  _outlineTableColumn = outlineTableColumn;
}

/**
 * Returns YES, by default.   Subclasses should override this method if
 * a different behaviour is required.
 */
- (BOOL)shouldCollapseAutoExpandedItemsForDeposited: (BOOL)deposited
{
  return YES;
}

/**
 * Sets the data source for this outline view.
 */
- (void) setDataSource: (id)anObject
{
#define CHECK_REQUIRED_METHOD(selector_name) \
  if (anObject && ![anObject respondsToSelector: @selector(selector_name)]) \
    [NSException raise: NSInternalInconsistencyException \
                 format: @"data source does not respond to %@", @#selector_name]

  CHECK_REQUIRED_METHOD(outlineView:child:ofItem:);
  CHECK_REQUIRED_METHOD(outlineView:isItemExpandable:);
  CHECK_REQUIRED_METHOD(outlineView:numberOfChildrenOfItem:);
  CHECK_REQUIRED_METHOD(outlineView:objectValueForTableColumn:byItem:);

  // Is the data source editable?
  _dataSource_editable = [anObject respondsToSelector:
    @selector(outlineView:setObjectValue:forTableColumn:byItem:)];

  /* We do *not* retain the dataSource, it's like a delegate */
  _dataSource = anObject;
  [self tile];
  [self reloadData];
}

/**
 * Forces a from scratch reload of all data in the outline view.
 */
- (void) reloadData
{
  // release the old array
  if (_items != nil)
    {
      RELEASE(_items);
    }

  if (_itemDict != NULL)
    {
      NSFreeMapTable(_itemDict);
    }

  if (_levelOfItems != NULL)
    {
      NSFreeMapTable(_levelOfItems);
    }

  // create a new empty one
  _items = [[NSMutableArray alloc] init];
  _itemDict = NSCreateMapTable(keyCallBacks,
                               NSObjectMapValueCallBacks,
                               64);
  _levelOfItems = NSCreateMapTable(keyCallBacks,
                                   NSObjectMapValueCallBacks,
                                   64);

  // reload all the open items...
  [self _openItem: nil];
  [super reloadData];
}

/**
 * Sets the delegate of the outlineView.
 */
- (void) setDelegate: (id)anObject
{
  const SEL sel = @selector(outlineView:willDisplayCell:forTableColumn:item:);

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

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

  SET_DELEGATE_NOTIFICATION(ColumnDidMove);
  SET_DELEGATE_NOTIFICATION(ColumnDidResize);
  SET_DELEGATE_NOTIFICATION(SelectionDidChange);
  SET_DELEGATE_NOTIFICATION(SelectionIsChanging);
  SET_DELEGATE_NOTIFICATION(ItemDidExpand);
  SET_DELEGATE_NOTIFICATION(ItemDidCollapse);
  SET_DELEGATE_NOTIFICATION(ItemWillExpand);
  SET_DELEGATE_NOTIFICATION(ItemWillCollapse);

  _del_responds = [_delegate respondsToSelector: sel];
}

- (void) encodeWithCoder: (NSCoder*)aCoder
{
  [super encodeWithCoder: aCoder];
  if ([aCoder allowsKeyedCoding] == NO)
    {
      float indentation = _indentationPerLevel;
      [aCoder encodeValueOfObjCType: @encode(BOOL)
                                 at: &_autoResizesOutlineColumn];
      [aCoder encodeValueOfObjCType: @encode(BOOL)
                                 at: &_indentationMarkerFollowsCell];
      [aCoder encodeValueOfObjCType: @encode(BOOL)
                                 at: &_autosaveExpandedItems];
      [aCoder encodeValueOfObjCType: @encode(float)
                                 at: &indentation];
      [aCoder encodeConditionalObject: _outlineTableColumn];
    }
}

- (id) initWithCoder: (NSCoder *)aDecoder
{
  // Since we only have one version....
  self = [super initWithCoder: aDecoder];
  if (self == nil)
    return self;

  [self _initOutlineDefaults];

  if ([aDecoder allowsKeyedCoding])
    {
      // init the table column... (this can't be chosen on IB either)...
      if ([_tableColumns count] > 0)
        {
          _outlineTableColumn = [_tableColumns objectAtIndex: 0];
        }
    }
  else
    {
      float indentation;
      // overrides outline defaults with archived values
      [aDecoder decodeValueOfObjCType: @encode(BOOL)
                                   at: &_autoResizesOutlineColumn];
      [aDecoder decodeValueOfObjCType: @encode(BOOL)
                                   at: &_indentationMarkerFollowsCell];
      [aDecoder decodeValueOfObjCType: @encode(BOOL)
                                   at: &_autosaveExpandedItems];
      [aDecoder decodeValueOfObjCType: @encode(float)
                                   at: &indentation];
      _indentationPerLevel = indentation;
      _outlineTableColumn = [aDecoder decodeObject];
    }
  return self;
}

- (void) mouseDown: (NSEvent *)theEvent
{
  NSPoint location = [theEvent locationInWindow];

  location = [self convertPoint: location  fromView: nil];
  _clickedRow = [self rowAtPoint: location];
  _clickedColumn = [self columnAtPoint: location];

  if (_clickedRow != -1
      && [_tableColumns objectAtIndex: _clickedColumn] == _outlineTableColumn)
    {
      NSImage *image;

      id item = [self itemAtRow:_clickedRow];
      int level = [self levelForRow: _clickedRow];
      int position = 0;

      if ([self isItemExpanded: item])
        {
          image = expanded;
        }
      else
        {
          image = collapsed;
        }

      if (_indentationMarkerFollowsCell)
        {
          position = _indentationPerLevel * level;
        }

      position += _columnOrigins[_clickedColumn];

      if ([self isExpandable:item]
        && location.x >= position
        && location.x <= position + [image size].width)
        {
          BOOL withChildren =
	    ([theEvent modifierFlags] & NSAlternateKeyMask) ? YES : NO;
          if (![self isItemExpanded: item])
            {
              [self expandItem: item expandChildren: withChildren];
            }
          else
            {
              [self collapseItem: item collapseChildren: withChildren];
            }
          return;
        }
    }

  [super mouseDown: theEvent];
}

- (void)keyDown: (NSEvent*)event
{
   NSString *characters = [event characters];

   if ([characters length] == 1)
     {
       unichar c = [characters characterAtIndex: 0];

       NSIndexSet *selected = [self selectedRowIndexes];
       NSInteger i;
       for (i = [selected firstIndex]; i != NSNotFound; i = [selected indexGreaterThanIndex: i])
	 {
	   id item = [self itemAtRow: i];
	   switch (c)
	     {
	     case NSLeftArrowFunctionKey:
	       {
		 if ([self isItemExpanded: item])
		   {
		     [self collapseItem: item];
		   }
		 else
		   {
		     id parent = [self parentForItem: item];
		     if (parent != nil)
		       {
			 NSInteger parentRow = [self rowForItem: parent];
			 [self selectRow: parentRow
			       byExtendingSelection: NO];
			 [self scrollRowToVisible: parentRow];
		       }
		   }
		 return;
	       }
	     case NSRightArrowFunctionKey:
	       [self expandItem: item];
	       return;
	     default:
	       break;
	     }
	 }
     }
 
   [super keyDown: event];
}

/*
 * Drawing
 */
- (void) drawRow: (NSInteger)rowIndex clipRect: (NSRect)aRect
{
  int startingColumn;
  int endingColumn;
  NSRect drawingRect;
  NSCell *imageCell = nil;
  NSRect imageRect;
  int i;
  float x_pos;

  if (_dataSource == nil)
    {
      return;
    }

  /* Using columnAtPoint: here would make it called twice per row per drawn
     rect - so we avoid it and do it natively */

  if (rowIndex >= _numberOfRows)
    {
      return;
    }

  /* Determine starting column as fast as possible */
  x_pos = NSMinX (aRect);
  i = 0;
  while ((i < _numberOfColumns) && (x_pos > _columnOrigins[i]))
    {
      i++;
    }
  startingColumn = (i - 1);

  if (startingColumn == -1)
    startingColumn = 0;

  /* Determine ending column as fast as possible */
  x_pos = NSMaxX (aRect);
  // Nota Bene: we do *not* reset i
  while ((i < _numberOfColumns) && (x_pos > _columnOrigins[i]))
    {
      i++;
    }
  endingColumn = (i - 1);

  if (endingColumn == -1)
    endingColumn = _numberOfColumns - 1;

  /* Draw the row between startingColumn and endingColumn */
  for (i = startingColumn; i <= endingColumn; i++)
    {
      id item = [self itemAtRow: rowIndex];
      NSTableColumn *tb = [_tableColumns objectAtIndex: i];
      NSCell *cell = [self preparedCellAtColumn: i row: rowIndex];

      [self _willDisplayCell: cell
            forTableColumn: tb
            row: rowIndex];
      if (i == _editedColumn && rowIndex == _editedRow)
        {
          [cell _setInEditing: YES];
          [cell setShowsFirstResponder: YES];
        }
      else
        {
          [cell setObjectValue: [_dataSource outlineView: self
                                             objectValueForTableColumn: tb
                                                  byItem: item]];
        }
      drawingRect = [self frameOfCellAtColumn: i
                          row: rowIndex];

      if (tb == _outlineTableColumn)
        {
          NSImage *image = nil;
          NSInteger level = 0;
          CGFloat indentationFactor = 0.0;
          // float originalWidth = drawingRect.size.width;

          // display the correct arrow...
          if ([self isItemExpanded: item])
            {
              image = expanded;
            }
          else
            {
              image = collapsed;
            }

          if (![self isExpandable: item])
            {
              image = unexpandable;
            }

          level = [self levelForItem: item];
          indentationFactor = _indentationPerLevel * level;
          imageCell = [[NSCell alloc] initImageCell: image];
          imageRect = [self frameOfOutlineCellAtRow: rowIndex];

          if ([_delegate respondsToSelector: @selector(outlineView:willDisplayOutlineCell:forTableColumn:item:)])
            {
              [_delegate outlineView: self
                         willDisplayOutlineCell: imageCell
                         forTableColumn: tb
                         item: item];
            }

          /* Do not indent if the delegate set the image to nil. */
          if ([imageCell image])
            {
              imageRect.size.width = [image size].width;
              imageRect.size.height = [image size].height;
              [imageCell drawWithFrame: imageRect inView: self];
              drawingRect.origin.x
                += indentationFactor + imageRect.size.width + 5;
              drawingRect.size.width
                -= indentationFactor + imageRect.size.width + 5;
            }
          else
            {
              drawingRect.origin.x += indentationFactor;
              drawingRect.size.width -= indentationFactor;
            }

          RELEASE(imageCell);
        }

      [cell drawWithFrame: drawingRect inView: self];
      if (i == _editedColumn && rowIndex == _editedRow)
        {
          [cell _setInEditing: NO];
          [cell setShowsFirstResponder: NO];
        }
    }
}

- (void) drawRect: (NSRect)aRect
{
  int index = 0;

  if (_autoResizesOutlineColumn)
    {
      float widest = 0;
      for (index = 0; index < _numberOfRows; index++)
        {
          float offset = [self levelForRow: index] *
            [self indentationPerLevel];
          NSRect drawingRect = [self frameOfCellAtColumn: 0
                                     row: index];
          float length = drawingRect.size.width + offset;
          if (widest < length) widest = length;
        }
      // [_outlineTableColumn setWidth: widest];
    }

  [super drawRect: aRect];
}

- (void) setDropItem: (id)item
      dropChildIndex: (NSInteger)childIndex
{
  if (item != nil && [_items indexOfObjectIdenticalTo: item] == NSNotFound)
    {
      /* FIXME raise an exception, or perhaps we should support
       * setting an item which is not visible (inside a collapsed
       * item presumably), or perhaps we should treat this as
       * cancelling the drop?
       */
      return;
    }
  currentDropItem = item;
  currentDropIndex = childIndex;
}

/*
 *  Drag'n'drop support
 */

- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
{
  //NSLog(@"draggingEntered");
  oldDropItem = currentDropItem = nil;
  oldDropIndex = currentDropIndex = -1;
  lastVerticalQuarterPosition = -1;
  dragOperation = NSDragOperationCopy;
  oldDraggingRect = NSMakeRect(0.,0., 0., 0.);
  return NSDragOperationCopy;
}

- (void) draggingExited: (id <NSDraggingInfo>) sender
{
  [self setNeedsDisplayInRect: oldDraggingRect];
  [self _autoCollapse];
  [self displayIfNeeded];
  DESTROY(lastDragUpdate);
  DESTROY(lastDragChange);
}

// TODO: Move the part that starts at 'Compute the indicator rect area' to GSTheme
- (void) drawDropAboveIndicatorWithDropItem: (id)currentDropItem 
                                      atRow: (int)row 
                             childDropIndex: (int)currentDropIndex
{
  int level = 0;
  NSBezierPath *path = nil;
  NSRect newRect = NSZeroRect;

  /* Compute the indicator rect area */
  if (currentDropItem == nil && currentDropIndex == 0)
    {
      newRect = NSMakeRect([self visibleRect].origin.x,
                           0,
                           [self visibleRect].size.width,
                           2);
    }
  else if (row == _numberOfRows)
    {
      newRect = NSMakeRect([self visibleRect].origin.x,
                           row * _rowHeight - 2,
                           [self visibleRect].size.width,
                           2);
    }
  else
    {
      newRect = NSMakeRect([self visibleRect].origin.x,
                           row * _rowHeight - 1,
                           [self visibleRect].size.width,
                           2);
    }
  level = [self levelForItem: currentDropItem] + 1;
  newRect.origin.x += level * _indentationPerLevel;
  newRect.size.width -= level * _indentationPerLevel;

  [[NSColor darkGrayColor] set];

  /* The rectangle is a line across the cell indicating the
   * insertion position.  We adjust by enough pixels to allow for
   * a ring drawn on the left end.
   */
  newRect.size.width -= 7;
  newRect.origin.x += 7;
  NSRectFill(newRect);

  /* We make the redraw rectangle big enough to hold both the
   * line and the circle (8 pixels high).
   */
  newRect.size.width += 7;
  newRect.origin.x -= 7;
  newRect.size.height = 8;
  newRect.origin.y -= 3;
  oldDraggingRect = newRect;
  if (newRect.size.width < 8)
    oldDraggingRect.size.width = 8;

  /* We draw the circle at the left of the line, and make it
   * a little smaller than the redraw rectangle so that the
   * bezier path will draw entirely inside the redraw area
   * and we won't leave artifacts behind on the screen.
   */
  newRect.size.width = 7;
  newRect.size.height = 7;
  newRect.origin.x += 0.5;
  newRect.origin.y += 0.5;
  path = [NSBezierPath bezierPath];
  [path appendBezierPathWithOvalInRect: newRect];
  [path stroke];
}

/* When the drop item is nil and the drop child index is -1 */
- (void) drawDropOnRootIndicator
{
  NSRect indicatorRect = [self visibleRect];

  /* Remember indicator area to be redrawn next time */
  oldDraggingRect = indicatorRect;

  [[NSColor darkGrayColor] set];
  NSFrameRectWithWidth(indicatorRect, 2.0);
}

// TODO: Move a method common to -drapOnRootIndicator and the one below to GSTheme
- (void) drawDropOnIndicatorWithDropItem: (id)currentDropItem
{
  int row = [_items indexOfObjectIdenticalTo: currentDropItem];
  int level = [self levelForItem: currentDropItem];
  NSRect newRect = [self frameOfCellAtColumn: 0
                                         row: row];

  newRect.origin.x = _bounds.origin.x;
  newRect.size.width = _bounds.size.width + 2;
  newRect.origin.x -= _intercellSpacing.height / 2;
  newRect.size.height += _intercellSpacing.height;

  /* Remember indicator area to be redrawn next time */
  oldDraggingRect = newRect;
  oldDraggingRect.origin.y -= 1;
  oldDraggingRect.size.height += 2;
  
  newRect.size.height -= 1;
  newRect.origin.x += 3;
  newRect.size.width -= 3;

  if (_drawsGrid)
    {
      //newRect.origin.y += 1;
      //newRect.origin.x += 1;
      //newRect.size.width -= 2;
      newRect.size.height += 1;
    }
 
  newRect.origin.x += level * _indentationPerLevel;
  newRect.size.width -= level * _indentationPerLevel;

  [[NSColor darkGrayColor] set];
  NSFrameRectWithWidth(newRect, 2.0);
}

/* Returns the row whose item is the parent that owns the child at the given row. 
Also returns the child index relative to this parent. */
- (NSInteger) _parentRowForRow: (NSInteger)row 
                       atLevel: (NSInteger)level 
           andReturnChildIndex: (NSInteger *)childIndex
{
  NSInteger i;
  NSInteger lvl;

  *childIndex = 0;

  for (i = row - 1; i >= 0; i--)
    {
      BOOL foundParent;
      BOOL foundSibling;

      lvl = [self levelForRow: i];

      foundParent = (lvl == level - 1);
      foundSibling = (lvl == level);

      if (foundParent)
      {
          break;
      }
      else if (foundSibling)
      {
        (*childIndex)++;
      }
    }

  return i;
}

- (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
{
  NSPoint p = [self convertPoint: [sender draggingLocation] fromView: nil];
  /* The insertion row.
   * The insertion row is identical to the hovered row, except when p is in 
   * the hovered row bottom part (the last quarter).
   */
  NSInteger row;
  /* A row can be divided into 4 vertically stacked portions.
   * We call each portion a quarter. 
   * verticalQuarterPosition is the number of quarters that exists between the 
   * top left origin (NSOutlineView is flipped) and the hovered row (precisely 
   * up to the quarter occupied by the pointer in this row). 
   */
  NSInteger verticalQuarterPosition;
  /* An indentation unit can be divided into 2 portions (left and right).
   * We call each portion a half.
   * We use it to compute the insertion level. */
  NSInteger horizontalHalfPosition;
  /* The quarter (0, 1, 2 or 3) occupied by the pointer within the hovered row
   * (not in the insertion row). */
  NSInteger positionInRow;
  /* The previous row level (the row before the insertion row) */
  NSInteger levelBefore;
  /* The next row level (the row after the insertion row) */
  NSInteger levelAfter;
  /* The insertion level that may vary with the horizontal pointer position, 
   * when the pointer is between two rows and the bottom row is a parent.
   */
  NSInteger level;


  ASSIGN(lastDragUpdate, [NSDate date]);
  //NSLog(@"draggingUpdated");

  /* _bounds.origin is (0, 0) when the outline view is not clipped.
   * When the view is scrolled, _bounds.origin.y returns the scrolled height. */
  verticalQuarterPosition =
    GSRoundTowardsInfinity(((p.y + _bounds.origin.y) / _rowHeight) * 4.);
  horizontalHalfPosition =
    GSRoundTowardsInfinity(((p.x + _bounds.origin.y) / _indentationPerLevel) * 2.);

  /* We add an extra quarter to shift the insertion row below the hovered row. */
  row = (verticalQuarterPosition + 1) / 4;
  positionInRow = verticalQuarterPosition % 4;
  if (row > _numberOfRows)
    {
      row = _numberOfRows; // beyond the last real row
      positionInRow = 1;   // inside the root item (we could also use 2)
    }

  //NSLog(@"horizontalHalfPosition = %d", horizontalHalfPosition);
  //NSLog(@"verticalQuarterPosition = %d", verticalQuarterPosition);
  //NSLog(@"insertion row = %d", row);

  if (row == 0)
    {
      levelBefore = 0;
    }
  else
    {
      levelBefore = [self levelForRow: (row - 1)];
    }
  if (row == _numberOfRows)
    {
      levelAfter = 0;
    }
  else
    {
      levelAfter = [self levelForRow: row];
    }
  //NSLog(@"level before = %d", levelBefore);
  //NSLog(@"level after = %d", levelAfter);

  if ((lastVerticalQuarterPosition != verticalQuarterPosition)
    || (lastHorizontalHalfPosition != horizontalHalfPosition))
    {
      NSInteger minInsertionLevel = levelAfter;
      NSInteger maxInsertionLevel = levelBefore;
      NSInteger pointerInsertionLevel = GSRoundTowardsInfinity((float)horizontalHalfPosition / 2.);

      /* Save positions to avoid executing this code when the general
       * position of the mouse is unchanged.
       */
      lastVerticalQuarterPosition = verticalQuarterPosition;
      lastHorizontalHalfPosition = horizontalHalfPosition;

      /* When the row before is an empty parent, we allow to insert the dragged 
       * item as its child. 
       */
      if ([self isExpandable: [self itemAtRow: (row - 1)]])
        {
          maxInsertionLevel++;
        } 

      /* Find the insertion level to be used with a drop above
       *
       * In the outline below, when the pointer moves horizontally on 
       * the dashed line, it can insert at three levels: x level, C level or 
       * B/D level but not at A level.
       * 
       * + A
       *    + B
       *       + C
       *          - x
       * --- pointer ---
       *    + D 
       */
      if (pointerInsertionLevel < minInsertionLevel)
        {
          level = minInsertionLevel;
        }
      else if (pointerInsertionLevel > maxInsertionLevel)
        {
          level = maxInsertionLevel;
        }
      else
        {
          level = pointerInsertionLevel; 
        }

      //NSLog(@"min insert level = %d", minInsertionLevel);
      //NSLog(@"max insert level = %d", maxInsertionLevel);
      //NSLog(@"insert level = %d", level);
      //NSLog(@"row = %d and position in row = %d", row, positionInRow);

      if (positionInRow > 0 && positionInRow < 3) /* Drop on */
	{
	  /* We are directly over the middle of a row ... so the drop
	   * should be directory on the item in that row.
	   */
	  currentDropItem = [self itemAtRow: row];
	  currentDropIndex = NSOutlineViewDropOnItemIndex;
	}
      else /* Drop above */
	{
          NSInteger childIndex = 0;
          NSInteger parentRow = [self _parentRowForRow: row 
                                               atLevel: level 
                                   andReturnChildIndex: &childIndex];

	  //NSLog(@"found %d (proposed childIndex = %d)", parentRow, childIndex);

	  currentDropItem = (parentRow == -1 ? nil : [self itemAtRow: parentRow]);
          currentDropIndex = childIndex;
	}

      if ([_dataSource respondsToSelector:
	@selector(outlineView:validateDrop:proposedItem:proposedChildIndex:)])
        {
           dragOperation = [_dataSource outlineView: self
                                       validateDrop: sender
                                       proposedItem: currentDropItem
				 proposedChildIndex: currentDropIndex];
        }

      //NSLog(@"Drop on %@ %d", currentDropItem, currentDropIndex);

      if ((currentDropItem != oldDropItem)
	|| (currentDropIndex != oldDropIndex))
        {
          oldDropItem = currentDropItem;
          oldDropIndex = currentDropIndex;

	  ASSIGN(lastDragChange, lastDragUpdate);
          [self lockFocus];

          [self setNeedsDisplayInRect: oldDraggingRect];
          [self displayIfNeeded];

	  if (dragOperation != NSDragOperationNone)
	    {
	      if (currentDropIndex != NSOutlineViewDropOnItemIndex && currentDropItem != nil)
		{
		  [self drawDropAboveIndicatorWithDropItem: currentDropItem 
						     atRow: row
					    childDropIndex: currentDropIndex];
		}
	      else if (currentDropIndex == NSOutlineViewDropOnItemIndex && currentDropItem == nil)
		{
		  [self drawDropOnRootIndicator];
		}
	      else
		{
		  [self drawDropOnIndicatorWithDropItem: currentDropItem];
		}
	    }

          [_window flushWindow];
          [self unlockFocus];

        }
    }
  else if (row != _numberOfRows)
    {
      /* If we have been hovering over an item for more than half a second,
       * we should expand it.
       */
      if (lastDragChange != nil && [lastDragUpdate timeIntervalSinceDate: lastDragChange] >= 0.5)
	{
	  id item = [_items objectAtIndex: row];
	  if ([self isExpandable: item] && ![self isItemExpanded: item])
	    {
	      [self expandItem: item expandChildren: NO];
	      if ([self isItemExpanded: item])
		{
		  [autoExpanded addObject: item];
		}
	    }
	  /* Set the change date even if we didn't actually expand ... so
	   * we don't keep trying to expand the same item unnecessarily.
	   */
	  ASSIGN(lastDragChange, lastDragUpdate);
	}
    }

  return dragOperation;
}

- (BOOL) performDragOperation: (id<NSDraggingInfo>)sender
{
  BOOL	result = NO;

  if ([_dataSource
        respondsToSelector:
          @selector(outlineView:acceptDrop:item:childIndex:)])
    {
      result = [_dataSource outlineView: self
			     acceptDrop: sender
				   item: currentDropItem
			     childIndex: currentDropIndex];
    }

  [self _autoCollapse];

  return result;
}

- (BOOL) prepareForDragOperation: (id<NSDraggingInfo>)sender
{
  [self setNeedsDisplayInRect: oldDraggingRect];
  [self displayIfNeeded];

  return YES;
}

- (NSArray*) namesOfPromisedFilesDroppedAtDestination: (NSURL *)dropDestination
{
  if ([_dataSource respondsToSelector:
                    @selector(outlineView:namesOfPromisedFilesDroppedAtDestination:forDraggedItems:)])
    {
      NSUInteger count = [_selectedRows count];
      NSMutableArray *itemArray = [NSMutableArray arrayWithCapacity: count];
      NSUInteger index = [_selectedRows firstIndex];
      
      while (index != NSNotFound)
        {
          [itemArray addObject: [self itemAtRow: index]];
          index = [_selectedRows indexGreaterThanIndex: index];
        }

      return [_dataSource outlineView: self
                          namesOfPromisedFilesDroppedAtDestination: dropDestination
                          forDraggedItems: itemArray];
    }
  else
    {
      return nil;
    }
}

// Autosave methods...
- (void) setAutosaveName: (NSString *)name
{
  [super setAutosaveName: name];
  [self _autoloadExpandedItems];
}

- (void) editColumn: (NSInteger) columnIndex
                row: (NSInteger) rowIndex
          withEvent: (NSEvent *) theEvent
             select: (BOOL) flag
{
  NSText *t;
  NSTableColumn *tb;
  NSRect drawingRect;
  unsigned length = 0;

  // We refuse to edit cells if the delegate can not accept results
  // of editing.
  if (_dataSource_editable == NO)
    {
      flag = YES;
    }

   if (rowIndex != _selectedRow)
    {
      [NSException raise:NSInvalidArgumentException
	      format:@"Attempted to edit unselected row"];
    }

   if (rowIndex < 0 || rowIndex >= _numberOfRows
      || columnIndex < 0 || columnIndex >= _numberOfColumns)
    {
      [NSException raise: NSInvalidArgumentException
                   format: @"Row/column out of index in edit"];
    }

  [self scrollRowToVisible: rowIndex];
  [self scrollColumnToVisible: columnIndex];

  if (_textObject != nil)
    {
      [self validateEditing];
      [self abortEditing];
    }

  // Now (_textObject == nil)

  t = [_window fieldEditor: YES  forObject: self];

  if ([t superview] != nil)
    {
      if ([t resignFirstResponder] == NO)
        {
          return;
        }
    }

  _editedRow = rowIndex;
  _editedColumn = columnIndex;

  // Prepare the cell
  // NB: need to be released when no longer used
  _editedCell = [[self preparedCellAtColumn: columnIndex row: rowIndex] copy];

  [_editedCell setEditable: _dataSource_editable];
  tb = [_tableColumns objectAtIndex: columnIndex];
  [_editedCell setObjectValue: [self _objectValueForTableColumn: tb
                                     row: rowIndex]];

  // But of course the delegate can mess it up if it wants
  [self _willDisplayCell: _editedCell
        forTableColumn: tb
        row: rowIndex];

  /* Please note the important point - calling stringValue normally
     causes the _editedCell to call the validateEditing method of its
     control view ... which happens to be this object :-)
     but we don't want any spurious validateEditing to be performed
     before the actual editing is started (otherwise you easily end up
     with the table view picking up the string stored in the field
     editor, which is likely to be the string resulting from the last
     edit somewhere else ... getting into the bug that when you TAB
     from one cell to another one, the string is copied!), so we must
     call stringValue when _textObject is still nil.  */
  if (flag)
    {
      length = [[_editedCell stringValue] length];
    }

  _textObject = [_editedCell setUpFieldEditorAttributes: t];
  // FIXME: Which background color do we want here?
  [_textObject setBackgroundColor: [NSColor selectedControlColor]];
  [_textObject setDrawsBackground: YES];

  drawingRect = [self frameOfCellAtColumn: columnIndex  row: rowIndex];

  if (tb == [self outlineTableColumn])
    {
      id item = nil;
      NSImage *image = nil;
      NSCell *imageCell = nil;
      NSRect imageRect;
      int level = 0;
      float indentationFactor = 0.0;

      item = [self itemAtRow: rowIndex];
      // determine which image to use...
      if ([self isItemExpanded: item])
        {
          image = expanded;
        }
      else
        {
          image = collapsed;
        }

      if (![self isExpandable: item])
        {
          image = unexpandable;
        }

      level = [self levelForItem: item];
      indentationFactor = _indentationPerLevel * level;
      // create the image cell..
      imageCell = [[NSCell alloc] initImageCell: image];
      imageRect = [self frameOfOutlineCellAtRow: rowIndex];

      if ([_delegate respondsToSelector: @selector(outlineView:willDisplayOutlineCell:forTableColumn:item:)])
        {
          [_delegate outlineView: self
                     willDisplayOutlineCell: imageCell
                     forTableColumn: tb
                     item: item];
        }


      if ([imageCell image])
        {

          imageRect.size.width = [image size].width;
          imageRect.size.height = [image size].height;
          
          // draw...
          [self lockFocus];
          [imageCell drawWithFrame: imageRect inView: self];
          [self unlockFocus];
          
          // move the drawing rect over like in the drawRow routine...
          drawingRect.origin.x += indentationFactor + 5 + imageRect.size.width;
          drawingRect.size.width
            -= indentationFactor + 5 + imageRect.size.width;
        }
      else
        {
          // move the drawing rect over like in the drawRow routine...
          drawingRect.origin.x += indentationFactor;
          drawingRect.size.width -= indentationFactor;
        }

      RELEASE(imageCell);
    }

  if (flag)
    {
      [_editedCell selectWithFrame: drawingRect
                   inView: self
                   editor: _textObject
                   delegate: self
                   start: 0
                   length: length];
    }
  else
    {
      [_editedCell editWithFrame: drawingRect
                   inView: self
                   editor: _textObject
                   delegate: self
                   event: theEvent];
    }

  return;
}

@end /* implementation of NSOutlineView */

@implementation NSOutlineView (NotificationRequestMethods)
/*
 * (NotificationRequestMethods)
 */
- (void) _postSelectionIsChangingNotification
{
  [nc postNotificationName:
        NSOutlineViewSelectionIsChangingNotification
      object: self];
}
- (void) _postSelectionDidChangeNotification
{
  [nc postNotificationName:
        NSOutlineViewSelectionDidChangeNotification
      object: self];
}
- (void) _postColumnDidMoveNotificationWithOldIndex: (int) oldIndex
                                           newIndex: (int) newIndex
{
  [nc postNotificationName:
        NSOutlineViewColumnDidMoveNotification
      object: self
      userInfo: [NSDictionary
                  dictionaryWithObjectsAndKeys:
                  [NSNumber numberWithInt: newIndex],
                  @"NSNewColumn",
                    [NSNumber numberWithInt: oldIndex],
                  @"NSOldColumn",
                  nil]];
}

- (void) _postColumnDidResizeNotificationWithOldWidth: (float) oldWidth
{
  [nc postNotificationName:
        NSOutlineViewColumnDidResizeNotification
      object: self
      userInfo: [NSDictionary
                  dictionaryWithObjectsAndKeys:
                    [NSNumber numberWithFloat: oldWidth],
                  @"NSOldWidth",
                  nil]];
}

- (BOOL) _shouldSelectTableColumn: (NSTableColumn *)tableColumn
{
  if ([_delegate respondsToSelector:
    @selector (outlineView:shouldSelectTableColumn:)] == YES)
    {
      if ([_delegate outlineView: self  shouldSelectTableColumn: tableColumn]
        == NO)
        {
          return NO;
        }
    }

  return YES;
}

- (BOOL) _shouldSelectRow: (int)rowIndex
{
  id item = [self itemAtRow: rowIndex];

  if ([_delegate respondsToSelector:
    @selector (outlineView:shouldSelectItem:)] == YES)
    {
      if ([_delegate outlineView: self  shouldSelectItem: item] == NO)
        {
          return NO;
        }
    }

  return YES;
}

- (BOOL) _shouldSelectionChange
{
  if ([_delegate respondsToSelector:
    @selector (selectionShouldChangeInTableView:)] == YES)
    {
      if ([_delegate selectionShouldChangeInTableView: self] == NO)
        {
          return NO;
        }
    }

  return YES;
}

- (void) _didChangeSortDescriptors: (NSArray *)oldSortDescriptors
{
  if ([_dataSource 
	respondsToSelector: @selector(outlineView:sortDescriptorsDidChange:)])
    {
      [_dataSource outlineView: self
      sortDescriptorsDidChange: oldSortDescriptors];
    }
}

- (void) _didClickTableColumn: (NSTableColumn *)tc
{
  if ([_delegate 
	respondsToSelector: @selector(outlineView:didClickTableColumn:)])
    {
      [_delegate outlineView: self didClickTableColumn: tc];
    }
}

- (BOOL) _shouldEditTableColumn: (NSTableColumn *)tableColumn
                            row: (int) rowIndex
{
  if ([_delegate respondsToSelector:
    @selector(outlineView:shouldEditTableColumn:item:)])
    {
      id item = [self itemAtRow: rowIndex];

      if ([_delegate outlineView: self shouldEditTableColumn: tableColumn
                     item: item] == NO)
        {
          return NO;
        }
    }

  return YES;
}

- (void) _willDisplayCell: (NSCell*)cell
           forTableColumn: (NSTableColumn *)tb
                      row: (int)index
{
  if (_del_responds)
    {
      id item = [self itemAtRow: index];

      [_delegate outlineView: self
                 willDisplayCell: cell
                 forTableColumn: tb
                 item: item];
    }
}

- (BOOL) _writeRows: (NSIndexSet *)rows
       toPasteboard: (NSPasteboard *)pboard
{
  NSUInteger count = [rows count];
  NSMutableArray *itemArray = [NSMutableArray arrayWithCapacity: count];
  NSUInteger index = [rows firstIndex];

  while (index != NSNotFound)
    {
      [itemArray addObject: [self itemAtRow: index]];
      index = [rows indexGreaterThanIndex: index];
    }

  if ([_dataSource respondsToSelector:
                     @selector(outlineView:writeItems:toPasteboard:)] == YES)
    {
      return [_dataSource outlineView: self
                          writeItems: itemArray
                          toPasteboard: pboard];
    }
  return NO;
}

- (BOOL) _isDraggingSource
{
  return [_dataSource respondsToSelector:
                        @selector(outlineView:writeItems:toPasteboard:)];
}

- (id) _objectValueForTableColumn: (NSTableColumn *)tb
                              row: (int) index
{
  id result = nil;

  if ([_dataSource respondsToSelector:
    @selector(outlineView:objectValueForTableColumn:byItem:)])
    {
      id item = [self itemAtRow: index];

      result = [_dataSource outlineView: self
                            objectValueForTableColumn: tb
                            byItem: item];
    }

  return result;
}

- (void) _setObjectValue: (id)value
          forTableColumn: (NSTableColumn *)tb
                     row: (int) index
{
  if ([_dataSource respondsToSelector:
    @selector(outlineView:setObjectValue:forTableColumn:byItem:)])
    {
      id item = [self itemAtRow: index];

      [_dataSource outlineView: self
                   setObjectValue: value
                   forTableColumn: tb
                   byItem: item];
    }
}

- (int) _numRows
{
  return [_items count];
}

@end

@implementation NSOutlineView (TableViewInternalPrivate)

- (void) _initOutlineDefaults
{
  _itemDict = NSCreateMapTable(keyCallBacks,
                               NSObjectMapValueCallBacks,
                               64);
  _items = [[NSMutableArray alloc] init];
  _expandedItems = [[NSMutableArray alloc] init];
  _levelOfItems = NSCreateMapTable(keyCallBacks,
                                   NSObjectMapValueCallBacks,
                                   64);

  _indentationMarkerFollowsCell = YES;
  _autoResizesOutlineColumn = NO;
  _autosaveExpandedItems = NO;
  _indentationPerLevel = 10.0;
}

- (void) _autosaveExpandedItems
{
  if (_autosaveExpandedItems && _autosaveName != nil)
    {
      NSUserDefaults *defaults;
      NSString       *tableKey;

      defaults  = [NSUserDefaults standardUserDefaults];
      tableKey = [NSString stringWithFormat: @"NSOutlineView Expanded Items %@",
                           _autosaveName];
      [defaults setObject: _expandedItems  forKey: tableKey];
      [defaults synchronize];
    }
}

- (void) _autoloadExpandedItems
{
  if (_autosaveExpandedItems && _autosaveName != nil)
    {
      NSUserDefaults *defaults;
      id             config;
      NSString       *tableKey;

      defaults  = [NSUserDefaults standardUserDefaults];
      tableKey = [NSString stringWithFormat: @"NSOutlineView Expanded Items %@",
        _autosaveName];
      config = [defaults objectForKey: tableKey];
      if (config != nil)
        {
          NSEnumerator *en = [config objectEnumerator];
          id item = nil;

          while ((item = [en nextObject]) != nil)
            {
              [self expandItem: item];
            }
        }
    }
}

// Collect all of the items under a given element.
- (void)_collectItemsStartingWith: (id)startitem
                             into: (NSMutableArray *)allChildren
{
  int num;
  int i;
  id sitem = (startitem == nil) ? (id)[NSNull null] : (id)startitem;
  NSMutableArray *anarray;

  anarray = NSMapGet(_itemDict, sitem);
  num = [anarray count];
  for (i = 0; i < num; i++)
    {
      id anitem = [anarray objectAtIndex: i];

      // Only collect the children if the item is expanded
      if ([self isItemExpanded: startitem])
        {
          [allChildren addObject: anitem];
        }

      [self _collectItemsStartingWith: anitem
            into: allChildren];
    }
}

- (BOOL) _isItemLoaded: (id)item
{
  id sitem = (item == nil) ? (id)[NSNull null] : (id)item;
  id object = NSMapGet(_itemDict, sitem);

  // NOTE: We could store the loaded items in a map to ensure we only load 
  // the children of item when it gets expanded for the first time. This would
  // allow to write: return (NSMapGet(_loadedItemDict, sitem) != nil);
  // The last line isn't truly correct because it implies an item without 
  // children will get incorrectly reloaded automatically on each 
  // expand/collapse.
  return ([object count] != 0);
}

- (void) _loadDictionaryStartingWith: (id) startitem
                             atLevel: (int) level
{
  int num = 0;
  int i = 0;
  id sitem = (startitem == nil) ? (id)[NSNull null] : (id)startitem;
  NSMutableArray *anarray = nil;

  /* Check to see if item is expandable and expanded before getting the number 
   * of items. For macos compatibility the topmost item (startitem==nil)
   * is always considered expandable and must not be checked.
   * We must load the item only if expanded, otherwise an outline view is not 
   * usable with a big tree structure. For example, an outline view to browse 
   * file system would try to traverse every file/directory on -reloadData.
   */
  if ((startitem == nil
    || [_dataSource outlineView: self isItemExpandable: startitem])
    && [self isItemExpanded: startitem])
    {
      num = [_dataSource outlineView: self
			 numberOfChildrenOfItem: startitem];
    }

  if (num > 0)
    {
      anarray = [NSMutableArray array];
      NSMapInsert(_itemDict, sitem, anarray);
    }

  NSMapInsert(_levelOfItems, sitem, [NSNumber numberWithInt: level]);

  for (i = 0; i < num; i++)
    {
      id anitem = [_dataSource outlineView: self
                               child: i
                               ofItem: startitem];

      [anarray addObject: anitem];
      [self _loadDictionaryStartingWith: anitem
            atLevel: level + 1];
    }
}

- (void)_closeItem: (id)item
{
  NSUInteger i, numChildren;
  NSMutableArray *removeAll = [NSMutableArray array];

  [self _collectItemsStartingWith: item into: removeAll];
  numChildren = [removeAll count];

  // close the item...
  if (item != nil)
    {
      [_expandedItems removeObjectIdenticalTo: item];
    }

  // For the close method it doesn't matter what order they are
  // removed in.
  for (i = 0; i < numChildren; i++)
    {
      id child = [removeAll objectAtIndex: i];
      [_items removeObjectIdenticalTo: child];
    }
  [self _noteNumberOfRowsChangedBelowItem: item by: -numChildren];
}

- (void)_openItem: (id)item
{
  NSUInteger insertionPoint, numChildren, numDescendants;
  NSInteger i;
  id object;
  id sitem = (item == nil) ? (id)[NSNull null] : (id)item;

  // open the item...
  if (item != nil)
    {
      [_expandedItems addObject: item];
    }

  // Load the children of the item if needed
  if ([self _isItemLoaded: item] == NO)
    {
      [self _loadDictionaryStartingWith: item
                                atLevel: [self levelForItem: item]];
    }

  object = NSMapGet(_itemDict, sitem);
  numChildren = numDescendants = [object count];

  insertionPoint = [_items indexOfObjectIdenticalTo: item];
  if (insertionPoint == NSNotFound)
    {
      insertionPoint = 0;
    }
  else
    {
      insertionPoint++;
    }

  for (i = numChildren-1; i >= 0; i--)
    {
      id obj = NSMapGet(_itemDict, sitem);
      id child = [obj objectAtIndex: i];

      // Add all of the children...
      if ([self isItemExpanded: child])
        {
          NSUInteger numItems;
          NSInteger j;
          NSMutableArray *insertAll = [NSMutableArray array];

          [self _collectItemsStartingWith: child into: insertAll];
          numItems = [insertAll count];
          numDescendants += numItems;
          for (j = numItems-1; j >= 0; j--)
            {
              [_items insertObject: [insertAll objectAtIndex: j]
                      atIndex: insertionPoint];
            }
        }

      // Add the parent
      [_items insertObject: child atIndex: insertionPoint];
    }

  [self _noteNumberOfRowsChangedBelowItem: item by: numDescendants];
}

- (void) _removeChildren: (id)startitem
{
  NSUInteger i, numChildren;
  id sitem = (startitem == nil) ? (id)[NSNull null] : (id)startitem;
  NSMutableArray *anarray;

  anarray = NSMapGet(_itemDict, sitem);
  numChildren = [anarray count];
  for (i = 0; i < numChildren; i++)
    {
      id child = [anarray objectAtIndex: i];

      [self _removeChildren: child];
      NSMapRemove(_itemDict, child);
      [_items removeObjectIdenticalTo: child];
      [_expandedItems removeObjectIdenticalTo: child];
    }
  [anarray removeAllObjects];
  [self _noteNumberOfRowsChangedBelowItem: startitem by: -numChildren];
}

- (void) _noteNumberOfRowsChangedBelowItem: (id)item by: (int)numItems
{
  BOOL selectionDidChange = NO;
  NSUInteger rowIndex, nextIndex;

  // check for trivial case
  if (numItems == 0)
    return;

  // if a row below item is selected, update the selected row indexes
  /* Note: We update the selected row indexes directly instead of calling
   * -selectRowIndexes:extendingSelection: to avoid posting bogus selection
   * did change notifications. */
  rowIndex = [_items indexOfObjectIdenticalTo: item];
  rowIndex = (rowIndex == NSNotFound) ? 0 : rowIndex + 1;
  nextIndex = [_selectedRows indexGreaterThanOrEqualToIndex: rowIndex];
  if (nextIndex != NSNotFound)
    {
      if (numItems > 0)
	{
	  [_selectedRows shiftIndexesStartingAtIndex: rowIndex by: numItems];
	  if (_selectedRow >= rowIndex)
	    {
	      _selectedRow += numItems;
	    }
	}
      else
        {
	  numItems = -numItems;
	  [_selectedRows shiftIndexesStartingAtIndex: rowIndex + numItems
						  by: -numItems];
	  if (nextIndex < rowIndex + numItems)
	    {
	      /* Don't post the notification here, as the table view is in
	       * an inconsistent state. */
	      selectionDidChange = YES;
	    }

	  /* If the selection becomes empty after removing items and the
	   * receiver does not allow empty selections, select the root item. */
          if ([_selectedRows firstIndex] == NSNotFound &&
              [self allowsEmptySelection] == NO)
            {
              [_selectedRows addIndex: 0];
            }

	  if (_selectedRow >= rowIndex + numItems)
	    {
	      _selectedRow -= numItems;
	    }
	  else if (_selectedRow >= rowIndex)
	    {
	      /* If the item at _selectedRow was removed, we arbitrarily choose
	       * another selected item (if there is still any). The policy
	       * implemented below chooses the index most close to item. */
	      NSUInteger r1 = [_selectedRows indexLessThanIndex: rowIndex];
	      NSUInteger r2 = [_selectedRows indexGreaterThanOrEqualToIndex: rowIndex];
	      if (r1 != NSNotFound && r2 != NSNotFound)
		{
		  _selectedRow = (rowIndex - r1) <= (r2 - rowIndex) ? r1 : r2;
		}
	      else if (r1 != NSNotFound)
		{
		  _selectedRow = r1;
		}
	      else if (r2 != NSNotFound)
		{
		  _selectedRow = r2;
		}
	      else
		{
		  _selectedRow = -1;
		}
	    }
        }
    }

  [self noteNumberOfRowsChanged];
  if (selectionDidChange)
    {
      [self _postSelectionDidChangeNotification];
    }
}

- (NSCell *) preparedCellAtColumn: (NSInteger)columnIndex row: (NSInteger)rowIndex
{
  NSCell *cell = nil;
  NSTableColumn *tb = [_tableColumns objectAtIndex: columnIndex];

  if ([_delegate respondsToSelector:
        @selector(outlineView:dataCellForTableColumn:item:)])
    {
      id item = [self itemAtRow: rowIndex];
      cell = [_delegate outlineView: self dataCellForTableColumn: tb
                                                            item: item];
    }
  if (cell == nil)
    {
      cell = [tb dataCellForRow: rowIndex];
    }
  return cell;
}

@end

@implementation	NSOutlineView (Private)
/* Collapse all the items which were automatically expanded to allow drop.
 */
- (void) _autoCollapse
{
  NSEnumerator	*e;
  id		item;

  e = [autoExpanded objectEnumerator];
  while ((item = [e nextObject]) != nil)
    {
      [self collapseItem: item collapseChildren: YES];
    }
  [autoExpanded removeAllObjects];
}
@end