File: NSMenu.m

package info (click to toggle)
gnustep-gui 0.7.6-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 16,464 kB
  • ctags: 7,163
  • sloc: objc: 84,669; ansic: 14,192; yacc: 290; makefile: 196; cpp: 87; sh: 21
file content (1505 lines) | stat: -rw-r--r-- 33,594 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
/** <title>NSMenu</title>

   Copyright (C) 1999 Free Software Foundation, Inc.

   Author: Fred Kiefer <FredKiefer@gmx.de>
   Date: Aug 2001
   Author: David Lazaro Saz <khelekir@encomix.es>
   Date: Oct 1999
   Author: Michael Hanni <mhanni@sprintmail.com>
   Date: 1999
   Author: Felipe A. Rodriguez <far@ix.netcom.com>
   Date: July 1998
   and: 
   Author: Ovidiu Predescu <ovidiu@net-community.com>
   Date: May 1997
   
   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 Library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with this library; see the file COPYING.LIB.
   If not, write to the Free Software Foundation,
   59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ 

#include <gnustep/gui/config.h>
#include <Foundation/NSCoder.h>
#include <Foundation/NSArray.h>
#include <Foundation/NSException.h>
#include <Foundation/NSProcessInfo.h>
#include <Foundation/NSString.h>
#include <Foundation/NSNotification.h>

#include <AppKit/NSMatrix.h>
#include <AppKit/NSApplication.h>
#include <AppKit/NSWindow.h>
#include <AppKit/NSEvent.h>
#include <AppKit/NSFont.h>
#include <AppKit/NSMenu.h>
#include <AppKit/NSMenuItem.h>
#include <AppKit/NSMenuView.h>
#include <AppKit/NSPopUpButton.h>
#include <AppKit/NSPopUpButtonCell.h>
#include <AppKit/NSScreen.h>

/* A menu's title is an instance of this class */
@interface NSMenuWindowTitleView : NSView
{
  id  menu;
  NSButton *button;
}

- (void) addCloseButton;
- (void) releaseCloseButton;
- (void) createButton;
- (void) setMenu: (NSMenu*)menu;
- (NSMenu*) menu;

@end

static NSZone	*menuZone = NULL;
static NSString	*NSMenuLocationsKey = @"NSMenuLocations";
static NSNotificationCenter *nc;

@interface	NSMenu (GNUstepPrivate)
- (NSString*) _locationKey;
- (NSPanel*) _createWindow;
@end

@implementation	NSMenu (GNUstepPrivate)

- (NSString*) _locationKey
{
  if (_superMenu == nil)
    {
      if ([NSApp mainMenu] == self)
	{
	  return @"\033";	/* Root menu.	*/
	}
      else
	{
	  return nil;		/* Unused menu.	*/
	}
    }
  else if (_superMenu->_superMenu == nil)
    {
      return [NSString stringWithFormat: @"\033%@", [self title]];
    }
  else
    {
      return [[_superMenu _locationKey] stringByAppendingFormat: @"\033%@",
	[self title]];
    }
}

/* Create a non autorelease window for this menu.  */
- (NSPanel*) _createWindow
{
  NSPanel *win = [[NSPanel alloc] 
		     initWithContentRect: NSZeroRect
		     styleMask: NSBorderlessWindowMask
		     backing: NSBackingStoreBuffered
		     defer: YES];
  [win setLevel: NSSubmenuWindowLevel];
  [win setWorksWhenModal: YES];
  [win setBecomesKeyOnlyIfNeeded: YES];

  return win;
}

@end


@implementation NSMenu

/*
 * Class Methods
 */
+ (void) initialize
{
  if (self == [NSMenu class])
    {
      [self setVersion: 1];
      nc = [NSNotificationCenter defaultCenter];
      menuZone = NSCreateZone(0, 0, YES);
    }
}

+ (void) setMenuZone: (NSZone*)zone
{
  menuZone = zone;
}

+ (NSZone*) menuZone
{
  return menuZone;
}

/*
 * Initializing a New NSMenu
 */
- (id) init
{
  return [self initWithTitle: @"Menu"];
}

- (void) dealloc
{
  NSDebugLog (@"NSMenu `%@' dealloc", _title);

  [nc removeObserver: self];

  RELEASE(_notifications);
  RELEASE(_title);
  RELEASE(_items);
  RELEASE(_view);
  RELEASE(_aWindow);
  RELEASE(_bWindow);
  RELEASE(_titleView);

  [super dealloc];
}

