AppleRemote.m 25.7 KB
Newer Older
1 2 3
/*****************************************************************************
 * AppleRemote.m
 * AppleRemote
4
 * $Id$
5
 *
6
 * Created by Martin Kahr on 11.03.06 under a MIT-style license.
7 8
 * Copyright (c) 2006 martinkahr.com. All rights reserved.
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a
10 11 12 13 14 15 16 17 18 19 20
 * 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,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 23 24 25 26 27 28 29
 * 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.
 *
 *****************************************************************************
 *
 * 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 34
 * Thus, the following statements apply to our changes:
 *
35
 * Copyright (C) 2006-2007 the VideoLAN team
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
 * Authors: Eric Petit <titer@m0k.org>
 *          Felix Kühne <fkuehne at videolan dot org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/
53 54 55

#import "AppleRemote.h"

56 57 58
/* this was added by the VideoLAN team to ensure Leopard-compatibility and is VLC-only */
#import "intf.h"

59 60
const char* AppleRemoteDeviceName = "AppleIRController";
const int REMOTE_SWITCH_COOKIE=19;
61 62
const NSTimeInterval DEFAULT_MAXIMUM_CLICK_TIME_DIFFERENCE=0.35;
const NSTimeInterval HOLD_RECOGNITION_TIME_INTERVAL=0.4;
63 64 65

@implementation AppleRemote

66 67
#pragma public interface

68
- (id) init {
69 70 71 72 73 74 75
    if ( self = [super init] ) {
        openInExclusiveMode = YES;
        queue = NULL;
        hidDeviceInterface = NULL;
        cookieToButtonMapping = [[NSMutableDictionary alloc] init];

        [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonVolume_Plus]  forKey:@"14_12_11_6_"];
76 77
        [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonVolume_Minus] forKey:@"14_13_11_6_"];
        [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonMenu]         forKey:@"14_7_6_14_7_6_"];
78 79 80 81 82 83 84
        [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonPlay]         forKey:@"14_8_6_14_8_6_"];
        [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonRight]        forKey:@"14_9_6_14_9_6_"];
        [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonLeft]         forKey:@"14_10_6_14_10_6_"];
        [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonRight_Hold]   forKey:@"14_6_4_2_"];
        [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonLeft_Hold]    forKey:@"14_6_3_2_"];
        [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonMenu_Hold]    forKey:@"14_6_14_6_"];
        [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteButtonPlay_Sleep]   forKey:@"18_14_6_18_14_6_"];
85
        [cookieToButtonMapping setObject:[NSNumber numberWithInt:kRemoteControl_Switched]   forKey:@"19_"];
86 87 88 89 90 91 92

        /* defaults */
        [self setSimulatesPlusMinusHold: YES];
        maxClickTimeDifference = DEFAULT_MAXIMUM_CLICK_TIME_DIFFERENCE;
    }

    return self;
93 94 95
}

- (void) dealloc {
96 97 98
    [self stopListening:self];
    [cookieToButtonMapping release];
    [super dealloc];
99 100
}

101 102 103 104 105 106 107 108 109
/* this was added by the VideoLAN team to ensure Leopard-compatibility and is VLC-only */
#if GC_ENABLED
- (void)finalize
{
    [self stopListening: self];
    [super finalize];
}
#endif

110
- (int) remoteId {
111
    return remoteId;
112 113
}

114
- (BOOL) isRemoteAvailable {
115 116 117 118 119
    io_object_t hidDevice = [self findAppleRemoteDevice];
    if (hidDevice != 0) {
        IOObjectRelease(hidDevice);
        return YES;
    } else {
120
        return NO;
121
    }
122 123 124
}

- (BOOL) isListeningToRemote {
125
    return (hidDeviceInterface != NULL && allCookies != NULL && queue != NULL);
126 127 128
}

- (void) setListeningToRemote: (BOOL) value {
129 130 131 132 133
    if (value == NO) {
        [self stopListening:self];
    } else {
        [self startListening:self];
    }
134 135
}

