1 /*****************************************************************************
6 * Created by Martin Kahr on 11.03.06 under a MIT-style license.
7 * Copyright (c) 2006 martinkahr.com. All rights reserved.
9 * Permission is hereby granted, free of charge, to any person obtaining a
10 * copy of this software and associated documentation files (the "Software"),
11 * to deal in the Software without restriction, including without limitation
12 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
13 * and/or sell copies of the Software, and to permit persons to whom the
14 * Software is furnished to do so, subject to the following conditions:
16 * The above copyright notice and this permission notice shall be included
17 * in all copies or substantial portions of the Software.
19 * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 *****************************************************************************
29 * Note that changes made by any members or contributors of the VideoLAN team
30 * (i.e. changes that were exclusively checked in to one of VideoLAN's source code
31 * repositories) are licensed under the GNU General Public License version 2,
32 * or (at your option) any later version.
33 * Thus, the following statements apply to our changes:
35 * Copyright (C) 2006-2009 the VideoLAN team
36 * Authors: Eric Petit <titer@m0k.org>
37 * Felix Kühne <fkuehne at videolan dot org>
39 * This program is free software; you can redistribute it and/or modify
40 * it under the terms of the GNU General Public License as published by
41 * the Free Software Foundation; either version 2 of the License, or
42 * (at your option) any later version.
44 * This program is distributed in the hope that it will be useful,
45 * but WITHOUT ANY WARRANTY; without even the implied warranty of
46 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
47 * GNU General Public License for more details.
49 * You should have received a copy of the GNU General Public License
50 * along with this program; if not, write to the Free Software
51 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
52 *****************************************************************************/
54 #import "AppleRemote.h"
56 /* this was added by the VideoLAN team to ensure Leopard-compatibility and is VLC-only */
59 const char* AppleRemoteDeviceName = "AppleIRController";
60 const int REMOTE_SWITCH_COOKIE=19;
61 const NSTimeInterval DEFAULT_MAXIMUM_CLICK_TIME_DIFFERENCE=0.35;
62 const NSTimeInterval HOLD_RECOGNITION_TIME_INTERVAL=0.4;
64 @implementation AppleRemote
66 #pragma public interface
68 static AppleRemote *_o_sharedInstance = nil;
70 + (AppleRemote *)sharedInstance
72 return _o_sharedInstance ? _o_sharedInstance : [[self alloc] init];
77 if (_o_sharedInstance) {
80 _o_sharedInstance = [super init];
81 openInExclusiveMode = YES;
83 hidDeviceInterface = NULL;
84 cookieToButtonMapping = [[NSMutableDictionary alloc] init];
86 if( NSAppKitVersionNumber < 1038.13 )
88 /* Leopard and early Snow Leopard Cookies */
89 msg_Dbg( VLCIntf, "using Leopard AR cookies" );
90 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonVolume_Plus] forKey:@"31_29_28_18_"];
91 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonVolume_Minus] forKey:@"31_30_28_18_"];
92 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonMenu] forKey:@"31_20_18_31_20_18_"];
93 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonPlay] forKey:@"31_21_18_31_21_18_"];
94 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonRight] forKey:@"31_22_18_31_22_18_"];
95 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonLeft] forKey:@"31_23_18_31_23_18_"];
96 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonRight_Hold] forKey:@"31_18_4_2_"];
97 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonLeft_Hold] forKey:@"31_18_3_2_"];
98 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonMenu_Hold] forKey:@"31_18_31_18_"];
99 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonPlay_Sleep] forKey:@"35_31_18_35_31_18_"];
100 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteControl_Switched] forKey:@"19_"];
102 else if( NSAppKitVersionNumber >= 1115.2 )
104 /* omg, keys from the future */
105 msg_Dbg( VLCIntf, "using future AR cookies" );
106 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonVolume_Plus] forKey:@"33_31_30_21_20_2_"];
107 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonVolume_Minus] forKey:@"33_32_30_21_20_2_"];
108 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonMenu] forKey:@"33_22_21_20_2_33_22_21_20_2_"];
109 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonPlay] forKey:@"33_23_21_20_2_33_23_21_20_2_"];
110 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonRight] forKey:@"33_24_21_20_2_33_24_21_20_2_"];
111 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonLeft] forKey:@"33_25_21_20_2_33_25_21_20_2_"];
112 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonRight_Hold] forKey:@"33_21_20_14_12_2_"];
113 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonLeft_Hold] forKey:@"33_21_20_13_12_2_"];
114 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonMenu_Hold] forKey:@"33_21_20_2_33_21_20_2_"];
115 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonPlay_Sleep] forKey:@"37_33_21_20_2_37_33_21_20_2_"];
116 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteControl_Switched] forKey:@"42_33_23_21_20_2_33_23_21_20_2_"];
117 [cookieToButtonMapping setObject:[NSNumber numberWithInt:k2009RemoteButtonPlay] forKey:@"33_21_20_8_2_33_21_20_8_2_"];
118 [cookieToButtonMapping setObject:[NSNumber numberWithInt:k2009RemoteButtonFullscreen] forKey:@"33_21_20_3_2_33_21_20_3_2_"];
122 /* current Snow Leopard cookies */
123 msg_Dbg( VLCIntf, "using Snow Leopard AR cookies" );
124 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonVolume_Plus] forKey:@"33_31_30_21_20_2_"];
125 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonVolume_Minus] forKey:@"33_32_30_21_20_2_"];
126 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonMenu] forKey:@"33_22_21_20_2_33_22_21_20_2_"];
127 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonPlay] forKey:@"33_23_21_20_2_33_23_21_20_2_"];
128 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonRight] forKey:@"33_24_21_20_2_33_24_21_20_2_"];
129 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonLeft] forKey:@"33_25_21_20_2_33_25_21_20_2_"];
130 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonRight_Hold] forKey:@"33_21_20_14_12_2_"];
131 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonLeft_Hold] forKey:@"33_21_20_13_12_2_"];
132 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonMenu_Hold] forKey:@"33_21_20_2_33_21_20_2_"];
133 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonPlay_Sleep] forKey:@"37_33_21_20_2_37_33_21_20_2_"];
134 [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteControl_Switched] forKey:@"19_"];
135 [cookieToButtonMapping setObject:[NSNumber numberWithInt:k2009RemoteButtonPlay] forKey:@"33_21_20_8_2_33_21_20_8_2_"];
136 [cookieToButtonMapping setObject:[NSNumber numberWithInt:k2009RemoteButtonFullscreen] forKey:@"33_21_20_3_2_33_21_20_3_2_"];
140 [self setSimulatesPlusMinusHold: YES];
141 maxClickTimeDifference = DEFAULT_MAXIMUM_CLICK_TIME_DIFFERENCE;
144 return _o_sharedInstance;
148 [self stopListening:self];
149 [cookieToButtonMapping release];
157 - (BOOL) isRemoteAvailable {
158 io_object_t hidDevice = [self findAppleRemoteDevice];
159 if (hidDevice != 0) {
160 IOObjectRelease(hidDevice);
167 - (BOOL) isListeningToRemote {
168 return (hidDeviceInterface != NULL && allCookies != NULL && queue != NULL);
171 - (void) setListeningToRemote: (BOOL) value {
173 [self stopListening:self];
175 [self startListening:self];
179 /* Delegates are not retained!
180 * http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/chapter_6_section_4.html
181 * Delegating objects do not (and should not) retain their delegates.
182 * However, clients of delegating objects (applications, usually) are responsible for ensuring that their delegates are around
183 * to receive delegation messages. To do this, they may have to retain the delegate. */
184 - (void) setDelegate: (id) _delegate {
185 if (_delegate && [_delegate respondsToSelector:@selector(appleRemoteButton:pressedDown:clickCount:)]==NO) return;
187 delegate = _delegate;
193 - (BOOL) isOpenInExclusiveMode {
194 return openInExclusiveMode;
196 - (void) setOpenInExclusiveMode: (BOOL) value {
197 openInExclusiveMode = value;
200 - (BOOL) clickCountingEnabled {
201 return clickCountEnabledButtons != 0;
203 - (void) setClickCountingEnabled: (BOOL) value {
205 [self setClickCountEnabledButtons: kRemoteButtonVolume_Plus | kRemoteButtonVolume_Minus | kRemoteButtonPlay | kRemoteButtonLeft | kRemoteButtonRight | kRemoteButtonMenu | k2009RemoteButtonPlay | k2009RemoteButtonFullscreen];
207 [self setClickCountEnabledButtons: 0];
211 - (unsigned int) clickCountEnabledButtons {
212 return clickCountEnabledButtons;
214 - (void) setClickCountEnabledButtons: (unsigned int)value {
215 clickCountEnabledButtons = value;
218 - (NSTimeInterval) maximumClickCountTimeDifference {
219 return maxClickTimeDifference;
221 - (void) setMaximumClickCountTimeDifference: (NSTimeInterval) timeDiff {
222 maxClickTimeDifference = timeDiff;
225 - (BOOL) processesBacklog {
226 return processesBacklog;
228 - (void) setProcessesBacklog: (BOOL) value {
229 processesBacklog = value;
232 - (BOOL) listeningOnAppActivate {
233 id appDelegate = [NSApp delegate];
234 return (appDelegate!=nil && [appDelegate isKindOfClass: [AppleRemoteApplicationDelegate class]]);
236 - (void) setListeningOnAppActivate: (BOOL) value {
238 if ([self listeningOnAppActivate]) return;
239 AppleRemoteApplicationDelegate* appDelegate = [[AppleRemoteApplicationDelegate alloc] initWithApplicationDelegate: [NSApp delegate]];
240 /* NSApp does not retain its delegate therefore we keep retain count on 1 */
241 [NSApp setDelegate: appDelegate];
243 if ([self listeningOnAppActivate]==NO) return;
244 AppleRemoteApplicationDelegate* appDelegate = (AppleRemoteApplicationDelegate*)[NSApp delegate];
245 id previousAppDelegate = [appDelegate applicationDelegate];
246 [NSApp setDelegate: previousAppDelegate];
247 [appDelegate release];
251 - (BOOL) simulatesPlusMinusHold {
252 return simulatePlusMinusHold;
254 - (void) setSimulatesPlusMinusHold: (BOOL) value {
255 simulatePlusMinusHold = value;
258 - (IBAction) startListening: (id) sender {
259 if ([self isListeningToRemote]) return;
261 io_object_t hidDevice = [self findAppleRemoteDevice];
262 if (hidDevice == 0) return;
264 if ([self createInterfaceForDevice:hidDevice] == NULL) {
268 if ([self initializeCookies]==NO) {
272 if ([self openDevice]==NO) {
278 [self stopListening:self];
281 IOObjectRelease(hidDevice);
284 - (IBAction) stopListening: (id) sender {
285 if (eventSource != NULL) {
286 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
287 CFRelease(eventSource);
291 (*queue)->stop(queue);
294 (*queue)->dispose(queue);
296 //release the queue we allocated
297 (*queue)->Release(queue);
302 if (allCookies != nil) {
303 [allCookies autorelease];
307 if (hidDeviceInterface != NULL) {
309 (*hidDeviceInterface)->close(hidDeviceInterface);
311 //release the interface
312 (*hidDeviceInterface)->Release(hidDeviceInterface);
314 hidDeviceInterface = NULL;
320 @implementation AppleRemote (Singleton)
322 static AppleRemote* sharedInstance=nil;
324 + (AppleRemote*) sharedRemote {
325 @synchronized(self) {
326 if (sharedInstance == nil) {
327 sharedInstance = [[self alloc] init];
330 return sharedInstance;
332 + (id)allocWithZone:(NSZone *)zone {
333 @synchronized(self) {
334 if (sharedInstance == nil) {
335 return [super allocWithZone:zone];
338 return sharedInstance;
340 - (id)copyWithZone:(NSZone *)zone {
346 - (NSUInteger)retainCount {
347 return UINT_MAX; //denotes an object that cannot be released
358 @implementation AppleRemote (PrivateMethods)
360 - (void) setRemoteId: (int) value {
364 - (IOHIDQueueInterface**) queue {
368 - (IOHIDDeviceInterface**) hidDeviceInterface {
369 return hidDeviceInterface;
373 - (NSDictionary*) cookieToButtonMapping {
374 return cookieToButtonMapping;
377 - (NSString*) validCookieSubstring: (NSString*) cookieString {
378 if (cookieString == nil || [cookieString length] == 0) return nil;
379 NSEnumerator* keyEnum = [[self cookieToButtonMapping] keyEnumerator];
381 while((key = [keyEnum nextObject])) {
382 NSRange range = [cookieString rangeOfString:key];
383 if (range.location == 0) return key;
388 - (void) sendSimulatedPlusMinusEvent: (id) time {
389 BOOL startSimulateHold = NO;
390 AppleRemoteEventIdentifier event = lastPlusMinusEvent;
391 @synchronized(self) {
392 startSimulateHold = (lastPlusMinusEvent>0 && lastPlusMinusEventTime == [time doubleValue]);
394 if (startSimulateHold) {
395 lastEventSimulatedHold = YES;
396 event = (event==kRemoteButtonVolume_Plus) ? kRemoteButtonVolume_Plus_Hold : kRemoteButtonVolume_Minus_Hold;
397 [delegate appleRemoteButton:event pressedDown: YES clickCount: 1];
401 - (void) sendRemoteButtonEvent: (AppleRemoteEventIdentifier) event pressedDown: (BOOL) pressedDown {
403 if (simulatePlusMinusHold) {
404 if (event == kRemoteButtonVolume_Plus || event == kRemoteButtonVolume_Minus) {
406 lastPlusMinusEvent = event;
407 lastPlusMinusEventTime = [NSDate timeIntervalSinceReferenceDate];
408 [self performSelector:@selector(sendSimulatedPlusMinusEvent:)
409 withObject:[NSNumber numberWithDouble:lastPlusMinusEventTime]
410 afterDelay:HOLD_RECOGNITION_TIME_INTERVAL];
413 if (lastEventSimulatedHold) {
414 event = (event==kRemoteButtonVolume_Plus) ? kRemoteButtonVolume_Plus_Hold : kRemoteButtonVolume_Minus_Hold;
415 lastPlusMinusEvent = 0;
416 lastEventSimulatedHold = NO;
418 @synchronized(self) {
419 lastPlusMinusEvent = 0;
427 if (([self clickCountEnabledButtons] & event) == event) {
428 if (pressedDown==NO && (event == kRemoteButtonVolume_Minus || event == kRemoteButtonVolume_Plus)) {
429 return; // this one is triggered automatically by the handler
431 NSNumber* eventNumber;
432 NSNumber* timeNumber;
433 @synchronized(self) {
434 lastClickCountEventTime = [NSDate timeIntervalSinceReferenceDate];
435 if (lastClickCountEvent == event) {
436 eventClickCount = eventClickCount + 1;
440 lastClickCountEvent = event;
441 timeNumber = [NSNumber numberWithDouble:lastClickCountEventTime];
442 eventNumber= [NSNumber numberWithUnsignedInt:event];
444 [self performSelector: @selector(executeClickCountEvent:)
445 withObject: [NSArray arrayWithObjects:eventNumber, timeNumber, nil]
446 afterDelay: maxClickTimeDifference];
448 [delegate appleRemoteButton:event pressedDown: pressedDown clickCount:1];
453 - (void) executeClickCountEvent: (NSArray*) values {
454 AppleRemoteEventIdentifier event = [[values objectAtIndex: 0] unsignedIntValue];
455 NSTimeInterval eventTimePoint = [[values objectAtIndex: 1] doubleValue];
457 BOOL finishedClicking = NO;
458 int finalClickCount = eventClickCount;
460 @synchronized(self) {
461 finishedClicking = (event != lastClickCountEvent || eventTimePoint == lastClickCountEventTime);
462 if (finishedClicking) eventClickCount = 0;
465 if (finishedClicking) {
466 [delegate appleRemoteButton:event pressedDown: YES clickCount:finalClickCount];
467 if ([self simulatesPlusMinusHold]==NO && (event == kRemoteButtonVolume_Minus || event == kRemoteButtonVolume_Plus)) {
468 // trigger a button release event, too
469 [NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow:0.1]];
470 [delegate appleRemoteButton:event pressedDown: NO clickCount:finalClickCount];
476 - (void) handleEventWithCookieString: (NSString*) cookieString sumOfValues: (SInt32) sumOfValues {
478 if (previousRemainingCookieString) {
479 cookieString = [previousRemainingCookieString stringByAppendingString: cookieString];
480 NSLog(@"New cookie string is %@", cookieString);
481 [previousRemainingCookieString release], previousRemainingCookieString=nil;
483 if (cookieString == nil || [cookieString length] == 0) return;
484 NSNumber* buttonId = [[self cookieToButtonMapping] objectForKey: cookieString];
485 if (buttonId != nil) {
486 [self sendRemoteButtonEvent: [buttonId intValue] pressedDown: (sumOfValues>0)];
488 // let's see if a number of events are stored in the cookie string. this does
489 // happen when the main thread is too busy to handle all incoming events in time.
490 NSString* subCookieString;
491 NSString* lastSubCookieString=nil;
492 while((subCookieString = [self validCookieSubstring: cookieString])) {
493 cookieString = [cookieString substringFromIndex: [subCookieString length]];
494 lastSubCookieString = subCookieString;
495 if (processesBacklog) [self handleEventWithCookieString: subCookieString sumOfValues:sumOfValues];
497 if (processesBacklog == NO && lastSubCookieString != nil) {
498 // process the last event of the backlog and assume that the button is not pressed down any longer.
499 // The events in the backlog do not seem to be in order and therefore (in rare cases) the last event might be
500 // a button pressed down event while in reality the user has released it.
501 // NSLog(@"processing last event of backlog");
502 [self handleEventWithCookieString: lastSubCookieString sumOfValues:0];
504 if ([cookieString length] > 0) {
505 msg_Warn( VLCIntf, "Unknown AR button for cookiestring %s", [cookieString UTF8String]);
512 /* Callback method for the device queue
513 Will be called for any event of any type (cookie) to which we subscribe
515 static void QueueCallbackFunction(void* target, IOReturn result, void* refcon, void* sender) {
516 AppleRemote* remote = (AppleRemote*)target;
518 IOHIDEventStruct event;
519 AbsoluteTime zeroTime = {0,0};
520 NSMutableString* cookieString = [NSMutableString string];
521 SInt32 sumOfValues = 0;
522 while (result == kIOReturnSuccess)
524 result = (*[remote queue])->getNextEvent([remote queue], &event, zeroTime, 0);
525 if ( result != kIOReturnSuccess )
528 //printf("%d %d %d\n", event.elementCookie, event.value, event.longValue);
530 if (REMOTE_SWITCH_COOKIE == (int)event.elementCookie) {
531 [remote setRemoteId: event.value];
532 [remote handleEventWithCookieString: @"19_" sumOfValues: 0];
534 if (((int)event.elementCookie)!=5) {
535 sumOfValues+=event.value;
536 [cookieString appendString:[NSString stringWithFormat:@"%d_", event.elementCookie]];
541 [remote handleEventWithCookieString: cookieString sumOfValues: sumOfValues];
544 @implementation AppleRemote (IOKitMethods)
546 - (IOHIDDeviceInterface**) createInterfaceForDevice: (io_object_t) hidDevice {
548 IOCFPlugInInterface** plugInInterface = NULL;
549 HRESULT plugInResult = S_OK;
551 IOReturn ioReturnValue = kIOReturnSuccess;
553 hidDeviceInterface = NULL;
555 ioReturnValue = IOObjectGetClass(hidDevice, className);
557 if (ioReturnValue != kIOReturnSuccess) {
558 msg_Err( VLCIntf, "Failed to get IOKit class name.");
562 ioReturnValue = IOCreatePlugInInterfaceForService(hidDevice,
563 kIOHIDDeviceUserClientTypeID,
564 kIOCFPlugInInterfaceID,
567 if (ioReturnValue == kIOReturnSuccess)
569 //Call a method of the intermediate plug-in to create the device interface
570 plugInResult = (*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID), (LPVOID) &hidDeviceInterface);
572 if (plugInResult != S_OK) {
573 msg_Err( VLCIntf, "Couldn't create HID class device interface");
576 if (plugInInterface) (*plugInInterface)->Release(plugInInterface);
578 return hidDeviceInterface;
581 - (io_object_t) findAppleRemoteDevice {
582 CFMutableDictionaryRef hidMatchDictionary = NULL;
583 IOReturn ioReturnValue = kIOReturnSuccess;
584 io_iterator_t hidObjectIterator = 0;
585 io_object_t hidDevice = 0;
587 // Set up a matching dictionary to search the I/O Registry by class
588 // name for all HID class devices
589 hidMatchDictionary = IOServiceMatching(AppleRemoteDeviceName);
591 // Now search I/O Registry for matching devices.
592 ioReturnValue = IOServiceGetMatchingServices(kIOMasterPortDefault, hidMatchDictionary, &hidObjectIterator);
594 if ((ioReturnValue == kIOReturnSuccess) && (hidObjectIterator != 0)) {
595 hidDevice = IOIteratorNext(hidObjectIterator);
598 // release the iterator
599 IOObjectRelease(hidObjectIterator);
604 - (BOOL) initializeCookies {
605 IOHIDDeviceInterface122** handle = (IOHIDDeviceInterface122**)hidDeviceInterface;
606 IOHIDElementCookie cookie;
610 NSArray* elements = nil;
611 NSDictionary* element;
614 if (!handle || !(*handle)) return NO;
616 /* Copy all elements, since we're grabbing most of the elements
617 * for this device anyway, and thus, it's faster to iterate them
618 * ourselves. When grabbing only one or two elements, a matching
619 * dictionary should be passed in here instead of NULL. */
620 success = (*handle)->copyMatchingElements(handle, NULL, (CFArrayRef*)&elements);
622 if (success == kIOReturnSuccess) {
624 [elements autorelease];
626 cookies = calloc(NUMBER_OF_APPLE_REMOTE_ACTIONS, sizeof(IOHIDElementCookie));
627 memset(cookies, 0, sizeof(IOHIDElementCookie) * NUMBER_OF_APPLE_REMOTE_ACTIONS);
629 allCookies = [[NSMutableArray alloc] init];
631 for (i=0; i< [elements count]; i++) {
632 element = [elements objectAtIndex:i];
635 object = [element valueForKey: (NSString*)CFSTR(kIOHIDElementCookieKey) ];
636 if (object == nil || ![object isKindOfClass:[NSNumber class]]) continue;
637 if (object == 0 || CFGetTypeID(object) != CFNumberGetTypeID()) continue;
638 cookie = (IOHIDElementCookie) [object longValue];
641 object = [element valueForKey: (NSString*)CFSTR(kIOHIDElementUsageKey) ];
642 if (object == nil || ![object isKindOfClass:[NSNumber class]]) continue;
643 usage = [object longValue];
646 object = [element valueForKey: (NSString*)CFSTR(kIOHIDElementUsagePageKey) ];
647 if (object == nil || ![object isKindOfClass:[NSNumber class]]) continue;
648 usagePage = [object longValue];
650 [allCookies addObject: [NSNumber numberWithInt:(int)cookie]];
659 - (BOOL) openDevice {
662 IOHIDOptionsType openMode = kIOHIDOptionsTypeNone;
663 if ([self isOpenInExclusiveMode]) openMode = kIOHIDOptionsTypeSeizeDevice;
664 IOReturn ioReturnValue = (*hidDeviceInterface)->open(hidDeviceInterface, openMode);
666 if (ioReturnValue == KERN_SUCCESS) {
667 queue = (*hidDeviceInterface)->allocQueue(hidDeviceInterface);
669 result = (*queue)->create(queue, 0, 12); //depth: maximum number of elements in queue before oldest elements in queue begin to be lost.
672 for(i=0; i<[allCookies count]; i++) {
673 IOHIDElementCookie cookie = (IOHIDElementCookie)[[allCookies objectAtIndex:i] intValue];
674 (*queue)->addElement(queue, cookie, 0);
677 // add callback for async events
678 ioReturnValue = (*queue)->createAsyncEventSource(queue, &eventSource);
679 if (ioReturnValue == KERN_SUCCESS) {
680 ioReturnValue = (*queue)->setEventCallout(queue,QueueCallbackFunction, self, NULL);
681 if (ioReturnValue == KERN_SUCCESS) {
682 CFRunLoopAddSource(CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
683 //start data delivery to queue
684 (*queue)->start(queue);
687 msg_Err( VLCIntf, "Error when setting event callout");
690 msg_Err( VLCIntf, "Error when creating async event source");
693 msg_Err( VLCIntf, "Error when opening HUD device");
701 @implementation AppleRemoteApplicationDelegate
703 - (id) initWithApplicationDelegate: (id) delegate {
704 if((self = [super init]))
705 applicationDelegate = [delegate retain];
710 [applicationDelegate release];
714 - (id) applicationDelegate {
715 return applicationDelegate;
718 - (void)applicationWillBecomeActive:(NSNotification *)aNotification {
719 if ([applicationDelegate respondsToSelector: @selector(applicationWillBecomeActive:)]) {
720 [applicationDelegate applicationWillBecomeActive: aNotification];
723 - (void)applicationDidBecomeActive:(NSNotification *)aNotification {
724 [[AppleRemote sharedRemote] setListeningToRemote: YES];
726 if ([applicationDelegate respondsToSelector: @selector(applicationDidBecomeActive:)]) {
727 [applicationDelegate applicationDidBecomeActive: aNotification];
730 - (void)applicationWillResignActive:(NSNotification *)aNotification {
731 [[AppleRemote sharedRemote] setListeningToRemote: NO];
733 if ([applicationDelegate respondsToSelector: @selector(applicationWillResignActive:)]) {
734 [applicationDelegate applicationWillResignActive: aNotification];
737 - (void)applicationDidResignActive:(NSNotification *)aNotification {
738 if ([applicationDelegate respondsToSelector: @selector(applicationDidResignActive:)]) {
739 [applicationDelegate applicationDidResignActive: aNotification];
743 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
744 NSMethodSignature* signature = [super methodSignatureForSelector: aSelector];
745 if (signature == nil && applicationDelegate != nil) {
746 signature = [applicationDelegate methodSignatureForSelector: aSelector];
751 - (void)forwardInvocation:(NSInvocation *)invocation {
752 SEL aSelector = [invocation selector];
754 if (applicationDelegate==nil || [applicationDelegate respondsToSelector:aSelector]==NO) {
755 [super forwardInvocation: invocation];
759 [invocation invokeWithTarget:applicationDelegate];