RCTTouchHandler.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #import "RCTTouchHandler.h"
  8. #import <UIKit/UIGestureRecognizerSubclass.h>
  9. #import "RCTAssert.h"
  10. #import "RCTBridge.h"
  11. #import "RCTEventDispatcher.h"
  12. #import "RCTLog.h"
  13. #import "RCTSurfaceView.h"
  14. #import "RCTTouchEvent.h"
  15. #import "RCTUIManager.h"
  16. #import "RCTUtils.h"
  17. #import "UIView+React.h"
  18. @interface RCTTouchHandler () <UIGestureRecognizerDelegate>
  19. @end
  20. // TODO: this class behaves a lot like a module, and could be implemented as a
  21. // module if we were to assume that modules and RootViews had a 1:1 relationship
  22. @implementation RCTTouchHandler
  23. {
  24. __weak RCTEventDispatcher *_eventDispatcher;
  25. /**
  26. * Arrays managed in parallel tracking native touch object along with the
  27. * native view that was touched, and the React touch data dictionary.
  28. * These must be kept track of because `UIKit` destroys the touch targets
  29. * if touches are canceled, and we have no other way to recover this info.
  30. */
  31. NSMutableOrderedSet<UITouch *> *_nativeTouches;
  32. NSMutableArray<NSMutableDictionary *> *_reactTouches;
  33. NSMutableArray<UIView *> *_touchViews;
  34. __weak UIView *_cachedRootView;
  35. uint16_t _coalescingKey;
  36. }
  37. - (instancetype)initWithBridge:(RCTBridge *)bridge
  38. {
  39. RCTAssertParam(bridge);
  40. if ((self = [super initWithTarget:nil action:NULL])) {
  41. _eventDispatcher = [bridge moduleForClass:[RCTEventDispatcher class]];
  42. _nativeTouches = [NSMutableOrderedSet new];
  43. _reactTouches = [NSMutableArray new];
  44. _touchViews = [NSMutableArray new];
  45. // `cancelsTouchesInView` and `delaysTouches*` are needed in order to be used as a top level
  46. // event delegated recognizer. Otherwise, lower-level components not built
  47. // using RCT, will fail to recognize gestures.
  48. self.cancelsTouchesInView = NO;
  49. self.delaysTouchesBegan = NO; // This is default value.
  50. self.delaysTouchesEnded = NO;
  51. self.delegate = self;
  52. }
  53. return self;
  54. }
  55. RCT_NOT_IMPLEMENTED(- (instancetype)initWithTarget:(id)target action:(SEL)action)
  56. - (void)attachToView:(UIView *)view
  57. {
  58. RCTAssert(self.view == nil, @"RCTTouchHandler already has attached view.");
  59. [view addGestureRecognizer:self];
  60. }
  61. - (void)detachFromView:(UIView *)view
  62. {
  63. RCTAssertParam(view);
  64. RCTAssert(self.view == view, @"RCTTouchHandler attached to another view.");
  65. [view removeGestureRecognizer:self];
  66. }
  67. #pragma mark - Bookkeeping for touch indices
  68. - (void)_recordNewTouches:(NSSet<UITouch *> *)touches
  69. {
  70. for (UITouch *touch in touches) {
  71. RCTAssert(![_nativeTouches containsObject:touch],
  72. @"Touch is already recorded. This is a critical bug.");
  73. // Find closest React-managed touchable view
  74. UIView *targetView = touch.view;
  75. while (targetView) {
  76. if (targetView.reactTag && targetView.userInteractionEnabled) {
  77. break;
  78. }
  79. targetView = targetView.superview;
  80. }
  81. NSNumber *reactTag = [targetView reactTagAtPoint:[touch locationInView:targetView]];
  82. if (!reactTag || !targetView.userInteractionEnabled) {
  83. continue;
  84. }
  85. // Get new, unique touch identifier for the react touch
  86. const NSUInteger RCTMaxTouches = 11; // This is the maximum supported by iDevices
  87. NSInteger touchID = ([_reactTouches.lastObject[@"identifier"] integerValue] + 1) % RCTMaxTouches;
  88. for (NSDictionary *reactTouch in _reactTouches) {
  89. NSInteger usedID = [reactTouch[@"identifier"] integerValue];
  90. if (usedID == touchID) {
  91. // ID has already been used, try next value
  92. touchID ++;
  93. } else if (usedID > touchID) {
  94. // If usedID > touchID, touchID must be unique, so we can stop looking
  95. break;
  96. }
  97. }
  98. // Create touch
  99. NSMutableDictionary *reactTouch = [[NSMutableDictionary alloc] initWithCapacity:RCTMaxTouches];
  100. reactTouch[@"target"] = reactTag;
  101. reactTouch[@"identifier"] = @(touchID);
  102. // Add to arrays
  103. [_touchViews addObject:targetView];
  104. [_nativeTouches addObject:touch];
  105. [_reactTouches addObject:reactTouch];
  106. }
  107. }
  108. - (void)_recordRemovedTouches:(NSSet<UITouch *> *)touches
  109. {
  110. for (UITouch *touch in touches) {
  111. NSUInteger index = [_nativeTouches indexOfObject:touch];
  112. if (index == NSNotFound) {
  113. continue;
  114. }
  115. [_touchViews removeObjectAtIndex:index];
  116. [_nativeTouches removeObjectAtIndex:index];
  117. [_reactTouches removeObjectAtIndex:index];
  118. }
  119. }
  120. - (void)_updateReactTouchAtIndex:(NSInteger)touchIndex
  121. {
  122. UITouch *nativeTouch = _nativeTouches[touchIndex];
  123. CGPoint windowLocation = [nativeTouch locationInView:nativeTouch.window];
  124. RCTAssert(_cachedRootView, @"We were unable to find a root view for the touch");
  125. CGPoint rootViewLocation = [nativeTouch.window convertPoint:windowLocation toView:_cachedRootView];
  126. UIView *touchView = _touchViews[touchIndex];
  127. CGPoint touchViewLocation = [nativeTouch.window convertPoint:windowLocation toView:touchView];
  128. NSMutableDictionary *reactTouch = _reactTouches[touchIndex];
  129. reactTouch[@"pageX"] = @(RCTSanitizeNaNValue(rootViewLocation.x, @"touchEvent.pageX"));
  130. reactTouch[@"pageY"] = @(RCTSanitizeNaNValue(rootViewLocation.y, @"touchEvent.pageY"));
  131. reactTouch[@"locationX"] = @(RCTSanitizeNaNValue(touchViewLocation.x, @"touchEvent.locationX"));
  132. reactTouch[@"locationY"] = @(RCTSanitizeNaNValue(touchViewLocation.y, @"touchEvent.locationY"));
  133. reactTouch[@"timestamp"] = @(nativeTouch.timestamp * 1000); // in ms, for JS
  134. // TODO: force for a 'normal' touch is usually 1.0;
  135. // should we expose a `normalTouchForce` constant somewhere (which would
  136. // have a value of `1.0 / nativeTouch.maximumPossibleForce`)?
  137. if (RCTForceTouchAvailable()) {
  138. reactTouch[@"force"] = @(RCTZeroIfNaN(nativeTouch.force / nativeTouch.maximumPossibleForce));
  139. }
  140. }
  141. /**
  142. * Constructs information about touch events to send across the serialized
  143. * boundary. This data should be compliant with W3C `Touch` objects. This data
  144. * alone isn't sufficient to construct W3C `Event` objects. To construct that,
  145. * there must be a simple receiver on the other side of the bridge that
  146. * organizes the touch objects into `Event`s.
  147. *
  148. * We send the data as an array of `Touch`es, the type of action
  149. * (start/end/move/cancel) and the indices that represent "changed" `Touch`es
  150. * from that array.
  151. */
  152. - (void)_updateAndDispatchTouches:(NSSet<UITouch *> *)touches
  153. eventName:(NSString *)eventName
  154. {
  155. // Update touches
  156. NSMutableArray<NSNumber *> *changedIndexes = [NSMutableArray new];
  157. for (UITouch *touch in touches) {
  158. NSInteger index = [_nativeTouches indexOfObject:touch];
  159. if (index == NSNotFound) {
  160. continue;
  161. }
  162. [self _updateReactTouchAtIndex:index];
  163. [changedIndexes addObject:@(index)];
  164. }
  165. if (changedIndexes.count == 0) {
  166. return;
  167. }
  168. // Deep copy the touches because they will be accessed from another thread
  169. // TODO: would it be safer to do this in the bridge or executor, rather than trusting caller?
  170. NSMutableArray<NSDictionary *> *reactTouches =
  171. [[NSMutableArray alloc] initWithCapacity:_reactTouches.count];
  172. for (NSDictionary *touch in _reactTouches) {
  173. [reactTouches addObject:[touch copy]];
  174. }
  175. BOOL canBeCoalesced = [eventName isEqualToString:@"touchMove"];
  176. // We increment `_coalescingKey` twice here just for sure that
  177. // this `_coalescingKey` will not be reused by another (preceding or following) event
  178. // (yes, even if coalescing only happens (and makes sense) on events of the same type).
  179. if (!canBeCoalesced) {
  180. _coalescingKey++;
  181. }
  182. RCTTouchEvent *event = [[RCTTouchEvent alloc] initWithEventName:eventName
  183. reactTag:self.view.reactTag
  184. reactTouches:reactTouches
  185. changedIndexes:changedIndexes
  186. coalescingKey:_coalescingKey];
  187. if (!canBeCoalesced) {
  188. _coalescingKey++;
  189. }
  190. [_eventDispatcher sendEvent:event];
  191. }
  192. /***
  193. * To ensure compatibilty when using UIManager.measure and RCTTouchHandler, we have to adopt
  194. * UIManager.measure's behavior in finding a "root view".
  195. * Usually RCTTouchHandler is already attached to a root view but in some cases (e.g. Modal),
  196. * we are instead attached to some RCTView subtree. This is also the case when embedding some RN
  197. * views inside a seperate ViewController not controlled by RN.
  198. * This logic will either find the nearest rootView, or go all the way to the UIWindow.
  199. * While this is not optimal, it is exactly what UIManager.measure does, and what Touchable.js
  200. * relies on.
  201. * We cache it here so that we don't have to repeat it for every touch in the gesture.
  202. */
  203. - (void)_cacheRootView
  204. {
  205. UIView *rootView = self.view;
  206. while (rootView.superview && ![rootView isReactRootView] && ![rootView isKindOfClass:[RCTSurfaceView class]]) {
  207. rootView = rootView.superview;
  208. }
  209. _cachedRootView = rootView;
  210. }
  211. #pragma mark - Gesture Recognizer Delegate Callbacks
  212. static BOOL RCTAllTouchesAreCancelledOrEnded(NSSet<UITouch *> *touches)
  213. {
  214. for (UITouch *touch in touches) {
  215. if (touch.phase == UITouchPhaseBegan ||
  216. touch.phase == UITouchPhaseMoved ||
  217. touch.phase == UITouchPhaseStationary) {
  218. return NO;
  219. }
  220. }
  221. return YES;
  222. }
  223. static BOOL RCTAnyTouchesChanged(NSSet<UITouch *> *touches)
  224. {
  225. for (UITouch *touch in touches) {
  226. if (touch.phase == UITouchPhaseBegan ||
  227. touch.phase == UITouchPhaseMoved) {
  228. return YES;
  229. }
  230. }
  231. return NO;
  232. }
  233. #pragma mark - `UIResponder`-ish touch-delivery methods
  234. - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
  235. {
  236. [super touchesBegan:touches withEvent:event];
  237. [self _cacheRootView];
  238. // "start" has to record new touches *before* extracting the event.
  239. // "end"/"cancel" needs to remove the touch *after* extracting the event.
  240. [self _recordNewTouches:touches];
  241. [self _updateAndDispatchTouches:touches eventName:@"touchStart"];
  242. if (self.state == UIGestureRecognizerStatePossible) {
  243. self.state = UIGestureRecognizerStateBegan;
  244. } else if (self.state == UIGestureRecognizerStateBegan) {
  245. self.state = UIGestureRecognizerStateChanged;
  246. }
  247. }
  248. - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
  249. {
  250. [super touchesMoved:touches withEvent:event];
  251. [self _updateAndDispatchTouches:touches eventName:@"touchMove"];
  252. self.state = UIGestureRecognizerStateChanged;
  253. }
  254. - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
  255. {
  256. [super touchesEnded:touches withEvent:event];
  257. [self _updateAndDispatchTouches:touches eventName:@"touchEnd"];
  258. if (RCTAllTouchesAreCancelledOrEnded(event.allTouches)) {
  259. self.state = UIGestureRecognizerStateEnded;
  260. } else if (RCTAnyTouchesChanged(event.allTouches)) {
  261. self.state = UIGestureRecognizerStateChanged;
  262. }
  263. [self _recordRemovedTouches:touches];
  264. }
  265. - (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
  266. {
  267. [super touchesCancelled:touches withEvent:event];
  268. [self _updateAndDispatchTouches:touches eventName:@"touchCancel"];
  269. if (RCTAllTouchesAreCancelledOrEnded(event.allTouches)) {
  270. self.state = UIGestureRecognizerStateCancelled;
  271. } else if (RCTAnyTouchesChanged(event.allTouches)) {
  272. self.state = UIGestureRecognizerStateChanged;
  273. }
  274. [self _recordRemovedTouches:touches];
  275. }
  276. - (BOOL)canPreventGestureRecognizer:(__unused UIGestureRecognizer *)preventedGestureRecognizer
  277. {
  278. return NO;
  279. }
  280. - (BOOL)canBePreventedByGestureRecognizer:(UIGestureRecognizer *)preventingGestureRecognizer
  281. {
  282. // We fail in favour of other external gesture recognizers.
  283. // iOS will ask `delegate`'s opinion about this gesture recognizer little bit later.
  284. return ![preventingGestureRecognizer.view isDescendantOfView:self.view];
  285. }
  286. - (void)reset
  287. {
  288. if (_nativeTouches.count != 0) {
  289. [self _updateAndDispatchTouches:_nativeTouches.set eventName:@"touchCancel"];
  290. [_nativeTouches removeAllObjects];
  291. [_reactTouches removeAllObjects];
  292. [_touchViews removeAllObjects];
  293. _cachedRootView = nil;
  294. }
  295. }
  296. #pragma mark - Other
  297. - (void)cancel
  298. {
  299. self.enabled = NO;
  300. self.enabled = YES;
  301. }
  302. #pragma mark - UIGestureRecognizerDelegate
  303. - (BOOL)gestureRecognizer:(__unused UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
  304. {
  305. // Same condition for `failure of` as for `be prevented by`.
  306. return [self canBePreventedByGestureRecognizer:otherGestureRecognizer];
  307. }
  308. @end