- (id) initWithTitle: (NSString*)aTitle
{
  float  height;
  NSView *contentView;

  [super init];

  // Keep the title.
  ASSIGN(_title, aTitle);

  // Create an array to store out menu items.
  _items = [[NSMutableArray alloc] init];

  // We have no supermenu.
  // _superMenu = nil;
  // _is_tornoff = NO;
  // _follow_transient = NO;

  _changedMessagesEnabled = YES;
  _notifications = [[NSMutableArray alloc] init];
  _changed = YES;
  // According to the spec, menus do autoenable by default.
  _autoenable = YES;

  // Transient windows private stuff.
  // _oldAttachedMenu = nil;

  /* Please note that we own all this menu network of objects.  So, 
     none of these objects should be retaining us.  When we are deallocated,
     we release all the objects we own, and that should cause deallocation
     of the whole menu network.  */

  // Create the windows that will display the menu.
  _aWindow = [self _createWindow];
  _bWindow = [self _createWindow];

  // Create a NSMenuView to draw our menu items.
  _view = [[NSMenuView alloc] initWithFrame: NSMakeRect(0,0,50,50)];
  [_view setMenu: self];

  // Create the title view
  height = [[_view class] menuBarHeight];
  _titleView = [[NSMenuWindowTitleView alloc] initWithFrame: 
						NSMakeRect(0, 0, 50, height)];
  [_titleView setMenu: self];

  contentView = [_aWindow contentView];
  [contentView addSubview: _view];
  [contentView addSubview: _titleView];

  /* Set up the notification to start the process of redisplaying
     the menus where the user left them the last time.  
     
     Use NSApplicationDidFinishLaunching, and not
     NSApplicationWillFinishLaunching, so that the programmer can set
     up menus in NSApplicationWillFinishLaunching.
  */
  [nc addObserver: self
      selector: @selector(_showTornOffMenuIfAny:)
      name: NSApplicationDidFinishLaunchingNotification 
      object: NSApp];

  return self;
}

/*
 * Setting Up the Menu Commands
 */
- (void) insertItem: (id <NSMenuItem>)newItem
	    atIndex: (int)index
{
  NSNotification *inserted;
  NSDictionary   *d;

  if (![(id)newItem conformsToProtocol: @protocol(NSMenuItem)])
    {
      NSLog(@"You must use an object that conforms to NSMenuItem.\n");
      return;
    }

  /*
   * If the item is already attached to another menu it
   * isn't added.
   */
  if ([newItem menu] != nil)
    return;
  
  [_items insertObject: newItem atIndex: index];
  _changed = YES;
  
  // Create the notification for the menu representation.
  d = [NSDictionary
	  dictionaryWithObject: [NSNumber numberWithInt: index]
	  forKey: @"NSMenuItemIndex"];
  inserted = [NSNotification
		 notificationWithName: NSMenuDidAddItemNotification
		 object: self
		 userInfo: d];
  
  if (_changedMessagesEnabled)
    [nc postNotification: inserted];
  else
    [_notifications addObject: inserted];

  // Set this after the insert notification has been send.
  [newItem setMenu: self];

  // Update the menu.
  [self update];
}

- (id <NSMenuItem>) insertItemWithTitle: (NSString*)aString
			         action: (SEL)aSelector
			  keyEquivalent: (NSString*)charCode 
			        atIndex: (unsigned int)index
{
  NSMenuItem *anItem = [[NSMenuItem alloc] initWithTitle: aString
					   action: aSelector
					   keyEquivalent: charCode];

  // Insert the new item into the menu.
  [self insertItem: anItem atIndex: index];

  // For returns sake.
  return AUTORELEASE(anItem);
}

- (void) addItem: (id <NSMenuItem>)newItem
{
  [self insertItem: newItem atIndex: [_items count]];
}

- (id <NSMenuItem>) addItemWithTitle: (NSString*)aString
			      action: (SEL)aSelector 
		       keyEquivalent: (NSString*)keyEquiv
{
  return [self insertItemWithTitle: aString
			    action: aSelector
		     keyEquivalent: keyEquiv
			   atIndex: [_items count]];
}

- (void) removeItem: (id <NSMenuItem>)anItem
{
  int index = [self indexOfItem: anItem];

  if (-1 == index)
    return;

  [self removeItemAtIndex: index];
}

- (void) removeItemAtIndex: (int)index
{
  NSNotification *removed;
  NSDictionary	 *d;
  id		 anItem = [_items objectAtIndex: index];

  if (!anItem)
    return;

  [anItem setMenu: nil];
  [_items removeObjectAtIndex: index];
  _changed = YES;
  
  d = [NSDictionary dictionaryWithObject: [NSNumber numberWithInt: index]
		    forKey: @"NSMenuItemIndex"];
  removed = [NSNotification
		notificationWithName: NSMenuDidRemoveItemNotification
		object: self
		userInfo: d];
  
  if (_changedMessagesEnabled)
    [nc postNotification: removed];
  else
    [_notifications addObject: removed];

  // Update the menu.
  [self update];
}