136 137
/* Delegates are not retained!
 * http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/chapter_6_section_4.html
138
 * Delegating objects do not (and should not) retain their delegates.
139 140
 * However, clients of delegating objects (applications, usually) are responsible for ensuring that their delegates are around
 * to receive delegation messages. To do this, they may have to retain the delegate. */
141
- (void) setDelegate: (id) _delegate {
142 143 144
    if (_delegate && [_delegate respondsToSelector:@selector(appleRemoteButton:pressedDown:clickCount:)]==NO) return;

    delegate = _delegate;
145 146
}
- (id) delegate {
147
    return delegate;
148 149 150
}

- (BOOL) isOpenInExclusiveMode {
151
    return openInExclusiveMode;
152 153
}
- (void) setOpenInExclusiveMode: (BOOL) value {
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
    openInExclusiveMode = value;
}

- (BOOL) clickCountingEnabled {
    return clickCountEnabledButtons != 0;
}
- (void) setClickCountingEnabled: (BOOL) value {
    if (value) {
        [self setClickCountEnabledButtons: kRemoteButtonVolume_Plus | kRemoteButtonVolume_Minus | kRemoteButtonPlay | kRemoteButtonLeft | kRemoteButtonRight | kRemoteButtonMenu];
    } else {
        [self setClickCountEnabledButtons: 0];
    }
}

- (unsigned int) clickCountEnabledButtons {
    return clickCountEnabledButtons;
}
- (void) setClickCountEnabledButtons: (unsigned int)value {
    clickCountEnabledButtons = value;
}

- (NSTimeInterval) maximumClickCountTimeDifference {
    return maxClickTimeDifference;
}
- (void) setMaximumClickCountTimeDifference: (NSTimeInterval) timeDiff {
    maxClickTimeDifference = timeDiff;
}

- (BOOL) processesBacklog {
    return processesBacklog;
}
- (void) setProcessesBacklog: (BOOL) value {
    processesBacklog = value;
}

- (BOOL) listeningOnAppActivate {
    id appDelegate = [NSApp delegate];
    return (appDelegate!=nil && [appDelegate isKindOfClass: [AppleRemoteApplicationDelegate class]]);
}
- (void) setListeningOnAppActivate: (BOOL) value {
    if (value) {
        if ([self listeningOnAppActivate]) return;
        AppleRemoteApplicationDelegate* appDelegate = [[AppleRemoteApplicationDelegate alloc] initWithApplicationDelegate: [NSApp delegate]];
        /* NSApp does not retain its delegate therefore we keep retain count on 1 */
        [NSApp setDelegate: appDelegate];
    } else {
        if ([self listeningOnAppActivate]==NO) return;
        AppleRemoteApplicationDelegate* appDelegate = (AppleRemoteApplicationDelegate*)[NSApp delegate];
        id previousAppDelegate = [appDelegate applicationDelegate];
        [NSApp setDelegate: previousAppDelegate];
        [appDelegate release];
    }
}

- (BOOL) simulatesPlusMinusHold {
    return simulatePlusMinusHold;
}
- (void) setSimulatesPlusMinusHold: (BOOL) value {
    simulatePlusMinusHold = value;
}

215
- (IBAction) startListening: (id) sender {
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    if ([self isListeningToRemote]) return;

    io_object_t hidDevice = [self findAppleRemoteDevice];
    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;

234
error:
235 236
    [self stopListening:self];

237
cleanup:
238
    IOObjectRelease(hidDevice);
239 240 241
}

- (IBAction) stopListening: (id) sender {
242
    if (queue != NULL) {
243
        (*queue)->stop(queue);
244 245

        //dispose of queue
246
        (*queue)->dispose(queue);
247 248

        //release the queue we allocated
249
        (*queue)->Release(queue);
250 251 252 253 254 255 256 257 258 259 260 261 262

        queue = NULL;
    }

    if (allCookies != nil) {
        [allCookies autorelease];
        allCookies = nil;
    }

    if (hidDeviceInterface != NULL) {
        //close the device
        (*hidDeviceInterface)->close(hidDeviceInterface);

263
        //release the interface
264 265
        (*hidDeviceInterface)->Release(hidDeviceInterface);

266 267
        hidDeviceInterface = NULL;
    }
268 269 270 271
}

