selectable_region_test.dart 169 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
// 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.

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';

12 13
import 'clipboard_utils.dart';
import 'keyboard_utils.dart';
14
import 'process_text_utils.dart';
15
import 'semantics_tester.dart';
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

Offset textOffsetToPosition(RenderParagraph paragraph, int offset) {
  const Rect caret = Rect.fromLTWH(0.0, 0.0, 2.0, 20.0);
  final Offset localOffset = paragraph.getOffsetForCaret(TextPosition(offset: offset), caret);
  return paragraph.localToGlobal(localOffset);
}

Offset globalize(Offset point, RenderBox box) {
  return box.localToGlobal(point);
}

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();
  final MockClipboard mockClipboard = MockClipboard();

  setUp(() async {
32
    TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall);
33 34 35 36
    await Clipboard.setData(const ClipboardData(text: 'empty'));
  });

  tearDown(() {
37
    TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
38 39
  });

40
  group('SelectableRegion', () {
41
    testWidgets('mouse selection single click sends correct events', (WidgetTester tester) async {
42
      final UniqueKey spy = UniqueKey();
43 44 45
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

46
      await tester.pumpWidget(
47 48
        MaterialApp(
          home: SelectableRegion(
49
            focusNode: focusNode,
50 51 52 53
            selectionControls: materialTextSelectionControls,
            child: SelectionSpy(key: spy),
          ),
        ),
54
      );
55
      await tester.pumpAndSettle();
56 57 58 59

      final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy));
      final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
60
      await tester.pumpAndSettle();
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
      renderSelectionSpy.events.clear();

      await gesture.moveTo(const Offset(200.0, 100.0));
      expect(renderSelectionSpy.events.length, 2);
      expect(renderSelectionSpy.events[0].type, SelectionEventType.startEdgeUpdate);
      final SelectionEdgeUpdateEvent startEdge = renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent;
      expect(startEdge.globalPosition, const Offset(200.0, 200.0));
      expect(renderSelectionSpy.events[1].type, SelectionEventType.endEdgeUpdate);
      SelectionEdgeUpdateEvent endEdge = renderSelectionSpy.events[1] as SelectionEdgeUpdateEvent;
      expect(endEdge.globalPosition, const Offset(200.0, 100.0));
      renderSelectionSpy.events.clear();

      await gesture.moveTo(const Offset(100.0, 100.0));
      expect(renderSelectionSpy.events.length, 1);
      expect(renderSelectionSpy.events[0].type, SelectionEventType.endEdgeUpdate);
      endEdge = renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent;
      expect(endEdge.globalPosition, const Offset(100.0, 100.0));

      await gesture.up();
    }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/102410.

82
    testWidgets('mouse double click sends select-word event', (WidgetTester tester) async {
83
      final UniqueKey spy = UniqueKey();
84 85 86
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

87 88 89
      await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
90
              focusNode: focusNode,
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
              selectionControls: materialTextSelectionControls,
              child: SelectionSpy(key: spy),
            ),
          )
      );

      final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy));
      final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.up();
      await tester.pump();
      renderSelectionSpy.events.clear();
      await gesture.down(const Offset(200.0, 200.0));
      await tester.pump();
      await gesture.up();
      expect(renderSelectionSpy.events.length, 1);
      expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>());
      final SelectWordSelectionEvent selectionEvent = renderSelectionSpy.events[0] as SelectWordSelectionEvent;
      expect(selectionEvent.globalPosition, const Offset(200.0, 200.0));
    });

113
    testWidgets('Does not crash when using Navigator pages', (WidgetTester tester) async {
114
      // Regression test for https://github.com/flutter/flutter/issues/119776
115 116 117
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

118 119 120 121 122 123 124 125 126
      await tester.pumpWidget(
        MaterialApp(
          home: Navigator(
            pages: <Page<void>> [
              MaterialPage<void>(
                child: Column(
                  children: <Widget>[
                    const Text('How are you?'),
                    SelectableRegion(
127
                      focusNode: focusNode,
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
                      selectionControls: materialTextSelectionControls,
                      child: const SelectAllWidget(child: SizedBox(width: 100, height: 100)),
                    ),
                    const Text('Fine, thank you.'),
                  ],
                ),
              ),
              const MaterialPage<void>(
                child: Scaffold(body: Text('Foreground Page')),
              ),
            ],
            onPopPage: (_, __) => false,
          ),
        ),
      );

      expect(tester.takeException(), isNull);
    });

147
    testWidgets('can draw handles when they are at rect boundaries', (WidgetTester tester) async {
148
      final UniqueKey spy = UniqueKey();
149 150 151
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

152 153 154 155 156 157
      await tester.pumpWidget(
        MaterialApp(
          home: Column(
            children: <Widget>[
              const Text('How are you?'),
              SelectableRegion(
158
                focusNode: focusNode,
159 160 161 162 163 164 165 166
                selectionControls: materialTextSelectionControls,
                child: SelectAllWidget(key: spy, child: const SizedBox(width: 100, height: 100)),
              ),
              const Text('Fine, thank you.'),
            ],
          ),
        ),
      );
167 168
      await tester.pumpAndSettle();

169 170 171 172 173 174 175 176 177 178 179
      final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(spy)));
      addTearDown(gesture.removePointer);
      await tester.pump(const Duration(milliseconds: 500));
      await gesture.up();
      await tester.pump();

      final RenderSelectAll renderSpy = tester.renderObject<RenderSelectAll>(find.byKey(spy));
      expect(renderSpy.startHandle, isNotNull);
      expect(renderSpy.endHandle, isNotNull);
    });

180
    testWidgets('touch does not accept drag', (WidgetTester tester) async {
181
      final UniqueKey spy = UniqueKey();
182 183 184
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

185 186 187
      await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
188
              focusNode: focusNode,
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
              selectionControls: materialTextSelectionControls,
              child: SelectionSpy(key: spy),
            ),
          )
      );

      final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy));
      final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0));
      addTearDown(gesture.removePointer);
      await gesture.moveTo(const Offset(200.0, 100.0));
      await gesture.up();
      expect(
        renderSelectionSpy.events.every((SelectionEvent element) => element is ClearSelectionEvent),
        isTrue
      );
    });

206
    testWidgets('does not merge semantics node of the children', (WidgetTester tester) async {
207
      final SemanticsTester semantics = SemanticsTester(tester);
208 209 210
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

211 212 213
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
214
            focusNode: focusNode,
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
            selectionControls: materialTextSelectionControls,
            child: Scaffold(
              body: Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    const Text('Line one'),
                    const Text('Line two'),
                    ElevatedButton(
                      onPressed: () {},
                      child: const Text('Button'),
                    )
                  ],
                ),
              ),
            ),
          ),
        ),
      );

      expect(
        semantics,
        hasSemantics(
          TestSemantics.root(
            children: <TestSemantics>[
              TestSemantics(
                textDirection: TextDirection.ltr,
                children: <TestSemantics>[
                  TestSemantics(
                    children: <TestSemantics>[
                      TestSemantics(
246
                        flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
247 248
                        children: <TestSemantics>[
                          TestSemantics(
249 250 251 252 253 254 255 256 257 258 259 260 261
                            label: 'Line one',
                            textDirection: TextDirection.ltr,
                          ),
                          TestSemantics(
                            label: 'Line two',
                            textDirection: TextDirection.ltr,
                          ),
                          TestSemantics(
                            flags: <SemanticsFlag>[
                              SemanticsFlag.isButton,
                              SemanticsFlag.hasEnabledState,
                              SemanticsFlag.isEnabled,
                              SemanticsFlag.isFocusable
262
                            ],
263 264 265
                            actions: <SemanticsAction>[SemanticsAction.tap],
                            label: 'Button',
                            textDirection: TextDirection.ltr,
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
          ignoreRect: true,
          ignoreTransform: true,
          ignoreId: true,
        ),
      );

      semantics.dispose();
    });

284
    testWidgets('mouse single-click selection collapses the selection', (WidgetTester tester) async {
285
      final UniqueKey spy = UniqueKey();
286 287 288
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

289 290 291
      await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
292
              focusNode: focusNode,
293 294 295 296 297
              selectionControls: materialTextSelectionControls,
              child: SelectionSpy(key: spy),
            ),
          )
      );
298
      await tester.pumpAndSettle();
299 300 301 302

      final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy));
      final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
303 304
      await tester.pump();
      await gesture.up();
305
      await tester.pumpAndSettle();
306 307 308 309 310
      expect(renderSelectionSpy.events.length, 2);
      expect(renderSelectionSpy.events[0], isA<SelectionEdgeUpdateEvent>());
      expect((renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent).type, SelectionEventType.startEdgeUpdate);
      expect(renderSelectionSpy.events[1], isA<SelectionEdgeUpdateEvent>());
      expect((renderSelectionSpy.events[1] as SelectionEdgeUpdateEvent).type, SelectionEventType.endEdgeUpdate);
311 312
    }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/102410.

313
    testWidgets('touch long press sends select-word event', (WidgetTester tester) async {
314
      final UniqueKey spy = UniqueKey();
315 316 317
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

318 319 320
      await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
321
              focusNode: focusNode,
322 323 324 325 326
              selectionControls: materialTextSelectionControls,
              child: SelectionSpy(key: spy),
            ),
          )
      );
327
      await tester.pumpAndSettle();
328 329 330 331 332 333 334 335 336 337 338 339 340

      final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy));
      renderSelectionSpy.events.clear();
      final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0));
      addTearDown(gesture.removePointer);
      await tester.pump(const Duration(milliseconds: 500));
      await gesture.up();
      expect(renderSelectionSpy.events.length, 1);
      expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>());
      final SelectWordSelectionEvent selectionEvent = renderSelectionSpy.events[0] as SelectWordSelectionEvent;
      expect(selectionEvent.globalPosition, const Offset(200.0, 200.0));
    });

341
    testWidgets('touch long press and drag sends correct events', (WidgetTester tester) async {
342
      final UniqueKey spy = UniqueKey();
343 344 345
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

346 347 348
      await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
349
              focusNode: focusNode,
350 351 352 353 354
              selectionControls: materialTextSelectionControls,
              child: SelectionSpy(key: spy),
            ),
          )
      );
355
      await tester.pumpAndSettle();
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

      final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy));
      renderSelectionSpy.events.clear();
      final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0));
      addTearDown(gesture.removePointer);
      await tester.pump(const Duration(milliseconds: 500));
      expect(renderSelectionSpy.events.length, 1);
      expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>());
      final SelectWordSelectionEvent selectionEvent = renderSelectionSpy.events[0] as SelectWordSelectionEvent;
      expect(selectionEvent.globalPosition, const Offset(200.0, 200.0));

      renderSelectionSpy.events.clear();
      await gesture.moveTo(const Offset(200.0, 50.0));
      await gesture.up();
      expect(renderSelectionSpy.events.length, 1);
      expect(renderSelectionSpy.events[0].type, SelectionEventType.endEdgeUpdate);
      final SelectionEdgeUpdateEvent edgeEvent = renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent;
      expect(edgeEvent.globalPosition, const Offset(200.0, 50.0));
374
      expect(edgeEvent.granularity, TextGranularity.word);
375 376
    });

377 378 379 380 381 382
    testWidgets(
      'touch long press cancel does not send ClearSelectionEvent',
      (WidgetTester tester) async {
        final UniqueKey spy = UniqueKey();
        final FocusNode focusNode = FocusNode();
        addTearDown(focusNode.dispose);
383

384 385 386 387 388 389 390
        await tester.pumpWidget(
            MaterialApp(
              home: SelectableRegion(
                focusNode: focusNode,
                selectionControls: materialTextSelectionControls,
                child: SelectionSpy(key: spy),
              ),
391
            ),
392 393
        );
        await tester.pumpAndSettle();
394

395 396 397 398 399
        final RenderSelectionSpy renderSelectionSpy =
            tester.renderObject<RenderSelectionSpy>(find.byKey(spy));
        renderSelectionSpy.events.clear();
        final TestGesture gesture =
            await tester.startGesture(const Offset(200.0, 200.0));
400

401
        addTearDown(gesture.removePointer);
402

403 404 405 406 407 408 409 410
        await tester.pump(const Duration(milliseconds: 500));
        await gesture.cancel();
        expect(
          renderSelectionSpy.events.any((SelectionEvent element) => element is ClearSelectionEvent),
          isFalse,
        );
      },
    );
411

412
    testWidgets(
413 414 415 416
      'scrolling after the selection does not send ClearSelectionEvent',
      (WidgetTester tester) async {
        // Regression test for https://github.com/flutter/flutter/issues/128765
        final UniqueKey spy = UniqueKey();
417 418 419
        final FocusNode focusNode = FocusNode();
        addTearDown(focusNode.dispose);

420 421 422 423 424 425 426 427
        await tester.pumpWidget(
          MaterialApp(
            home: SizedBox(
              height: 750,
              child: SingleChildScrollView(
                child: SizedBox(
                  height: 2000,
                  child: SelectableRegion(
428
                    focusNode: focusNode,
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
                    selectionControls: materialTextSelectionControls,
                    child: SelectionSpy(key: spy),
                  ),
                ),
              ),
            ),
          ),
        );
        await tester.pumpAndSettle();

        final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy));
        renderSelectionSpy.events.clear();
        final TestGesture selectGesture = await tester.startGesture(const Offset(200.0, 200.0));
        addTearDown(selectGesture.removePointer);
        await tester.pump(const Duration(milliseconds: 500));
        await selectGesture.up();
        expect(renderSelectionSpy.events.length, 1);
        expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>());

        renderSelectionSpy.events.clear();
         final TestGesture scrollGesture =
            await tester.startGesture(const Offset(250.0, 850.0));
        await tester.pump(const Duration(milliseconds: 500));
        await scrollGesture.moveTo(Offset.zero);
        await scrollGesture.up();
        await tester.pumpAndSettle();
        expect(renderSelectionSpy.events.length, 0);
      },
    );

459
    testWidgets('mouse long press does not send select-word event', (WidgetTester tester) async {
460
      final UniqueKey spy = UniqueKey();
461 462 463
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

464 465 466
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
467
            focusNode: focusNode,
468 469 470 471 472
            selectionControls: materialTextSelectionControls,
            child: SelectionSpy(key: spy),
          ),
        ),
      );
473
      await tester.pumpAndSettle();
