1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
|
/** <title>NSMenuView</title>
Copyright (C) 1999 Free Software Foundation, Inc.
Author: Fred Kiefer <FredKiefer@gmx.de>
Date: Sep 2001
Author: David Lazaro Saz <khelekir@encomix.es>
Date: Oct 1999
Author: Michael Hanni <mhanni@sprintmail.com>
Date: 1999
This file is part of the GNUstep GUI Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; see the file COPYING.LIB.
If not, see <http://www.gnu.org/licenses/> or write to the
Free Software Foundation, 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#import <Foundation/NSArray.h>
#import <Foundation/NSCoder.h>
#import <Foundation/NSDate.h>
#import <Foundation/NSDebug.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSException.h>
#import <Foundation/NSNotification.h>
#import <Foundation/NSRunLoop.h>
#import <Foundation/NSString.h>
#import <Foundation/NSValue.h>
#import "AppKit/NSApplication.h"
#import "AppKit/NSEvent.h"
#import "AppKit/NSFont.h"
#import "AppKit/NSImage.h"
#import "AppKit/NSMenuView.h"
#import "AppKit/NSMenu.h"
#import "AppKit/NSButton.h"
#import "AppKit/NSPopUpButtonCell.h"
#import "AppKit/NSScreen.h"
#import "AppKit/NSWindow.h"
#import "AppKit/PSOperators.h"
#import "GNUstepGUI/GSTheme.h"
#import "GNUstepGUI/GSTitleView.h"
typedef struct _GSCellRect {
NSRect rect;
} GSCellRect;
#define GSI_ARRAY_TYPES 0
#define GSI_ARRAY_TYPE GSCellRect
#define GSI_ARRAY_NO_RETAIN
#define GSI_ARRAY_NO_RELEASE
#ifdef GSIArray
#undef GSIArray
#endif
#include <GNUstepBase/GSIArray.h>
static NSMapTable *viewInfo = 0;
#define cellRects ((GSIArray)NSMapGet(viewInfo, self))
#define HORIZONTAL_MENU_LEFT_PADDING 8
/*
NSMenuView contains:
a) Title, if needed, this is a subview
b) menu items
*/
/* A menu's title is an instance of this class */
@class NSButton;
@interface NSMenu (Private)
- (void) _attachMenu: (NSMenu*)aMenu;
@end
@implementation NSMenu (Private)
- (void) _attachMenu: (NSMenu*)aMenu
{
_attachedMenu = aMenu;
}
@end
@interface NSMenuView (Private)
- (BOOL) _rootIsHorizontal: (BOOL*)isAppMenu;
@end
@implementation NSMenuView (Private)
- (BOOL) _rootIsHorizontal: (BOOL*)isAppMenu
{
NSMenu *m = _attachedMenu;
/* Determine root menu of this menu hierarchy */
while ([m supermenu] != nil)
{
m = [m supermenu];
}
if (isAppMenu != 0)
{
if (m == [NSApp mainMenu])
{
*isAppMenu = YES;
}
else
{
*isAppMenu = NO;
}
}
return [[m menuRepresentation] isHorizontal];
}
@end
@implementation NSMenuView
/*
* Class methods.
*/
static float menuBarHeight = 0.0;
+ (void) _themeWillDeactivate: (NSNotification*)n
{
/* Clear cached information from the old theme ... will get info from
* the new theme as required.
*/
menuBarHeight = 0;
}
+ (void) initialize
{
if (viewInfo == 0)
{
viewInfo = NSCreateMapTable(NSNonOwnedPointerMapKeyCallBacks,
NSNonOwnedPointerMapValueCallBacks, 20);
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(_themeWillDeactivate:)
name: GSThemeWillDeactivateNotification
object: nil];
}
}
+ (float) menuBarHeight
{
if (menuBarHeight == 0.0)
{
const CGFloat themeHeight = [[GSTheme theme] menuBarHeight];
NSFont *font = [NSFont menuBarFontOfSize: 0.0];
menuBarHeight = [font boundingRectForFont].size.height;
if (menuBarHeight < themeHeight)
menuBarHeight = themeHeight;
}
return menuBarHeight;
}
/*
* NSView overrides
*/
- (BOOL) acceptsFirstMouse: (NSEvent*)theEvent
{
return YES;
}
// We do not want to popup menus in this menu view.
- (NSMenu *) menuForEvent: (NSEvent*) theEvent
{
NSDebugLLog (@"NSMenu", @"Query for menu in view");
return nil;
}
/*
* Init methods.
*/
- (id) initWithFrame: (NSRect)aFrame
{
self = [super initWithFrame: aFrame];
if (!self)
return nil;
[self setFont: [NSFont menuFontOfSize: 0.0]];
_highlightedItemIndex = -1;
_horizontalEdgePad = 4.;
/* Set the necessary offset for the menuView. That is, how many pixels
* do we need for our left side border line.
*/
_leftBorderOffset = 1;
// Create an array to store our menu item cells.
_itemCells = [NSMutableArray new];
// FIXME: Should this go in NSMenu instead of here?
[[NSNotificationCenter defaultCenter]
addObserver: self
selector: @selector(_themeDidActivate:)
name: GSThemeDidActivateNotification
object: nil];
return self;
}
- (id) initAsTearOff
{
self = [self initWithFrame: NSZeroRect];
if (nil == self)
return nil;
if (_attachedMenu)
[_attachedMenu setTornOff: YES];
return self;
}
- (void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver: self];
// We must remove the menu view from the menu list of observers.
if (_attachedMenu != nil)
{
[[NSNotificationCenter defaultCenter] removeObserver: self
name: nil
object: _attachedMenu];
}
/* Clean the pointer to us stored into the _itemCells. */
[_itemCells makeObjectsPerformSelector: @selector(setMenuView:)
withObject: nil];
RELEASE(_itemCells);
RELEASE(_font);
/*
* Get rid of any cached cell rects.
*/
{
GSIArray a = NSMapGet(viewInfo, self);
if (a != 0)
{
GSIArrayEmpty(a);
NSZoneFree(NSDefaultMallocZone(), a);
NSMapRemove(viewInfo, self);
}
}
[super dealloc];
}
/*
* Getting and Setting Menu View Attributes
*/
- (void) setMenu: (NSMenu*)menu
{
NSNotificationCenter *theCenter = [NSNotificationCenter defaultCenter];
unsigned count;
unsigned i;
if (_attachedMenu != nil)
{
// Remove this menu view from the old menu list of observers.
[theCenter removeObserver: self name: nil object: _attachedMenu];
}
/* menu is retaining us, so we should not be retaining menu. */
_attachedMenu = menu;
_items_link = [_attachedMenu itemArray];
if (_attachedMenu != nil)
{
// Add this menu view to the menu's list of observers.
[theCenter addObserver: self
selector: @selector(itemChanged:)
name: NSMenuDidChangeItemNotification
object: _attachedMenu];
[theCenter addObserver: self
selector: @selector(itemAdded:)
name: NSMenuDidAddItemNotification
object: _attachedMenu];
[theCenter addObserver: self
selector: @selector(itemRemoved:)
name: NSMenuDidRemoveItemNotification
object: _attachedMenu];
}
count = [[[self menu] itemArray] count];
for (i = 0; i < count; i++)
{
NSNumber *n = [NSNumber numberWithInt: i];
NSDictionary *d;
d = [NSDictionary dictionaryWithObject: n forKey: @"NSMenuItemIndex"];
[self itemAdded: [NSNotification
notificationWithName: NSMenuDidAddItemNotification
object: self
userInfo: d]];
}
// Force menu view's layout to be recalculated.
[self setNeedsSizing: YES];
[self update];
}
- (NSMenu*) menu
{
return _attachedMenu;
}
- (void) setHorizontal: (BOOL)flag
{
if (flag == YES && _horizontal == NO)
{
NSRect scRect = [[NSScreen mainScreen] frame];
GSIArray a = NSZoneMalloc(NSDefaultMallocZone(), sizeof(GSIArray_t));
GSIArrayInitWithZoneAndCapacity(a, NSDefaultMallocZone(), 8);
NSMapInsert(viewInfo, self, a);
scRect.size.height = [NSMenuView menuBarHeight];
[self setFrameSize: scRect.size];
[self setNeedsSizing: YES];
}
else if (flag == NO && _horizontal == YES)
{
GSIArray a = NSMapGet(viewInfo, self);
if (a != 0)
{
GSIArrayEmpty(a);
NSZoneFree(NSDefaultMallocZone(), a);
NSMapRemove(viewInfo, self);
}
[self setNeedsSizing: YES];
}
_horizontal = flag;
}
- (BOOL) isHorizontal
{
return _horizontal;
}
- (void) setFont: (NSFont*)font
{
ASSIGN(_font, font);
if (_font != nil)
{
const CGFloat themeHeight = [[GSTheme theme] menuItemHeight];
NSRect r;
r = [_font boundingRectForFont];
/* Should make up 110, 20 for default font */
_cellSize = NSMakeSize (r.size.width * 10., r.size.height + 3.);
if (_cellSize.height < themeHeight)
_cellSize.height = themeHeight;
[self setNeedsSizing: YES];
}
}
- (NSFont*) font
{
return _font;
}
- (void) setHighlightedItemIndex: (NSInteger)index
{
NSMenuItemCell *aCell;
if (index == _highlightedItemIndex)
return;
// Unhighlight old
if (_highlightedItemIndex != -1)
{
aCell = [self menuItemCellForItemAtIndex: _highlightedItemIndex];
[aCell setHighlighted: NO];
[self setNeedsDisplayForItemAtIndex: _highlightedItemIndex];
}
// Set ivar to new index.
_highlightedItemIndex = index;
// Highlight new
if (_highlightedItemIndex != -1)
{
aCell = [self menuItemCellForItemAtIndex: _highlightedItemIndex];
[aCell setHighlighted: YES];
[self setNeedsDisplayForItemAtIndex: _highlightedItemIndex];
}
}
- (NSInteger) highlightedItemIndex
{
return _highlightedItemIndex;
}
- (void) setMenuItemCell: (NSMenuItemCell *)cell
forItemAtIndex: (NSInteger)index
{
NSMenuItem *anItem = [_items_link objectAtIndex: index];
[_itemCells replaceObjectAtIndex: index withObject: cell];
[cell setMenuItem: anItem];
[cell setMenuView: self];
if ([self highlightedItemIndex] == index)
[cell setHighlighted: YES];
else
[cell setHighlighted: NO];
// Mark the new cell and the menu view as needing resizing.
[cell setNeedsSizing: YES];
[self setNeedsSizing: YES];
[self setNeedsDisplayForItemAtIndex: index];
}
- (NSMenuItemCell*) menuItemCellForItemAtIndex: (NSInteger)index
{
if ((index >= 0) && (index < [_itemCells count]))
return [_itemCells objectAtIndex: index];
else
return nil;
}
- (NSMenuView*) attachedMenuView
{
return [[_attachedMenu attachedMenu] menuRepresentation];
}
- (NSMenu*) attachedMenu
{
return [_attachedMenu attachedMenu];
}
- (BOOL) isAttached
{
return [_attachedMenu isAttached];
}
- (BOOL) isTornOff
{
return [_attachedMenu isTornOff];
}
- (void) setHorizontalEdgePadding: (float)pad
{
_horizontalEdgePad = pad;
[self setNeedsSizing: YES];
}
- (float) horizontalEdgePadding
{
return _horizontalEdgePad;
}
/*
* Notification Methods
*/
- (void) itemChanged: (NSNotification*)notification
{
int index = [[[notification userInfo] objectForKey: @"NSMenuItemIndex"]
intValue];
NSMenuItemCell *aCell = [self menuItemCellForItemAtIndex: index];
// Enabling of the item may have changed
[aCell setEnabled: [[aCell menuItem] isEnabled]];
// Mark the cell associated with the item as needing resizing.
[aCell setNeedsSizing: YES];
// Mark the menu view as needing to be resized.
[self setNeedsSizing: YES];
[self setNeedsDisplayForItemAtIndex: index];
}
- (void) itemAdded: (NSNotification*)notification
{
int index = [[[notification userInfo]
objectForKey: @"NSMenuItemIndex"] intValue];
NSMenuItem *anItem = [_items_link objectAtIndex: index];
id aCell = [NSMenuItemCell new];
int wasHighlighted = _highlightedItemIndex;
// FIXME do we need to differentiate between popups and non popups
[aCell setMenuItem: anItem];
[aCell setMenuView: self];
[aCell setFont: _font];
/* Unlight the previous highlighted cell if the index of the highlighted
* cell will be ruined up by the insertion of the new cell. */
if (wasHighlighted >= index)
{
[self setHighlightedItemIndex: -1];
}
[_itemCells insertObject: aCell atIndex: index];
/* Restore the highlighted cell, with the new index for it. */
if (wasHighlighted >= index)
{
/* Please note that if wasHighlighted == -1, it shouldn't be possible
* to be here. */
[self setHighlightedItemIndex: ++wasHighlighted];
}
[aCell setNeedsSizing: YES];
RELEASE(aCell);
// Mark the menu view as needing to be resized.
[self setNeedsSizing: YES];
[self setNeedsDisplay: YES];
}
- (void) itemRemoved: (NSNotification*)notification
{
int wasHighlighted = [self highlightedItemIndex];
int index = [[[notification userInfo] objectForKey: @"NSMenuItemIndex"]
intValue];
if (index <= wasHighlighted)
{
[self setHighlightedItemIndex: -1];
}
[_itemCells removeObjectAtIndex: index];
if (wasHighlighted > index)
{
[self setHighlightedItemIndex: --wasHighlighted];
}
// Mark the menu view as needing to be resized.
[self setNeedsSizing: YES];
[self setNeedsDisplay: YES];
}
/*
* Working with Submenus.
*/
- (void) detachSubmenu
{
NSMenu *attachedMenu = [_attachedMenu attachedMenu];
NSMenuView *attachedMenuView;
if (!attachedMenu)
return;
attachedMenuView = [attachedMenu menuRepresentation];
[attachedMenuView detachSubmenu];
NSDebugLLog (@"NSMenu", @"detach submenu: %@ from: %@",
attachedMenu, _attachedMenu);
if ([attachedMenu isTransient])
{
[attachedMenu closeTransient];
}
else
{
[attachedMenu close];
// Unselect the active item
[self setHighlightedItemIndex: -1];
}
}
- (void) attachSubmenuForItemAtIndex: (NSInteger)index
{
/*
* Transient menus are used for torn-off menus, which are already on the
* screen and for sons of transient menus. As transients disappear as
* soon as we release the mouse the user will be able to leave submenus
* open on the screen and interact with other menus at the same time.
*/
NSMenu *attachableMenu;
if (index < 0)
{
return;
}
attachableMenu = [[_items_link objectAtIndex: index] submenu];
if ([attachableMenu isTornOff] || [_attachedMenu isTransient])
{
NSDebugLLog (@"NSMenu", @"Will open transient: %@", attachableMenu);
[attachableMenu displayTransient];
[[attachableMenu menuRepresentation] setHighlightedItemIndex: -1];
}
else
{
NSDebugLLog (@"NSMenu", @"Will open normal: %@", attachableMenu);
// FIXME: Only resize when needed
[attachableMenu sizeToFit];
[[attachableMenu window] setFrameOrigin: [self locationForSubmenu: attachableMenu]];
[_attachedMenu _attachMenu: attachableMenu];
[[attachableMenu window] orderFrontRegardless];
}
}
/*
* Calculating Menu Geometry
*/
- (void) update
{
BOOL needTitleView;
BOOL rootIsAppMenu;
NSInterfaceStyle style;
NSDebugLLog (@"NSMenu", @"update called on menu view");
/*
* Ensure that a title view exists only if needed.
*/
style = NSInterfaceStyleForKey(@"NSMenuInterfaceStyle", nil);
if (style == NSWindows95InterfaceStyle || style == NSMacintoshInterfaceStyle)
{
needTitleView = NO;
}
else if (_attachedMenu == nil)
{
needTitleView = NO;
}
else if ([self _rootIsHorizontal: &rootIsAppMenu] == YES)
{
needTitleView = NO;
}
else if (rootIsAppMenu == YES)
{
needTitleView = YES;
}
else
{
// Popup menu doesn't need title bar
needTitleView = ([_attachedMenu _ownedByPopUp] == YES) ? NO : YES;
}
if (needTitleView == YES && _titleView == nil)
{
Class titleViewClass = [[GSTheme theme] titleViewClassForMenuView: self];
_titleView = [[titleViewClass alloc] initWithOwner: _attachedMenu];
[self addSubview: _titleView];
RELEASE(_titleView);
}
if (needTitleView == NO && _titleView != nil)
{
[_titleView removeFromSuperview];
_titleView = nil;
}
if (_titleView != nil)
{
if ([_attachedMenu isTornOff] && ![_attachedMenu isTransient])
{
[_titleView
addCloseButtonWithAction: @selector(_performMenuClose:)];
}
else
{
[_titleView removeCloseButton];
}
}
// Ask the menu to update itself. This will call sizeToFit if needed.
[_attachedMenu update];
}
- (void) setNeedsSizing: (BOOL)flag
{
_needsSizing = flag;
}
- (BOOL) needsSizing
{
return _needsSizing;
}
- (CGFloat) heightForItem: (NSInteger)idx
{
NSMenuItemCell *cell = [self menuItemCellForItemAtIndex: idx];
if (cell != nil)
{
NSMenuItem *item = [cell menuItem];
if ([item isSeparatorItem])
{
return [[GSTheme theme] menuSeparatorHeight];
}
}
return _cellSize.height;
}
- (CGFloat) yOriginForItem: (NSInteger)item
{
const NSInteger count = [_itemCells count];
CGFloat total = 0;
if (item >= 0)
{
NSInteger i = 0;
for (i = (count - 1); i > item; i--)
{
total += [self heightForItem: i];
}
}
return total;
}
- (CGFloat) totalHeight
{
CGFloat total = 0;
NSUInteger i = 0;
for (i = 0; i < [_itemCells count]; i++)
{
total += [self heightForItem: i];
}
return total;
}
- (void) sizeToFit
{
BOOL isPullDown =
[_attachedMenu _ownedByPopUp] && [[_attachedMenu _owningPopUp] pullsDown];
if (_horizontal == YES)
{
unsigned i;
unsigned howMany = [_itemCells count];
float currentX = HORIZONTAL_MENU_LEFT_PADDING;
// NSRect scRect = [[NSScreen mainScreen] frame];
GSIArrayRemoveAllItems(cellRects);
/*
scRect.size.height = [NSMenuView menuBarHeight];
[self setFrameSize: scRect.size];
_cellSize.height = scRect.size.height;
*/
_cellSize.height = [NSMenuView menuBarHeight];
if (howMany && isPullDown)
{
GSCellRect elem;
elem.rect = NSMakeRect (currentX,
0,
(2 * _horizontalEdgePad),
[self heightForItem: 0]);
GSIArrayAddItem(cellRects, (GSIArrayItem)elem);
currentX += 2 * _horizontalEdgePad;
}
for (i = isPullDown ? 1 : 0; i < howMany; i++)
{
GSCellRect elem;
NSMenuItemCell *aCell = [self menuItemCellForItemAtIndex: i];
float titleWidth = [aCell titleWidth];
if ([aCell imageWidth])
{
titleWidth += [aCell imageWidth] + GSCellTextImageXDist;
}
elem.rect = NSMakeRect (currentX,
0,
(titleWidth + (2 * _horizontalEdgePad)),
[self heightForItem: i]);
GSIArrayAddItem(cellRects, (GSIArrayItem)elem);
currentX += titleWidth + (2 * _horizontalEdgePad);
}
}
else
{
unsigned i;
unsigned howMany = [_itemCells count];
unsigned wideTitleView = 1;
float neededImageAndTitleWidth = 0.0;
float neededKeyEquivalentWidth = 0.0;
float neededStateImageWidth = 0.0;
float accumulatedOffset = 0.0;
float popupImageWidth = 0.0;
float menuBarHeight = 0.0;
if (_titleView)
{
NSMenu *m = [_attachedMenu supermenu];
NSMenuView *r = [m menuRepresentation];
neededImageAndTitleWidth = [_titleView titleSize].width;
if (r != nil && [r isHorizontal] == YES)
{
NSMenuItemCell *msr;
msr = [r menuItemCellForItemAtIndex:
[m indexOfItemWithTitle: [_attachedMenu title]]];
neededImageAndTitleWidth
= [msr titleWidth] + GSCellTextImageXDist;
}
if (_titleView)
menuBarHeight = [[self class] menuBarHeight];
else
menuBarHeight += _leftBorderOffset;
}
else
{
menuBarHeight += _leftBorderOffset;
}
for (i = isPullDown ? 1 : 0; i < howMany; i++)
{
float aStateImageWidth;
float aTitleWidth;
float anImageWidth;
float anImageAndTitleWidth;
float aKeyEquivalentWidth;
NSMenuItemCell *aCell = [self menuItemCellForItemAtIndex: i];
// State image area.
aStateImageWidth = [aCell stateImageWidth];
// Title and Image area.
aTitleWidth = [aCell titleWidth];
anImageWidth = [aCell imageWidth];
// Key equivalent area.
aKeyEquivalentWidth = [aCell keyEquivalentWidth];
switch ([aCell imagePosition])
{
case NSNoImage:
anImageAndTitleWidth = aTitleWidth;
break;
case NSImageOnly:
anImageAndTitleWidth = anImageWidth;
break;
case NSImageLeft:
case NSImageRight:
anImageAndTitleWidth
= anImageWidth + aTitleWidth + GSCellTextImageXDist;
break;
case NSImageBelow:
case NSImageAbove:
case NSImageOverlaps:
default:
if (aTitleWidth > anImageWidth)
anImageAndTitleWidth = aTitleWidth;
else
anImageAndTitleWidth = anImageWidth;
break;
}
if (aStateImageWidth > neededStateImageWidth)
neededStateImageWidth = aStateImageWidth;
if (anImageAndTitleWidth > neededImageAndTitleWidth)
neededImageAndTitleWidth = anImageAndTitleWidth;
if (aKeyEquivalentWidth > neededKeyEquivalentWidth)
neededKeyEquivalentWidth = aKeyEquivalentWidth;
// Title view width less than item's left part width
if ((anImageAndTitleWidth + aStateImageWidth)
> neededImageAndTitleWidth)
wideTitleView = 0;
// Popup menu has only one item with nibble or arrow image
if (anImageWidth)
popupImageWidth = anImageWidth;
}
if (isPullDown && howMany)
howMany -= 1;
// Cache the needed widths.
_stateImageWidth = neededStateImageWidth;
_imageAndTitleWidth = neededImageAndTitleWidth;
_keyEqWidth = neededKeyEquivalentWidth;
accumulatedOffset = _horizontalEdgePad;
if (howMany)
{
// Calculate the offsets and cache them.
if (neededStateImageWidth)
{
_stateImageOffset = accumulatedOffset;
accumulatedOffset += neededStateImageWidth += _horizontalEdgePad;
}
if (neededImageAndTitleWidth)
{
_imageAndTitleOffset = accumulatedOffset;
accumulatedOffset += neededImageAndTitleWidth;
}
if (wideTitleView)
{
_keyEqOffset = accumulatedOffset = neededImageAndTitleWidth
+ (3 * _horizontalEdgePad);
}
else
{
_keyEqOffset = accumulatedOffset += (2 * _horizontalEdgePad);
}
accumulatedOffset += neededKeyEquivalentWidth + _horizontalEdgePad;
if ([_attachedMenu supermenu] != nil && neededKeyEquivalentWidth < 8)
{
accumulatedOffset += 8 - neededKeyEquivalentWidth;
}
}
else
{
accumulatedOffset += neededImageAndTitleWidth + 3 + 2;
if ([_attachedMenu supermenu] != nil)
accumulatedOffset += 15;
}
// Calculate frame size.
if (_needsSizing)
{
// Add the border width: 1 for left, 2 for right sides
_cellSize.width = accumulatedOffset + 3;
}
if ([_attachedMenu _ownedByPopUp])
{
_keyEqOffset = _cellSize.width - _keyEqWidth - popupImageWidth;
}
[self setFrameSize: NSMakeSize(_cellSize.width + _leftBorderOffset,
[self totalHeight]
+ menuBarHeight)];
[_titleView setFrame: NSMakeRect (0, [self totalHeight],
NSWidth (_bounds), menuBarHeight)];
}
_needsSizing = NO;
}
- (float) stateImageOffset
{
if (_needsSizing)
[self sizeToFit];
return _stateImageOffset;
}
- (float) stateImageWidth
{
if (_needsSizing)
[self sizeToFit];
return _stateImageWidth;
}
- (float) imageAndTitleOffset
{
if (_needsSizing)
[self sizeToFit];
return _imageAndTitleOffset;
}
- (float) imageAndTitleWidth
{
if (_needsSizing)
[self sizeToFit];
return _imageAndTitleWidth;
}
- (float) keyEquivalentOffset
{
if (_needsSizing)
[self sizeToFit];
return _keyEqOffset;
}
- (float) keyEquivalentWidth
{
if (_needsSizing)
[self sizeToFit];
return _keyEqWidth;
}
- (NSRect) innerRect
{
if (_horizontal == NO)
{
return NSMakeRect (_bounds.origin.x + _leftBorderOffset,
_bounds.origin.y,
_bounds.size.width - _leftBorderOffset,
_bounds.size.height);
}
else
{
return NSMakeRect (_bounds.origin.x,
_bounds.origin.y + _leftBorderOffset,
_bounds.size.width,
_bounds.size.height - _leftBorderOffset);
}
}
- (NSRect) rectOfItemAtIndex: (NSInteger)index
{
if (_needsSizing == YES)
{
[self sizeToFit];
}
// The first item of a pull down menu holds its title and isn't displayed
if (index == 0 && [_attachedMenu _ownedByPopUp] &&
[[_attachedMenu _owningPopUp] pullsDown])
{
return NSZeroRect;
}
if (_horizontal == YES)
{
GSCellRect aRect;
aRect = GSIArrayItemAtIndex(cellRects, index).ext;
return aRect.rect;
}
else
{
NSRect theRect;
theRect.origin.y = [self yOriginForItem: index];
theRect.origin.x = _leftBorderOffset;
theRect.size = _cellSize;
theRect.size.height = [self heightForItem: index];
/* NOTE: This returns the correct NSRect for drawing cells, but nothing
* else (unless we are a popup). This rect will have to be modified for
* event calculation, etc..
*/
return theRect;
}
}
- (NSInteger) indexOfItemAtPoint: (NSPoint)point
{
unsigned howMany = [_itemCells count];
unsigned i;
for (i = 0; i < howMany; i++)
{
NSRect aRect = [self rectOfItemAtIndex: i];
//NSLog(@"indexOfItemAtPoint called for %@ %@ %d %@", self, NSStringFromPoint(point), i, NSStringFromRect(aRect));
aRect.origin.x -= _leftBorderOffset;
aRect.size.width += _leftBorderOffset;
// For horizontal menus, clicking in the left padding should be treated
// as hitting the first menu item.
if (_horizontal == YES && i == 0)
{
aRect.origin.x -= HORIZONTAL_MENU_LEFT_PADDING;
aRect.size.width += HORIZONTAL_MENU_LEFT_PADDING;
}
if (NSMouseInRect(point, aRect, NO))
return (int)i;
}
return -1;
}
- (void) setNeedsDisplayForItemAtIndex: (NSInteger)index
{
NSRect aRect;
aRect = [self rectOfItemAtIndex: index];
aRect.origin.x -= _leftBorderOffset;
aRect.size.width += _leftBorderOffset;
[self setNeedsDisplayInRect: aRect];
}
- (NSPoint) locationForSubmenu: (NSMenu *)aSubmenu
{
NSRect frame = [_window frame];
NSRect submenuFrame;
const CGFloat submenuHorizOverlap = [[GSTheme theme] menuSubmenuHorizontalOverlap];
const CGFloat submenuVertOverlap = [[GSTheme theme] menuSubmenuVerticalOverlap];
if (_needsSizing)
[self sizeToFit];
if (aSubmenu)
submenuFrame = [[[aSubmenu menuRepresentation] window] frame];
else
submenuFrame = NSZeroRect;
if (_horizontal == NO)
{
if (NSInterfaceStyleForKey(@"NSMenuInterfaceStyle",
[aSubmenu menuRepresentation])
== GSWindowMakerInterfaceStyle)
{
NSRect aRect = [self convertRect: [self rectOfItemAtIndex:
[_attachedMenu indexOfItemWithSubmenu: aSubmenu]] toView: nil];
NSPoint subOrigin = [_window convertBaseToScreen: aRect.origin];
return NSMakePoint (NSMaxX(frame) - submenuHorizOverlap,
subOrigin.y - NSHeight(submenuFrame) - 2 +
2*[NSMenuView menuBarHeight]);
}
else if ([self _rootIsHorizontal: 0] == YES)
{
NSRect aRect = [self convertRect: [self rectOfItemAtIndex:
[_attachedMenu indexOfItemWithSubmenu: aSubmenu]] toView: nil];
NSPoint subOrigin = [_window convertBaseToScreen: aRect.origin];
// FIXME ... why is the offset +1 needed below?
return NSMakePoint (NSMaxX(frame) - submenuHorizOverlap,
subOrigin.y - NSHeight(submenuFrame) + aRect.size.height + 1);
}
else
{
return NSMakePoint(NSMaxX(frame) - submenuHorizOverlap,
NSMaxY(frame) - NSHeight(submenuFrame));
}
}
else
{
NSRect aRect = [self convertRect: [self rectOfItemAtIndex:
[_attachedMenu indexOfItemWithSubmenu: aSubmenu]] toView: nil];
NSPoint subOrigin = [_window convertBaseToScreen: aRect.origin];
/* If menu is in window, we add +1 for don't lose the track when
the user move the mouse from the horizontal menu to a submenu.*/
if (NSInterfaceStyleForKey(@"NSMenuInterfaceStyle", nil) ==
NSWindows95InterfaceStyle)
{
return NSMakePoint(subOrigin.x,
subOrigin.y - NSHeight(submenuFrame) + 1 + submenuVertOverlap);
}
else
{
return NSMakePoint(subOrigin.x,
subOrigin.y - NSHeight(submenuFrame) + submenuVertOverlap);
}
}
}
- (void) resizeWindowWithMaxHeight: (float)maxHeight
{
// FIXME set the menuview's window to max height in order to keep on screen?
}
- (void) setWindowFrameForAttachingToRect: (NSRect)screenRect
onScreen: (NSScreen*)screen
preferredEdge: (NSRectEdge)edge
popUpSelectedItem: (NSInteger)selectedItemIndex
{
NSRect r;
NSRect cellFrame;
NSRect popUpFrame;
int items = [_itemCells count];
BOOL growHeight = YES;
BOOL resizeCell = NO;
CGFloat borderOffsetInBaseCoords;
// Our window needs to have a nonzero size for the
// -convertRect:fromView: and relatead methods to work.
[_window setFrame: NSMakeRect(0,0,1,1) display: NO];
// Make sure the menu entries are up to date
[self update];
if (_needsSizing)
[self sizeToFit];
/* FIXME: Perhaps all of this belongs into NSPopupButtonCell and
should be used to determine the proper screenRect to pass on into
this method.
*/
/* certain style of pulldowns don't want sizing on the _cellSize.height */
if ([_attachedMenu _ownedByPopUp])
{
NSPopUpButtonCell *bcell;
bcell = [_attachedMenu _owningPopUp];
if ([bcell pullsDown])
{
if ([bcell isBordered] == NO)
{
growHeight = NO;
}
else
{
switch ([bcell bezelStyle])
{
case NSRegularSquareBezelStyle:
case NSShadowlessSquareBezelStyle:
growHeight = NO;
break;
default:
break;
}
}
}
}
cellFrame = screenRect;
/*
we should have the calculated cell size, grow the width
if needed to match the screenRect and vice versa
*/
if (cellFrame.size.width > [self convertSizeToBase: _cellSize].width)
{
_cellSize.width = [self convertSizeFromBase: cellFrame.size].width;
resizeCell = YES;
}
else
{
cellFrame.size.width = [self convertSizeToBase: _cellSize].width;
}
/* certain pop-ups don't want the height resized */
if (growHeight && cellFrame.size.height > [self convertSizeToBase: _cellSize].height)
{
_cellSize.height = [self convertSizeFromBase: cellFrame.size].height;
resizeCell = YES;
}
else
{
cellFrame.size.height = [self convertSizeToBase: _cellSize].height;
}
/*
now sizeToFit again with needs sizing = NO so it doesn't
overwrite _cellSize just recalculate the offsets.
*/
if (resizeCell)
[self sizeToFit];
/*
* Compute the frame. popUpFrame is in screen coordinates
*/
popUpFrame = cellFrame;
borderOffsetInBaseCoords = [self convertSizeToBase: NSMakeSize(_leftBorderOffset, 0)].width;
if (items > 0)
{
float f;
if (_horizontal == NO)
{
f = cellFrame.size.height * (items - 1);
popUpFrame.size.height += f + borderOffsetInBaseCoords;
popUpFrame.origin.y -= f;
popUpFrame.size.width += borderOffsetInBaseCoords;
popUpFrame.origin.x -= borderOffsetInBaseCoords;
// If the menu is a pull down menu the first item, which would
// appear at the top of the menu, holds the title and is omitted
if ([_attachedMenu _ownedByPopUp])
{
if ([[_attachedMenu _owningPopUp] pullsDown])
{
popUpFrame.size.height -= cellFrame.size.height;
popUpFrame.origin.y += cellFrame.size.height;
}
}
// Compute position for popups, if needed
if (selectedItemIndex != -1)
{
popUpFrame.origin.y
+= cellFrame.size.height * selectedItemIndex;
}
}
else
{
f = cellFrame.size.width * (items - 1);
popUpFrame.size.width += f;
// If the menu is a pull down menu the first item holds the
// title and is omitted
if ([_attachedMenu _ownedByPopUp])
{
if ([[_attachedMenu _owningPopUp] pullsDown])
{
popUpFrame.size.width -= cellFrame.size.width;
}
}
// Compute position for popups, if needed
if (selectedItemIndex != -1)
{
popUpFrame.origin.x -= cellFrame.size.width * selectedItemIndex;
}
}
}
// Update position, if needed, using the preferredEdge
if (selectedItemIndex == -1)
{
NSRect screenFrame;
if (screen == nil)
screen = [NSScreen mainScreen];
screenFrame = [screen frame];
popUpFrame.origin.y -= cellFrame.size.height;
if (edge == NSMinYEdge || edge == NSMaxYEdge)
{
NSRect minYFrame = popUpFrame;
NSRect maxYFrame = popUpFrame;
// show menu above or below the cell depending on the preferred edge
// if the menu would be partially off screen on that edge use the
// opposite edge or at least the one where more space is left
maxYFrame.origin.y +=
maxYFrame.size.height + screenRect.size.height - _leftBorderOffset;
if (edge == NSMinYEdge)
{
if ((NSMinY(minYFrame) < NSMinY(screenFrame))
&& ((NSMaxY(maxYFrame) <= NSMaxY(screenFrame))
|| (NSMaxY(screenFrame) - NSMaxY(screenRect) >
NSMinY(screenRect) - NSMinY(screenFrame))))
{
edge = NSMaxYEdge;
}
}
else
{
if ((NSMaxY(maxYFrame) > NSMaxY(screenFrame))
&& ((NSMinY(minYFrame) >= NSMinY(screenFrame))
|| (NSMaxY(screenFrame) - NSMaxY(screenRect) <
NSMinY(screenRect) - NSMinY(screenFrame))))
{
edge = NSMinYEdge;
}
}
popUpFrame = edge == NSMinYEdge ? minYFrame : maxYFrame;
}
else
{
NSRect minXFrame = popUpFrame;
NSRect maxXFrame = popUpFrame;
minXFrame.origin.y += screenRect.size.height;
minXFrame.origin.x -= minXFrame.size.width;
maxXFrame.origin.y += screenRect.size.height;
maxXFrame.origin.x += screenRect.size.width + _leftBorderOffset;
// show menu on the opposite edge if it does not fit on screen on
// the preferred edge
if (edge == NSMinXEdge)
{
if ((NSMinX(minXFrame) < NSMinX(screenFrame))
&& ((NSMaxX(maxXFrame) <= NSMaxX(screenFrame))
|| (NSMaxX(screenFrame) - NSMaxX(screenRect) >
NSMinX(screenRect) - NSMinX(screenFrame))))
{
edge = NSMaxXEdge;
}
}
else
{
if ((NSMaxX(maxXFrame) > NSMaxX(screenFrame))
&& ((NSMinX(minXFrame) >= NSMinX(screenFrame))
|| (NSMaxX(screenFrame) - NSMaxX(screenRect) <
NSMinX(screenRect) - NSMinX(screenFrame))))
{
edge = NSMinXEdge;
}
}
popUpFrame = edge == NSMinXEdge ? minXFrame : maxXFrame;
}
}
// Get the frameRect
{
NSSize contentSize = [self convertSizeFromBase: popUpFrame.size];
NSRect contentRect = NSMakeRect(popUpFrame.origin.x,
popUpFrame.origin.y,
contentSize.width,
contentSize.height);
r = [_window frameRectForContentRect: contentRect];
// Set the window frame. r should be identical to popUpFrame except with
// any borders the window wanted to add.
[_window setFrame: r display: NO];
}
}
/*
* Drawing.
*/
- (BOOL) isOpaque
{
return NO;
}
- (void) drawRect: (NSRect)rect
{
[[GSTheme theme] drawMenuRect: rect
inView: self
isHorizontal: _horizontal
itemCells: _itemCells];
}
/*
* Event Handling
*/
- (void) performActionWithHighlightingForItemAtIndex: (NSInteger)index
{
NSMenu *candidateMenu = _attachedMenu;
NSMenuView *targetMenuView;
int indexToHighlight = index;
int oldHighlightedIndex;
for (;;)
{
NSMenu *superMenu = [candidateMenu supermenu];
if (superMenu == nil
|| [candidateMenu isAttached]
|| [candidateMenu isTornOff])
{
targetMenuView = [candidateMenu menuRepresentation];
break;
}
else
{
indexToHighlight = [superMenu indexOfItemWithSubmenu: candidateMenu];
candidateMenu = superMenu;
}
}
oldHighlightedIndex = [targetMenuView highlightedItemIndex];
[targetMenuView setHighlightedItemIndex: indexToHighlight];
/* We need to let the run loop run a little so that the fact that
* the item is highlighted gets displayed on screen.
*/
[[NSRunLoop currentRunLoop]
runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.1]];
[_attachedMenu performActionForItemAtIndex: index];
if (![_attachedMenu _ownedByPopUp])
{
[targetMenuView setHighlightedItemIndex: oldHighlightedIndex];
}
}
#define MOVE_THRESHOLD_DELTA 2.0
#define DELAY_MULTIPLIER 10
- (BOOL) _executeItemAtIndex: (int)indexOfActionToExecute
removeSubmenu: (BOOL)subMenusNeedRemoving
{
NSInterfaceStyle style =
NSInterfaceStyleForKey(@"NSMenuInterfaceStyle", self);
if (indexOfActionToExecute >= 0
&& [_attachedMenu attachedMenu] != nil && [_attachedMenu attachedMenu] ==
[[_items_link objectAtIndex: indexOfActionToExecute] submenu])
{
if (style == NSMacintoshInterfaceStyle)
{
// On Macintosh, clicking on or releasing the mouse over a
// submenu item always closes the menu (if it is open) and
// ends menu tracking. We do the same here, too.
[self detachSubmenu];
return YES;
}
if (style == NSWindows95InterfaceStyle)
{
return YES;
}
if (subMenusNeedRemoving)
{
[self detachSubmenu];
}
// Clicked on a submenu.
return NO;
}
return YES;
}
- (BOOL) _trackWithEvent: (NSEvent*)event
startingMenuView: (NSMenuView*)mainWindowMenuView
{
NSUInteger eventMask = NSPeriodicMask;
NSDate *theDistantFuture = [NSDate distantFuture];
NSPoint lastLocation = {0,0};
BOOL justAttachedNewSubmenu = NO;
BOOL subMenusNeedRemoving = YES;
BOOL shouldFinish = YES;
BOOL popUpProcessEvents = [[GSTheme theme] doesProcessEventsForPopUpMenu];
int delayCount = 0;
int indexOfActionToExecute = -1;
int firstIndex = -1;
NSInterfaceStyle style =
NSInterfaceStyleForKey(@"NSMenuInterfaceStyle", self);
NSEvent *original;
NSEventType type;
/*
* The original event is unused except to determine whether the method
* was invoked in response to a right or left mouse down.
* We pass the same event on when we want tracking to move into a
* submenu.
*/
original = AUTORELEASE(RETAIN(event));
type = [event type];
/**
* The following event tracking run loop can run for a long time, during
* which new windows (for submenus) are created and put on screen. The
* window manager might not place the menus where we ask them to be placed
* (e.g. Metacity will move menus so they don't overlap the GNOME
* top-of-screen panel).
*
* The mechanism which updates an NSWindow's frame when an external force
* (such as the window manager) moves a window is an NSAppKitDefined event.
* Since we need the frames of the menu windows to be accurate to know which
* menu item the cursor is actually over, and since we are running our own
* event loop and the NSAppKitDefined events aren't handled for us, we need
* to request them ourselves and forward them to the relevant window.
*
* NOTE: While it seems messy to have to handle these events, Cocoa doesn't
* handle them automatically either for code which goes in to an event
* tracking loop.
*/
eventMask |= NSAppKitDefinedMask;
eventMask |= NSRightMouseUpMask | NSRightMouseDraggedMask;
eventMask |= NSRightMouseDownMask;
eventMask |= NSOtherMouseUpMask | NSOtherMouseDraggedMask;
eventMask |= NSOtherMouseDownMask;
eventMask |= NSLeftMouseUpMask | NSLeftMouseDraggedMask;
eventMask |= NSLeftMouseDownMask;
/* We need know if the user press a modifier key to close the menu
when the menu is in a window or when is owned by a popup and theme
process events. */
if (style == NSWindows95InterfaceStyle || popUpProcessEvents)
{
eventMask |= NSFlagsChangedMask;
}
// Ignore the first mouse up if menu is horizontal.
if ([self isHorizontal] == YES ||
// Or if menu is transient and style is NSWindows95InterfaceStyle.
([[self menu] isTransient] && style == NSWindows95InterfaceStyle) ||
/* Or to mimic Mac OS X behavior for pop up menus. If the user
presses the mouse button over a pop up button and then drags the mouse
over the menu, the menu is closed when the user releases the mouse. On
the other hand, when the user clicks on the button and then moves the
mouse the menu is closed upon the next mouse click. */
([[self menu] _ownedByPopUp] && (style == NSMacintoshInterfaceStyle ||
popUpProcessEvents)))
{
/*
* Ignore the first mouse up if nothing interesting has happened.
*/
shouldFinish = NO;
}
do
{
if (type == NSFlagsChanged)
{
/* Close the menu if the user press a modifier key and menu
is in a window */
if (mainWindowMenuView != nil)
{
[self setHighlightedItemIndex: -1];
[[[mainWindowMenuView menu] attachedMenu] close];
return NO;
}
/* Close the menu if is owned by a popup and theme process events */
if ([[self menu] _ownedByPopUp] && popUpProcessEvents)
{
[[[self menu] _owningPopUp] dismissPopUp];
return NO;
}
}
if (type == NSLeftMouseUp ||
type == NSRightMouseUp ||
type == NSOtherMouseUp)
{
shouldFinish = YES;
}
if (type == NSPeriodic || event == original)
{
NSPoint location;
int index;
location = [_window mouseLocationOutsideOfEventStream];
index = [self indexOfItemAtPoint:
[self convertPoint: location fromView: nil]];
if (event == original)
{
firstIndex = index;
}
if (index != firstIndex)
{
shouldFinish = YES;
}
/*
* 1 - if menus is only partly visible and the mouse is at the
* edge of the screen we move the menu so it will be visible.
*/
if ([_attachedMenu isPartlyOffScreen])
{
NSPoint pointerLoc = [_window convertBaseToScreen: location];
NSRect screenFrame = [[_window screen] visibleFrame];
/*
* The +/-1 in the y - direction is because the flipping
* between X-coordinates and GNUstep coordinates let the
* GNUstep screen coordinates start with 1.
*/
if (pointerLoc.x == 0 || pointerLoc.y == 1
|| pointerLoc.x == screenFrame.size.width - 1
|| pointerLoc.y == screenFrame.size.height)
[_attachedMenu shiftOnScreen];
}
/*
* 2 - Check if we have to reset the justAttachedNewSubmenu
* flag to NO.
*/
if (justAttachedNewSubmenu && index != -1
&& index != _highlightedItemIndex)
{
if (location.x - lastLocation.x > MOVE_THRESHOLD_DELTA)
{
delayCount ++;
if (delayCount >= DELAY_MULTIPLIER)
{
justAttachedNewSubmenu = NO;
}
}
else
{
justAttachedNewSubmenu = NO;
}
}
// 3 - If we have moved outside this menu, take appropriate action
if (index == -1)
{
NSPoint locationInScreenCoordinates;
NSWindow *windowUnderMouse;
NSMenu *candidateMenu;
subMenusNeedRemoving = NO;
locationInScreenCoordinates
= [_window convertBaseToScreen: location];
/*
* 3a - Check if moved into one of the ancestor menus.
* This is tricky, there are a few possibilities:
* We are a transient attached menu of a
* non-transient menu
* We are a non-transient attached menu
* We are a root: isTornOff of AppMenu
*/
candidateMenu = [_attachedMenu supermenu];
while (candidateMenu
&& !NSMouseInRect (locationInScreenCoordinates,
[[candidateMenu window] frame], NO) // not found yet
&& (! ([candidateMenu isTornOff]
&& ![candidateMenu isTransient])) // no root of display tree
&& [candidateMenu isAttached]) // has displayed parent
{
candidateMenu = [candidateMenu supermenu];
}
if (candidateMenu != nil
&& NSMouseInRect (locationInScreenCoordinates,
[[candidateMenu window] frame], NO))
{
BOOL candidateMenuResult;
NSMenuView *subMenuView = [[candidateMenu attachedMenu] menuRepresentation];
// The call to fetch attachedMenu is not needed. But putting
// it here avoids flicker when we go back to an ancestor
// menu and the attached menu is already correct.
[subMenuView detachSubmenu];
// Reset highlighted index for this menu.
// This way if we return to this submenu later there
// won't be a highlighted item.
[subMenuView setHighlightedItemIndex: -1];
candidateMenuResult = [[candidateMenu menuRepresentation]
_trackWithEvent: original
startingMenuView: mainWindowMenuView];
return candidateMenuResult;
}
// 3b - Check if we enter the attached submenu
windowUnderMouse = [[_attachedMenu attachedMenu] window];
if (windowUnderMouse != nil
&& NSMouseInRect (locationInScreenCoordinates,
[windowUnderMouse frame], NO))
{
BOOL wasTransient = [_attachedMenu isTransient];
BOOL subMenuResult;
subMenuResult
= [[self attachedMenuView] _trackWithEvent: original
startingMenuView: mainWindowMenuView];
if (subMenuResult
&& wasTransient == [_attachedMenu isTransient])
{
[self detachSubmenu];
}
return subMenuResult;
}
/* We track the menu correctly when this is located
in a window */
if (mainWindowMenuView != nil)
{
// If the user moves the mouse into the main window
// horizontal menu, start tracking again.
NSWindow *mainWindow = [mainWindowMenuView window];
NSPoint locationInMainWindow = [mainWindow
convertScreenToBase: locationInScreenCoordinates];
if ([mainWindowMenuView
hitTest: locationInMainWindow] != nil)
{
int index = [mainWindowMenuView indexOfItemAtPoint:
[mainWindowMenuView
convertPoint: locationInMainWindow
fromView: nil]];
if (index != -1 &&
index != [mainWindowMenuView highlightedItemIndex])
{
[self setHighlightedItemIndex: -1];
return [mainWindowMenuView
_trackWithEvent: original
startingMenuView: mainWindowMenuView];
}
}
}
}
// 4 - We changed the selected item and should update.
if (!justAttachedNewSubmenu && index != _highlightedItemIndex)
{
subMenusNeedRemoving = NO;
[self detachSubmenu];
[self setHighlightedItemIndex: index];
// WO: Question? Why the ivar _items_link
if (index >= 0 && [[_items_link objectAtIndex: index] submenu])
{
[self attachSubmenuForItemAtIndex: index];
justAttachedNewSubmenu = YES;
delayCount = 0;
}
}
// Update last seen location for the justAttachedNewSubmenu logic.
lastLocation = location;
}
do
{
event = [NSApp nextEventMatchingMask: eventMask
untilDate: theDistantFuture
inMode: NSEventTrackingRunLoopMode
dequeue: YES];
type = [event type];
if (type == NSAppKitDefined)
{
[[event window] sendEvent: event];
}
}
while (type == NSAppKitDefined);
}
while ((type != NSLeftMouseUp &&
type != NSRightMouseUp &&
type != NSOtherMouseUp) || shouldFinish == NO);
/*
* Ok, we released the mouse
* There are now a few possibilities:
* A - We released the mouse outside the menu.
* Then we want the situation as it was before
* we entered everything.
* B - We released the mouse on a submenu item
* (i) - this was highlighted before we started clicking:
* Remove attached menus
* (ii) - this was not highlighted before pressed the mouse button;
* Keep attached menus.
* C - We released the mouse above an ordinary action:
* Execute the action.
*
* In case A, B and C we want the transient menus to be removed
* In case A and C we want to remove the menus that were created
* during the dragging.
*
* So we should do the following things:
*
* 1 - Stop periodic events,
* 2 - Determine the action.
* 3 - Remove the Transient menus from the screen.
* 4 - Perform the action if there is one.
*/
// FIXME
[NSEvent stopPeriodicEvents];
/*
* We need to store this, because _highlightedItemIndex
* will not be valid after we removed this menu from the screen.
*/
indexOfActionToExecute = _highlightedItemIndex;
// remove transient menus. --------------------------------------------
{
NSMenu *currentMenu = _attachedMenu;
while (currentMenu && ![currentMenu isTransient])
{
currentMenu = [currentMenu attachedMenu];
}
while ([currentMenu isTransient] && [currentMenu supermenu])
{
currentMenu = [currentMenu supermenu];
}
[[currentMenu menuRepresentation] detachSubmenu];
if ([currentMenu isTransient])
{
[currentMenu closeTransient];
}
}
if (indexOfActionToExecute == -1)
{
return YES;
}
// Before executing the action, uncapture the mouse
[_window _releaseMouse: self];
/* If we have menu in window, close the menu after select
an option */
if (mainWindowMenuView != nil)
{
if (self != mainWindowMenuView)
{
[mainWindowMenuView setHighlightedItemIndex: -1];
}
[[[mainWindowMenuView menu] attachedMenu] close];
}
if ([self _executeItemAtIndex: indexOfActionToExecute
removeSubmenu: subMenusNeedRemoving] == NO)
{
return NO;
}
[_attachedMenu performActionForItemAtIndex: indexOfActionToExecute];
/*
* Remove highlighting.
* We first check if it still highlighted because it could be the
* case that we choose an action in a transient window which
* has already dissappeared.
*/
if (_highlightedItemIndex >= 0)
{
[self setHighlightedItemIndex: -1];
}
return YES;
}
- (BOOL) trackWithEvent: (NSEvent*)event
{
BOOL result = NO;
NSMenuView *mainWindowMenuView = nil;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName: NSMenuDidBeginTrackingNotification
object: [self menu]];
if (NSInterfaceStyleForKey(@"NSMenuInterfaceStyle", self) ==
NSWindows95InterfaceStyle &&
![[self menu] isTransient] &&
![[self menu] _ownedByPopUp])
{
mainWindowMenuView = self;
}
// Capture the mouse so we get clicks outside the menus and
// GNUstep windows.
[_window _captureMouse: self];
NS_DURING
result = [self _trackWithEvent: event
startingMenuView: mainWindowMenuView];
NS_HANDLER
[_window _releaseMouse: self];
[localException raise];
NS_ENDHANDLER
[_window _releaseMouse: self];
[nc postNotificationName: NSMenuDidEndTrackingNotification
object: [self menu]];
return result;
}
/**
This method is called when the user clicks on a button in the menu.
Or, if a right click happens and the app menu is brought up.
The original position is stored, so we can restore the position of menu.
The position of the menu can change during the event tracking because
the menu will automatillay move when parts are outside the screen and
the user move the mouse pointer to the edge of the screen.
*/
- (void) mouseDown: (NSEvent*)theEvent
{
NSRect currentFrame;
NSRect originalFrame;
NSPoint currentTopLeft;
NSPoint originalTopLeft = NSZeroPoint; /* Silence compiler. */
BOOL restorePosition;
/*
* Only for non transient menus do we want
* to remember the position.
*/
restorePosition = ![_attachedMenu isTransient];
if (restorePosition)
{ // store old position;
originalFrame = [_window frame];
originalTopLeft = originalFrame.origin;
originalTopLeft.y += originalFrame.size.height;
}
[NSEvent startPeriodicEventsAfterDelay: 0.1 withPeriod: 0.01];
[self trackWithEvent: theEvent];
[NSEvent stopPeriodicEvents];
if (restorePosition)
{
currentFrame = [_window frame];
currentTopLeft = currentFrame.origin;
currentTopLeft.y += currentFrame.size.height;
if (NSEqualPoints(currentTopLeft, originalTopLeft) == NO)
{
NSPoint origin = currentFrame.origin;
origin.x += (originalTopLeft.x - currentTopLeft.x);
origin.y += (originalTopLeft.y - currentTopLeft.y);
[_attachedMenu nestedSetFrameOrigin: origin];
}
}
}
- (void) rightMouseDown: (NSEvent*) theEvent
{
[self mouseDown: theEvent];
}
- (void) otherMouseDown: (NSEvent*) theEvent
{
[self mouseDown: theEvent];
}
- (BOOL) performKeyEquivalent: (NSEvent *)theEvent
{
return [_attachedMenu performKeyEquivalent: theEvent];
}
- (void) _themeDidActivate: (NSNotification*)notification
{
// The new theme may have different menu item sizes,
// so the window size for the menu needs to be recalculated.
[[self menu] sizeToFit];
}
/*
* NSCoding Protocol
*
* Normally unused because NSMenu does not encode its NSMenuView since
* NSMenuView is considered a platform specific way of rendering the menu.
*/
- (void) encodeWithCoder: (NSCoder*)encoder
{
[super encodeWithCoder: encoder];
if ([encoder allowsKeyedCoding] == NO)
{
[encoder encodeObject: _itemCells];
[encoder encodeObject: _font];
[encoder encodeValueOfObjCType: @encode(BOOL) at: &_horizontal];
[encoder encodeValueOfObjCType: @encode(float) at: &_horizontalEdgePad];
[encoder encodeValueOfObjCType: @encode(NSSize) at: &_cellSize];
}
}
- (id) initWithCoder: (NSCoder*)decoder
{
self = [super initWithCoder: decoder];
if (!self)
return nil;
if ([decoder allowsKeyedCoding] == NO)
{
[decoder decodeValueOfObjCType: @encode(id) at: &_itemCells];
[_itemCells makeObjectsPerformSelector: @selector(setMenuView:)
withObject: self];
[decoder decodeValueOfObjCType: @encode(id) at: &_font];
[decoder decodeValueOfObjCType: @encode(BOOL) at: &_horizontal];
[decoder decodeValueOfObjCType: @encode(float) at: &_horizontalEdgePad];
[decoder decodeValueOfObjCType: @encode(NSSize) at: &_cellSize];
_highlightedItemIndex = -1;
_needsSizing = YES;
}
return self;
}
@end
@implementation NSMenuView (GNUstepPrivate)
- (NSArray *)_itemCells
{
return _itemCells;
}
@end
|