]> git.sesse.net Git - vlc/blob - modules/gui/macosx/AppleRemote.m
macosx: Make sure empty nodes are shown as node.
[vlc] / modules / gui / macosx / AppleRemote.m
1 /*****************************************************************************
2  * AppleRemote.m
3  * AppleRemote
4  * $Id$
5  *
6  * Created by Martin Kahr on 11.03.06 under a MIT-style license.
7  * Copyright (c) 2006 martinkahr.com. All rights reserved.
8  *
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:
15  *
16  * The above copyright notice and this permission notice shall be included
17  * in all copies or substantial portions of the Software.
18  *
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
25  * THE SOFTWARE.
26  *
27  *****************************************************************************
28  *
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:
34  *
35  * Copyright (C) 2006-2007 the VideoLAN team
36  * Authors: Eric Petit <titer@m0k.org>
37  *          Felix Kühne <fkuehne at videolan dot org>
38  *
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.
43  *
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.
48  *
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  *****************************************************************************/
53
54 #import "AppleRemote.h"
55
56 /* this was added by the VideoLAN team to ensure Leopard-compatibility and is VLC-only */
57 #import "intf.h"
58
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;
63
64 @implementation AppleRemote
65
66 #pragma public interface
67
68 - (id) init {
69     if ( self = [super init] ) {
70         openInExclusiveMode = YES;
71         queue = NULL;
72         hidDeviceInterface = NULL;
73         cookieToButtonMapping = [[NSMutableDictionary alloc] init];
74
75         if( MACOS_VERSION < 10.5f )
76         {
77             /* use the traditional cookies for Tiger (and Panther, if it is supported by the frame app) */
78             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonVolume_Plus]  forKey:@"14_12_11_6_"];
79             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonVolume_Minus] forKey:@"14_13_11_6_"];
80             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonMenu]         forKey:@"14_7_6_14_7_6_"];
81             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonPlay]         forKey:@"14_8_6_14_8_6_"];
82             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonRight]        forKey:@"14_9_6_14_9_6_"];
83             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonLeft]         forKey:@"14_10_6_14_10_6_"];
84             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonRight_Hold]   forKey:@"14_6_4_2_"];
85             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonLeft_Hold]    forKey:@"14_6_3_2_"];
86             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonMenu_Hold]    forKey:@"14_6_14_6_"];
87             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonPlay_Sleep]   forKey:@"18_14_6_18_14_6_"];
88             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteControl_Switched]   forKey:@"19_"];
89         }
90         else
91         {
92             /* we're on Leopard and need to use a new set of cookies */
93             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonVolume_Plus]  forKey:@"31_29_28_18_"];
94             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonVolume_Minus] forKey:@"31_30_28_18_"];
95             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonMenu]         forKey:@"31_20_18_31_20_18_"];
96             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonPlay]         forKey:@"31_21_18_31_21_18_"];
97             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonRight]        forKey:@"31_22_18_31_22_18_"];
98             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonLeft]         forKey:@"31_23_18_31_23_18_"];
99             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonRight_Hold]   forKey:@"31_18_4_2_"];
100             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonLeft_Hold]    forKey:@"31_18_3_2_"];
101             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonMenu_Hold]    forKey:@"31_18_31_18_"];
102             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonPlay_Sleep]   forKey:@"35_31_18_35_31_18_"];
103             [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteControl_Switched]   forKey:@"19_"];
104         }
105
106         /* defaults */
107         [self setSimulatesPlusMinusHold: YES];
108         maxClickTimeDifference = DEFAULT_MAXIMUM_CLICK_TIME_DIFFERENCE;
109     }
110
111     return self;
112 }
113
114 - (void) dealloc {
115     [self stopListening:self];
116     [cookieToButtonMapping release];
117     [super dealloc];
118 }
119
120 - (int) remoteId {
121     return remoteId;
122 }
123
124 - (BOOL) isRemoteAvailable {
125     io_object_t hidDevice = [self findAppleRemoteDevice];
126     if (hidDevice != 0) {
127         IOObjectRelease(hidDevice);
128         return YES;
129     } else {
130         return NO;
131     }
132 }
133
134 - (BOOL) isListeningToRemote {
135     return (hidDeviceInterface != NULL && allCookies != NULL && queue != NULL);
136 }
137
138 - (void) setListeningToRemote: (BOOL) value {
139     if (value == NO) {
140         [self stopListening:self];
141     } else {
142         [self startListening:self];
143     }
144 }
145
146 /* Delegates are not retained!
147  * http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/chapter_6_section_4.html
148  * Delegating objects do not (and should not) retain their delegates.
149  * However, clients of delegating objects (applications, usually) are responsible for ensuring that their delegates are around
150  * to receive delegation messages. To do this, they may have to retain the delegate. */
151 - (void) setDelegate: (id) _delegate {
152     if (_delegate && [_delegate respondsToSelector:@selector(appleRemoteButton:pressedDown:clickCount:)]==NO) return;
153
154     delegate = _delegate;
155 }
156 - (id) delegate {
157     return delegate;
158 }
159
160 - (BOOL) isOpenInExclusiveMode {
161     return openInExclusiveMode;
162 }
163 - (void) setOpenInExclusiveMode: (BOOL) value {
164     openInExclusiveMode = value;
165 }
166
167 - (BOOL) clickCountingEnabled {
168     return clickCountEnabledButtons != 0;
169 }
170 - (void) setClickCountingEnabled: (BOOL) value {
171     if (value) {
172         [self setClickCountEnabledButtons: kRemoteButtonVolume_Plus | kRemoteButtonVolume_Minus | kRemoteButtonPlay | kRemoteButtonLeft | kRemoteButtonRight | kRemoteButtonMenu];
173     } else {
174         [self setClickCountEnabledButtons: 0];
175     }
176 }
177
178 - (unsigned int) clickCountEnabledButtons {
179     return clickCountEnabledButtons;
180 }
181 - (void) setClickCountEnabledButtons: (unsigned int)value {
182     clickCountEnabledButtons = value;
183 }
184
185 - (NSTimeInterval) maximumClickCountTimeDifference {
186     return maxClickTimeDifference;
187 }
188 - (void) setMaximumClickCountTimeDifference: (NSTimeInterval) timeDiff {
189     maxClickTimeDifference = timeDiff;
190 }
191
192 - (BOOL) processesBacklog {
193     return processesBacklog;
194 }
195 - (void) setProcessesBacklog: (BOOL) value {
196     processesBacklog = value;
197 }
198
199 - (BOOL) listeningOnAppActivate {
200     id appDelegate = [NSApp delegate];
201     return (appDelegate!=nil && [appDelegate isKindOfClass: [AppleRemoteApplicationDelegate class]]);
202 }
203 - (void) setListeningOnAppActivate: (BOOL) value {
204     if (value) {
205         if ([self listeningOnAppActivate]) return;
206         AppleRemoteApplicationDelegate* appDelegate = [[AppleRemoteApplicationDelegate alloc] initWithApplicationDelegate: [NSApp delegate]];
207         /* NSApp does not retain its delegate therefore we keep retain count on 1 */
208         [NSApp setDelegate: appDelegate];
209     } else {
210         if ([self listeningOnAppActivate]==NO) return;
211         AppleRemoteApplicationDelegate* appDelegate = (AppleRemoteApplicationDelegate*)[NSApp delegate];
212         id previousAppDelegate = [appDelegate applicationDelegate];
213         [NSApp setDelegate: previousAppDelegate];
214         [appDelegate release];
215     }
216 }
217
218 - (BOOL) simulatesPlusMinusHold {
219     return simulatePlusMinusHold;
220 }
221 - (void) setSimulatesPlusMinusHold: (BOOL) value {
222     simulatePlusMinusHold = value;
223 }
224
225 - (IBAction) startListening: (id) sender {
226     if ([self isListeningToRemote]) return;
227
228     io_object_t hidDevice = [self findAppleRemoteDevice];
229     if (hidDevice == 0) return;
230
231     if ([self createInterfaceForDevice:hidDevice] == NULL) {
232         goto error;
233     }
234
235     if ([self initializeCookies]==NO) {
236         goto error;
237     }
238
239     if ([self openDevice]==NO) {
240         goto error;
241     }
242     goto cleanup;
243
244 error:
245     [self stopListening:self];
246
247 cleanup:
248     IOObjectRelease(hidDevice);
249 }
250
251 - (IBAction) stopListening: (id) sender {
252     if (queue != NULL) {
253         (*queue)->stop(queue);
254
255         //dispose of queue
256         (*queue)->dispose(queue);
257
258         //release the queue we allocated
259         (*queue)->Release(queue);
260
261         queue = NULL;
262     }
263
264     if (allCookies != nil) {
265         [allCookies autorelease];
266         allCookies = nil;
267     }
268
269     if (hidDeviceInterface != NULL) {
270         //close the device
271         (*hidDeviceInterface)->close(hidDeviceInterface);
272
273         //release the interface
274         (*hidDeviceInterface)->Release(hidDeviceInterface);
275
276         hidDeviceInterface = NULL;
277     }
278 }
279
280 @end
281
282 @implementation AppleRemote (Singleton)
283
284 static AppleRemote* sharedInstance=nil;
285
286 + (AppleRemote*) sharedRemote {
287     @synchronized(self) {
288         if (sharedInstance == nil) {
289             sharedInstance = [[self alloc] init];
290         }
291     }
292     return sharedInstance;
293 }
294 + (id)allocWithZone:(NSZone *)zone {
295     @synchronized(self) {
296         if (sharedInstance == nil) {
297             return [super allocWithZone:zone];
298         }
299     }
300     return sharedInstance;
301 }
302 - (id)copyWithZone:(NSZone *)zone {
303     return self;
304 }
305 - (id)retain {
306     return self;
307 }
308 - (unsigned)retainCount {
309     return UINT_MAX;  //denotes an object that cannot be released
310 }
311 - (void)release {
312     //do nothing
313 }
314 - (id)autorelease {
315     return self;
316 }
317
318 @end
319
320 @implementation AppleRemote (PrivateMethods)
321
322 - (void) setRemoteId: (int) value {
323     remoteId = value;
324 }
325
326 - (IOHIDQueueInterface**) queue {
327     return queue;
328 }
329
330 - (IOHIDDeviceInterface**) hidDeviceInterface {
331     return hidDeviceInterface;
332 }
333
334
335 - (NSDictionary*) cookieToButtonMapping {
336     return cookieToButtonMapping;
337 }
338
339 - (NSString*) validCookieSubstring: (NSString*) cookieString {
340     if (cookieString == nil || [cookieString length] == 0) return nil;
341     NSEnumerator* keyEnum = [[self cookieToButtonMapping] keyEnumerator];
342     NSString* key;
343     while(key = [keyEnum nextObject]) {
344         NSRange range = [cookieString rangeOfString:key];
345         if (range.location == 0) return key;
346     }
347     return nil;
348 }
349
350 - (void) sendSimulatedPlusMinusEvent: (id) time {
351     BOOL startSimulateHold = NO;
352     AppleRemoteEventIdentifier event = lastPlusMinusEvent;
353     @synchronized(self) {
354         startSimulateHold = (lastPlusMinusEvent>0 && lastPlusMinusEventTime == [time doubleValue]);
355     }
356     if (startSimulateHold) {
357         lastEventSimulatedHold = YES;
358         event = (event==kRemoteButtonVolume_Plus) ? kRemoteButtonVolume_Plus_Hold : kRemoteButtonVolume_Minus_Hold;
359         [delegate appleRemoteButton:event pressedDown: YES clickCount: 1];
360     }
361 }
362
363 - (void) sendRemoteButtonEvent: (AppleRemoteEventIdentifier) event pressedDown: (BOOL) pressedDown {
364     if (delegate) {
365         if (simulatePlusMinusHold) {
366             if (event == kRemoteButtonVolume_Plus || event == kRemoteButtonVolume_Minus) {
367                 if (pressedDown) {
368                     lastPlusMinusEvent = event;
369                     lastPlusMinusEventTime = [NSDate timeIntervalSinceReferenceDate];
370                     [self performSelector:@selector(sendSimulatedPlusMinusEvent:)
371                                withObject:[NSNumber numberWithDouble:lastPlusMinusEventTime]
372                                afterDelay:HOLD_RECOGNITION_TIME_INTERVAL];
373                     return;
374                 } else {
375                     if (lastEventSimulatedHold) {
376                         event = (event==kRemoteButtonVolume_Plus) ? kRemoteButtonVolume_Plus_Hold : kRemoteButtonVolume_Minus_Hold;
377                         lastPlusMinusEvent = 0;
378                         lastEventSimulatedHold = NO;
379                     } else {
380                         @synchronized(self) {
381                             lastPlusMinusEvent = 0;
382                         }
383                         pressedDown = YES;
384                     }
385                 }
386             }
387         }
388
389         if (([self clickCountEnabledButtons] & event) == event) {
390             if (pressedDown==NO && (event == kRemoteButtonVolume_Minus || event == kRemoteButtonVolume_Plus)) {
391                 return; // this one is triggered automatically by the handler
392             }
393             NSNumber* eventNumber;
394             NSNumber* timeNumber;
395             @synchronized(self) {
396                 lastClickCountEventTime = [NSDate timeIntervalSinceReferenceDate];
397                 if (lastClickCountEvent == event) {
398                     eventClickCount = eventClickCount + 1;
399                 } else {
400                     eventClickCount = 1;
401                 }
402                 lastClickCountEvent = event;
403                 timeNumber = [NSNumber numberWithDouble:lastClickCountEventTime];
404                 eventNumber= [NSNumber numberWithUnsignedInt:event];
405             }
406             [self performSelector: @selector(executeClickCountEvent:)
407                        withObject: [NSArray arrayWithObjects:eventNumber, timeNumber, nil]
408                        afterDelay: maxClickTimeDifference];
409         } else {
410             [delegate appleRemoteButton:event pressedDown: pressedDown clickCount:1];
411         }
412     }
413 }
414
415 - (void) executeClickCountEvent: (NSArray*) values {
416     AppleRemoteEventIdentifier event = [[values objectAtIndex: 0] unsignedIntValue];
417     NSTimeInterval eventTimePoint = [[values objectAtIndex: 1] doubleValue];
418
419     BOOL finishedClicking = NO;
420     int finalClickCount = eventClickCount;
421
422     @synchronized(self) {
423         finishedClicking = (event != lastClickCountEvent || eventTimePoint == lastClickCountEventTime);
424         if (finishedClicking) eventClickCount = 0;
425     }
426
427     if (finishedClicking) {
428         [delegate appleRemoteButton:event pressedDown: YES clickCount:finalClickCount];
429         if ([self simulatesPlusMinusHold]==NO && (event == kRemoteButtonVolume_Minus || event == kRemoteButtonVolume_Plus)) {
430             // trigger a button release event, too
431             [NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow:0.1]];
432             [delegate appleRemoteButton:event pressedDown: NO clickCount:finalClickCount];
433         }
434     }
435
436 }
437
438 - (void) handleEventWithCookieString: (NSString*) cookieString sumOfValues: (SInt32) sumOfValues {
439     /*
440     if (previousRemainingCookieString) {
441         cookieString = [previousRemainingCookieString stringByAppendingString: cookieString];
442         NSLog(@"New cookie string is %@", cookieString);
443         [previousRemainingCookieString release], previousRemainingCookieString=nil;
444     }*/
445     if (cookieString == nil || [cookieString length] == 0) return;
446     NSNumber* buttonId = [[self cookieToButtonMapping] objectForKey: cookieString];
447     if (buttonId != nil) {
448         [self sendRemoteButtonEvent: [buttonId intValue] pressedDown: (sumOfValues>0)];
449     } else {
450         // let's see if a number of events are stored in the cookie string. this does
451         // happen when the main thread is too busy to handle all incoming events in time.
452         NSString* subCookieString;
453         NSString* lastSubCookieString=nil;
454         while(subCookieString = [self validCookieSubstring: cookieString]) {
455             cookieString = [cookieString substringFromIndex: [subCookieString length]];
456             lastSubCookieString = subCookieString;
457             if (processesBacklog) [self handleEventWithCookieString: subCookieString sumOfValues:sumOfValues];
458         }
459         if (processesBacklog == NO && lastSubCookieString != nil) {
460             // process the last event of the backlog and assume that the button is not pressed down any longer.
461             // The events in the backlog do not seem to be in order and therefore (in rare cases) the last event might be
462             // a button pressed down event while in reality the user has released it.
463             // NSLog(@"processing last event of backlog");
464             [self handleEventWithCookieString: lastSubCookieString sumOfValues:0];
465         }
466         if ([cookieString length] > 0) {
467             NSLog(@"Unknown button for cookiestring %@", cookieString);
468         }
469     }
470 }
471
472 @end
473
474 /*  Callback method for the device queue
475 Will be called for any event of any type (cookie) to which we subscribe
476 */
477 static void QueueCallbackFunction(void* target,  IOReturn result, void* refcon, void* sender) {
478     AppleRemote* remote = (AppleRemote*)target;
479
480     IOHIDEventStruct event;
481     AbsoluteTime     zeroTime = {0,0};
482     NSMutableString* cookieString = [NSMutableString string];
483     SInt32           sumOfValues = 0;
484     while (result == kIOReturnSuccess)
485     {
486         result = (*[remote queue])->getNextEvent([remote queue], &event, zeroTime, 0);
487         if ( result != kIOReturnSuccess )
488             continue;
489
490         //printf("%d %d %d\n", event.elementCookie, event.value, event.longValue);
491
492         if (REMOTE_SWITCH_COOKIE == (int)event.elementCookie) {
493             [remote setRemoteId: event.value];
494             [remote handleEventWithCookieString: @"19_" sumOfValues: 0];
495         } else {
496             if (((int)event.elementCookie)!=5) {
497                 sumOfValues+=event.value;
498                 [cookieString appendString:[NSString stringWithFormat:@"%d_", event.elementCookie]];
499             }
500         }
501     }
502
503     [remote handleEventWithCookieString: cookieString sumOfValues: sumOfValues];
504 }
505
506 @implementation AppleRemote (IOKitMethods)
507
508 - (IOHIDDeviceInterface**) createInterfaceForDevice: (io_object_t) hidDevice {
509     io_name_t               className;
510     IOCFPlugInInterface**   plugInInterface = NULL;
511     HRESULT                 plugInResult = S_OK;
512     SInt32                  score = 0;
513     IOReturn                ioReturnValue = kIOReturnSuccess;
514
515     hidDeviceInterface = NULL;
516
517     ioReturnValue = IOObjectGetClass(hidDevice, className);
518
519     if (ioReturnValue != kIOReturnSuccess) {
520         NSLog(@"Error: Failed to get class name.");
521         return NULL;
522     }
523
524     ioReturnValue = IOCreatePlugInInterfaceForService(hidDevice,
525                                                       kIOHIDDeviceUserClientTypeID,
526                                                       kIOCFPlugInInterfaceID,
527                                                       &plugInInterface,
528                                                       &score);
529     if (ioReturnValue == kIOReturnSuccess)
530     {
531         //Call a method of the intermediate plug-in to create the device interface
532         plugInResult = (*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID), (LPVOID) &hidDeviceInterface);
533
534         if (plugInResult != S_OK) {
535             NSLog(@"Error: Couldn't create HID class device interface");
536         }
537         // Release
538         if (plugInInterface) (*plugInInterface)->Release(plugInInterface);
539     }
540     return hidDeviceInterface;
541 }
542
543 - (io_object_t) findAppleRemoteDevice {
544     CFMutableDictionaryRef hidMatchDictionary = NULL;
545     IOReturn ioReturnValue = kIOReturnSuccess;
546     io_iterator_t hidObjectIterator = 0;
547     io_object_t hidDevice = 0;
548
549     // Set up a matching dictionary to search the I/O Registry by class
550     // name for all HID class devices
551     hidMatchDictionary = IOServiceMatching(AppleRemoteDeviceName);
552
553     // Now search I/O Registry for matching devices.
554     ioReturnValue = IOServiceGetMatchingServices(kIOMasterPortDefault, hidMatchDictionary, &hidObjectIterator);
555
556     if ((ioReturnValue == kIOReturnSuccess) && (hidObjectIterator != 0)) {
557         hidDevice = IOIteratorNext(hidObjectIterator);
558     }
559
560     // release the iterator
561     IOObjectRelease(hidObjectIterator);
562
563     return hidDevice;
564 }
565
566 - (BOOL) initializeCookies {
567     IOHIDDeviceInterface122** handle = (IOHIDDeviceInterface122**)hidDeviceInterface;
568     IOHIDElementCookie      cookie;
569     long                    usage;
570     long                    usagePage;
571     id                      object;
572     NSArray*                elements = nil;
573     NSDictionary*           element;
574     IOReturn success;
575
576     if (!handle || !(*handle)) return NO;
577
578     /* Copy all elements, since we're grabbing most of the elements
579      * for this device anyway, and thus, it's faster to iterate them
580      * ourselves. When grabbing only one or two elements, a matching
581      * dictionary should be passed in here instead of NULL. */
582     success = (*handle)->copyMatchingElements(handle, NULL, (CFArrayRef*)&elements);
583
584     if (success == kIOReturnSuccess) {
585
586         [elements autorelease];
587         /*
588         cookies = calloc(NUMBER_OF_APPLE_REMOTE_ACTIONS, sizeof(IOHIDElementCookie));
589         memset(cookies, 0, sizeof(IOHIDElementCookie) * NUMBER_OF_APPLE_REMOTE_ACTIONS);
590         */
591         allCookies = [[NSMutableArray alloc] init];
592         int i;
593         for (i=0; i< [elements count]; i++) {
594             element = [elements objectAtIndex:i];
595
596             //Get cookie
597             object = [element valueForKey: (NSString*)CFSTR(kIOHIDElementCookieKey) ];
598             if (object == nil || ![object isKindOfClass:[NSNumber class]]) continue;
599             if (object == 0 || CFGetTypeID(object) != CFNumberGetTypeID()) continue;
600             cookie = (IOHIDElementCookie) [object longValue];
601
602             //Get usage
603             object = [element valueForKey: (NSString*)CFSTR(kIOHIDElementUsageKey) ];
604             if (object == nil || ![object isKindOfClass:[NSNumber class]]) continue;
605             usage = [object longValue];
606
607             //Get usage page
608             object = [element valueForKey: (NSString*)CFSTR(kIOHIDElementUsagePageKey) ];
609             if (object == nil || ![object isKindOfClass:[NSNumber class]]) continue;
610             usagePage = [object longValue];
611
612             [allCookies addObject: [NSNumber numberWithInt:(int)cookie]];
613         }
614     } else {
615         return NO;
616     }
617
618     return YES;
619 }
620
621 - (BOOL) openDevice {
622     HRESULT  result;
623
624     IOHIDOptionsType openMode = kIOHIDOptionsTypeNone;
625     if ([self isOpenInExclusiveMode]) openMode = kIOHIDOptionsTypeSeizeDevice;
626     IOReturn ioReturnValue = (*hidDeviceInterface)->open(hidDeviceInterface, openMode);
627
628     if (ioReturnValue == KERN_SUCCESS) {
629         queue = (*hidDeviceInterface)->allocQueue(hidDeviceInterface);
630         if (queue) {
631             result = (*queue)->create(queue, 0, 12);    //depth: maximum number of elements in queue before oldest elements in queue begin to be lost.
632
633             int i=0;
634             for(i=0; i<[allCookies count]; i++) {
635                 IOHIDElementCookie cookie = (IOHIDElementCookie)[[allCookies objectAtIndex:i] intValue];
636                 (*queue)->addElement(queue, cookie, 0);
637             }
638
639             // add callback for async events
640             CFRunLoopSourceRef eventSource;
641             ioReturnValue = (*queue)->createAsyncEventSource(queue, &eventSource);
642             if (ioReturnValue == KERN_SUCCESS) {
643                 ioReturnValue = (*queue)->setEventCallout(queue,QueueCallbackFunction, self, NULL);
644                 if (ioReturnValue == KERN_SUCCESS) {
645                     CFRunLoopAddSource(CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
646                     //start data delivery to queue
647                     (*queue)->start(queue);
648                     return YES;
649                 } else {
650                     NSLog(@"Error when setting event callout");
651                 }
652             } else {
653                 NSLog(@"Error when creating async event source");
654             }
655         } else {
656             NSLog(@"Error when opening device");
657         }
658     }
659     return NO;
660 }
661
662 @end
663
664 @implementation AppleRemoteApplicationDelegate
665
666 - (id) initWithApplicationDelegate: (id) delegate {
667     if (self = [super init]) {
668         applicationDelegate = [delegate retain];
669     }
670     return self;
671 }
672
673 - (void) dealloc {
674     NSLog(@"Dealloc");
675     [applicationDelegate release];
676     [super dealloc];
677 }
678
679 - (id) applicationDelegate {
680     return applicationDelegate;
681 }
682
683 - (void)applicationWillBecomeActive:(NSNotification *)aNotification {
684     if ([applicationDelegate respondsToSelector: @selector(applicationWillBecomeActive:)]) {
685         [applicationDelegate applicationWillBecomeActive: aNotification];
686     }
687 }
688 - (void)applicationDidBecomeActive:(NSNotification *)aNotification {
689     [[AppleRemote sharedRemote] setListeningToRemote: YES];
690
691     if ([applicationDelegate respondsToSelector: @selector(applicationDidBecomeActive:)]) {
692         [applicationDelegate applicationDidBecomeActive: aNotification];
693     }
694 }
695 - (void)applicationWillResignActive:(NSNotification *)aNotification {
696     [[AppleRemote sharedRemote] setListeningToRemote: NO];
697
698     if ([applicationDelegate respondsToSelector: @selector(applicationWillResignActive:)]) {
699         [applicationDelegate applicationWillResignActive: aNotification];
700     }
701 }
702 - (void)applicationDidResignActive:(NSNotification *)aNotification {
703     if ([applicationDelegate respondsToSelector: @selector(applicationDidResignActive:)]) {
704         [applicationDelegate applicationDidResignActive: aNotification];
705     }
706 }
707
708 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
709     NSMethodSignature* signature = [super methodSignatureForSelector: aSelector];
710     if (signature == nil && applicationDelegate != nil) {
711         signature = [applicationDelegate methodSignatureForSelector: aSelector];
712     }
713     return signature;
714 }
715
716 - (void)forwardInvocation:(NSInvocation *)invocation {
717     SEL aSelector = [invocation selector];
718
719     if (applicationDelegate==nil || [applicationDelegate respondsToSelector:aSelector]==NO) {
720         [super forwardInvocation: invocation];
721         return;
722     }
723
724     [invocation invokeWithTarget:applicationDelegate];
725 }
726 @end