474 475 476 477 478 479 480 481

      final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy));
      renderSelectionSpy.events.clear();
      final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump(const Duration(milliseconds: 500));
      await gesture.up();
      expect(
482
        renderSelectionSpy.events.every((SelectionEvent element) => element is SelectionEdgeUpdateEvent),
483 484 485 486 487
        isTrue,
      );
    });
  });

488
  testWidgets('dragging handle or selecting word triggers haptic feedback on Android', (WidgetTester tester) async {
489 490 491 492 493 494 495 496
    final List<MethodCall> log = <MethodCall>[];
    tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async {
      log.add(methodCall);
      return null;
    });
    addTearDown(() {
      tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall);
    });
497 498
    final FocusNode focusNode = FocusNode();
    addTearDown(focusNode.dispose);
499 500 501 502

    await tester.pumpWidget(
      MaterialApp(
        home: SelectableRegion(
503
          focusNode: focusNode,
504 505 506 507 508
          selectionControls: materialTextSelectionControls,
          child: const Text('How are you?'),
        ),
      ),
    );
509
    await tester.pumpAndSettle();
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533

    final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
    final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 6)); // at the 'r'
    addTearDown(gesture.removePointer);
    await tester.pump(const Duration(milliseconds: 500));
    await gesture.up();
    await tester.pump(const Duration(milliseconds: 500));
    // `are` is selected.
    expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7));
    expect(
      log.last,
      isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.selectionClick'),
    );
    log.clear();
    final List<TextBox> boxes = paragraph.getBoxesForSelection(paragraph.selections[0]);
    expect(boxes.length, 1);
    final Offset handlePos = globalize(boxes[0].toRect().bottomRight, paragraph);
    await gesture.down(handlePos);
    final Offset endPos = Offset(textOffsetToPosition(paragraph, 8).dx, handlePos.dy);

    // Select 1 more character by dragging end handle to trigger feedback.
    await gesture.moveTo(endPos);
    expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 8));
    // Only Android vibrate when dragging the handle.
534
    switch (defaultTargetPlatform) {
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
      case TargetPlatform.android:
        expect(
          log.last,
          isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.selectionClick'),
        );
      case TargetPlatform.fuchsia:
      case TargetPlatform.iOS:
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
        expect(log, isEmpty);
    }
    await gesture.up();
  }, variant: TargetPlatformVariant.all());

550
  group('SelectionArea integration', () {
551
    testWidgets('mouse can select single text on desktop platforms', (WidgetTester tester) async {
552 553 554
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

555 556 557
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
558
            focusNode: focusNode,
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
            selectionControls: materialTextSelectionControls,
            child: const Center(
              child: Text('How are you'),
            ),
          ),
        ),
      );
      final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();

      await gesture.moveTo(textOffsetToPosition(paragraph, 4));
      await tester.pump();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4));

      await gesture.moveTo(textOffsetToPosition(paragraph, 6));
      await tester.pump();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6));

      // Check backward selection.
      await gesture.moveTo(textOffsetToPosition(paragraph, 1));
      await tester.pump();
582
      expect(paragraph.selections.isEmpty, isFalse);
583 584 585 586
      expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 1));

      // Start a new drag.
      await gesture.up();
587 588
      await tester.pumpAndSettle();

589
      await gesture.down(textOffsetToPosition(paragraph, 5));
590
      await tester.pumpAndSettle();
591 592
      expect(paragraph.selections.isEmpty, isFalse);
      expect(paragraph.selections[0], const TextSelection.collapsed(offset: 5));
593 594 595 596 597 598 599

      // Selecting across line should select to the end.
      await gesture.moveTo(textOffsetToPosition(paragraph, 5) + const Offset(0.0, 200.0));
      await tester.pump();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 5, extentOffset: 11));

      await gesture.up();
600 601
    }, variant: TargetPlatformVariant.desktop());

602
    testWidgets('mouse can select single text on mobile platforms', (WidgetTester tester) async {
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
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
            focusNode: focusNode,
            selectionControls: materialTextSelectionControls,
            child: const Center(
              child: Text('How are you'),
            ),
          ),
        ),
      );
      final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();

      await gesture.moveTo(textOffsetToPosition(paragraph, 4));
      await tester.pump();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4));

      await gesture.moveTo(textOffsetToPosition(paragraph, 6));
      await tester.pump();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6));

      // Check backward selection.
      await gesture.moveTo(textOffsetToPosition(paragraph, 1));
      await tester.pump();
      expect(paragraph.selections.isEmpty, isFalse);
      expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 1));

      // Start a new drag.
      await gesture.up();
      await tester.pumpAndSettle();

      await gesture.down(textOffsetToPosition(paragraph, 5));
      await tester.pumpAndSettle();
      await gesture.moveTo(textOffsetToPosition(paragraph, 6));
      await tester.pump();
      expect(paragraph.selections.isEmpty, isFalse);
      expect(paragraph.selections[0], const TextSelection(baseOffset: 5, extentOffset: 6));

      // Selecting across line should select to the end.
      await gesture.moveTo(textOffsetToPosition(paragraph, 5) + const Offset(0.0, 200.0));
      await tester.pump();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 5, extentOffset: 11));

      await gesture.up();
    }, variant: TargetPlatformVariant.mobile());
654

655
    testWidgets('mouse can select word-by-word on double click drag', (WidgetTester tester) async {
656 657 658
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

659 660 661
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
662
            focusNode: focusNode,
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
            selectionControls: materialTextSelectionControls,
            child: const Center(
              child: Text('How are you'),
            ),
          ),
        ),
      );
      final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.up();
      await tester.pump();

      await gesture.down(textOffsetToPosition(paragraph, 2));
      await tester.pumpAndSettle();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3));

      await gesture.moveTo(textOffsetToPosition(paragraph, 3));
      await tester.pumpAndSettle();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 4));

      await gesture.moveTo(textOffsetToPosition(paragraph, 4));
      await tester.pump();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7));

      await gesture.moveTo(textOffsetToPosition(paragraph, 7));
      await tester.pump();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 8));

      await gesture.moveTo(textOffsetToPosition(paragraph, 8));
      await tester.pump();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11));

      // Check backward selection.
      await gesture.moveTo(textOffsetToPosition(paragraph, 1));
      await tester.pump();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3));

      // Start a new double-click drag.
      await gesture.up();
      await tester.pump();
      await gesture.down(textOffsetToPosition(paragraph, 5));
      await tester.pump();
      await gesture.up();
708 709
      expect(paragraph.selections.isEmpty, isFalse);
      expect(paragraph.selections[0], const TextSelection.collapsed(offset: 5));
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
      await tester.pump(kDoubleTapTimeout);

      // Double-click.
      await gesture.down(textOffsetToPosition(paragraph, 5));
      await tester.pump();
      await gesture.up();
      await tester.pump();
      await gesture.down(textOffsetToPosition(paragraph, 5));
      await tester.pumpAndSettle();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7));

      // Selecting across line should select to the end.
      await gesture.moveTo(textOffsetToPosition(paragraph, 5) + const Offset(0.0, 200.0));
      await tester.pump();
      expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 11));
      await gesture.up();
    }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582.

728
    testWidgets('mouse can select multiple widgets on double click drag', (WidgetTester tester) async {
729 730 731
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

732 733 734
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
735
            focusNode: focusNode,
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
            selectionControls: materialTextSelectionControls,
            child: const Column(
              children: <Widget>[
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.up();
      await tester.pump();

      await gesture.down(textOffsetToPosition(paragraph1, 2));
      await tester.pumpAndSettle();
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3));

      await gesture.moveTo(textOffsetToPosition(paragraph1, 4));
      await tester.pump();
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7));

      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph2, 5));
      // Should select the rest of paragraph 1.
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6));

      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph3, 6));
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11));

      await gesture.up();
    }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582.

777
    testWidgets('mouse can select multiple widgets on double click drag and return to origin word', (WidgetTester tester) async {
778 779 780
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

781 782 783
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
784
            focusNode: focusNode,
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
            selectionControls: materialTextSelectionControls,
            child: const Column(
              children: <Widget>[
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.up();
      await tester.pump();

      await gesture.down(textOffsetToPosition(paragraph1, 2));
      await tester.pumpAndSettle();
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3));

      await gesture.moveTo(textOffsetToPosition(paragraph1, 4));
      await tester.pump();
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7));

      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph2, 5));
      // Should select the rest of paragraph 1.
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6));

      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph3, 6));
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11));

      await gesture.moveTo(textOffsetToPosition(paragraph2, 5));
      // Should clear the selection on paragraph 3.
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6));
827
      expect(paragraph3.selections.isEmpty, isTrue);
828 829 830 831

      await gesture.moveTo(textOffsetToPosition(paragraph1, 4));
      // Should clear the selection on paragraph 2.
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7));
832 833
      expect(paragraph2.selections.isEmpty, isTrue);
      expect(paragraph3.selections.isEmpty, isTrue);
834 835 836 837

      await gesture.up();
    }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582.

838
    testWidgets('mouse can reverse selection across multiple widgets on double click drag', (WidgetTester tester) async {
839 840 841
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

842 843 844
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
845
            focusNode: focusNode,
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
            selectionControls: materialTextSelectionControls,
            child: const Column(
              children: <Widget>[
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 10), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.up();
      await tester.pump();

      await gesture.down(textOffsetToPosition(paragraph3, 10));
      await tester.pumpAndSettle();
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11));

      await gesture.moveTo(textOffsetToPosition(paragraph3, 4));
      await tester.pump();
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 4));

      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph2, 5));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 0));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 5));

      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph1, 6));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 0));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 0));
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 12, extentOffset: 4));

      await gesture.up();
    }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582.

886
    testWidgets('mouse can select multiple widgets', (WidgetTester tester) async {
887 888 889
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

890 891 892
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
893
            focusNode: focusNode,
894
            selectionControls: materialTextSelectionControls,
895 896
            child: const Column(
              children: <Widget>[
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
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();

      await gesture.moveTo(textOffsetToPosition(paragraph1, 4));
      await tester.pump();
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4));

      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph2, 5));
      // Should select the rest of paragraph 1.
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5));

      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph3, 6));
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6));

      await gesture.up();
    });

929
    testWidgets('collapsing selection should clear selection of all other selectables', (WidgetTester tester) async {
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
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
            focusNode: focusNode,
            selectionControls: materialTextSelectionControls,
            child: const Column(
              children: <Widget>[
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.up();
      await tester.pumpAndSettle();
      expect(paragraph1.selections[0], const TextSelection.collapsed(offset: 2));

      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      await gesture.down(textOffsetToPosition(paragraph2, 5));
      await tester.pump();
      await gesture.up();
      await tester.pumpAndSettle();
      expect(paragraph1.selections.isEmpty, isTrue);
      expect(paragraph2.selections[0], const TextSelection.collapsed(offset: 5));

      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      await gesture.down(textOffsetToPosition(paragraph3, 13));
      await tester.pump();
      await gesture.up();
      await tester.pumpAndSettle();

      expect(paragraph1.selections.isEmpty, isTrue);
      expect(paragraph2.selections.isEmpty, isTrue);
      expect(paragraph3.selections[0], const TextSelection.collapsed(offset: 13));
    });

975
    testWidgets('mouse can work with disabled container', (WidgetTester tester) async {
976 977 978
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

979 980 981
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
982
            focusNode: focusNode,
983
            selectionControls: materialTextSelectionControls,
984 985
            child: const Column(
              children: <Widget>[
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
                Text('How are you?'),
                SelectionContainer.disabled(child: Text('Good, and you?')),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();

      await gesture.moveTo(textOffsetToPosition(paragraph1, 4));
      await tester.pump();
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4));

      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph2, 5));
      // Should select the rest of paragraph 1.
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12));
      // paragraph2 is in a disabled container.
      expect(paragraph2.selections.isEmpty, isTrue);

      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph3, 6));
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12));
      expect(paragraph2.selections.isEmpty, isTrue);
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6));

      await gesture.up();
    });

1019
    testWidgets('mouse can reverse selection', (WidgetTester tester) async {
1020 1021 1022
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

1023 1024 1025
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
1026
            focusNode: focusNode,
1027
            selectionControls: materialTextSelectionControls,
1028 1029
            child: const Column(
              children: <Widget>[
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 10), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();

      await gesture.moveTo(textOffsetToPosition(paragraph3, 4));
      await tester.pump();
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 10, extentOffset: 4));

      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph2, 5));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 10, extentOffset: 0));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 5));

      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph1, 6));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 10, extentOffset: 0));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 0));
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 12, extentOffset: 6));

      await gesture.up();
    });

1061 1062 1063 1064 1065 1066 1067 1068 1069
    testWidgets(
      'long press selection overlay behavior on iOS and Android',
      (WidgetTester tester) async {
        // This test verifies that all platforms wait until long press end to
        // show the context menu, and only Android waits until long press end to
        // show the selection handles.
        final bool isPlatformAndroid = defaultTargetPlatform == TargetPlatform.android;
        Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{};
        final UniqueKey toolbarKey = UniqueKey();
1070 1071
        final FocusNode focusNode = FocusNode();
        addTearDown(focusNode.dispose);
1072 1073 1074
        await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
1075
              focusNode: focusNode,
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
              selectionControls: materialTextSelectionHandleControls,
              contextMenuBuilder: (
                BuildContext context,
                SelectableRegionState selectableRegionState,
              ) {
                buttonTypes = selectableRegionState.contextMenuButtonItems
                  .map((ContextMenuButtonItem buttonItem) => buttonItem.type)
                  .toSet();
                return SizedBox.shrink(key: toolbarKey);
              },
              child: const Text('How are you?'),
            ),
          ),
        );

        expect(buttonTypes.isEmpty, true);
        expect(find.byKey(toolbarKey), findsNothing);

        final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
        final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2));
        addTearDown(gesture.removePointer);
        await tester.pump(const Duration(milliseconds: 500));
        await tester.pumpAndSettle();

        // All platform except Android should show the selection handles when the
        // long press starts.
        List<FadeTransition> transitions = find.descendant(
          of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'),
          matching: find.byType(FadeTransition),
        ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList();
        expect(transitions.length, isPlatformAndroid ? 0 : 2);
        FadeTransition? left;
        FadeTransition? right;
        if (!isPlatformAndroid) {
          left = transitions[0];
          right = transitions[1];
          expect(left.opacity.value, equals(1.0));
          expect(right.opacity.value, equals(1.0));
        }
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3));
        expect(find.byKey(toolbarKey), findsNothing);

        await gesture.moveTo(textOffsetToPosition(paragraph, 8));
        await tester.pumpAndSettle();
        transitions = find.descendant(
          of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'),
          matching: find.byType(FadeTransition),
        ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList();
        // All platform except Android should show the selection handles while doing
        // a long press drag.
        expect(transitions.length, isPlatformAndroid ? 0 : 2);
        if (!isPlatformAndroid) {
          left = transitions[0];
          right = transitions[1];
          expect(left.opacity.value, equals(1.0));
          expect(right.opacity.value, equals(1.0));
        }
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11));
        expect(find.byKey(toolbarKey), findsNothing);

        await gesture.up();
        await tester.pumpAndSettle();
        transitions = find.descendant(
          of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'),
          matching: find.byType(FadeTransition),
        ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList();
        expect(transitions.length, 2);
        left = transitions[0];
        right = transitions[1];

        // All platforms should show the selection handles and context menu when
        // the long press ends.
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11));
        expect(left.opacity.value, equals(1.0));
        expect(right.opacity.value, equals(1.0));
        expect(find.byKey(toolbarKey), findsOneWidget);
      },
      variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }),
      skip: kIsWeb, // [intended] Web uses its native context menu.
    );