- (void) itemChanged: (id <NSMenuItem>)anObject
{
  NSNotification *changed;
  NSDictionary   *d;
  int index = [self indexOfItem: anObject];

  if (-1 == index)
    return;

  _changed = YES;

  d = [NSDictionary dictionaryWithObject: [NSNumber numberWithInt: index]
		    forKey: @"NSMenuItemIndex"];
  changed = [NSNotification
	      notificationWithName: NSMenuDidChangeItemNotification
	                    object: self
	                  userInfo: d];

  if (_changedMessagesEnabled)
    [nc postNotification: changed];
  else
    [_notifications addObject: changed];

  // Update the menu.
  [self update];
}

/*
 * Finding Menu Items
 */
- (id <NSMenuItem>) itemWithTag: (int)aTag
{
  unsigned i;
  unsigned count = [_items count];

  for (i = 0; i < count; i++)
    {
      id menuItem = [_items objectAtIndex: i];

      if ([menuItem tag] == aTag)
        return menuItem;
    }
  return nil;
}

- (id <NSMenuItem>) itemWithTitle: (NSString*)aString
{
  unsigned i;
  unsigned count = [_items count];

  for (i = 0; i < count; i++)
    {
      id menuItem = [_items objectAtIndex: i];

      if ([[menuItem title] isEqualToString: aString])
        return menuItem;
    }
  return nil;
}

- (id <NSMenuItem>) itemAtIndex: (int)index
{
  if (index >= [_items count] || index < 0)
    [NSException  raise: NSRangeException
		 format: @"Range error in method -itemAtIndex: "];

  return [_items objectAtIndex: index];
}

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

- (NSArray*) itemArray
{
  return (NSArray*)_items;
}

/*
 * Finding Indices of Menu Items
 */
- (int) indexOfItem: (id <NSMenuItem>)anObject
{
  int index;

  index = [_items indexOfObjectIdenticalTo: anObject];

  if (index == NSNotFound)
    return -1;
  else
    return index;
}

- (int) indexOfItemWithTitle: (NSString*)aTitle
{
  id anItem;

  if ((anItem = [self itemWithTitle: aTitle]))
    return [_items indexOfObjectIdenticalTo: anItem];
  else
    return -1;
}

- (int) indexOfItemWithTag: (int)aTag
{
  id anItem;

  if ((anItem = [self itemWithTag: aTag]))
    return [_items indexOfObjectIdenticalTo: anItem];
  else
    return -1;
}

- (int) indexOfItemWithTarget: (id)anObject
		    andAction: (SEL)actionSelector
{
  unsigned i;
  unsigned count = [_items count];

  for (i = 0; i < count; i++)
    {
      NSMenuItem *menuItem = [_items objectAtIndex: i];

      if (actionSelector == 0 || sel_eq([menuItem action], actionSelector))
	{
	  if ([[menuItem target] isEqual: anObject])
	    {
	      return i;
	    }
	}
    }

  return -1;
}

- (int) indexOfItemWithRepresentedObject: (id)anObject
{
  int i, count = [_items count];

  for (i = 0; i < count; i++)
    {
      if ([[[_items objectAtIndex: i] representedObject]
	isEqual: anObject])
	{
	  return i;
	}
    }

  return -1;
}

- (int) indexOfItemWithSubmenu: (NSMenu *)anObject
{
  int i, count = [_items count];

  for (i = 0; i < count; i++)
    {
      id item = [_items objectAtIndex: i];

      if ([item hasSubmenu] && 
	  [[item submenu] isEqual: anObject])
	{
	  return i;
	}
    }
  
  return -1;
}

//
// Managing Submenus.
//
- (void) setSubmenu: (NSMenu *)aMenu
	    forItem: (id <NSMenuItem>)anItem 
{
  [anItem setSubmenu: aMenu];
}

- (void) submenuAction: (id)sender
{
  [_view detachSubmenu];
}

- (NSMenu *) attachedMenu
{
  if (_attachedMenu && _follow_transient
      && !_attachedMenu->_follow_transient)
    return nil;

  return _attachedMenu;
}

- (BOOL) isAttached
{
  return _superMenu && [_superMenu attachedMenu] == self;
}

- (BOOL) isTornOff
{
  return _is_tornoff;
}

- (NSPoint) locationForSubmenu: (NSMenu*)aSubmenu
{
  return [_view locationForSubmenu: aSubmenu];
}

- (NSMenu *) supermenu
{
  return _superMenu;
}

- (void) setSupermenu: (NSMenu *)supermenu
{
  /* The supermenu retains us (indirectly).  Do not retain it.  */
  _superMenu = supermenu;
}

//
// Enabling and Disabling Menu Items
//
- (void) setAutoenablesItems: (BOOL)flag
{
  _autoenable = flag;
}

- (BOOL) autoenablesItems
{
  return _autoenable;
}

