forked from martinkahr/apple_remote_control
-
Notifications
You must be signed in to change notification settings - Fork 3
/
HIDRemoteControlDevice.m
570 lines (463 loc) · 17.6 KB
/
HIDRemoteControlDevice.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
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
/*****************************************************************************
* HIDRemoteControlDevice.m
* RemoteControlWrapper
*
* Created by Martin Kahr on 11.03.06 under a MIT-style license.
* Copyright (c) 2006-2016 martinkahr.com. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS 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 "HIDRemoteControlDevice.h"
#import <IOKit/IOKitLib.h>
#import <IOKit/IOCFPlugIn.h>
#import <IOKit/hid/IOHIDKeys.h>
@interface HIDRemoteControlDevice (PrivateMethods)
- (NSDictionary*) cookieToButtonMapping;
- (IOHIDQueueInterface**) queue;
- (IOHIDDeviceInterface**) hidDeviceInterface;
- (void) handleEventWithCookieString: (NSString*) cookieString sumOfValues: (SInt32) sumOfValues;
- (void) removeNotifcationObserver;
- (void) remoteControlAvailable:(NSNotification *)notification;
@end
@interface HIDRemoteControlDevice (IOKitMethods)
- (IOHIDDeviceInterface**) createInterfaceForDevice: (io_object_t) hidDevice;
- (BOOL) initializeCookies;
- (BOOL) openDevice;
@end
@implementation HIDRemoteControlDevice
// This class acts as an abstract base class - therefore subclasses have to override this method
+ (const char*) remoteControlDeviceName {
return "";
}
+ (BOOL) isRemoteAvailable {
io_object_t hidDevice = [self findRemoteDevice];
if (hidDevice != 0) {
IOObjectRelease(hidDevice);
return YES;
} else {
return NO;
}
}
+ (io_object_t) findRemoteDevice {
CFMutableDictionaryRef hidMatchDictionary = NULL;
IOReturn ioReturnValue = kIOReturnSuccess;
io_iterator_t hidObjectIterator = 0;
io_object_t hidDevice = 0;
// Set up a matching dictionary to search the I/O Registry by class
// name for all HID class devices
hidMatchDictionary = IOServiceMatching([self remoteControlDeviceName]);
// Now search I/O Registry for matching devices.
ioReturnValue = IOServiceGetMatchingServices(kIOMasterPortDefault, hidMatchDictionary, &hidObjectIterator);
if ((ioReturnValue == kIOReturnSuccess) && (hidObjectIterator != 0)) {
hidDevice = IOIteratorNext(hidObjectIterator);
// release the iterator
IOObjectRelease(hidObjectIterator);
}
// Returned value must be released by the caller when it is finished
return hidDevice;
}
// Designated initializer
- (nullable instancetype) initWithDelegate: (nullable id<RemoteControlDelegate>) inRemoteControlDelegate {
if ([[self class] isRemoteAvailable] == NO) {
#if _isMRR
[self release];
#endif
self = nil;
} else if ( (self = [super initWithDelegate: inRemoteControlDelegate]) ) {
_openInExclusiveMode = YES;
_queue = NULL;
_hidDeviceInterface = NULL;
_cookieToButtonMapping = [[NSMutableDictionary alloc] init];
[self setCookieMappingInDictionary: _cookieToButtonMapping];
NSEnumerator* enumerator = [_cookieToButtonMapping objectEnumerator];
NSNumber* identifier;
_supportedButtonEvents = 0;
while( (identifier = [enumerator nextObject]) ) {
_supportedButtonEvents |= [identifier intValue];
}
}
return self;
}
#if !_isGC
- (void) dealloc {
[self removeNotifcationObserver];
[self stopListening:self];
#if _isMRR
[_cookieToButtonMapping release];
_cookieToButtonMapping = nil;
[super dealloc];
#endif
}
#endif
- (void) sendRemoteButtonEvent: (RemoteControlEventIdentifier) event pressedDown: (BOOL) pressedDown {
//NSLog(@"Button 0x%x %s", event, pressedDown ? "pressed down" : "released");
id<RemoteControlDelegate> strongDelegate = [self delegate];
[strongDelegate sendRemoteButtonEvent: event pressedDown: pressedDown remoteControl:self];
}
- (void) setCookieMappingInDictionary: (NSMutableDictionary*) aCookieToButtonMapping {
assert(aCookieToButtonMapping);
(void)aCookieToButtonMapping;
}
- (int) remoteIdSwitchCookie {
return 0;
}
- (BOOL) sendsEventForButtonIdentifier: (RemoteControlEventIdentifier) identifier {
return (_supportedButtonEvents & identifier) == identifier;
}
- (BOOL) isListeningToRemote {
return (_hidDeviceInterface != NULL && _allCookies != NULL && _queue != NULL);
}
- (void) setListeningToRemote: (BOOL) value {
if (value == NO) {
[self stopListening:self];
} else {
[self startListening:self];
}
}
@synthesize openInExclusiveMode = _openInExclusiveMode;
@synthesize processesBacklog = _processesBacklog;
- (void) openRemoteControlDevice {
io_object_t hidDevice = [[self class] findRemoteDevice];
if (hidDevice == 0) {
return;
}
if ([self createInterfaceForDevice:hidDevice] == NULL) {
goto error;
}
if ([self initializeCookies]==NO) {
goto error;
}
if ([self openDevice]==NO) {
goto error;
}
goto cleanup;
error:
[self stopListening:self];
cleanup:
IOObjectRelease(hidDevice);
}
- (void) closeRemoteControlDevice: (BOOL) shallSendNotifications {
BOOL sendNotification = NO;
if (_eventSource != NULL) {
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), _eventSource, kCFRunLoopDefaultMode);
CFRelease(_eventSource);
_eventSource = NULL;
}
if (_queue != NULL) {
(*_queue)->stop(_queue);
//dispose of queue
(*_queue)->dispose(_queue);
//release the queue we allocated
(*_queue)->Release(_queue);
_queue = NULL;
sendNotification = YES;
}
if (_allCookies != NULL) {
CFRelease(_allCookies);
_allCookies = NULL;
}
if (_hidDeviceInterface != NULL) {
//close the device
(*_hidDeviceInterface)->close(_hidDeviceInterface);
//release the interface
(*_hidDeviceInterface)->Release(_hidDeviceInterface);
_hidDeviceInterface = NULL;
}
if (shallSendNotifications && [self isOpenInExclusiveMode] && sendNotification) {
[[self class] sendFinishedNotifcationForAppIdentifier: nil];
}
}
- (IBAction) startListening: (id) sender {
(void)sender;
if ([self isListeningToRemote]) {
return;
}
[self willChangeValueForKey:@"listeningToRemote"];
[self openRemoteControlDevice];
[self didChangeValueForKey:@"listeningToRemote"];
}
- (IBAction) stopListening: (id) sender {
(void)sender;
if ([self isListeningToRemote]==NO) {
return;
}
[self willChangeValueForKey:@"listeningToRemote"];
[self closeRemoteControlDevice: YES];
[self didChangeValueForKey:@"listeningToRemote"];
}
@end
@implementation HIDRemoteControlDevice (PrivateMethods)
- (IOHIDQueueInterface**) queue {
return _queue;
}
- (IOHIDDeviceInterface**) hidDeviceInterface {
return _hidDeviceInterface;
}
- (NSDictionary*) cookieToButtonMapping {
return _cookieToButtonMapping;
}
- (NSString*) validCookieSubstring: (NSString*) cookieString {
if ([cookieString length] == 0) {
return nil;
}
NSEnumerator* keyEnum = [[self cookieToButtonMapping] keyEnumerator];
NSString* key;
// find the best match
while( (key = [keyEnum nextObject]) ) {
NSRange range = [cookieString rangeOfString:key];
if (range.location == 0) {
return key;
}
}
return nil;
}
- (void) handleEventWithCookieString: (NSString*) cookieString sumOfValues: (SInt32) sumOfValues {
assert(cookieString);
//NSLog(@"handleEventWithCookieString: %@ sumOfValues:%d", cookieString, sumOfValues);
if ([cookieString length] == 0) {
return;
}
NSNumber* buttonId = [[self cookieToButtonMapping] objectForKey: cookieString];
if (buttonId != nil) {
RemoteControlEventIdentifier remoteControlEvent = (RemoteControlEventIdentifier)[buttonId intValue];
[self sendRemoteButtonEvent: remoteControlEvent pressedDown: (sumOfValues>0)];
} else {
// let's see if this is the first event after a restart of the OS, or the first from this remote after a different one was used.
// In this case the event has a prefix that we can ignore and we just get the down event but no up event
NSEnumerator* keyEnum = [[self cookieToButtonMapping] keyEnumerator];
NSString* key;
while( (key = [keyEnum nextObject]) ) {
NSRange range = [cookieString rangeOfString:key];
if (range.location != NSNotFound && range.location > 0) {
buttonId = [[self cookieToButtonMapping] objectForKey: key];
if (buttonId != nil) {
RemoteControlEventIdentifier remoteControlEvent = (RemoteControlEventIdentifier)[buttonId intValue];
// In the AppleRemote subclass the sendRemoteButtonEvent:pressedDown: does some extra magic that
// results in the delegate being called exactly once or twice, but here we always want exactly twice:
// firist pressedDown:YES then pressedDown:NO, so just message the delegate directly.
id<RemoteControlDelegate> strongDelegate = [self delegate];
[strongDelegate sendRemoteButtonEvent: remoteControlEvent pressedDown: YES remoteControl:self];
[strongDelegate sendRemoteButtonEvent: remoteControlEvent pressedDown: NO remoteControl:self];
}
return;
}
}
// let's see if a number of events are stored in the cookie string. this does
// happen when the main thread is too busy to handle all incoming events in time.
NSString* subCookieString;
NSString* lastSubCookieString=nil;
while( (subCookieString = [self validCookieSubstring: cookieString]) ) {
cookieString = [cookieString substringFromIndex: [subCookieString length]];
lastSubCookieString = subCookieString;
if (_processesBacklog) {
[self handleEventWithCookieString: subCookieString sumOfValues:sumOfValues];
}
}
if (_processesBacklog == NO && lastSubCookieString != nil) {
// process the last event of the backlog and assume that the button is not pressed down any longer.
// The events in the backlog do not seem to be in order and therefore (in rare cases) the last event might be
// a button pressed down event while in reality the user has released it.
// NSLog(@"processing last event of backlog: %@", lastSubCookieString);
[self handleEventWithCookieString: lastSubCookieString sumOfValues:0];
}
if ([cookieString length] > 0) {
NSLog(@"Unknown button for cookiestring %@", cookieString);
}
}
}
- (void) removeNotifcationObserver {
NSDistributedNotificationCenter* defaultCenter = [NSDistributedNotificationCenter defaultCenter];
[defaultCenter removeObserver:self name:FINISHED_USING_REMOTE_CONTROL_NOTIFICATION object:nil];
}
- (void) remoteControlAvailable:(NSNotification *)notification {
assert(notification);
(void)notification;
[self removeNotifcationObserver];
[self startListening: self];
}
@end
/* Callback method for the device queue
Will be called for any event of any type (cookie) to which we subscribe
*/
static void QueueCallbackFunction(void* target, IOReturn result, void* refcon, void* sender) {
(void)refcon;
(void)sender;
if (target == NULL) {
NSLog(@"QueueCallbackFunction called with invalid target!");
return;
}
#if _isMRR
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
#elif _isARC
@autoreleasepool
#endif
{
HIDRemoteControlDevice* remote = (_arcbridge HIDRemoteControlDevice*)target;
IOHIDEventStruct event;
AbsoluteTime zeroTime = {0,0};
NSMutableString* cookieString = [NSMutableString string];
SInt32 sumOfValues = 0;
while (result == kIOReturnSuccess)
{
result = (*[remote queue])->getNextEvent([remote queue], &event, zeroTime, 0);
if ( result != kIOReturnSuccess ) {
continue;
}
//printf("%lu %d %p\n", (unsigned long)event.elementCookie, event.value, event.longValue);
if (((unsigned long)event.elementCookie)!=5) {
sumOfValues+=event.value;
[cookieString appendString:[NSString stringWithFormat:@"%lu_", (unsigned long)event.elementCookie]];
}
}
//NSLog(@"raw cookieString: %@, sumOfValues: %d", cookieString, sumOfValues);
[remote handleEventWithCookieString: cookieString sumOfValues: sumOfValues];
}
#if _isMRR
[pool drain];
#endif
}
@implementation HIDRemoteControlDevice (IOKitMethods)
- (IOHIDDeviceInterface**) createInterfaceForDevice: (io_object_t) hidDevice {
_hidDeviceInterface = NULL;
io_name_t className;
IOReturn ioReturnValue = IOObjectGetClass(hidDevice, className);
if (ioReturnValue != kIOReturnSuccess) {
NSLog(@"Error: Failed to get class name.");
return NULL;
}
IOCFPlugInInterface** plugInInterface = NULL;
SInt32 score = 0;
ioReturnValue = IOCreatePlugInInterfaceForService(hidDevice,
kIOHIDDeviceUserClientTypeID,
kIOCFPlugInInterfaceID,
&plugInInterface,
&score);
if (ioReturnValue == kIOReturnSuccess) {
//Call a method of the intermediate plug-in to create the device interface
HRESULT plugInResult = (*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID), (LPVOID) &_hidDeviceInterface);
if (plugInResult != S_OK) {
NSLog(@"Error: Couldn't create HID class device interface");
}
// Release
if (plugInInterface) {
(*plugInInterface)->Release(plugInInterface);
}
}
return _hidDeviceInterface;
}
- (BOOL) initializeCookies {
IOHIDDeviceInterface122** handle = (IOHIDDeviceInterface122**)_hidDeviceInterface;
if (!handle || !(*handle)) {
return NO;
}
// Copy all elements, since we're grabbing most of the elements
// for this device anyway, and thus, it's faster to iterate them
// ourselves. When grabbing only one or two elements, a matching
// dictionary should be passed in here instead of NULL.
CFArrayRef elements = NULL;
IOReturn success = (*handle)->copyMatchingElements(handle, NULL, &elements);
if ( (success == kIOReturnSuccess) && elements ) {
_allCookies = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
CFIndex elementsCount = CFArrayGetCount(elements);
if (elementsCount > 0) {
for (CFIndex idx = 0; idx < elementsCount; idx++) {
CFDictionaryRef element = CFArrayGetValueAtIndex(elements, idx);
// Get cookie
CFNumberRef cookie = CFDictionaryGetValue(element, CFSTR(kIOHIDElementCookieKey));
if (cookie == NULL || CFGetTypeID(cookie) != CFNumberGetTypeID()) {
continue;
}
// Get usage
CFNumberRef usage = CFDictionaryGetValue(element, CFSTR(kIOHIDElementUsageKey));
if (usage == NULL || CFGetTypeID(usage) != CFNumberGetTypeID()) {
continue;
}
// Get usage page
CFNumberRef usagePage = CFDictionaryGetValue(element, CFSTR(kIOHIDElementUsagePageKey));
if (usagePage == NULL || CFGetTypeID(usagePage) != CFNumberGetTypeID()) {
continue;
}
CFArrayAppendValue(_allCookies, cookie);
}
}
CFRelease(elements);
} else {
return NO;
}
return YES;
}
- (BOOL) openDevice {
IOHIDOptionsType openMode = kIOHIDOptionsTypeNone;
if ([self isOpenInExclusiveMode]) {
openMode = kIOHIDOptionsTypeSeizeDevice;
}
IOReturn ioReturnValue = (*_hidDeviceInterface)->open(_hidDeviceInterface, openMode);
if (ioReturnValue == KERN_SUCCESS) {
_queue = (*_hidDeviceInterface)->allocQueue(_hidDeviceInterface);
if (_queue) {
HRESULT result = (*_queue)->create(_queue, 0, 12); //depth: maximum number of elements in queue before oldest elements in queue begin to be lost.
if (result == kIOReturnSuccess) {
CFIndex cookiesCount = CFArrayGetCount(_allCookies);
if (cookiesCount > 0) {
for (CFIndex idx = 0; idx < cookiesCount; idx++) {
CFNumberRef cookieRef = CFArrayGetValueAtIndex(_allCookies, idx);
IOHIDElementCookie cookie; // Note: this is 32 bit in both 32 & 64 bit ABIs!
CFNumberGetValue(cookieRef, kCFNumberSInt32Type, &cookie);
(*_queue)->addElement(_queue, cookie, 0);
}
}
// add callback for async events
ioReturnValue = (*_queue)->createAsyncEventSource(_queue, &_eventSource);
if (ioReturnValue == KERN_SUCCESS) {
ioReturnValue = (*_queue)->setEventCallout(_queue,
QueueCallbackFunction,
(_arcbridge void *)(self),
NULL);
if (ioReturnValue == KERN_SUCCESS) {
CFRunLoopAddSource(CFRunLoopGetCurrent(), _eventSource, kCFRunLoopDefaultMode);
//start data delivery to queue
(*_queue)->start(_queue);
return YES;
} else {
NSLog(@"Error when setting event callback");
}
} else {
NSLog(@"Error when creating async event source");
}
} else {
NSLog(@"Error when creating queue");
}
} else {
NSLog(@"Error when opening device");
}
} else if (ioReturnValue == (IOReturn)0xE00002C5 /* kIOReturnExclusiveAccess */) {
// Alas, the kIOReturnExclusiveAccess macro performs undefined bit shifts,
// as warned by -Wshift-sign-overflow. At runtime, under UBSan, this can crash
// so we hardcode the numeric value and cast. <rdar://12665902>
// the device is used exclusive by another application
// 1. we register for the FINISHED_USING_REMOTE_CONTROL_NOTIFICATION notification
NSDistributedNotificationCenter* defaultCenter = [NSDistributedNotificationCenter defaultCenter];
[defaultCenter addObserver:self selector:@selector(remoteControlAvailable:) name:FINISHED_USING_REMOTE_CONTROL_NOTIFICATION object:nil];
// 2. send a distributed notification that we wanted to use the remote control
[[self class] sendRequestForRemoteControlNotification];
}
return NO;
}
@end