1157
    testWidgets(
1158 1159 1160 1161
      'single tap on the previous selection toggles the toolbar on iOS',
      (WidgetTester tester) async {
        Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{};
        final UniqueKey toolbarKey = UniqueKey();
1162 1163 1164
        final FocusNode focusNode = FocusNode();
        addTearDown(focusNode.dispose);

1165 1166 1167
        await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
1168
              focusNode: focusNode,
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
              selectionControls: materialTextSelectionHandleControls,
              contextMenuBuilder: (
                BuildContext context,
                SelectableRegionState selectableRegionState,
              ) {
                buttonTypes = selectableRegionState.contextMenuButtonItems
                  .map((ContextMenuButtonItem buttonItem) => buttonItem.type)
                  .toSet();
                return SizedBox.shrink(key: toolbarKey);
              },
              child: const Column(
                children: <Widget>[
                  Text('How are you?'),
                  Text('Good, and you?'),
                  Text('Fine, thank you.'),
                ],
              ),
            ),
          ),
        );

        expect(buttonTypes.isEmpty, true);
        expect(find.byKey(toolbarKey), findsNothing);

        final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
        final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2));
        addTearDown(gesture.removePointer);
        await tester.pump(const Duration(milliseconds: 500));
        await gesture.up();
        await tester.pumpAndSettle();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3));
        expect(buttonTypes, contains(ContextMenuButtonType.copy));
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsOneWidget);

        await gesture.down(textOffsetToPosition(paragraph, 2));
        await tester.pump();
        await gesture.up();
        await tester.pumpAndSettle();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3));
        expect(buttonTypes, contains(ContextMenuButtonType.copy));
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsNothing);

        await gesture.down(textOffsetToPosition(paragraph, 2));
        await tester.pump();
        await gesture.up();
        await tester.pumpAndSettle();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3));
        expect(buttonTypes, contains(ContextMenuButtonType.copy));
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsOneWidget);

1222
        // Collapse selection.
1223 1224
        await tester.tapAt(textOffsetToPosition(paragraph, 9));
        await tester.pump();
1225 1226
        expect(paragraph.selections.isEmpty, isFalse);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 9));
1227 1228 1229 1230 1231 1232
        expect(find.byKey(toolbarKey), findsNothing);
      },
      variant: TargetPlatformVariant.only(TargetPlatform.iOS),
      skip: kIsWeb, // [intended] Web uses its native context menu.
    );

1233
    testWidgets(
1234 1235 1236 1237
      'right-click mouse can select word at position on Apple platforms',
      (WidgetTester tester) async {
        Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{};
        final UniqueKey toolbarKey = UniqueKey();
1238 1239 1240
        final FocusNode focusNode = FocusNode();
        addTearDown(focusNode.dispose);

1241 1242 1243
        await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
1244
              focusNode: focusNode,
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
              selectionControls: materialTextSelectionHandleControls,
              contextMenuBuilder: (
                BuildContext context,
                SelectableRegionState selectableRegionState,
              ) {
                buttonTypes = selectableRegionState.contextMenuButtonItems
                  .map((ContextMenuButtonItem buttonItem) => buttonItem.type)
                  .toSet();
                return SizedBox.shrink(key: toolbarKey);
              },
              child: const Center(
                child: Text('How are you'),
              ),
            ),
          ),
        );

        expect(buttonTypes.isEmpty, true);
        expect(find.byKey(toolbarKey), findsNothing);

        final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText)));
1266
        final TestGesture primaryMouseButtonGesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
1267
        final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton);
1268
        addTearDown(primaryMouseButtonGesture.removePointer);
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
        addTearDown(gesture.removePointer);
        await tester.pump();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3));

        await gesture.up();
        await tester.pump();

        expect(buttonTypes, contains(ContextMenuButtonType.copy));
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsOneWidget);

        await gesture.down(textOffsetToPosition(paragraph, 6));
        await tester.pump();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7));

        await gesture.up();
        await tester.pump();

        expect(buttonTypes, contains(ContextMenuButtonType.copy));
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsOneWidget);

        await gesture.down(textOffsetToPosition(paragraph, 9));
        await tester.pump();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 8, extentOffset: 11));

        await gesture.up();
        await tester.pump();

        expect(buttonTypes, contains(ContextMenuButtonType.copy));
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsOneWidget);

1302 1303
        // Collapse selection.
        await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 1));
1304
        await tester.pump();
1305 1306 1307 1308 1309
        await primaryMouseButtonGesture.up();
        await tester.pumpAndSettle();
        // Selection is collapsed.
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1));
1310 1311 1312 1313 1314 1315
        expect(find.byKey(toolbarKey), findsNothing);
      },
      variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }),
      skip: kIsWeb, // [intended] Web uses its native context menu.
    );

1316
    testWidgets(
1317 1318 1319 1320
      'right-click mouse at the same position as previous right-click toggles the context menu on macOS',
      (WidgetTester tester) async {
        Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{};
        final UniqueKey toolbarKey = UniqueKey();
1321 1322 1323
        final FocusNode focusNode = FocusNode();
        addTearDown(focusNode.dispose);

1324 1325 1326
        await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
1327
              focusNode: focusNode,
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
              selectionControls: materialTextSelectionHandleControls,
              contextMenuBuilder: (
                BuildContext context,
                SelectableRegionState selectableRegionState,
              ) {
                buttonTypes = selectableRegionState.contextMenuButtonItems
                  .map((ContextMenuButtonItem buttonItem) => buttonItem.type)
                  .toSet();
                return SizedBox.shrink(key: toolbarKey);
              },
              child: const Center(
                child: Text('How are you'),
              ),
            ),
          ),
        );

        expect(buttonTypes.isEmpty, true);
        expect(find.byKey(toolbarKey), findsNothing);

        final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText)));
        final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton);
1350 1351
        final TestGesture primaryMouseButtonGesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
        addTearDown(primaryMouseButtonGesture.removePointer);
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
        addTearDown(gesture.removePointer);
        await tester.pump();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3));

        await gesture.up();
        await tester.pump();

        expect(buttonTypes, contains(ContextMenuButtonType.copy));
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsOneWidget);

        await gesture.down(textOffsetToPosition(paragraph, 2));
        await tester.pump();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3));

        await gesture.up();
        await tester.pump();

        // Right-click at same position will toggle the context menu off.
        expect(buttonTypes, contains(ContextMenuButtonType.copy));
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsNothing);

        await gesture.down(textOffsetToPosition(paragraph, 9));
        await tester.pump();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 8, extentOffset: 11));

        await gesture.up();
        await tester.pump();

        expect(buttonTypes, contains(ContextMenuButtonType.copy));
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsOneWidget);

        await gesture.down(textOffsetToPosition(paragraph, 9));
        await tester.pump();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 8, extentOffset: 11));

        await gesture.up();
        await tester.pump();

        // Right-click at same position will toggle the context menu off.
        expect(buttonTypes, contains(ContextMenuButtonType.copy));
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsNothing);

        await gesture.down(textOffsetToPosition(paragraph, 6));
        await tester.pump();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7));

        await gesture.up();
        await tester.pump();

        expect(buttonTypes, contains(ContextMenuButtonType.copy));
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsOneWidget);

1409 1410
        // Collapse selection.
        await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 1));
1411
        await tester.pump();
1412 1413 1414 1415 1416
        await primaryMouseButtonGesture.up();
        await tester.pumpAndSettle();
        // Selection is collapsed.
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1));
1417 1418 1419 1420 1421 1422
        expect(find.byKey(toolbarKey), findsNothing);
      },
      variant: TargetPlatformVariant.only(TargetPlatform.macOS),
      skip: kIsWeb, // [intended] Web uses its native context menu.
    );

1423
    testWidgets(
1424
      'right-click mouse shows the context menu at position on Android, Fuchsia, and Windows',
1425 1426 1427
      (WidgetTester tester) async {
        Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{};
        final UniqueKey toolbarKey = UniqueKey();
1428 1429 1430
        final FocusNode focusNode = FocusNode();
        addTearDown(focusNode.dispose);

1431 1432 1433
        await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
1434
              focusNode: focusNode,
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
              selectionControls: materialTextSelectionHandleControls,
              contextMenuBuilder: (
                BuildContext context,
                SelectableRegionState selectableRegionState,
              ) {
                buttonTypes = selectableRegionState.contextMenuButtonItems
                  .map((ContextMenuButtonItem buttonItem) => buttonItem.type)
                  .toSet();
                return SizedBox.shrink(key: toolbarKey);
              },
              child: const Center(
                child: Text('How are you'),
              ),
            ),
          ),
        );

        expect(buttonTypes.isEmpty, true);
        expect(find.byKey(toolbarKey), findsNothing);

        final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText)));
        final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton);
1457 1458
        final TestGesture primaryMouseButtonGesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
        addTearDown(primaryMouseButtonGesture.removePointer);
1459 1460 1461 1462 1463
        addTearDown(gesture.removePointer);
        await tester.pump();
        await gesture.up();
        await tester.pump();

1464 1465 1466
        // Selection is collapsed.
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 2));
1467 1468 1469 1470 1471 1472
        expect(buttonTypes.length, 1);
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsOneWidget);

        await gesture.down(textOffsetToPosition(paragraph, 6));
        await tester.pump();
1473 1474
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 6));
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484

        await gesture.up();
        await tester.pump();

        expect(buttonTypes.length, 1);
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsOneWidget);

        await gesture.down(textOffsetToPosition(paragraph, 9));
        await tester.pump();
1485 1486
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 9));
1487 1488 1489 1490 1491 1492 1493 1494

        await gesture.up();
        await tester.pump();

        expect(buttonTypes.length, 1);
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsOneWidget);

1495 1496
        // Collapse selection.
        await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 1));
1497
        await tester.pump();
1498 1499 1500 1501 1502
        await primaryMouseButtonGesture.up();
        await tester.pumpAndSettle(kDoubleTapTimeout);
        // Selection is collapsed.
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1));
1503 1504 1505
        expect(find.byKey(toolbarKey), findsNothing);

        // Create an uncollapsed selection by dragging.
1506
        await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 0));
1507
        await tester.pump();
1508
        await primaryMouseButtonGesture.moveTo(textOffsetToPosition(paragraph, 5));
1509 1510
        await tester.pump();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5));
1511
        await primaryMouseButtonGesture.up();
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
        await tester.pump();

        // Right click on previous selection should not collapse the selection.
        await gesture.down(textOffsetToPosition(paragraph, 2));
        await tester.pump();
        await gesture.up();
        await tester.pump();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5));
        expect(find.byKey(toolbarKey), findsOneWidget);

        // Right click anywhere outside previous selection should collapse the
        // selection.
        await gesture.down(textOffsetToPosition(paragraph, 7));
        await tester.pump();
        await gesture.up();
        await tester.pump();
1528 1529
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 7));
1530 1531
        expect(find.byKey(toolbarKey), findsOneWidget);

1532 1533
        // Collapse selection.
        await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 1));
1534
        await tester.pump();
1535 1536 1537 1538 1539
        await primaryMouseButtonGesture.up();
        await tester.pumpAndSettle();
        // Selection is collapsed.
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1));
1540 1541 1542 1543 1544 1545
        expect(find.byKey(toolbarKey), findsNothing);
      },
      variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.windows }),
      skip: kIsWeb, // [intended] Web uses its native context menu.
    );

1546
    testWidgets(
1547 1548 1549 1550
      'right-click mouse toggles the context menu on Linux',
      (WidgetTester tester) async {
        Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{};
        final UniqueKey toolbarKey = UniqueKey();
1551 1552 1553
        final FocusNode focusNode = FocusNode();
        addTearDown(focusNode.dispose);

1554 1555 1556
        await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
1557
              focusNode: focusNode,
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
              selectionControls: materialTextSelectionHandleControls,
              contextMenuBuilder: (
                BuildContext context,
                SelectableRegionState selectableRegionState,
              ) {
                buttonTypes = selectableRegionState.contextMenuButtonItems
                  .map((ContextMenuButtonItem buttonItem) => buttonItem.type)
                  .toSet();
                return SizedBox.shrink(key: toolbarKey);
              },
              child: const Center(
                child: Text('How are you'),
              ),
            ),
          ),
        );

        expect(buttonTypes.isEmpty, true);
        expect(find.byKey(toolbarKey), findsNothing);

        final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText)));
        final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton);
1580 1581
        final TestGesture primaryMouseButtonGesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
        addTearDown(primaryMouseButtonGesture.removePointer);
1582 1583 1584 1585
        addTearDown(gesture.removePointer);
        await tester.pump();
        await gesture.up();
        await tester.pump();
1586 1587 1588
        // Selection is collapsed.
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 2));
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598

        // Context menu toggled on.
        expect(buttonTypes.length, 1);
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsOneWidget);

        await gesture.down(textOffsetToPosition(paragraph, 6));
        await tester.pump();
        await gesture.up();
        await tester.pump();
1599 1600
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 2));
1601

1602
        // Context menu toggled off. Selection remains the same.
1603 1604 1605 1606
        expect(find.byKey(toolbarKey), findsNothing);

        await gesture.down(textOffsetToPosition(paragraph, 9));
        await tester.pump();
1607 1608
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 9));
1609 1610 1611 1612 1613 1614 1615 1616 1617

        await gesture.up();
        await tester.pump();

        // Context menu toggled on.
        expect(buttonTypes.length, 1);
        expect(buttonTypes, contains(ContextMenuButtonType.selectAll));
        expect(find.byKey(toolbarKey), findsOneWidget);

