summaryrefslogtreecommitdiffstats
path: root/DDHotKeyCenter.m
blob: a5ae67835fe5c18bd6deb14e12ed174d9b32e7a1 (plain)
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
/*
 DDHotKey -- DDHotKeyCenter.m
 
 Copyright (c) 2012, Dave DeLong <http://www.davedelong.com>
 
 Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
 
 The software is  provided "as is", without warranty of any kind, including all implied warranties of merchantability and fitness. In no event shall the author(s) or copyright holder(s) be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the software or the use or other dealings in the software.
 */

#import "DDHotKeyCenter.h"
#import <Carbon/Carbon.h>
#import <objc/runtime.h>

#if __has_feature(objc_arc)

#define DDHK_HAS_ARC 1
#define DDHK_RETAIN(_o) (_o)
#define DDHK_RELEASE(_o)
#define DDHK_AUTORELEASE(_o) (_o)

#else

#define DDHK_HAS_ARC 0
#define DDHK_RETAIN(_o) [(_o) retain]
#define DDHK_RELEASE(_o) [(_o) release]
#define DDHK_AUTORELEASE(_o) [(_o) autorelease]

#endif

#pragma mark Private Global Declarations

OSStatus dd_hotKeyHandler(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData);
UInt32 dd_translateModifierFlags(NSUInteger flags);

#pragma mark DDHotKey

@interface DDHotKey ()

@property (nonatomic, retain) NSValue *hotKeyRef;
@property (nonatomic) UInt32 hotKeyID;

@end

@implementation DDHotKey {
    id _target;
    SEL _action;
    id _object;
    
    unsigned short _keyCode;
    NSUInteger _modifierFlags;
    DDHotKeyTask _task;
}

- (void) dealloc {
    [[DDHotKeyCenter sharedHotKeyCenter] unregisterHotKey:self];
#if !DDHK_HAS_ARC
    DDHK_RELEASE(_target); _target = nil;
    DDHK_RELEASE(_object); _object = nil;
    DDHK_RELEASE(_hotKeyRef); _hotKeyRef = nil;
    DDHK_RELEASE(_task); _task = nil;
    [super dealloc];
#endif
}

- (void)_setTarget:(id)target {
    if (target != _target) {
        DDHK_RELEASE(_target);
        _target = DDHK_RETAIN(target);
    }
}

- (void)_setAction:(SEL)action {
    _action = action;
}

- (void)_setObject:(id)object {
    if (object != _object) {
        DDHK_RELEASE(_object);
        _object = DDHK_RETAIN(object);
    }
}

- (void)_setKeyCode:(unsigned short)keyCode {
    _keyCode = keyCode;
}

- (void)_setModifierFlags:(NSUInteger)modifierFlags {
    _modifierFlags = modifierFlags;
}

- (void)_setTask:(DDHotKeyTask)task {
    DDHK_RELEASE(_task);
    _task = [task copy];
}

- (NSUInteger)hash {
    return [self keyCode] ^ [self modifierFlags];
}

- (BOOL)isEqual:(id)object {
    BOOL equal = NO;
    if ([object isKindOfClass:[DDHotKey class]]) {
        equal = ([object keyCode] == [self keyCode]);
        equal &= ([object modifierFlags] == [self modifierFlags]);
    }
    return equal;
}

- (NSString *)description {
    NSMutableArray *bits = [NSMutableArray array];
    if ((_modifierFlags & NSControlKeyMask) > 0) { [bits addObject:@"NSControlKeyMask"]; }
    if ((_modifierFlags & NSCommandKeyMask) > 0) { [bits addObject:@"NSCommandKeyMask"]; }
    if ((_modifierFlags & NSShiftKeyMask) > 0) { [bits addObject:@"NSShiftKeyMask"]; }
    if ((_modifierFlags & NSAlternateKeyMask) > 0) { [bits addObject:@"NSAlternateKeyMask"]; }
    
    NSString *flags = [NSString stringWithFormat:@"(%@)", [bits componentsJoinedByString:@" | "]];
    NSString *invokes = @"(block)";
    if ([self target] != nil && [self action] != nil) {
        invokes = [NSString stringWithFormat:@"[%@ %@]", [self target], NSStringFromSelector([self action])];
    }
    return [NSString stringWithFormat:@"%@\n\t(key: %hu\n\tflags: %@\n\tinvokes: %@)", [super description], [self keyCode], flags, invokes];
}

