File: NSComboBoxCell.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 (1925 lines) | stat: -rw-r--r-- 54,559 bytes parent folder | download | duplicates (3)
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
/** <title>NSComboBoxCell</title>

   Copyright (C) 1999 Free Software Foundation, Inc.

   Author:  Gerrit van Dyk <gerritvd@decillion.net>
   Date: 1999
   Author:  Quentin Mathe <qmathe@club-internet.fr>
   Date: 2004

   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/NSNotification.h>
#import <Foundation/NSString.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSRunLoop.h>
#import <Foundation/NSException.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSValue.h>
#import "AppKit/NSApplication.h"
#import "AppKit/NSBox.h"
#import "AppKit/NSBrowser.h"
#import "AppKit/NSBrowserCell.h"
#import "AppKit/NSButtonCell.h"
#import "AppKit/NSComboBox.h"
#import "AppKit/NSComboBoxCell.h"
#import "AppKit/NSEvent.h"
#import "AppKit/NSGraphicsContext.h"
#import "AppKit/NSImage.h"
#import "AppKit/NSPanel.h"
#import "AppKit/NSScreen.h"
#import "AppKit/NSScroller.h"
#import "AppKit/NSScrollView.h"
#import "AppKit/NSTableColumn.h"
#import "AppKit/NSTableView.h"
#import "AppKit/NSTextView.h"
#import "GNUstepGUI/GSTheme.h"
#import "GSGuiPrivate.h"

static NSNotificationCenter *nc;

@interface GSComboBoxTableView : NSTableView
{
}

@end

@implementation GSComboBoxTableView
- (BOOL) acceptsFirstMouse: (NSEvent *)event
{
  return YES;
}
@end

@interface GSComboWindow : NSPanel
{
   NSBrowser *_browser;
   GSComboBoxTableView *_tableView;
   NSComboBoxCell *_cell;
   BOOL _stopped;
}

+ (GSComboWindow *) defaultPopUp;

- (void) layoutWithComboBoxCell:(NSComboBoxCell *)comboBoxCell;
- (void) positionWithComboBoxCell:(NSComboBoxCell *)comboBoxCell;
- (void) popUpForComboBoxCell: (NSComboBoxCell *)comboBoxCell;
- (void) runModalPopUpWithComboBoxCell:(NSComboBoxCell *)comboBoxCell;
- (void) runLoopWithComboBoxCell:(NSComboBoxCell *)comboBoxCell;
- (void) onWindowEdited: (NSNotification *)notification;
- (void) clickItem: (id)sender;
- (void) reloadData;
- (void) noteNumberOfItemsChanged;
- (void) scrollItemAtIndexToTop: (NSInteger)index;
- (void) scrollItemAtIndexToVisible: (NSInteger)index;
- (void) selectItemAtIndex: (NSInteger)index;
- (void) deselectItemAtIndex: (NSInteger)index;
- (void) moveUpSelection;
- (void) moveDownSelection;
- (void) validateSelection;

@end

@interface NSComboBoxCell (GNUstepPrivate)
- (NSString *) _stringValueAtIndex: (NSInteger)index;
- (void) _performClickWithFrame: (NSRect)cellFrame inView: (NSView *)controlView;
- (void) _didClickWithinButton: (id)sender;
- (BOOL) _isWantedEvent: (NSEvent *)event;
- (GSComboWindow *) _popUp;
- (NSRect) _textCellFrame;
- (void) _setSelectedItem: (NSInteger)index;
- (void) _loadButtonCell;
- (void) _selectCompleted;
@end

// ---

static GSComboWindow *gsWindow = nil;

@implementation GSComboWindow

+ (GSComboWindow *) defaultPopUp
{
  if (gsWindow == nil)
    gsWindow = [[self alloc] initWithContentRect: NSMakeRect(0,0,200,200)
			               styleMask: NSBorderlessWindowMask
			                 backing: NSBackingStoreNonretained // NSBackingStoreBuffered
			                   defer: YES];
  return gsWindow;
}

- (id) initWithContentRect: (NSRect)contentRect
		 styleMask: (NSUInteger)aStyle
		   backing: (NSBackingStoreType)bufferingType
		     defer: (BOOL)flag
{
  NSBox *box;
  NSRect borderRect;
  NSScrollView *scrollView;
  NSTableColumn *column;
  NSCell *cell;
   
  self = [super initWithContentRect: contentRect
		          styleMask: aStyle
		            backing: bufferingType
		              defer: flag];	  
  if (nil == self)
    return self;

  [self setLevel: NSPopUpMenuWindowLevel];
  [self setBecomesKeyOnlyIfNeeded: YES];
  
  box = [[NSBox alloc] initWithFrame: contentRect];
  [box setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
  [box setBorderType: NSLineBorder];
  [box setTitlePosition: NSNoTitle];
  [box setContentViewMargins: NSMakeSize(0, 0)];
  [self setContentView: box];
  borderRect = contentRect;
  RELEASE(box);
  
  _tableView = [[GSComboBoxTableView alloc] 
                     initWithFrame: NSMakeRect(0, 0, 100, 100)];
  [_tableView setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
  //[_tableView setBackgroundColor: [NSColor whiteColor]];
  [_tableView setDrawsGrid: NO];
  [_tableView setAllowsEmptySelection: YES];
  [_tableView setAllowsMultipleSelection: NO];
  [_tableView setAutoresizesAllColumnsToFit: YES];
  [_tableView setHeaderView: nil];
  [_tableView setCornerView: nil];
  
  column = [[NSTableColumn alloc] initWithIdentifier: @"content"];
  cell = [[NSCell alloc] initTextCell: @""];
  [column setDataCell: cell];
  RELEASE(cell);
  [_tableView addTableColumn: column];
  RELEASE(column);
  
  [_tableView setDataSource: self];
  [_tableView setDelegate: self];
  [_tableView setAction: @selector(clickItem:)];
  [_tableView setTarget: self];
  
  scrollView = [[NSScrollView alloc] initWithFrame: NSMakeRect(borderRect.origin.x, 
                                                               borderRect.origin.y,
                                                               borderRect.size.width, 
                                                               borderRect.size.height)];
  [scrollView setHasVerticalScroller: YES];
  [scrollView setDocumentView: _tableView];
  [_tableView release];
  [box setContentView: scrollView];
  RELEASE(scrollView);
  
  [_tableView reloadData];

  return self;
}

- (BOOL) canBecomeKeyWindow 
{ 
  return YES; 
}

- (void)dealloc
{
  // Browser, table view and scroll view were not retained so don't release them
  [super dealloc];
}

- (void) layoutWithComboBoxCell: (NSComboBoxCell *)comboBoxCell
{
  NSSize bsize = [[GSTheme theme] sizeForBorderType: NSLineBorder];
  NSSize size;
  CGFloat itemHeight;
  CGFloat textCellWidth;
  CGFloat popUpWidth;
  NSSize intercellSpacing;
  NSInteger num = [comboBoxCell numberOfItems];
  NSInteger max = [comboBoxCell numberOfVisibleItems];
  
  // Manage table view or browser cells height
  
  itemHeight = [comboBoxCell itemHeight];
  if (itemHeight <= 0)
    {
      // FIX ME : raise NSException
      itemHeight = [_tableView rowHeight];
    }
  size.height = itemHeight;
    
  // Manage table view or browser cells width
  
  textCellWidth = [comboBoxCell _textCellFrame].size.width;
  if ([comboBoxCell hasVerticalScroller])
    {
      popUpWidth = textCellWidth + [NSScroller scrollerWidth];
    }
  else 
    {
      popUpWidth = textCellWidth;
    }
  size.width = textCellWidth - bsize.width;
    
  if (size.width < 0)
    {
      size.width = 0;
    }
   
  [_tableView setRowHeight: size.height];
    
  // Just check intercell spacing

  intercellSpacing = [comboBoxCell intercellSpacing];
  if (intercellSpacing.height <= 0)
    {
      // FIX ME : raise NSException
      intercellSpacing.height = [_tableView intercellSpacing].height;
    }
  else 
    {
      [_tableView setIntercellSpacing: intercellSpacing];
    }
    
    
  if (num > max)
    num = max;
   
  [self setFrame: [self frameRectForContentRect: NSMakeRect(0, 0, popUpWidth, 
     2 * bsize.height + (itemHeight + intercellSpacing.height) * (num - 1)
     + itemHeight)] display: NO];
}

- (void) positionWithComboBoxCell: (NSComboBoxCell *)comboBoxCell
{
  NSView *viewWithComboCell = [comboBoxCell controlView];
  NSRect screenFrame;
  NSRect comboWindowFrame;
  NSRect viewWithComboCellFrame;
  NSRect rect;
  NSPoint point, oldPoint;
   
  [self layoutWithComboBoxCell: comboBoxCell];
  
  // Now we can ask for the size
  comboWindowFrame = [self frame];
  if (comboWindowFrame.size.width == 0 || comboWindowFrame.size.height == 0)
    return;
  
  screenFrame = [[[viewWithComboCell window] screen] frame];
  viewWithComboCellFrame = [comboBoxCell _textCellFrame];
  if ([viewWithComboCell isFlipped])
  {
      point = viewWithComboCellFrame.origin;
      point.y = NSMaxY(viewWithComboCellFrame);
  }
  else
  {
      point = viewWithComboCellFrame.origin;
  }

  // Switch to the window coordinates
  point = [viewWithComboCell convertPoint: point toView: nil];
  
  // Switch to the screen coordinates
  point = [[viewWithComboCell window] convertBaseToScreen: point];
  point.y -= 1 + NSHeight(comboWindowFrame);
  
  if (point.y < 0)
    {
      // Off screen, so move it
      oldPoint = point;
      
      point = viewWithComboCellFrame.origin;
      point.y = NSMaxY(viewWithComboCellFrame);
      
      // Switch to the window coordinates  
      point = [viewWithComboCell convertPoint: point toView: nil];
  
      // Switch to the screen coordiantes
      point = [[viewWithComboCell window] convertBaseToScreen: point];
      point.y += 1;  
      
      if (point.y + NSHeight(comboWindowFrame) > NSHeight(screenFrame))
	  point = oldPoint;
    }

  rect.size.width = NSWidth(comboWindowFrame);
  rect.size.height = NSHeight(comboWindowFrame);
  rect.origin.x = point.x;
  rect.origin.y = point.y;
  [self setFrame: rect display: NO];
}

- (void) popUpForComboBoxCell: (NSComboBoxCell *)comboBoxCell
{
  _cell = comboBoxCell;
   
  [self positionWithComboBoxCell: _cell];
  [_cell _selectCompleted];
  [self reloadData];
  [self enableKeyEquivalentForDefaultButtonCell];
  [self runModalPopUpWithComboBoxCell: _cell];

  _cell = nil;
  [self deselectItemAtIndex: 0];
}

- (void) runModalPopUpWithComboBoxCell: (NSComboBoxCell *)comboBoxCell
{
  NSWindow	*onWindow;
  
  onWindow = [[_cell controlView] window];

  [nc addObserver: self selector: @selector(onWindowEdited:) 
    name: NSWindowWillCloseNotification object: onWindow];
  [nc addObserver: self selector: @selector(onWindowEdited:) 
    name: NSWindowWillMoveNotification object: onWindow];
  [nc addObserver: self selector: @selector(onWindowEdited:) 
    name: NSWindowWillMiniaturizeNotification object: onWindow];
    
  // FIX ME: The notification below doesn't exist currently
  // [nc addObserver: self selector: @selector(onWindowEdited:) 
  //   name: NSWindowWillResizeNotification object: onWindow];
   
  
  // FIXME: The code below must be removed when the notifications over will work
  [nc addObserver: self selector: @selector(onWindowEdited:) 
    name: NSWindowDidMoveNotification object: onWindow];
  [nc addObserver: self selector: @selector(onWindowEdited:) 
    name: NSWindowDidMiniaturizeNotification object: onWindow];
  [nc addObserver: self selector: @selector(onWindowEdited:) 
    name: NSWindowDidResizeNotification object: onWindow];
  // End of the code to remove
  
  [self orderFront: self];
  [self makeFirstResponder: _tableView];
  [self runLoopWithComboBoxCell: comboBoxCell];
  
  [nc removeObserver: self name: nil object: onWindow];
  
  [self close];

  [onWindow makeFirstResponder: [_cell controlView]];
}

- (void) runLoopWithComboBoxCell: (NSComboBoxCell *)comboBoxCell
{
  NSEvent *event;
  NSDate *limit = [NSDate distantFuture];
  unichar key;
  CREATE_AUTORELEASE_POOL (pool);

  while (YES)
    {
      event = [NSApp nextEventMatchingMask: NSAnyEventMask
		                 untilDate: limit
		                    inMode: NSDefaultRunLoopMode
		                   dequeue: YES];
      if ([event type] == NSLeftMouseDown
       || [event type] == NSRightMouseDown)
        {		   
          if ([comboBoxCell _isWantedEvent: event] == NO && [event window] != self)
	    {
              break;
	    }
	  else
	    {
	      [NSApp sendEvent: event];
	    }
        }
      else if ([event type] == NSKeyDown)
        {
	  key = [[event characters] characterAtIndex: 0];
          if (key == NSUpArrowFunctionKey)
            {
              [self moveUpSelection]; 
            }
          else if (key == NSDownArrowFunctionKey)
            {
              [self moveDownSelection];
            }
          else if (key == NSNewlineCharacter 
	    || key == NSEnterCharacter 
	    || key == NSCarriageReturnCharacter)
            {
              [self validateSelection];
            }
	  else if (key == 0x001b)
	    {
	      break;
	    }
          else
            {
	      [NSApp sendEvent: event];
	    }
	}
      else
        {
	  [NSApp sendEvent: event];
	}
      
      if (_stopped)
        break;      
    }
    
  _stopped = NO;
    
  [pool drain];
}

// onWindow notifications

- (void) onWindowEdited: (NSNotification *)notification
{
  _stopped = YES;
}

- (void) reloadData
{
  [_tableView reloadData];
  [self selectItemAtIndex: [_cell indexOfSelectedItem]];
}

- (void) noteNumberOfItemsChanged
{
  // FIXME: Probably should only load the additional items
  [self reloadData];
}

- (void) scrollItemAtIndexToTop: (NSInteger)index
{
  NSRect rect;
  
  rect = [_tableView frameOfCellAtColumn: 0 row: index];
  [_tableView scrollPoint: rect.origin]; 
}

- (void) scrollItemAtIndexToVisible: (NSInteger)index
{
  [_tableView scrollRowToVisible: index];
}

- (void) selectItemAtIndex: (NSInteger)index
{ 
  if (index < 0)
    return;
  
  if ([_tableView selectedRow] == index || [_tableView numberOfRows] <= index)
    return;
  
  [_tableView selectRow: index byExtendingSelection: NO];     
}

- (void) deselectItemAtIndex: (NSInteger)index
{
  [_tableView deselectAll: self];
}

// Target/Action method
- (void) clickItem: (id)sender
{  
  if (_cell == nil)
    return;
  
  [_cell _setSelectedItem: [sender selectedRow]];
  [self validateSelection];
  
  [nc postNotificationName: NSComboBoxSelectionDidChangeNotification
	            object: [_cell controlView]
	          userInfo: nil];
}

// Browser delegate methods
- (NSInteger) browser: (NSBrowser *)sender numberOfRowsInColumn: (NSInteger)column
{
  if (_cell == nil)
    return 0;

  return [_cell numberOfItems];
}

- (void) browser: (NSBrowser *)sender 
 willDisplayCell: (id)aCell
	   atRow: (NSInteger)row 
	  column: (NSInteger)column
{
  if (_cell == nil)
    return;

  [aCell setStringValue: [_cell _stringValueAtIndex: row]];
  [aCell setLeaf: YES];
}

// Table view data source methods
- (NSInteger) numberOfRowsInTableView: (NSTableView *)tv
{
  return [_cell numberOfItems];
}

- (id) tableView: (NSTableView *)tv objectValueForTableColumn: (NSTableColumn *)tc row: (NSInteger)row
{
  return [_cell _stringValueAtIndex: row];
}

// Table view delegate methods
- (void) tableViewSelectionDidChange: (NSNotification *)notification
{
  [_cell _setSelectedItem: [[notification object] selectedRow]];
  
  [nc postNotificationName: NSComboBoxSelectionDidChangeNotification
	            object: [_cell controlView]
	          userInfo: nil];
}

// Key actions methods
- (void) moveUpSelection
{
  NSInteger index = [_tableView selectedRow] - 1;

  if (index > -1 && index < [_tableView numberOfRows])
    {
      [_tableView selectRow: index byExtendingSelection: NO];
      [_tableView scrollRowToVisible: index];
    }
}

- (void) moveDownSelection
{
  NSInteger index = [_tableView selectedRow] + 1;
  
  if (index > -1 && index < [_tableView numberOfRows])
    {
      [_tableView selectRow: index byExtendingSelection: NO];
      [_tableView scrollRowToVisible: index];
    }
}

- (void) validateSelection
{
  if (_cell != nil)
    {
      NSText	*textObject = nil;
      id	cv = [_cell controlView];
      NSInteger	index = [_cell indexOfSelectedItem];
      
      if ([cv isKindOfClass: [NSControl class]])
        {
	  textObject = [(NSControl *)cv currentEditor];
	}
      
      if (index != -1)
        {
          [_cell setStringValue: [_cell _stringValueAtIndex: 
            [_cell indexOfSelectedItem]]]; 
          // Will update the editor when needed
        }
      
      if  (textObject != nil)
        {
	  NSRange selectionRange = NSMakeRange(0, [[textObject string] length]);
	  [textObject setSelectedRange: selectionRange];
	  [textObject scrollRangeToVisible: selectionRange];
	}	
      
      [cv sendAction: [_cell action] to: [_cell target]];
      
      _stopped = YES;
    }
}

@end

// ---

/**
 <unit>
 <heading>Class Description</heading> 
 <p>An NSComboBoxCell is what we can call a completion/choices box cell, derived from
 NSTextFieldCell, it allows you to enter text like in a text field but also to click
 in the ellipsis button (indicating the fact other user inputs are possible) on
 the right of it to obtain a list of choices, you can use them as the text field
 value by selecting a row in this list. You can also obtain direct completion
 when it  is enabled via <code>setCompletes:</code> to get a suggested text
 field value updated as you type. </p>
 <p>Like other NSCell classes, NSComboBoxCell has a matching NSControl named NSComboBox
 which is relying on it to implement the combo box behavior in a standalone
 control.</p>
 </unit>
*/ 