- (void) update
{
  // We use this as a recursion check.
  if (!_changedMessagesEnabled)
    return;

  if ([self autoenablesItems])
    {
      unsigned i, count;

      count = [_items count];  
      
      // Temporary disable automatic displaying of menu.
      [self setMenuChangedMessagesEnabled: NO];
      
      for (i = 0; i < count; i++)
	{
	  NSMenuItem *item = [_items objectAtIndex: i];
	  SEL	      action = [item action];
	  id	      target;
	  id	      validator = nil;
	  BOOL	      wasEnabled = [item isEnabled];
	  BOOL	      shouldBeEnabled;

	  // Update the submenu items if any.
	  if ([item hasSubmenu])
	    [[item submenu] update];

	  // If there is no action - there can be no validator for the item.
	  if (action)
	    {
	      // If there is a target use that for validation (or nil).
	      if (nil != (target = [item target]))
		{
		  if ([target respondsToSelector: action])
		    {  
		      validator = target;
		    }
		}
	      else
		{
		  validator = [NSApp targetForAction: action];
		}
	    }
	  else if (_popUpButtonCell != nil)
	    {
	      if (NULL != (action = [_popUpButtonCell action]))
	        {
		  // If there is a target use that for validation (or nil).
		  if (nil != (target = [_popUpButtonCell target]))
		    {
		      if ([target respondsToSelector: action])
		        {  
			  validator = target;
			}
		    }
		  else
		    {
		      validator = [NSApp targetForAction: action];
		    }
		}
	    }

	  if (validator == nil)
	    {
	      shouldBeEnabled = NO;
	    }
	  else if ([validator
		     respondsToSelector: @selector(validateMenuItem:)])
	    {
	      shouldBeEnabled = [validator validateMenuItem: item];
	    }
	  else
	    {
	      shouldBeEnabled = YES;
	    }

	  if (shouldBeEnabled != wasEnabled)
	    {
	      [item setEnabled: shouldBeEnabled];
	    }
	}
          
      // Reenable displaying of menus
      [self setMenuChangedMessagesEnabled: YES];
    }

  if (_changed)
    [self sizeToFit];

  return;
}

//
// Handling Keyboard Equivalents
//
- (BOOL) performKeyEquivalent: (NSEvent*)theEvent
{
  unsigned      i;
  unsigned      count = [_items count];
  NSEventType   type = [theEvent type];
         
  if (type != NSKeyDown && type != NSKeyUp) 
    return NO;
             
  for (i = 0; i < count; i++)
    {
      NSMenuItem *item = [_items objectAtIndex: i];
                                    
      if ([item hasSubmenu])
        {
	  // FIXME: Should we only check active submenus?
	  // Recurse through submenus.
          if ([[item submenu] performKeyEquivalent: theEvent])
            {
              // The event has been handled by an item in the submenu.
              return YES;
            }
        }
      else
        {
	  // FIXME: Should also check the modifier mask  
          if ([[item keyEquivalent] isEqualToString: 
				      [theEvent charactersIgnoringModifiers]])
	    {
	      [_view performActionWithHighlightingForItemAtIndex: i];
	      return YES;
	    }
	}
    }
  return NO; 
}

//
// Simulating Mouse Clicks
//
- (void)  performActionForItemAtIndex: (int)index
{
  id<NSMenuItem> item = [_items objectAtIndex: index];
  NSDictionary *d;
  SEL action;

  if (![item isEnabled])
    return;

  // Send the actual action and the estipulated notifications.
  d = [NSDictionary dictionaryWithObject: item forKey: @"MenuItem"];
  [nc postNotificationName: NSMenuWillSendActionNotification
                    object: self
                  userInfo: d];
  if (NULL != (action = [item action]))
    {
      [NSApp sendAction: action
	     to: [item target]
	     from: item];
    }
  else if (_popUpButtonCell != nil)
    {
      // Tell the popup button, which item was selected
      [_popUpButtonCell selectItemAtIndex: index];
      if (NULL != (action = [_popUpButtonCell action]))
	[NSApp sendAction: action
	       to: [_popUpButtonCell target]
	       from: [_popUpButtonCell controlView]];
    }

  [nc postNotificationName: NSMenuDidSendActionNotification
                    object: self
                  userInfo: d];
}

//
// Setting the Title
//
- (void) setTitle: (NSString*)aTitle
{
  ASSIGN(_title, aTitle);
  [self sizeToFit];
}
  
- (NSString*) title
{
  return _title;
}

//
// Setting the Representing Object
//
- (void) setMenuRepresentation: (id)menuRep
{
  NSView *contentView;

  if (![menuRep isKindOfClass: [NSMenuView class]])
    {
      NSLog(@"You must use an NSMenuView, or a derivative thereof.\n");
      return;
    }

  // remove the old representation
  contentView = [_aWindow contentView];
  [contentView removeSubview: _view];

  ASSIGN(_view, menuRep);
  [_view setMenu: self];

  // add the new representation
  [contentView addSubview: _view];
}

- (id) menuRepresentation
{
  return _view;
}