1618 1619
        // Collapse selection.
        await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 1));
1620
        await tester.pump();
1621 1622 1623 1624 1625
        await primaryMouseButtonGesture.up();
        await tester.pumpAndSettle(kDoubleTapTimeout);
        // Selection is collapsed.
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1));
1626 1627
        expect(find.byKey(toolbarKey), findsNothing);

1628
        await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 0));
1629
        await tester.pump();
1630
        await primaryMouseButtonGesture.moveTo(textOffsetToPosition(paragraph, 5));
1631 1632
        await tester.pump();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5));
1633
        await primaryMouseButtonGesture.up();
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
        await tester.pump();

        // Right click on previous selection should not collapse the selection.
        await gesture.down(textOffsetToPosition(paragraph, 2));
        await tester.pump();
        await gesture.up();
        await tester.pump();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5));
        expect(find.byKey(toolbarKey), findsOneWidget);

        // Right click anywhere outside previous selection should first toggle the context
        // menu off.
        await gesture.down(textOffsetToPosition(paragraph, 7));
        await tester.pump();
        await gesture.up();
        await tester.pump();
        expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5));
        expect(find.byKey(toolbarKey), findsNothing);

        // Right click again should collapse the selection and toggle the context
        // menu on.
        await gesture.down(textOffsetToPosition(paragraph, 7));
        await tester.pump();
        await gesture.up();
        await tester.pump();
1659 1660
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 7));
1661 1662
        expect(find.byKey(toolbarKey), findsOneWidget);

1663 1664
        // Collapse selection.
        await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 1));
1665
        await tester.pump();
1666 1667 1668 1669 1670
        await primaryMouseButtonGesture.up();
        await tester.pumpAndSettle();
        // Selection is collapsed.
        expect(paragraph.selections.isEmpty, false);
        expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1));
1671 1672 1673 1674 1675 1676
        expect(find.byKey(toolbarKey), findsNothing);
      },
      variant: TargetPlatformVariant.only(TargetPlatform.linux),
      skip: kIsWeb, // [intended] Web uses its native context menu.
    );

1677
    testWidgets('can copy a selection made with the mouse', (WidgetTester tester) async {
1678 1679 1680
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

1681 1682 1683
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
1684
            focusNode: focusNode,
1685
            selectionControls: materialTextSelectionControls,
1686 1687
            child: const Column(
              children: <Widget>[
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      // Select from offset 2 of paragraph 1 to offset 6 of paragraph3.
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();

      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph3, 6));
      await gesture.up();

      // keyboard copy.
1707
      await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true));
1708 1709 1710 1711 1712

      final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>;
      expect(clipboardData['text'], 'w are you?Good, and you?Fine, ');
    }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }));

1713
    testWidgets(
1714 1715 1716
      'does not override TextField keyboard shortcuts if the TextField is focused - non apple',
      (WidgetTester tester) async {
        final TextEditingController controller = TextEditingController(text: 'I am fine, thank you.');
1717
        addTearDown(controller.dispose);
1718
        final FocusNode selectableRegionFocus = FocusNode();
1719
        addTearDown(selectableRegionFocus.dispose);
1720
        final FocusNode textFieldFocus = FocusNode();
1721 1722
        addTearDown(textFieldFocus.dispose);

1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
        await tester.pumpWidget(
          MaterialApp(
            home: Material(
              child: SelectableRegion(
                focusNode: selectableRegionFocus,
                selectionControls: materialTextSelectionControls,
                child: Column(
                  children: <Widget>[
                    const Text('How are you?'),
                    const Text('Good, and you?'),
                    TextField(controller: controller, focusNode: textFieldFocus),
                  ],
                ),
              ),
            ),
          ),
        );
        textFieldFocus.requestFocus();
        await tester.pump();

        // Make sure keyboard select all works on TextField.
1744
        await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true));
1745 1746 1747 1748 1749 1750 1751 1752
        expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 21));

        // Make sure no selection in SelectableRegion.
        final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
        final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
        expect(paragraph1.selections.isEmpty, isTrue);
        expect(paragraph2.selections.isEmpty, isTrue);

1753
        // Focus selectable region.
1754 1755 1756
        selectableRegionFocus.requestFocus();
        await tester.pump();

1757 1758 1759
        // Reset controller selection once the TextField is unfocused.
        controller.selection = const TextSelection.collapsed(offset: -1);

1760
        // Make sure keyboard select all will be handled by selectable region now.
1761
        await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true));
1762 1763 1764 1765 1766 1767 1768 1769
        expect(controller.selection, const TextSelection.collapsed(offset: -1));
        expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14));
        expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12));
      },
      variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }),
      skip: kIsWeb, // [intended] the web handles this on its own.
    );

1770
    testWidgets(
1771 1772 1773
      'does not override TextField keyboard shortcuts if the TextField is focused - apple',
      (WidgetTester tester) async {
        final TextEditingController controller = TextEditingController(text: 'I am fine, thank you.');
1774
        addTearDown(controller.dispose);
1775
        final FocusNode selectableRegionFocus = FocusNode();
1776
        addTearDown(selectableRegionFocus.dispose);
1777
        final FocusNode textFieldFocus = FocusNode();
1778 1779
        addTearDown(textFieldFocus.dispose);

1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
        await tester.pumpWidget(
          MaterialApp(
            home: Material(
              child: SelectableRegion(
                focusNode: selectableRegionFocus,
                selectionControls: materialTextSelectionControls,
                child: Column(
                  children: <Widget>[
                    const Text('How are you?'),
                    const Text('Good, and you?'),
                    TextField(controller: controller, focusNode: textFieldFocus),
                  ],
                ),
              ),
            ),
          ),
        );
        textFieldFocus.requestFocus();
        await tester.pump();

        // Make sure keyboard select all works on TextField.
1801
        await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, meta: true));
1802 1803 1804 1805 1806 1807 1808 1809
        expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 21));

        // Make sure no selection in SelectableRegion.
        final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
        final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
        expect(paragraph1.selections.isEmpty, isTrue);
        expect(paragraph2.selections.isEmpty, isTrue);

1810
        // Focus selectable region.
1811 1812 1813
        selectableRegionFocus.requestFocus();
        await tester.pump();

1814 1815 1816
        // Reset controller selection once the TextField is unfocused.
        controller.selection = const TextSelection.collapsed(offset: -1);

1817
        // Make sure keyboard select all will be handled by selectable region now.
1818
        await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, meta: true));
1819 1820 1821 1822 1823 1824 1825 1826
        expect(controller.selection, const TextSelection.collapsed(offset: -1));
        expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14));
        expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12));
      },
      variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }),
      skip: kIsWeb, // [intended] the web handles this on its own.
    );

1827
    testWidgets('select all', (WidgetTester tester) async {
1828
      final FocusNode focusNode = FocusNode();
1829 1830
      addTearDown(focusNode.dispose);

1831 1832 1833 1834 1835
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
            focusNode: focusNode,
            selectionControls: materialTextSelectionControls,
1836 1837
            child: const Column(
              children: <Widget>[
1838 1839 1840 1841 1842 1843 1844 1845
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
1846
      await tester.pumpAndSettle();
1847 1848 1849
      focusNode.requestFocus();

      // keyboard select all.
1850
      await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true));
1851 1852 1853 1854 1855 1856 1857 1858 1859

      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 16));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14));
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12));
    }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }));

1860
    testWidgets(
1861 1862
      'mouse selection can handle widget span', (WidgetTester tester) async {
      final UniqueKey outerText = UniqueKey();
1863 1864 1865
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

1866 1867 1868
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
1869
            focusNode: focusNode,
1870 1871 1872 1873
            selectionControls: materialTextSelectionControls,
            child: Center(
              child: Text.rich(
                const TextSpan(
1874 1875 1876 1877 1878
                  children: <InlineSpan>[
                    TextSpan(text: 'How are you?'),
                    WidgetSpan(child: Text('Good, and you?')),
                    TextSpan(text: 'Fine, thank you.'),
                  ],
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
                ),
                key: outerText,
              ),
            ),
          ),
        ),
      );
      final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first);
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`.
      await gesture.up();

      // keyboard copy.
1894
      await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true));
1895 1896 1897 1898 1899 1900 1901
      final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>;
      expect(clipboardData['text'], 'w are you?Good, and you?Fine');
    },
      variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }),
      skip: isBrowser, // https://github.com/flutter/flutter/issues/61020
    );

1902
    testWidgets(
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
      'double click + drag mouse selection can handle widget span', (WidgetTester tester) async {
      final UniqueKey outerText = UniqueKey();
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
            focusNode: focusNode,
            selectionControls: materialTextSelectionControls,
            child: Center(
              child: Text.rich(
                const TextSpan(
                  children: <InlineSpan>[
                    TextSpan(text: 'How are you?'),
                    WidgetSpan(child: Text('Good, and you?')),
                    TextSpan(text: 'Fine, thank you.'),
                  ],
                ),
                key: outerText,
              ),
            ),
          ),
        ),
      );
      final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first);
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 0), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.up();
      await tester.pump();

      await gesture.down(textOffsetToPosition(paragraph, 0));
      await tester.pump();
      await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`.
      await gesture.up();

      // keyboard copy.
      await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true));
      final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>;
      expect(clipboardData['text'], 'How are you?Good, and you?Fine,');
    },
      variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }),
      skip: isBrowser, // https://github.com/flutter/flutter/issues/61020
    );

1949
    testWidgets(
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
      'double click + drag mouse selection can handle widget span - multiline', (WidgetTester tester) async {
      final UniqueKey outerText = UniqueKey();
      final UniqueKey innerText = UniqueKey();
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
            focusNode: focusNode,
            selectionControls: materialTextSelectionControls,
            child: Center(
              child: Text.rich(
                TextSpan(
                  children: <InlineSpan>[
                    const TextSpan(text: 'How are you\n?'),
                    WidgetSpan(
                      child: Text(
                        'Good, and you?',
                        key: innerText,
                      ),
                    ),
                    const TextSpan(text: 'Fine, thank you.'),
                  ],
                ),
                key: outerText,
              ),
            ),
          ),
        ),
      );
      final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first);
      final RenderParagraph innerParagraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(innerText), matching: find.byType(RichText)).first);
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 0), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.up();
      await tester.pump();

      await gesture.down(textOffsetToPosition(paragraph, 0));
      await tester.pump();
      await gesture.moveTo(textOffsetToPosition(innerParagraph, 2)); // on `Good`.

      // Should not crash.
      expect(tester.takeException(), isNull);
    },
      variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }),
      skip: isBrowser, // https://github.com/flutter/flutter/issues/61020
    );

2000
    testWidgets(
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
      'select word event can select inline widget', (WidgetTester tester) async {
      final UniqueKey outerText = UniqueKey();
      final UniqueKey innerText = UniqueKey();
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
            focusNode: focusNode,
            selectionControls: materialTextSelectionControls,
            child: Center(
              child: Text.rich(
                TextSpan(
                  children: <InlineSpan>[
                    const TextSpan(text: 'How are\n you?'),
                    WidgetSpan(
                      child: Text(
                        'Good, and you?',
                        key: innerText,
                      ),
                    ),
                    const TextSpan(text: 'Fine, thank you.'),
                  ],
                ),
                key: outerText,
              ),
            ),
          ),
        ),
      );
      final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first);
      final RenderParagraph innerParagraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(innerText), matching: find.byType(RichText)).first);
      final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(innerText)), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.up();
      await tester.pump();

      // Should select "and".
      expect(paragraph.selections.isEmpty, isTrue);
      expect(innerParagraph.selections[0], const TextSelection(baseOffset: 6, extentOffset: 9));
    },
      variant: TargetPlatformVariant.only(TargetPlatform.macOS),
      skip: isBrowser, // https://github.com/flutter/flutter/issues/61020
    );

2048
    testWidgets(
2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
      'select word event should not crash when its position is at an unselectable inline element', (WidgetTester tester) async {
      final FocusNode focusNode = FocusNode();
      final UniqueKey flutterLogo = UniqueKey();
      addTearDown(focusNode.dispose);

      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
            focusNode: focusNode,
            selectionControls: materialTextSelectionControls,
            child: Scaffold(
              body: Center(
                child: Text.rich(
                  TextSpan(
                    children: <InlineSpan>[
                      const TextSpan(
                        text:
                            'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
                      ),
                      WidgetSpan(child: FlutterLogo(key: flutterLogo)),
                      const TextSpan(text: 'Hello, world.'),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      );
      final Offset gestureOffset = tester.getCenter(find.byKey(flutterLogo).first);

2080
      // Right click on unselectable element.
2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
      final TestGesture gesture = await tester.startGesture(gestureOffset, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.up();
      await tester.pump();

      // Should not crash.
      expect(tester.takeException(), isNull);
    },
      variant: TargetPlatformVariant.only(TargetPlatform.macOS),
      skip: isBrowser, // https://github.com/flutter/flutter/issues/61020
    );

2094
    testWidgets(
2095 2096 2097
      'can select word when a selectables rect is completely inside of another selectables rect', (WidgetTester tester) async {
      // Regression test for https://github.com/flutter/flutter/issues/127076.
      final UniqueKey outerText = UniqueKey();
2098 2099 2100
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2101 2102 2103
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
2104
            focusNode: focusNode,
2105 2106 2107 2108 2109
            selectionControls: materialTextSelectionControls,
            child: Scaffold(
              body: Center(
                child: Text.rich(
                  const TextSpan(
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
                    children: <InlineSpan>[
                      TextSpan(
                        text:
                            'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
                      ),
                      WidgetSpan(child: Text('Some text in a WidgetSpan. ')),
                      TextSpan(text: 'Hello, world.'),
                    ],
                  ),
                  key: outerText,
                ),
              ),
            ),
          ),
        ),
      );
      final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first);

      // Adjust `textOffsetToPosition` result because it returns the wrong vertical position (wrong line).
      // TODO(bleroux): Remove when https://github.com/flutter/flutter/issues/133637 is fixed.
      final Offset gestureOffset = textOffsetToPosition(paragraph, 125).translate(0, 10);

      // Right click to select word at position.
      final TestGesture gesture = await tester.startGesture(gestureOffset, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.up();
      await tester.pump();
      // Should select "Hello".
      expect(paragraph.selections[0], const TextSelection(baseOffset: 124, extentOffset: 129));
    },
      variant: TargetPlatformVariant.only(TargetPlatform.macOS),
      skip: isBrowser, // https://github.com/flutter/flutter/issues/61020
    );

2145
    testWidgets(
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
      'can select word when selectable is broken up by an unselectable WidgetSpan', (WidgetTester tester) async {
      final UniqueKey outerText = UniqueKey();
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
            focusNode: focusNode,
            selectionControls: materialTextSelectionControls,
            child: Scaffold(
              body: Center(
                child: Text.rich(
                  const TextSpan(
                    children: <InlineSpan>[
                      TextSpan(
                        text:
                            'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
                      ),
                      WidgetSpan(child: SizedBox.shrink()),
                      TextSpan(text: 'Hello, world.'),
                    ],
2168 2169 2170 2171 2172 2173 2174 2175 2176
                  ),
                  key: outerText,
                ),
              ),
            ),
          ),
        ),
      );
      final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first);
