1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
|
/*
* tkMacOSXMenu.c --
*
* This module implements the Mac-platform specific features of menus.
*
* Copyright © 1996-1997 Sun Microsystems, Inc.
* Copyright © 2001-2009 Apple Inc.
* Copyright © 2005-2009 Daniel A. Steffen <das@users.sourceforge.net>
* Copyright © 2012 Adrian Robert.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include "tkMacOSXPrivate.h"
#include "tkMenubutton.h"
#include "tkMenu.h"
#include "tkColor.h"
#include "tkFont.h"
#include "tkMacOSXWm.h"
#include "tkMacOSXDebug.h"
#include "tkMacOSXConstants.h"
/*
#ifdef TK_MAC_DEBUG
#define TK_MAC_DEBUG_MENUS
#endif
*/
#define ENTRY_HELP_MENU ENTRY_PLATFORM_FLAG1
#define ENTRY_APPLE_MENU ENTRY_PLATFORM_FLAG2
#define ENTRY_WINDOWS_MENU ENTRY_PLATFORM_FLAG3
#define sl(s) ((int) (sizeof(s "") - 1))
#define SPECIALMENU(n, f) {.name = "." #n, .len = sl(#n) + 1, \
.flag = ENTRY_##f##_MENU }
static const struct {
const char *name; size_t len; int flag;
} specialMenus[] = {
SPECIALMENU(help, HELP),
SPECIALMENU(apple, APPLE),
SPECIALMENU(window, WINDOWS),
{NULL, 0, 0}
};
#undef SPECIALMENU
#define MODIFIER(n, f) {.name = #n, .len = sl(#n), .mask = f }
static const struct {
const char *name; size_t len; NSUInteger mask;
} allModifiers[] = {
MODIFIER(Control, NSControlKeyMask),
MODIFIER(Ctrl, NSControlKeyMask),
MODIFIER(Option, NSAlternateKeyMask),
MODIFIER(Opt, NSAlternateKeyMask),
MODIFIER(Alt, NSAlternateKeyMask),
MODIFIER(Shift, NSShiftKeyMask),
MODIFIER(Command, NSCommandKeyMask),
MODIFIER(Cmd, NSCommandKeyMask),
MODIFIER(Meta, NSCommandKeyMask),
{NULL, 0, 0}
};
#undef MODIFIER
#define ACCEL(n, c) {.name = #n, .len = sl(#n), .ch = c }
static const struct {
const char *name; size_t len; UniChar ch;
} specialAccelerators[] = {
ACCEL(PageUp, NSPageUpFunctionKey),
ACCEL(PageDown, NSPageDownFunctionKey),
ACCEL(Left, NSLeftArrowFunctionKey),
ACCEL(Right, NSRightArrowFunctionKey),
ACCEL(Up, NSUpArrowFunctionKey),
ACCEL(Down, NSDownArrowFunctionKey),
ACCEL(Escape, 0x001b),
ACCEL(Clear, NSClearDisplayFunctionKey),
ACCEL(Enter, NSEnterCharacter),
ACCEL(Backspace, NSBackspaceCharacter),
ACCEL(Space, ' '),
ACCEL(Tab, NSTabCharacter),
ACCEL(BackTab, NSBackTabCharacter),
ACCEL(Delete, NSDeleteCharacter),
ACCEL(Home, NSHomeFunctionKey),
ACCEL(End, NSEndFunctionKey),
ACCEL(Return, NSCarriageReturnCharacter),
ACCEL(Help, NSHelpFunctionKey),
ACCEL(Power, 0x233d),
ACCEL(Eject, 0xf804),
{NULL, 0, 0}
};
#undef ACCEL
#undef sl
static int inPostMenu = 0;
static SInt32 menuMarkColumnWidth = 0, menuIconTrailingEdgeMargin = 0;
static SInt32 menuTextLeadingEdgeMargin = 0, menuTextTrailingEdgeMargin = 0;
static SInt16 menuItemExtraHeight = 0, menuItemExtraWidth = 0;
static SInt16 menuSeparatorHeight = 0;
static void CheckForSpecialMenu(TkMenu *menuPtr);
static NSString *ParseAccelerator(const char *accel, NSUInteger *maskPtr);
static int GenerateMenuSelectEvent(TKMenu *menu, NSMenuItem *menuItem);
static void MenuSelectEvent(TkMenu *menuPtr);
static void RecursivelyClearActiveMenu(TkMenu *menuPtr);
static int ModifierCharWidth(Tk_Font tkfont);
#pragma mark TkBackgroundLoop
/*
* The function TkMacOSXEventsCheckProc (in tkMacOSXNotify.c) is the "check
* proc" for the macOS event source. Its job is to remove NSEvents from the
* default event queue of the NSApplication. It does this by calling the
* method [NSApp nextEventMatchingMask: untilDate: inMode: dequeue:]. As a
* rule, when the untilDate is set to the distant past this method returns
* immediately. An exception to that rule is when the next event is the button
* press on a menu button. In that case, the method starts running a nested
* event loop in the mode NSEventTrackingRunLoopMode which does not return
* until the menu has been dismissed. In Tk 8.6.10 and earlier, this meant
* that the Tk event loop would block in its call to the check proc as long as
* the menu was posted. For example, opening a menu during the Rube Goldberg
* demo would cause the animation to stop. This was also the case for
* menubuttons.
*
* The TKBackground object below works around this problem, and allows a Tk
* event loop to run while a menu is open. It is a subclass of NSThread which
* inserts requests to call [NSApp _runBackgroundLoop] onto the queue
* associated with the NSEventTrackingRunLoopMode. One of these threads gets
* started in the callback [NSApp menuBeginTracking] and cancelled in [NSApp
* menuEndTracking].
*/
@interface TKBackgroundLoop: NSThread
@end
@implementation TKBackgroundLoop
- (void) main
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSArray *modeArray = [NSArray arrayWithObjects: NSEventTrackingRunLoopMode,
nil];
while(1) {
/*
* Queue a request to process Tk events during event tracking.
*/
[NSApp performSelectorOnMainThread:@selector(_runBackgroundLoop)
withObject:nil
waitUntilDone:true
modes:modeArray];
if ([self isCancelled]) {
[NSThread exit];
}
/*
* Allow the tracked events to be processed too.
*/
[NSThread sleepForTimeInterval:0.001];
}
[pool drain];
}
@end
TKBackgroundLoop *backgroundLoop = nil;
#pragma mark TKMenu
/*
* This interface is not declared in tkMacOSXPrivate.h because it requires
* tkMenu.h.
*/
@interface TKMenu(TKMenuPrivate)
- (id) initWithTkMenu: (TkMenu *) tkMenu;
- (TkMenu *) tkMenu;
- (int) tkIndexOfItem: (NSMenuItem *) menuItem;
- (void) insertItem: (NSMenuItem *) newItem atTkIndex: (NSInteger) index;
@end
@implementation TKMenu
- (void) setSpecial: (NSUInteger) special
{
NSAssert(!_tkSpecial, @"Cannot change specialness of a special menu");
_tkSpecial = special;
}
- (BOOL) isSpecial: (NSUInteger) special
{
return (_tkSpecial == special);
}
/*
* There are cases where a KeyEquivalent (aka menu accelerator) is defined for
* a "dead key", i.e. a key which does not have an associated character but is
* only meant to be the start of a composition sequence. For example, on a
* Spanish keyboard both the ' and the ` keys are dead keys used to place
* accents over letters. But ⌘` is a standard KeyEquivalent which cycles
* through the open windows of an application, changing the focus to the next
* window.
*
* The performKeyEquivalent callback method is being overridden here to work
* around a bug reported in [1626ed65b8]. When a dead key that is also as a
* KeyEquivalent is pressed, a KeyDown event with no characters is passed to
* performKeyEquivalent. The default implementation provided by Apple will
* cause that event to be routed to some private methods of NSMenu which raise
* NSInvalidArgumentException, causing an abort. Returning NO in such a case
* prevents the abort, but does not prevent the KeyEquivalent action from being
* invoked, presumably because the event does get correctly handled higher in
* the responder chain.
*/
- (BOOL)performKeyEquivalent:(NSEvent *)event
{
if (event.characters.length == 0) {
return NO;
}
return [super performKeyEquivalent:event];
}
@end
@implementation TKMenu(TKMenuPrivate)
- (id) initWithTitle: (NSString *) aTitle
{
self = [super initWithTitle:aTitle];
if (self) {
_tkMenu = NULL;
_tkOffset = 0;
_tkItemCount = 0;
_tkSpecial = 0;
[self setDelegate:self];
}
return self;
}
- (id) initWithTkMenu: (TkMenu *) tkMenu
{
NSString *title = [[NSString alloc] initWithUTF8String:
Tk_PathName(tkMenu->tkwin)];
self = [self initWithTitle:title];
[title release];
if (self) {
_tkMenu = tkMenu;
}
return self;
}
- (id) copyWithZone: (NSZone *) zone
{
TKMenu *copy = [super copyWithZone:zone];
NSAssert(_tkMenu == nil, @"Cannot copy tkMenu");
copy->_tkMenu = _tkMenu;
copy->_tkOffset = _tkOffset;
copy->_tkItemCount = _tkItemCount;
copy->_tkSpecial = _tkSpecial;
return copy;
}
- (TkMenu *) tkMenu
{
return (TkMenu *)_tkMenu;
}
- (int) tkIndexOfItem: (NSMenuItem *) menuItem
{
return [self indexOfItem:menuItem] - _tkOffset;
}
- (void) insertItem: (NSMenuItem *) newItem atTkIndex: (NSInteger) index
{
[super insertItem:newItem atIndex:index + _tkOffset];
_tkItemCount++;
}
- (void) insertItem: (NSMenuItem *) newItem atIndex: (NSInteger) index
{
if (_tkMenu && index >= 0) {
if ((NSUInteger) index <= _tkOffset) {
_tkOffset++;
} else {
NSAssert((NSUInteger) index >= _tkItemCount + _tkOffset,
@"Cannot insert in the middle of Tk menu");
}
}
[super insertItem:newItem atIndex:index];
}
- (void) removeItemAtIndex: (NSInteger) index
{
if (_tkMenu && index >= 0) {
if ((NSUInteger) index < _tkOffset) {
_tkOffset--;
} else if ((NSUInteger) index < _tkItemCount + _tkOffset) {
_tkItemCount--;
}
}
[super removeItemAtIndex:index];
}
- (NSMenuItem *) newTkMenuItem: (TkMenuEntry *) mePtr
{
NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:@""
action:@selector(tkMenuItemInvoke:) keyEquivalent:@""];
[menuItem setTarget:self];
[menuItem setTag:(NSInteger) mePtr];
return menuItem;
}
@end
@implementation TKMenu(TKMenuActions)
- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
{
return [menuItem isEnabled];
}
/*
* Workaround for bug 3572016; leave menu items enabled during modal dialog.
*/
- (BOOL)worksWhenModal
{
return YES;
}
- (void) tkMenuItemInvoke: (id) sender
{
/*
* With the delegate matching key equivalents, when a menu action is sent
* in response to a key equivalent, the sender is the whole menu and not the
* specific menu item. We use this to ignore key equivalents for Tk
* menus (as Tk handles them directly via bindings).
*/
if ([sender isKindOfClass:[NSMenuItem class]]) {
NSMenuItem *menuItem = (NSMenuItem *) sender;
TkMenu *menuPtr = (TkMenu *) _tkMenu;
TkMenuEntry *mePtr = (TkMenuEntry *) [menuItem tag];
if (menuPtr && mePtr) {
Tcl_Interp *interp = menuPtr->interp;
Tcl_Preserve(interp);
Tcl_Preserve(menuPtr);
int result = TkInvokeMenu(interp, menuPtr, mePtr->index);
if (result != TCL_OK && result != TCL_CONTINUE &&
result != TCL_BREAK) {
Tcl_AddErrorInfo(interp, "\n (menu invoke)");
Tcl_BackgroundException(interp, result);
}
Tcl_Release(menuPtr);
Tcl_Release(interp);
}
}
}
@end
@implementation TKMenu(TKMenuDelegate)
- (BOOL) menuHasKeyEquivalent: (NSMenu *) menu forEvent: (NSEvent *) event
target: (id *) target action: (SEL *) action
{
(void)menu;
/*
* Use lowercaseString when comparing keyEquivalents since the notion of
* a shifted upper case letter does not make much sense.
*/
NSString *key = [[event charactersIgnoringModifiers] lowercaseString];
NSUInteger modifiers = [event modifierFlags] &
NSDeviceIndependentModifierFlagsMask;
if (modifiers == (NSCommandKeyMask | NSShiftKeyMask) &&
[key compare:@"?"] == NSOrderedSame) {
/*
* Command-Shift-? has not been allowed as a keyboard equivalent since
* the first aqua port, for some mysterious reason.
*/
return NO;
} else if (modifiers == (NSControlKeyMask | NSShiftKeyMask) &&
[event keyCode] == 48) {
/*
* Starting with OSX 10.12 Control-Tab and Control-Shift-Tab are used
* to select window tabs. But for some even more mysterious reason the
* Control-Shift-Tab event has character 0x19 = NSBackTabCharacter
* rather than 0x09 = NSTabCharacter. At the same time, the
* keyEquivalent must be \0x09 in order for it to be displayed
* correctly in the menu. This makes it impossible for the standard
* "Select Previous Tab" to work correctly, unless we intervene.
*/
key = @"\t";
} else if (([event modifierFlags] & NSCommandKeyMask) == NSCommandKeyMask) {
/*
* If the command modifier is set, use the full character string so
* things like the dvorak / qwerty layout will work.
*/
key = [event characters];
}
NSArray *itemArray = [self itemArray];
for (NSMenuItem *item in itemArray) {
if ([item isEnabled] &&
[[item keyEquivalent] compare:key] == NSOrderedSame) {
NSUInteger keyEquivModifiers = [item keyEquivalentModifierMask];
if (keyEquivModifiers == modifiers) {
*target = [item target];
*action = [item action];
return YES;
}
}
}
return NO;
}
- (void) menuWillOpen: (NSMenu *) menu
{
(void)menu;
if (_tkMenu) {
//RecursivelyClearActiveMenu(_tkMenu);
GenerateMenuSelectEvent((TKMenu *)[self supermenu],
[self itemInSupermenu]);
}
}
- (void) menuDidClose: (NSMenu *) menu
{
(void)menu;
if (_tkMenu) {
RecursivelyClearActiveMenu((TkMenu *)_tkMenu);
}
}
- (void) menu: (NSMenu *) menu willHighlightItem: (NSMenuItem *) item
{
(void)menu;
if (_tkMenu) {
GenerateMenuSelectEvent(self, item);
}
}
- (void) menuNeedsUpdate: (NSMenu *) menu
{
TkMenu *menuPtr = (TkMenu *) _tkMenu;
(void)menu;
if (menuPtr) {
Tcl_Interp *interp = menuPtr->interp;
Tcl_Preserve(interp);
Tcl_Preserve(menuPtr);
int result = TkPostCommand(menuPtr);
if (result!=TCL_OK && result!=TCL_CONTINUE && result!=TCL_BREAK) {
Tcl_AddErrorInfo(interp, "\n (menu preprocess)");
Tcl_BackgroundException(interp, result);
}
Tcl_Release(menuPtr);
Tcl_Release(interp);
}
}
@end
#pragma mark TKApplication(TKMenu)
@implementation TKApplication(TKMenu)
- (void) menuBeginTracking: (NSNotification *) notification
{
(void)notification;
#ifdef TK_MAC_DEBUG_NOTIFICATIONS
TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification);
#endif
if (backgroundLoop) {
[backgroundLoop cancel];
[backgroundLoop release];
}
backgroundLoop = [[TKBackgroundLoop alloc] init];
[backgroundLoop start];
//TkMacOSXClearMenubarActive();
//TkMacOSXPreprocessMenu();
}
- (void) menuEndTracking: (NSNotification *) notification
{
(void)notification;
#ifdef TK_MAC_DEBUG_NOTIFICATIONS
TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification);
#endif
if (backgroundLoop) {
[backgroundLoop cancel];
[backgroundLoop release];
backgroundLoop = nil;
}
if (!inPostMenu) {
TkMacOSXClearMenubarActive();
}
}
- (void) tkSetMainMenu: (TKMenu *) menu
{
TKMenu *applicationMenu = nil;
if (menu) {
NSMenuItem *applicationMenuItem = [menu numberOfItems] ?
[menu itemAtIndex:0] : nil;
if (![menu isSpecial:tkMainMenu]) {
TkMenuEntry *mePtr = (TkMenuEntry *)[applicationMenuItem tag];
if (!mePtr || !(mePtr->entryFlags & ENTRY_APPLE_MENU)) {
applicationMenuItem = [NSMenuItem itemWithSubmenu:
[_defaultApplicationMenu copy]];
[menu insertItem:applicationMenuItem atIndex:0];
}
[menu setSpecial:tkMainMenu];
}
applicationMenu = (TKMenu *)[applicationMenuItem submenu];
if (![applicationMenu isSpecial:tkApplicationMenu]) {
for (NSMenuItem *item in _defaultApplicationMenuItems) {
[applicationMenu addItem:[item copy]];
}
[applicationMenu setSpecial:tkApplicationMenu];
}
NSArray *itemArray = [menu itemArray];
for (NSMenuItem *item in itemArray) {
TkMenuEntry *mePtr = (TkMenuEntry *)[item tag];
TKMenu *submenu = (TKMenu *)[item submenu];
if (mePtr && submenu) {
if ((mePtr->entryFlags & ENTRY_WINDOWS_MENU) &&
![submenu isSpecial:tkWindowsMenu]) {
NSInteger index = 0;
for (NSMenuItem *i in _defaultWindowsMenuItems) {
[submenu insertItem:[i copy] atIndex:index++];
}
[self setWindowsMenu:submenu];
[submenu setSpecial:tkWindowsMenu];
} else if ((mePtr->entryFlags & ENTRY_HELP_MENU) &&
![submenu isSpecial:tkHelpMenu]) {
NSInteger index = 0;
for (NSMenuItem *i in _defaultHelpMenuItems) {
[submenu insertItem:[i copy] atIndex:index++];
}
[submenu setSpecial:tkHelpMenu];
}
}
}
} else {
menu = _defaultMainMenu;
applicationMenu = _defaultApplicationMenu;
}
NSMenuItem *servicesMenuItem =
[applicationMenu itemWithTitle:@"Services"];
if (servicesMenuItem && [servicesMenuItem submenu] != _servicesMenu) {
[[_servicesMenu itemInSupermenu] setSubmenu:nil];
[servicesMenuItem setSubmenu:_servicesMenu];
}
[self setAppleMenu:applicationMenu];
[self setMainMenu:menu];
}
@end
#pragma mark -
/*
*----------------------------------------------------------------------
*
* TkpNewMenu --
*
* Gets a new blank menu. Only the platform specific options are filled
* in.
*
* Results:
* Returns a standard Tcl error.
*
* Side effects:
* Allocates a NSMenu and puts it into the platformData field of the
* menuPtr.
*
*----------------------------------------------------------------------
*/
int
TkpNewMenu(
TkMenu *menuPtr) /* The common structure we are making the
* platform structure for. */
{
TKMenu *menu = [[TKMenu alloc] initWithTkMenu:menuPtr];
menuPtr->platformData = (TkMenuPlatformData) menu;
CheckForSpecialMenu(menuPtr);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TkpDestroyMenu --
*
* Destroys platform-specific menu structures.
*
* Results:
* None.
*
* Side effects:
* All platform-specific allocations are freed up.
*
*----------------------------------------------------------------------
*/
void
TkpDestroyMenu(
TkMenu *menuPtr) /* The common menu structure */
{
NSMenu* nsmenu = (NSMenu*)(menuPtr->platformData);
[nsmenu release];
menuPtr->platformData = NULL;
}
/*
*----------------------------------------------------------------------
*
* TkpMenuNewEntry --
*
* Adds a pointer to a new menu entry structure with the platform-
* specific fields filled in. The Macintosh uses the platformEntryData
* field of the TkMenuEntry record.
*
* Results:
* Standard TCL error.
*
* Side effects:
* Storage gets allocated. New menu entry data is put into the
* platformEntryData field of the mePtr.
*
*----------------------------------------------------------------------
*/
int
TkpMenuNewEntry(
TkMenuEntry *mePtr) /* The menu we are adding an entry to */
{
TKMenu *menu = (TKMenu *) mePtr->menuPtr->platformData;
NSMenuItem *menuItem;
if (mePtr->type == SEPARATOR_ENTRY || mePtr->type == TEAROFF_ENTRY) {
menuItem = [[NSMenuItem separatorItem] retain];
} else {
menuItem = [menu newTkMenuItem:mePtr];
}
mePtr->platformEntryData = (TkMenuPlatformEntryData) menuItem;
/*
* Caller TkMenuEntry() already did this same insertion into the generic
* TkMenu so we just match it for the platform menu.
*/
[menu insertItem:menuItem atTkIndex:mePtr->index];
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TkpConfigureMenuEntry --
*
* Processes configurations for menu entries.
*
* Results:
* Returns standard TCL result. If TCL_ERROR is returned, then the
* interp's result contains an error message.
*
* Side effects:
* Configuration information get set for mePtr; old resources get freed,
* if any need it.
*
*----------------------------------------------------------------------
*/
int
TkpConfigureMenuEntry(
TkMenuEntry *mePtr) /* Information about menu entry; may or may
* not already have values for some fields. */
{
NSMenuItem *menuItem = (NSMenuItem *) mePtr->platformEntryData;
NSString *title = @"";
NSAttributedString *attributedTitle = nil;
NSImage *image = nil;
NSString *keyEquivalent = @"";
NSUInteger modifierMask = NSCommandKeyMask;
NSMenu *submenu = nil;
int imageWidth, imageHeight;
GC gc = (mePtr->textGC ? mePtr->textGC : mePtr->menuPtr->textGC);
Tcl_Obj *fontPtr = (mePtr->fontPtr ?
mePtr->fontPtr : mePtr->menuPtr->fontPtr);
static int initialized = 0;
if (!initialized) {
TkColor *tkColPtr = TkpGetColor(NULL, DEF_MENU_BG_COLOR);
ckfree(tkColPtr);
tkColPtr = TkpGetColor(NULL, DEF_MENU_FG);
ckfree(tkColPtr);
}
if (mePtr->image) {
Tk_SizeOfImage(mePtr->image, &imageWidth, &imageHeight);
image = TkMacOSXGetNSImageFromTkImage(mePtr->menuPtr->display,
mePtr->image, imageWidth, imageHeight);
} else if (mePtr->bitmapPtr != NULL) {
Pixmap bitmap = Tk_GetBitmapFromObj(mePtr->menuPtr->tkwin,
mePtr->bitmapPtr);
Tk_SizeOfBitmap(mePtr->menuPtr->display, bitmap, &imageWidth,
&imageHeight);
image = TkMacOSXGetNSImageFromBitmap(mePtr->menuPtr->display, bitmap,
gc, imageWidth, imageHeight);
[image setTemplate:YES];
}
[menuItem setImage:image];
if ((!image || mePtr->compound != COMPOUND_NONE) && mePtr->labelPtr &&
mePtr->labelLength) {
title = [[[NSString alloc] initWithBytes:Tcl_GetString(mePtr->labelPtr)
length:mePtr->labelLength encoding:NSUTF8StringEncoding]
autorelease];
if ([title hasSuffix:@"..."]) {
title = [NSString stringWithFormat:@"%@%C",
[title substringToIndex:[title length] - 3], 0x2026];
}
}
[menuItem setTitle:title];
#if 0
/*
* The -background and -foreground options are now ignored in Aqua.
* See ticket [635167af14].
*/
NSDictionary fontAttributes = TkMacOSXNSFontAttributesForFont(
Tk_GetFontFromObj(mePtr->menuPtr->tkwin, fontPtr));
NSMutableDictionary *attributes = [fontAttributes mutableCopy];
static unsigned long defaultBg = 0, defaultFg = 0;
if (defaultBg == 0) {
tkColor *tkColPtr = TkpGetColor(NULL, DEF_MENU_BG_COLOR);
defaultBg = tkColPtr->color.pixel;
ckfree(tkColPtr);
}
if (defaultFg == 0) {
tkColor *tkColPtr = TkpGetColor(NULL, DEF_MENU_FG);
defaultFg = tkColPtr->color.pixel;
ckfree(tkColPtr);
}
if (gc->foreground != defaultFg) {
NSColor *fgcolor = TkMacOSXGetNSColor(gc, gc->foreground);
[attributes setObject:fgcolor
forKey:NSForegroundColorAttributeName];
}
if (gc->background != defaultBg) {
NSColor *bgcolor = TkMacOSXGetNSColor(gc, gc->background);
[attributes setObject:bgcolor
forKey:NSBackgroundColorAttributeName];
}
#else
NSDictionary *attributes = TkMacOSXNSFontAttributesForFont(
Tk_GetFontFromObj(mePtr->menuPtr->tkwin, fontPtr));
#endif
attributedTitle = [[NSAttributedString alloc] initWithString:title
attributes:attributes];
[menuItem setAttributedTitle:attributedTitle];
[menuItem setEnabled:(mePtr->state != ENTRY_DISABLED)];
[menuItem setState:((mePtr->type == CHECK_BUTTON_ENTRY ||
mePtr->type == RADIO_BUTTON_ENTRY) && mePtr->indicatorOn &&
(mePtr->entryFlags & ENTRY_SELECTED) ? NSOnState : NSOffState)];
if (mePtr->type != CASCADE_ENTRY && mePtr->accelPtr && mePtr->accelLength) {
keyEquivalent = ParseAccelerator(Tcl_GetString(mePtr->accelPtr),
&modifierMask);
}
[menuItem setKeyEquivalent:keyEquivalent];
[menuItem setKeyEquivalentModifierMask:modifierMask];
if (mePtr->type == CASCADE_ENTRY && mePtr->namePtr) {
TkMenuReferences *menuRefPtr;
menuRefPtr = TkFindMenuReferencesObj(mePtr->menuPtr->interp,
mePtr->namePtr);
if (menuRefPtr && menuRefPtr->menuPtr) {
CheckForSpecialMenu(menuRefPtr->menuPtr);
submenu = (TKMenu *) menuRefPtr->menuPtr->platformData;
if ([submenu supermenu] && [menuItem submenu] != submenu) {
/*
* This happens during a clone, where the parent menu is
* cloned before its children, so just ignore this temprary
* setting, it will be changed shortly (c.f. tkMenu.c
* CloneMenu())
*/
submenu = nil;
} else {
[submenu setTitle:title];
if ([menuItem isEnabled]) {
/*
* This menuItem might have been previously disabled which
* would have disabled all of its entries; we must re-enable the
* entries here. It is important to iterate though the Tk
* entries, not the NSMenuItems, since some NSMenuItems may
* have been added by the system. See [7185d26cf4].
*/
for (Tcl_Size i = 0; i < menuRefPtr->menuPtr->numEntries; i++) {
TkMenuEntry *submePtr = menuRefPtr->menuPtr->entries[i];
NSMenuItem *item = (NSMenuItem *) submePtr->platformEntryData;
[item setEnabled:(submePtr->state != ENTRY_DISABLED)];
}
}
}
}
}
[menuItem setSubmenu:submenu];
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TkpDestroyMenuEntry --
*
* Cleans up platform-specific menu entry items.
*
* Results:
* None
*
* Side effects:
* All platform-specific allocations are freed up.
*
*----------------------------------------------------------------------
*/
void
TkpDestroyMenuEntry(
TkMenuEntry *mePtr)
{
NSMenuItem *menuItem;
TKMenu *menu;
NSInteger index;
if (mePtr->platformEntryData && mePtr->menuPtr->platformData) {
menu = (TKMenu *) mePtr->menuPtr->platformData;
menuItem = (NSMenuItem *) mePtr->platformEntryData;
index = [menu indexOfItem:menuItem];
if (index > -1) {
[menu removeItemAtIndex:index];
}
[menuItem release];
mePtr->platformEntryData = NULL;
}
}
/*
*----------------------------------------------------------------------
*
* TkpPostMenu --
*
* Posts a menu on the screen. If entry is < 0 then the menu is drawn so
* its top left corner is located at the point with screen coordinates
* (x,y). Otherwise the top left corner of the specified entry is located
* at that point.
*
* Results:
* Returns a standard Tcl result.
*
* Side effects:
* The menu is posted and handled.
*
*----------------------------------------------------------------------
*/
int
TkpPostMenu(
TCL_UNUSED(Tcl_Interp *), /* The interpreter this menu lives in */
TkMenu *menuPtr, /* The menu we are posting */
int x, int y, /* The screen coordinates where the top left
* corner of the menu, or of the specified
* entry, will be located. */
int index)
{
int result;
Tk_Window realWin = menuPtr->tkwin;
TkWindow *realWinPtr;
NSView *realWinView;
while (1) {
if (realWin == NULL) {
return TCL_ERROR;
}
/*
* Fix for bug 07cfc9f03e: use the view for the parent real (non-menu)
* toplevel window, rather than always using the root window.
* This allows menus to appear on a separate monitor than the root
* window, and to use the appearance of their parent real window
* rather than the appearance of the root window.
*/
realWinPtr = (TkWindow*) realWin;
realWinView = TkMacOSXGetNSViewForDrawable(realWinPtr->privatePtr);
if (realWinView != nil) {
break;
}
realWin = Tk_Parent(realWin);
}
NSWindow *win = [realWinView window];
NSView *view = [win contentView];
NSMenu *menu = (NSMenu *) menuPtr->platformData;
NSInteger itemIndex = index;
NSInteger numItems = [menu numberOfItems];
NSMenuItem *item = nil;
NSPoint location = NSMakePoint(x, TkMacOSXZeroScreenHeight() - y);
inPostMenu = 1;
result = TkPreprocessMenu(menuPtr);
if (result != TCL_OK) {
inPostMenu = 0;
return result;
}
if (itemIndex >= numItems) {
itemIndex = numItems - 1;
}
if (itemIndex >= 0) {
item = [menu itemAtIndex:itemIndex];
}
/*
* The post commands could have deleted the menu, which means we are dead
* and should go away.
*/
if (menuPtr->tkwin == NULL) {
return TCL_OK;
}
[menu popUpMenuPositioningItem:item
atLocation:[win tkConvertPointFromScreen:location]
inView:view];
inPostMenu = 0;
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TkpPostTearoffMenu --
*
* Tearoff menus are not supported on the Mac. This placeholder function,
* which is simply a copy of the unix function, posts a completely useless
* window with a black background on the screen. If entry is < 0 then the
* window is positioned so that its top left corner is located at the
* point with screen coordinates (x, y). Otherwise the window position is
* offset so that top left corner of the specified entry would be located
* at that point, if there actually were a menu.
*
* Mac menus steal all mouse or keyboard input from the application until
* the menu is dismissed, with or without a selection, by a mouse or key
* event. Posting a Mac menu in a regression test will cause the test to
* halt waiting for user input. This is why the TkpPostMenu function is
* not being used as the placeholder.
*
* Results:
* None.
*
* Side effects:
* A useless window is posted.
*
*----------------------------------------------------------------------
*/
int
TkpPostTearoffMenu(
TCL_UNUSED(Tcl_Interp *), /* The interpreter this menu lives in */
TkMenu *menuPtr, /* The menu we are posting */
int x, int y, int index) /* The screen coordinates where the top left
* corner of the menu, or of the specified
* entry, will be located. */
{
int vRootX, vRootY, vRootWidth, vRootHeight;
int result;
TkActivateMenuEntry(menuPtr, -1);
TkRecomputeMenu(menuPtr);
result = TkPostCommand(menuPtr);
if (result != TCL_OK) {
return result;
}
/*
* The post commands could have deleted the menu, which means we are dead
* and should go away.
*/
if (menuPtr->tkwin == NULL) {
return TCL_OK;
}
/*
* Adjust the menu y position so that the specified entry will be located
* at the given coordinates.
*/
if (index < 0 || (Tcl_Size)index >= menuPtr->numEntries) {
index = menuPtr->numEntries - 1;
}
if (index >= 0) {
y -= menuPtr->entries[index]->y;
}
/*
* Adjust the position of the menu if necessary to keep it visible on the
* screen. There are two special tricks to make this work right:
*
* 1. If a virtual root window manager is being used then the coordinates
* are in the virtual root window of menuPtr's parent; since the menu
* uses override-redirect mode it will be in the *real* root window for
* the screen, so we have to map the coordinates from the virtual root
* (if any) to the real root. Can't get the virtual root from the menu
* itself (it will never be seen by the wm) so use its parent instead
* (it would be better to have an an option that names a window to use
* for this...).
* 2. The menu may not have been mapped yet, so its current size might be
* the default 1x1. To compute how much space it needs, use its
* requested size, not its actual size.
*/
Tk_GetVRootGeometry(Tk_Parent(menuPtr->tkwin), &vRootX, &vRootY,
&vRootWidth, &vRootHeight);
vRootWidth -= Tk_ReqWidth(menuPtr->tkwin);
if (x > vRootX + vRootWidth) {
x = vRootX + vRootWidth;
}
if (x < vRootX) {
x = vRootX;
}
vRootHeight -= Tk_ReqHeight(menuPtr->tkwin);
if (y > vRootY + vRootHeight) {
y = vRootY + vRootHeight;
}
if (y < vRootY) {
y = vRootY;
}
Tk_MoveToplevelWindow(menuPtr->tkwin, x, y);
if (!Tk_IsMapped(menuPtr->tkwin)) {
Tk_MapWindow(menuPtr->tkwin);
}
TkWmRestackToplevel((TkWindow *) menuPtr->tkwin, Above, NULL);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TkpSetWindowMenuBar --
*
* Associates a given menu with a window.
*
* Results:
* None.
*
* Side effects:
* On Windows and UNIX, associates the platform menu with the platform
* window.
*
*----------------------------------------------------------------------
*/
void
TkpSetWindowMenuBar(
Tk_Window tkwin, /* The window we are setting the menu in */
TkMenu *menuPtr) /* The menu we are setting */
{
TkWindow *winPtr = (TkWindow *) tkwin;
if (winPtr->wmInfoPtr) {
winPtr->wmInfoPtr->menuPtr = menuPtr;
}
}
/*
*----------------------------------------------------------------------
*
* Tk_SetMainMenubar --
*
* Puts the menu associated with a window into the menubar. Should only be
* called when the window is in front.
*
* This is a no-op on all other platforms. On OS X it is a no-op when
* passed a NULL menuName or a nonexistent menuName, with an exception for
* the first call in a new interpreter. In that special case, passing a
* NULL menuName installs the default menu.
*
* Results:
* None.
*
* Side effects:
* The menubar may be changed.
*
*----------------------------------------------------------------------
*/
void
Tk_SetMainMenubar(
Tcl_Interp *interp, /* The interpreter of the application */
Tk_Window tkwin, /* The frame we are setting up */
const char *menuName) /* The name of the menu to put in front. */
{
static Tcl_Interp *currentInterp = NULL;
TKMenu *menu = nil;
TkWindow *winPtr = (TkWindow *) tkwin;
/*
* We will be called when an embedded window receives an ActivationNotify
* event, but we should not change the menubar in that case.
*/
if (Tk_IsEmbedded(winPtr)) {
return;
}
if (menuName) {
Tk_Window menubar = NULL;
if (winPtr->wmInfoPtr &&
winPtr->wmInfoPtr->menuPtr &&
winPtr->wmInfoPtr->menuPtr->mainMenuPtr) {
menubar = winPtr->wmInfoPtr->menuPtr->mainMenuPtr->tkwin;
}
/*
* Attempt to find the NSMenu directly. If that fails, ask Tk to find
* it.
*/
if (menubar != NULL && strcmp(menuName, Tk_PathName(menubar)) == 0) {
menu = (TKMenu *) winPtr->wmInfoPtr->menuPtr->platformData;
} else {
TkMenuReferences *menuRefPtr = TkFindMenuReferences(interp,
menuName);
if (menuRefPtr && menuRefPtr->menuPtr &&
menuRefPtr->menuPtr->platformData) {
menu = (TKMenu *) menuRefPtr->menuPtr->platformData;
}
}
}
/*
* If we couldn't find a menu, do nothing unless the window belongs to a
* different application. In that case, install the default menubar.
*/
if (menu || interp != currentInterp) {
[NSApp tkSetMainMenu:menu];
}
currentInterp = interp;
}
/*
*----------------------------------------------------------------------
*
* CheckForSpecialMenu --
*
* Given a menu, check to see whether or not it is a cascade in a menubar
* with one of the special names ".apple", ".help" or ".window". If it is,
* the entry that points to this menu will be marked.
*
* Results:
* None.
*
* Side effects:
* Will set entryFlags appropriately.
*
*----------------------------------------------------------------------
*/
static void
CheckForSpecialMenu(
TkMenu *menuPtr) /* The menu we are checking */
{
if (!menuPtr->mainMenuPtr->tkwin) {
return;
}
for (TkMenuEntry *cascadeEntryPtr = menuPtr->menuRefPtr->parentEntryPtr;
cascadeEntryPtr;
cascadeEntryPtr = cascadeEntryPtr->nextCascadePtr) {
if (cascadeEntryPtr->menuPtr->menuType == MENUBAR
&& cascadeEntryPtr->menuPtr->mainMenuPtr->tkwin) {
TkMenu *mainMenuPtr = cascadeEntryPtr->menuPtr->mainMenuPtr;
int i = 0;
Tcl_DString ds;
Tcl_DStringInit(&ds);
Tcl_DStringAppend(&ds, Tk_PathName(mainMenuPtr->tkwin), -1);
while (specialMenus[i].name) {
Tcl_DStringAppend(&ds, specialMenus[i].name,
specialMenus[i].len);
if (strcmp(Tcl_DStringValue(&ds),
Tk_PathName(menuPtr->mainMenuPtr->tkwin)) == 0) {
cascadeEntryPtr->entryFlags |= specialMenus[i].flag;
} else {
cascadeEntryPtr->entryFlags &= ~specialMenus[i].flag;
}
Tcl_DStringSetLength(&ds, Tcl_DStringLength(&ds) -
specialMenus[i].len);
i++;
}
Tcl_DStringFree(&ds);
}
}
}
/*
*----------------------------------------------------------------------
*
* ParseAccelerator --
*
* Parse accelerator string.
*
* Results:
* Accelerator string & flags.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static NSString *
ParseAccelerator(
const char *accel,
NSUInteger *maskPtr)
{
unichar ch = 0;
size_t len;
int i;
*maskPtr = 0;
while (1) {
i = 0;
while (allModifiers[i].name) {
int l = allModifiers[i].len;
if (!strncasecmp(accel, allModifiers[i].name, l) &&
(accel[l] == '-' || accel[l] == '+')) {
*maskPtr |= allModifiers[i].mask;
accel += l+1;
break;
}
i++;
}
if (!allModifiers[i].name || !*accel) {
break;
}
}
len = strlen(accel);
if (len > 1) {
i = 0;
if (accel[0] == 'F' && len < 4 && accel[1] > '0' && accel[1] <= '9') {
int fkey = accel[1] - '0';
if (len == 3) {
if (accel[2] >= '0' && accel[2] <= '9') {
fkey = 10 * fkey + (accel[2] - '0');
} else {
fkey = 0;
}
}
if (fkey >= 1 && fkey <= 15) {
ch = NSF1FunctionKey + fkey - 1;
}
} else while (specialAccelerators[i].name) {
if (accel[0] == specialAccelerators[i].name[0] &&
len == specialAccelerators[i].len && !strncasecmp(accel,
specialAccelerators[i].name, specialAccelerators[i].len)) {
ch = specialAccelerators[i].ch;
break;
}
i++;
}
}
if (ch) {
return [[[NSString alloc] initWithCharacters:&ch length:1] autorelease];
} else {
return [[[[NSString alloc] initWithUTF8String:accel] autorelease]
lowercaseString];
}
}
/*
*--------------------------------------------------------------
*
* ModifierCharWidth --
*
* Helper mesuring width of command char in given font.
*
* Results:
* Width of command char.
*
* Side effects:
* None.
*
*--------------------------------------------------------------
*/
static int
ModifierCharWidth(
Tk_Font tkfont)
{
static NSString *cmdChar = nil;
if (!cmdChar) {
unichar cmd = kCommandUnicode;
cmdChar = [[NSString alloc] initWithCharacters:&cmd length:1];
}
return [cmdChar sizeWithAttributes:
TkMacOSXNSFontAttributesForFont(tkfont)].width;
}
/*
*--------------------------------------------------------------
*
* TkpComputeStandardMenuGeometry --
*
* This procedure is invoked to recompute the size and layout of a menu
* that is not a menubar clone.
*
* Results:
* None.
*
* Side effects:
* Fields of menu entries are changed to reflect their current positions,
* and the size of the menu window itself may be changed.
*
*--------------------------------------------------------------
*/
void
TkpComputeStandardMenuGeometry(
TkMenu *menuPtr) /* Structure describing menu. */
{
NSSize menuSize;
Tk_Font tkfont, menuFont;
Tk_FontMetrics menuMetrics, entryMetrics;
int modifierCharWidth, menuModifierCharWidth;
int x, y, modifierWidth, labelWidth, indicatorSpace;
int windowWidth, windowHeight, accelWidth;
int i, maxWidth;
int entryWidth, maxIndicatorSpace, borderWidth, activeBorderWidth;
TkMenuEntry *mePtr;
int haveAccel = 0;
/*
* Do nothing if this menu is a clone.
*/
if (menuPtr->tkwin == NULL || menuPtr->mainMenuPtr != menuPtr) {
return;
}
menuSize = [(NSMenu *) menuPtr->platformData size];
Tk_GetPixelsFromObj(NULL, menuPtr->tkwin, menuPtr->borderWidthPtr,
&borderWidth);
Tk_GetPixelsFromObj(NULL, menuPtr->tkwin, menuPtr->activeBorderWidthPtr,
&activeBorderWidth);
x = y = borderWidth;
windowHeight = maxWidth = 0;
maxIndicatorSpace = 0;
/*
* On the Mac especially, getting font metrics can be quite slow, so we
* want to do it intelligently. We are going to precalculate them and pass
* them down to all of the measuring and drawing routines. We will measure
* the font metrics of the menu once. If an entry does not have its own
* font set, then we give the geometry/drawing routines the menu's font and
* metrics. If an entry has its own font, we will measure that font and
* give all of the geometry/drawing the entry's font and metrics.
*/
menuFont = Tk_GetFontFromObj(menuPtr->tkwin, menuPtr->fontPtr);
Tk_GetFontMetrics(menuFont, &menuMetrics);
menuModifierCharWidth = ModifierCharWidth(menuFont);
for (i = 0; i < (int) menuPtr->numEntries; i++) {
mePtr = menuPtr->entries[i];
if (mePtr->type == CASCADE_ENTRY || mePtr->accelLength > 0) {
haveAccel = 1;
break;
}
}
for (i = 0; i < (int) menuPtr->numEntries; i++) {
mePtr = menuPtr->entries[i];
if (mePtr->type == TEAROFF_ENTRY) {
continue;
}
if (mePtr->fontPtr == NULL) {
tkfont = menuFont;
modifierCharWidth = menuModifierCharWidth;
} else {
tkfont = Tk_GetFontFromObj(menuPtr->tkwin, mePtr->fontPtr);
Tk_GetFontMetrics(tkfont, &entryMetrics);
modifierCharWidth = ModifierCharWidth(tkfont);
}
accelWidth = modifierWidth = indicatorSpace = 0;
if (mePtr->type == SEPARATOR_ENTRY) {
mePtr->height = menuSeparatorHeight;
} else {
/*
* For each entry, compute the height required by that particular
* entry, plus three widths: the width of the label, the width to
* allow for an indicator to be displayed to the left of the label
* (if any), and the width of the accelerator to be displayed to
* the right of the label (if any). These sizes depend, of course,
* on the type of the entry.
*/
NSMenuItem *menuItem = (NSMenuItem *) mePtr->platformEntryData;
int haveImage = 0, width = 0, height = 0;
if (mePtr->image) {
Tk_SizeOfImage(mePtr->image, &width, &height);
haveImage = 1;
height += 2; /* tweak */
} else if (mePtr->bitmapPtr) {
Pixmap bitmap = Tk_GetBitmapFromObj(menuPtr->tkwin,
mePtr->bitmapPtr);
Tk_SizeOfBitmap(menuPtr->display, bitmap, &width, &height);
haveImage = 1;
height += 2; /* tweak */
}
if (!haveImage || (mePtr->compound != COMPOUND_NONE)) {
NSAttributedString *attrTitle = [menuItem attributedTitle];
NSSize size;
if (attrTitle) {
size = [attrTitle size];
} else {
size = [[menuItem title] sizeWithAttributes:
TkMacOSXNSFontAttributesForFont(tkfont)];
}
size.width += menuTextLeadingEdgeMargin + menuTextTrailingEdgeMargin;
size.height -= 1; /* tweak */
if (haveImage && (mePtr->compound != COMPOUND_NONE)) {
int margin = width + menuIconTrailingEdgeMargin;
if (margin > menuTextLeadingEdgeMargin) {
margin = menuTextLeadingEdgeMargin;
}
width += size.width + menuIconTrailingEdgeMargin - margin;
if (size.height > height) {
height = size.height;
}
} else {
width = size.width;
height = size.height;
}
}
else {
/* image only. */
}
labelWidth = width + menuItemExtraWidth;
mePtr->height = height + menuItemExtraHeight;
if (mePtr->type == CASCADE_ENTRY) {
modifierWidth = modifierCharWidth;
} else if (mePtr->accelLength == 0) {
if (haveAccel && !mePtr->hideMargin) {
modifierWidth = modifierCharWidth;
}
} else {
NSUInteger modifMask = [menuItem keyEquivalentModifierMask];
int j = 0;
while (allModifiers[j].name) {
if (modifMask & allModifiers[j].mask) {
modifMask &= ~allModifiers[j].mask;
modifierWidth += modifierCharWidth;
}
j++;
}
accelWidth = [[menuItem keyEquivalent] sizeWithAttributes:
TkMacOSXNSFontAttributesForFont(tkfont)].width;
}
if (!mePtr->hideMargin) {
indicatorSpace = menuMarkColumnWidth;
}
if (indicatorSpace > maxIndicatorSpace) {
maxIndicatorSpace = indicatorSpace;
}
entryWidth = labelWidth + modifierWidth + accelWidth;
if (entryWidth > maxWidth) {
maxWidth = entryWidth;
}
menuPtr->entries[i]->width = entryWidth;
mePtr->height += 2 * activeBorderWidth;
}
mePtr->x = x;
mePtr->y = y;
y += menuPtr->entries[i]->height + borderWidth;
}
windowWidth = menuSize.width;
if (windowWidth <= 0) {
windowWidth = 1;
}
windowHeight = menuSize.height;
if (windowHeight <= 0) {
windowHeight = 1;
}
menuPtr->totalWidth = windowWidth;
menuPtr->totalHeight = windowHeight;
}
/*
*----------------------------------------------------------------------
*
* GenerateMenuSelectEvent --
*
* Respond to a menu item being selected.
*
* Results:
* True if event(s) are generated - false otherwise.
*
* Side effects:
* Places a virtual event on the event queue.
*
*----------------------------------------------------------------------
*/
int
GenerateMenuSelectEvent(
TKMenu *menu,
NSMenuItem *menuItem)
{
TkMenu *menuPtr = [menu tkMenu];
if (menuPtr) {
int index = [menu tkIndexOfItem:menuItem];
if (index < 0 || index >= (int) menuPtr->numEntries ||
(menuPtr->entries[index])->state == ENTRY_DISABLED) {
TkActivateMenuEntry(menuPtr, -1);
} else {
TkActivateMenuEntry(menuPtr, index);
MenuSelectEvent(menuPtr);
return true;
}
}
return false;
}
/*
*----------------------------------------------------------------------
*
* MenuSelectEvent --
*
* Generates a "MenuSelect" virtual event. This can be used to do
* context-sensitive menu help.
*
* Results:
* None.
*
* Side effects:
* Places a virtual event on the event queue.
*
*----------------------------------------------------------------------
*/
void
MenuSelectEvent(
TkMenu *menuPtr) /* the menu we have selected. */
{
union {XEvent general; XVirtualEvent virt;} event;
bzero(&event, sizeof(event));
event.virt.type = VirtualEvent;
event.virt.serial = LastKnownRequestProcessed(menuPtr->display);
event.virt.send_event = false;
event.virt.display = menuPtr->display;
event.virt.event = Tk_WindowId(menuPtr->tkwin);
event.virt.root = XRootWindow(menuPtr->display, 0);
event.virt.subwindow = None;
event.virt.time = TkpGetMS();
XQueryPointer(NULL, None, NULL, NULL, &event.virt.x_root, &event.virt.y_root, NULL,
NULL, &event.virt.state);
event.virt.same_screen = true;
event.virt.name = Tk_GetUid("MenuSelect");
Tk_MakeWindowExist(menuPtr->tkwin);
if (Tcl_GetServiceMode() != TCL_SERVICE_NONE) {
Tk_HandleEvent(&event.general);
} else {
Tk_QueueWindowEvent(&event.general, TCL_QUEUE_TAIL);
}
}
/*
*----------------------------------------------------------------------
*
* RecursivelyClearActiveMenu --
*
* Recursively clears the active entry in the menu's cascade hierarchy.
*
* Results:
* None.
*
* Side effects:
* Generates <<MenuSelect>> virtual events.
*
*----------------------------------------------------------------------
*/
void
RecursivelyClearActiveMenu(
TkMenu *menuPtr) /* The menu to reset. */
{
int i;
TkActivateMenuEntry(menuPtr, -1);
for (i = 0; i < (int) menuPtr->numEntries; i++) {
TkMenuEntry *mePtr = menuPtr->entries[i];
if (mePtr->type == CASCADE_ENTRY
&& (mePtr->childMenuRefPtr != NULL)
&& (mePtr->childMenuRefPtr->menuPtr != NULL)) {
RecursivelyClearActiveMenu(mePtr->childMenuRefPtr->menuPtr);
}
}
}
/*
*----------------------------------------------------------------------
*
* TkMacOSXClearMenubarActive --
*
* Recursively clears the active entry in the current menubar hierarchy.
*
* Results:
* None.
*
* Side effects:
* Generates <<MenuSelect>> virtual events.
*
*----------------------------------------------------------------------
*/
void
TkMacOSXClearMenubarActive(void)
{
NSMenu *mainMenu = [NSApp mainMenu];
if (mainMenu && [mainMenu isKindOfClass:[TKMenu class]]) {
TkMenu *menuPtr = [(TKMenu *) mainMenu tkMenu];
if (menuPtr &&
!(menuPtr->menuFlags & MENU_DELETION_PENDING) &&
menuPtr->numEntries > 0 &&
menuPtr->entries != NULL) {
RecursivelyClearActiveMenu(menuPtr);
}
}
}
/*
*----------------------------------------------------------------------
*
* TkpMenuInit --
*
* Initializes Mac-specific menu data.
*
* Results:
* None.
*
* Side effects:
* Allocates a hash table.
*
*----------------------------------------------------------------------
*/
void
TkpMenuInit(void)
{
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
#define observe(n, s) \
[nc addObserver:NSApp selector:@selector(s) name:(n) object:nil]
observe(NSMenuDidBeginTrackingNotification, menuBeginTracking:);
observe(NSMenuDidEndTrackingNotification, menuEndTracking:);
#undef observe
[NSMenuItem setUsesUserKeyEquivalents:NO];
ChkErr(GetThemeMetric, kThemeMetricMenuMarkColumnWidth,
&menuMarkColumnWidth);
ChkErr(GetThemeMetric, kThemeMetricMenuTextLeadingEdgeMargin,
&menuTextLeadingEdgeMargin);
ChkErr(GetThemeMetric, kThemeMetricMenuTextTrailingEdgeMargin,
&menuTextTrailingEdgeMargin);
ChkErr(GetThemeMetric, kThemeMetricMenuIconTrailingEdgeMargin,
&menuIconTrailingEdgeMargin);
ChkErr(GetThemeMenuItemExtra, kThemeMenuItemPlain, &menuItemExtraHeight,
&menuItemExtraWidth);
ChkErr(GetThemeMenuSeparatorHeight, &menuSeparatorHeight);
}
#pragma mark -
#pragma mark NOPs
/*
*----------------------------------------------------------------------
*
* TkpMenuThreadInit --
*
* Does platform-specific initialization of thread-specific menu state.
*
* Results:
* None.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
void
TkpMenuThreadInit(void)
{
/*
* Nothing to do.
*/
}
/*
*----------------------------------------------------------------------
*
* TkpMenuNotifyToplevelCreate --
*
* This routine reconfigures the menu and the clones indicated by
* menuName because a toplevel has been created and any system menus need
* to be created. Only applicable to Windows.
*
* Results:
* None.
*
* Side effects:
* An idle handler is set up to do the reconfiguration.
*
*----------------------------------------------------------------------
*/
void
TkpMenuNotifyToplevelCreate(
TCL_UNUSED(Tcl_Interp *), /* The interp the menu lives in. */
TCL_UNUSED(const char *)) /* The name of the menu to reconfigure. */
{
/*
* Nothing to do.
*/
}
/*
*--------------------------------------------------------------
*
* TkpInitializeMenuBindings --
*
* For every interp, initializes the bindings for Windows menus. Does
* nothing on Mac or XWindows.
*
* Results:
* None.
*
* Side effects:
* C-level bindings are setup for the interp which will handle Alt-key
* sequences for menus without beeping or interfering with user-defined
* Alt-key bindings.
*
*--------------------------------------------------------------
*/
void
TkpInitializeMenuBindings(
TCL_UNUSED(Tcl_Interp *), /* The interpreter to set. */
TCL_UNUSED(Tk_BindingTable))
/* The table to add to. */
{
/*
* Nothing to do.
*/
}
/*
*--------------------------------------------------------------
*
* TkpComputeMenubarGeometry --
*
* This procedure is invoked to recompute the size and layout of a menu
* that is a menubar clone.
*
* Results:
* None.
*
* Side effects:
* Fields of menu entries are changed to reflect their current positions,
* and the size of the menu window itself may be changed.
*
*--------------------------------------------------------------
*/
void
TkpComputeMenubarGeometry(
TkMenu *menuPtr) /* Structure describing menu. */
{
TkpComputeStandardMenuGeometry(menuPtr);
}
/*
*----------------------------------------------------------------------
*
* TkpDrawMenuEntry --
*
* Draws the given menu entry at the given coordinates with the given
* attributes. This is a no-op on macOS since the menus are drawn by
* the Apple window manager, which also handles all events related to
* selecting menu items. This function is only called for tearoff
* menus, which are not supported on macOS but do get drawn as nearly
* invisible 1 pixel wide windows on macOS
*
* Results:
* None.
*
* Side effects:
* None
*
*----------------------------------------------------------------------
*/
void
TkpDrawMenuEntry(
TCL_UNUSED(TkMenuEntry *), /* The entry to draw */
TCL_UNUSED(Drawable), /* What to draw into */
TCL_UNUSED(Tk_Font), /* Precalculated font for menu */
TCL_UNUSED(const Tk_FontMetrics *),
/* Precalculated metrics for menu */
TCL_UNUSED(int), /* X-coordinate of topleft of entry */
TCL_UNUSED(int), /* Y-coordinate of topleft of entry */
TCL_UNUSED(int), /* Width of the entry rectangle */
TCL_UNUSED(int), /* Height of the current rectangle */
TCL_UNUSED(int), /* Boolean flag */
TCL_UNUSED(int)) /* Whether or not to draw the cascade arrow
* for cascade items. */
{
}
#pragma mark Obsolete
/*
*----------------------------------------------------------------------
*
* TkMacOSXPreprocessMenu --
*
* Handle preprocessing of menubar if it exists.
*
* Results:
* None.
*
* Side effects:
* All post commands for the current menubar get executed.
*
*----------------------------------------------------------------------
*/
void
TkMacOSXPreprocessMenu(void)
{
}
/*
*----------------------------------------------------------------------
*
* TkMacOSXUseID --
*
* Take the ID out of the available list for new menus. Used by the
* default menu bar's menus so that they do not get created at the Tk
* level. See TkMacOSXGetNewMenuID for more information.
*
* Results:
* Returns TCL_OK if the id was not in use. Returns TCL_ERROR if the id
* was in use.
*
* Side effects:
* A hash table entry in the command table is created with a NULL value.
*
*----------------------------------------------------------------------
*/
int
TkMacOSXUseMenuID(
TCL_UNUSED(short)) /* The id to take out of the table */
{
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* TkMacOSXDispatchMenuEvent --
*
* Given a menu id and an item, dispatches the command associated with it.
*
* Results:
* None.
*
* Side effects:
* Commands for the event are scheduled for execution at idle time.
*
*----------------------------------------------------------------------
*/
int
TkMacOSXDispatchMenuEvent(
TCL_UNUSED(int), /* The menu id of the menu we are invoking */
TCL_UNUSED(int)) /* The one-based index of the item that was
* selected. */
{
return TCL_ERROR;
}
/*
*----------------------------------------------------------------------
*
* TkMacOSXHandleTearoffMenu() --
*
* This routine sees if the MDEF has set a menu and a mouse position for
* tearing off and makes a tearoff menu if it has.
*
* Results:
* menuPtr->interp will have the result of the tearoff command.
*
* Side effects:
* A new tearoff menu is created if it is supposed to be.
*
*----------------------------------------------------------------------
*/
void
TkMacOSXHandleTearoffMenu(void)
{
/*
* Obsolete: Nothing to do.
*/
}
/*
*----------------------------------------------------------------------
*
* TkMacOSXSetHelpMenuItemCount --
*
* Has to be called after the first call to InsertMenu. Sets up the global
* variable for the number of items in the unmodified help menu.
*
* NB: Nobody uses this any more, since you can get the number of system
* help items from HMGetHelpMenu trivially. But it is in the stubs
* table...
*
* Results:
* None.
*
* Side effects:
* Nothing.
*
*----------------------------------------------------------------------
*/
void
TkMacOSXSetHelpMenuItemCount(void)
{
}
/*
*----------------------------------------------------------------------
*
* TkMacOSXMenuClick --
*
* Prepares a menubar for MenuSelect or MenuKey.
*
* Results:
* None.
*
* Side effects:
* Any pending configurations of the menubar are completed.
*
*----------------------------------------------------------------------
*/
void
TkMacOSXMenuClick(void)
{
}
/*
* Local Variables:
* mode: objc
* c-basic-offset: 4
* fill-column: 79
* coding: utf-8
* End:
*/
|