/
BXKeyboardEventTap.m
333 lines (276 loc) · 10.1 KB
/
BXKeyboardEventTap.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
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
/*
Boxer is copyright 2011 Alun Bestor and contributors.
Boxer is released under the GNU General Public License 2.0. A full copy of this license can be
found in this XCode project at Resources/English.lproj/BoxerHelp/pages/legalese.html, or read
online at [http://www.gnu.org/licenses/gpl-2.0.txt].
*/
#import <AppKit/AppKit.h> //For NSApp
#import <Carbon/Carbon.h> //For keycodes
#import <IOKit/hidsystem/ev_keymap.h> //For media key codes
#import "BXKeyboardEventTap.h"
#import "BXContinuousThread.h"
@interface BXKeyboardEventTap ()
//The dedicated thread on which our tap runs.
@property (retain) BXContinuousThread *tapThread;
//Our CGEventTap callback. Receives the BXKeyboardEventTap instance as the userInfo parameter,
//and passes handling directly on to it.
static CGEventRef _handleEventFromTap(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *userInfo);
//Actually does the work of handling the event. Checks
- (CGEventRef) _handleEvent: (CGEventRef)event
ofType: (CGEventType)type
fromProxy: (CGEventTapProxy)proxy;
//Creates an event tap, and starts up a dedicated thread to monitor it (if usesDedicatedThread is YES)
//or adds it to the main thread (if usesDedicatedThread is NO).
- (void) _startTapping;
//Removes the tap and any dedicated thread we were running it on.
- (void) _stopTapping;
//Runs continuously on tapThread, listening to the tap until _stopTapping is called and the thread is cancelled.
- (void) _runTapInDedicatedThread;
@end
@implementation BXKeyboardEventTap
@synthesize enabled = _enabled;
@synthesize usesDedicatedThread = _usesDedicatedThread;
@synthesize tapThread = _tapThread;
@synthesize delegate = _delegate;
- (id) init
{
if ((self = [super init]))
{
self.usesDedicatedThread = NO;
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver: self
selector: @selector(applicationDidBecomeActive:)
name: NSApplicationDidBecomeActiveNotification
object: NSApp];
}
return self;
}
- (void) applicationDidBecomeActive: (NSNotification *)notification
{
//Listen for when Boxer becomes the active application and re-check
//the availability of the accessibility API at this point.
//If the API is available, attempt to reestablish a tap if we're
//enabled and don't already have one (which means it failed when
//we tried it the last time.)
[self willChangeValueForKey: @"canTapEvents"];
if (!self.isTapping && self.isEnabled && self.canTapEvents)
{
[self _startTapping];
}
[self didChangeValueForKey: @"canTapEvents"];
}
- (void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver: self];
[self _stopTapping];
self.tapThread = nil;
[super dealloc];
}
- (void) setEnabled: (BOOL)flag
{
if (_enabled != flag)
{
_enabled = flag;
if (flag) [self _startTapping];
else [self _stopTapping];
}
}
- (void) setUsesDedicatedThread: (BOOL)usesDedicatedThread
{
if (usesDedicatedThread != self.usesDedicatedThread)
{
BOOL wasTapping = self.isTapping;
if (wasTapping)
{
[self _stopTapping];
}
_usesDedicatedThread = usesDedicatedThread;
if (wasTapping)
{
[self _startTapping];
}
}
}
- (BOOL) canTapEvents
{
return (AXAPIEnabled() || AXIsProcessTrusted());
}
- (BOOL) isTapping
{
return _tap != NULL;
}
- (void) _startTapping
{
if (!self.isTapping)
{
//Create the event tap, and keep a reference to it as an instance variable
//so that we can access it from our callback if needed.
//This will fail and return NULL if Boxer does not have permission to tap
//keyboard events.
CGEventMask eventTypes = CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(NX_SYSDEFINED);
_tap = CGEventTapCreate(kCGSessionEventTap,
kCGHeadInsertEventTap,
kCGEventTapOptionDefault,
eventTypes,
_handleEventFromTap,
self);
if (_tap)
{
_source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, _tap, 0);
//Decide whether to run the tap on a dedicated thread or on the main thread.
if (self.usesDedicatedThread)
{
#ifdef BOXER_DEBUG
NSLog(@"Installing event tap on dedicated thread.");
#endif
//_runTapInDedicatedThread will handle adding and removing the source
//on its own run loop.
self.tapThread = [[[BXContinuousThread alloc] initWithTarget: self
selector: @selector(_runTapInDedicatedThread)
object: nil] autorelease];
[self.tapThread start];
}
else
{
#ifdef BOXER_DEBUG
NSLog(@"Installing event tap on main thread.");
#endif
CFRunLoopAddSource(CFRunLoopGetMain(), _source, kCFRunLoopCommonModes);
}
}
}
}
- (void) _stopTapping
{
if (self.isTapping)
{
if (self.usesDedicatedThread && self.tapThread)
{
[self.tapThread cancel];
[self.tapThread waitUntilFinished];
self.tapThread = nil;
}
else
{
CFRunLoopRemoveSource(CFRunLoopGetMain(), _source, kCFRunLoopCommonModes);
}
//Clean up the event tap and source after ourselves.
CFMachPortInvalidate(_tap);
CFRunLoopSourceInvalidate(_source);
CFRelease(_source);
CFRelease(_tap);
_tap = NULL;
_source = NULL;
}
}
- (void) _runTapInDedicatedThread
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (_source != NULL)
{
CFRetain(_source);
//Create a source on the thread's run loop so that we'll receive messages
//from the tap when an event comes in.
CFRunLoopAddSource(CFRunLoopGetCurrent(), _source, kCFRunLoopCommonModes);
//Run this thread's run loop until we're told to stop, processing event-tap
//callbacks and other messages on this thread.
[(BXContinuousThread *)[NSThread currentThread] runUntilCancelled];
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), _source, kCFRunLoopCommonModes);
CFRelease(_source);
}
[pool drain];
}
- (CGEventRef) _handleEvent: (CGEventRef)event
ofType: (CGEventType)type
fromProxy: (CGEventTapProxy)proxy
{
//If we're not enabled or we have no way of validating the events, give up early
if (!self.enabled || !self.delegate)
{
return event;
}
switch (type)
{
case kCGEventKeyDown:
case kCGEventKeyUp:
case NX_SYSDEFINED:
{
BOOL shouldCapture = NO;
//First try and make this into a cocoa event
NSEvent *cocoaEvent = nil;
@try
{
cocoaEvent = [NSEvent eventWithCGEvent: event];
}
@catch (NSException *exception)
{
#ifdef BOXER_DEBUG
//If the event could not be converted into a cocoa event, give up
CFStringRef eventDesc = CFCopyDescription(event);
NSLog(@"Could not convert CGEvent: %@", (NSString *)eventDesc);
CFRelease(eventDesc);
#endif
}
if (cocoaEvent)
{
if (type == NX_SYSDEFINED)
{
shouldCapture = [self.delegate eventTap: self shouldCaptureSystemDefinedEvent: cocoaEvent];
}
else
{
shouldCapture = [self.delegate eventTap: self shouldCaptureKeyEvent: cocoaEvent];
}
}
if (shouldCapture)
{
[NSApp postEvent: cocoaEvent atStart: YES];
//This approach ought to be closer to the normal behaviour
//of the event dispatch mechanism, but seems to result
//in key events occasionally getting lost, causing stuck keys.
//So we go with a more explicit NSEvent-based dispatch instead.
/*
ProcessSerialNumber PSN;
OSErr error = GetCurrentProcess(&PSN);
if (error == noErr)
{
CGEventPostToPSN(&PSN, event);
//Returning NULL cancels the original event
return NULL;
}
*/
//Returning NULL cancels the original event
return NULL;
}
break;
}
case kCGEventTapDisabledByTimeout:
{
//Re-enable the event tap if it has been disabled after a timeout.
//(This may occur if our thread has been blocked for some reason.)
CGEventTapEnable(_tap, YES);
break;
}
case kCGEventTapDisabledByUserInput:
{
//Re-enable the event tap if it has been disabled after a timeout.
//(This may occur if our thread has been blocked for some reason.)
CGEventTapEnable(_tap, YES);
break;
}
}
return event;
}
static CGEventRef _handleEventFromTap(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *userInfo)
{
CGEventRef returnedEvent = event;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
BXKeyboardEventTap *tap = (BXKeyboardEventTap *)userInfo;
if (tap)
{
returnedEvent = [tap _handleEvent: event ofType: type fromProxy: proxy];
}
[pool drain];
return returnedEvent;
}
@end