@end

272
@implementation AppleRemote (Singleton)
273 274 275

static AppleRemote* sharedInstance=nil;

276
+ (AppleRemote*) sharedRemote {
277
    @synchronized(self) {
278
        if (sharedInstance == nil) {
279 280 281
            sharedInstance = [[self alloc] init];
        }
    }
282
    return sharedInstance;
283 284 285 286 287 288
}
+ (id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if (sharedInstance == nil) {
            return [super allocWithZone:zone];
        }
289
    }
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    return sharedInstance;
}
- (id)copyWithZone:(NSZone *)zone {
    return self;
}
- (id)retain {
    return self;
}
- (unsigned)retainCount {
    return UINT_MAX;  //denotes an object that cannot be released
}
- (void)release {
    //do nothing
}
- (id)autorelease {
    return self;
}

@end

310
@implementation AppleRemote (PrivateMethods)
311

312 313 314 315
- (void) setRemoteId: (int) value {
    remoteId = value;
}

316
- (IOHIDQueueInterface**) queue {
317
    return queue;
318 319 320
}

- (IOHIDDeviceInterface**) hidDeviceInterface {
321
    return hidDeviceInterface;
322 323 324 325
}


- (NSDictionary*) cookieToButtonMapping {
326 327 328 329 330 331 332 333 334
    return cookieToButtonMapping;
}

- (NSString*) validCookieSubstring: (NSString*) cookieString {
    if (cookieString == nil || [cookieString length] == 0) return nil;
    NSEnumerator* keyEnum = [[self cookieToButtonMapping] keyEnumerator];
    NSString* key;
    while(key = [keyEnum nextObject]) {
        NSRange range = [cookieString rangeOfString:key];
335
        if (range.location == 0) return key;
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
    }
    return nil;
}

- (void) sendSimulatedPlusMinusEvent: (id) time {
    BOOL startSimulateHold = NO;
    AppleRemoteEventIdentifier event = lastPlusMinusEvent;
    @synchronized(self) {
        startSimulateHold = (lastPlusMinusEvent>0 && lastPlusMinusEventTime == [time doubleValue]);
    }
    if (startSimulateHold) {
        lastEventSimulatedHold = YES;
        event = (event==kRemoteButtonVolume_Plus) ? kRemoteButtonVolume_Plus_Hold : kRemoteButtonVolume_Minus_Hold;
        [delegate appleRemoteButton:event pressedDown: YES clickCount: 1];
    }
}

- (void) sendRemoteButtonEvent: (AppleRemoteEventIdentifier) event pressedDown: (BOOL) pressedDown {
    if (delegate) {
        if (simulatePlusMinusHold) {
            if (event == kRemoteButtonVolume_Plus || event == kRemoteButtonVolume_Minus) {
                if (pressedDown) {
                    lastPlusMinusEvent = event;
                    lastPlusMinusEventTime = [NSDate timeIntervalSinceReferenceDate];
360
                    [self performSelector:@selector(sendSimulatedPlusMinusEvent:)
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
                               withObject:[NSNumber numberWithDouble:lastPlusMinusEventTime]
                               afterDelay:HOLD_RECOGNITION_TIME_INTERVAL];
                    return;
                } else {
                    if (lastEventSimulatedHold) {
                        event = (event==kRemoteButtonVolume_Plus) ? kRemoteButtonVolume_Plus_Hold : kRemoteButtonVolume_Minus_Hold;
                        lastPlusMinusEvent = 0;
                        lastEventSimulatedHold = NO;
                    } else {
                        @synchronized(self) {
                            lastPlusMinusEvent = 0;
                        }
                        pressedDown = YES;
                    }
                }
            }
        }

        if (([self clickCountEnabledButtons] & event) == event) {
            if (pressedDown==NO && (event == kRemoteButtonVolume_Minus || event == kRemoteButtonVolume_Plus)) {
                return; // this one is triggered automatically by the handler
            }
            NSNumber* eventNumber;
            NSNumber* timeNumber;
            @synchronized(self) {
                lastClickCountEventTime = [NSDate timeIntervalSinceReferenceDate];
                if (lastClickCountEvent == event) {
                    eventClickCount = eventClickCount + 1;
                } else {
                    eventClickCount = 1;
                }
                lastClickCountEvent = event;
                timeNumber = [NSNumber numberWithDouble:lastClickCountEventTime];
                eventNumber= [NSNumber numberWithUnsignedInt:event];
            }
396
            [self performSelector: @selector(executeClickCountEvent:)
397 398 399 400
                       withObject: [NSArray arrayWithObjects:eventNumber, timeNumber, nil]
                       afterDelay: maxClickTimeDifference];
        } else {
            [delegate appleRemoteButton:event pressedDown: pressedDown clickCount:1];
401
        }
402 403 404 405
    }
}