- (void)invokeWithEvent:(NSEvent *)event {
    if (_target != nil && _action != nil && [_target respondsToSelector:_action]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [_target performSelector:_action withObject:event withObject:_object];
#pragma clang diagnostic pop
    } else if (_task != nil) {
        _task(event);
    }
}

- (NSString *)actionString {
    return NSStringFromSelector(_action);
}

@end

#pragma mark DDHotKeyCenter

static DDHotKeyCenter *center = nil;

@implementation DDHotKeyCenter {
    NSMutableSet *_registeredHotKeys;
    UInt32 _nextHotKeyID;
}

+ (id)sharedHotKeyCenter {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        center = [[DDHotKeyCenter alloc] _init];
    });
    return center;
}

+ (id)allocWithZone:(NSZone *)zone {
    if (center == nil) {
        return [super allocWithZone:zone];
    }
    return DDHK_RETAIN(center);
}

- (id)_init {
    self = [super init];
    if (self) {
        _registeredHotKeys = [[NSMutableSet alloc] init];
        _nextHotKeyID = 1;
    }
    return self;
}

- (NSSet *)hotKeysMatchingPredicate:(NSPredicate *)predicate {
    return [_registeredHotKeys filteredSetUsingPredicate:predicate];
}

- (BOOL)hasRegisteredHotKeyWithKeyCode:(unsigned short)keyCode modifierFlags:(NSUInteger)flags {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"keyCode = %hu AND modifierFlags = %lu", keyCode, flags];
    return ([[self hotKeysMatchingPredicate:predicate] count] > 0);
}

- (BOOL)_registerHotKey:(DDHotKey *)hotKey {
    BOOL success = NO;
    
    EventHotKeyID keyID;
    keyID.signature = 'htk1';
    keyID.id = _nextHotKeyID;
    
    EventHotKeyRef carbonHotKey;
    UInt32 flags = dd_translateModifierFlags([hotKey modifierFlags]);
    OSStatus err = RegisterEventHotKey([hotKey keyCode], flags, keyID, GetEventDispatcherTarget(), 0, &carbonHotKey);
    
    //error registering hot key
    if (err != 0) { return NO; }
    
    NSValue *refValue = [NSValue valueWithPointer:carbonHotKey];
    [hotKey setHotKeyRef:refValue];
    [hotKey setHotKeyID:_nextHotKeyID];
    
    _nextHotKeyID++;
    [_registeredHotKeys addObject:hotKey];
    
    return success;
}

- (void)unregisterHotKey:(DDHotKey *)hotKey {
    NSValue *hotKeyRef = [hotKey hotKeyRef];
    if (hotKeyRef) {
        EventHotKeyRef carbonHotKey = (EventHotKeyRef)[hotKeyRef pointerValue];
        UnregisterEventHotKey(carbonHotKey);
        [hotKey setHotKeyRef:nil];
        
        [_registeredHotKeys removeObject:hotKey];
    }
}

- (BOOL)registerHotKeyWithKeyCode:(unsigned short)keyCode modifierFlags:(NSUInteger)flags task:(DDHotKeyTask)task {
    //we can't add a new hotkey if something already has this combo
    if ([self hasRegisteredHotKeyWithKeyCode:keyCode modifierFlags:flags]) { return NO; }
    
    DDHotKey *newHotKey = DDHK_AUTORELEASE([[DDHotKey alloc] init]);
    [newHotKey _setTask:task];
    [newHotKey _setKeyCode:keyCode];
    [newHotKey _setModifierFlags:flags];
    
    return [self _registerHotKey:newHotKey];
}