/**
 * <p>No special instructions to use NSComboBoxCell or text to detail the implementation.</p>
 */
@implementation NSComboBoxCell

/*
 * Class methods
 */
+ (void) initialize
{
  if (self == [NSComboBoxCell class])
    {
      [NSComboBoxCell setVersion: 2];
      nc = [NSNotificationCenter defaultCenter];
    }
}

- (id) initTextCell: (NSString *)aString
{
  self = [super initTextCell: aString];

  // Implicitly set by allocation:
  //
  //_dataSource = nil;
  //_buttonCell = nil;
  //_usesDataSource = NO;
  //_completes = NO;
  _popUpList = [[NSMutableArray alloc] init];
  _hasVerticalScroller = YES;
  _visibleItems = 10;
  _intercellSpacing = NSMakeSize(3.0, 2.0);
  _itemHeight = 16;
  _selectedItem = -1;
  
  [self _loadButtonCell];

  return self;
}

- (void) dealloc
{
  RELEASE(_buttonCell);
  RELEASE(_popUpList);
  
  [super dealloc];
}

- (id) copyWithZone: (NSZone*)zone
{
  NSComboBoxCell *c = [super copyWithZone: zone];

  c->_buttonCell = [_buttonCell copyWithZone: zone];
  [c->_buttonCell setTarget: c];
  c->_popUpList = [_popUpList copyWithZone: zone];

  return c;
}