//
// Updating the Menu Layout
//
- (void) setMenuChangedMessagesEnabled: (BOOL)flag
{ 
  if (_changedMessagesEnabled != flag)
    {
      if (flag)
	{
	  if ([_notifications count])
	    {
	      NSEnumerator *enumerator = [_notifications objectEnumerator];
	      id            aNotification;

	      while ((aNotification = [enumerator nextObject]))
		[nc postNotification: aNotification];
	    }

	  // Clean the notification array.
	  [_notifications removeAllObjects];
	}

      _changedMessagesEnabled = flag;
    }
}
 
- (BOOL) menuChangedMessagesEnabled
{
  return _changedMessagesEnabled;
}

- (void) sizeToFit
{
  NSRect windowFrame;
  NSRect menuFrame;
  NSSize size;

  //if ([_view needsSizing])
    [_view sizeToFit];

  menuFrame = [_view frame];
  size = menuFrame.size;

  windowFrame = [_aWindow frame];

  if (_popUpButtonCell == nil)
    {
      float height = [[_view class] menuBarHeight];

      size.height += height;
      [_aWindow setContentSize: size];
      [_aWindow setFrameTopLeftPoint:
	NSMakePoint(NSMinX(windowFrame),NSMaxY(windowFrame))];

      windowFrame = [_bWindow frame];
      [_bWindow setContentSize: size];
      [_bWindow setFrameTopLeftPoint:
	NSMakePoint(NSMinX(windowFrame),NSMaxY(windowFrame))];

      [_view setFrameOrigin: NSMakePoint (0, 0)];
      [_titleView setFrame: NSMakeRect (0, size.height - height, 
				       size.width, height)];
      [_titleView setNeedsDisplay: YES];
    }
  else
    {
      [_aWindow setContentSize: size];
      [_aWindow setFrameTopLeftPoint:
	NSMakePoint(NSMinX(windowFrame),NSMaxY(windowFrame))];
    }

  [_view setNeedsDisplay: YES];

  _changed = NO;
}

/*
 * Displaying Context Sensitive Help
 */
- (void) helpRequested: (NSEvent *)event
{
  // TODO: Won't be implemented until we have NSHelp*
}

+ (void) popUpContextMenu: (NSMenu*)menu
		withEvent: (NSEvent*)event
		  forView: (NSView*)view
{
  // TODO
}

/*
 * NSObject Protocol
 */
- (BOOL) isEqual: (id)anObject
{
  if (self == anObject)
    return YES;
  if ([anObject isKindOfClass: [NSMenu class]])
    {
      if (![_title isEqualToString: [anObject title]])
	return NO;
      return [[self itemArray] isEqual: [anObject itemArray]];
    }
  return NO;
}

/*
 * NSCoding Protocol
 */
- (void) encodeWithCoder: (NSCoder*)encoder
{
  [encoder encodeObject: _title];
  [encoder encodeObject: _items];
  [encoder encodeValueOfObjCType: @encode(BOOL) at: &_autoenable];
}

- (id) initWithCoder: (NSCoder*)decoder
{
  NSString	*dTitle;
  NSArray	*dItems;
  BOOL		dAuto;
  unsigned	i;

  dTitle = [decoder decodeObject];
  dItems = [decoder decodeObject];
  [decoder decodeValueOfObjCType: @encode(BOOL) at: &dAuto];

  self = [self initWithTitle: dTitle];
  [self setAutoenablesItems: dAuto];

  [self setMenuChangedMessagesEnabled: NO];
  /*
   * Make sure that items and submenus are set correctly.
   */
  for (i = 0; i < [dItems count]; i++)
    {
      NSMenuItem	*item = [dItems objectAtIndex: i];
      NSMenu		*sub = [item submenu];

      [self addItem: item];
      // FIXME: We propably don't need this, as all the fields are
      // already set up for the submenu item.
      if (sub != nil)
	{
	  [sub setSupermenu: nil];
	  [self setSubmenu: sub  forItem: item];
	}
    }
  [self setMenuChangedMessagesEnabled: YES];

  return self;
}

/*
 * NSCopying Protocol
 */
- (id) copyWithZone: (NSZone*)zone
{
  NSMenu *new = [[NSMenu allocWithZone: zone] initWithTitle: _title];
  unsigned i;
  unsigned count = [_items count];

  [new setAutoenablesItems: _autoenable];
  for (i = 0; i < count; i++)
    {
      // This works because the copy on NSMenuItem sets the menu to nil!!!
      [new insertItem: [[_items objectAtIndex: i] copyWithZone: zone]
	   atIndex: i];
    }
  
  return new;
}

@end

@implementation NSMenu (GNUstepExtra)

#define IS_OFFSCREEN(WINDOW) \
  !(NSContainsRect([[NSScreen mainScreen] frame], [WINDOW frame]))

