forked from facebook/react-native
-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathRCTSurfacePointerHandler.mm
More file actions
946 lines (797 loc) · 30.3 KB
/
RCTSurfacePointerHandler.mm
File metadata and controls
946 lines (797 loc) · 30.3 KB
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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "RCTSurfacePointerHandler.h"
#import <React/RCTIdentifierPool.h>
#import <React/RCTReactTaggedView.h>
#import <React/RCTUtils.h>
#import <React/RCTViewComponentView.h>
#import "RCTConversions.h"
#import "RCTTouchableComponentViewProtocol.h"
using namespace facebook::react;
typedef NS_ENUM(NSInteger, RCTPointerEventType) {
RCTPointerEventTypeStart,
RCTPointerEventTypeMove,
RCTPointerEventTypeEnd,
RCTPointerEventTypeCancel,
};
#if !TARGET_OS_OSX // [macOS]
static BOOL AllTouchesAreCancelledOrEnded(NSSet<UITouch *> *touches)
{
for (UITouch *touch in touches) {
if (touch.phase == UITouchPhaseBegan || touch.phase == UITouchPhaseMoved || touch.phase == UITouchPhaseStationary) {
return NO;
}
}
return YES;
}
static BOOL AnyTouchesChanged(NSSet<UITouch *> *touches)
{
for (UITouch *touch in touches) {
if (touch.phase == UITouchPhaseBegan || touch.phase == UITouchPhaseMoved) {
return YES;
}
}
return NO;
}
#endif // [macOS]
struct ActivePointer {
/*
* Pointer ID
*/
NSInteger identifier;
/*
* The component view on which the touch started.
*/
RCTPlatformView<RCTComponentViewProtocol> *initialComponentView = nil; // [macOS]
/*
* The current target component view of the pointer
*/
RCTPlatformView<RCTComponentViewProtocol> *componentView = nil; // [macOS]
/*
* The location of the pointer relative to the root component view
*/
CGPoint clientPoint;
/*
* The location of the pointer relative to the device's screen
*/
CGPoint screenPoint;
/*
* The location of the pointer relative to the pointer's target
*/
CGPoint offsetPoint;
/*
* Current timestamp of the pointer event
*/
NSTimeInterval timestamp;
/*
* The current force of the pointer
*/
Float force;
/*
* The type of touch received.
*/
UITouchType touchType;
/*
* The radius (in points) of the touch.
*/
CGFloat majorRadius;
/*
* The altitude (in radians) of the stylus.
*/
CGFloat altitudeAngle;
/*
* The azimuth angle (in radians) of the stylus.
*/
CGFloat azimuthAngle;
/*
* The button mask of the touch
*/
UIEventButtonMask buttonMask;
/*
* The bit mask of modifier flags in the gesture represented by the receiver.
*/
UIKeyModifierFlags modifierFlags;
/*
* Indicates if the active touch represents the primary pointer of this pointer type.
*/
BOOL isPrimary;
/*
* The button number that was pressed (if applicable) when the event was fired.
*/
NSInteger button;
/*
* Informs the event system that when the touch is released it should be treated as the
* pointer leaving the screen entirely.
*/
BOOL shouldLeaveWhenReleased;
struct Hasher {
size_t operator()(const ActivePointer &activePointer) const
{
return std::hash<decltype(activePointer.identifier)>()(activePointer.identifier);
}
};
struct Comparator {
bool operator()(const ActivePointer &lhs, const ActivePointer &rhs) const
{
return lhs.identifier == rhs.identifier;
}
};
};
// Mouse and Pen pointers get reserved IDs so they stay consistent no matter the order
// at which events come in
static NSInteger constexpr kMousePointerId = 0;
static NSInteger constexpr kPencilPointerId = 1;
// If a new reserved ID is added above this should be incremented to ensure touch events
// do not conflict
static NSInteger constexpr kTouchIdentifierPoolOffset = 2;
static SharedTouchEventEmitter GetTouchEmitterFromView(RCTUIView *componentView, CGPoint point) // [macOS]
{
return [(id<RCTTouchableComponentViewProtocol>)componentView touchEventEmitterAtPoint:point];
}
static NSOrderedSet<RCTReactTaggedView *> *GetTouchableViewsInPathToRoot(RCTPlatformView *componentView) // [macOS]
{
NSMutableOrderedSet *results = [NSMutableOrderedSet orderedSet];
do {
if ([componentView respondsToSelector:@selector(touchEventEmitterAtPoint:)]) {
[results addObject:[RCTReactTaggedView wrap:componentView]];
}
componentView = componentView.superview;
} while (componentView);
return results;
}
static RCTPlatformView *FindClosestFabricManagedTouchableView(RCTPlatformView *componentView) // [macOS]
{
while (componentView) {
if ([componentView respondsToSelector:@selector(touchEventEmitterAtPoint:)]) {
return componentView;
}
componentView = componentView.superview;
}
return nil;
}
static NSInteger ButtonMaskDiffToButton(UIEventButtonMask prevButtonMask, UIEventButtonMask curButtonMask)
{
#if !TARGET_OS_OSX // [macOS]
if ((prevButtonMask & UIEventButtonMaskPrimary) != (curButtonMask & UIEventButtonMaskPrimary)) {
return 0;
}
if ((prevButtonMask & 0x4) != (curButtonMask & 0x4)) {
return 1;
}
if ((prevButtonMask & UIEventButtonMaskSecondary) != (curButtonMask & UIEventButtonMaskSecondary)) {
return 2;
}
#endif // [macOS]
return -1;
}
// Returns a CGPoint which represents the tiltX/Y values (in RADIANS)
// Adapted from https://gist.github.com/k3a/2903719bb42b48c9198d20c2d6f73ac1
static CGPoint SphericalToTilt(CGFloat altitudeAngleRad, CGFloat azimuthAngleRad)
{
if (altitudeAngleRad == M_PI / 2.0) {
return CGPointMake(0.0, 0.0);
} else if (altitudeAngleRad == 0.0) {
// when pen is laying on the pad it is impossible to precisely encode but at least approximate for 4 cases
if (azimuthAngleRad > 7.0 * M_PI / 4.0 || azimuthAngleRad <= M_PI / 4.0) {
// for azimuthRad == 0, the pen is on the positive Y axis
return CGPointMake(0.0, M_PI / 2.0);
} else if (azimuthAngleRad > M_PI / 4.0 && azimuthAngleRad <= 3 * M_PI / 4.0) {
// for azimuthRad == math.pi/2 the pen is on the positive X axis
return CGPointMake(M_PI / 2.0, 0.0);
} else if (azimuthAngleRad > 3.0 * M_PI / 4.0 && azimuthAngleRad <= 5.0 * M_PI / 4.0) {
// for azimuthRad == math.pi, the pen is on the negative Y axis
return CGPointMake(0.0, -M_PI / 2.0);
} else if (azimuthAngleRad > 5.0 * M_PI / 4.0 && azimuthAngleRad <= 7.0 * M_PI / 4.0) {
// for azimuthRad == math.pi + math.pi/2 pen on negative X axis
return CGPointMake(-M_PI / 2.0, 0.0);
}
}
CGFloat tanAlt = tan(altitudeAngleRad); // tan(x) = sin(x)/cos(x)
CGFloat tiltXrad = atan(sin(azimuthAngleRad) / tanAlt);
CGFloat tiltYrad = atan(cos(azimuthAngleRad) / tanAlt);
return CGPointMake(tiltXrad, tiltYrad);
}
static CGFloat RadsToDegrees(CGFloat rads)
{
return rads * 180 / M_PI;
}
static NSInteger ButtonMaskToButtons(UIEventButtonMask buttonMask)
{
NSInteger buttonsMaskResult = 0;
#if !TARGET_OS_OSX // [macOS]
if ((buttonMask & UIEventButtonMaskPrimary) != 0) {
buttonsMaskResult |= 1;
}
if ((buttonMask & UIEventButtonMaskSecondary) != 0) {
buttonsMaskResult |= 2;
}
// undocumented mask value which represents the "auxiliary button" (i.e. middle mouse button)
if ((buttonMask & 0x4) != 0) {
buttonsMaskResult |= 4;
}
#endif // [macOS]
return buttonsMaskResult;
}
#if !TARGET_OS_OSX // [macOS]
static const char *PointerTypeCStringFromUITouchType(UITouchType type)
{
switch (type) {
case UITouchTypeDirect:
return "touch";
case UITouchTypePencil:
return "pen";
case UITouchTypeIndirectPointer:
return "mouse";
case UITouchTypeIndirect:
default:
return "";
}
}
static void UpdatePointerEventModifierFlags(PointerEvent &event, UIKeyModifierFlags flags)
{
event.ctrlKey = (flags & UIKeyModifierControl) != 0;
event.shiftKey = (flags & UIKeyModifierShift) != 0;
event.altKey = (flags & UIKeyModifierAlternate) != 0;
event.metaKey = (flags & UIKeyModifierCommand) != 0;
}
static PointerEvent CreatePointerEventFromActivePointer(
ActivePointer activePointer,
RCTPointerEventType eventType,
UIView *rootComponentView)
{
PointerEvent event = {};
event.pointerId = activePointer.identifier;
event.pointerType = PointerTypeCStringFromUITouchType(activePointer.touchType);
if (eventType == RCTPointerEventTypeCancel) {
event.clientPoint = RCTPointFromCGPoint(CGPointZero);
#if !TARGET_OS_VISION // [visionOS]
event.screenPoint =
RCTPointFromCGPoint([rootComponentView convertPoint:CGPointZero
toCoordinateSpace:rootComponentView.window.screen.coordinateSpace]);
#endif // [visionOS]
event.offsetPoint = RCTPointFromCGPoint([rootComponentView convertPoint:CGPointZero
toView:activePointer.componentView]);
} else {
event.clientPoint = RCTPointFromCGPoint(activePointer.clientPoint);
event.screenPoint = RCTPointFromCGPoint(activePointer.screenPoint);
event.offsetPoint = RCTPointFromCGPoint(activePointer.offsetPoint);
}
event.pressure = activePointer.force;
if (activePointer.touchType == UITouchTypeIndirectPointer) {
// pointer events with a mouse button pressed should report a pressure of 0.5
// when the touch is down and 0.0 when it is lifted regardless of how it is reported by the OS
event.pressure = eventType != RCTPointerEventTypeEnd ? 0.5 : 0.0;
}
CGFloat pointerSize = activePointer.majorRadius * 2.0;
if (activePointer.touchType == UITouchTypeIndirectPointer) {
// mouse type pointers should always report a size of 1
pointerSize = 1.0;
}
event.width = pointerSize;
event.height = pointerSize;
CGPoint tilt = SphericalToTilt(activePointer.altitudeAngle, activePointer.azimuthAngle);
event.tiltX = RadsToDegrees(tilt.x);
event.tiltY = RadsToDegrees(tilt.y);
event.detail = 0;
event.button = activePointer.button;
event.buttons = ButtonMaskToButtons(activePointer.buttonMask);
UpdatePointerEventModifierFlags(event, activePointer.modifierFlags);
event.tangentialPressure = 0.0;
event.twist = 0;
event.isPrimary = activePointer.isPrimary;
return event;
}
static PointerEvent CreatePointerEventFromIncompleteHoverData(
NSInteger pointerId,
std::string pointerType,
CGPoint clientLocation,
CGPoint screenLocation,
CGPoint offsetLocation,
UIKeyModifierFlags modifierFlags)
{
PointerEvent event = {};
event.pointerId = pointerId;
event.pressure = 0.0;
event.pointerType = pointerType;
event.clientPoint = RCTPointFromCGPoint(clientLocation);
event.screenPoint = RCTPointFromCGPoint(screenLocation);
event.offsetPoint = RCTPointFromCGPoint(offsetLocation);
event.width = 1.0;
event.height = 1.0;
event.tiltX = 0;
event.tiltY = 0;
event.detail = 0;
event.button = -1;
event.buttons = 0;
UpdatePointerEventModifierFlags(event, modifierFlags);
event.tangentialPressure = 0.0;
event.twist = 0;
event.isPrimary = true;
return event;
}
#endif // [macOS]
static void UpdateActivePointerWithUITouch(
ActivePointer &activePointer,
RCTUITouch *uiTouch, // [macOS]
UIEvent *uiEvent,
RCTUIView *rootComponentView) // [macOS]
{
#if !TARGET_OS_OSX // [macOS]
CGPoint location = [uiTouch locationInView:rootComponentView];
UIView *hitTestedView = [rootComponentView hitTest:location withEvent:nil];
activePointer.componentView = FindClosestFabricManagedTouchableView(hitTestedView);
#else // [macOS
CGPoint touchLocation = [rootComponentView.superview convertPoint:uiTouch.locationInWindow fromView:nil];
activePointer.componentView = (RCTUIView *) [rootComponentView hitTest:touchLocation];
#endif // macOS]
#if !TARGET_OS_OSX // [macOS]
activePointer.clientPoint = [uiTouch locationInView:rootComponentView];
#if !TARGET_OS_VISION // [visionOS]
activePointer.screenPoint = [rootComponentView convertPoint:activePointer.clientPoint
toCoordinateSpace:rootComponentView.window.screen.coordinateSpace];
#endif // [visionOS]
activePointer.offsetPoint = [uiTouch locationInView:activePointer.componentView];
#else // [macOS
activePointer.offsetPoint = [activePointer.componentView convertPoint:uiTouch.locationInWindow fromView:nil];
activePointer.screenPoint = uiTouch.locationInWindow;
activePointer.clientPoint = CGPointMake(activePointer.screenPoint.x, CGRectGetHeight(rootComponentView.window.frame) - activePointer.screenPoint.y);
#endif // macOS]
activePointer.timestamp = uiTouch.timestamp;
#if !TARGET_OS_OSX // [macOS]
activePointer.force = RCTZeroIfNaN(uiTouch.force / uiTouch.maximumPossibleForce);
activePointer.touchType = uiTouch.type;
activePointer.majorRadius = uiTouch.majorRadius;
activePointer.altitudeAngle = uiTouch.altitudeAngle;
activePointer.azimuthAngle = [uiTouch azimuthAngleInView:nil];
UIEventButtonMask nextButtonMask = 0;
if (uiTouch.phase != UITouchPhaseEnded) {
nextButtonMask = uiTouch.type == UITouchTypeIndirectPointer ? uiEvent.buttonMask : 1;
}
activePointer.button = ButtonMaskDiffToButton(activePointer.buttonMask, nextButtonMask);
activePointer.buttonMask = nextButtonMask;
activePointer.modifierFlags = uiEvent.modifierFlags;
#else // [macOS
NSEventType type = uiTouch.type;
if (type == NSEventTypeLeftMouseDown || type == NSEventTypeLeftMouseUp || type == NSEventTypeLeftMouseDragged) {
activePointer.button = 0;
} else if (type == NSEventTypeRightMouseDown || type == NSEventTypeRightMouseUp || type == NSEventTypeRightMouseDragged) {
activePointer.button = 2;
}
activePointer.modifierFlags = uiEvent.modifierFlags;
#endif // macOS]
}
/**
* Given an ActivePointer determine if it is still within the same event target tree as
* the one which initiated the pointer gesture.
*/
static BOOL IsPointerWithinInitialTree(ActivePointer activePointer)
{
NSOrderedSet<RCTReactTaggedView *> *initialViewSet =
GetTouchableViewsInPathToRoot(activePointer.initialComponentView);
for (RCTReactTaggedView *canidateTaggedView in initialViewSet) {
if (canidateTaggedView.tag == activePointer.componentView.tag) {
return YES;
}
}
return NO;
}
/**
* Surprisingly, `__unsafe_unretained id` pointers are not regular pointers
* and `std::hash<>` cannot hash them.
* This is quite trivial but decent implementation of hasher function
* inspired by this research: https://stackoverflow.com/a/21062520/496389.
*/
template <typename PointerT>
struct PointerHasher {
constexpr std::size_t operator()(const PointerT &value) const
{
return reinterpret_cast<size_t>(value);
}
};
@interface RCTSurfacePointerHandler () <UIGestureRecognizerDelegate>
@end
@implementation RCTSurfacePointerHandler {
#if !TARGET_OS_OSX // [macOS]
std::unordered_map<__unsafe_unretained RCTUITouch *, ActivePointer, PointerHasher<__unsafe_unretained RCTUITouch *>>
_activePointers;
#else // [macOS
std::unordered_map<NSInteger, ActivePointer> _activePointers;
#endif // macOS]
/*
* We hold the view weakly to prevent a retain cycle.
*/
__weak RCTUIView *_rootComponentView; // [macOS]
RCTIdentifierPool<11> _identifierPool;
#if !TARGET_OS_OSX // [macOS]
UIHoverGestureRecognizer *_mouseHoverRecognizer API_AVAILABLE(ios(13.0));
UIHoverGestureRecognizer *_penHoverRecognizer API_AVAILABLE(ios(13.0));
#endif // [macOS]
NSMutableDictionary<NSNumber *, NSOrderedSet<RCTReactTaggedView *> *> *_currentlyHoveredViewsPerPointer;
NSInteger _primaryTouchPointerId;
}
- (instancetype)init
{
if (self = [super initWithTarget:nil action:nil]) {
// `cancelsTouchesInView` and `delaysTouches*` are needed in order
// to be used as a top level event delegated recognizer.
// Otherwise, lower-level components not built using React Native,
// will fail to recognize gestures.
#if !TARGET_OS_OSX // [macOS]
self.cancelsTouchesInView = NO;
self.delaysTouchesBegan = NO; // This is default value.
self.delaysTouchesEnded = NO;
#endif // [macOS]
self.delegate = self;
#if !TARGET_OS_OSX // [macOS]
_mouseHoverRecognizer = nil;
_penHoverRecognizer = nil;
#endif // [macOS]
_currentlyHoveredViewsPerPointer = [[NSMutableDictionary alloc] init];
_primaryTouchPointerId = -1;
}
return self;
}
RCT_NOT_IMPLEMENTED(-(instancetype)initWithTarget : (id)target action : (SEL)action)
- (void)attachToView:(RCTPlatformView *)view // [macOS]
{
RCTAssert(self.view == nil, @"RCTSurfacePointerHandler already has an attached view.");
[view addGestureRecognizer:self];
_rootComponentView = view;
#if !TARGET_OS_OSX // [macOS]
_mouseHoverRecognizer = [[UIHoverGestureRecognizer alloc] initWithTarget:self action:@selector(mouseHovering:)];
_mouseHoverRecognizer.allowedTouchTypes = @[ @(UITouchTypeIndirectPointer) ];
[view addGestureRecognizer:_mouseHoverRecognizer];
_penHoverRecognizer = [[UIHoverGestureRecognizer alloc] initWithTarget:self action:@selector(penHovering:)];
_penHoverRecognizer.allowedTouchTypes = @[ @(UITouchTypePencil) ];
[view addGestureRecognizer:_penHoverRecognizer];
#endif // [macOS]
}
- (void)detachFromView:(RCTPlatformView *)view // [macOS]
{
RCTAssertParam(view);
RCTAssert(self.view == view, @"RCTSufracePointerHandler attached to another view.");
[view removeGestureRecognizer:self];
_rootComponentView = nil;
#if !TARGET_OS_OSX // [macOS]
if (_mouseHoverRecognizer != nil) {
[view removeGestureRecognizer:_mouseHoverRecognizer];
_mouseHoverRecognizer = nil;
}
if (_penHoverRecognizer != nil) {
[view removeGestureRecognizer:_penHoverRecognizer];
_penHoverRecognizer = nil;
}
#endif
}
#pragma mark - UITouch to ActivePointer management
- (void)_registerTouches:(NSSet<RCTUITouch *> *)touches withEvent:(UIEvent *)event // [macOS]
{
for (RCTUITouch *touch in touches) { // [macOS]
ActivePointer activePointer = {};
#if !TARGET_OS_OSX // [macOS]
// Determine the identifier of the Pointer and if it is the primary pointer
switch (touch.type) {
case UITouchTypeIndirectPointer:
activePointer.identifier = kMousePointerId;
activePointer.isPrimary = true;
break;
case UITouchTypePencil:
activePointer.identifier = kPencilPointerId;
activePointer.isPrimary = true;
break;
default:
// use the identifier pool offset to ensure no conflicts between the reserved IDs and the
// touch IDs
activePointer.identifier = _identifierPool.dequeue() + kTouchIdentifierPoolOffset;
if (_primaryTouchPointerId == -1) {
_primaryTouchPointerId = activePointer.identifier;
activePointer.isPrimary = true;
}
break;
}
#endif // [macOS]
// If the pointer has not been marked as hovering over views before the touch started, we register
// that the activeTouch should not maintain its hovered state once the pointer has been lifted.
auto currentlyHoveredViews = [_currentlyHoveredViewsPerPointer objectForKey:@(activePointer.identifier)];
if (currentlyHoveredViews == nil || [currentlyHoveredViews count] == 0) {
activePointer.shouldLeaveWhenReleased = YES;
}
#if !TARGET_OS_OSX // [macOS]
activePointer.initialComponentView = FindClosestFabricManagedTouchableView(touch.view);
#else // [macOS
CGPoint touchLocation = [_rootComponentView.superview convertPoint:touch.locationInWindow fromView:nil];
RCTPlatformView *componentView = (RCTPlatformView *) [_rootComponentView hitTest:touchLocation];
activePointer.initialComponentView = FindClosestFabricManagedTouchableView(componentView);
#endif // macOS]
UpdateActivePointerWithUITouch(activePointer, touch, event, _rootComponentView);
#if !TARGET_OS_OSX // [macOS]
_activePointers.emplace(touch, activePointer);
#else // [macOS
_activePointers.emplace(touch.eventNumber, activePointer);
#endif // macOS]
}
}
- (void)_updateTouches:(NSSet<RCTUITouch *> *)touches withEvent:(UIEvent *)event // [macOS]
{
for (RCTUITouch *touch in touches) { // [macOS]
#if !TARGET_OS_OSX // [macOS]
auto iterator = _activePointers.find(touch);
#else // [macOS
auto iterator = _activePointers.find(touch.eventNumber);
#endif // macOS]
RCTAssert(iterator != _activePointers.end(), @"Inconsistency between local and UIKit touch registries");
if (iterator == _activePointers.end()) {
continue;
}
UpdateActivePointerWithUITouch(iterator->second, touch, event, _rootComponentView);
}
}
- (void)_unregisterTouches:(NSSet<RCTUITouch *> *)touches // [macOS]
{
for (RCTUITouch *touch in touches) { // [macOS]
#if !TARGET_OS_OSX // [macOS]
auto iterator = _activePointers.find(touch);
#else // [macOS
auto iterator = _activePointers.find(touch.eventNumber);
#endif // macOS]
RCTAssert(iterator != _activePointers.end(), @"Inconsistency between local and UIKit touch registries");
if (iterator == _activePointers.end()) {
continue;
}
auto &activePointer = iterator->second;
if (activePointer.identifier == _primaryTouchPointerId) {
_primaryTouchPointerId = -1;
}
#if !TARGET_OS_OSX // [macOS]
// only need to enqueue if the touch type isn't one with a reserved identifier
switch (touch.type) {
case UITouchTypeIndirectPointer:
case UITouchTypePencil:
break;
default:
// since the touch's identifier has been offset we need to re-normalize it to 0-based
// which is what the identifier pool expects
_identifierPool.enqueue(activePointer.identifier - kTouchIdentifierPoolOffset);
}
_activePointers.erase(touch);
#else // [macOS
_activePointers.erase(touch.eventNumber);
#endif // macOS]
}
}
- (std::vector<ActivePointer>)_activePointersFromTouches:(NSSet<RCTUITouch *> *)touches // [macOS]
{
std::vector<ActivePointer> activePointers;
activePointers.reserve(touches.count);
for (RCTUITouch *touch in touches) { // [macOS]
#if !TARGET_OS_OSX // [macOS]
auto iterator = _activePointers.find(touch);
#else // [macOS
auto iterator = _activePointers.find(touch.eventNumber);
#endif // macOS]
RCTAssert(iterator != _activePointers.end(), @"Inconsistency between local and UIKit touch registries");
if (iterator == _activePointers.end()) {
continue;
}
activePointers.push_back(iterator->second);
}
return activePointers;
}
- (void)_dispatchActivePointers:(std::vector<ActivePointer>)activePointers eventType:(RCTPointerEventType)eventType
{
#if !TARGET_OS_OSX // [macOS]
for (const auto &activePointer : activePointers) {
PointerEvent pointerEvent = CreatePointerEventFromActivePointer(activePointer, eventType, _rootComponentView);
SharedTouchEventEmitter eventEmitter = GetTouchEmitterFromView(
activePointer.componentView,
[_rootComponentView convertPoint:activePointer.clientPoint toView:activePointer.componentView]);
if (eventEmitter != nil) {
switch (eventType) {
case RCTPointerEventTypeStart: {
eventEmitter->onPointerDown(std::move(pointerEvent));
break;
}
case RCTPointerEventTypeMove: {
eventEmitter->onPointerMove(std::move(pointerEvent));
break;
}
case RCTPointerEventTypeEnd: {
eventEmitter->onPointerUp(pointerEvent);
if (pointerEvent.isPrimary && pointerEvent.button == 0) {
if (IsPointerWithinInitialTree(activePointer)) {
eventEmitter->onClick(std::move(pointerEvent));
}
} else if (IsPointerWithinInitialTree(activePointer)) {
eventEmitter->onAuxClick(std::move(pointerEvent));
}
break;
}
case RCTPointerEventTypeCancel: {
eventEmitter->onPointerCancel(std::move(pointerEvent));
break;
}
}
}
}
#endif // [macOS]
}
#pragma mark - `UIResponder`-ish touch-delivery methods
#if !TARGET_OS_OSX // [macOS]
- (void)touchesBegan:(NSSet<RCTUITouch *> *)touches withEvent:(UIEvent *)event // [macOS]
{
[super touchesBegan:touches withEvent:event];
[self _registerTouches:touches withEvent:event];
[self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeStart];
if (self.state == UIGestureRecognizerStatePossible) {
self.state = UIGestureRecognizerStateBegan;
} else if (self.state == UIGestureRecognizerStateBegan) {
self.state = UIGestureRecognizerStateChanged;
}
}
- (void)touchesMoved:(NSSet<RCTUITouch *> *)touches withEvent:(UIEvent *)event // [macOS]
{
[super touchesMoved:touches withEvent:event];
[self _updateTouches:touches withEvent:event];
[self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeMove];
self.state = UIGestureRecognizerStateChanged;
}
- (void)touchesEnded:(NSSet<RCTUITouch *> *)touches withEvent:(UIEvent *)event // [macOS]
{
[super touchesEnded:touches withEvent:event];
[self _updateTouches:touches withEvent:event];
[self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeEnd];
[self _unregisterTouches:touches];
if (AllTouchesAreCancelledOrEnded(event.allTouches)) {
self.state = UIGestureRecognizerStateEnded;
} else if (AnyTouchesChanged(event.allTouches)) {
self.state = UIGestureRecognizerStateChanged;
}
}
- (void)touchesCancelled:(NSSet<RCTUITouch *> *)touches withEvent:(UIEvent *)event // [macOS]
{
[super touchesCancelled:touches withEvent:event];
[self _updateTouches:touches withEvent:event];
[self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeCancel];
[self _unregisterTouches:touches];
if (AllTouchesAreCancelledOrEnded(event.allTouches)) {
self.state = UIGestureRecognizerStateCancelled;
} else if (AnyTouchesChanged(event.allTouches)) {
self.state = UIGestureRecognizerStateChanged;
}
}
#else // [macOS
- (BOOL)acceptsFirstMouse:(NSEvent *)event
{
// This will only be called if the hit-tested view returns YES for acceptsFirstMouse,
// therefore asking it again would be redundant.
return YES;
}
- (void)mouseDown:(NSEvent *)event
{
[super mouseDown:event];
{
NSSet* touches = [NSSet setWithObject:event];
[self _registerTouches:touches withEvent:event]; // [macOS]
[self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeStart];
if (self.state == NSGestureRecognizerStatePossible) {
self.state = NSGestureRecognizerStateBegan;
} else if (self.state == NSGestureRecognizerStateBegan) {
self.state = NSGestureRecognizerStateChanged;
}
}
}
- (void)rightMouseDown:(NSEvent *)event
{
[super rightMouseDown:event];
{
NSSet* touches = [NSSet setWithObject:event];
[self _registerTouches:touches withEvent:event]; // [macOS]
[self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeStart];
if (self.state == NSGestureRecognizerStatePossible) {
self.state = NSGestureRecognizerStateBegan;
} else if (self.state == NSGestureRecognizerStateBegan) {
self.state = NSGestureRecognizerStateChanged;
}
}
}
- (void)mouseDragged:(NSEvent *)event
{
[super mouseDragged:event];
NSSet* touches = [NSSet setWithObject:event];
[self _updateTouches:touches withEvent:event]; // [macOS]
[self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeMove];
self.state = NSGestureRecognizerStateChanged;
}
- (void)rightMouseDragged:(NSEvent *)event
{
[super rightMouseDragged:event];
NSSet* touches = [NSSet setWithObject:event];
[self _updateTouches:touches withEvent:event]; // [macOS]
[self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeMove];
self.state = NSGestureRecognizerStateChanged;
}
- (void)mouseUp:(NSEvent *)event
{
[super mouseUp:event];
NSSet* touches = [NSSet setWithObject:event];
[self _updateTouches:touches withEvent:event]; // [macOS]
[self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeEnd];
[self _unregisterTouches:touches];
self.state = NSGestureRecognizerStateEnded;
}
- (void)rightMouseUp:(NSEvent *)event
{
[super rightMouseUp:event];
NSSet* touches = [NSSet setWithObject:event];
[self _updateTouches:touches withEvent:event]; // [macOS]
[self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeEnd];
[self _unregisterTouches:touches];
self.state = NSGestureRecognizerStateEnded;
}
#endif // macOS]
- (void)reset
{
[super reset];
if (!_activePointers.empty()) {
std::vector<ActivePointer> activePointers;
activePointers.reserve(_activePointers.size());
for (const auto &pair : _activePointers) {
activePointers.push_back(pair.second);
}
[self _dispatchActivePointers:activePointers eventType:RCTPointerEventTypeCancel];
// Force-unregistering all the pointers
_activePointers.clear();
_identifierPool.reset();
}
}
- (BOOL)canPreventGestureRecognizer:(UIGestureRecognizer *)preventedGestureRecognizer
{
return NO;
}
#pragma mark - Hover callbacks
#if !TARGET_OS_OSX // [macOS]
- (void)penHovering:(UIHoverGestureRecognizer *)recognizer API_AVAILABLE(ios(13.0))
{
[self hovering:recognizer pointerId:kPencilPointerId pointerType:"pen"];
}
- (void)mouseHovering:(UIHoverGestureRecognizer *)recognizer API_AVAILABLE(ios(13.0))
{
[self hovering:recognizer pointerId:kMousePointerId pointerType:"mouse"];
}
- (void)hovering:(UIHoverGestureRecognizer *)recognizer
pointerId:(int)pointerId
pointerType:(std::string)pointerType API_AVAILABLE(ios(13.0))
{
UIView *listenerView = recognizer.view;
CGPoint clientLocation = [recognizer locationInView:listenerView];
#if !TARGET_OS_VISION // [visionOS]
CGPoint screenLocation = [listenerView convertPoint:clientLocation
toCoordinateSpace:listenerView.window.screen.coordinateSpace];
#else // [visionOS
CGPoint screenLocation = CGPointZero;
#endif // visionOS]
UIView *targetView = [listenerView hitTest:clientLocation withEvent:nil];
targetView = FindClosestFabricManagedTouchableView(targetView);
CGPoint offsetLocation = [recognizer locationInView:targetView];
UIKeyModifierFlags modifierFlags;
modifierFlags = recognizer.modifierFlags;
PointerEvent event = CreatePointerEventFromIncompleteHoverData(
pointerId, pointerType, clientLocation, screenLocation, offsetLocation, modifierFlags);
SharedTouchEventEmitter eventEmitter = GetTouchEmitterFromView(targetView, offsetLocation);
if (eventEmitter != nil) {
switch (recognizer.state) {
case UIGestureRecognizerStateEnded:
eventEmitter->onPointerLeave(std::move(event));
break;
default:
eventEmitter->onPointerMove(std::move(event));
break;
}
}
}
#endif // [macOS]
@end