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