/**
 * Returns YES when the combo box cell displays a vertical scroller for its
 * list, returns NO otherwise. 
 * Take note that the scroller will be displayed even when the sum of the items
 * height in the list is inferior to the minimal height of the list displayed
 * area. 
 */
- (BOOL) hasVerticalScroller 
{ 
  return _hasVerticalScroller; 
}

/**
 * Sets whether the combo box cell list displays a vertical scroller, by default
 * it is the case. When <var>flag</var> is NO and the combo cell list has more
 * items (either in its default list or from its data source) than the number
 * returned by <code>numberOfVisibleItems</code>, only a subset of them will be
 * displayed. Uses scroll related methods to position this subset in the combo
 * box cell list.
 * Take note that the scroller will be displayed even when the sum of the items
 * height in the list is inferior to the minimal height of the list displayed
 * area.
 */
- (void) setHasVerticalScroller: (BOOL)flag
{
  _hasVerticalScroller = flag;
}

/**
 * Returns the width and the height (as the values of an NSSize variable)
 * between each item of the combo box cell list.
 */
- (NSSize) intercellSpacing
{ 
  return _intercellSpacing; 
}

/**
 * Sets the width and the height between each item of the combo box cell list to
 * the values in <var>aSize</var>.
 */
- (void) setIntercellSpacing: (NSSize)aSize
{
  _intercellSpacing = aSize;
}