2177 2178 2179 2180 2181

      // Adjust `textOffsetToPosition` result because it returns the wrong vertical position (wrong line).
      // TODO(bleroux): Remove when https://github.com/flutter/flutter/issues/133637 is fixed.
      final Offset gestureOffset = textOffsetToPosition(paragraph, 125).translate(0, 10);

2182
      // Right click to select word at position.
2183
      final TestGesture gesture = await tester.startGesture(gestureOffset, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton);
2184 2185 2186 2187 2188 2189 2190
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.up();
      await tester.pump();
      // Should select "Hello".
      expect(paragraph.selections[0], const TextSelection(baseOffset: 124, extentOffset: 129));
    },
2191
      variant: TargetPlatformVariant.only(TargetPlatform.macOS),
2192 2193 2194
      skip: isBrowser, // https://github.com/flutter/flutter/issues/61020
    );

2195
    testWidgets(
2196 2197 2198
      'widget span is ignored if it does not contain text - non Apple',
      (WidgetTester tester) async {
        final UniqueKey outerText = UniqueKey();
2199 2200 2201
        final FocusNode focusNode = FocusNode();
        addTearDown(focusNode.dispose);

2202 2203 2204
        await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
2205
              focusNode: focusNode,
2206 2207 2208 2209
              selectionControls: materialTextSelectionControls,
              child: Center(
                child: Text.rich(
                  const TextSpan(
2210 2211 2212 2213 2214
                    children: <InlineSpan>[
                      TextSpan(text: 'How are you?'),
                      WidgetSpan(child: Placeholder()),
                      TextSpan(text: 'Fine, thank you.'),
                    ],
2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
                  ),
                  key: outerText,
                ),
              ),
            ),
          ),
        );
        final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first);
        final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse);
        addTearDown(gesture.removePointer);
        await tester.pump();
        await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`.
        await gesture.up();

        // keyboard copy.
2230
        await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true));
2231 2232 2233 2234 2235 2236 2237
        final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>;
        expect(clipboardData['text'], 'w are you?Fine');
      },
      variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }),
      skip: isBrowser, // https://github.com/flutter/flutter/issues/61020
    );

2238
    testWidgets(
2239 2240 2241
      'widget span is ignored if it does not contain text - Apple',
          (WidgetTester tester) async {
        final UniqueKey outerText = UniqueKey();
2242 2243 2244
        final FocusNode focusNode = FocusNode();
        addTearDown(focusNode.dispose);

2245 2246 2247
        await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
2248
              focusNode: focusNode,
2249 2250 2251 2252
              selectionControls: materialTextSelectionControls,
              child: Center(
                child: Text.rich(
                  const TextSpan(
2253 2254 2255 2256 2257
                    children: <InlineSpan>[
                      TextSpan(text: 'How are you?'),
                      WidgetSpan(child: Placeholder()),
                      TextSpan(text: 'Fine, thank you.'),
                    ],
2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
                  ),
                  key: outerText,
                ),
              ),
            ),
          ),
        );
        final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first);
        final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse);
        addTearDown(gesture.removePointer);
        await tester.pump();
        await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`.
        await gesture.up();

        // keyboard copy.
2273
        await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, meta: true));
2274 2275 2276 2277 2278 2279 2280
        final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>;
        expect(clipboardData['text'], 'w are you?Fine');
      },
      variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }),
      skip: isBrowser, // https://github.com/flutter/flutter/issues/61020
    );

2281
    testWidgets('mouse can select across bidi text', (WidgetTester tester) async {
2282 2283 2284
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2285 2286 2287
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
2288
            focusNode: focusNode,
2289
            selectionControls: materialTextSelectionControls,
2290 2291
            child: const Column(
              children: <Widget>[
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
                Text('How are you?'),
                Text('جيد وانت؟', textDirection: TextDirection.rtl),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();

      await gesture.moveTo(textOffsetToPosition(paragraph1, 4));
      await tester.pump();
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4));

      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('جيد وانت؟'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph2, 5));
      // Should select the rest of paragraph 1.
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5));

      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      // Add a little offset to cross the boundary between paragraph 2 and 3.
      await gesture.moveTo(textOffsetToPosition(paragraph3, 6) + const Offset(0, 1));
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12));
2319
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 9));
2320 2321 2322 2323 2324
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6));

      await gesture.up();
    }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61020

2325
    testWidgets('long press and drag touch moves selection word by word', (WidgetTester tester) async {
2326 2327 2328
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2329 2330 2331
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
2332
            focusNode: focusNode,
2333
            selectionControls: materialTextSelectionControls,
2334 2335
            child: const Column(
              children: <Widget>[
2336 2337 2338 2339 2340 2341 2342 2343
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
2344
      await tester.pumpAndSettle();
2345 2346 2347 2348 2349 2350 2351 2352
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 6)); // at the 'r'
      addTearDown(gesture.removePointer);
      await tester.pump(const Duration(milliseconds: 500));
      // `are` is selected.
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7));

      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
2353
      await gesture.moveTo(textOffsetToPosition(paragraph2, 7));
2354
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 12));
2355
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 9));
2356 2357 2358
      await gesture.up();
    });

2359
    testWidgets('can drag end handle when not covering entire screen', (WidgetTester tester) async {
2360
      // Regression test for https://github.com/flutter/flutter/issues/104620.
2361 2362 2363
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2364 2365
      await tester.pumpWidget(
        MaterialApp(
2366 2367 2368 2369
          home: Column(
            children: <Widget>[
              const Text('How are you?'),
              SelectableRegion(
2370
                focusNode: focusNode,
2371 2372 2373 2374 2375
                selectionControls: materialTextSelectionControls,
                child: const Text('Good, and you?'),
              ),
              const Text('Fine, thank you.'),
            ],
2376 2377 2378
          ),
        ),
      );
2379
      await tester.pumpAndSettle();
2380

2381 2382
      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph2, 7)); // at the 'a'
2383 2384 2385 2386
      addTearDown(gesture.removePointer);
      await tester.pump(const Duration(milliseconds: 500));
      await gesture.up();
      await tester.pump(const Duration(milliseconds: 500));
2387 2388
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 6, extentOffset: 9));
      final List<TextBox> boxes = paragraph2.getBoxesForSelection(paragraph2.selections[0]);
2389 2390
      expect(boxes.length, 1);

2391
      final Offset handlePos = globalize(boxes[0].toRect().bottomRight, paragraph2);
2392
      await gesture.down(handlePos);
2393 2394 2395 2396 2397 2398

      await gesture.moveTo(textOffsetToPosition(paragraph2, 11) + Offset(0, paragraph2.size.height / 2));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11));
      await gesture.up();
    });

2399
    testWidgets('can drag start handle when not covering entire screen', (WidgetTester tester) async {
2400
      // Regression test for https://github.com/flutter/flutter/issues/104620.
2401 2402 2403
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2404 2405 2406 2407 2408 2409
      await tester.pumpWidget(
        MaterialApp(
          home: Column(
            children: <Widget>[
              const Text('How are you?'),
              SelectableRegion(
2410
                focusNode: focusNode,
2411 2412 2413 2414 2415 2416 2417 2418
                selectionControls: materialTextSelectionControls,
                child: const Text('Good, and you?'),
              ),
              const Text('Fine, thank you.'),
            ],
          ),
        ),
      );
2419
      await tester.pumpAndSettle();
2420
      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
2421 2422 2423 2424 2425 2426 2427 2428
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph2, 7)); // at the 'a'
      addTearDown(gesture.removePointer);
      await tester.pump(const Duration(milliseconds: 500));
      await gesture.up();
      await tester.pump(const Duration(milliseconds: 500));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 6, extentOffset: 9));
      final List<TextBox> boxes = paragraph2.getBoxesForSelection(paragraph2.selections[0]);
      expect(boxes.length, 1);
2429

2430 2431 2432 2433 2434
      final Offset handlePos = globalize(boxes[0].toRect().bottomLeft, paragraph2);
      await gesture.down(handlePos);

      await gesture.moveTo(textOffsetToPosition(paragraph2, 11) + Offset(0, paragraph2.size.height / 2));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 11, extentOffset: 9));
2435 2436 2437
      await gesture.up();
    });

2438
    testWidgets('can drag start selection handle', (WidgetTester tester) async {
2439 2440 2441
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2442 2443 2444
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
2445
            focusNode: focusNode,
2446
            selectionControls: materialTextSelectionControls,
2447 2448
            child: const Column(
              children: <Widget>[
2449 2450 2451 2452 2453 2454 2455 2456
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
2457
      await tester.pumpAndSettle();
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482
      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h'
      addTearDown(gesture.removePointer);
      await tester.pump(const Duration(milliseconds: 500));
      await gesture.up();
      await tester.pump(const Duration(milliseconds: 500));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11));
      final List<TextBox> boxes = paragraph3.getBoxesForSelection(paragraph3.selections[0]);
      expect(boxes.length, 1);

      final Offset handlePos = globalize(boxes[0].toRect().bottomLeft, paragraph3);
      await gesture.down(handlePos);
      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph2, 5) + Offset(0, paragraph2.size.height / 2));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 5, extentOffset: 14));

      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      await gesture.moveTo(textOffsetToPosition(paragraph1, 6) + Offset(0, paragraph1.size.height / 2));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14));
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 6, extentOffset: 12));
      await gesture.up();
    });

2483
    testWidgets('can drag start selection handle across end selection handle', (WidgetTester tester) async {
2484 2485 2486
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2487 2488 2489
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
2490
            focusNode: focusNode,
2491
            selectionControls: materialTextSelectionControls,
2492 2493
            child: const Column(
              children: <Widget>[
2494 2495 2496 2497 2498 2499 2500 2501
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
2502
      await tester.pumpAndSettle();
2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h'
      addTearDown(gesture.removePointer);
      await tester.pump(const Duration(milliseconds: 500));
      await gesture.up();
      await tester.pump(const Duration(milliseconds: 500));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11));
      final List<TextBox> boxes = paragraph3.getBoxesForSelection(paragraph3.selections[0]);
      expect(boxes.length, 1);

      final Offset handlePos = globalize(boxes[0].toRect().bottomLeft, paragraph3);
      await gesture.down(handlePos);
      await gesture.moveTo(textOffsetToPosition(paragraph3, 14) + Offset(0, paragraph3.size.height / 2));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 14, extentOffset: 11));

      await gesture.moveTo(textOffsetToPosition(paragraph3, 4) + Offset(0, paragraph3.size.height / 2));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 4, extentOffset: 11));
      await gesture.up();
    });

2523
    testWidgets('can drag end selection handle across start selection handle', (WidgetTester tester) async {
2524 2525 2526
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2527 2528 2529
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
2530
            focusNode: focusNode,
2531
            selectionControls: materialTextSelectionControls,
2532 2533
            child: const Column(
              children: <Widget>[
2534 2535 2536 2537 2538 2539 2540 2541
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
2542
      await tester.pumpAndSettle();
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h'
      addTearDown(gesture.removePointer);
      await tester.pump(const Duration(milliseconds: 500));
      await gesture.up();
      await tester.pump(const Duration(milliseconds: 500));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11));
      final List<TextBox> boxes = paragraph3.getBoxesForSelection(paragraph3.selections[0]);
      expect(boxes.length, 1);

      final Offset handlePos = globalize(boxes[0].toRect().bottomRight, paragraph3);
      await gesture.down(handlePos);
      await gesture.moveTo(textOffsetToPosition(paragraph3, 4) + Offset(0, paragraph3.size.height / 2));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 4));

      await gesture.moveTo(textOffsetToPosition(paragraph3, 12) + Offset(0, paragraph3.size.height / 2));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 12));
      await gesture.up();
    });

2563
    testWidgets('can select all from toolbar', (WidgetTester tester) async {
2564 2565 2566
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2567 2568 2569
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
2570
            focusNode: focusNode,
2571
            selectionControls: materialTextSelectionControls,
2572 2573
            child: const Column(
              children: <Widget>[
2574 2575 2576 2577 2578 2579 2580 2581
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
2582
      await tester.pumpAndSettle();
2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h'
      addTearDown(gesture.removePointer);
      await tester.pump(const Duration(milliseconds: 500));
      await gesture.up();
      await tester.pump(const Duration(milliseconds: 500));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11));
      expect(find.text('Select all'), findsOneWidget);

      await tester.tap(find.text('Select all'));
      await tester.pump();

      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 16));
      expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14));
      expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12));
    }, skip: kIsWeb); // [intended] Web uses its native context menu.

2602
    testWidgets('can copy from toolbar', (WidgetTester tester) async {
2603 2604 2605
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2606 2607 2608
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
2609
            focusNode: focusNode,
2610
            selectionControls: materialTextSelectionControls,
2611 2612
            child: const Column(
              children: <Widget>[
2613 2614 2615 2616 2617 2618 2619 2620
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
2621
      await tester.pumpAndSettle();
2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643
      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h'
      addTearDown(gesture.removePointer);
      await tester.pump(const Duration(milliseconds: 500));
      await gesture.up();
      await tester.pump(const Duration(milliseconds: 500));
      expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11));
      expect(find.text('Copy'), findsOneWidget);

      await tester.tap(find.text('Copy'));
      await tester.pump();

      // Selection should be cleared.
      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      expect(paragraph3.selections.isEmpty, isTrue);
      expect(paragraph2.selections.isEmpty, isTrue);
      expect(paragraph1.selections.isEmpty, isTrue);

      final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>;
      expect(clipboardData['text'], 'thank');
    }, skip: kIsWeb); // [intended] Web uses its native context menu.
2644