- (void) executeClickCountEvent: (NSArray*) values {
406
    AppleRemoteEventIdentifier event = [[values objectAtIndex: 0] unsignedIntValue];
407 408 409
    NSTimeInterval eventTimePoint = [[values objectAtIndex: 1] doubleValue];

    BOOL finishedClicking = NO;
410
    int finalClickCount = eventClickCount;
411 412 413

    @synchronized(self) {
        finishedClicking = (event != lastClickCountEvent || eventTimePoint == lastClickCountEventTime);
414
        if (finishedClicking) eventClickCount = 0;
415 416
    }

417 418
    if (finishedClicking) {
        [delegate appleRemoteButton:event pressedDown: YES clickCount:finalClickCount];
419 420 421 422 423 424 425
        if ([self simulatesPlusMinusHold]==NO && (event == kRemoteButtonVolume_Minus || event == kRemoteButtonVolume_Plus)) {
            // trigger a button release event, too
            [NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow:0.1]];
            [delegate appleRemoteButton:event pressedDown: NO clickCount:finalClickCount];
        }
    }

426 427 428
}

- (void) handleEventWithCookieString: (NSString*) cookieString sumOfValues: (SInt32) sumOfValues {
429 430 431 432
    /*
    if (previousRemainingCookieString) {
        cookieString = [previousRemainingCookieString stringByAppendingString: cookieString];
        NSLog(@"New cookie string is %@", cookieString);
433
        [previousRemainingCookieString release], previousRemainingCookieString=nil;
434 435 436 437 438 439 440 441 442 443
    }*/
    if (cookieString == nil || [cookieString length] == 0) return;
    NSNumber* buttonId = [[self cookieToButtonMapping] objectForKey: cookieString];
    if (buttonId != nil) {
        [self sendRemoteButtonEvent: [buttonId intValue] pressedDown: (sumOfValues>0)];
    } else {
        // 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;
444
        while(subCookieString = [self validCookieSubstring: cookieString]) {
445 446 447 448 449 450
            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.
451 452
            // 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.
453 454 455 456 457
            // NSLog(@"processing last event of backlog");
            [self handleEventWithCookieString: lastSubCookieString sumOfValues:0];
        }
        if ([cookieString length] > 0) {
            NSLog(@"Unknown button for cookiestring %@", cookieString);
458
        }
459
    }
460 461 462 463
}

@end

464
/*  Callback method for the device queue
465 466
Will be called for any event of any type (cookie) to which we subscribe
*/
467
static void QueueCallbackFunction(void* target,  IOReturn result, void* refcon, void* sender) {
468 469
    AppleRemote* remote = (AppleRemote*)target;

470
    IOHIDEventStruct event;
471 472 473 474 475
    AbsoluteTime     zeroTime = {0,0};
    NSMutableString* cookieString = [NSMutableString string];
    SInt32           sumOfValues = 0;
    while (result == kIOReturnSuccess)
    {
476
        result = (*[remote queue])->getNextEvent([remote queue], &event, zeroTime, 0);
477 478 479
        if ( result != kIOReturnSuccess )
            continue;

480
        //printf("%d %d %d\n", event.elementCookie, event.value, event.longValue);
481 482 483 484 485 486 487 488 489

        if (REMOTE_SWITCH_COOKIE == (int)event.elementCookie) {
            [remote setRemoteId: event.value];
            [remote handleEventWithCookieString: @"19_" sumOfValues: 0];
        } else {
            if (((int)event.elementCookie)!=5) {
                sumOfValues+=event.value;
                [cookieString appendString:[NSString stringWithFormat:@"%d_", event.elementCookie]];
            }
490
        }
491 492
    }

493
    [remote handleEventWithCookieString: cookieString sumOfValues: sumOfValues];
494 495 496 497 498
}