/**
 * Returns the height of the items in the combo box cell list.
 */
- (CGFloat) itemHeight 
{ 
  return _itemHeight; 
}

/**
 * Sets the height of the items in the combo box cell list to
 * <var>itemHeight</var>.
 */
- (void) setItemHeight: (CGFloat)itemHeight
{
  if (itemHeight > 14.0)
    _itemHeight = itemHeight;
}

/**
 * Returns the maximum number of allowed items to be displayed in the combo box
 * cell list.
 */
- (NSInteger) numberOfVisibleItems 
{ 
  return _visibleItems; 
}

/**
 * Sets the maximum number of allowed items to be displayed in the combo box
 * cell list.
 */
- (void) setNumberOfVisibleItems: (NSInteger)visibleItems
{
  if (visibleItems > 10)
    _visibleItems = visibleItems;
}

/** 
 * Marks the combo box cell in order to have its items list reloaded in the
 * case it uses a data source, and to have it redisplayed.
 */
- (void) reloadData
{
  [_popup reloadData];
}

/**
 * Informs the combo box cell that the number of items in its data source has
 * changed, in order to permit to the scrollers in its displayed list being
 * updated without needing the reload of the data. 
 * It is recommended to use this method with a data source that continually
 * receives data in the background, to keep the the combo box cell responsive to
 * the user while the data is received.
 * Take a look at the <code>NSComboBoxDataSource</code> informal protocol
 * specification to know more on the messages NSComboBox sends to its data
 * source. 
 */
- (void) noteNumberOfItemsChanged
{
  [_popup noteNumberOfItemsChanged];
}

/**
 * Returns YES when the combo box cell uses a data source (which is external) to
 * populate its items list, otherwise returns NO in the case it uses its default
 * list.
 */
- (BOOL) usesDataSource 
{ 
  return _usesDataSource; 
}

/**
 * Sets according to <var>flag</var> whether the combo box cell uses a data
 * source (which is external) to populate its items list.
 */
- (void) setUsesDataSource: (BOOL)flag
{
  _usesDataSource = flag;
}

/**
 * Scrolls the combo box cell list vertically in order to have the item at
 * <var>index</var> in the closest position relative to the top. There is no
 * need to have the list displayed when this method is invoked.
 */
- (void) scrollItemAtIndexToTop: (NSInteger)index
{
  [_popup scrollItemAtIndexToTop: index];
}

/**
 * Scrolls the combo box cell list vertically in order to have the item at
 * <var>index</var> visible. There is no need to have the list displayed when
 * this method is invoked. 
 */
- (void) scrollItemAtIndexToVisible: (NSInteger)index
{
  [_popup scrollItemAtIndexToVisible: index];
}

/**
 * Selects the combo box cell list row at <var>index</var>. 
 * Take note no changes occurs in the combo box cell list when this method is
 * called. 
 * Posts an NSComboBoxSelectionDidChangeNotification to the default notification
 * center when there is a new selection different from the previous one.
 */
- (void) selectItemAtIndex: (NSInteger)index
{
  // Method called by GSComboWindow when a selection is done in the table view or 
  // the browser
  
  if (index < 0 || [self numberOfItems] <= index)
    return; // FIXME: Probably we should raise an exception

  if (_selectedItem != index)
    {
      [self _setSelectedItem: index];
      
      [_popup selectItemAtIndex: index]; 
      // This method call will not create a infinite loop when the index has been 
      // already set by a mouse click because the method is not completed when the 
      // current index is not different from the index parameter

      [nc postNotificationName: NSComboBoxSelectionDidChangeNotification
	                object: [self controlView]
	              userInfo: nil];
    }
}

/**
 * Deselects the combo box cell list row at <var>index</var> in the case this
 * row is selected. 
 * Posts an NSComboBoxSelectionDidChangeNotification to the default notification
 * center, when there is a new selection.
 */
- (void) deselectItemAtIndex: (NSInteger)index
{
  if (_selectedItem == index)
    {
      [self _setSelectedItem: -1];

      [_popup deselectItemAtIndex: index];

      [nc postNotificationName: NSComboBoxSelectionDidChangeNotification
  	                object: [self controlView]
	              userInfo: nil];
    }
}

/**
 * Returns the index of the selected item in the combo box cell list or -1 when
 * there is no selection, the selected item can be related to the data source
 * object in the case <code>usesDataSource</code> returns YES else to the
 * default items list. 
 */
- (NSInteger) indexOfSelectedItem
{
  return _selectedItem;
}

/**
 * Returns the number of items in the the combo box cell list, the numbers of
 * items can be be related to the data source object in the case
 * <code>usesDataSource</code> returns YES else to the default items list.
 */
- (NSInteger) numberOfItems
{
  if (_usesDataSource)
    {
      if (_dataSource == nil)
        {
          NSLog(@"%@: No data source currently specified", self);
        }
      else if ([_dataSource respondsToSelector: 
                 @selector(numberOfItemsInComboBox:)])
        {
          return [_dataSource numberOfItemsInComboBox: 
            (NSComboBox *)[self controlView]];
        }
      else if ([_dataSource respondsToSelector: 
                  @selector(numberOfItemsInComboBoxCell:)])
        {
          return [_dataSource numberOfItemsInComboBoxCell: self];
        }
    }
  else
    {
      return [_popUpList count];
    }
     
  return 0;
}

/**
 * Returns the combo box cell data source object which is reponsible to provide
 * the data to be displayed. To know how to implement a data source object,
 * take a  look at the NSComboBoxDataSource informal protocol description. In
 * the case <code>usesDataSource</code> returns NO, this method logs a warning.
 */
- (id) dataSource 
{ 
  return _dataSource; 
}

/**
 * Sets the combo box cell data source to <var>aSource</var>. Just calling this
 * method doesn't set <code>usesDataSource</code> to return YES, you must call
 * <code>setUsesDataSource:</code> with YES before or a warning will be logged.
 * To know how to implement a data source objects, take a  look at the
 * NSComboBoxDataSource informal protocol description. When <var>aSource</var>
 * doesn't respond to the methods <code>numberOfItemsInComboBox:</code>
 * <code>comboBox:objectValueForItemAtIndex:</code>, this method
 * logs a warning.
 */
- (void) setDataSource: (id)aSource
{
  if (_usesDataSource == NO)
    {
      NSLog(@"%@: This method is invalid, this combo box is not set to use a data source", 
        self);
    }
  else
    {
      _dataSource = aSource;
    }
}

/**
 * Adds an item to the combo box cell default items list which is used when
 * <code>usesDataSource</code> returns NO. In the case
 * <code>usesDataSource</code> returns YES, this method logs a warning.
 */
- (void) addItemWithObjectValue: (id)object
{
  if (_usesDataSource)
    {
      NSLog(@"%@: This method is invalid, this combo box is set to use a data source", 
        self);
    }
  else
    {
      [_popUpList addObject: object];
    }
    
  [self reloadData];
}