- (void) _setTornOff: (BOOL)flag
{
  NSMenu	*supermenu;

  _is_tornoff = flag;

  if (flag)
    [_titleView addCloseButton];
  else
    [_titleView releaseCloseButton];

  supermenu = [self supermenu];
  if (supermenu != nil)
    {
      [[supermenu menuRepresentation] setHighlightedItemIndex: -1];
      supermenu->_attachedMenu = nil;
    }
}

- (void) _showTornOffMenuIfAny: (NSNotification*)notification
{
  if ([NSApp mainMenu] != self)
    {
      NSString		*key;

      key = [self _locationKey];
      if (key != nil)
	{
	  NSString		*location;
	  NSUserDefaults	*defaults;
	  NSDictionary		*menuLocations;

	  defaults  = [NSUserDefaults standardUserDefaults];
	  menuLocations = [defaults objectForKey: NSMenuLocationsKey];
      
	  location = [menuLocations objectForKey: key];
	  if (location && [location isKindOfClass: [NSString class]])
	    {
	      [self _setTornOff: YES];
	      [self display];
	    }
	}
    }
}

- (BOOL) isFollowTransient
{
  return _follow_transient;
} 

- (BOOL) isPartlyOffScreen
{
  return _isPartlyOffScreen;
}

- (void) nestedCheckOffScreen
{
  // This method is used when the menu is moved.
  if (_attachedMenu)
    [_attachedMenu nestedCheckOffScreen];

  _isPartlyOffScreen = IS_OFFSCREEN(_aWindow);
}

- (void) _performMenuClose: (id)sender
{
  NSString		*key;

  if (_attachedMenu)
    [_view detachSubmenu];

  key = [self _locationKey];
  if (key != nil)
    {
      NSUserDefaults		*defaults;
      NSMutableDictionary	*menuLocations;

      defaults = [NSUserDefaults standardUserDefaults];
      menuLocations = [[defaults objectForKey: NSMenuLocationsKey] mutableCopy];
      [menuLocations removeObjectForKey: key];
      if ([menuLocations count] > 0)
        [defaults setObject: menuLocations forKey: NSMenuLocationsKey];
      else
        [defaults removeObjectForKey: NSMenuLocationsKey];
      RELEASE(menuLocations);
      [defaults synchronize];
    }

  [_view setHighlightedItemIndex: -1];
  [self _setTornOff: NO];
  [self close];
} 

- (void) _rightMouseDisplay: (NSEvent*)theEvent
{
  [self displayTransient];
  [_view mouseDown: theEvent];
  [self closeTransient];
}

- (void) display
{
  NSString *key;

  if (_changed)
    [self sizeToFit];

  if (_superMenu && ![self isTornOff])
    {                 
      // query super menu for position
      [_aWindow setFrameOrigin: [_superMenu locationForSubmenu: self]];
      _superMenu->_attachedMenu = self;
    }
  else if (nil != (key = [self _locationKey]))
    {
      NSUserDefaults *defaults;
      NSDictionary *menuLocations;
      NSString *location;

      defaults = [NSUserDefaults standardUserDefaults];
      menuLocations = [defaults objectForKey: NSMenuLocationsKey];
      location = [menuLocations objectForKey: key];
      if (location && [location isKindOfClass: [NSString class]])
        {
	  [_aWindow setFrameFromString: location];
	  /*
	   * May need resize in case saved frame is out of sync
	   * with number of items in menu.
	   */
	  [self sizeToFit];
	}
      else
        {
	  NSPoint aPoint = {0, [[NSScreen mainScreen] frame].size.height
			    - [_aWindow frame].size.height};
	  
	  [_aWindow setFrameOrigin: aPoint];
	  [_bWindow setFrameOrigin: aPoint];
	}
    }

  [_aWindow orderFrontRegardless];

  _isPartlyOffScreen = IS_OFFSCREEN(_aWindow);

  /*
   * If we have just been made visible, we must make sure that any attached
   * submenu is visible too.
   */
  [[self attachedMenu] display];
}

- (void) displayTransient
{
  NSPoint location;
  NSView *contentView;

  _follow_transient = YES;

  /*
   * Cache the old submenu if any and query the supermenu our position.
   * Otherwise, raise menu under the mouse.
   */
  if (_superMenu != nil)
    {
      _oldAttachedMenu = _superMenu->_attachedMenu;
      _superMenu->_attachedMenu = self;
      location = [_superMenu locationForSubmenu: self];
    }
  else
    {
      NSRect	frame = [_aWindow frame];

      location = [_aWindow mouseLocationOutsideOfEventStream];
      location = [_aWindow convertBaseToScreen: location];
      location.x -= frame.size.width/2;
      if (location.x < 0)
	location.x = 0;
      location.y -= frame.size.height - 10;
    }

  [_bWindow setFrameOrigin: location];

  [_view removeFromSuperviewWithoutNeedingDisplay];
  [_titleView removeFromSuperviewWithoutNeedingDisplay];

  if (_is_tornoff)
    [_titleView releaseCloseButton];

  contentView = [_bWindow contentView];
  [contentView addSubview: _view];
  [contentView addSubview: _titleView];

  [_bWindow orderFront: self];

  _isPartlyOffScreen = IS_OFFSCREEN(_bWindow);
}

