Skip to content

Fix onBegin and onTouchesDown events ordering on Android #2279

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ open class GestureHandler<ConcreteGestureHandlerT : GestureHandler<ConcreteGestu
var trackedPointersCount = 0
private set
private val trackedPointers: Array<PointerData?> = Array(MAX_POINTERS_COUNT) { null }
private var deferredPointerEventSender: (() -> Unit)? = null
var needsPointerData = false


Expand Down Expand Up @@ -447,14 +448,36 @@ open class GestureHandler<ConcreteGestureHandlerT : GestureHandler<ConcreteGestu
}

fun updatePointerData(event: MotionEvent) {
if (event.actionMasked == MotionEvent.ACTION_DOWN || event.actionMasked == MotionEvent.ACTION_POINTER_DOWN) {
dispatchTouchDownEvent(event)
dispatchTouchMoveEvent(event)
} else if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_POINTER_UP) {
dispatchTouchMoveEvent(event)
dispatchTouchUpEvent(event)
} else if (event.actionMasked == MotionEvent.ACTION_MOVE) {
dispatchTouchMoveEvent(event)
// Touch events are sent before the handler itself has a chance to process them. This means that
// the first `onTouchesDown` event is sent before a gesture begins, activation in callback for
// this event causes problems because the handler doesn't have a chance to initialize itself
// with starting values of pointer, resulting in wrong positioning or trying to send NaN values.
// The simplest (I think) solution to that, while preserving the correct ordering of events on
// the JS side, is to defer sending the first `onTouchesDown` event until the gesture is
// initialized and sends `BEGIN` event. When that happens we can also send deferred touch event
// preserving the correct flow.

val eventSender = {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
dispatchTouchDownEvent(event)
dispatchTouchMoveEvent(event)
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> {
dispatchTouchMoveEvent(event)
dispatchTouchUpEvent(event)
}
MotionEvent.ACTION_MOVE -> {
dispatchTouchMoveEvent(event)
}
}
}

if (this.state != STATE_UNDETERMINED) {
eventSender()
} else {
// this is the first event, we want to defer it
this.deferredPointerEventSender = eventSender
}
}

Expand Down Expand Up @@ -648,6 +671,19 @@ open class GestureHandler<ConcreteGestureHandlerT : GestureHandler<ConcreteGestu
}