/**
 * Adds several items in an array to the combo box cell default items list which
 * is used when <code>usesDataSource</code> returns NO. In the case
 * <code>usesDataSource</code> returns YES, this method logs a warning.
 */
- (void) addItemsWithObjectValues: (NSArray *)objects
{
  if (_usesDataSource)
    {
      NSLog(@"%@: This method is invalid, this combo box is set to use a data source", 
        self);
    }
  else
    {
      [_popUpList addObjectsFromArray: objects];
    }
    
  [self reloadData];
}

/**
 * Inserts an item in the combo box cell default items list which
 * is used when <code>usesDataSource</code> returns NO. In the case
 * <code>usesDataSource</code> returns YES, this method logs a warning.
 */
- (void) insertItemWithObjectValue: (id)object atIndex: (NSInteger)index
{
  if (_usesDataSource)
    {
      NSLog(@"%@: This method is invalid, this combo box is set to use a data source", 
        self);
    }
  else
    {
      [_popUpList insertObject: object atIndex: index];
    }
    
  [self reloadData];
}

/**
 * Removes an item in the combo box cell default items list which
 * is used when <code>usesDataSource</code> returns NO. In the case
 * <code>usesDataSource</code> returns YES, this method logs a warning.
 */
- (void) removeItemWithObjectValue: (id)object
{
  if (_usesDataSource)
    {
      NSLog(@"%@: This method is invalid, this combo box is set to use a data source", 
        self);
    }
  else
    {
      [_popUpList removeObject: object];
    }
    
  [self reloadData];
}

/**
 * Removes the item with the specified <var>index</var> in the combo box cell
 * default items list which is used when <code>usesDataSource</code> returns NO.
 * In the case <code>usesDataSource</code> returns YES, this method logs a warning.
 */
- (void) removeItemAtIndex: (NSInteger)index
{
  if (_usesDataSource)
    {
      NSLog(@"%@: This method is invalid, this combo box is set to use a data source", 
        self);
    }
  else
    {
      [_popUpList removeObjectAtIndex: index];
    }
    
  [self reloadData];
}

/**
 * Removes all the items in the combo box cell default items list which is used
 * when <code>usesDataSource</code> returns NO. In the case
 * <code>usesDataSource</code> returns YES, this method logs a warning.
 */
- (void) removeAllItems
{
  if (_usesDataSource)
    {
      NSLog(@"%@: This method is invalid, this combo box is set to use a data source", 
        self);
    }
  else
    {
      [_popUpList removeAllObjects];
    }
    
  [self reloadData];
}

/**
 * Selects the first item in the default combo box cell list which is equal to
 * <var>object</var>. In the case <code>usesDataSource</code> returns YES, this
 * method logs a warning. 
 * Take note that this method doesn't update the text field part value. 
 * Posts an NSComboBoxSelectionDidChange notification to the default
 * notification center when the new selection is different than the previous
 * one. 
 */
- (void) selectItemWithObjectValue: (id)object
{
 if (_usesDataSource)
   {
     NSLog(@"%@: This method is invalid, this combo box is set to use a data source", 
       self);
   }
 else
   {
     NSInteger i = [_popUpList indexOfObject: object];

     if (i == NSNotFound)
       i = -1;

     [self selectItemAtIndex: i];
   }
}

/**
 * Returns the object value at <var>index</var> within combo box cell default
 * items list. When the index is beyond the end of the list, an NSRangeException is
 * raised. In the case <code>usesDataSource</code> returns YES, this method logs
 * a warning.
 */
- (id) itemObjectValueAtIndex: (NSInteger)index
{
  if (_usesDataSource)
    {
      NSLog(@"%@: This method is invalid, this combo box is set to use a data source", 
        self);
      return nil;
    }
  else
    {
      return [_popUpList objectAtIndex: index];
    }
}

/* FIXME: Not sure, if this is the best way to implement objectValue,
 * perhaps it would be better to store the current value with setObjectValue: 
 * whenever it changes.
 */
- (id) objectValue
{
  NSInteger index = [self indexOfSelectedItem];

  if (index == -1)
    {
      return nil;
    }
  else
    {
      if (_usesDataSource)
        {
	  if (_dataSource == nil)
	    {
	      NSLog(@"%@: No data source currently specified", self);
	      return nil;
	    }
	  if ([_dataSource respondsToSelector: 
			       @selector(comboBox:objectValueForItemAtIndex:)])
	    {
	      return [_dataSource comboBox: (NSComboBox *)[self controlView] 
				  objectValueForItemAtIndex: index];
	    }
	  else if ([_dataSource respondsToSelector: 
				    @selector(comboBoxCell:objectValueForItemAtIndex:)])
	    {
	      return [_dataSource comboBoxCell: self
				  objectValueForItemAtIndex: index];
	    }
	}
      else
        {
	  return [self itemObjectValueAtIndex: index];
	}
    }
    
  return nil;
}

/**
 * Returns the object value of the selected item in the combo box cell default
 * items list or nil when there is no selection. In the case
 * <code>usesDataSource</code> returns YES, this method logs a warning.
 */
- (id) objectValueOfSelectedItem
{
  if (_usesDataSource)
    {
      NSLog(@"%@: This method is invalid, this combo box is set to use a data source", 
        self);
      return nil;
    }
  else
    {
      NSInteger index = [self indexOfSelectedItem];

      if (index == -1)
        {
          return nil;
        }
      else
        {
          return [_popUpList objectAtIndex: index];
        }
    }
}

/**
 * Returns the lowest index associated with a value in the combo box
 * cell default items list, which is equal to <var>object</var>, and returns
 * NSNotFound when there is no such value. In the case
 * <code>usesDataSource</code> returns YES, this method logs a warning.
 */
- (NSInteger) indexOfItemWithObjectValue: (id)object
{
  if (_usesDataSource)
    {
      NSLog(@"%@: This method is invalid, this combo box is set to use a data source", 
        self);
      return 0;
    }
    
  return [_popUpList indexOfObject: object];
}

/** 
 * Returns the combo box cell default items list in an array.
 */
- (NSArray *) objectValues
{
  if (_usesDataSource)
    {
      NSLog(@"%@: This method is invalid, this combo box is set to use a data source", 
        self);
      return nil;
    }
    
  return _popUpList;
}

// Text completion
/**
 * Returns a string by looking in the combo box cell list for an item wich
 * starts with <var>substring</var>, or nil when there is no such string. 
 * <var>substring</var> is equal to what the user entered in the text field
 * part.
 * You rarely needs to call this method explicitly in your code.
 * By default, the implementation of this method first checks whether the combo
 * box cell uses a data source and whether the data source responds to 
 * <code>comboBox:completedString:</code> or <code>comboBoxCell:completedString:</code>. 
 * When it is the case, it uses this method to return <var>str</var>, else this
 * method goes through the combo box cell items one by one and returns the first
 * item found starting with <var>substring</var>.
 * In the case, you want another behavior, you can override this method without
 * need to call the superclass method.
 */
