Expose GestureBinding.handlePointerEvent, replacing dispatchEvent as the preferred way to dispatch events (#64846)

This commit is contained in:
Tong Mu
2020-09-15 22:17:06 -07:00
committed by GitHub
parent ea039ed3f9
commit a48e14308e
16 changed files with 219 additions and 229 deletions

View File

@@ -176,9 +176,9 @@ const Duration _defaultSamplingOffset = Duration(milliseconds: -38);
///
/// A pointer that is [PointerEvent.down] may send further events, such as
/// [PointerMoveEvent], [PointerUpEvent], or [PointerCancelEvent]. These are
/// sent to the same [HitTestTarget] nodes as were found when the down event was
/// received (even if they have since been disposed; it is the responsibility of
/// those objects to be aware of that possibility).
/// sent to the same [HitTestTarget] nodes as were found when the
/// [PointerDownEvent] was received (even if they have since been disposed; it is
/// the responsibility of those objects to be aware of that possibility).
///
/// Then, the events are routed to any still-registered entrants in the
/// [PointerRouter]'s table for that pointer.
@@ -237,7 +237,7 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H
_resampler.stop();
while (_pendingPointerEvents.isNotEmpty)
_handlePointerEvent(_pendingPointerEvents.removeFirst());
handlePointerEvent(_pendingPointerEvents.removeFirst());
}
/// A router that routes all pointer events received from the engine.
@@ -247,8 +247,8 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H
/// pointer events.
final GestureArenaManager gestureArena = GestureArenaManager();
/// The resolver used for determining which widget handles a pointer
/// signal event.
/// The resolver used for determining which widget handles a
/// [PointerSignalEvent].
final PointerSignalResolver pointerSignalResolver = PointerSignalResolver();
/// State for all pointers which are currently down.
@@ -257,7 +257,17 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H
/// hit-testing on every frame.
final Map<int, HitTestResult> _hitTests = <int, HitTestResult>{};
void _handlePointerEvent(PointerEvent event) {
/// Dispatch an event to the targets found by a hit test on its position.
///
/// This method sends the given event to [dispatchEvent] based on event types:
///
/// * [PointerDownEvent]s and [PointerSignalEvent]s are dispatched to the
/// result of a new [hitTest].
/// * [PointerUpEvent]s and [PointerMoveEvent]s are dispatched to the result of hit test of the
/// preceding [PointerDownEvent]s.
/// * [PointerHoverEvent]s, [PointerAddedEvent]s, and [PointerRemovedEvent]s
/// are dispatched without a hit test result.
void handlePointerEvent(PointerEvent event) {
assert(!locked);
HitTestResult? hitTestResult;
if (event is PointerDownEvent || event is PointerSignalEvent) {
@@ -276,7 +286,7 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H
hitTestResult = _hitTests.remove(event.pointer);
} else if (event.down) {
// Because events that occur with the pointer down (like
// PointerMoveEvents) should be dispatched to the same place that their
// [PointerMoveEvent]s) should be dispatched to the same place that their
// initial PointerDownEvent was, we want to re-use the path we found when
// the pointer went down, rather than do hit detection each time we get
// such an event.
@@ -302,18 +312,20 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H
result.add(HitTestEntry(this));
}
/// Dispatch an event to a hit test result's path.
/// Dispatch an event to [pointerRouter] and the path of a hit test result.
///
/// This sends the given event to every [HitTestTarget] in the entries of the
/// given [HitTestResult], and catches exceptions that any of the handlers
/// might throw. The [hitTestResult] argument may only be null for
/// [PointerHoverEvent], [PointerAddedEvent], or [PointerRemovedEvent] events.
/// The `event` is routed to [pointerRouter]. If the `hitTestResult` is not
/// null, the event is also sent to every [HitTestTarget] in the entries of the
/// given [HitTestResult]. Any exceptions from the handlers are caught.
///
/// The `hitTestResult` argument may only be null for [PointerHoverEvent]s,
/// [PointerAddedEvent]s, or [PointerRemovedEvent]s.
@override // from HitTestDispatcher
void dispatchEvent(PointerEvent event, HitTestResult? hitTestResult) {
assert(!locked);
// No hit test information implies that this is a pointer hover or
// add/remove event. These events are specially routed here; other events
// will be routed through the `handleEvent` below.
// No hit test information implies that this is a [PointerHoverEvent],
// [PointerAddedEvent], or [PointerRemovedEvent]. These events are specially
// routed here; other events will be routed through the `handleEvent` below.
if (hitTestResult == null) {
assert(event is PointerHoverEvent || event is PointerAddedEvent || event is PointerRemovedEvent);
try {
@@ -365,6 +377,16 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H
}
}
/// Reset states of [GestureBinding].
///
/// This clears the hit test records.
///
/// This is typically called between tests.
@protected
void resetGestureBinding() {
_hitTests.clear();
}
void _handleSampleTimeChanged() {
if (!locked) {
_flushPointerEventQueue();
@@ -374,7 +396,7 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H
// Resampler used to filter incoming pointer events when resampling
// is enabled.
late final _Resampler _resampler = _Resampler(
_handlePointerEvent,
handlePointerEvent,
_handleSampleTimeChanged,
);
@@ -429,7 +451,8 @@ class FlutterErrorDetailsForPointerEventDispatcher extends FlutterErrorDetails {
/// The hit test result entry for the object whose handleEvent method threw
/// the exception. May be null if no hit test entry is associated with the
/// event (e.g. hover and pointer add/remove events).
/// event (e.g. [PointerHoverEvent]s, [PointerAddedEvent]s, and
/// [PointerRemovedEvent]s).
///
/// The target object itself is given by the [HitTestEntry.target] property of
/// the hitTestEntry object.

View File

@@ -6,6 +6,7 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -1471,6 +1472,25 @@ void main() {
expect(find.text('first', skipOffstage: false), findsOneWidget);
expect(find.text('second'), findsOneWidget);
});
testWidgets('Popping routes should cancel down events', (WidgetTester tester) async {
await tester.pumpWidget(_TestPostRouteCancel());
final TestGesture gesture = await tester.createGesture();
await gesture.down(tester.getCenter(find.text('PointerCancelEvents: 0')));
await gesture.up();
await tester.pumpAndSettle();
expect(find.byType(CupertinoButton), findsNothing);
expect(find.text('Hold'), findsOneWidget);
await gesture.down(tester.getCenter(find.text('Hold')));
await tester.pump(const Duration(seconds: 2));
await tester.pumpAndSettle();
expect(find.text('Hold'), findsNothing);
expect(find.byType(CupertinoButton), findsOneWidget);
expect(find.text('PointerCancelEvents: 1'), findsOneWidget);
});
}
class MockNavigatorObserver extends NavigatorObserver {
@@ -1571,3 +1591,75 @@ Widget buildNavigator({
),
);
}
// A test target for post-route cancel events.
//
// It contains 2 routes:
//
// * The initial route, 'home', displays a button showing 'PointerCancelEvents: #',
// where # is the number of cancel events received. Tapping the button pushes
// route 'sub'.
// * The 'sub' route, displays a text showing 'Hold'. Holding the button (a down
// event) will pop this route after 1 second.
//
// Holding the 'Hold' button at the moment of popping will force the navigator to
// cancel the down event, increasing the Home counter by 1.
class _TestPostRouteCancel extends StatefulWidget {
@override
State<StatefulWidget> createState() => _TestPostRouteCancelState();
}
class _TestPostRouteCancelState extends State<_TestPostRouteCancel> {
int counter = 0;
Widget _buildHome(BuildContext context) {
return Center(
child: CupertinoButton(
child: Text('PointerCancelEvents: $counter'),
onPressed: () => Navigator.pushNamed<void>(context, 'sub'),
),
);
}
Widget _buildSub(BuildContext context) {
return Listener(
onPointerDown: (_) {
Future<void>.delayed(const Duration(seconds: 1)).then((_) {
Navigator.pop(context);
});
},
onPointerCancel: (_) {
setState(() {
counter += 1;
});
},
child: const Center(
child: Text('Hold', style: TextStyle(color: Colors.blue)),
),
);
}
@override
Widget build(BuildContext context) {
return CupertinoApp(
initialRoute: 'home',
onGenerateRoute: (RouteSettings settings) {
return CupertinoPageRoute<void>(
settings: settings,
builder: (BuildContext context) {
switch (settings.name) {
case 'home':
return _buildHome(context);
case 'sub':
return _buildSub(context);
default:
throw UnimplementedError();
}
},
);
},
);
}
}

View File

@@ -16,22 +16,8 @@ import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class PointerDataAutomatedTestWidgetsFlutterBinding extends AutomatedTestWidgetsFlutterBinding {
// PointerData injection would usually considerred device input and therefore
// blocked by [AutomatedTestWidgetsFlutterBinding]. Override this behavior
// to help events go into widget tree.
@override
void dispatchEvent(
PointerEvent event,
HitTestResult hitTestResult, {
TestBindingEventSource source = TestBindingEventSource.device,
}) {
super.dispatchEvent(event, hitTestResult, source: TestBindingEventSource.test);
}
}
void main() {
final TestWidgetsFlutterBinding binding = PointerDataAutomatedTestWidgetsFlutterBinding();
final TestWidgetsFlutterBinding binding = AutomatedTestWidgetsFlutterBinding();
testWidgets('PointerEvent resampling on a widget', (WidgetTester tester) async {
assert(WidgetsBinding.instance == binding);
Duration currentTestFrameTime() => Duration(milliseconds: binding.clock.now().millisecondsSinceEpoch);

View File

@@ -753,6 +753,7 @@ void main() {
await hoverGesture.addPointer();
await hoverGesture.moveTo(center);
await tester.pumpAndSettle();
await hoverGesture.moveTo(const Offset(0, 0));
inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_RenderInkFeatures';
@@ -761,7 +762,6 @@ void main() {
inkFeatures,
paints..rect(color: theme.colorScheme.onSurface.withOpacity(0.04)),
);
await hoverGesture.removePointer();
// focusColor
focusNode.requestFocus();
@@ -770,6 +770,8 @@ void main() {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(inkFeatures, paints..rect(color: theme.colorScheme.onSurface.withOpacity(0.12)));
await hoverGesture.removePointer();
});
testWidgets('Default InkWell colors - selected', (WidgetTester tester) async {
@@ -825,7 +827,7 @@ void main() {
inkFeatures,
paints..rect(color: theme.colorScheme.primary.withOpacity(0.04)),
);
await hoverGesture.removePointer();
await hoverGesture.moveTo(const Offset(0, 0));
// focusColor
focusNode.requestFocus();
@@ -834,6 +836,8 @@ void main() {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(inkFeatures, paints..rect(color: theme.colorScheme.primary.withOpacity(0.12)));
await hoverGesture.removePointer();
});
testWidgets('Custom InkWell colors', (WidgetTester tester) async {
@@ -894,7 +898,7 @@ void main() {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(inkFeatures, paints..rect(color: hoverColor));
await hoverGesture.removePointer();
await hoverGesture.moveTo(const Offset(0, 0));
// focusColor
focusNode.requestFocus();
@@ -903,6 +907,8 @@ void main() {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(inkFeatures, paints..rect(color: focusColor));
await hoverGesture.removePointer();
});
testWidgets(

View File

@@ -429,7 +429,7 @@ void main() {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(inkFeatures, paints..rect(color: hoverColor));
await hoverGesture.removePointer();
await hoverGesture.moveTo(const Offset(0, 0));
// focusColor
focusNode.requestFocus();
@@ -438,6 +438,8 @@ void main() {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(inkFeatures, paints..rect(color: focusColor));
await hoverGesture.removePointer();
});

View File

@@ -11,6 +11,5 @@ Future<void> scrollAt(Offset position, WidgetTester tester, [Offset offset = con
final TestPointer testPointer = TestPointer(1, PointerDeviceKind.mouse);
// Create a hover event so that |testPointer| has a location when generating the scroll.
testPointer.hover(position);
final HitTestResult result = tester.hitTestOnBinding(position);
return tester.sendEventToBinding(testPointer.scroll(offset), result);
return tester.sendEventToBinding(testPointer.scroll(offset));
}

View File

@@ -290,11 +290,10 @@ void main() {
final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse);
// Create a hover event so that |testPointer| has a location when generating the scroll.
testPointer.hover(scrollEventLocation);
final HitTestResult result = tester.hitTestOnBinding(scrollEventLocation);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)), result);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)));
expect(getScrollOffset(tester), 20.0);
// Pointer signals should not cause overscroll.
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -30.0)), result);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -30.0)));
expect(getScrollOffset(tester), 0.0);
});
@@ -308,11 +307,10 @@ void main() {
final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse);
// Create a hover event so that |testPointer| has a location when generating the scroll.
testPointer.hover(scrollEventLocation);
final HitTestResult result = tester.hitTestOnBinding(scrollEventLocation);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)), result);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)));
expect(getScrollOffset(tester, last: true), 20.0);
// Pointer signals should not cause overscroll.
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -30.0)), result);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -30.0)));
expect(getScrollOffset(tester, last: true), 0.0);
});
@@ -322,8 +320,7 @@ void main() {
final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse);
// Create a hover event so that |testPointer| has a location when generating the scroll.
testPointer.hover(scrollEventLocation);
final HitTestResult result = tester.hitTestOnBinding(scrollEventLocation);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)), result);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0)));
expect(getScrollOffset(tester), 0.0);
});
@@ -334,8 +331,7 @@ void main() {
final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse);
// Create a hover event so that |testPointer| has a location when generating the scroll.
testPointer.hover(scrollEventLocation);
final HitTestResult result = tester.hitTestOnBinding(scrollEventLocation);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -20.0)), result);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -20.0)));
expect(getScrollOffset(tester), 20.0);
});