@implementation AppleRemote (IOKitMethods)

- (IOHIDDeviceInterface**) createInterfaceForDevice: (io_object_t) hidDevice {
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
    io_name_t               className;
    IOCFPlugInInterface**   plugInInterface = NULL;
    HRESULT                 plugInResult = S_OK;
    SInt32                  score = 0;
    IOReturn                ioReturnValue = kIOReturnSuccess;

    hidDeviceInterface = NULL;

    ioReturnValue = IOObjectGetClass(hidDevice, className);

    if (ioReturnValue != kIOReturnSuccess) {
        NSLog(@"Error: Failed to get class name.");
        return NULL;
    }

    ioReturnValue = IOCreatePlugInInterfaceForService(hidDevice,
                                                      kIOHIDDeviceUserClientTypeID,
                                                      kIOCFPlugInInterfaceID,
                                                      &plugInInterface,
                                                      &score);
    if (ioReturnValue == kIOReturnSuccess)
    {
        //Call a method of the intermediate plug-in to create the device interface
        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;
531 532 533
}

- (io_object_t) findAppleRemoteDevice {
534
    CFMutableDictionaryRef hidMatchDictionary = NULL;
535
    IOReturn ioReturnValue = kIOReturnSuccess;
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    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(AppleRemoteDeviceName);

    // 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);

    return hidDevice;
554 555 556
}

- (BOOL) initializeCookies {
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    IOHIDDeviceInterface122** handle = (IOHIDDeviceInterface122**)hidDeviceInterface;
    IOHIDElementCookie      cookie;
    long                    usage;
    long                    usagePage;
    id                      object;
    NSArray*                elements = nil;
    NSDictionary*           element;
    IOReturn success;

    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. */
    success = (*handle)->copyMatchingElements(handle, NULL, (CFArrayRef*)&elements);

    if (success == kIOReturnSuccess) {

576
        [elements autorelease];
577
        /*
578
        cookies = calloc(NUMBER_OF_APPLE_REMOTE_ACTIONS, sizeof(IOHIDElementCookie));
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
        memset(cookies, 0, sizeof(IOHIDElementCookie) * NUMBER_OF_APPLE_REMOTE_ACTIONS);
        */
        allCookies = [[NSMutableArray alloc] init];
        int i;
        for (i=0; i< [elements count]; i++) {
            element = [elements objectAtIndex:i];

            //Get cookie
            object = [element valueForKey: (NSString*)CFSTR(kIOHIDElementCookieKey) ];
            if (object == nil || ![object isKindOfClass:[NSNumber class]]) continue;
            if (object == 0 || CFGetTypeID(object) != CFNumberGetTypeID()) continue;
            cookie = (IOHIDElementCookie) [object longValue];

            //Get usage
            object = [element valueForKey: (NSString*)CFSTR(kIOHIDElementUsageKey) ];
594
            if (object == nil || ![object isKindOfClass:[NSNumber class]]) continue;
595 596 597 598
            usage = [object longValue];

            //Get usage page
            object = [element valueForKey: (NSString*)CFSTR(kIOHIDElementUsagePageKey) ];
599
            if (object == nil || ![object isKindOfClass:[NSNumber class]]) continue;
600 601 602 603 604 605 606 607 608
            usagePage = [object longValue];

            [allCookies addObject: [NSNumber numberWithInt:(int)cookie]];
        }
    } else {
        return NO;
    }

    return YES;
609 610 611
}

- (BOOL) openDevice {
612 613 614
    HRESULT  result;

    IOHIDOptionsType openMode = kIOHIDOptionsTypeNone;
615 616
    if ([self isOpenInExclusiveMode]) openMode = kIOHIDOptionsTypeSeizeDevice;
    IOReturn ioReturnValue = (*hidDeviceInterface)->open(hidDeviceInterface, openMode);
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634

    if (ioReturnValue == KERN_SUCCESS) {
        queue = (*hidDeviceInterface)->allocQueue(hidDeviceInterface);
        if (queue) {
            result = (*queue)->create(queue, 0, 12);    //depth: maximum number of elements in queue before oldest elements in queue begin to be lost.

            int i=0;
            for(i=0; i<[allCookies count]; i++) {
                IOHIDElementCookie cookie = (IOHIDElementCookie)[[allCookies objectAtIndex:i] intValue];
                (*queue)->addElement(queue, cookie, 0);
            }

            // add callback for async events
            CFRunLoopSourceRef eventSource;
            ioReturnValue = (*queue)->createAsyncEventSource(queue, &eventSource);
            if (ioReturnValue == KERN_SUCCESS) {
                ioReturnValue = (*queue)->setEventCallout(queue,QueueCallbackFunction, self, NULL);
                if (ioReturnValue == KERN_SUCCESS) {
635
                    CFRunLoopAddSource(CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
636
                    //start data delivery to queue
637
                    (*queue)->start(queue);
638 639 640 641 642 643 644 645 646 647 648
                    return YES;
                } else {
                    NSLog(@"Error when setting event callout");
                }
            } else {
                NSLog(@"Error when creating async event source");
            }
        } else {
            NSLog(@"Error when opening device");
        }
    }
649
    return NO;
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
}

@end

@implementation AppleRemoteApplicationDelegate

- (id) initWithApplicationDelegate: (id) delegate {
    if (self = [super init]) {
        applicationDelegate = [delegate retain];
    }
    return self;
}

- (void) dealloc {
    NSLog(@"Dealloc");
    [applicationDelegate release];
    [super dealloc];
}

- (id) applicationDelegate {
    return applicationDelegate;
671 672
}

673 674 675 676 677 678 679 680 681 682
- (void)applicationWillBecomeActive:(NSNotification *)aNotification {
    if ([applicationDelegate respondsToSelector: @selector(applicationWillBecomeActive:)]) {
        [applicationDelegate applicationWillBecomeActive: aNotification];
    }
}
- (void)applicationDidBecomeActive:(NSNotification *)aNotification {
    [[AppleRemote sharedRemote] setListeningToRemote: YES];

    if ([applicationDelegate respondsToSelector: @selector(applicationDidBecomeActive:)]) {
        [applicationDelegate applicationDidBecomeActive: aNotification];
683
    }
684 685 686 687 688 689
}
- (void)applicationWillResignActive:(NSNotification *)aNotification {
    [[AppleRemote sharedRemote] setListeningToRemote: NO];

    if ([applicationDelegate respondsToSelector: @selector(applicationWillResignActive:)]) {
        [applicationDelegate applicationWillResignActive: aNotification];
690
    }
691 692 693 694
}
- (void)applicationDidResignActive:(NSNotification *)aNotification {
    if ([applicationDelegate respondsToSelector: @selector(applicationDidResignActive:)]) {
        [applicationDelegate applicationDidResignActive: aNotification];
695
    }
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    NSMethodSignature* signature = [super methodSignatureForSelector: aSelector];
    if (signature == nil && applicationDelegate != nil) {
        signature = [applicationDelegate methodSignatureForSelector: aSelector];
    }
    return signature;
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    SEL aSelector = [invocation selector];

    if (applicationDelegate==nil || [applicationDelegate respondsToSelector:aSelector]==NO) {
        [super forwardInvocation: invocation];
        return;
    }

    [invocation invokeWithTarget:applicationDelegate];
}
716
@end