- (NSString *) completedString: (NSString *)substring
{
  if (nil == substring)
    {
      return nil;
    }

  if (_usesDataSource)
    {
      if (_dataSource == nil)
        {
	  NSLog(@"%@: No data source currently specified", self);
	}
      else if ([_dataSource respondsToSelector: @selector(comboBox:completedString:)])
        {
	  return [_dataSource comboBox: (NSComboBox *)[self controlView] 
		       completedString: substring];
	}
      else if ([_dataSource respondsToSelector: @selector(comboBoxCell:completedString:)])
        {
	  return [_dataSource comboBoxCell: self completedString: substring];
	}
      else
        {
          NSInteger i;

          for (i = 0; i < [self numberOfItems]; i++)
            {
	      NSString *str = [self _stringValueAtIndex: i];

	      if ([str length] > [substring length] && [str hasPrefix: substring])
	        return str;
            }	
	}
    }
  else
    {
      NSUInteger i;

      for (i = 0; i < [_popUpList count]; i++)
        {
	  NSString *str = [[_popUpList objectAtIndex: i] description];

	  if ([str length] > [substring length] && [str hasPrefix: substring])
	    return str;
        }
    }
  
  return substring;
}

/** 
 * Returns YES when the combo box cell automatic completion is active, returns
 * NO otherwise. 
 * Take a look at the <code>setCompletes:</code> method documentation to know
 * how the automatic completion works. 
 */
- (BOOL) completes 
{ 
  return _completes; 
}

/** 
 * Sets whether the combo box cell automatic completion is active or not.
 * The automatic completion tries to complete what the user types in the text
 * field part, it tries to complete only when the the user adds characters at
 * the end of the string, not when it deletes characters or when the insertion
 * point precedes the end of the string.
 * To do the automatic completion, the <code>completedString:</code> method is
 * called, and when the returned string is longer than the current one in the text
 * field, the completion occurs and the completed part gets selected.
 */
- (void) setCompletes: (BOOL)completes
{
  _completes = completes;
}

- (BOOL) isButtonBordered
{
  return [_buttonCell isBordered];
}

- (void) setButtonBordered:(BOOL)flag
{
  [_buttonCell setBordered: flag];
}

#define ComboBoxHeight 21 // FIX ME: All this stuff shouldn't be hardcoded
#define ButtonWidth 17
#define ButtonHeight 17
#define BorderSize 2
// The inset border for the top and the bottom of the button

/*
 * Inlined methods
 */
 
static inline NSRect textCellFrameFromRect(NSRect cellRect) 
// Not the drawed part, precises just the part which receives events
{
  return NSMakeRect(NSMinX(cellRect),
		    NSMinY(cellRect),
		    NSWidth(cellRect) - ButtonWidth - BorderSize,
		    NSHeight(cellRect));
}

static inline NSRect buttonCellFrameFromRect(NSRect cellRect)
{
  return NSMakeRect(NSMaxX(cellRect) - ButtonWidth - BorderSize,
		    NSMinY(cellRect) + BorderSize,
		    ButtonWidth,
		    ButtonHeight);
}

// Overridden
+ (BOOL) prefersTrackingUntilMouseUp
{
  return YES; 
  
  /* Needed to have the clickability of the button take in account when the tracking happens.
     This method is call by the NSControl -mouseDown: method with the code :
     [_cell trackMouse: e
		inRect: _bounds
	        ofView: self
          untilMouseUp: [[_cell class] prefersTrackingUntilMouseUp]] */
}

- (NSSize) cellSize
{
  NSSize textSize;
  NSSize buttonSize;
  NSSize mySize;

  /* Simple version takes the size from text field. A more useful one could 
     loop over the strings of the combo box and calculate the maximal width of 
     all strings. */
  textSize = [super cellSize];
  // Or should we use the hard coded values from above here?
  buttonSize = [_buttonCell cellSize];

  mySize.height = MAX(textSize.height, buttonSize.height);
  mySize.width = textSize.width + BorderSize + buttonSize.width;

  return mySize;
}

- (void) drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
  NSRect rect = cellFrame;

  // FIX ME: Is this test case below with the method call really needed ?
  if ([GSCurrentContext() isDrawingToScreen]) 
    {		           
      [super drawInteriorWithFrame: textCellFrameFromRect(rect)
			    inView: controlView];
      [_buttonCell drawWithFrame: buttonCellFrameFromRect(rect)
		          inView: controlView];
    }
  else
    {
      [super drawInteriorWithFrame: rect inView: controlView];
    }
    
  // Used by GSComboWindow to appear in the right position
  _lastValidFrame = cellFrame; 
}

- (void) highlight: (BOOL)flag
	 withFrame: (NSRect)cellFrame
	    inView: (NSView *)controlView
{
  NSRect rect = cellFrame;

  // FIX ME: Is this test case below with the method call really needed ?
  if ([GSCurrentContext() isDrawingToScreen])
    {
      [super highlight: flag
	     withFrame: textCellFrameFromRect(rect)
	        inView: controlView];
      [_buttonCell highlight: flag
		   withFrame: buttonCellFrameFromRect(rect)
		      inView: controlView];
    }
  else
    {
      [super highlight: flag withFrame: rect inView: controlView];
    }
}

/** Overrides NSCell <code>trackMouse:inRect:ofView:untilMouseUp:</code> method to establish a
 * new method behavior.
 * In the case <var>flag</var> is NO, returns NO when the mouse down occurs in the text
 * cell part or when the mouse down occurs in the button cell part followed by a
 * mouse up outside, otherwise returns YES (when both the mouse down and the
 * mouse up occurs in the button cell part).
 * In the case <var>flag</var> is YES, returns NO when the mouse occurs in the text
 * cell part, otherwise returns YES (when the mouse down occurs in the button cell
 * part).
 */
- (BOOL) trackMouse: (NSEvent *)theEvent 
	     inRect: (NSRect)cellFrame
	     ofView: (NSView *)controlView 
       untilMouseUp: (BOOL)flag
{
  NSPoint point;
  BOOL isFlipped = [controlView isFlipped];
  NSRect buttonRect = buttonCellFrameFromRect(cellFrame);
  NSRect textRect = textCellFrameFromRect(cellFrame);
  BOOL result = NO;

  // FIXME: May be that should be set by NSActionCell
  if (_control_view != controlView)
    _control_view = controlView;
  
  // Used by GSComboWindow to appear in the right position
  _lastValidFrame = cellFrame;
  point = [controlView convertPoint: [theEvent locationInWindow]
			   fromView: nil];

  if (NSMouseInRect(point, textRect, isFlipped))
    {
      return NO;
    }
  else if (NSMouseInRect(point, buttonRect, isFlipped))
    {
      NSEvent *e = theEvent;
      BOOL isMouseUp = NO;  
      NSUInteger eventMask = NSLeftMouseDownMask | NSLeftMouseUpMask
       | NSMouseMovedMask | NSLeftMouseDraggedMask | NSOtherMouseDraggedMask
       | NSRightMouseDraggedMask;
      NSPoint location;
      
      while (isMouseUp == NO) // Loop until mouse goes up
        {
          location = [controlView convertPoint: [e locationInWindow] fromView: nil];
             
	  // Ask the cell to track the mouse only when the mouse is within the cell
          if (NSMouseInRect(location, buttonRect, isFlipped))
	    {
	      [_buttonCell setHighlighted: YES];
	      [controlView setNeedsDisplayInRect: cellFrame];
		
	      result = [_buttonCell trackMouse: e
		                        inRect: buttonRect
		                        ofView: controlView
		                  untilMouseUp: [NSButtonCell prefersTrackingUntilMouseUp]];
              isMouseUp = result;

	      [_buttonCell setHighlighted: NO];
	      [controlView setNeedsDisplayInRect: cellFrame];
            }
		
          if (isMouseUp == NO)
	    {
	      e = [NSApp nextEventMatchingMask: eventMask
			             untilDate: [NSDate distantFuture]
		  		        inMode: NSEventTrackingRunLoopMode
				       dequeue: YES];
            
	      if ([e type] == NSLeftMouseUp)
	        isMouseUp = YES;
	    }
	}
	
      if (flag)
        {
	  return YES;
	}
      else
        {	   
          return NO;
	}
    }

  return NO; // Pathological case, normally never happens
}

