-
Notifications
You must be signed in to change notification settings - Fork 30.4k
Expand file tree
/
Copy pathcontroller.dart
More file actions
2549 lines (2401 loc) · 97 KB
/
controller.dart
File metadata and controls
2549 lines (2401 loc) · 97 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
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 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// @docImport 'dart:io';
///
/// @docImport 'package:flutter/scheduler.dart';
/// @docImport 'package:flutter_driver/flutter_driver.dart';
///
/// @docImport 'binding.dart';
/// @docImport 'finders.dart';
/// @docImport 'matchers.dart';
/// @docImport 'widget_tester.dart';
library;
import 'dart:ui' as ui;
import 'package:clock/clock.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'event_simulation.dart';
import 'finders.dart' as finders;
import 'test_async_utils.dart';
import 'test_pointer.dart';
import 'tree_traversal.dart';
import 'window.dart';
/// The default drag touch slop used to break up a large drag into multiple
/// smaller moves.
///
/// This value must be greater than [kTouchSlop].
const double kDragSlopDefault = 20.0;
// Finds the end index (exclusive) of the span at `startIndex`, or `endIndex` if
// there are no other spans between `startIndex` and `endIndex`.
// The InlineSpan protocol doesn't expose the length of the span so we'll
// have to iterate through the whole range.
(InlineSpan, int)? _findEndOfSpan(InlineSpan rootSpan, int startIndex, int endIndex) {
assert(endIndex > startIndex);
final InlineSpan? subspan = rootSpan.getSpanForPosition(TextPosition(offset: startIndex));
if (subspan == null) {
return null;
}
int i = startIndex + 1;
while (i < endIndex && rootSpan.getSpanForPosition(TextPosition(offset: i)) == subspan) {
i += 1;
}
return (subspan, i);
}
// Examples can assume:
// typedef MyWidget = Placeholder;
/// Class that programmatically interacts with the [Semantics] tree.
///
/// Allows for testing of the [Semantics] tree, which is used by assistive
/// technology, search engines, and other analysis software to determine the
/// meaning of an application.
///
/// Should be accessed through [WidgetController.semantics]. If no custom
/// implementation is provided, a default [SemanticsController] will be created.
class SemanticsController {
/// Creates a [SemanticsController] that uses the given binding. Will be
/// automatically created as part of instantiating a [WidgetController], but
/// a custom implementation can be passed via the [WidgetController] constructor.
SemanticsController._(this._controller);
static final int _scrollingActions =
SemanticsAction.scrollUp.index |
SemanticsAction.scrollDown.index |
SemanticsAction.scrollLeft.index |
SemanticsAction.scrollRight.index |
SemanticsAction.scrollToOffset.index;
final WidgetController _controller;
/// Attempts to find the [SemanticsNode] of first result from `finder`.
///
/// If the object identified by the finder doesn't own its semantic node,
/// this will return the semantics data of the first ancestor with semantics.
/// The ancestor's semantic data will include the child's as well as
/// other nodes that have been merged together.
///
/// If the [SemanticsNode] of the object identified by the finder is
/// force-merged into an ancestor (e.g. via the [MergeSemantics] widget)
/// the node into which it is merged is returned. That node will include
/// all the semantics information of the nodes merged into it.
///
/// Will throw a [StateError] if the finder returns more than one element or
/// if no semantics are found or are not enabled.
SemanticsNode find(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
final Iterable<Element> candidates = finder.evaluate();
if (candidates.isEmpty) {
throw StateError('Finder returned no matching elements.');
}
if (candidates.length > 1) {
throw StateError('Finder returned more than one element.');
}
final Element element = candidates.single;
RenderObject? renderObject = element.findRenderObject();
SemanticsNode? result = renderObject?.debugSemantics;
while (renderObject != null && (result == null || result.isMergedIntoParent)) {
renderObject = renderObject.parent;
result = renderObject?.debugSemantics;
}
if (result == null) {
throw StateError('No Semantics data found.');
}
return result;
}
/// Simulates a traversal of the currently visible semantics tree as if by
/// assistive technologies.
///
/// Starts at the node for `startNode`. If `startNode` is not provided, then
/// the traversal begins with the first accessible node in the tree. If
/// `startNode` finds zero elements or more than one element, a [StateError]
/// will be thrown.
///
/// Ends at the node for `endNode`, inclusive. If `endNode` is not provided,
/// then the traversal ends with the last accessible node in the currently
/// available tree. If `endNode` finds zero elements or more than one element,
/// a [StateError] will be thrown.
///
/// If provided, the nodes for `endNode` and `startNode` must be part of the
/// same semantics tree, i.e. they must be part of the same view.
///
/// If neither `startNode` or `endNode` is provided, `view` can be provided to
/// specify the semantics tree to traverse. If `view` is left unspecified,
/// [WidgetTester.view] is traversed by default.
///
/// Since the order is simulated, edge cases that differ between platforms
/// (such as how the last visible item in a scrollable list is handled) may be
/// inconsistent with platform behavior, but are expected to be sufficient for
/// testing order, availability to assistive technologies, and interactions.
///
/// ## Sample Code
///
/// ```dart
/// testWidgets('MyWidget', (WidgetTester tester) async {
/// await tester.pumpWidget(const MyWidget());
///
/// expect(
/// tester.semantics.simulatedAccessibilityTraversal(),
/// containsAllInOrder(<Matcher>[
/// isSemantics(label: 'My Widget'),
/// isSemantics(label: 'is awesome!', isChecked: true),
/// ]),
/// );
/// });
/// ```
///
/// See also:
///
/// * [isSemantics] and [matchesSemantics], which can be used to match
/// against a single node in the traversal.
/// * [containsAllInOrder], which can be given an [Iterable<Matcher>] to fuzzy
/// match the order allowing extra nodes before after and between matching
/// parts of the traversal.
/// * [orderedEquals], which can be given an [Iterable<Matcher>] to exactly
/// match the order of the traversal.
Iterable<SemanticsNode> simulatedAccessibilityTraversal({
@Deprecated(
'Use startNode instead. '
'This method was originally created before semantics finders were available. '
'Semantics finders avoid edge cases where some nodes are not discoverable by widget finders and should be preferred for semantics testing. '
'This feature was deprecated after v3.15.0-15.2.pre.',
)
finders.FinderBase<Element>? start,
@Deprecated(
'Use endNode instead. '
'This method was originally created before semantics finders were available. '
'Semantics finders avoid edge cases where some nodes are not discoverable by widget finders and should be preferred for semantics testing. '
'This feature was deprecated after v3.15.0-15.2.pre.',
)
finders.FinderBase<Element>? end,
finders.FinderBase<SemanticsNode>? startNode,
finders.FinderBase<SemanticsNode>? endNode,
FlutterView? view,
}) {
TestAsyncUtils.guardSync();
assert(
start == null || startNode == null,
'Cannot provide both start and startNode. Prefer startNode as start is deprecated.',
);
assert(
end == null || endNode == null,
'Cannot provide both end and endNode. Prefer endNode as end is deprecated.',
);
FlutterView? startView;
if (start != null) {
startView = _controller.viewOf(start);
if (view != null && startView != view) {
throw StateError(
'The start node is not part of the provided view.\n'
'Finder: ${start.toString(describeSelf: true)}\n'
'View of start node: $startView\n'
'Specified view: $view',
);
}
} else if (startNode != null) {
final SemanticsOwner owner = startNode.evaluate().single.owner!;
final RenderView renderView = _controller.binding.renderViews.firstWhere(
(RenderView render) => render.owner!.semanticsOwner == owner,
);
startView = renderView.flutterView;
if (view != null && startView != view) {
throw StateError(
'The start node is not part of the provided view.\n'
'Finder: ${startNode.toString(describeSelf: true)}\n'
'View of start node: $startView\n'
'Specified view: $view',
);
}
}
FlutterView? endView;
if (end != null) {
endView = _controller.viewOf(end);
if (view != null && endView != view) {
throw StateError(
'The end node is not part of the provided view.\n'
'Finder: ${end.toString(describeSelf: true)}\n'
'View of end node: $endView\n'
'Specified view: $view',
);
}
} else if (endNode != null) {
final SemanticsOwner owner = endNode.evaluate().single.owner!;
final RenderView renderView = _controller.binding.renderViews.firstWhere(
(RenderView render) => render.owner!.semanticsOwner == owner,
);
endView = renderView.flutterView;
if (view != null && endView != view) {
throw StateError(
'The end node is not part of the provided view.\n'
'Finder: ${endNode.toString(describeSelf: true)}\n'
'View of end node: $endView\n'
'Specified view: $view',
);
}
}
if (endView != null && startView != null && endView != startView) {
throw StateError(
'The start and end node are in different views.\n'
'Start finder: ${start!.toString(describeSelf: true)}\n'
'End finder: ${end!.toString(describeSelf: true)}\n'
'View of start node: $startView\n'
'View of end node: $endView',
);
}
final FlutterView actualView = view ?? startView ?? endView ?? _controller.view;
final RenderView renderView = _controller.binding.renderViews.firstWhere(
(RenderView r) => r.flutterView == actualView,
);
final traversal = <SemanticsNode>[];
_accessibilityTraversal(renderView.owner!.semanticsOwner!.rootSemanticsNode!, traversal);
// Setting the range
SemanticsNode? node;
String? errorString;
int startIndex;
if (start != null) {
node = find(start);
startIndex = traversal.indexOf(node);
errorString = start.toString(describeSelf: true);
} else if (startNode != null) {
node = startNode.evaluate().single;
startIndex = traversal.indexOf(node);
errorString = startNode.toString(describeSelf: true);
} else {
startIndex = 0;
}
if (startIndex == -1) {
throw StateError(
'The expected starting node was not found.\n'
'Finder: $errorString\n\n'
'Expected Start Node: $node\n\n'
'Traversal: [\n ${traversal.join('\n ')}\n]',
);
}
int? endIndex;
if (end != null) {
node = find(end);
endIndex = traversal.indexOf(node);
errorString = end.toString(describeSelf: true);
} else if (endNode != null) {
node = endNode.evaluate().single;
endIndex = traversal.indexOf(node);
errorString = endNode.toString(describeSelf: true);
}
if (endIndex == -1) {
throw StateError(
'The expected ending node was not found.\n'
'Finder: $errorString\n\n'
'Expected End Node: $node\n\n'
'Traversal: [\n ${traversal.join('\n ')}\n]',
);
}
endIndex ??= traversal.length - 1;
return traversal.getRange(startIndex, endIndex + 1);
}
/// Recursive depth first traversal of the specified `node`, adding nodes
/// that are important for semantics to the `traversal` list.
void _accessibilityTraversal(SemanticsNode node, List<SemanticsNode> traversal) {
if (_isImportantForAccessibility(node)) {
traversal.add(node);
}
final List<SemanticsNode> children = node.debugListChildrenInOrder(
DebugSemanticsDumpOrder.traversalOrder,
);
for (final child in children) {
_accessibilityTraversal(child, traversal);
}
}
/// Whether or not the node is important for semantics. Should match most cases
/// on the platforms, but certain edge cases will be inconsistent.
///
/// Based on:
///
/// * [flutter/engine/AccessibilityBridge.java#SemanticsNode.isFocusable()](https://github.com/flutter/flutter/blob/main/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java#L2641)
/// * [flutter/engine/SemanticsObject.mm#SemanticsObject.isAccessibilityElement](https://github.com/flutter/flutter/blob/main/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.mm#L449)
//
// TODO(quncheng): If this method is modified, please also update the copy of
// this method located in `packages/flutter/lib/src/widgets/_accessibility_evaluations.dart`.
// This private method will be removed once the feature flag
// `isAccessibilityEvaluationsEnabled` is turned on.
bool _isImportantForAccessibility(SemanticsNode node) {
if (node.isMergedIntoParent) {
// If this node is merged, all its information are present on an ancestor
// node.
return false;
}
final SemanticsData data = node.getSemanticsData();
// If the node scopes a route, it doesn't matter what other flags/actions it
// has, it is _not_ important for accessibility, so we short circuit.
if (data.flagsCollection.scopesRoute) {
return false;
}
final hasNonScrollingAction = data.actions & ~_scrollingActions != 0;
if (hasNonScrollingAction) {
return true;
}
/// Based on Android's FOCUSABLE_FLAGS. See [flutter/engine/AccessibilityBridge.java](https://github.com/flutter/flutter/blob/main/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java).
final bool hasImportantFlag =
data.flagsCollection.isChecked != ui.CheckedState.none ||
data.flagsCollection.isToggled != ui.Tristate.none ||
data.flagsCollection.isEnabled != ui.Tristate.none ||
data.flagsCollection.isButton ||
data.flagsCollection.isTextField ||
data.flagsCollection.isFocused != ui.Tristate.none ||
data.flagsCollection.isSlider ||
data.flagsCollection.isInMutuallyExclusiveGroup;
if (hasImportantFlag) {
return true;
}
final bool hasContent =
data.label.isNotEmpty ||
data.value.isNotEmpty ||
data.hint.isNotEmpty ||
data.tooltip.isNotEmpty;
if (hasContent) {
return true;
}
return false;
}
/// Performs the given [SemanticsAction] on the [SemanticsNode] found by `finder`.
///
/// If `args` are provided, they will be passed unmodified with the `action`.
/// The `checkForAction` argument allows for attempting to perform `action` on
/// `node` even if it doesn't report supporting that action. This is useful
/// for implicitly supported actions such as [SemanticsAction.showOnScreen].
void performAction(
finders.FinderBase<SemanticsNode> finder,
SemanticsAction action, {
Object? args,
bool checkForAction = true,
}) {
final SemanticsNode node = finder.evaluate().single;
if (checkForAction && !node.getSemanticsData().hasAction(action)) {
throw StateError(
'The given node does not support $action. If the action is implicitly '
'supported or an unsupported action is being tested for this node, '
'set `checkForAction` to false.\n'
'Node: $node',
);
}
node.owner!.performAction(node.id, action, args);
}
/// Performs a [SemanticsAction.tap] action on the [SemanticsNode] found
/// by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.tap].
void tap(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.tap);
}
/// Performs a [SemanticsAction.longPress] action on the [SemanticsNode] found
/// by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.longPress].
void longPress(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.longPress);
}
/// Performs a [SemanticsAction.scrollLeft] action on the [SemanticsNode]
/// found by `scrollable` or the first scrollable node in the default
/// semantics tree if no `scrollable` is provided.
///
/// Throws a [StateError] if:
/// * The given `scrollable` returns zero or more than one result.
/// * The [SemanticsNode] found with `scrollable` does not support
/// [SemanticsAction.scrollLeft].
void scrollLeft({finders.FinderBase<SemanticsNode>? scrollable}) {
performAction(scrollable ?? finders.find.semantics.scrollable(), SemanticsAction.scrollLeft);
}
/// Performs a [SemanticsAction.scrollRight] action on the [SemanticsNode]
/// found by `scrollable` or the first scrollable node in the default
/// semantics tree if no `scrollable` is provided.
///
/// Throws a [StateError] if:
/// * The given `scrollable` returns zero or more than one result.
/// * The [SemanticsNode] found with `scrollable` does not support
/// [SemanticsAction.scrollRight].
void scrollRight({finders.FinderBase<SemanticsNode>? scrollable}) {
performAction(scrollable ?? finders.find.semantics.scrollable(), SemanticsAction.scrollRight);
}
/// Performs a [SemanticsAction.scrollUp] action on the [SemanticsNode] found
/// by `scrollable` or the first scrollable node in the default semantics
/// tree if no `scrollable` is provided.
///
/// Throws a [StateError] if:
/// * The given `scrollable` returns zero or more than one result.
/// * The [SemanticsNode] found with `scrollable` does not support
/// [SemanticsAction.scrollUp].
void scrollUp({finders.FinderBase<SemanticsNode>? scrollable}) {
performAction(scrollable ?? finders.find.semantics.scrollable(), SemanticsAction.scrollUp);
}
/// Performs a [SemanticsAction.scrollDown] action on the [SemanticsNode]
/// found by `scrollable` or the first scrollable node in the default
/// semantics tree if no `scrollable` is provided.
///
/// Throws a [StateError] if:
/// * The given `scrollable` returns zero or more than one result.
/// * The [SemanticsNode] found with `scrollable` does not support
/// [SemanticsAction.scrollDown].
void scrollDown({finders.FinderBase<SemanticsNode>? scrollable}) {
performAction(scrollable ?? finders.find.semantics.scrollable(), SemanticsAction.scrollDown);
}
/// Performs a [SemanticsAction.increase] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.increase].
void increase(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.increase);
}
/// Performs a [SemanticsAction.decrease] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.decrease].
void decrease(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.decrease);
}
/// Performs a [SemanticsAction.showOnScreen] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.showOnScreen].
void showOnScreen(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.showOnScreen, checkForAction: false);
}
/// Performs a [SemanticsAction.moveCursorForwardByCharacter] action on the
/// [SemanticsNode] found by `finder`.
///
/// If `shouldModifySelection` is true, then the cursor will begin or extend
/// a selection.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.moveCursorForwardByCharacter].
void moveCursorForwardByCharacter(
finders.FinderBase<SemanticsNode> finder, {
bool shouldModifySelection = false,
}) {
performAction(
finder,
SemanticsAction.moveCursorForwardByCharacter,
args: shouldModifySelection,
);
}
/// Performs a [SemanticsAction.moveCursorForwardByWord] action on the
/// [SemanticsNode] found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.moveCursorForwardByWord].
void moveCursorForwardByWord(
finders.FinderBase<SemanticsNode> finder, {
bool shouldModifySelection = false,
}) {
performAction(finder, SemanticsAction.moveCursorForwardByWord, args: shouldModifySelection);
}
/// Performs a [SemanticsAction.moveCursorBackwardByCharacter] action on the
/// [SemanticsNode] found by `finder`.
///
/// If `shouldModifySelection` is true, then the cursor will begin or extend
/// a selection.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.moveCursorBackwardByCharacter].
void moveCursorBackwardByCharacter(
finders.FinderBase<SemanticsNode> finder, {
bool shouldModifySelection = false,
}) {
performAction(
finder,
SemanticsAction.moveCursorBackwardByCharacter,
args: shouldModifySelection,
);
}
/// Performs a [SemanticsAction.moveCursorBackwardByWord] action on the
/// [SemanticsNode] found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.moveCursorBackwardByWord].
void moveCursorBackwardByWord(
finders.FinderBase<SemanticsNode> finder, {
bool shouldModifySelection = false,
}) {
performAction(finder, SemanticsAction.moveCursorBackwardByWord, args: shouldModifySelection);
}
/// Performs a [SemanticsAction.setText] action on the [SemanticsNode]
/// found by `finder` using the given `text`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.setText].
void setText(finders.FinderBase<SemanticsNode> finder, String text) {
performAction(finder, SemanticsAction.setText, args: text);
}
/// Performs a [SemanticsAction.setSelection] action on the [SemanticsNode]
/// found by `finder`.
///
/// The `base` parameter is the start index of selection, and the `extent`
/// parameter is the length of the selection. Each value should be limited
/// between 0 and the length of the found [SemanticsNode]'s `value`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.setSelection].
void setSelection(
finders.FinderBase<SemanticsNode> finder, {
required int base,
required int extent,
}) {
performAction(
finder,
SemanticsAction.setSelection,
args: <String, int>{'base': base, 'extent': extent},
);
}
/// Performs a [SemanticsAction.copy] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.copy].
void copy(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.copy);
}
/// Performs a [SemanticsAction.cut] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.cut].
void cut(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.cut);
}
/// Performs a [SemanticsAction.paste] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.paste].
void paste(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.paste);
}
/// Performs a [SemanticsAction.didGainAccessibilityFocus] action on the
/// [SemanticsNode] found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.didGainAccessibilityFocus].
void didGainAccessibilityFocus(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.didGainAccessibilityFocus);
}
/// Performs a [SemanticsAction.didLoseAccessibilityFocus] action on the
/// [SemanticsNode] found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.didLoseAccessibilityFocus].
void didLoseAccessibilityFocus(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.didLoseAccessibilityFocus);
}
/// Performs a [SemanticsAction.customAction] action on the
/// [SemanticsNode] found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.customAction].
void customAction(finders.FinderBase<SemanticsNode> finder, CustomSemanticsAction action) {
performAction(
finder,
SemanticsAction.customAction,
args: CustomSemanticsAction.getIdentifier(action),
);
}
/// Performs a [SemanticsAction.dismiss] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.dismiss].
void dismiss(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.dismiss);
}
}
/// Class that programmatically interacts with widgets.
///
/// For a variant of this class suited specifically for unit tests, see
/// [WidgetTester]. For one suitable for live tests on a device, consider
/// [LiveWidgetController].
///
/// Concrete subclasses must implement the [pump] method.
abstract class WidgetController {
/// Creates a widget controller that uses the given binding.
WidgetController(this.binding);
/// A reference to the current instance of the binding.
final WidgetsBinding binding;
/// The [TestPlatformDispatcher] that is being used in this test.
///
/// This will be injected into the framework such that calls to
/// [WidgetsBinding.platformDispatcher] will use this. This allows
/// users to change platform specific properties for testing.
///
/// See also:
///
/// * [TestFlutterView] which allows changing view specific properties
/// for testing
/// * [view] and [viewOf] which are used to find
/// [TestFlutterView]s from the widget tree
TestPlatformDispatcher get platformDispatcher =>
binding.platformDispatcher as TestPlatformDispatcher;
/// The [TestFlutterView] provided by default when testing with
/// [WidgetTester.pumpWidget].
///
/// If the test uses multiple views, this will return the view that is painted
/// into by [WidgetTester.pumpWidget]. If a different view needs to be
/// accessed use [viewOf] to ensure that the view related to the widget being
/// evaluated is the one that gets updated.
///
/// See also:
///
/// * [viewOf], which can find a [TestFlutterView] related to a given finder.
/// This is how to modify view properties for testing when dealing with
/// multiple views.
TestFlutterView get view => platformDispatcher.implicitView!;
/// Provides access to a [SemanticsController] for testing anything related to
/// the [Semantics] tree.
///
/// Assistive technologies, search engines, and other analysis tools all make
/// use of the [Semantics] tree to determine the meaning of an application.
/// If semantics has been disabled for the test, this will throw a [StateError].
SemanticsController get semantics {
if (!binding.semanticsEnabled) {
throw StateError(
'Semantics are not enabled. Enable them by passing '
'`semanticsEnabled: true` to `testWidgets`, or by manually creating a '
'`SemanticsHandle` with `WidgetController.ensureSemantics()`.',
);
}
return _semantics;
}
late final SemanticsController _semantics = SemanticsController._(this);
// FINDER API
// TODO(ianh): verify that the return values are of type T and throw
// a good message otherwise, in all the generic methods below
/// Finds the [TestFlutterView] that is the closest ancestor of the widget
/// found by [finder].
///
/// [TestFlutterView] can be used to modify view specific properties for testing.
///
/// See also:
///
/// * [view] which returns the [TestFlutterView] used when only a single
/// view is being used.
TestFlutterView viewOf(finders.FinderBase<Element> finder) {
return _viewOf(finder) as TestFlutterView;
}
FlutterView _viewOf(finders.FinderBase<Element> finder) {
final FlutterView? view = _maybeViewOf(finder);
if (view == null) {
throw StateError(
'No FlutterView ancestor found for finder: '
'${finder.toString(describeSelf: true)}',
);
}
return view;
}
FlutterView? _maybeViewOf(finders.FinderBase<Element> finder) {
final Iterable<View> views = widgetList<View>(
finders.find.ancestor(of: finder, matching: finders.find.byType(View)),
);
if (views.isEmpty) {
return null;
}
return views.first.view;
}
/// Checks if `finder` exists in the tree.
bool any(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().isNotEmpty;
}
/// All widgets currently in the widget tree (lazy pre-order traversal).
///
/// Can contain duplicates, since widgets can be used in multiple
/// places in the widget tree.
Iterable<Widget> get allWidgets {
TestAsyncUtils.guardSync();
return allElements.map<Widget>((Element element) => element.widget);
}
/// The matching widget in the widget tree.
///
/// Throws a [StateError] if `finder` is empty or matches more than
/// one widget.
///
/// * Use [firstWidget] if you expect to match several widgets but only want the first.
/// * Use [widgetList] if you expect to match several widgets and want all of them.
T widget<T extends Widget>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().single.widget as T;
}
/// The first matching widget according to a depth-first pre-order
/// traversal of the widget tree.
///
/// Throws a [StateError] if `finder` is empty.
///
/// * Use [widget] if you only expect to match one widget.
T firstWidget<T extends Widget>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().first.widget as T;
}
/// The matching widgets in the widget tree.
///
/// * Use [widget] if you only expect to match one widget.
/// * Use [firstWidget] if you expect to match several but only want the first.
Iterable<T> widgetList<T extends Widget>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().map<T>((Element element) {
final result = element.widget as T;
return result;
});
}
/// Find all layers that are children of the provided [finder].
///
/// The [finder] must match exactly one element.
Iterable<Layer> layerListOf(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
final Element element = finder.evaluate().single;
final RenderObject object = element.renderObject!;
var current = object;
while (current.debugLayer == null) {
current = current.parent!;
}
final ContainerLayer layer = current.debugLayer!;
return _walkLayers(layer);
}
/// All elements currently in the widget tree (lazy pre-order traversal).
///
/// The returned iterable is lazy. It does not walk the entire widget tree
/// immediately, but rather a chunk at a time as the iteration progresses
/// using [Iterator.moveNext].
Iterable<Element> get allElements {
TestAsyncUtils.guardSync();
return collectAllElementsFrom(binding.rootElement!, skipOffstage: false);
}
/// The matching element in the widget tree.
///
/// Throws a [StateError] if `finder` is empty or matches more than
/// one element.
///
/// * Use [firstElement] if you expect to match several elements but only want the first.
/// * Use [elementList] if you expect to match several elements and want all of them.
T element<T extends Element>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().single as T;
}
/// The first matching element according to a depth-first pre-order
/// traversal of the widget tree.
///
/// Throws a [StateError] if `finder` is empty.
///
/// * Use [element] if you only expect to match one element.
T firstElement<T extends Element>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().first as T;
}
/// The matching elements in the widget tree.
///
/// * Use [element] if you only expect to match one element.
/// * Use [firstElement] if you expect to match several but only want the first.
Iterable<T> elementList<T extends Element>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().cast<T>();
}
/// All states currently in the widget tree (lazy pre-order traversal).
///
/// The returned iterable is lazy. It does not walk the entire widget tree
/// immediately, but rather a chunk at a time as the iteration progresses
/// using [Iterator.moveNext].
Iterable<State> get allStates {
TestAsyncUtils.guardSync();
return allElements.whereType<StatefulElement>().map<State>(
(StatefulElement element) => element.state,
);
}
/// The matching state in the widget tree.
///
/// Throws a [StateError] if `finder` is empty, matches more than
/// one state, or matches a widget that has no state.
///
/// * Use [firstState] if you expect to match several states but only want the first.
/// * Use [stateList] if you expect to match several states and want all of them.
T state<T extends State>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return _stateOf<T>(finder.evaluate().single, finder);
}
/// The first matching state according to a depth-first pre-order
/// traversal of the widget tree.
///
/// Throws a [StateError] if `finder` is empty or if the first
/// matching widget has no state.
///
/// * Use [state] if you only expect to match one state.
T firstState<T extends State>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return _stateOf<T>(finder.evaluate().first, finder);
}
/// The matching states in the widget tree.
///
/// Throws a [StateError] if any of the elements in `finder` match a widget
/// that has no state.
///
/// * Use [state] if you only expect to match one state.
/// * Use [firstState] if you expect to match several but only want the first.
Iterable<T> stateList<T extends State>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().map<T>((Element element) => _stateOf<T>(element, finder));
}
T _stateOf<T extends State>(Element element, finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
if (element is StatefulElement) {
return element.state as T;
}
throw StateError(
'Widget of type ${element.widget.runtimeType}, with ${finder.describeMatch(finders.Plurality.many)}, is not a StatefulWidget.',
);
}
/// Render objects of all the widgets currently in the widget tree
/// (lazy pre-order traversal).
///
/// This will almost certainly include many duplicates since the
/// render object of a [StatelessWidget] or [StatefulWidget] is the
/// render object of its child; only [RenderObjectWidget]s have
/// their own render object.
Iterable<RenderObject> get allRenderObjects {
TestAsyncUtils.guardSync();
return allElements.map<RenderObject>((Element element) => element.renderObject!);
}
/// The render object of the matching widget in the widget tree.
///
/// Throws a [StateError] if `finder` is empty or matches more than
/// one widget (even if they all have the same render object).
///
/// * Use [firstRenderObject] if you expect to match several render objects but only want the first.
/// * Use [renderObjectList] if you expect to match several render objects and want all of them.
T renderObject<T extends RenderObject>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().single.renderObject! as T;
}
/// The render object of the first matching widget according to a
/// depth-first pre-order traversal of the widget tree.
///
/// Throws a [StateError] if `finder` is empty.
///
/// * Use [renderObject] if you only expect to match one render object.
T firstRenderObject<T extends RenderObject>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();