- (void) close
{
  NSMenu *sub = [self attachedMenu];

  /*
   * If we have an attached submenu, we must close that too - but then make
   * sure we still have a record of it so that it can be re-displayed if we
   * are redisplayed.
   */
  if (sub != nil)
    {
      [sub close];
      _attachedMenu = sub;
    }
  [_aWindow orderOut: self];

  if (_superMenu)
    _superMenu->_attachedMenu = nil;
}

- (void) closeTransient
{
  NSView *contentView;
  
  [_bWindow orderOut: self];
  [_view removeFromSuperviewWithoutNeedingDisplay];
  [_titleView removeFromSuperviewWithoutNeedingDisplay];

  contentView = [_aWindow contentView];
  [contentView addSubview: _view];

  if (_is_tornoff)
    [_titleView addCloseButton];

  [contentView addSubview: _titleView];
  [contentView setNeedsDisplay: YES];

  // Restore the old submenu (if any).
  if (_superMenu != nil)
    _superMenu->_attachedMenu = _oldAttachedMenu;

  _follow_transient = NO;

  _isPartlyOffScreen = IS_OFFSCREEN(_aWindow);
}

- (NSWindow*) window
{
  if (_follow_transient)
    return (NSWindow *)_bWindow;
  else
    return (NSWindow *)_aWindow;
}

/**
   Set the frame origin of the receiver to aPoint. If a submenu of
   the receiver is attached. The frame origin of the submenu is set
   appropriately.
*/
- (void) nestedSetFrameOrigin: (NSPoint) aPoint
{
  NSWindow *theWindow = _follow_transient ? _bWindow : _aWindow;

  // Move ourself and get our width.
  [theWindow setFrameOrigin: aPoint];

  // Do the same for attached menus.
  if (_attachedMenu)
    {
      aPoint = [self locationForSubmenu: _attachedMenu];
      [_attachedMenu nestedSetFrameOrigin: aPoint];
    }
}

#define SHIFT_DELTA 18.0

- (void) shiftOnScreen
{
  NSWindow *theWindow = _follow_transient ? _bWindow : _aWindow;
  NSRect    frameRect = [theWindow frame];
  NSPoint   vector    = {0.0, 0.0};
  BOOL      moveIt    = YES;

  if (frameRect.origin.y < 0)
    {
      if (frameRect.origin.y + SHIFT_DELTA <= 0)
	vector.y = SHIFT_DELTA;
      else
	vector.y = -frameRect.origin.y;
    }
  else if (frameRect.origin.x < 0)
    {
      if (frameRect.origin.x + SHIFT_DELTA <= 0)
	vector.x = SHIFT_DELTA;
      else
	vector.x = -frameRect.origin.x;
    }
  else
    {
      vector.x  = frameRect.origin.x + frameRect.size.width;
      vector.x -= [[NSScreen mainScreen] frame].size.width;

      if (vector.x > 0)
	{
	  if (vector.x - SHIFT_DELTA <= 0)
	    vector.x = -SHIFT_DELTA;
	  else
	    vector.x = -vector.x - 2;
	}
      else
	moveIt = NO;
    }

  if (moveIt)
    {
        NSMenu  *candidateMenu;
	NSMenu  *masterMenu;
	NSPoint  masterLocation;
	NSPoint  destinationPoint;

	// Look for the "master" menu, i.e. the one to move from.
	for (candidateMenu = masterMenu = self;
	     (candidateMenu = masterMenu->_superMenu)
	       && (!masterMenu->_is_tornoff
		   || masterMenu->_follow_transient);
	     masterMenu = candidateMenu);

	masterLocation = [[masterMenu window] frame].origin;
	destinationPoint.x = masterLocation.x + vector.x;
	destinationPoint.y = masterLocation.y + vector.y;

	[masterMenu nestedSetFrameOrigin: destinationPoint];
    }
  else
    _isPartlyOffScreen = NO;
}

- (BOOL)_ownedByPopUp
{
  return _popUpButtonCell != nil;
}

- (void)_setOwnedByPopUp: (NSPopUpButtonCell*)popUp
{
  if (_popUpButtonCell != popUp)
    {
      _popUpButtonCell = popUp;
      if (popUp != nil)
	{
	  [_titleView removeFromSuperviewWithoutNeedingDisplay];
	  [_aWindow setLevel: NSPopUpMenuWindowLevel];
	  [_bWindow setLevel: NSPopUpMenuWindowLevel];
	}
      // FIXME
    }
}

@end


@implementation NSMenuWindowTitleView

- (BOOL) acceptsFirstMouse: (NSEvent *)theEvent
{
  return YES;
} 
 
- (void) setMenu: (NSMenu*)aMenu
{
  menu = aMenu;
}