- (void) resetCursorRect: (NSRect)cellFrame inView: (NSView *)controlView
{
  [super resetCursorRect: textCellFrameFromRect(cellFrame)
	 inView: controlView];
}

- (void) setEnabled: (BOOL)flag
{
  [_buttonCell setEnabled: flag];
  [super setEnabled: flag];
}

// NSCoding
/**
 * Encodes the combo box cell using <var>encoder</var>. take note that when it
 * uses a data source, the data source is conditionally encoded.
 */
- (void) encodeWithCoder: (NSCoder *)coder
{
  [super encodeWithCoder: coder];

  if ([coder allowsKeyedCoding])
    {
      [coder encodeBool: [self hasVerticalScroller] forKey: @"NSHasVerticalScroller"];
      [coder encodeInt: [self numberOfVisibleItems] forKey: @"NSVisibleItemCount"];
      [coder encodeBool: [self completes] forKey: @"NSCompletes"];
      [coder encodeDouble: _intercellSpacing.width forKey: @"NSIntercellSpacingWidth"];
      [coder encodeDouble: _intercellSpacing.height forKey: @"NSIntercellSpacingHeight"];
      [coder encodeDouble: [self itemHeight] forKey: @"NSRowHeight"];
      [coder encodeBool: [self usesDataSource] forKey: @"NSUsesDataSource"];
      [coder encodeObject: [self dataSource] forKey: @"NSDataSource"];
      [coder encodeObject: _popUpList forKey: @"NSPopUpListData"];
    }
  else
    {
      [coder encodeValueOfObjCType: @encode(id) at: &_popUpList];
      [coder encodeValueOfObjCType: @encode(BOOL) at: &_usesDataSource];
      [coder encodeValueOfObjCType: @encode(BOOL) at: &_hasVerticalScroller];
      [coder encodeValueOfObjCType: @encode(BOOL) at: &_completes];
      [coder encodeValueOfObjCType: @encode(BOOL) at: &_usesDataSource];
      [coder encodeValueOfObjCType: @encode(int) at: &_visibleItems];
      [coder encodeValueOfObjCType: @encode(NSSize) at: &_intercellSpacing];
      [coder encodeValueOfObjCType: @encode(float) at: &_itemHeight];
      [coder encodeValueOfObjCType: @encode(int) at: &_selectedItem];
      
      if (_usesDataSource == YES)
	[coder encodeConditionalObject: _dataSource];      
    }
}

/**
 * Initializes the combo box cell with data linked to <var>decoder</var>. Take
 * note that when the decoded instance uses a data source,
 * <code>initWithCoder:<var> decodes the data source. 
 * Finally, returns thr initialized object.
 */
- (id) initWithCoder: (NSCoder *)aDecoder
{
  self = [super initWithCoder: aDecoder];
  if (nil == self)
    return nil;

  if ([aDecoder allowsKeyedCoding])
    {
      //id delegate = [aDecoder decodeObjectForKey: @"NSDelegate"];
      //id table = [aDecoder decodeObjectForKey: @"NSTableView"];

      if ([aDecoder containsValueForKey: @"NSHasVerticalScroller"])
        {
	  [self setHasVerticalScroller: [aDecoder decodeBoolForKey: 
						      @"NSHasVerticalScroller"]];
	}
      if ([aDecoder containsValueForKey: @"NSVisibleItemCount"])
        {
	  [self setNumberOfVisibleItems: [aDecoder decodeIntForKey: 
						       @"NSVisibleItemCount"]];
	}
      if ([aDecoder containsValueForKey: @"NSCompletes"])
        {
          [self setCompletes: [aDecoder decodeBoolForKey: @"NSCompletes"]];
        }
      if ([aDecoder containsValueForKey: @"NSIntercellSpacingWidth"])
        {
          _intercellSpacing.width = [aDecoder decodeDoubleForKey: 
                                                @"NSIntercellSpacingWidth"];
        }
      if ([aDecoder containsValueForKey: @"NSIntercellSpacingHeight"])
        {
          _intercellSpacing.height = [aDecoder decodeDoubleForKey: 
                                                 @"NSIntercellSpacingHeight"];
        }
      if ([aDecoder containsValueForKey: @"NSRowHeight"])
        {
	  [self setItemHeight: [aDecoder decodeDoubleForKey: 
                                           @"NSRowHeight"]];
	}
      if ([aDecoder containsValueForKey: @"NSUsesDataSource"])
        {
          [self setUsesDataSource: [aDecoder decodeBoolForKey: 
                                               @"NSUsesDataSource"]];
        }
      if ([aDecoder containsValueForKey: @"NSDataSource"])
        {
          [self setDataSource: [aDecoder decodeObjectForKey: @"NSDataSource"]];
        }
      if ([aDecoder containsValueForKey: @"NSPopUpListData"])
        {
          ASSIGN(_popUpList, [aDecoder decodeObjectForKey: @"NSPopUpListData"]);
        }
    }
  else
    {
      BOOL dummy;
      
      if ([aDecoder versionForClassName: @"NSComboBoxCell"] < 2)
        {
          // In previous version we decode _buttonCell, we just discard the decoded value here
          id previouslyEncodedButton;
          [aDecoder decodeValueOfObjCType: @encode(id) at: &previouslyEncodedButton];
        }

      [aDecoder decodeValueOfObjCType: @encode(id) at: &_popUpList];
      RETAIN(_popUpList);
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &_usesDataSource];
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &_hasVerticalScroller];
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &_completes];
      [aDecoder decodeValueOfObjCType: @encode(BOOL) at: &dummy];
      [aDecoder decodeValueOfObjCType: @encode(int) at: &_visibleItems];
      [aDecoder decodeValueOfObjCType: @encode(NSSize) at: &_intercellSpacing];
      [aDecoder decodeValueOfObjCType: @encode(float) at: &_itemHeight];
      [aDecoder decodeValueOfObjCType: @encode(int) at: &_selectedItem];

      if (_usesDataSource == YES)
	[self setDataSource: [aDecoder decodeObject]];      
    }
  
  [self _loadButtonCell];

  return self;
}