2645
    testWidgets('can use keyboard to granularly extend selection - character', (WidgetTester tester) async {
2646 2647 2648
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2649 2650 2651
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
2652
            focusNode: focusNode,
2653
            selectionControls: materialTextSelectionControls,
2654 2655
            child: const Column(
              children: <Widget>[
2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      // Select from offset 2 of paragraph1 to offset 6 of paragraph1.
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.moveTo(textOffsetToPosition(paragraph1, 6));
      await gesture.up();
      await tester.pump();

      // Ho[w ar]e you?
      // Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 6);

      await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true));
      await tester.pump();
      // Ho[w are] you?
      // Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 7);

      for (int i = 0; i < 5; i += 1) {
        await sendKeyCombination(tester,
            const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true));
        await tester.pump();
        expect(paragraph1.selections.length, 1);
        expect(paragraph1.selections[0].start, 2);
        expect(paragraph1.selections[0].end, 8 + i);
      }

      for (int i = 0; i < 5; i += 1) {
        await sendKeyCombination(tester,
            const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true));
        await tester.pump();
        expect(paragraph1.selections.length, 1);
        expect(paragraph1.selections[0].start, 2);
        expect(paragraph1.selections[0].end, 11 - i);
      }
    }, variant: TargetPlatformVariant.all());

2708
    testWidgets('can use keyboard to granularly extend selection - word', (WidgetTester tester) async {
2709 2710 2711
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2712 2713 2714
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
2715
            focusNode: focusNode,
2716
            selectionControls: materialTextSelectionControls,
2717 2718
            child: const Column(
              children: <Widget>[
2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      // Select from offset 2 of paragraph1 to offset 6 of paragraph1.
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.moveTo(textOffsetToPosition(paragraph1, 6));
      await gesture.up();
      await tester.pump();

      final bool alt;
      final bool control;
2738
      switch (defaultTargetPlatform) {
2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
        case TargetPlatform.android:
        case TargetPlatform.fuchsia:
        case TargetPlatform.linux:
        case TargetPlatform.windows:
          alt = false;
          control = true;
        case TargetPlatform.iOS:
        case TargetPlatform.macOS:
          alt = true;
          control = false;
      }

      // Ho[w ar]e you?
      // Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 6);

      await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control));
      await tester.pump();
      // Ho[w are] you?
      // Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 7);

      await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control));
      await tester.pump();
      // Ho[w are you]?
      // Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 11);

      await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control));
      await tester.pump();
      // Ho[w are you?]
      // Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 12);

      await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control));
      await tester.pump();
      // Ho[w are you?
      // Good], and you?
      // Fine, thank you.
      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 12);
      expect(paragraph2.selections.length, 1);
      expect(paragraph2.selections[0].start, 0);
      expect(paragraph2.selections[0].end, 4);

      await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, control: control));
      await tester.pump();
      // Ho[w are you?
      // ]Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 12);
2806 2807 2808
      expect(paragraph2.selections.length, 1);
      expect(paragraph2.selections[0].start, 0);
      expect(paragraph2.selections[0].end, 0);
2809 2810 2811

      await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, control: control));
      await tester.pump();
2812
      // Ho[w are ]you?
2813 2814 2815 2816
      // Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
2817
      expect(paragraph1.selections[0].end, 8);
2818 2819 2820
      expect(paragraph2.selections.length, 1);
      expect(paragraph2.selections[0].start, 0);
      expect(paragraph2.selections[0].end, 0);
2821 2822
    }, variant: TargetPlatformVariant.all());

2823
    testWidgets('can use keyboard to granularly extend selection - line', (WidgetTester tester) async {
2824 2825 2826
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2827 2828 2829
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
2830
            focusNode: focusNode,
2831
            selectionControls: materialTextSelectionControls,
2832 2833
            child: const Column(
              children: <Widget>[
2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      // Select from offset 2 of paragraph1 to offset 6 of paragraph1.
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.moveTo(textOffsetToPosition(paragraph1, 6));
      await gesture.up();
      await tester.pump();

      final bool alt;
      final bool meta;
2853
      switch (defaultTargetPlatform) {
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902
        case TargetPlatform.android:
        case TargetPlatform.fuchsia:
        case TargetPlatform.linux:
        case TargetPlatform.windows:
          meta = false;
          alt = true;
        case TargetPlatform.iOS:
        case TargetPlatform.macOS:
          meta = true;
          alt = false;
      }

      // Ho[w ar]e you?
      // Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 6);

      await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, meta: meta));
      await tester.pump();
      // Ho[w are you?]
      // Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 12);

      await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, meta: meta));
      await tester.pump();
      // Ho[w are you?
      // Good, and you?]
      // Fine, thank you.
      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 12);
      expect(paragraph2.selections.length, 1);
      expect(paragraph2.selections[0].start, 0);
      expect(paragraph2.selections[0].end, 14);

      await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, meta: meta));
      await tester.pump();
      // Ho[w are you?]
      // Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 12);
2903 2904 2905
      expect(paragraph2.selections.length, 1);
      expect(paragraph2.selections[0].start, 0);
      expect(paragraph2.selections[0].end, 0);
2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916

      await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, meta: meta));
      await tester.pump();
      // [Ho]w are you?
      // Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 0);
      expect(paragraph1.selections[0].end, 2);
    }, variant: TargetPlatformVariant.all());

2917
    testWidgets('can use keyboard to granularly extend selection - document', (WidgetTester tester) async {
2918 2919 2920
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

2921 2922 2923
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
2924
            focusNode: focusNode,
2925
            selectionControls: materialTextSelectionControls,
2926 2927
            child: const Column(
              children: <Widget>[
2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      // Select from offset 2 of paragraph1 to offset 6 of paragraph1.
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.moveTo(textOffsetToPosition(paragraph1, 6));
      await gesture.up();
      await tester.pump();

      final bool alt;
      final bool meta;
2947
      switch (defaultTargetPlatform) {
2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991
        case TargetPlatform.android:
        case TargetPlatform.fuchsia:
        case TargetPlatform.linux:
        case TargetPlatform.windows:
          meta = false;
          alt = true;
        case TargetPlatform.iOS:
        case TargetPlatform.macOS:
          meta = true;
          alt = false;
      }

      // Ho[w ar]e you?
      // Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 6);

      await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, meta: meta, alt: alt));
      await tester.pump();
      // Ho[w are you?
      // Good, and you?
      // Fine, thank you.]
      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 12);
      expect(paragraph2.selections.length, 1);
      expect(paragraph2.selections[0].start, 0);
      expect(paragraph2.selections[0].end, 14);
      expect(paragraph3.selections.length, 1);
      expect(paragraph3.selections[0].start, 0);
      expect(paragraph3.selections[0].end, 16);

      await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, meta: meta, alt: alt));
      await tester.pump();
      // [Ho]w are you?
      // Good, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 0);
      expect(paragraph1.selections[0].end, 2);
2992 2993 2994 2995 2996 2997
      expect(paragraph2.selections.length, 1);
      expect(paragraph2.selections[0].start, 0);
      expect(paragraph2.selections[0].end, 0);
      expect(paragraph3.selections.length, 1);
      expect(paragraph3.selections[0].start, 0);
      expect(paragraph3.selections[0].end, 0);
2998 2999
    }, variant: TargetPlatformVariant.all());

3000
    testWidgets('can use keyboard to directionally extend selection', (WidgetTester tester) async {
3001 3002 3003
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

3004 3005 3006
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
3007
            focusNode: focusNode,
3008
            selectionControls: materialTextSelectionControls,
3009 3010
            child: const Column(
              children: <Widget>[
3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067
                Text('How are you?'),
                Text('Good, and you?'),
                Text('Fine, thank you.'),
              ],
            ),
          ),
        ),
      );
      // Select from offset 2 of paragraph2 to offset 6 of paragraph2.
      final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
      final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph2, 2), kind: PointerDeviceKind.mouse);
      addTearDown(gesture.removePointer);
      await tester.pump();
      await gesture.moveTo(textOffsetToPosition(paragraph2, 6));
      await gesture.up();
      await tester.pump();

      // How are you?
      // Go[od, ]and you?
      // Fine, thank you.
      expect(paragraph2.selections.length, 1);
      expect(paragraph2.selections[0].start, 2);
      expect(paragraph2.selections[0].end, 6);

      await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true));
      await tester.pump();
      // How are you?
      // Go[od, and you?
      // Fine, t]hank you.
      final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
      expect(paragraph2.selections.length, 1);
      expect(paragraph2.selections[0].start, 2);
      expect(paragraph2.selections[0].end, 14);
      expect(paragraph3.selections.length, 1);
      expect(paragraph3.selections[0].start, 0);
      expect(paragraph3.selections[0].end, 7);

      await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true));
      await tester.pump();
      // How are you?
      // Go[od, and you?
      // Fine, thank you.]
      expect(paragraph2.selections.length, 1);
      expect(paragraph2.selections[0].start, 2);
      expect(paragraph2.selections[0].end, 14);
      expect(paragraph3.selections.length, 1);
      expect(paragraph3.selections[0].start, 0);
      expect(paragraph3.selections[0].end, 16);

      await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true));
      await tester.pump();
      // How are you?
      // Go[od, ]and you?
      // Fine, thank you.
      expect(paragraph2.selections.length, 1);
      expect(paragraph2.selections[0].start, 2);
      expect(paragraph2.selections[0].end, 6);
3068 3069 3070
      expect(paragraph3.selections.length, 1);
      expect(paragraph3.selections[0].start, 0);
      expect(paragraph3.selections[0].end, 0);
3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097

      await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true));
      await tester.pump();
      // How a[re you?
      // Go]od, and you?
      // Fine, thank you.
      final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 5);
      expect(paragraph1.selections[0].end, 12);
      expect(paragraph2.selections.length, 1);
      expect(paragraph2.selections[0].start, 0);
      expect(paragraph2.selections[0].end, 2);

      await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true));
      await tester.pump();
      // [How are you?
      // Go]od, and you?
      // Fine, thank you.
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 0);
      expect(paragraph1.selections[0].end, 12);
      expect(paragraph2.selections.length, 1);
      expect(paragraph2.selections[0].start, 0);
      expect(paragraph2.selections[0].end, 2);
    }, variant: TargetPlatformVariant.all());

3098
    group('magnifier', () {
3099
      late ValueNotifier<MagnifierInfo> magnifierInfo;
3100 3101
      final Widget fakeMagnifier = Container(key: UniqueKey());

3102
      testWidgets('Can drag handles to show, unshow, and update magnifier',
3103
          (WidgetTester tester) async {
Lioness100's avatar
Lioness100 committed
3104
        const String text = 'Monkeys and rabbits in my soup';
3105 3106
        final FocusNode focusNode = FocusNode();
        addTearDown(focusNode.dispose);
3107 3108 3109 3110 3111 3112 3113

        await tester.pumpWidget(
          MaterialApp(
            home: SelectableRegion(
              magnifierConfiguration: TextMagnifierConfiguration(
                magnifierBuilder: (_,
                    MagnifierController controller,
3114 3115 3116
                    ValueNotifier<MagnifierInfo>
                        localMagnifierInfo) {
                  magnifierInfo = localMagnifierInfo;
3117 3118 3119
                  return fakeMagnifier;
                },
              ),
3120
              focusNode: focusNode,
3121 3122 3123 3124 3125
              selectionControls: materialTextSelectionControls,
              child: const Text(text),
            ),
          ),
        );
3126
        await tester.pumpAndSettle();
3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151

        final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(
            find.descendant(
                of: find.text(text), matching: find.byType(RichText)));

        // Show the selection handles.
        final TestGesture activateSelectionGesture = await tester
            .startGesture(textOffsetToPosition(paragraph, text.length ~/ 2));
        addTearDown(activateSelectionGesture.removePointer);
        await tester.pump(const Duration(milliseconds: 500));
        await activateSelectionGesture.up();
        await tester.pump(const Duration(milliseconds: 500));

        // Drag the handle around so that the magnifier shows.
        final TextBox selectionBox =
            paragraph.getBoxesForSelection(paragraph.selections.first).first;
        final Offset leftHandlePos =
            globalize(selectionBox.toRect().bottomLeft, paragraph);
        final TestGesture gesture = await tester.startGesture(leftHandlePos);
        await gesture.moveTo(textOffsetToPosition(paragraph, text.length - 2));
        await tester.pump();

        // Expect the magnifier to show and then store it's position.
        expect(find.byKey(fakeMagnifier.key!), findsOneWidget);
        final Offset firstDragGesturePosition =
3152
            magnifierInfo.value.globalGesturePosition;
3153 3154 3155 3156 3157 3158

        await gesture.moveTo(textOffsetToPosition(paragraph, text.length));
        await tester.pump();

        // Expect the position the magnifier gets to have moved.
        expect(firstDragGesturePosition,
3159
            isNot(magnifierInfo.value.globalGesturePosition));
3160 3161 3162 3163 3164 3165 3166 3167

        // Lift the pointer and expect the magnifier to disappear.
        await gesture.up();
        await tester.pump();

        expect(find.byKey(fakeMagnifier.key!), findsNothing);
      });
    });
3168
  });
3169

3170
  testWidgets('toolbar is hidden on Android and iOS when orientation changes', (WidgetTester tester) async {
3171
    addTearDown(tester.view.reset);
3172 3173
    final FocusNode focusNode = FocusNode();
    addTearDown(focusNode.dispose);
3174

3175 3176 3177
    await tester.pumpWidget(
      MaterialApp(
        home: SelectableRegion(
3178
          focusNode: focusNode,
3179 3180 3181 3182 3183
          selectionControls: materialTextSelectionControls,
          child: const Text('How are you?'),
        ),
      ),
    );
3184
    await tester.pumpAndSettle();
3185 3186 3187 3188 3189 3190 3191 3192

    final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
    final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 6)); // at the 'r'
    addTearDown(gesture.removePointer);
    await tester.pump(const Duration(milliseconds: 500));
    // `are` is selected.
    expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7));
    await tester.pumpAndSettle();
3193 3194 3195

    await gesture.up();
    await tester.pumpAndSettle();
3196 3197 3198 3199
    // Text selection toolbar has appeared.
    expect(find.text('Copy'), findsOneWidget);

    // Hide the toolbar by changing orientation.
3200
    tester.view.physicalSize = const Size(1800.0, 2400.0);
3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213
    await tester.pumpAndSettle();
    expect(find.text('Copy'), findsNothing);

    // Handles should be hidden as well on Android
    expect(
      find.descendant(
        of: find.byType(CompositedTransformFollower),
        matching: find.byType(Padding),
      ),
      defaultTargetPlatform == TargetPlatform.android ? findsNothing : findsNWidgets(2),
    );
  },
    variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android }),