- (NSMenu*) menu
{
  return menu;
}
  
- (void) drawRect: (NSRect)rect
{
  NSRect workRect = [self bounds];
  NSRectEdge sides[] = {NSMinXEdge, NSMaxYEdge};
  float grays[] = {NSDarkGray, NSDarkGray};
  /* Cache the title attributes */
  static NSDictionary *attr = nil;

  // Draw the dark gray upper left lines.
  workRect = NSDrawTiledRects(workRect, workRect, sides, grays, 2);
  
  // Draw the title box's button.
  NSDrawButton(workRect, workRect);
  
  // Paint it Black!
  workRect.origin.x += 1;
  workRect.origin.y += 2;
  workRect.size.height -= 3;
  workRect.size.width -= 3;
  [[NSColor windowFrameColor] set];
  NSRectFill(workRect);

  // Draw the title
  if (attr == nil)
    {
      attr = [[NSDictionary alloc] 
	       initWithObjectsAndKeys: 
		 [NSFont boldSystemFontOfSize: 0], NSFontAttributeName,
	       [NSColor windowFrameTextColor], NSForegroundColorAttributeName,
	       nil];
    }

  // This gives the correct position
  workRect.origin.x += 5;
  workRect.size.width -= 5;
  workRect.size.height -= 2;
  [[menu title] drawInRect: workRect  withAttributes: attr];
}

- (void) mouseDown: (NSEvent*)theEvent
{
  NSString		*key;
  NSPoint		lastLocation;
  NSPoint		location;
  unsigned		eventMask = NSLeftMouseUpMask | NSLeftMouseDraggedMask;
  BOOL			done = NO;
  NSDate		*theDistantFuture = [NSDate distantFuture];

  lastLocation = [theEvent locationInWindow];
   
  if (![menu isTornOff] && [menu supermenu])
    {
      [menu _setTornOff: YES];
    }
 
  while (!done)
    {
      theEvent = [NSApp nextEventMatchingMask: eventMask
                                     untilDate: theDistantFuture
                                        inMode: NSEventTrackingRunLoopMode
                                       dequeue: YES];
  
      switch ([theEvent type])
        {
	case NSLeftMouseUp: 
	  done = YES; 
	  break;
	case NSLeftMouseDragged:   
	  location = [_window mouseLocationOutsideOfEventStream];
	  if (NSEqualPoints(location, lastLocation) == NO)
	    {
	      NSPoint origin = [_window frame].origin;

	      origin.x += (location.x - lastLocation.x);
	      origin.y += (location.y - lastLocation.y);
	      [menu nestedSetFrameOrigin: origin];
	      [menu nestedCheckOffScreen];
	    }
	  break;
         
	default: 
	  break;
        }
    }

  /*
   * Same current menu frame in defaults database.
   */
  key = [menu _locationKey];
  if (key != nil)
    {
      NSUserDefaults		*defaults;
      NSMutableDictionary	*menuLocations;
      NSString			*locString;

      defaults = [NSUserDefaults standardUserDefaults];
      menuLocations = [[defaults objectForKey: NSMenuLocationsKey] mutableCopy];
      if (menuLocations == nil)
	{
	  menuLocations = AUTORELEASE([[NSMutableDictionary alloc] initWithCapacity: 2]);
	}
      locString = [[menu window] stringWithSavedFrame];
      [menuLocations setObject: locString forKey: key];
      [defaults setObject: menuLocations forKey: NSMenuLocationsKey];
      [defaults synchronize];
    }
}

- (void) createButton
{
  // create the menu's close button
  NSImage* closeImage = [NSImage imageNamed: @"common_Close"];
  NSImage* closeHImage = [NSImage imageNamed: @"common_CloseH"];
  NSSize imageSize = [closeImage size];
  NSRect rect = { { _frame.size.width - imageSize.width - 4,
		    (_frame.size.height - imageSize.height) / 2},
		  { imageSize.height, imageSize.width } };

  button = [[NSButton alloc] initWithFrame: rect];
  [button setButtonType: NSMomentaryLight];
  [button setImagePosition: NSImageOnly];
  [button setImage: closeImage];
  [button setAlternateImage: closeHImage];
  [button setBordered: NO];
  [button setTarget: menu];
  [button setAction: @selector(_performMenuClose:)];
  [button setAutoresizingMask: NSViewMinXMargin];
  
  [self setAutoresizingMask: NSViewMinXMargin | NSViewMinYMargin | NSViewMaxYMargin];
}
            
- (void) releaseCloseButton
{
  [button removeFromSuperview];
}
  
- (void) addCloseButton
{
  if (button == nil)
    [self createButton];
  [self addSubview: button];
  [self setNeedsDisplay: YES];
}

- (void) rightMouseDown: (NSEvent*)theEvent
{
  // Dont show our menu
}

@end /* NSMenuWindowTitleView */