-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMenuItemCollection.m
95 lines (78 loc) · 2.21 KB
/
MenuItemCollection.m
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
/*
Copyright (c) 2015-2021 hkrn All rights reserved
This file is part of emapp component and it's licensed under Mozilla Public License. see LICENSE.md for more details.
*/
#include "MenuItemCollection.h"
#import <AppKit/AppKit.h>
@implementation MenuItemCollection
@synthesize menu = m_menu;
- (instancetype)initWithTitle:(NSString *)title
{
if (self = [super init]) {
m_menu = [[NSMenu alloc] initWithTitle:title];
m_menu.autoenablesItems = NO;
m_actions = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)clearAllBlocks
{
[m_actions removeAllObjects];
}
- (void)dealloc
{
[self clearAllBlocks];
}
- (void)setParentMenu:(NSMenuItem *)parentMenu
{
parentMenu.submenu = m_menu;
}
- (NSMenuItem *)addItemWithTitle:(NSString *)title
{
return [self addItemWithTitle:title action:nil keyEquivalent:@""];
}
- (NSMenuItem *)addItemWithTitle:(NSString *)title action:(MenuItemActionItemCallback)actionApply
{
return [self addItemWithTitle:title action:actionApply keyEquivalent:@""];
}
- (NSMenuItem *)addItemWithTitle:(NSString *)title
action:(MenuItemActionItemCallback)actionApply
keyEquivalent:(NSString *)keyEquiv
{
NSMenuItem *item = [m_menu addItemWithTitle:title action:@selector(handleBlockCallback:) keyEquivalent:keyEquiv];
item.target = self;
if (actionApply) {
[m_actions setObject:actionApply forKey:title];
}
return item;
}
- (void)addSeparator
{
[m_menu addItem:[NSMenuItem separatorItem]];
}
- (void)removeItemWithTitle:(NSString *)title
{
NSInteger index = [m_menu indexOfItemWithTitle:title];
if (index != -1) {
MenuItemActionItemCallback action = [m_actions objectForKey:title];
if (action) {
[m_actions removeObjectForKey:title];
}
[m_menu removeItemAtIndex:index];
}
}
- (void)removeAllItems
{
[self clearAllBlocks];
[m_menu removeAllItems];
}
- (void)handleBlockCallback:(id)sender
{
NSMenuItem *menuItem = (NSMenuItem *) sender;
NSString *title = [menuItem title];
MenuItemActionItemCallback actionApply = [m_actions objectForKey:title];
if (actionApply) {
actionApply();
}
}
@end