fun begin() {
// double state check as it might change because of the touch event
if (state == STATE_UNDETERMINED && this.deferredPointerEventSender != null) {
// if there was a deferred touch event, we want to send it before sending `BEGAN` event, to
// preserve the correct event flow.

// set `deferredPointerEventSender` to null before invoking the sender, as the current state
// is still UNDETERMINED, and there is a possibility that `begin` will be called on the JS
// which would result in an infinite loop
val sender = this.deferredPointerEventSender
this.deferredPointerEventSender = null
sender!!()
}

if (state == STATE_UNDETERMINED) {
moveToState(STATE_BEGAN)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,21 +253,10 @@ class GestureHandlerOrchestrator(

val action = sourceEvent.actionMasked
val event = transformEventToViewCoords(handler.view, MotionEvent.obtain(sourceEvent))

// Touch events are sent before the handler itself has a chance to process them,
// mainly because `onTouchesUp` shoul be send befor gesture finishes. This means that
// the first `onTouchesDown` event is sent before a gesture begins, activation in
// callback for this event causes problems because the handler doesn't have a chance
// to initialize itself with starting values of pointer (in pan this causes translation
// to be equal to the coordinates of the pointer). The simplest solution is to send
// the first `onTouchesDown` event after the handler processes it and changes state
// to `BEGAN`.
if (handler.needsPointerData && handler.state != 0) {
handler.updatePointerData(event)
}

handler.updatePointerData(event)

if (!handler.isAwaiting || action != MotionEvent.ACTION_MOVE) {
val isFirstEvent = handler.state == 0
handler.handle(event, sourceEvent)
if (handler.isActive) {
// After handler is done waiting for other one to fail its progress should be
Expand All @@ -284,10 +273,6 @@ class GestureHandlerOrchestrator(
handler.dispatchHandlerUpdate(event)
}

if (handler.needsPointerData && isFirstEvent) {
handler.updatePointerData(event)
}

// if event was of type UP or POINTER_UP we request handler to stop tracking now that
// the event has been dispatched
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,12 @@ class RNGestureHandlerModule(reactContext: ReactApplicationContext?) :
override fun setGestureHandlerState(handlerTag: Int, newState: Int) {
registry.getHandler(handlerTag)?.let { handler ->
when (newState) {
GestureHandler.STATE_ACTIVE -> handler.activate(force = true)
GestureHandler.STATE_ACTIVE -> {
// also call begin to force correct state flow in case the `activate` is called in the
// UNDETERMINED state
handler.begin()
handler.activate(force = true)
}
GestureHandler.STATE_BEGAN -> handler.begin()
GestureHandler.STATE_END -> handler.end()
GestureHandler.STATE_FAILED -> handler.fail()
Expand Down
76 changes: 39 additions & 37 deletions ios/Handlers/RNFlingHandler.m
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

@interface RNBetterSwipeGestureRecognizer : UISwipeGestureRecognizer

- (id)initWithGestureHandler:(RNGestureHandler*)gestureHandler;
- (id)initWithGestureHandler:(RNGestureHandler *)gestureHandler;

@end

@implementation RNBetterSwipeGestureRecognizer {
__weak RNGestureHandler* _gestureHandler;
__weak RNGestureHandler *_gestureHandler;
CGPoint _lastPoint; // location of the most recently updated touch, relative to the view
bool _hasBegan; // whether the `BEGAN` event has been sent
}
Expand All @@ -27,6 +27,7 @@ - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
_lastPoint = [[[touches allObjects] objectAtIndex:0] locationInView:_gestureHandler.recognizer.view];
[_gestureHandler reset];
[super touchesBegan:touches withEvent:event];
[_gestureHandler.pointerTracker touchesBegan:touches withEvent:event];

// self.numberOfTouches doesn't work for this because in case than one finger is required,
// when holding one finger on the screen and tapping with the second one, numberOfTouches is equal
Expand All @@ -35,8 +36,6 @@ - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
[self triggerAction];
_hasBegan = YES;
}

[_gestureHandler.pointerTracker touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
Expand Down Expand Up @@ -73,7 +72,8 @@ - (void)reset
[super reset];
}

- (CGPoint)getLastLocation {
- (CGPoint)getLastLocation
{
// I think keeping the location of only one touch is enough since it would be used to determine the direction
// of the movement, and if it's wrong the recognizer fails anyway.
// In case the location of all touches is required, touch events are the way to go
Expand Down Expand Up @@ -103,48 +103,50 @@ - (void)resetConfig

- (void)configure:(NSDictionary *)config
{
[super configure:config];
UISwipeGestureRecognizer *recognizer = (UISwipeGestureRecognizer *)_recognizer;

id prop = config[@"direction"];
if (prop != nil) {
recognizer.direction = [RCTConvert NSInteger:prop];
}
[super configure:config];
UISwipeGestureRecognizer *recognizer = (UISwipeGestureRecognizer *)_recognizer;

id prop = config[@"direction"];
if (prop != nil) {
recognizer.direction = [RCTConvert NSInteger:prop];
}

#if !TARGET_OS_TV
prop = config[@"numberOfPointers"];
if (prop != nil) {
recognizer.numberOfTouchesRequired = [RCTConvert NSInteger:prop];
}
prop = config[@"numberOfPointers"];
if (prop != nil) {
recognizer.numberOfTouchesRequired = [RCTConvert NSInteger:prop];
}
#endif
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
RNGestureHandlerState savedState = _lastState;
BOOL shouldBegin = [super gestureRecognizerShouldBegin:gestureRecognizer];
_lastState = savedState;
return shouldBegin;
RNGestureHandlerState savedState = _lastState;
BOOL shouldBegin = [super gestureRecognizerShouldBegin:gestureRecognizer];
_lastState = savedState;

return shouldBegin;
}

- (RNGestureHandlerEventExtraData *)eventExtraData:(id)_recognizer
{
// For some weird reason [recognizer locationInView:recognizer.view.window] returns (0, 0).
// To calculate the correct absolute position, first calculate the absolute position of the
// view inside the root view controller (https://stackoverflow.com/a/7448573) and then
// add the relative touch position to it.

RNBetterSwipeGestureRecognizer *recognizer = (RNBetterSwipeGestureRecognizer *)_recognizer;

CGPoint viewAbsolutePosition = [recognizer.view convertPoint:recognizer.view.bounds.origin toView:[UIApplication sharedApplication].keyWindow.rootViewController.view];
CGPoint locationInView = [recognizer getLastLocation];

return [RNGestureHandlerEventExtraData
forPosition:locationInView
withAbsolutePosition:CGPointMake(viewAbsolutePosition.x + locationInView.x, viewAbsolutePosition.y + locationInView.y)
withNumberOfTouches:recognizer.numberOfTouches];
// For some weird reason [recognizer locationInView:recognizer.view.window] returns (0, 0).
// To calculate the correct absolute position, first calculate the absolute position of the
// view inside the root view controller (https://stackoverflow.com/a/7448573) and then
// add the relative touch position to it.

RNBetterSwipeGestureRecognizer *recognizer = (RNBetterSwipeGestureRecognizer *)_recognizer;

CGPoint viewAbsolutePosition =
[recognizer.view convertPoint:recognizer.view.bounds.origin
toView:[UIApplication sharedApplication].keyWindow.rootViewController.view];
CGPoint locationInView = [recognizer getLastLocation];

return [RNGestureHandlerEventExtraData
forPosition:locationInView
withAbsolutePosition:CGPointMake(
viewAbsolutePosition.x + locationInView.x, viewAbsolutePosition.y + locationInView.y)
withNumberOfTouches:recognizer.numberOfTouches];
}

@end

Loading