- (void) selectWithFrame: (NSRect)aRect 
		  inView: (NSView *)controlView
		  editor: (NSText *)textObj 
		delegate: (id)anObject
		   start: (NSInteger)selStart 
		  length: (NSInteger)selLength
{
  [super selectWithFrame: textCellFrameFromRect(aRect)
                  inView: controlView
                  editor: textObj 
                delegate: anObject
                   start: selStart 
                  length: selLength];
  
  [nc addObserver: self 
         selector: @selector(textDidChange:)
	     name: NSTextDidChangeNotification 
	   object: textObj];
  [nc addObserver: self 
         selector: @selector(textViewDidChangeSelection:)
	     name: NSTextViewDidChangeSelectionNotification 
	   object: textObj];
	  
  // This method is called when the cell obtains the focus;
  // don't know why the next method editWithFrame: is not called
}

- (void) editWithFrame: (NSRect)frame
                inView: (NSView *)controlView
	        editor: (NSText *)textObj 
	      delegate: (id)delegate 
	         event: (NSEvent *)theEvent
{
  [super editWithFrame: textCellFrameFromRect(frame)
                inView: controlView
                editor: textObj
              delegate: delegate
                 event: theEvent];
  
  /*
  [nc addObserver: self 
         selector: @selector(textDidChange:)
	     name: NSTextDidChangeNotification 
	   object: textObj];
  [nc addObserver: self 
         selector: @selector(textViewDidChangeSelection:)
	     name: NSTextViewDidChangeSelectionNotification 
	   object: textObj]; */
}

- (void) endEditing: (NSText *)editor
{
  /* Close the pop up if it is still open. This may happen, e.g., when the
     user presses the Tab key to shift focus to a different cell or view. */
  if (_popup)
    [_popup onWindowEdited: nil];

  [super endEditing: editor];
  [nc removeObserver: self name: NSTextDidChangeNotification object: editor];
  [nc removeObserver: self 
                name: NSTextViewDidChangeSelectionNotification 
	      object: editor];
}

- (void) textViewDidChangeSelection: (NSNotification *)notification
{
  _prevSelectedRange = [[[notification userInfo] 
    objectForKey: @"NSOldSelectedCharacterRange"] rangeValue];
}

- (void) textDidChange: (NSNotification *)notification
{
  NSText *textObject = [notification object];

  if ([self completes])
    {
      NSString *myString = [[textObject string] copy];
      NSString *more;
      NSUInteger myStringLength = [myString length];
      NSUInteger location, length;
      NSRange selectedRange = [textObject selectedRange];
      
      if (myStringLength != 0
        && selectedRange.location == myStringLength
        && _prevSelectedRange.location < selectedRange.location)
        {
          more = [self completedString: myString];
          if ((more != nil) && [more isEqualToString: myString] == NO)
            {
	      [textObject setString: more];
	      location = myStringLength;
              length = [more length] - location;
	      [textObject setSelectedRange: NSMakeRange(location, length)];
	      [textObject scrollRangeToVisible: NSMakeRange(location, length)];
	    }
        }
      RELEASE(myString);
    }
}

@end

@implementation NSComboBoxCell (GNUstepPrivate)

- (NSString *) _stringValueAtIndex: (NSInteger)index
{
  if (_usesDataSource == NO)
    {
      return [[self itemObjectValueAtIndex: index] description];
    }
  else
    {
      if (_dataSource == nil)
        {
	  NSLog(@"%@: No data source currently specified", self);
	  return nil;
	}
      else if ([_dataSource respondsToSelector: 
			   @selector(comboBox:objectValueForItemAtIndex:)])
        {
	  return [[_dataSource comboBox: (NSComboBox *)[self controlView] 
			       objectValueForItemAtIndex: index] description];
	}
      else if ([_dataSource respondsToSelector: 
				@selector(comboBoxCell:objectValueForItemAtIndex:)])
        {
	  return [[_dataSource comboBoxCell: self
			      objectValueForItemAtIndex: index] description];
	}
    }

  return nil;
}

- (void) _performClickWithFrame: (NSRect)cellFrame 
                         inView: (NSView *)controlView
{
  NSWindow *cvWindow = [controlView window];
  NSRect buttonRect = buttonCellFrameFromRect(cellFrame);

  _control_view = controlView;
  [controlView lockFocus];
  [_buttonCell highlight: YES 
	       withFrame: buttonRect
	          inView: controlView];
  [controlView unlockFocus];
  [cvWindow flushWindow];

  [self _didClickWithinButton: self];
  
  [controlView lockFocus];
  [_buttonCell highlight: NO 
	       withFrame: buttonRect
	          inView: controlView];
  [controlView unlockFocus];
  [cvWindow flushWindow];

}

- (void) _didClickWithinButton: (id)sender
{
  NSView *controlView = [self controlView];
  
  if ((_cell.is_disabled) || (controlView == nil))
    return;

  [nc postNotificationName: NSComboBoxWillPopUpNotification 
                    object: controlView 
		  userInfo: nil];
  
  _popup = [self _popUp];
  [_popup popUpForComboBoxCell: self];
  _popup = nil;

  [nc postNotificationName: NSComboBoxWillDismissNotification
                    object: controlView
                  userInfo: nil];
}

- (BOOL) _isWantedEvent: (NSEvent *)event
{
  NSPoint loc;
  NSWindow *window = [event window];
  NSView *controlView = [self controlView];
  
  if (window == [[self controlView] window])
    {
      loc = [event locationInWindow];
      loc = [controlView convertPoint: loc fromView: nil];
      return NSMouseInRect(loc, [self _textCellFrame], [controlView isFlipped]);
    }
  else
    {
      return NO;
    }
}

- (GSComboWindow *) _popUp
{
  return [GSComboWindow defaultPopUp];
}

- (NSRect) _textCellFrame
{
  return textCellFrameFromRect(_lastValidFrame);
}

- (void) _setSelectedItem: (NSInteger)index
{
  _selectedItem = index;
}

- (void) _loadButtonCell
{
  _buttonCell = [[NSButtonCell alloc] initImageCell: 
		    [NSImage imageNamed: @"NSComboArrow"]];
  [_buttonCell setImagePosition: NSImageOnly];
  [_buttonCell setButtonType: NSMomentaryPushButton];
  [_buttonCell setHighlightsBy: NSPushInCellMask];
  [_buttonCell setBordered: YES];
  [_buttonCell setTarget: self];
  [_buttonCell setAction: @selector(_didClickWithinButton:)];
  [_buttonCell setEnabled: [self isEnabled]];
}

- (void) _selectCompleted
{
  NSString *more;
  NSUInteger index = NSNotFound;

  more = [self completedString: [self stringValue]];
  if (_usesDataSource)
    {
      if (_dataSource == nil)
        {
	  NSLog(@"%@: No data source currently specified", self);
	}
      else
        {
	  if ([_dataSource respondsToSelector: 
			       @selector(comboBoxCell:indexOfItemWithStringValue:)])
	    {
	      index = [_dataSource comboBoxCell: self 
		     indexOfItemWithStringValue: more];
	    }
	}
    }
  else
    {
      index = [[self objectValues] indexOfObject: more];
    }

  if (index != NSNotFound)
    {
      [self _setSelectedItem: index];
    }
  // Otherwise keep old selection
}

@end