forked from alexjsp/SpotifyMacRemote
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HIDRemote.m
2070 lines (1720 loc) · 63.9 KB
/
HIDRemote.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// HIDRemote.m
// HIDRemote V1.2 (27th May 2011)
//
// Created by Felix Schwarz on 06.04.07.
// Copyright 2007-2011 IOSPIRIT GmbH. All rights reserved.
//
// The latest version of this class is available at
// http://www.iospirit.com/developers/hidremote/
//
// ** LICENSE *************************************************************************
//
// Copyright (c) 2007-2011 IOSPIRIT GmbH (http://www.iospirit.com/)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// * Neither the name of IOSPIRIT GmbH nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ************************************************************************************
// ************************************************************************************
// ********************************** DOCUMENTATION ***********************************
// ************************************************************************************
//
// - a reference is available at http://www.iospirit.com/developers/hidremote/reference/
// - for a guide, please see http://www.iospirit.com/developers/hidremote/guide/
//
// ************************************************************************************
#import "HIDRemote.h"
// Callback Prototypes
static void HIDEventCallback( void * target,
IOReturn result,
void * refcon,
void * sender);
static void ServiceMatchingCallback( void *refCon,
io_iterator_t iterator);
static void ServiceNotificationCallback(void * refCon,
io_service_t service,
natural_t messageType,
void * messageArgument);
static void SecureInputNotificationCallback( void * refCon,
io_service_t service,
natural_t messageType,
void * messageArgument);
// Shared HIDRemote instance
static HIDRemote *sHIDRemote = nil;
@implementation HIDRemote
#pragma mark -- Init, dealloc & shared instance --
+ (HIDRemote *)sharedHIDRemote
{
if (sHIDRemote==nil)
{
sHIDRemote = [[HIDRemote alloc] init];
}
return (sHIDRemote);
}
- (id)init
{
if ((self = [super init]) != nil)
{
#ifdef HIDREMOTE_THREADSAFETY_HARDENED_NOTIFICATION_HANDLING
_runOnThread = [[NSThread currentThread] retain];
#endif
// Detect application becoming active/inactive
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_appStatusChanged:) name:NSApplicationDidBecomeActiveNotification object:[NSApplication sharedApplication]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_appStatusChanged:) name:NSApplicationWillResignActiveNotification object:[NSApplication sharedApplication]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_appStatusChanged:) name:NSApplicationWillTerminateNotification object:[NSApplication sharedApplication]];
// Handle distributed notifications
_pidString = [[NSString alloc] initWithFormat:@"%d", getpid()];
[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(_handleNotifications:) name:kHIDRemoteDNHIDRemotePing object:nil];
[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(_handleNotifications:) name:kHIDRemoteDNHIDRemoteRetry object:kHIDRemoteDNHIDRemoteRetryGlobalObject];
[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(_handleNotifications:) name:kHIDRemoteDNHIDRemoteRetry object:_pidString];
// Enabled by default: simulate hold events for plus/minus
_simulateHoldEvents = YES;
// Enabled by default: work around for a locking issue introduced with Security Update 2008-004 / 10.4.9 and beyond (credit for finding this workaround goes to Martin Kahr)
_secureEventInputWorkAround = YES;
_secureInputNotification = 0;
// Initialize instance variables
_lastSeenRemoteID = -1;
_lastSeenModel = kHIDRemoteModelUndetermined;
_unusedButtonCodes = [[NSMutableArray alloc] init];
_exclusiveLockLending = NO;
_sendExclusiveResourceReuseNotification = YES;
_applicationIsTerminating = NO;
// Send status notifications
_sendStatusNotifications = YES;
}
return (self);
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationWillTerminateNotification object:[NSApplication sharedApplication]];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationWillResignActiveNotification object:[NSApplication sharedApplication]];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationDidBecomeActiveNotification object:[NSApplication sharedApplication]];
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self name:kHIDRemoteDNHIDRemotePing object:nil];
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self name:kHIDRemoteDNHIDRemoteRetry object:kHIDRemoteDNHIDRemoteRetryGlobalObject];
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self name:kHIDRemoteDNHIDRemoteRetry object:_pidString];
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self name:nil object:nil]; /* As demanded by the documentation for -[NSDistributedNotificationCenter removeObserver:name:object:] */
[self stopRemoteControl];
[self setExclusiveLockLendingEnabled:NO];
[self setDelegate:nil];
if (_unusedButtonCodes != nil)
{
[_unusedButtonCodes release];
_unusedButtonCodes = nil;
}
#ifdef HIDREMOTE_THREADSAFETY_HARDENED_NOTIFICATION_HANDLING
[_runOnThread release];
_runOnThread = nil;
#endif
[_pidString release];
_pidString = nil;
[super dealloc];
}
#pragma mark -- PUBLIC: System Information --
+ (BOOL)isCandelairInstalled
{
mach_port_t masterPort = 0;
kern_return_t kernResult;
io_service_t matchingService = 0;
BOOL isInstalled = NO;
kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
if ((kernResult!=kIOReturnSuccess) || (masterPort==0)) { return(NO); }
if ((matchingService = IOServiceGetMatchingService(masterPort, IOServiceMatching("IOSPIRITIRController"))) != 0)
{
isInstalled = YES;
IOObjectRelease((io_object_t) matchingService);
}
mach_port_deallocate(mach_task_self(), masterPort);
return (isInstalled);
}
+ (BOOL)isCandelairInstallationRequiredForRemoteMode:(HIDRemoteMode)remoteMode
{
SInt32 systemVersion = 0;
// Determine OS version
if (Gestalt(gestaltSystemVersion, &systemVersion) == noErr)
{
switch (systemVersion)
{
case 0x1060: // OS 10.6
case 0x1061: // OS 10.6.1
// OS X 10.6(.0) and OS X 10.6.1 require the Candelair driver for to be installed,
// so that third party apps can acquire an exclusive lock on the receiver HID Device
// via IOKit.
switch (remoteMode)
{
case kHIDRemoteModeExclusive:
case kHIDRemoteModeExclusiveAuto:
if (![self isCandelairInstalled])
{
return (YES);
}
break;
default:
break;
}
break;
}
}
return (NO);
}
- (HIDRemoteAluminumRemoteSupportLevel)aluminiumRemoteSystemSupportLevel
{
HIDRemoteAluminumRemoteSupportLevel supportLevel = kHIDRemoteAluminumRemoteSupportLevelNone;
NSEnumerator *attribDictsEnum;
NSDictionary *hidAttribsDict;
attribDictsEnum = [_serviceAttribMap objectEnumerator];
while ((hidAttribsDict = [attribDictsEnum nextObject]) != nil)
{
NSNumber *deviceSupportLevel;
if ((deviceSupportLevel = [hidAttribsDict objectForKey:kHIDRemoteAluminumRemoteSupportLevel]) != nil)
{
if ([deviceSupportLevel intValue] > (int)supportLevel)
{
supportLevel = [deviceSupportLevel intValue];
}
}
}
return (supportLevel);
}
#pragma mark -- PUBLIC: Interface / API --
- (BOOL)startRemoteControl:(HIDRemoteMode)hidRemoteMode
{
if ((_mode == kHIDRemoteModeNone) && (hidRemoteMode != kHIDRemoteModeNone))
{
kern_return_t kernReturn;
CFMutableDictionaryRef matchDict=NULL;
io_service_t rootService;
do
{
// Get IOKit master port
kernReturn = IOMasterPort(bootstrap_port, &_masterPort);
if ((kernReturn!=kIOReturnSuccess) || (_masterPort==0)) { break; }
// Setup notification port
_notifyPort = IONotificationPortCreate(_masterPort);
if ((_notifyRLSource = IONotificationPortGetRunLoopSource(_notifyPort)) != NULL)
{
CFRunLoopAddSource( CFRunLoopGetCurrent(),
_notifyRLSource,
kCFRunLoopCommonModes);
}
else
{
break;
}
// Setup SecureInput notification
if ((hidRemoteMode == kHIDRemoteModeExclusive) || (hidRemoteMode == kHIDRemoteModeExclusiveAuto))
{
if ((rootService = IORegistryEntryFromPath(_masterPort, kIOServicePlane ":/")) != 0)
{
kernReturn = IOServiceAddInterestNotification( _notifyPort,
rootService,
kIOBusyInterest,
SecureInputNotificationCallback,
(void *)self,
&_secureInputNotification);
if (kernReturn != kIOReturnSuccess) { break; }
[self _updateSessionInformation];
}
else
{
break;
}
}
// Setup notification matching dict
matchDict = IOServiceMatching(kIOHIDDeviceKey);
CFRetain(matchDict);
// Actually add notification
kernReturn = IOServiceAddMatchingNotification( _notifyPort,
kIOFirstMatchNotification,
matchDict, // one reference count consumed by this call
ServiceMatchingCallback,
(void *) self,
&_matchingServicesIterator);
if (kernReturn != kIOReturnSuccess) { break; }
// Setup serviceAttribMap
_serviceAttribMap = [[NSMutableDictionary alloc] init];
if (_serviceAttribMap==nil) { break; }
// Phew .. everything went well!
_mode = hidRemoteMode;
CFRelease(matchDict);
[self _serviceMatching:_matchingServicesIterator];
[self _postStatusWithAction:kHIDRemoteDNStatusActionStart];
return (YES);
}while(0);
// An error occured. Do necessary clean up.
if (matchDict!=NULL)
{
CFRelease(matchDict);
matchDict = NULL;
}
[self stopRemoteControl];
}
return (NO);
}
- (void)stopRemoteControl
{
UInt32 serviceCount = 0;
_autoRecover = NO;
_isStopping = YES;
if (_autoRecoveryTimer!=nil)
{
[_autoRecoveryTimer invalidate];
[_autoRecoveryTimer release];
_autoRecoveryTimer = nil;
}
if (_serviceAttribMap!=nil)
{
NSDictionary *cloneDict = [[NSDictionary alloc] initWithDictionary:_serviceAttribMap];
if (cloneDict!=nil)
{
NSEnumerator *mapKeyEnum = [cloneDict keyEnumerator];
NSNumber *serviceValue;
while ((serviceValue = [mapKeyEnum nextObject]) != nil)
{
[self _destructService:(io_object_t)[serviceValue unsignedIntValue]];
serviceCount++;
};
[cloneDict release];
cloneDict = nil;
}
[_serviceAttribMap release];
_serviceAttribMap = nil;
}
if (_matchingServicesIterator!=0)
{
IOObjectRelease((io_object_t) _matchingServicesIterator);
_matchingServicesIterator = 0;
}
if (_secureInputNotification!=0)
{
IOObjectRelease((io_object_t) _secureInputNotification);
_secureInputNotification = 0;
}
if (_notifyRLSource!=NULL)
{
CFRunLoopSourceInvalidate(_notifyRLSource);
_notifyRLSource = NULL;
}
if (_notifyPort!=NULL)
{
IONotificationPortDestroy(_notifyPort);
_notifyPort = NULL;
}
if (_masterPort!=0)
{
mach_port_deallocate(mach_task_self(), _masterPort);
_masterPort = 0;
}
if (_returnToPID!=nil)
{
[_returnToPID release];
_returnToPID = nil;
}
if (_mode!=kHIDRemoteModeNone)
{
// Post status
[self _postStatusWithAction:kHIDRemoteDNStatusActionStop];
if (_sendStatusNotifications)
{
// In case we were not ready to lend it earlier, tell other HIDRemote apps that the resources (if any were used) are now again available for use by other applications
if (((_mode==kHIDRemoteModeExclusive) || (_mode==kHIDRemoteModeExclusiveAuto)) && (_sendExclusiveResourceReuseNotification==YES) && (_exclusiveLockLending==NO) && (serviceCount>0))
{
_mode = kHIDRemoteModeNone;
if (!_isRestarting)
{
[[NSDistributedNotificationCenter defaultCenter] postNotificationName:kHIDRemoteDNHIDRemoteRetry
object:kHIDRemoteDNHIDRemoteRetryGlobalObject
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithUnsignedInt:(unsigned int)getpid()], kHIDRemoteDNStatusPIDKey,
[[NSBundle mainBundle] bundleIdentifier], (NSString *)kCFBundleIdentifierKey,
nil]
deliverImmediately:YES];
}
}
}
}
_mode = kHIDRemoteModeNone;
_isStopping = NO;
}
- (BOOL)isStarted
{
return (_mode != kHIDRemoteModeNone);
}
- (HIDRemoteMode)startedInMode
{
return (_mode);
}
- (unsigned)activeRemoteControlCount
{
return ([_serviceAttribMap count]);
}
- (SInt32)lastSeenRemoteControlID
{
return (_lastSeenRemoteID);
}
- (HIDRemoteModel)lastSeenModel
{
return (_lastSeenModel);
}
- (void)setLastSeenModel:(HIDRemoteModel)aModel
{
_lastSeenModel = aModel;
}
- (void)setSimulateHoldEvents:(BOOL)newSimulateHoldEvents
{
_simulateHoldEvents = newSimulateHoldEvents;
}
- (BOOL)simulateHoldEvents
{
return (_simulateHoldEvents);
}
- (NSArray *)unusedButtonCodes
{
return (_unusedButtonCodes);
}
- (void)setUnusedButtonCodes:(NSArray *)newArrayWithUnusedButtonCodesAsNSNumbers
{
[newArrayWithUnusedButtonCodesAsNSNumbers retain];
[_unusedButtonCodes release];
_unusedButtonCodes = newArrayWithUnusedButtonCodesAsNSNumbers;
[self _postStatusWithAction:kHIDRemoteDNStatusActionUpdate];
}
- (void)setDelegate:(NSObject <HIDRemoteDelegate> *)newDelegate
{
_delegate = newDelegate;
}
- (NSObject <HIDRemoteDelegate> *)delegate
{
return (_delegate);
}
#pragma mark -- PUBLIC: Expert APIs --
- (void)setEnableSecureEventInputWorkaround:(BOOL)newEnableSecureEventInputWorkaround
{
_secureEventInputWorkAround = newEnableSecureEventInputWorkaround;
}
- (BOOL)enableSecureEventInputWorkaround
{
return (_secureEventInputWorkAround);
}
- (void)setExclusiveLockLendingEnabled:(BOOL)newExclusiveLockLendingEnabled
{
if (newExclusiveLockLendingEnabled != _exclusiveLockLending)
{
_exclusiveLockLending = newExclusiveLockLendingEnabled;
if (_exclusiveLockLending)
{
[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(_handleNotifications:) name:kHIDRemoteDNHIDRemoteStatus object:nil];
}
else
{
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self name:kHIDRemoteDNHIDRemoteStatus object:nil];
[_waitForReturnByPID release];
_waitForReturnByPID = nil;
}
}
}
- (BOOL)exclusiveLockLendingEnabled
{
return (_exclusiveLockLending);
}
- (void)setSendExclusiveResourceReuseNotification:(BOOL)newSendExclusiveResourceReuseNotification
{
_sendExclusiveResourceReuseNotification = newSendExclusiveResourceReuseNotification;
}
- (BOOL)sendExclusiveResourceReuseNotification
{
return (_sendExclusiveResourceReuseNotification);
}
- (BOOL)isApplicationTerminating
{
return (_applicationIsTerminating);
}
- (BOOL)isStopping
{
return (_isStopping);
}
#pragma mark -- PRIVATE: Application becomes active / inactive handling for kHIDRemoteModeExclusiveAuto --
- (void)_appStatusChanged:(NSNotification *)notification
{
#ifdef HIDREMOTE_THREADSAFETY_HARDENED_NOTIFICATION_HANDLING
if ([self respondsToSelector:@selector(performSelector:onThread:withObject:waitUntilDone:)]) // OS X 10.5+ only
{
if ([NSThread currentThread] != _runOnThread)
{
if ([[notification name] isEqual:NSApplicationDidBecomeActiveNotification])
{
if (!_autoRecover)
{
return;
}
}
if ([[notification name] isEqual:NSApplicationWillResignActiveNotification])
{
if (_mode != kHIDRemoteModeExclusiveAuto)
{
return;
}
}
[self performSelector:@selector(_appStatusChanged:) onThread:_runOnThread withObject:notification waitUntilDone:[[notification name] isEqual:NSApplicationWillTerminateNotification]];
return;
}
}
#endif
if (notification!=nil)
{
if (_autoRecoveryTimer!=nil)
{
[_autoRecoveryTimer invalidate];
[_autoRecoveryTimer release];
_autoRecoveryTimer = nil;
}
if ([[notification name] isEqual:NSApplicationDidBecomeActiveNotification])
{
if (_autoRecover)
{
// Delay autorecover by 0.1 to avoid race conditions
if ((_autoRecoveryTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:0.1] interval:0.1 target:self selector:@selector(_delayedAutoRecovery:) userInfo:nil repeats:NO]) != nil)
{
// Using CFRunLoopAddTimer instead of [[NSRunLoop currentRunLoop] addTimer:.. for consistency with run loop modes.
// The kCFRunLoopCommonModes counterpart NSRunLoopCommonModes is only available in 10.5 and later, whereas this code
// is designed to be also compatible with 10.4. CFRunLoopTimerRef is "toll-free-bridged" with NSTimer since 10.0.
CFRunLoopAddTimer(CFRunLoopGetCurrent(), (CFRunLoopTimerRef)_autoRecoveryTimer, kCFRunLoopCommonModes);
}
}
}
if ([[notification name] isEqual:NSApplicationWillResignActiveNotification])
{
if (_mode == kHIDRemoteModeExclusiveAuto)
{
[self stopRemoteControl];
_autoRecover = YES;
}
}
if ([[notification name] isEqual:NSApplicationWillTerminateNotification])
{
_applicationIsTerminating = YES;
if ([self isStarted])
{
[self stopRemoteControl];
}
}
}
}
- (void)_delayedAutoRecovery:(NSTimer *)aTimer
{
[_autoRecoveryTimer invalidate];
[_autoRecoveryTimer release];
_autoRecoveryTimer = nil;
if (_autoRecover)
{
[self startRemoteControl:kHIDRemoteModeExclusiveAuto];
_autoRecover = NO;
}
}
#pragma mark -- PRIVATE: Distributed notifiations handling --
- (void)_postStatusWithAction:(NSString *)action
{
if (_sendStatusNotifications)
{
[[NSDistributedNotificationCenter defaultCenter] postNotificationName:kHIDRemoteDNHIDRemoteStatus
object:((_pidString!=nil) ? _pidString : [NSString stringWithFormat:@"%d",getpid()])
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:1], kHIDRemoteDNStatusHIDRemoteVersionKey,
[NSNumber numberWithUnsignedInt:(unsigned int)getpid()], kHIDRemoteDNStatusPIDKey,
[NSNumber numberWithInt:(int)_mode], kHIDRemoteDNStatusModeKey,
[NSNumber numberWithUnsignedInt:(unsigned int)[self activeRemoteControlCount]], kHIDRemoteDNStatusRemoteControlCountKey,
((_unusedButtonCodes!=nil) ? _unusedButtonCodes : [NSArray array]), kHIDRemoteDNStatusUnusedButtonCodesKey,
action, kHIDRemoteDNStatusActionKey,
[[NSBundle mainBundle] bundleIdentifier], (NSString *)kCFBundleIdentifierKey,
_returnToPID, kHIDRemoteDNStatusReturnToPIDKey,
nil]
deliverImmediately:YES
];
}
}
- (void)_handleNotifications:(NSNotification *)notification
{
NSString *notificationName;
#ifdef HIDREMOTE_THREADSAFETY_HARDENED_NOTIFICATION_HANDLING
if ([self respondsToSelector:@selector(performSelector:onThread:withObject:waitUntilDone:)]) // OS X 10.5+ only
{
if ([NSThread currentThread] != _runOnThread)
{
[self performSelector:@selector(_handleNotifications:) onThread:_runOnThread withObject:notification waitUntilDone:NO];
return;
}
}
#endif
if ((notification!=nil) && ((notificationName = [notification name]) != nil))
{
if ([notificationName isEqual:kHIDRemoteDNHIDRemotePing])
{
[self _postStatusWithAction:kHIDRemoteDNStatusActionUpdate];
}
if ([notificationName isEqual:kHIDRemoteDNHIDRemoteRetry])
{
if ([self isStarted])
{
BOOL retry = YES;
// Ignore our own global retry broadcasts
if ([[notification object] isEqual:kHIDRemoteDNHIDRemoteRetryGlobalObject])
{
NSNumber *fromPID;
if ((fromPID = [[notification userInfo] objectForKey:kHIDRemoteDNStatusPIDKey]) != nil)
{
if (getpid() == (int)[fromPID unsignedIntValue])
{
retry = NO;
}
}
}
if (retry)
{
if (([self delegate] != nil) &&
([[self delegate] respondsToSelector:@selector(hidRemote:shouldRetryExclusiveLockWithInfo:)]))
{
retry = [[self delegate] hidRemote:self shouldRetryExclusiveLockWithInfo:[notification userInfo]];
}
}
if (retry)
{
HIDRemoteMode restartInMode = _mode;
if (restartInMode != kHIDRemoteModeNone)
{
_isRestarting = YES;
[self stopRemoteControl];
[_returnToPID release];
_returnToPID = nil;
[self startRemoteControl:restartInMode];
_isRestarting = NO;
if (restartInMode != kHIDRemoteModeShared)
{
_returnToPID = [[[notification userInfo] objectForKey:kHIDRemoteDNStatusPIDKey] retain];
}
}
}
else
{
NSNumber *cacheReturnPID = _returnToPID;
_returnToPID = [[[notification userInfo] objectForKey:kHIDRemoteDNStatusPIDKey] retain];
[self _postStatusWithAction:kHIDRemoteDNStatusActionNoNeed];
[_returnToPID release];
_returnToPID = cacheReturnPID;
}
}
}
if (_exclusiveLockLending)
{
if ([notificationName isEqual:kHIDRemoteDNHIDRemoteStatus])
{
NSString *action;
if ((action = [[notification userInfo] objectForKey:kHIDRemoteDNStatusActionKey]) != nil)
{
if ((_mode == kHIDRemoteModeNone) && (_waitForReturnByPID!=nil))
{
NSNumber *pidNumber, *returnToPIDNumber;
if ((pidNumber = [[notification userInfo] objectForKey:kHIDRemoteDNStatusPIDKey]) != nil)
{
returnToPIDNumber = [[notification userInfo] objectForKey:kHIDRemoteDNStatusReturnToPIDKey];
if ([action isEqual:kHIDRemoteDNStatusActionStart])
{
if ([pidNumber isEqual:_waitForReturnByPID])
{
NSNumber *startMode;
if ((startMode = [[notification userInfo] objectForKey:kHIDRemoteDNStatusModeKey]) != nil)
{
if ([startMode intValue] == kHIDRemoteModeShared)
{
returnToPIDNumber = [NSNumber numberWithInt:getpid()];
action = kHIDRemoteDNStatusActionNoNeed;
}
}
}
}
if (returnToPIDNumber != nil)
{
if ([action isEqual:kHIDRemoteDNStatusActionStop] || [action isEqual:kHIDRemoteDNStatusActionNoNeed])
{
if ([pidNumber isEqual:_waitForReturnByPID] && ([returnToPIDNumber intValue] == getpid()))
{
[_waitForReturnByPID release];
_waitForReturnByPID = nil;
if (([self delegate] != nil) &&
([[self delegate] respondsToSelector:@selector(hidRemote:exclusiveLockReleasedByApplicationWithInfo:)]))
{
[[self delegate] hidRemote:self exclusiveLockReleasedByApplicationWithInfo:[notification userInfo]];
}
else
{
[self startRemoteControl:kHIDRemoteModeExclusive];
}
}
}
}
}
}
if (_mode==kHIDRemoteModeExclusive)
{
if ([action isEqual:kHIDRemoteDNStatusActionStart])
{
NSNumber *originPID = [[notification userInfo] objectForKey:kHIDRemoteDNStatusPIDKey];
BOOL lendLock = YES;
if ([originPID intValue] != getpid())
{
if (([self delegate] != nil) &&
([[self delegate] respondsToSelector:@selector(hidRemote:lendExclusiveLockToApplicationWithInfo:)]))
{
lendLock = [[self delegate] hidRemote:self lendExclusiveLockToApplicationWithInfo:[notification userInfo]];
}
if (lendLock)
{
[_waitForReturnByPID release];
_waitForReturnByPID = [originPID retain];
if (_waitForReturnByPID != nil)
{
[self stopRemoteControl];
[[NSDistributedNotificationCenter defaultCenter] postNotificationName:kHIDRemoteDNHIDRemoteRetry
object:[NSString stringWithFormat:@"%d", [_waitForReturnByPID intValue]]
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithUnsignedInt:(unsigned int)getpid()], kHIDRemoteDNStatusPIDKey,
[[NSBundle mainBundle] bundleIdentifier], (NSString *)kCFBundleIdentifierKey,
nil]
deliverImmediately:YES];
}
}
}
}
}
}
}
}
}
}
- (void)_setSendStatusNotifications:(BOOL)doSend
{
_sendStatusNotifications = doSend;
}
- (BOOL)_sendStatusNotifications
{
return (_sendStatusNotifications);
}
#pragma mark -- PRIVATE: Service setup and destruction --
- (BOOL)_prematchService:(io_object_t)service
{
BOOL serviceMatches = NO;
NSString *ioClass;
NSNumber *candelairHIDRemoteCompatibilityMask;
if (service != 0)
{
// IOClass matching
if ((ioClass = (NSString *)IORegistryEntryCreateCFProperty((io_registry_entry_t)service,
CFSTR(kIOClassKey),
kCFAllocatorDefault,
0)) != nil)
{
// Match on Apple's AppleIRController and old versions of the Remote Buddy IR Controller
if ([ioClass isEqual:@"AppleIRController"] || [ioClass isEqual:@"RBIOKitAIREmu"])
{
CFTypeRef candelairHIDRemoteCompatibilityDevice;
serviceMatches = YES;
if ((candelairHIDRemoteCompatibilityDevice = IORegistryEntryCreateCFProperty((io_registry_entry_t)service, CFSTR("CandelairHIDRemoteCompatibilityDevice"), kCFAllocatorDefault, 0)) != NULL)
{
if (CFEqual(kCFBooleanTrue, candelairHIDRemoteCompatibilityDevice))
{
serviceMatches = NO;
}
CFRelease (candelairHIDRemoteCompatibilityDevice);
}
}
// Match on the virtual IOSPIRIT IR Controller
if ([ioClass isEqual:@"IOSPIRITIRController"])
{
serviceMatches = YES;
}
CFRelease((CFTypeRef)ioClass);
}
// Match on services that claim compatibility with the HID Remote class (Candelair or third-party) by having a property of CandelairHIDRemoteCompatibilityMask = 1 <Type: Number>
if ((candelairHIDRemoteCompatibilityMask = (NSNumber *)IORegistryEntryCreateCFProperty((io_registry_entry_t)service, CFSTR("CandelairHIDRemoteCompatibilityMask"), kCFAllocatorDefault, 0)) != nil)
{
if ([candelairHIDRemoteCompatibilityMask isKindOfClass:[NSNumber class]])
{
if ([candelairHIDRemoteCompatibilityMask unsignedIntValue] & kHIDRemoteCompatibilityFlagsStandardHIDRemoteDevice)
{
serviceMatches = YES;
}
else
{
serviceMatches = NO;
}
}
CFRelease((CFTypeRef)candelairHIDRemoteCompatibilityMask);
}
}
if (([self delegate]!=nil) &&
([[self delegate] respondsToSelector:@selector(hidRemote:inspectNewHardwareWithService:prematchResult:)]))
{
serviceMatches = [((NSObject <HIDRemoteDelegate> *)[self delegate]) hidRemote:self inspectNewHardwareWithService:service prematchResult:serviceMatches];
}
return (serviceMatches);
}
- (HIDRemoteButtonCode)buttonCodeForUsage:(unsigned int)usage usagePage:(unsigned int)usagePage
{
HIDRemoteButtonCode buttonCode = kHIDRemoteButtonCodeNone;
switch (usagePage)
{
case kHIDPage_Consumer:
switch (usage)
{
case kHIDUsage_Csmr_MenuPick:
// Aluminum Remote: Center
buttonCode = (kHIDRemoteButtonCodeCenter|kHIDRemoteButtonCodeAluminumMask);
break;
case kHIDUsage_Csmr_ModeStep:
// Aluminium Remote: Center Hold
buttonCode = (kHIDRemoteButtonCodeCenterHold|kHIDRemoteButtonCodeAluminumMask);
break;
case kHIDUsage_Csmr_PlayOrPause:
// Aluminum Remote: Play/Pause
buttonCode = (kHIDRemoteButtonCodePlay|kHIDRemoteButtonCodeAluminumMask);
break;
case kHIDUsage_Csmr_Rewind:
buttonCode = kHIDRemoteButtonCodeLeftHold;
break;
case kHIDUsage_Csmr_FastForward:
buttonCode = kHIDRemoteButtonCodeRightHold;
break;
case kHIDUsage_Csmr_Menu:
buttonCode = kHIDRemoteButtonCodeMenuHold;
break;
}
break;
case kHIDPage_GenericDesktop:
switch (usage)
{
case kHIDUsage_GD_SystemAppMenu:
buttonCode = kHIDRemoteButtonCodeMenu;
break;
case kHIDUsage_GD_SystemMenu:
buttonCode = kHIDRemoteButtonCodeCenter;
break;
case kHIDUsage_GD_SystemMenuRight:
buttonCode = kHIDRemoteButtonCodeRight;
break;
case kHIDUsage_GD_SystemMenuLeft:
buttonCode = kHIDRemoteButtonCodeLeft;
break;
case kHIDUsage_GD_SystemMenuUp:
buttonCode = kHIDRemoteButtonCodeUp;
break;
case kHIDUsage_GD_SystemMenuDown:
buttonCode = kHIDRemoteButtonCodeDown;
break;