- (BOOL)registerHotKeyWithKeyCode:(unsigned short)keyCode modifierFlags:(NSUInteger)flags target:(id)target action:(SEL)action object:(id)object {
    //we can't add a new hotkey if something already has this combo
    if ([self hasRegisteredHotKeyWithKeyCode:keyCode modifierFlags:flags]) { return NO; }
    
    //build the hotkey object:
    DDHotKey *newHotKey = DDHK_AUTORELEASE([[DDHotKey alloc] init]);
    [newHotKey _setTarget:target];
    [newHotKey _setAction:action];
    [newHotKey _setObject:object];
    [newHotKey _setKeyCode:keyCode];
    [newHotKey _setModifierFlags:flags];
    return [self _registerHotKey:newHotKey];
}

- (void)unregisterHotKeysMatchingPredicate:(NSPredicate *)predicate {
    //explicitly unregister the hotkey, since relying on the unregistration in -dealloc can be problematic
    @autoreleasepool {
        NSSet *matches = [self hotKeysMatchingPredicate:predicate];
        for (DDHotKey *hotKey in matches) {
            [self unregisterHotKey:hotKey];
        }
    }
}

- (void)unregisterHotKeysWithTarget:(id)target {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"target = %@", target];
    [self unregisterHotKeysMatchingPredicate:predicate];
}

- (void)unregisterHotKeysWithTarget:(id)target action:(SEL)action {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"target = %@ AND actionString = %@", target, NSStringFromSelector(action)];
    [self unregisterHotKeysMatchingPredicate:predicate];
}

- (void)unregisterHotKeyWithKeyCode:(unsigned short)keyCode modifierFlags:(NSUInteger)flags {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"keyCode = %hu AND modifierFlags = %lu", keyCode, flags];
    [self unregisterHotKeysMatchingPredicate:predicate];
}

- (void)unregisterAllHotKeys {
    NSSet *keys = [_registeredHotKeys copy];
    for (DDHotKey *key in keys) {
        [self unregisterHotKey:key];
    }
    DDHK_RELEASE(keys);
}

- (NSSet *)registeredHotKeys {
    return [self hotKeysMatchingPredicate:[NSPredicate predicateWithFormat:@"hotKeyRef != NULL"]];
}

@end

OSStatus dd_hotKeyHandler(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) {
    @autoreleasepool {
        EventHotKeyID hotKeyID;
        GetEventParameter(theEvent, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(hotKeyID),NULL,&hotKeyID);
        
        UInt32 keyID = hotKeyID.id;
        
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"hotKeyID = %u", keyID];
        NSSet *matchingHotKeys = [[DDHotKeyCenter sharedHotKeyCenter] hotKeysMatchingPredicate:predicate];
        if ([matchingHotKeys count] > 1) { NSLog(@"ERROR!"); }
        DDHotKey *matchingHotKey = [matchingHotKeys anyObject];
        
        NSEvent *event = [NSEvent eventWithEventRef:theEvent];
        NSEvent *keyEvent = [NSEvent keyEventWithType:NSKeyUp
                                             location:[event locationInWindow]
                                        modifierFlags:[event modifierFlags]
                                            timestamp:[event timestamp]
                                         windowNumber:-1
                                              context:nil
                                           characters:@""
                          charactersIgnoringModifiers:@""
                                            isARepeat:NO
                                              keyCode:[matchingHotKey keyCode]];
        
        [matchingHotKey invokeWithEvent:keyEvent];
    }
    
    return noErr;
}

UInt32 dd_translateModifierFlags(NSUInteger flags) {
    UInt32 newFlags = 0;
    if ((flags & NSControlKeyMask) > 0) { newFlags |= controlKey; }
    if ((flags & NSCommandKeyMask) > 0) { newFlags |= cmdKey; }
    if ((flags & NSShiftKeyMask) > 0) { newFlags |= shiftKey; }
    if ((flags & NSAlternateKeyMask) > 0) { newFlags |= optionKey; }
    return newFlags;
}