-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
HIDEventGenerator.mm
1229 lines (1021 loc) · 45.8 KB
/
HIDEventGenerator.mm
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
/*
* Copyright (C) 2015-2024 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
*/
#import "config.h"
#import "HIDEventGenerator.h"
#import "BackBoardServicesSPI.h"
#import "GeneratedTouchesDebugWindow.h"
#import "UIKitSPIForTesting.h"
#import <mach/mach_time.h>
#import <pal/spi/cocoa/IOKitSPI.h>
#import <wtf/Assertions.h>
#import <wtf/BlockPtr.h>
#import <wtf/SoftLinking.h>
#import <wtf/Vector.h>
SOFT_LINK_PRIVATE_FRAMEWORK(BackBoardServices)
SOFT_LINK(BackBoardServices, BKSHIDEventSetDigitizerInfo, void, (IOHIDEventRef digitizerEvent, uint32_t contextID, uint8_t systemGestureisPossible, uint8_t isSystemGestureStateChangeEvent, CFStringRef displayUUID, CFTimeInterval initialTouchTimestamp, float maxForce), (digitizerEvent, contextID, systemGestureisPossible, isSystemGestureStateChangeEvent, displayUUID, initialTouchTimestamp, maxForce));
SOFT_LINK(BackBoardServices, BKSHIDEventGetDigitizerAttributes, BKSHIDEventDigitizerAttributes *, (IOHIDEventRef event), (event));
SOFT_LINK_CLASS(BackBoardServices, BKSHIDEventDigitizerAttributes);
class ActiveModifierState {
public:
void updateForUsageCode(uint32_t usageCode, bool isKeyDown)
{
switch (usageCode) {
case kHIDUsage_KeyboardRightShift:
case kHIDUsage_KeyboardLeftShift:
return update(m_shiftCount, isKeyDown);
case kHIDUsage_KeyboardRightControl:
case kHIDUsage_KeyboardLeftControl:
return update(m_controlCount, isKeyDown);
case kHIDUsage_KeyboardRightAlt:
case kHIDUsage_KeyboardLeftAlt:
return update(m_altCount, isKeyDown);
case kHIDUsage_KeyboardRightGUI:
case kHIDUsage_KeyboardLeftGUI:
return update(m_commandCount, isKeyDown);
default:
break;
}
}
BKSKeyModifierFlags flags() const
{
BKSKeyModifierFlags flags { 0 };
if (m_shiftCount)
flags |= BKSKeyModifierShift;
if (m_controlCount)
flags |= BKSKeyModifierControl;
if (m_altCount)
flags |= BKSKeyModifierAlternate;
if (m_commandCount)
flags |= BKSKeyModifierCommand;
return flags;
}
private:
void update(unsigned& counter, bool isKeyDown)
{
if (isKeyDown) {
counter++;
return;
}
if (!counter) {
ASSERT_NOT_REACHED();
return;
}
counter--;
}
unsigned m_shiftCount { 0 };
unsigned m_controlCount { 0 };
unsigned m_altCount { 0 };
unsigned m_commandCount { 0 };
};
NSString* const TopLevelEventInfoKey = @"events";
NSString* const HIDEventInputType = @"inputType";
NSString* const HIDEventTimeOffsetKey = @"timeOffset";
NSString* const HIDEventTouchesKey = @"touches";
NSString* const HIDEventPhaseKey = @"phase";
NSString* const HIDEventInterpolateKey = @"interpolate";
NSString* const HIDEventTimestepKey = @"timestep";
NSString* const HIDEventCoordinateSpaceKey = @"coordinateSpace";
NSString* const HIDEventStartEventKey = @"startEvent";
NSString* const HIDEventEndEventKey = @"endEvent";
NSString* const HIDEventTouchIDKey = @"id";
NSString* const HIDEventPressureKey = @"pressure";
NSString* const HIDEventXKey = @"x";
NSString* const HIDEventYKey = @"y";
NSString* const HIDEventTwistKey = @"twist";
NSString* const HIDEventMajorRadiusKey = @"majorRadius";
NSString* const HIDEventMinorRadiusKey = @"minorRadius";
NSString* const HIDEventInputTypeHand = @"hand";
NSString* const HIDEventInputTypeFinger = @"finger";
NSString* const HIDEventInputTypeStylus = @"stylus";
NSString* const HIDEventCoordinateSpaceTypeGlobal = @"global";
NSString* const HIDEventCoordinateSpaceTypeContent = @"content";
NSString* const HIDEventInterpolationTypeLinear = @"linear";
NSString* const HIDEventInterpolationTypeSimpleCurve = @"simpleCurve";
NSString* const HIDEventPhaseBegan = @"began";
NSString* const HIDEventPhaseStationary = @"stationary";
NSString* const HIDEventPhaseMoved = @"moved";
NSString* const HIDEventPhaseEnded = @"ended";
NSString* const HIDEventPhaseCanceled = @"canceled";
static const NSTimeInterval fingerLiftDelay = 0.05;
static const NSTimeInterval multiTapInterval = 0.15;
static const NSTimeInterval fingerMoveInterval = 0.016;
static const NSTimeInterval longPressHoldDelay = 2.0;
static const IOHIDFloat defaultMajorRadius = 5;
static const IOHIDFloat defaultPathPressure = 0;
static const long nanosecondsPerSecond = 1e9;
NSUInteger const HIDMaxTouchCount = 5;
static int fingerIdentifiers[HIDMaxTouchCount] = { 2, 3, 4, 5, 1 };
typedef enum {
InterpolationTypeLinear,
InterpolationTypeSimpleCurve,
} InterpolationType;
typedef enum {
HandEventNull,
HandEventTouched,
HandEventMoved,
HandEventChordChanged,
HandEventLifted,
HandEventCanceled,
StylusEventTouched,
StylusEventMoved,
StylusEventLifted,
} HandEventType;
typedef struct {
int identifier;
CGPoint point;
IOHIDFloat pathMajorRadius;
IOHIDFloat pathPressure;
UInt8 pathProximity;
BOOL isStylus;
IOHIDFloat azimuthAngle;
IOHIDFloat altitudeAngle;
} SyntheticEventDigitizerInfo;
static CFTimeInterval secondsSinceAbsoluteTime(CFAbsoluteTime startTime)
{
return (CFAbsoluteTimeGetCurrent() - startTime);
}
static double linearInterpolation(double a, double b, double t)
{
return (a + (b - a) * t );
}
static double simpleCurveInterpolation(double a, double b, double t)
{
return (a + (b - a) * sin(sin(t * M_PI / 2) * t * M_PI / 2));
}
static CGPoint calculateNextCurveLocation(CGPoint a, CGPoint b, CFTimeInterval t)
{
return CGPointMake(simpleCurveInterpolation(a.x, b.x, t), simpleCurveInterpolation(a.y, b.y, t));
}
typedef double(*pressureInterpolationFunction)(double, double, CFTimeInterval);
static pressureInterpolationFunction interpolations[] = {
linearInterpolation,
simpleCurveInterpolation,
};
static void delayBetweenMove(int eventIndex, double elapsed)
{
// Delay next event until expected elapsed time.
double delay = (eventIndex * fingerMoveInterval) - elapsed;
if (delay > 0) {
struct timespec moveDelay = { 0, static_cast<long>(delay * nanosecondsPerSecond) };
nanosleep(&moveDelay, NULL);
}
}
@implementation HIDEventGenerator {
IOHIDEventSystemClientRef _ioSystemClient;
SyntheticEventDigitizerInfo _activePoints[HIDMaxTouchCount];
NSUInteger _activePointCount;
RetainPtr<NSMutableDictionary> _eventCallbacks;
ActiveModifierState _activeModifiers;
}
+ (HIDEventGenerator *)sharedHIDEventGenerator
{
static NeverDestroyed<RetainPtr<HIDEventGenerator>> eventGenerator = adoptNS([[HIDEventGenerator alloc] init]);
return eventGenerator.get().get();
}
+ (CFIndex)nextEventCallbackID
{
static CFIndex callbackID = 0;
return ++callbackID;
}
- (instancetype)init
{
self = [super init];
if (!self)
return nil;
for (NSUInteger i = 0; i < HIDMaxTouchCount; ++i)
_activePoints[i].identifier = fingerIdentifiers[i];
_eventCallbacks = adoptNS([[NSMutableDictionary alloc] init]);
return self;
}
- (void)_sendIOHIDKeyboardEvent:(uint64_t)timestamp usage:(uint32_t)usage isKeyDown:(bool)isKeyDown
{
auto eventRef = adoptCF(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault,
timestamp,
kHIDPage_KeyboardOrKeypad,
usage,
isKeyDown,
kIOHIDEventOptionNone));
[self _sendHIDEvent:eventRef.get()];
_activeModifiers.updateForUsageCode(usage, isKeyDown);
}
- (void)resetActiveModifiers
{
_activeModifiers = { };
}
static IOHIDDigitizerTransducerType transducerTypeFromString(NSString * transducerTypeString)
{
if ([transducerTypeString isEqualToString:HIDEventInputTypeHand])
return kIOHIDDigitizerTransducerTypeHand;
if ([transducerTypeString isEqualToString:HIDEventInputTypeFinger])
return kIOHIDDigitizerTransducerTypeFinger;
if ([transducerTypeString isEqualToString:HIDEventInputTypeStylus])
return kIOHIDDigitizerTransducerTypeStylus;
ASSERT_NOT_REACHED();
return 0;
}
static UITouchPhase phaseFromString(NSString *string)
{
if ([string isEqualToString:HIDEventPhaseBegan])
return UITouchPhaseBegan;
if ([string isEqualToString:HIDEventPhaseStationary])
return UITouchPhaseStationary;
if ([string isEqualToString:HIDEventPhaseMoved])
return UITouchPhaseMoved;
if ([string isEqualToString:HIDEventPhaseEnded])
return UITouchPhaseEnded;
if ([string isEqualToString:HIDEventPhaseCanceled])
return UITouchPhaseCancelled;
return UITouchPhaseStationary;
}
static InterpolationType interpolationFromString(NSString *string)
{
if ([string isEqualToString:HIDEventInterpolationTypeLinear])
return InterpolationTypeLinear;
if ([string isEqualToString:HIDEventInterpolationTypeSimpleCurve])
return InterpolationTypeSimpleCurve;
return InterpolationTypeLinear;
}
- (IOHIDDigitizerEventMask)eventMaskFromEventInfo:(NSDictionary *)info
{
IOHIDDigitizerEventMask eventMask = 0;
NSArray *childEvents = info[HIDEventTouchesKey];
for (NSDictionary *touchInfo in childEvents) {
UITouchPhase phase = phaseFromString(touchInfo[HIDEventPhaseKey]);
// If there are any new or ended events, mask includes touch.
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded || phase == UITouchPhaseCancelled)
eventMask |= kIOHIDDigitizerEventTouch;
// If there are any pressure readings, set mask must include attribute
if ([touchInfo[HIDEventPressureKey] floatValue])
eventMask |= kIOHIDDigitizerEventAttribute;
}
return eventMask;
}
// Returns 1 for all events where the fingers are on the glass (everything but ended and canceled).
- (CFIndex)touchFromEventInfo:(NSDictionary *)info
{
NSArray *childEvents = info[HIDEventTouchesKey];
for (NSDictionary *touchInfo in childEvents) {
UITouchPhase phase = phaseFromString(touchInfo[HIDEventPhaseKey]);
if (phase == UITouchPhaseBegan || phase == UITouchPhaseMoved || phase == UITouchPhaseStationary)
return 1;
}
return 0;
}
// FIXME: callers of _createIOHIDEventType could switch to this.
- (IOHIDEventRef)_createIOHIDEventWithInfo:(NSDictionary *)info
{
uint64_t machTime = mach_absolute_time();
IOHIDDigitizerEventMask eventMask = [self eventMaskFromEventInfo:info];
CFIndex range = 0;
// touch is 1 if a finger is down.
CFIndex touch = [self touchFromEventInfo:info];
IOHIDEventRef eventRef = IOHIDEventCreateDigitizerEvent(kCFAllocatorDefault, machTime,
transducerTypeFromString(info[HIDEventInputType]), // transducerType
0, // index
0, // identifier
eventMask, // event mask
0, // button event
0, // x
0, // y
0, // z
0, // presure
0, // twist
range, // range
touch, // touch
kIOHIDEventOptionNone);
IOHIDEventSetIntegerValue(eventRef, kIOHIDEventFieldDigitizerIsDisplayIntegrated, 1);
NSArray *childEvents = info[HIDEventTouchesKey];
for (NSDictionary *touchInfo in childEvents) {
[[GeneratedTouchesDebugWindow sharedGeneratedTouchesDebugWindow] updateDebugIndicatorForTouch:[touchInfo[HIDEventTouchIDKey] intValue] withPointInWindowCoordinates:CGPointMake([touchInfo[HIDEventXKey] floatValue], [touchInfo[HIDEventYKey] floatValue]) isTouching:(BOOL)touch];
IOHIDDigitizerEventMask childEventMask = 0;
UITouchPhase phase = phaseFromString(touchInfo[HIDEventPhaseKey]);
if (phase != UITouchPhaseCancelled && phase != UITouchPhaseBegan && phase != UITouchPhaseEnded && phase != UITouchPhaseStationary)
childEventMask |= kIOHIDDigitizerEventPosition;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded || phase == UITouchPhaseCancelled)
childEventMask |= (kIOHIDDigitizerEventTouch | kIOHIDDigitizerEventRange);
if (phase == UITouchPhaseCancelled)
childEventMask |= kIOHIDDigitizerEventCancel;
if ([touchInfo[HIDEventPressureKey] floatValue])
childEventMask |= kIOHIDDigitizerEventAttribute;
auto subEvent = adoptCF(IOHIDEventCreateDigitizerFingerEvent(kCFAllocatorDefault, machTime,
[touchInfo[HIDEventTouchIDKey] intValue], // index
2, // identifier (which finger we think it is). FIXME: this should come from the data.
childEventMask,
[touchInfo[HIDEventXKey] floatValue],
[touchInfo[HIDEventYKey] floatValue],
0, // z
[touchInfo[HIDEventPressureKey] floatValue],
[touchInfo[HIDEventTwistKey] floatValue],
touch, // range
touch, // touch
kIOHIDEventOptionNone));
IOHIDEventSetFloatValue(subEvent.get(), kIOHIDEventFieldDigitizerMajorRadius, [touchInfo[HIDEventMajorRadiusKey] floatValue]);
IOHIDEventSetFloatValue(subEvent.get(), kIOHIDEventFieldDigitizerMinorRadius, [touchInfo[HIDEventMinorRadiusKey] floatValue]);
IOHIDEventAppendEvent(eventRef, subEvent.get(), 0);
}
return eventRef;
}
- (IOHIDEventRef)_createIOHIDEventType:(HandEventType)eventType
{
BOOL isTouching = (eventType == HandEventTouched || eventType == HandEventMoved || eventType == HandEventChordChanged || eventType == StylusEventTouched || eventType == StylusEventMoved);
IOHIDDigitizerEventMask eventMask = kIOHIDDigitizerEventTouch;
if (eventType == HandEventMoved) {
eventMask &= ~kIOHIDDigitizerEventTouch;
eventMask |= kIOHIDDigitizerEventPosition;
eventMask |= kIOHIDDigitizerEventAttribute;
} else if (eventType == HandEventChordChanged) {
eventMask |= kIOHIDDigitizerEventPosition;
eventMask |= kIOHIDDigitizerEventAttribute;
} else if (eventType == HandEventTouched || eventType == HandEventCanceled || eventType == HandEventLifted)
eventMask |= kIOHIDDigitizerEventIdentity;
uint64_t machTime = mach_absolute_time();
auto eventRef = adoptCF(IOHIDEventCreateDigitizerEvent(kCFAllocatorDefault, machTime,
kIOHIDDigitizerTransducerTypeHand,
0,
0,
eventMask,
0,
0, 0, 0,
0,
0,
0,
isTouching,
kIOHIDEventOptionNone));
IOHIDEventSetIntegerValue(eventRef.get(), kIOHIDEventFieldDigitizerIsDisplayIntegrated, 1);
for (NSUInteger i = 0; i < _activePointCount; ++i) {
SyntheticEventDigitizerInfo* pointInfo = &_activePoints[i];
if (eventType == HandEventTouched) {
if (!pointInfo->pathMajorRadius)
pointInfo->pathMajorRadius = defaultMajorRadius;
if (!pointInfo->pathPressure)
pointInfo->pathPressure = defaultPathPressure;
if (!pointInfo->pathProximity)
pointInfo->pathProximity = kGSEventPathInfoInTouch | kGSEventPathInfoInRange;
} else if (eventType == HandEventLifted || eventType == HandEventCanceled || eventType == StylusEventLifted) {
pointInfo->pathMajorRadius = 0;
pointInfo->pathPressure = 0;
pointInfo->pathProximity = 0;
}
CGPoint point = pointInfo->point;
point = CGPointMake(roundf(point.x), roundf(point.y));
[[GeneratedTouchesDebugWindow sharedGeneratedTouchesDebugWindow] updateDebugIndicatorForTouch:i withPointInWindowCoordinates:point isTouching:isTouching];
RetainPtr<IOHIDEventRef> subEvent;
if (pointInfo->isStylus) {
if (eventType == StylusEventTouched) {
eventMask |= kIOHIDDigitizerEventEstimatedAltitude;
eventMask |= kIOHIDDigitizerEventEstimatedAzimuth;
eventMask |= kIOHIDDigitizerEventEstimatedPressure;
} else if (eventType == StylusEventMoved)
eventMask = kIOHIDDigitizerEventPosition;
subEvent = adoptCF(IOHIDEventCreateDigitizerStylusEventWithPolarOrientation(kCFAllocatorDefault, machTime,
pointInfo->identifier,
pointInfo->identifier,
eventMask,
0,
point.x, point.y, 0,
pointInfo->pathPressure,
pointInfo->pathPressure,
0,
pointInfo->altitudeAngle,
pointInfo->azimuthAngle,
1,
0,
isTouching ? kIOHIDTransducerTouch : 0));
if (eventType == StylusEventTouched)
IOHIDEventSetIntegerValue(subEvent.get(), kIOHIDEventFieldDigitizerWillUpdateMask, 0x0400);
else if (eventType == StylusEventMoved)
IOHIDEventSetIntegerValue(subEvent.get(), kIOHIDEventFieldDigitizerDidUpdateMask, 0x0400);
} else {
subEvent = adoptCF(IOHIDEventCreateDigitizerFingerEvent(kCFAllocatorDefault, machTime,
pointInfo->identifier,
pointInfo->identifier,
eventMask,
point.x, point.y, 0,
pointInfo->pathPressure,
0,
pointInfo->pathProximity & kGSEventPathInfoInRange,
pointInfo->pathProximity & kGSEventPathInfoInTouch,
kIOHIDEventOptionNone));
}
IOHIDEventSetFloatValue(subEvent.get(), kIOHIDEventFieldDigitizerMajorRadius, pointInfo->pathMajorRadius);
IOHIDEventSetFloatValue(subEvent.get(), kIOHIDEventFieldDigitizerMinorRadius, pointInfo->pathMajorRadius);
IOHIDEventAppendEvent(eventRef.get(), subEvent.get(), 0);
}
return eventRef.leakRef();
}
- (BOOL)_sendHIDEvent:(IOHIDEventRef)eventRef
{
if (!_ioSystemClient)
_ioSystemClient = IOHIDEventSystemClientCreate(kCFAllocatorDefault);
if (!eventRef)
return YES;
dispatch_async(dispatch_get_main_queue(), [modifierFlags = _activeModifiers.flags(), strongEvent = RetainPtr { eventRef }] {
uint32_t contextID = [UIApplication sharedApplication].keyWindow._contextId;
ASSERT(contextID);
BKSHIDEventSetDigitizerInfo(strongEvent.get(), contextID, false, false, NULL, 0, 0);
static auto canSetActiveModifiers = [&] {
return [getBKSHIDEventDigitizerAttributesClass() instancesRespondToSelector:@selector(setActiveModifiers:)];
}();
if (canSetActiveModifiers && IOHIDEventGetType(strongEvent.get()) == kIOHIDEventTypeDigitizer) {
// As of iOS 16, this is necessary in order for sythesized gestures to properly simulate
// keyboard modifier state (for instance, when shift-tapping).
BKSHIDEventGetDigitizerAttributes(strongEvent.get()).activeModifiers = modifierFlags;
}
[[UIApplication sharedApplication] _enqueueHIDEvent:strongEvent.get()];
});
return YES;
}
- (BOOL)sendMarkerHIDEventWithCompletionBlock:(void (^)(void))completionBlock
{
auto callbackID = [HIDEventGenerator nextEventCallbackID];
[_eventCallbacks setObject:Block_copy(completionBlock) forKey:@(callbackID)];
auto markerEvent = adoptCF(IOHIDEventCreateVendorDefinedEvent(kCFAllocatorDefault,
mach_absolute_time(),
kHIDPage_VendorDefinedStart + 100,
0,
1,
(uint8_t*)&callbackID,
sizeof(CFIndex),
kIOHIDEventOptionNone));
if (markerEvent) {
dispatch_async(dispatch_get_main_queue(), [markerEvent = WTFMove(markerEvent)] {
auto contextID = [UIApplication sharedApplication].keyWindow._contextId;
ASSERT(contextID);
BKSHIDEventSetDigitizerInfo(markerEvent.get(), contextID, false, false, NULL, 0, 0);
[[UIApplication sharedApplication] _enqueueHIDEvent:markerEvent.get()];
});
}
return YES;
}
- (void)_updateTouchPoints:(CGPoint*)points count:(NSUInteger)count
{
HandEventType handEventType;
// The hand event type is based on previous state.
if (!_activePointCount)
handEventType = HandEventTouched;
else if (!count)
handEventType = HandEventLifted;
else if (count == _activePointCount)
handEventType = HandEventMoved;
else
handEventType = HandEventChordChanged;
// Update previous count for next event.
_activePointCount = count;
// Update point locations.
for (NSUInteger i = 0; i < count; ++i) {
_activePoints[i].point = points[i];
[[GeneratedTouchesDebugWindow sharedGeneratedTouchesDebugWindow] updateDebugIndicatorForTouch:i withPointInWindowCoordinates:points[i] isTouching:YES];
}
auto eventRef = adoptCF([self _createIOHIDEventType:handEventType]);
[self _sendHIDEvent:eventRef.get()];
}
- (void)touchDownAtPoints:(CGPoint*)locations touchCount:(NSUInteger)touchCount
{
touchCount = std::min(touchCount, HIDMaxTouchCount);
_activePointCount = touchCount;
for (NSUInteger index = 0; index < touchCount; ++index) {
_activePoints[index].point = locations[index];
_activePoints[index].isStylus = NO;
[[GeneratedTouchesDebugWindow sharedGeneratedTouchesDebugWindow] updateDebugIndicatorForTouch:index withPointInWindowCoordinates:locations[index] isTouching:YES];
}
auto eventRef = adoptCF([self _createIOHIDEventType:HandEventTouched]);
[self _sendHIDEvent:eventRef.get()];
}
- (void)touchDown:(CGPoint)location touchCount:(NSUInteger)touchCount
{
touchCount = std::min(touchCount, HIDMaxTouchCount);
Vector<CGPoint> locations(touchCount);
for (NSUInteger index = 0; index < touchCount; ++index)
locations[index] = location;
[self touchDownAtPoints:&locations[0] touchCount:touchCount];
}
- (void)touchDown:(CGPoint)location
{
[self touchDownAtPoints:&location touchCount:1];
}
- (void)liftUpAtPoints:(CGPoint*)locations touchCount:(NSUInteger)touchCount
{
touchCount = std::min(touchCount, HIDMaxTouchCount);
touchCount = std::min(touchCount, _activePointCount);
NSUInteger newPointCount = _activePointCount - touchCount;
for (NSUInteger index = 0; index < touchCount; ++index) {
_activePoints[newPointCount + index].point = locations[index];
[[GeneratedTouchesDebugWindow sharedGeneratedTouchesDebugWindow] updateDebugIndicatorForTouch:index withPointInWindowCoordinates:CGPointZero isTouching:NO];
}
auto eventRef = adoptCF([self _createIOHIDEventType:HandEventLifted]);
[self _sendHIDEvent:eventRef.get()];
_activePointCount = newPointCount;
}
- (void)liftUp:(CGPoint)location touchCount:(NSUInteger)touchCount
{
touchCount = std::min(touchCount, HIDMaxTouchCount);
Vector<CGPoint> locations(touchCount);
for (NSUInteger index = 0; index < touchCount; ++index)
locations[index] = location;
[self liftUpAtPoints:&locations[0] touchCount:touchCount];
}
- (void)liftUp:(CGPoint)location
{
[self liftUp:location touchCount:1];
}
- (void)moveToPoints:(CGPoint*)newLocations touchCount:(NSUInteger)touchCount duration:(NSTimeInterval)seconds
{
touchCount = std::min(touchCount, HIDMaxTouchCount);
Vector<CGPoint> startLocations(touchCount);
Vector<CGPoint> nextLocations(touchCount);
CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();
CFTimeInterval elapsed = 0;
int eventIndex = 0;
while (elapsed < (seconds - fingerMoveInterval)) {
elapsed = secondsSinceAbsoluteTime(startTime);
CFTimeInterval interval = elapsed / seconds;
for (NSUInteger i = 0; i < touchCount; ++i) {
if (!eventIndex)
startLocations[i] = _activePoints[i].point;
nextLocations[i] = calculateNextCurveLocation(startLocations[i], newLocations[i], interval);
}
[self _updateTouchPoints:&nextLocations[0] count:touchCount];
delayBetweenMove(eventIndex++, elapsed);
}
[self _updateTouchPoints:newLocations count:touchCount];
}
- (void)touchDown:(CGPoint)location touchCount:(NSUInteger)count completionBlock:(void (^)(void))completionBlock
{
[self touchDown:location touchCount:count];
[self sendMarkerHIDEventWithCompletionBlock:completionBlock];
}
- (void)liftUp:(CGPoint)location touchCount:(NSUInteger)count completionBlock:(void (^)(void))completionBlock
{
[self liftUp:location touchCount:count];
[self sendMarkerHIDEventWithCompletionBlock:completionBlock];
}
- (void)stylusDownAtPoint:(CGPoint)location azimuthAngle:(CGFloat)azimuthAngle altitudeAngle:(CGFloat)altitudeAngle pressure:(CGFloat)pressure
{
_activePointCount = 1;
_activePoints[0].point = location;
_activePoints[0].isStylus = YES;
// At the time of writing, the IOKit documentation isn't always correct. For example
// it says that pressure is a value [0,1], but in practice it is [0,500] for stylus
// data. It does not mention that the azimuth angle is offset from a full rotation.
// Also, UIKit and IOHID interpret the altitude as different adjacent angles.
_activePoints[0].pathPressure = pressure * 500;
_activePoints[0].azimuthAngle = M_PI * 2 - azimuthAngle;
_activePoints[0].altitudeAngle = M_PI_2 - altitudeAngle;
auto eventRef = adoptCF([self _createIOHIDEventType:StylusEventTouched]);
[self _sendHIDEvent:eventRef.get()];
}
- (void)stylusMoveToPoint:(CGPoint)location azimuthAngle:(CGFloat)azimuthAngle altitudeAngle:(CGFloat)altitudeAngle pressure:(CGFloat)pressure
{
_activePointCount = 1;
_activePoints[0].point = location;
_activePoints[0].isStylus = YES;
// See notes above for details on these calculations.
_activePoints[0].pathPressure = pressure * 500;
_activePoints[0].azimuthAngle = M_PI * 2 - azimuthAngle;
_activePoints[0].altitudeAngle = M_PI_2 - altitudeAngle;
auto eventRef = adoptCF([self _createIOHIDEventType:StylusEventMoved]);
[self _sendHIDEvent:eventRef.get()];
}
- (void)stylusUpAtPoint:(CGPoint)location
{
_activePointCount = 1;
_activePoints[0].point = location;
_activePoints[0].isStylus = YES;
_activePoints[0].pathPressure = 0;
_activePoints[0].azimuthAngle = 0;
_activePoints[0].altitudeAngle = 0;
auto eventRef = adoptCF([self _createIOHIDEventType:StylusEventLifted]);
[self _sendHIDEvent:eventRef.get()];
}
- (void)stylusDownAtPoint:(CGPoint)location azimuthAngle:(CGFloat)azimuthAngle altitudeAngle:(CGFloat)altitudeAngle pressure:(CGFloat)pressure completionBlock:(void (^)(void))completionBlock
{
[self stylusDownAtPoint:location azimuthAngle:azimuthAngle altitudeAngle:altitudeAngle pressure:pressure];
[self sendMarkerHIDEventWithCompletionBlock:completionBlock];
}
- (void)stylusMoveToPoint:(CGPoint)location azimuthAngle:(CGFloat)azimuthAngle altitudeAngle:(CGFloat)altitudeAngle pressure:(CGFloat)pressure completionBlock:(void (^)(void))completionBlock
{
[self stylusMoveToPoint:location azimuthAngle:azimuthAngle altitudeAngle:altitudeAngle pressure:pressure];
[self sendMarkerHIDEventWithCompletionBlock:completionBlock];
}
- (void)stylusUpAtPoint:(CGPoint)location completionBlock:(void (^)(void))completionBlock
{
[self stylusUpAtPoint:location];
[self sendMarkerHIDEventWithCompletionBlock:completionBlock];
}
- (void)stylusTapAtPoint:(CGPoint)location azimuthAngle:(CGFloat)azimuthAngle altitudeAngle:(CGFloat)altitudeAngle pressure:(CGFloat)pressure completionBlock:(void (^)(void))completionBlock
{
struct timespec pressDelay = { 0, static_cast<long>(fingerLiftDelay * nanosecondsPerSecond) };
[self stylusDownAtPoint:location azimuthAngle:azimuthAngle altitudeAngle:altitudeAngle pressure:pressure];
nanosleep(&pressDelay, 0);
[self stylusUpAtPoint:location];
[self sendMarkerHIDEventWithCompletionBlock:completionBlock];
}
- (void)_waitFor:(NSTimeInterval)delay
{
if (delay <= 0)
return;
bool doneWaitingForDelay = false;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), [&doneWaitingForDelay] {
doneWaitingForDelay = true;
});
while (!doneWaitingForDelay)
[NSRunLoop.currentRunLoop runMode:NSDefaultRunLoopMode beforeDate:NSDate.distantFuture];
}
- (void)sendTaps:(int)tapCount location:(CGPoint)location withNumberOfTouches:(int)touchCount delay:(NSTimeInterval)delay completionBlock:(void (^)(void))completionBlock
{
struct timespec doubleDelay = { 0, static_cast<long>(multiTapInterval * nanosecondsPerSecond) };
struct timespec pressDelay = { 0, static_cast<long>(fingerLiftDelay * nanosecondsPerSecond) };
for (int i = 0; i < tapCount; i++) {
[self touchDown:location touchCount:touchCount];
nanosleep(&pressDelay, 0);
[self liftUp:location touchCount:touchCount];
if (i + 1 != tapCount)
nanosleep(&doubleDelay, 0);
[self _waitFor:delay];
}
[self sendMarkerHIDEventWithCompletionBlock:completionBlock];
}
- (void)tap:(CGPoint)location completionBlock:(void (^)(void))completionBlock
{
[self sendTaps:1 location:location withNumberOfTouches:1 delay:0 completionBlock:completionBlock];
}
- (void)doubleTap:(CGPoint)location delay:(NSTimeInterval)delay completionBlock:(void (^)(void))completionBlock
{
[self sendTaps:2 location:location withNumberOfTouches:1 delay:delay completionBlock:completionBlock];
}
- (void)twoFingerTap:(CGPoint)location completionBlock:(void (^)(void))completionBlock
{
[self sendTaps:1 location:location withNumberOfTouches:2 delay:0 completionBlock:completionBlock];
}
- (void)longPress:(CGPoint)location completionBlock:(void (^)(void))completionBlock
{
[self touchDown:location touchCount:1];
auto completionBlockCopy = makeBlockPtr(completionBlock);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, longPressHoldDelay * nanosecondsPerSecond), dispatch_get_main_queue(), ^ {
[self liftUp:location];
[self sendMarkerHIDEventWithCompletionBlock:completionBlockCopy.get()];
});
}
- (void)dragWithStartPoint:(CGPoint)startLocation endPoint:(CGPoint)endLocation duration:(double)seconds completionBlock:(void (^)(void))completionBlock
{
[self touchDown:startLocation touchCount:1];
[self moveToPoints:&endLocation touchCount:1 duration:seconds];
[self liftUp:endLocation];
[self sendMarkerHIDEventWithCompletionBlock:completionBlock];
}
- (void)pinchCloseWithStartPoint:(CGPoint)startLocation endPoint:(CGPoint)endLocation duration:(double)seconds completionBlock:(void (^)(void))completionBlock
{
}
- (void)pinchOpenWithStartPoint:(CGPoint)startLocation endPoint:(CGPoint)endLocation duration:(double)seconds completionBlock:(void (^)(void))completionBlock
{
}
- (void)markerEventReceived:(IOHIDEventRef)event
{
if (IOHIDEventGetType(event) != kIOHIDEventTypeVendorDefined)
return;
CFIndex callbackID = IOHIDEventGetIntegerValue(event, kIOHIDEventFieldVendorDefinedData);
void (^completionBlock)() = [_eventCallbacks objectForKey:@(callbackID)];
if (completionBlock) {
[_eventCallbacks removeObjectForKey:@(callbackID)];
completionBlock();
Block_release(completionBlock);
}
}
- (BOOL)hasOutstandingCallbacks
{
return [_eventCallbacks count];
}
static inline bool shouldWrapWithShiftKeyEventForCharacter(NSString *key)
{
if (key.length != 1)
return false;
int keyCode = [key characterAtIndex:0];
if (65 <= keyCode && keyCode <= 90)
return true;
switch (keyCode) {
case '!':
case '@':
case '#':
case '$':
case '%':
case '^':
case '&':
case '*':
case '(':
case ')':
case '_':
case '+':
case '{':
case '}':
case '|':
case ':':
case '"':
case '<':
case '>':
case '?':
case '~':
return true;
}
return false;
}
static std::optional<uint32_t> keyCodeForDOMFunctionKey(NSString *key)
{
// Compare the input string with the function-key names defined by the DOM spec (i.e. "F1",...,"F24").
// If the input string is a function-key name, set its key code. On iOS the key codes for the first 12
// function keys are disjoint from the key codes of the last 12 function keys.
for (int i = 1; i <= 12; ++i) {
if ([key isEqualToString:[NSString stringWithFormat:@"F%d", i]])
return kHIDUsage_KeyboardF1 + i - 1;
}
for (int i = 13; i <= 24; ++i) {
if ([key isEqualToString:[NSString stringWithFormat:@"F%d", i]])
return kHIDUsage_KeyboardF13 + i - 13;
}
return std::nullopt;
}
static inline uint32_t hidUsageCodeForCharacter(NSString *key)
{
const int uppercaseAlphabeticOffset = 'A' - kHIDUsage_KeyboardA;
const int lowercaseAlphabeticOffset = 'a' - kHIDUsage_KeyboardA;
const int numericNonZeroOffset = '1' - kHIDUsage_Keyboard1;
if (key.length == 1) {
// Handle alphanumeric characters and basic symbols.
int keyCode = [key characterAtIndex:0];
if (97 <= keyCode && keyCode <= 122) // Handle a-z.
return keyCode - lowercaseAlphabeticOffset;
if (65 <= keyCode && keyCode <= 90) // Handle A-Z.
return keyCode - uppercaseAlphabeticOffset;
if (49 <= keyCode && keyCode <= 57) // Handle 1-9.
return keyCode - numericNonZeroOffset;
// Handle all other cases.
switch (keyCode) {
case '`':
case '~':
return kHIDUsage_KeyboardGraveAccentAndTilde;
case '!':
return kHIDUsage_Keyboard1;
case '@':
return kHIDUsage_Keyboard2;
case '#':
return kHIDUsage_Keyboard3;
case '$':
return kHIDUsage_Keyboard4;
case '%':
return kHIDUsage_Keyboard5;
case '^':
return kHIDUsage_Keyboard6;
case '&':
return kHIDUsage_Keyboard7;
case '*':
return kHIDUsage_Keyboard8;
case '(':
return kHIDUsage_Keyboard9;
case ')':
case '0':
return kHIDUsage_Keyboard0;
case '-':
case '_':
return kHIDUsage_KeyboardHyphen;
case '=':
case '+':
return kHIDUsage_KeyboardEqualSign;
case '\b':
return kHIDUsage_KeyboardDeleteOrBackspace;
case '\t':
return kHIDUsage_KeyboardTab;
case '[':
case '{':
return kHIDUsage_KeyboardOpenBracket;
case ']':
case '}':
return kHIDUsage_KeyboardCloseBracket;
case '\\':
case '|':
return kHIDUsage_KeyboardBackslash;
case ';':
case ':':
return kHIDUsage_KeyboardSemicolon;
case '\'':
case '"':
return kHIDUsage_KeyboardQuote;
case '\r':
case '\n':
return kHIDUsage_KeyboardReturnOrEnter;
case ',':
case '<':
return kHIDUsage_KeyboardComma;
case '.':
case '>':
return kHIDUsage_KeyboardPeriod;
case '/':
case '?':
return kHIDUsage_KeyboardSlash;