3214
    skip: kIsWeb, // [intended] Web uses its native context menu.
3215
  );
3216

3217
  testWidgets('the selection behavior when clicking `Copy` item in mobile platforms', (WidgetTester tester) async {
3218
    List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[];
3219 3220 3221
    final FocusNode focusNode = FocusNode();
    addTearDown(focusNode.dispose);

3222 3223 3224
    await tester.pumpWidget(
      MaterialApp(
        home: SelectableRegion(
3225
          focusNode: focusNode,
3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237
          selectionControls: materialTextSelectionHandleControls,
          contextMenuBuilder: (
            BuildContext context,
            SelectableRegionState selectableRegionState,
          ) {
            buttonItems = selectableRegionState.contextMenuButtonItems;
            return const SizedBox.shrink();
          },
          child: const Text('How are you?'),
        ),
      ),
    );
3238
    await tester.pumpAndSettle();
3239 3240 3241 3242 3243 3244 3245

    final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
    await tester.longPressAt(textOffsetToPosition(paragraph1, 6)); // at the 'r'
    await tester.pump(kLongPressTimeout);
    // `are` is selected.
    expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7));

3246
    // Press `Copy` item.
3247
    expect(buttonItems[0].type, ContextMenuButtonType.copy);
3248
    buttonItems[0].onPressed?.call();
3249 3250 3251 3252

    final SelectableRegionState regionState = tester.state<SelectableRegionState>(find.byType(SelectableRegion));

    // In Android copy should clear the selection.
3253
    switch (defaultTargetPlatform) {
3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
        expect(regionState.selectionOverlay, isNull);
        expect(regionState.selectionOverlay?.startHandleLayerLink, isNull);
        expect(regionState.selectionOverlay?.endHandleLayerLink, isNull);
      case TargetPlatform.iOS:
        expect(regionState.selectionOverlay, isNotNull);
        expect(regionState.selectionOverlay?.startHandleLayerLink, isNotNull);
        expect(regionState.selectionOverlay?.endHandleLayerLink, isNotNull);
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
3266 3267
        // Test doesn't run these platforms.
        break;    }
3268
  },
3269 3270
    variant: TargetPlatformVariant.mobile(),
    skip: kIsWeb, // [intended] Web uses its native context menu.
3271 3272
  );

3273
  testWidgets('the handles do not disappear when clicking `Select all` item in mobile platforms', (WidgetTester tester) async {
3274
    List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[];
3275 3276 3277
    final FocusNode focusNode = FocusNode();
    addTearDown(focusNode.dispose);

3278 3279 3280
    await tester.pumpWidget(
      MaterialApp(
        home: SelectableRegion(
3281
          focusNode: focusNode,
3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293
          selectionControls: materialTextSelectionHandleControls,
          contextMenuBuilder: (
            BuildContext context,
            SelectableRegionState selectableRegionState,
          ) {
            buttonItems = selectableRegionState.contextMenuButtonItems;
            return const SizedBox.shrink();
          },
          child: const Text('How are you?'),
        ),
      ),
    );
3294
    await tester.pumpAndSettle();
3295 3296 3297 3298 3299 3300 3301

    final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
    await tester.longPressAt(textOffsetToPosition(paragraph1, 6)); // at the 'r'
    await tester.pump(kLongPressTimeout);
    // `are` is selected.
    expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7));

3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315
    late ContextMenuButtonItem selectAllButton;
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
        // On Android, the select all button is after the share button.
        expect(buttonItems[2].type, ContextMenuButtonType.selectAll);
        selectAllButton = buttonItems[2];
      case TargetPlatform.iOS:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
        expect(buttonItems[1].type, ContextMenuButtonType.selectAll);
        selectAllButton = buttonItems[1];
    }
3316

3317 3318
    // Press `Select All` item.
    selectAllButton.onPressed?.call();
3319 3320 3321

    final SelectableRegionState regionState = tester.state<SelectableRegionState>(find.byType(SelectableRegion));

3322
    switch (defaultTargetPlatform) {
3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334
      case TargetPlatform.android:
      case TargetPlatform.iOS:
      case TargetPlatform.fuchsia:
        expect(regionState.selectionOverlay, isNotNull);
        expect(regionState.selectionOverlay?.startHandleLayerLink, isNotNull);
        expect(regionState.selectionOverlay?.endHandleLayerLink, isNotNull);
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
        // Test doesn't run these platforms.
        break;
    }
3335 3336 3337 3338
  },
    variant: TargetPlatformVariant.mobile(),
    skip: kIsWeb, // [intended] Web uses its native context menu.
  );
3339

3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395
  testWidgets('Selection behavior when clicking the `Share` button on Android', (WidgetTester tester) async {
    List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[];
    final FocusNode focusNode = FocusNode();
    addTearDown(focusNode.dispose);

    await tester.pumpWidget(
      MaterialApp(
        home: SelectableRegion(
          focusNode: focusNode,
          selectionControls: materialTextSelectionHandleControls,
          contextMenuBuilder: (
            BuildContext context,
            SelectableRegionState selectableRegionState,
          ) {
            buttonItems = selectableRegionState.contextMenuButtonItems;
            return const SizedBox.shrink();
          },
          child: const Text('How are you?'),
        ),
      ),
    );
    await tester.pumpAndSettle();

    final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(
      find.descendant(
        of: find.text('How are you?'),
        matching: find.byType(RichText),
      ),
    );
    await tester.longPressAt(textOffsetToPosition(paragraph, 6)); // at the 'r'
    await tester.pump(kLongPressTimeout);

    // `are` is selected.
    expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7));

    String? lastShare;
    TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
        .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async {
      if (methodCall.method == 'Share.invoke') {
        expect(methodCall.arguments, isA<String>());
        lastShare = methodCall.arguments as String;
      }
      return null;
    });
    addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null));

    final SelectableRegionState regionState = tester.state<SelectableRegionState>(find.byType(SelectableRegion));

    // Press the `Share` button.
    expect(buttonItems[1].type, ContextMenuButtonType.share);
    buttonItems[1].onPressed?.call();
    expect(lastShare, 'are');
    // On Android, share should clear the selection.
    expect(regionState.selectionOverlay, isNull);
    expect(regionState.selectionOverlay?.startHandleLayerLink, isNull);
    expect(regionState.selectionOverlay?.endHandleLayerLink, isNull);
3396
  },
3397
    skip: kIsWeb, // [intended] Web uses its native context menu.
3398 3399
  );

3400
  testWidgets('builds the correct button items', (WidgetTester tester) async {
3401
    List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[];
3402 3403 3404
    final FocusNode focusNode = FocusNode();
    addTearDown(focusNode.dispose);

3405 3406 3407
    await tester.pumpWidget(
      MaterialApp(
        home: SelectableRegion(
3408
          focusNode: focusNode,
3409 3410 3411 3412 3413
          selectionControls: materialTextSelectionHandleControls,
          contextMenuBuilder: (
            BuildContext context,
            SelectableRegionState selectableRegionState,
          ) {
3414
            buttonItems = selectableRegionState.contextMenuButtonItems;
3415 3416 3417 3418 3419 3420
            return const SizedBox.shrink();
          },
          child: const Text('How are you?'),
        ),
      ),
    );
3421
    await tester.pumpAndSettle();
3422 3423 3424

    expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing);

3425 3426 3427 3428 3429 3430 3431
    final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(
      find.descendant(
        of: find.text('How are you?'),
        matching: find.byType(RichText),
      ),
    );
    final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 6)); // at the 'r'
3432 3433 3434
    addTearDown(gesture.removePointer);
    await tester.pump(const Duration(milliseconds: 500));
    // `are` is selected.
3435
    expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7));
3436 3437

    await gesture.up();
3438 3439
    await tester.pumpAndSettle();

3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
        // On Android, the share button is before the select all button.
        expect(buttonItems.length, 3);
        expect(buttonItems[0].type, ContextMenuButtonType.copy);
        expect(buttonItems[1].type, ContextMenuButtonType.share);
        expect(buttonItems[2].type, ContextMenuButtonType.selectAll);
      case TargetPlatform.iOS:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
        expect(buttonItems.length, 2);
        expect(buttonItems[0].type, ContextMenuButtonType.copy);
        expect(buttonItems[1].type, ContextMenuButtonType.selectAll);
    }
3456 3457
  },
    variant: TargetPlatformVariant.all(),
3458
    skip: kIsWeb, // [intended] Web uses its native context menu.
3459 3460
  );

3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511
  testWidgets('Text processing actions are added to the toolbar', (WidgetTester tester) async {
    final MockProcessTextHandler mockProcessTextHandler = MockProcessTextHandler();
    TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger
        .setMockMethodCallHandler(SystemChannels.processText, mockProcessTextHandler.handleMethodCall);
    addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, null));

    Set<String?> buttonLabels = <String?>{};
    final FocusNode focusNode = FocusNode();
    addTearDown(focusNode.dispose);

    await tester.pumpWidget(
      MaterialApp(
        home: SelectableRegion(
          focusNode: focusNode,
          selectionControls: materialTextSelectionHandleControls,
          contextMenuBuilder: (
            BuildContext context,
            SelectableRegionState selectableRegionState,
          ) {
            buttonLabels = selectableRegionState.contextMenuButtonItems
              .map((ContextMenuButtonItem buttonItem) => buttonItem.label)
              .toSet();
            return const SizedBox.shrink();
          },
          child: const Text('How are you?'),
        ),
      ),
    );
    await tester.pumpAndSettle();

    final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(
      find.descendant(
        of: find.text('How are you?'),
        matching: find.byType(RichText),
      ),
    );
    final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 6)); // at the 'r'
    addTearDown(gesture.removePointer);
    await tester.pump(const Duration(milliseconds: 500));
    // `are` is selected.
    expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7));

    await gesture.up();
    await tester.pumpAndSettle();

    // The text processing actions are available on Android only.
    final bool areTextActionsSupported = defaultTargetPlatform == TargetPlatform.android;
    expect(buttonLabels.contains(fakeAction1Label), areTextActionsSupported);
    expect(buttonLabels.contains(fakeAction2Label), areTextActionsSupported);
  },
    variant: TargetPlatformVariant.all(),
3512
    skip: kIsWeb, // [intended] Web uses its native context menu.
3513 3514
  );

3515
  testWidgets('onSelectionChange is called when the selection changes through gestures', (WidgetTester tester) async {
3516
    SelectedContent? content;
3517 3518
    final FocusNode focusNode = FocusNode();
    addTearDown(focusNode.dispose);
3519 3520 3521 3522 3523

    await tester.pumpWidget(
      MaterialApp(
        home: SelectableRegion(
          onSelectionChanged: (SelectedContent? selectedContent) => content = selectedContent,
3524
          focusNode: focusNode,
3525 3526 3527 3528 3529 3530 3531
          selectionControls: materialTextSelectionControls,
          child: const Center(
            child: Text('How are you'),
          ),
        ),
      ),
    );
3532

3533
    final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText)));
3534 3535 3536
    final TestGesture mouseGesture = await tester.startGesture(textOffsetToPosition(paragraph, 4), kind: PointerDeviceKind.mouse);
    final TestGesture touchGesture = await tester.createGesture();

3537
    expect(content, isNull);
3538 3539
    addTearDown(mouseGesture.removePointer);
    addTearDown(touchGesture.removePointer);
3540 3541
    await tester.pump();

3542 3543 3544
    // Called on drag.
    await mouseGesture.moveTo(textOffsetToPosition(paragraph, 7));
    await tester.pumpAndSettle();
3545 3546 3547
    expect(content, isNotNull);
    expect(content!.plainText, 'are');

3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559
    // Updates on drag.
    await mouseGesture.moveTo(textOffsetToPosition(paragraph, 10));
    await tester.pumpAndSettle();
    expect(content, isNotNull);
    expect(content!.plainText, 'are yo');

    // Called on drag end.
    await mouseGesture.up();
    await tester.pump();
    expect(content, isNotNull);
    expect(content!.plainText, 'are yo');

3560
    // Backwards selection.
3561
    await mouseGesture.down(textOffsetToPosition(paragraph, 3));
3562 3563 3564 3565 3566 3567 3568 3569
    await tester.pump();
    await mouseGesture.up();
    await tester.pumpAndSettle(kDoubleTapTimeout);
    expect(content, isNotNull);
    expect(content!.plainText, '');

    await mouseGesture.down(textOffsetToPosition(paragraph, 3));
    await tester.pump();
3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584

    await mouseGesture.moveTo(textOffsetToPosition(paragraph, 0));
    await tester.pumpAndSettle();
    expect(content, isNotNull);
    expect(content!.plainText, 'How');

    await mouseGesture.up();
    await tester.pump();
    expect(content, isNotNull);
    expect(content!.plainText, 'How');

    // Called on double tap.
    await mouseGesture.down(textOffsetToPosition(paragraph, 6));
    await tester.pump();
    await mouseGesture.up();
3585
    await tester.pump();
3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596
    await mouseGesture.down(textOffsetToPosition(paragraph, 6));
    await tester.pumpAndSettle();
    expect(content, isNotNull);
    expect(content!.plainText, 'are');
    await mouseGesture.up();
    await tester.pumpAndSettle();

    // Called on tap.
    await mouseGesture.down(textOffsetToPosition(paragraph, 0));
    await tester.pumpAndSettle();
    await mouseGesture.up();
3597 3598 3599
    await tester.pumpAndSettle(kDoubleTapTimeout);
    expect(content, isNotNull);
    expect(content!.plainText, '');
3600 3601 3602 3603 3604 3605

    // With touch gestures.

    // Called on long press start.
    await touchGesture.down(textOffsetToPosition(paragraph, 0));
    await tester.pumpAndSettle(kLongPressTimeout);
3606 3607
    expect(content, isNotNull);
    expect(content!.plainText, 'How');
3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655

    // Called on long press update.
    await touchGesture.moveTo(textOffsetToPosition(paragraph, 5));
    await tester.pumpAndSettle();
    expect(content, isNotNull);
    expect(content!.plainText, 'How are');

    // Called on long press end.
    await touchGesture.up();
    await tester.pumpAndSettle();
    expect(content, isNotNull);
    expect(content!.plainText, 'How are');

    // Long press to select 'you'.
    await touchGesture.down(textOffsetToPosition(paragraph, 9));
    await tester.pumpAndSettle(kLongPressTimeout);
    expect(content, isNotNull);
    expect(content!.plainText, 'you');
    await touchGesture.up();
    await tester.pumpAndSettle();

    // Called while moving selection handles.
    final List<TextBox> boxes = paragraph.getBoxesForSelection(paragraph.selections[0]);
    expect(boxes.length, 1);
    final Offset startHandlePos = globalize(boxes[0].toRect().bottomLeft, paragraph);
    final Offset endHandlePos = globalize(boxes[0].toRect().bottomRight, paragraph);
    final Offset startPos = Offset(textOffsetToPosition(paragraph, 4).dx, startHandlePos.dy);
    final Offset endPos = Offset(textOffsetToPosition(paragraph, 6).dx, endHandlePos.dy);

    // Start handle.
    await touchGesture.down(startHandlePos);
    await touchGesture.moveTo(startPos);
    await tester.pumpAndSettle();
    expect(content, isNotNull);
    expect(content!.plainText, 'are you');
    await touchGesture.up();
    await tester.pumpAndSettle();

    // End handle.
    await touchGesture.down(endHandlePos);
    await touchGesture.moveTo(endPos);
    await tester.pumpAndSettle();
    expect(content, isNotNull);
    expect(content!.plainText, 'ar');
    await touchGesture.up();
    await tester.pumpAndSettle();
  });

3656
  testWidgets('onSelectionChange is called when the selection changes through keyboard actions', (WidgetTester tester) async {
3657
    SelectedContent? content;
3658 3659
    final FocusNode focusNode = FocusNode();
    addTearDown(focusNode.dispose);
3660 3661 3662 3663 3664

    await tester.pumpWidget(
      MaterialApp(
        home: SelectableRegion(
          onSelectionChanged: (SelectedContent? selectedContent) => content = selectedContent,
3665
          focusNode: focusNode,
3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775
          selectionControls: materialTextSelectionControls,
          child: const Column(
            children: <Widget>[
              Text('How are you?'),
              Text('Good, and you?'),
              Text('Fine, thank you.'),
            ],
          ),
        ),
      ),
    );

    expect(content, isNull);
    await tester.pump();

    final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)));
    final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)));
    final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)));
    final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse);
    addTearDown(gesture.removePointer);
    await tester.pump();
    await gesture.moveTo(textOffsetToPosition(paragraph1, 6));
    await gesture.up();
    await tester.pump();

    expect(paragraph1.selections.length, 1);
    expect(paragraph1.selections[0].start, 2);
    expect(paragraph1.selections[0].end, 6);
    expect(content, isNotNull);
    expect(content!.plainText, 'w ar');

    await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true));
    await tester.pump();
    expect(paragraph1.selections.length, 1);
    expect(paragraph1.selections[0].start, 2);
    expect(paragraph1.selections[0].end, 7);
    expect(content, isNotNull);
    expect(content!.plainText, 'w are');

    for (int i = 0; i < 5; i += 1) {
      await sendKeyCombination(tester,
          const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true));
      await tester.pump();
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 8 + i);
      expect(content, isNotNull);
    }
    expect(content, isNotNull);
    expect(content!.plainText, 'w are you?');

    for (int i = 0; i < 5; i += 1) {
      await sendKeyCombination(tester,
          const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true));
      await tester.pump();
      expect(paragraph1.selections.length, 1);
      expect(paragraph1.selections[0].start, 2);
      expect(paragraph1.selections[0].end, 11 - i);
      expect(content, isNotNull);
    }
    expect(content, isNotNull);
    expect(content!.plainText, 'w are');

    await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true));
    await tester.pump();
    expect(paragraph1.selections.length, 1);
    expect(paragraph1.selections[0].start, 2);
    expect(paragraph1.selections[0].end, 12);
    expect(paragraph2.selections.length, 1);
    expect(paragraph2.selections[0].start, 0);
    expect(paragraph2.selections[0].end, 8);
    expect(content, isNotNull);
    expect(content!.plainText, 'w are you?Good, an');

    await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true));
    await tester.pump();
    expect(paragraph1.selections.length, 1);
    expect(paragraph1.selections[0].start, 2);
    expect(paragraph1.selections[0].end, 12);
    expect(paragraph2.selections.length, 1);
    expect(paragraph2.selections[0].start, 0);
    expect(paragraph2.selections[0].end, 14);
    expect(paragraph3.selections.length, 1);
    expect(paragraph3.selections[0].start, 0);
    expect(paragraph3.selections[0].end, 9);
    expect(content, isNotNull);
    expect(content!.plainText, 'w are you?Good, and you?Fine, tha');

    await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true));
    await tester.pump();
    expect(paragraph1.selections.length, 1);
    expect(paragraph1.selections[0].start, 2);
    expect(paragraph1.selections[0].end, 12);
    expect(paragraph2.selections.length, 1);
    expect(paragraph2.selections[0].start, 0);
    expect(paragraph2.selections[0].end, 14);
    expect(paragraph3.selections.length, 1);
    expect(paragraph3.selections[0].start, 0);
    expect(paragraph3.selections[0].end, 16);
    expect(content, isNotNull);
    expect(content!.plainText, 'w are you?Good, and you?Fine, thank you.');

    await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true));
    await tester.pump();
    expect(paragraph1.selections.length, 1);
    expect(paragraph1.selections[0].start, 2);
    expect(paragraph1.selections[0].end, 12);
    expect(paragraph2.selections.length, 1);
    expect(paragraph2.selections[0].start, 0);
    expect(paragraph2.selections[0].end, 8);
3776
    expect(paragraph3.selections.length, 1);
3777 3778 3779 3780 3781 3782 3783 3784
    expect(content, isNotNull);
    expect(content!.plainText, 'w are you?Good, an');

    await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true));
    await tester.pump();
    expect(paragraph1.selections.length, 1);
    expect(paragraph1.selections[0].start, 2);
    expect(paragraph1.selections[0].end, 7);
3785 3786
    expect(paragraph2.selections.length, 1);
    expect(paragraph3.selections.length, 1);
3787 3788 3789 3790 3791 3792 3793 3794
    expect(content, isNotNull);
    expect(content!.plainText, 'w are');

    await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true));
    await tester.pump();
    expect(paragraph1.selections.length, 1);
    expect(paragraph1.selections[0].start, 0);
    expect(paragraph1.selections[0].end, 2);
3795 3796
    expect(paragraph2.selections.length, 1);
    expect(paragraph3.selections.length, 1);
3797 3798
    expect(content, isNotNull);
    expect(content!.plainText, 'Ho');
3799
  });
3800 3801 3802

  group('BrowserContextMenu', () {
    setUp(() async {
3803
      TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, (MethodCall call) {
3804 3805 3806 3807 3808 3809 3810 3811 3812
        // Just complete successfully, so that BrowserContextMenu thinks that
        // the engine successfully received its call.
        return Future<void>.value();
      });
      await BrowserContextMenu.disableContextMenu();
    });

    tearDown(() async {
      await BrowserContextMenu.enableContextMenu();
3813
      TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, null);
3814 3815
    });

3816
    testWidgets('web can show flutter context menu when the browser context menu is disabled', (WidgetTester tester) async {
3817 3818 3819
      final FocusNode focusNode = FocusNode();
      addTearDown(focusNode.dispose);

3820 3821 3822 3823
      await tester.pumpWidget(
        MaterialApp(
          home: SelectableRegion(
            onSelectionChanged: (SelectedContent? selectedContent) {},
3824
            focusNode: focusNode,
3825 3826 3827 3828 3829 3830 3831
            selectionControls: materialTextSelectionControls,
            child: const Center(
              child: Text('How are you'),
            ),
          ),
        ),
      );
3832
      await tester.pumpAndSettle();
3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848

      final SelectableRegionState state =
          tester.state<SelectableRegionState>(find.byType(SelectableRegion));
      expect(find.text('Copy'), findsNothing);

      state.selectAll(SelectionChangedCause.toolbar);
      await tester.pumpAndSettle();
      expect(find.text('Copy'), findsOneWidget);

      state.hideToolbar();
      await tester.pumpAndSettle();
      expect(find.text('Copy'), findsNothing);
    },
      skip: !kIsWeb, // [intended]
    );
  });
3849

3850
  testWidgets('Multiple selectables on a single line should be in screen order', (WidgetTester tester) async {
3851 3852 3853
    // Regression test for https://github.com/flutter/flutter/issues/127942.
    final UniqueKey outerText = UniqueKey();
    const TextStyle textStyle = TextStyle(fontSize: 10);
3854 3855 3856
    final FocusNode focusNode = FocusNode();
    addTearDown(focusNode.dispose);

3857 3858 3859
    await tester.pumpWidget(
      MaterialApp(
        home: SelectableRegion(
3860
          focusNode: focusNode,
3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896
          selectionControls: materialTextSelectionControls,
          child: Scaffold(
            body: Center(
              child: Text.rich(
                const TextSpan(
                  children: <InlineSpan>[
                    TextSpan(text: 'Hello my name is ', style: textStyle),
                    WidgetSpan(
                      child: Text('Dash', style: textStyle),
                      alignment: PlaceholderAlignment.middle,
                    ),
                    TextSpan(text: '.', style: textStyle),
                  ],
                ),
                key: outerText,
              ),
            ),
          ),
        ),
      ),
    );
    final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first);
    final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 0), kind: PointerDeviceKind.mouse);
    addTearDown(gesture.removePointer);
    await tester.pump();
    await gesture.up();

    // Select all.
    await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true));

    // keyboard copy.
    await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true));

    final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>;
    expect(clipboardData['text'], 'Hello my name is Dash.');
  });
3897 3898 3899 3900
}

class SelectionSpy extends LeafRenderObjectWidget {
  const SelectionSpy({
3901
    super.key,
3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925
  });

  @override
  RenderObject createRenderObject(BuildContext context) {
    return RenderSelectionSpy(
      SelectionContainer.maybeOf(context),
    );
  }

  @override
  void updateRenderObject(BuildContext context, covariant RenderObject renderObject) { }
}

class RenderSelectionSpy extends RenderProxyBox
    with Selectable, SelectionRegistrant {
  RenderSelectionSpy(
      SelectionRegistrar? registrar,
      ) {
    this.registrar = registrar;
  }

  final Set<VoidCallback> listeners = <VoidCallback>{};
  List<SelectionEvent> events = <SelectionEvent>[];

3926 3927 3928 3929
  @override
  Size get size => _size;
  Size _size = Size.zero;

3930 3931 3932
  @override
  List<Rect> get boundingBoxes => <Rect>[paintBounds];

3933 3934 3935 3936 3937 3938
  @override
  Size computeDryLayout(BoxConstraints constraints) {
    _size = Size(constraints.maxWidth, constraints.maxHeight);
    return _size;
  }

3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956
  @override
  void addListener(VoidCallback listener) => listeners.add(listener);

  @override
  void removeListener(VoidCallback listener) => listeners.remove(listener);

  @override
  SelectionResult dispatchSelectionEvent(SelectionEvent event) {
    events.add(event);
    return SelectionResult.end;
  }

  @override
  SelectedContent? getSelectedContent() {
    return const SelectedContent(plainText: 'content');
  }

  @override
3957
  final SelectionGeometry value = const SelectionGeometry(
3958 3959
    hasContent: true,
    status: SelectionStatus.uncollapsed,
3960
    startSelectionPoint: SelectionPoint(
3961 3962 3963 3964
      localPosition: Offset.zero,
      lineHeight: 0.0,
      handleType: TextSelectionHandleType.left,
    ),
3965
    endSelectionPoint: SelectionPoint(
3966 3967 3968 3969 3970 3971 3972 3973 3974
      localPosition: Offset.zero,
      lineHeight: 0.0,
      handleType: TextSelectionHandleType.left,
    ),
  );

  @override
  void pushHandleLayers(LayerLink? startHandle, LayerLink? endHandle) { }
}
3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000

class SelectAllWidget extends SingleChildRenderObjectWidget {
  const SelectAllWidget({
    super.key,
    super.child,
  });

  @override
  RenderObject createRenderObject(BuildContext context) {
    return RenderSelectAll(
      SelectionContainer.maybeOf(context),
    );
  }

  @override
  void updateRenderObject(BuildContext context, covariant RenderObject renderObject) { }
}

class RenderSelectAll extends RenderProxyBox
    with Selectable, SelectionRegistrant {
  RenderSelectAll(
    SelectionRegistrar? registrar,
  ) {
    this.registrar = registrar;
  }

4001 4002 4003
  @override
  List<Rect> get boundingBoxes => <Rect>[paintBounds];

4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039
  final Set<VoidCallback> listeners = <VoidCallback>{};
  LayerLink? startHandle;
  LayerLink? endHandle;

  @override
  void addListener(VoidCallback listener) => listeners.add(listener);

  @override
  void removeListener(VoidCallback listener) => listeners.remove(listener);

  @override
  SelectionResult dispatchSelectionEvent(SelectionEvent event) {
    value = SelectionGeometry(
      hasContent: true,
      status: SelectionStatus.uncollapsed,
      startSelectionPoint: SelectionPoint(
        localPosition: Offset(0, size.height),
        lineHeight: 0.0,
        handleType: TextSelectionHandleType.left,
      ),
      endSelectionPoint: SelectionPoint(
        localPosition: Offset(size.width, size.height),
        lineHeight: 0.0,
        handleType: TextSelectionHandleType.left,
      ),
    );
    return SelectionResult.end;
  }

  @override
  SelectedContent? getSelectedContent() {
    return const SelectedContent(plainText: 'content');
  }

  @override
  SelectionGeometry get value => _value;
4040
  SelectionGeometry _value = const SelectionGeometry(
4041 4042
    hasContent: true,
    status: SelectionStatus.uncollapsed,
4043
    startSelectionPoint: SelectionPoint(
4044 4045 4046 4047
      localPosition: Offset.zero,
      lineHeight: 0.0,
      handleType: TextSelectionHandleType.left,
    ),
4048
    endSelectionPoint: SelectionPoint(
4049 4050 4051 4052 4053 4054
      localPosition: Offset.zero,
      lineHeight: 0.0,
      handleType: TextSelectionHandleType.left,
    ),
  );
  set value(SelectionGeometry other) {
4055
    if (other == _value) {
4056
      return;
4057
    }
4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069
    _value = other;
    for (final VoidCallback callback in listeners) {
      callback();
    }
  }

  @override
  void pushHandleLayers(LayerLink? startHandle, LayerLink? endHandle) {
    this.startHandle = startHandle;
    this.endHandle = endHandle;
  }
}