text_selection.dart 79.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

xster's avatar
xster committed
5
import 'dart:async';
6
import 'dart:math' as math;
xster's avatar
xster committed
7

8
import 'package:characters/characters.dart';
9 10
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
11
import 'package:flutter/rendering.dart';
12
import 'package:flutter/scheduler.dart';
13
import 'package:flutter/services.dart';
14 15

import 'basic.dart';
16
import 'binding.dart';
17
import 'constants.dart';
18
import 'container.dart';
19
import 'editable_text.dart';
20 21 22
import 'framework.dart';
import 'gesture_detector.dart';
import 'overlay.dart';
23
import 'ticker_provider.dart';
24
import 'transitions.dart';
25

jslavitz's avatar
jslavitz committed
26 27
export 'package:flutter/services.dart' show TextSelectionDelegate;

28 29 30 31
/// A duration that controls how often the drag selection update callback is
/// called.
const Duration _kDragSelectionUpdateThrottle = Duration(milliseconds: 50);

32 33 34 35
/// Which type of selection handle to be displayed.
///
/// With mixed-direction text, both handles may be the same type. Examples:
///
36 37 38 39 40
/// * LTR text: 'the <quick brown> fox':
///
///   The '<' is drawn with the [left] type, the '>' with the [right]
///
/// * RTL text: 'XOF <NWORB KCIUQ> EHT':
41
///
42
///   Same as above.
43
///
44 45 46 47 48 49 50 51 52
/// * mixed text: '<the NWOR<B KCIUQ fox'
///
///   Here 'the QUICK B' is selected, but 'QUICK BROWN' is RTL. Both are drawn
///   with the [left] type.
///
/// See also:
///
///  * [TextDirection], which discusses left-to-right and right-to-left text in
///    more detail.
53 54 55
enum TextSelectionHandleType {
  /// The selection handle is to the left of the selection end point.
  left,
56

57 58 59 60 61 62 63
  /// The selection handle is to the right of the selection end point.
  right,

  /// The start and end of the selection are co-incident at this point.
  collapsed,
}

64 65 66 67 68 69 70 71 72 73 74 75 76
/// Signature for when a pointer that's dragging to select text has moved again.
///
/// The first argument [startDetails] contains the details of the event that
/// initiated the dragging.
///
/// The second argument [updateDetails] contains the details of the current
/// pointer movement. It's the same as the one passed to [DragGestureRecognizer.onUpdate].
///
/// This signature is different from [GestureDragUpdateCallback] to make it
/// easier for various text fields to use [TextSelectionGestureDetector] without
/// having to store the start position.
typedef DragSelectionUpdateCallback = void Function(DragStartDetails startDetails, DragUpdateDetails updateDetails);

77 78 79 80 81 82 83 84 85 86 87
/// The type for a Function that builds a toolbar's container with the given
/// child.
///
/// See also:
///
///   * [TextSelectionToolbar.toolbarBuilder], which is of this type.
///     type.
///   * [CupertinoTextSelectionToolbar.toolbarBuilder], which is similar, but
///     for a Cupertino-style toolbar.
typedef ToolbarBuilder = Widget Function(BuildContext context, Widget child);

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
/// ParentData that determines whether or not to paint the corresponding child.
///
/// Used in the layout of the Cupertino and Material text selection menus, which
/// decide whether or not to paint their buttons after laying them out and
/// determining where they overflow.
class ToolbarItemsParentData extends ContainerBoxParentData<RenderBox> {
  /// Whether or not this child is painted.
  ///
  /// Children in the selection toolbar may be laid out for measurement purposes
  /// but not painted. This allows these children to be identified.
  bool shouldPaint = false;

  @override
  String toString() => '${super.toString()}; shouldPaint=$shouldPaint';
}

104
/// An interface for building the selection UI, to be provided by the
105
/// implementer of the toolbar widget.
xster's avatar
xster committed
106 107
///
/// Override text operations such as [handleCut] if needed.
108
abstract class TextSelectionControls {
109
  /// Builds a selection handle of the given `type`.
xster's avatar
xster committed
110 111 112
  ///
  /// The top left corner of this widget is positioned at the bottom of the
  /// selection position.
113 114 115 116 117
  ///
  /// The supplied [onTap] should be invoked when the handle is tapped, if such
  /// interaction is allowed. As a counterexample, the default selection handle
  /// on iOS [cupertinoTextSelectionControls] does not call [onTap] at all,
  /// since its handles are not meant to be tapped.
118
  Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]);
119

120 121 122
  /// Get the anchor point of the handle relative to itself. The anchor point is
  /// the point that is aligned with a specific point in the text. A handle
  /// often visually "points to" that location.
123
  Offset getHandleAnchor(TextSelectionHandleType type, double textLineHeight);
124

125 126 127
  /// Builds a toolbar near a text selection.
  ///
  /// Typically displays buttons for copying and pasting text.
128 129 130 131
  ///
  /// [globalEditableRegion] is the TextField size of the global coordinate system
  /// in logical pixels.
  ///
132 133 134
  /// [textLineHeight] is the `preferredLineHeight` of the [RenderEditable] we
  /// are building a toolbar for.
  ///
135 136 137 138 139 140
  /// The [position] is a general calculation midpoint parameter of the toolbar.
  /// If you want more detailed position information, can use [endpoints]
  /// to calculate it.
  Widget buildToolbar(
    BuildContext context,
    Rect globalEditableRegion,
141
    double textLineHeight,
142 143 144
    Offset position,
    List<TextSelectionPoint> endpoints,
    TextSelectionDelegate delegate,
145 146 147
    // TODO(chunhtai): Change to ValueListenable<ClipboardStatus>? once
    // mirgration is done. https://github.com/flutter/flutter/issues/99360
    ClipboardStatusNotifier? clipboardStatus,
148
    Offset? lastSecondaryTapDownPosition,
149
  );
150 151

  /// Returns the size of the selection handle.
152
  Size getHandleSize(double textLineHeight);
xster's avatar
xster committed
153

154 155 156 157 158 159 160 161 162
  /// Whether the current selection of the text field managed by the given
  /// `delegate` can be removed from the text field and placed into the
  /// [Clipboard].
  ///
  /// By default, false is returned when nothing is selected in the text field.
  ///
  /// Subclasses can use this to decide if they should expose the cut
  /// functionality to the user.
  bool canCut(TextSelectionDelegate delegate) {
163
    return delegate.cutEnabled && !delegate.textEditingValue.selection.isCollapsed;
164 165 166 167 168 169 170 171 172 173
  }

  /// Whether the current selection of the text field managed by the given
  /// `delegate` can be copied to the [Clipboard].
  ///
  /// By default, false is returned when nothing is selected in the text field.
  ///
  /// Subclasses can use this to decide if they should expose the copy
  /// functionality to the user.
  bool canCopy(TextSelectionDelegate delegate) {
174
    return delegate.copyEnabled && !delegate.textEditingValue.selection.isCollapsed;
175 176
  }

177 178
  /// Whether the text field managed by the given `delegate` supports pasting
  /// from the clipboard.
179 180 181
  ///
  /// Subclasses can use this to decide if they should expose the paste
  /// functionality to the user.
182 183 184 185
  ///
  /// This does not consider the contents of the clipboard. Subclasses may want
  /// to, for example, disallow pasting when the clipboard contains an empty
  /// string.
186
  bool canPaste(TextSelectionDelegate delegate) {
187
    return delegate.pasteEnabled;
188 189
  }

190
  /// Whether the current selection of the text field managed by the given
191 192 193 194 195 196
  /// `delegate` can be extended to include the entire content of the text
  /// field.
  ///
  /// Subclasses can use this to decide if they should expose the select all
  /// functionality to the user.
  bool canSelectAll(TextSelectionDelegate delegate) {
197
    return delegate.selectAllEnabled && delegate.textEditingValue.text.isNotEmpty && delegate.textEditingValue.selection.isCollapsed;
198 199
  }

200
  /// Call [TextSelectionDelegate.cutSelection] to cut current selection.
201 202 203
  ///
  /// This is called by subclasses when their cut affordance is activated by
  /// the user.
204 205 206
  // TODO(chunhtai): remove optional parameter once migration is done.
  // https://github.com/flutter/flutter/issues/99360
  void handleCut(TextSelectionDelegate delegate, [ClipboardStatusNotifier? clipboardStatus]) {
207
    delegate.cutSelection(SelectionChangedCause.toolbar);
xster's avatar
xster committed
208 209
  }

210
  /// Call [TextSelectionDelegate.copySelection] to copy current selection.
211 212 213
  ///
  /// This is called by subclasses when their copy affordance is activated by
  /// the user.
214 215 216
  // TODO(chunhtai): remove optional parameter once migration is done.
  // https://github.com/flutter/flutter/issues/99360
  void handleCopy(TextSelectionDelegate delegate, [ClipboardStatusNotifier? clipboardStatus]) {
217
    delegate.copySelection(SelectionChangedCause.toolbar);
xster's avatar
xster committed
218 219
  }

220
  /// Call [TextSelectionDelegate.pasteText] to paste text.
221 222 223 224 225 226 227 228
  ///
  /// This is called by subclasses when their paste affordance is activated by
  /// the user.
  ///
  /// This function is asynchronous since interacting with the clipboard is
  /// asynchronous. Race conditions may exist with this API as currently
  /// implemented.
  // TODO(ianh): https://github.com/flutter/flutter/issues/11427
229
  Future<void> handlePaste(TextSelectionDelegate delegate) async {
230
    delegate.pasteText(SelectionChangedCause.toolbar);
xster's avatar
xster committed
231 232
  }

233 234
  /// Call [TextSelectionDelegate.selectAll] to set the current selection to
  /// contain the entire text value.
235 236 237 238 239
  ///
  /// Does not hide the toolbar.
  ///
  /// This is called by subclasses when their select-all affordance is activated
  /// by the user.
xster's avatar
xster committed
240
  void handleSelectAll(TextSelectionDelegate delegate) {
241
    delegate.selectAll(SelectionChangedCause.toolbar);
242
    delegate.bringIntoView(delegate.textEditingValue.selection.extent);
xster's avatar
xster committed
243
  }
244 245
}

246 247
/// An object that manages a pair of text selection handles for a
/// [RenderEditable].
248
///
249 250 251
/// This class is a wrapper of [SelectionOverlay] to provide APIs specific for
/// [RenderEditable]s. To manage selection handles for custom widgets, use
/// [SelectionOverlay] instead.
252
class TextSelectionOverlay {
Marc Plano-Lesay's avatar
Marc Plano-Lesay committed
253
  /// Creates an object that manages overlay entries for selection handles.
254 255
  ///
  /// The [context] must not be null and must have an [Overlay] as an ancestor.
256
  TextSelectionOverlay({
257
    required TextEditingValue value,
258 259 260 261 262
    required BuildContext context,
    Widget? debugRequiredFor,
    required LayerLink toolbarLayerLink,
    required LayerLink startHandleLayerLink,
    required LayerLink endHandleLayerLink,
263
    required this.renderObject,
264
    this.selectionControls,
265
    bool handlesVisible = false,
266
    required this.selectionDelegate,
267 268 269
    DragStartBehavior dragStartBehavior = DragStartBehavior.start,
    VoidCallback? onSelectionHandleTapped,
    ClipboardStatusNotifier? clipboardStatus,
270 271
  }) : assert(value != null),
       assert(context != null),
272 273
       assert(handlesVisible != null),
       _handlesVisible = handlesVisible,
274
       _value = value {
275 276 277
    renderObject.selectionStartInViewport.addListener(_updateTextSelectionOverlayVisibilities);
    renderObject.selectionEndInViewport.addListener(_updateTextSelectionOverlayVisibilities);
    _updateTextSelectionOverlayVisibilities();
278 279 280 281 282 283 284 285 286 287 288 289 290 291
    _selectionOverlay = SelectionOverlay(
      context: context,
      debugRequiredFor: debugRequiredFor,
      // The metrics will be set when show handles.
      startHandleType: TextSelectionHandleType.collapsed,
      startHandlesVisible: _effectiveStartHandleVisibility,
      lineHeightAtStart: 0.0,
      onStartHandleDragStart: _handleSelectionStartHandleDragStart,
      onStartHandleDragUpdate: _handleSelectionStartHandleDragUpdate,
      endHandleType: TextSelectionHandleType.collapsed,
      endHandlesVisible: _effectiveEndHandleVisibility,
      lineHeightAtEnd: 0.0,
      onEndHandleDragStart: _handleSelectionEndHandleDragStart,
      onEndHandleDragUpdate: _handleSelectionEndHandleDragUpdate,
292
      toolbarVisible: _effectiveToolbarVisibility,
293 294 295 296 297 298 299 300 301 302 303 304 305
      selectionEndPoints: const <TextSelectionPoint>[],
      selectionControls: selectionControls,
      selectionDelegate: selectionDelegate,
      clipboardStatus: clipboardStatus,
      startHandleLayerLink: startHandleLayerLink,
      endHandleLayerLink: endHandleLayerLink,
      toolbarLayerLink: toolbarLayerLink,
      onSelectionHandleTapped: onSelectionHandleTapped,
      dragStartBehavior: dragStartBehavior,
      toolbarLocation: renderObject.lastSecondaryTapDownPosition,
    );
  }

306 307 308 309 310 311 312
  /// Controls the fade-in and fade-out animations for the toolbar and handles.
  @Deprecated(
    'Use `SelectionOverlay.fadeDuration` instead. '
    'This feature was deprecated after v2.12.0-4.1.pre.'
  )
  static const Duration fadeDuration = SelectionOverlay.fadeDuration;

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
  // TODO(mpcomplete): what if the renderObject is removed or replaced, or
  // moves? Not sure what cases I need to handle, or how to handle them.
  /// The editable line in which the selected text is being displayed.
  final RenderEditable renderObject;

  /// {@macro flutter.widgets.SelectionOverlay.selectionControls}
  final TextSelectionControls? selectionControls;

  /// {@macro flutter.widgets.SelectionOverlay.selectionDelegate}
  final TextSelectionDelegate selectionDelegate;

  late final SelectionOverlay _selectionOverlay;

  /// Retrieve current value.
  @visibleForTesting
  TextEditingValue get value => _value;

  TextEditingValue _value;

  TextSelection get _selection => _value.selection;

  final ValueNotifier<bool> _effectiveStartHandleVisibility = ValueNotifier<bool>(false);
  final ValueNotifier<bool> _effectiveEndHandleVisibility = ValueNotifier<bool>(false);
336 337
  final ValueNotifier<bool> _effectiveToolbarVisibility = ValueNotifier<bool>(false);
  void _updateTextSelectionOverlayVisibilities() {
338 339
    _effectiveStartHandleVisibility.value = _handlesVisible && renderObject.selectionStartInViewport.value;
    _effectiveEndHandleVisibility.value = _handlesVisible && renderObject.selectionEndInViewport.value;
340
    _effectiveToolbarVisibility.value = renderObject.selectionStartInViewport.value || renderObject.selectionEndInViewport.value;
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
  }

  /// Whether selection handles are visible.
  ///
  /// Set to false if you want to hide the handles. Use this property to show or
  /// hide the handle without rebuilding them.
  ///
  /// Defaults to false.
  bool get handlesVisible => _handlesVisible;
  bool _handlesVisible = false;
  set handlesVisible(bool visible) {
    assert(visible != null);
    if (_handlesVisible == visible)
      return;
    _handlesVisible = visible;
356
    _updateTextSelectionOverlayVisibilities();
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
  }

  /// {@macro flutter.widgets.SelectionOverlay.showHandles}
  void showHandles() {
    _updateSelectionOverlay();
    _selectionOverlay.showHandles();
  }

  /// {@macro flutter.widgets.SelectionOverlay.hideHandles}
  void hideHandles() => _selectionOverlay.hideHandles();

  /// {@macro flutter.widgets.SelectionOverlay.showToolbar}
  void showToolbar() {
    _updateSelectionOverlay();
    _selectionOverlay.showToolbar();
  }

  /// Updates the overlay after the selection has changed.
  ///
  /// If this method is called while the [SchedulerBinding.schedulerPhase] is
  /// [SchedulerPhase.persistentCallbacks], i.e. during the build, layout, or
  /// paint phases (see [WidgetsBinding.drawFrame]), then the update is delayed
  /// until the post-frame callbacks phase. Otherwise the update is done
  /// synchronously. This means that it is safe to call during builds, but also
  /// that if you do call this during a build, the UI will not update until the
  /// next frame (i.e. many milliseconds later).
  void update(TextEditingValue newValue) {
    if (_value == newValue)
      return;
    _value = newValue;
    _updateSelectionOverlay();
  }

  void _updateSelectionOverlay() {
    _selectionOverlay
      // Update selection handle metrics.
      ..startHandleType = _chooseType(
        renderObject.textDirection,
        TextSelectionHandleType.left,
        TextSelectionHandleType.right,
      )
      ..lineHeightAtStart = _getStartGlyphHeight()
      ..endHandleType = _chooseType(
        renderObject.textDirection,
        TextSelectionHandleType.right,
        TextSelectionHandleType.left,
      )
      ..lineHeightAtEnd = _getEndGlyphHeight()
      // Update selection toolbar metrics.
      ..selectionEndPoints = renderObject.getEndpointsForSelection(_selection)
      ..toolbarLocation = renderObject.lastSecondaryTapDownPosition;
  }

  /// Causes the overlay to update its rendering.
  ///
  /// This is intended to be called when the [renderObject] may have changed its
  /// text metrics (e.g. because the text was scrolled).
  void updateForScroll() => _updateSelectionOverlay();

  /// Whether the handles are currently visible.
  bool get handlesAreVisible => _selectionOverlay._handles != null && handlesVisible;

  /// Whether the toolbar is currently visible.
  bool get toolbarIsVisible => _selectionOverlay._toolbar != null;

  /// {@macro flutter.widgets.SelectionOverlay.hide}
  void hide() => _selectionOverlay.hide();

  /// {@macro flutter.widgets.SelectionOverlay.hideToolbar}
  void hideToolbar() => _selectionOverlay.hideToolbar();

  /// {@macro flutter.widgets.SelectionOverlay.dispose}
  void dispose() {
    _selectionOverlay.dispose();
431 432 433 434 435
    renderObject.selectionStartInViewport.removeListener(_updateTextSelectionOverlayVisibilities);
    renderObject.selectionEndInViewport.removeListener(_updateTextSelectionOverlayVisibilities);
    _effectiveToolbarVisibility.dispose();
    _effectiveStartHandleVisibility.dispose();
    _effectiveEndHandleVisibility.dispose();
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
  }

  double _getStartGlyphHeight() {
    final InlineSpan span = renderObject.text!;
    final String prevText = span.toPlainText();
    final String currText = selectionDelegate.textEditingValue.text;
    final int firstSelectedGraphemeExtent;
    Rect? startHandleRect;
    // Only calculate handle rects if the text in the previous frame
    // is the same as the text in the current frame. This is done because
    // widget.renderObject contains the renderEditable from the previous frame.
    // If the text changed between the current and previous frames then
    // widget.renderObject.getRectForComposingRange might fail. In cases where
    // the current frame is different from the previous we fall back to
    // renderObject.preferredLineHeight.
    if (prevText == currText && _selection != null && _selection.isValid && !_selection.isCollapsed) {
      final String selectedGraphemes = _selection.textInside(currText);
      firstSelectedGraphemeExtent = selectedGraphemes.characters.first.length;
      startHandleRect = renderObject.getRectForComposingRange(TextRange(start: _selection.start, end: _selection.start + firstSelectedGraphemeExtent));
    }
    return startHandleRect?.height ?? renderObject.preferredLineHeight;
  }

  double _getEndGlyphHeight() {
    final InlineSpan span = renderObject.text!;
    final String prevText = span.toPlainText();
    final String currText = selectionDelegate.textEditingValue.text;
    final int lastSelectedGraphemeExtent;
    Rect? endHandleRect;
    // See the explanation in _getStartGlyphHeight.
    if (prevText == currText && _selection != null && _selection.isValid && !_selection.isCollapsed) {
      final String selectedGraphemes = _selection.textInside(currText);
      lastSelectedGraphemeExtent = selectedGraphemes.characters.last.length;
      endHandleRect = renderObject.getRectForComposingRange(TextRange(start: _selection.end - lastSelectedGraphemeExtent, end: _selection.end));
    }
    return endHandleRect?.height ?? renderObject.preferredLineHeight;
  }

  late Offset _dragEndPosition;

  void _handleSelectionEndHandleDragStart(DragStartDetails details) {
    final Size handleSize = selectionControls!.getHandleSize(
      renderObject.preferredLineHeight,
    );
    _dragEndPosition = details.globalPosition + Offset(0.0, -handleSize.height);
  }

  void _handleSelectionEndHandleDragUpdate(DragUpdateDetails details) {
    _dragEndPosition += details.delta;
    final TextPosition position = renderObject.getPositionForPoint(_dragEndPosition);

    if (_selection.isCollapsed) {
      _handleSelectionHandleChanged(TextSelection.fromPosition(position), isEnd: true);
      return;
    }

    final TextSelection newSelection = TextSelection(
      baseOffset: _selection.baseOffset,
      extentOffset: position.offset,
    );

    if (newSelection.baseOffset >= newSelection.extentOffset)
      return; // don't allow order swapping.

    _handleSelectionHandleChanged(newSelection, isEnd: true);
  }

  late Offset _dragStartPosition;

  void _handleSelectionStartHandleDragStart(DragStartDetails details) {
    final Size handleSize = selectionControls!.getHandleSize(
      renderObject.preferredLineHeight,
    );
    _dragStartPosition = details.globalPosition + Offset(0.0, -handleSize.height);
  }

  void _handleSelectionStartHandleDragUpdate(DragUpdateDetails details) {
    _dragStartPosition += details.delta;
    final TextPosition position = renderObject.getPositionForPoint(_dragStartPosition);

    if (_selection.isCollapsed) {
      _handleSelectionHandleChanged(TextSelection.fromPosition(position), isEnd: false);
      return;
    }

    final TextSelection newSelection = TextSelection(
      baseOffset: position.offset,
      extentOffset: _selection.extentOffset,
    );

    if (newSelection.baseOffset >= newSelection.extentOffset)
      return; // don't allow order swapping.

    _handleSelectionHandleChanged(newSelection, isEnd: false);
  }

  void _handleSelectionHandleChanged(TextSelection newSelection, {required bool isEnd}) {
    final TextPosition textPosition = isEnd ? newSelection.extent : newSelection.base;
    selectionDelegate.userUpdateTextEditingValue(
      _value.copyWith(selection: newSelection),
      SelectionChangedCause.drag,
    );
    selectionDelegate.bringIntoView(textPosition);
  }

  TextSelectionHandleType _chooseType(
      TextDirection textDirection,
      TextSelectionHandleType ltrType,
      TextSelectionHandleType rtlType,
      ) {
    if (_selection.isCollapsed)
      return TextSelectionHandleType.collapsed;

    assert(textDirection != null);
    switch (textDirection) {
      case TextDirection.ltr:
        return ltrType;
      case TextDirection.rtl:
        return rtlType;
    }
  }
}

/// An object that manages a pair of selection handles.
///
/// The selection handles are displayed in the [Overlay] that most closely
/// encloses the given [BuildContext].
class SelectionOverlay {
  /// Creates an object that manages overlay entries for selection handles.
  ///
  /// The [context] must not be null and must have an [Overlay] as an ancestor.
  SelectionOverlay({
    required this.context,
    this.debugRequiredFor,
    required TextSelectionHandleType startHandleType,
    required double lineHeightAtStart,
    this.startHandlesVisible,
    this.onStartHandleDragStart,
    this.onStartHandleDragUpdate,
    this.onStartHandleDragEnd,
    required TextSelectionHandleType endHandleType,
    required double lineHeightAtEnd,
    this.endHandlesVisible,
    this.onEndHandleDragStart,
    this.onEndHandleDragUpdate,
    this.onEndHandleDragEnd,
582
    this.toolbarVisible,
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
    required List<TextSelectionPoint> selectionEndPoints,
    required this.selectionControls,
    required this.selectionDelegate,
    required this.clipboardStatus,
    required this.startHandleLayerLink,
    required this.endHandleLayerLink,
    required this.toolbarLayerLink,
    this.dragStartBehavior = DragStartBehavior.start,
    this.onSelectionHandleTapped,
    Offset? toolbarLocation,
  }) : _startHandleType = startHandleType,
       _lineHeightAtStart = lineHeightAtStart,
       _endHandleType = endHandleType,
       _lineHeightAtEnd = lineHeightAtEnd,
       _selectionEndPoints = selectionEndPoints,
       _toolbarLocation = toolbarLocation {
599
    final OverlayState? overlay = Overlay.of(context, rootOverlay: true);
600 601
    assert(
      overlay != null,
602 603
      'No Overlay widget exists above $context.\n'
      'Usually the Navigator created by WidgetsApp provides the overlay. Perhaps your '
604 605
      'app content was created above the Navigator with the WidgetsApp builder parameter.',
    );
606
  }
607

608 609 610 611
  /// The context in which the selection handles should appear.
  ///
  /// This context must have an [Overlay] as an ancestor because this object
  /// will display the text selection handles in that [Overlay].
612
  final BuildContext context;
613

614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
  /// The type of start selection handle.
  ///
  /// Changing the value while the handles are visible causes them to rebuild.
  TextSelectionHandleType get startHandleType => _startHandleType;
  TextSelectionHandleType _startHandleType;
  set startHandleType(TextSelectionHandleType value) {
    if (_startHandleType == value)
      return;
    _startHandleType = value;
    _markNeedsBuild();
  }

  /// The line height at the selection start.
  ///
  /// This value is used for calculating the size of the start selection handle.
  ///
  /// Changing the value while the handles are visible causes them to rebuild.
  double get lineHeightAtStart => _lineHeightAtStart;
  double _lineHeightAtStart;
  set lineHeightAtStart(double value) {
    if (_lineHeightAtStart == value)
      return;
    _lineHeightAtStart = value;
    _markNeedsBuild();
  }

  /// Whether the start handle is visible.
  ///
  /// If the value changes, the start handle uses [FadeTransition] to transition
  /// itself on and off the screen.
  ///
  /// If this is null, the start selection handle will always be visible.
  final ValueListenable<bool>? startHandlesVisible;

  /// Called when the users start dragging the start selection handles.
  final ValueChanged<DragStartDetails>? onStartHandleDragStart;

  /// Called when the users drag the start selection handles to new locations.
  final ValueChanged<DragUpdateDetails>? onStartHandleDragUpdate;

  /// Called when the users lift their fingers after dragging the start selection
  /// handles.
  final ValueChanged<DragEndDetails>? onStartHandleDragEnd;

  /// The type of end selection handle.
  ///
  /// Changing the value while the handles are visible causes them to rebuild.
  TextSelectionHandleType get endHandleType => _endHandleType;
  TextSelectionHandleType _endHandleType;
  set endHandleType(TextSelectionHandleType value) {
    if (_endHandleType == value)
      return;
    _endHandleType = value;
    _markNeedsBuild();
  }

  /// The line height at the selection end.
  ///
  /// This value is used for calculating the size of the end selection handle.
  ///
  /// Changing the value while the handles are visible causes them to rebuild.
  double get lineHeightAtEnd => _lineHeightAtEnd;
  double _lineHeightAtEnd;
  set lineHeightAtEnd(double value) {
    if (_lineHeightAtEnd == value)
      return;
    _lineHeightAtEnd = value;
    _markNeedsBuild();
  }

  /// Whether the end handle is visible.
  ///
  /// If the value changes, the end handle uses [FadeTransition] to transition
  /// itself on and off the screen.
  ///
  /// If this is null, the end selection handle will always be visible.
  final ValueListenable<bool>? endHandlesVisible;

  /// Called when the users start dragging the end selection handles.
  final ValueChanged<DragStartDetails>? onEndHandleDragStart;

  /// Called when the users drag the end selection handles to new locations.
  final ValueChanged<DragUpdateDetails>? onEndHandleDragUpdate;

  /// Called when the users lift their fingers after dragging the end selection
  /// handles.
  final ValueChanged<DragEndDetails>? onEndHandleDragEnd;

702 703 704 705 706 707 708 709
  /// Whether the toolbar is visible.
  ///
  /// If the value changes, the toolbar uses [FadeTransition] to transition
  /// itself on and off the screen.
  ///
  /// If this is null the toolbar will always be visible.
  final ValueListenable<bool>? toolbarVisible;

710 711 712 713 714 715 716 717 718 719
  /// The text selection positions of selection start and end.
  List<TextSelectionPoint> get selectionEndPoints => _selectionEndPoints;
  List<TextSelectionPoint> _selectionEndPoints;
  set selectionEndPoints(List<TextSelectionPoint> value) {
    if (!listEquals(_selectionEndPoints, value)) {
      _markNeedsBuild();
    }
    _selectionEndPoints = value;
  }

720
  /// Debugging information for explaining why the [Overlay] is required.
721
  final Widget? debugRequiredFor;
722

723 724
  /// The object supplied to the [CompositedTransformTarget] that wraps the text
  /// field.
725 726 727 728 729 730 731 732 733
  final LayerLink toolbarLayerLink;

  /// The objects supplied to the [CompositedTransformTarget] that wraps the
  /// location of start selection handle.
  final LayerLink startHandleLayerLink;

  /// The objects supplied to the [CompositedTransformTarget] that wraps the
  /// location of end selection handle.
  final LayerLink endHandleLayerLink;
734

735
  /// {@template flutter.widgets.SelectionOverlay.selectionControls}
736
  /// Builds text selection handles and toolbar.
737
  /// {@endtemplate}
738
  final TextSelectionControls? selectionControls;
739

740
  /// {@template flutter.widgets.SelectionOverlay.selectionDelegate}
741 742
  /// The delegate for manipulating the current selection in the owning
  /// text field.
743
  /// {@endtemplate}
744
  final TextSelectionDelegate selectionDelegate;
745

746 747 748
  /// Determines the way that drag start behavior is handled.
  ///
  /// If set to [DragStartBehavior.start], handle drag behavior will
749 750 751
  /// begin at the position where the drag gesture won the arena. If set to
  /// [DragStartBehavior.down] it will begin at the position where a down
  /// event is first detected.
752 753 754 755 756
  ///
  /// In general, setting this to [DragStartBehavior.start] will make drag
  /// animation smoother and setting it to [DragStartBehavior.down] will make
  /// drag behavior feel slightly more reactive.
  ///
757
  /// By default, the drag start behavior is [DragStartBehavior.start].
758 759 760 761 762 763
  ///
  /// See also:
  ///
  ///  * [DragGestureRecognizer.dragStartBehavior], which gives an example for the different behaviors.
  final DragStartBehavior dragStartBehavior;

764
  /// {@template flutter.widgets.SelectionOverlay.onSelectionHandleTapped}
765 766 767
  /// A callback that's optionally invoked when a selection handle is tapped.
  ///
  /// The [TextSelectionControls.buildHandle] implementation the text field
Ahmed Ashour's avatar
Ahmed Ashour committed
768
  /// uses decides where the handle's tap "hotspot" is, or whether the
769 770 771 772 773 774
  /// selection handle supports tap gestures at all. For instance,
  /// [MaterialTextSelectionControls] calls [onSelectionHandleTapped] when the
  /// selection handle's "knob" is tapped, while
  /// [CupertinoTextSelectionControls] builds a handle that's not sufficiently
  /// large for tapping (as it's not meant to be tapped) so it does not call
  /// [onSelectionHandleTapped] even when tapped.
775
  /// {@endtemplate}
776 777
  // See https://github.com/flutter/flutter/issues/39376#issuecomment-848406415
  // for provenance.
778
  final VoidCallback? onSelectionHandleTapped;
779

780 781 782 783 784
  /// Maintains the status of the clipboard for determining if its contents can
  /// be pasted or not.
  ///
  /// Useful because the actual value of the clipboard can only be checked
  /// asynchronously (see [Clipboard.getData]).
785
  final ClipboardStatusNotifier? clipboardStatus;
786

787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
  /// The location of where the toolbar should be drawn in relative to the
  /// location of [toolbarLayerLink].
  ///
  /// If this is null, the toolbar is drawn based on [selectionEndPoints] and
  /// the rect of render object of [context].
  ///
  /// This is useful for displaying toolbars at the mouse right-click locations
  /// in desktop devices.
  Offset? get toolbarLocation => _toolbarLocation;
  Offset? _toolbarLocation;
  set toolbarLocation(Offset? value) {
    if (_toolbarLocation == value) {
      return;
    }
    _toolbarLocation = value;
    _markNeedsBuild();
  }

805 806 807
  /// Controls the fade-in and fade-out animations for the toolbar and handles.
  static const Duration fadeDuration = Duration(milliseconds: 150);

808 809
  /// A pair of handles. If this is non-null, there are always 2, though the
  /// second is hidden when the selection is collapsed.
810
  List<OverlayEntry>? _handles;
811

812
  /// A copy/paste toolbar.
813
  OverlayEntry? _toolbar;
814

815
  /// {@template flutter.widgets.SelectionOverlay.showHandles}
816
  /// Builds the handles by inserting them into the [context]'s overlay.
817
  /// {@endtemplate}
818
  void showHandles() {
819 820 821
    if (_handles != null)
      return;

822
    _handles = <OverlayEntry>[
823 824
      OverlayEntry(builder: _buildStartHandle),
      OverlayEntry(builder: _buildEndHandle),
825
    ];
826

827 828
    Overlay.of(context, rootOverlay: true, debugRequiredFor: debugRequiredFor)!
      .insertAll(_handles!);
829 830
  }

831
  /// {@template flutter.widgets.SelectionOverlay.hideHandles}
832
  /// Destroys the handles by removing them from overlay.
833
  /// {@endtemplate}
834 835
  void hideHandles() {
    if (_handles != null) {
836 837
      _handles![0].remove();
      _handles![1].remove();
838 839 840 841
      _handles = null;
    }
  }

842
  /// {@template flutter.widgets.SelectionOverlay.showToolbar}
843
  /// Shows the toolbar by inserting it into the [context]'s overlay.
844
  /// {@endtemplate}
845
  void showToolbar() {
846 847 848
    if (_toolbar != null) {
      return;
    }
849
    _toolbar = OverlayEntry(builder: _buildToolbar);
850
    Overlay.of(context, rootOverlay: true, debugRequiredFor: debugRequiredFor)!.insert(_toolbar!);
851 852
  }

853 854 855
  bool _buildScheduled = false;
  void _markNeedsBuild() {
    if (_handles == null && _toolbar == null)
856
      return;
857 858
    // If we are in build state, it will be too late to update visibility.
    // We will need to schedule the build in next frame.
859
    if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
860 861 862 863 864 865 866 867 868 869 870
      if (_buildScheduled)
        return;
      _buildScheduled = true;
      SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
        _buildScheduled = false;
        if (_handles != null) {
          _handles![0].markNeedsBuild();
          _handles![1].markNeedsBuild();
        }
        _toolbar?.markNeedsBuild();
      });
871
    } else {
872 873 874 875 876
      if (_handles != null) {
        _handles![0].markNeedsBuild();
        _handles![1].markNeedsBuild();
      }
      _toolbar?.markNeedsBuild();
877
    }
878 879
  }

880
  /// {@template flutter.widgets.SelectionOverlay.hide}
881
  /// Hides the entire overlay including the toolbar and the handles.
882
  /// {@endtemplate}
883
  void hide() {
884
    if (_handles != null) {
885 886
      _handles![0].remove();
      _handles![1].remove();
887 888
      _handles = null;
    }
889 890 891 892
    if (_toolbar != null) {
      hideToolbar();
    }
  }
893

894
  /// {@template flutter.widgets.SelectionOverlay.hideToolbar}
895 896 897
  /// Hides the toolbar part of the overlay.
  ///
  /// To hide the whole overlay, see [hide].
898
  /// {@endtemplate}
899
  void hideToolbar() {
900 901
    if (_toolbar == null)
      return;
902
    _toolbar?.remove();
903
    _toolbar = null;
904 905
  }

906 907 908
  /// {@template flutter.widgets.SelectionOverlay.dispose}
  /// Disposes this object and release resources.
  /// {@endtemplate}
909 910
  void dispose() {
    hide();
911 912
  }

913
  Widget _buildStartHandle(BuildContext context) {
914 915
    final Widget handle;
    final TextSelectionControls? selectionControls = this.selectionControls;
916 917 918
    if (selectionControls == null)
      handle = Container();
    else {
919
      handle = _SelectionHandleOverlay(
920
        type: _startHandleType,
921 922
        handleLayerLink: startHandleLayerLink,
        onSelectionHandleTapped: onSelectionHandleTapped,
923 924 925
        onSelectionHandleDragStart: onStartHandleDragStart,
        onSelectionHandleDragUpdate: onStartHandleDragUpdate,
        onSelectionHandleDragEnd: onStartHandleDragEnd,
926
        selectionControls: selectionControls,
927 928
        visibility: startHandlesVisible,
        preferredLineHeight: _lineHeightAtStart,
929
        dragStartBehavior: dragStartBehavior,
930 931 932 933 934 935 936 937 938 939
      );
    }
    return ExcludeSemantics(
      child: handle,
    );
  }

  Widget _buildEndHandle(BuildContext context) {
    final Widget handle;
    final TextSelectionControls? selectionControls = this.selectionControls;
940 941
    if (selectionControls == null || _startHandleType == TextSelectionHandleType.collapsed)
      handle = Container(); // hide the second handle when collapsed.
942
    else {
943
      handle = _SelectionHandleOverlay(
944
        type: _endHandleType,
945 946
        handleLayerLink: endHandleLayerLink,
        onSelectionHandleTapped: onSelectionHandleTapped,
947 948 949
        onSelectionHandleDragStart: onEndHandleDragStart,
        onSelectionHandleDragUpdate: onEndHandleDragUpdate,
        onSelectionHandleDragEnd: onEndHandleDragEnd,
950
        selectionControls: selectionControls,
951 952
        visibility: endHandlesVisible,
        preferredLineHeight: _lineHeightAtEnd,
953
        dragStartBehavior: dragStartBehavior,
954 955 956 957 958
      );
    }
    return ExcludeSemantics(
      child: handle,
    );
959 960
  }

961
  Widget _buildToolbar(BuildContext context) {
962
    if (selectionControls == null)
963
      return Container();
964

965
    final RenderBox renderBox = this.context.findRenderObject()! as RenderBox;
966

967
    final Rect editingRegion = Rect.fromPoints(
968 969
      renderBox.localToGlobal(Offset.zero),
      renderBox.localToGlobal(renderBox.size.bottomRight(Offset.zero)),
970 971
    );

972 973
    final bool isMultiline = selectionEndPoints.last.point.dy - selectionEndPoints.first.point.dy >
        lineHeightAtEnd / 2;
974 975 976 977 978

    // If the selected text spans more than 1 line, horizontally center the toolbar.
    // Derived from both iOS and Android.
    final double midX = isMultiline
      ? editingRegion.width / 2
979
      : (selectionEndPoints.first.point.dx + selectionEndPoints.last.point.dx) / 2;
980 981 982 983

    final Offset midpoint = Offset(
      midX,
      // The y-coordinate won't be made use of most likely.
984
      selectionEndPoints.first.point.dy - lineHeightAtStart,
985 986
    );

987 988
    return Directionality(
      textDirection: Directionality.of(this.context),
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
      child: _SelectionToolbarOverlay(
        preferredLineHeight: lineHeightAtStart,
        toolbarLocation: toolbarLocation,
        layerLink: toolbarLayerLink,
        editingRegion: editingRegion,
        selectionControls: selectionControls,
        midpoint: midpoint,
        selectionEndpoints: selectionEndPoints,
        visibility: toolbarVisible,
        selectionDelegate: selectionDelegate,
        clipboardStatus: clipboardStatus,
      ),
    );
  }
}

/// This widget represents a selection toolbar.
class _SelectionToolbarOverlay extends StatefulWidget {
  /// Creates a toolbar overlay.
  const _SelectionToolbarOverlay({
    required this.preferredLineHeight,
    required this.toolbarLocation,
    required this.layerLink,
    required this.editingRegion,
    required this.selectionControls,
    this.visibility,
    required this.midpoint,
    required this.selectionEndpoints,
    required this.selectionDelegate,
    required this.clipboardStatus,
1019
  });
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 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 1061 1062 1063 1064 1065 1066 1067 1068

  final double preferredLineHeight;
  final Offset? toolbarLocation;
  final LayerLink layerLink;
  final Rect editingRegion;
  final TextSelectionControls? selectionControls;
  final ValueListenable<bool>? visibility;
  final Offset midpoint;
  final List<TextSelectionPoint> selectionEndpoints;
  final TextSelectionDelegate? selectionDelegate;
  final ClipboardStatusNotifier? clipboardStatus;

  @override
  _SelectionToolbarOverlayState createState() => _SelectionToolbarOverlayState();
}

class _SelectionToolbarOverlayState extends State<_SelectionToolbarOverlay> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  Animation<double> get _opacity => _controller.view;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(duration: SelectionOverlay.fadeDuration, vsync: this);

    _toolbarVisibilityChanged();
    widget.visibility?.addListener(_toolbarVisibilityChanged);
  }

  @override
  void didUpdateWidget(_SelectionToolbarOverlay oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.visibility == widget.visibility) {
      return;
    }
    oldWidget.visibility?.removeListener(_toolbarVisibilityChanged);
    _toolbarVisibilityChanged();
    widget.visibility?.addListener(_toolbarVisibilityChanged);
  }

  @override
  void dispose() {
    widget.visibility?.removeListener(_toolbarVisibilityChanged);
    _controller.dispose();
    super.dispose();
  }

  void _toolbarVisibilityChanged() {
1069
    if (widget.visibility?.value ?? true) {
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
      _controller.forward();
    } else {
      _controller.reverse();
    }
  }

  @override
  Widget build(BuildContext context) {
    return FadeTransition(
      opacity: _opacity,
      child: CompositedTransformFollower(
        link: widget.layerLink,
        showWhenUnlinked: false,
        offset: -widget.editingRegion.topLeft,
        child: Builder(
          builder: (BuildContext context) {
            return widget.selectionControls!.buildToolbar(
              context,
              widget.editingRegion,
              widget.preferredLineHeight,
              widget.midpoint,
              widget.selectionEndpoints,
              widget.selectionDelegate!,
1093
              widget.clipboardStatus,
1094 1095 1096
              widget.toolbarLocation,
            );
          },
1097
        ),
1098
      ),
1099
    );
1100
  }
1101 1102
}

1103 1104 1105 1106 1107 1108 1109 1110 1111
/// This widget represents a single draggable selection handle.
class _SelectionHandleOverlay extends StatefulWidget {
  /// Create selection overlay.
  const _SelectionHandleOverlay({
    required this.type,
    required this.handleLayerLink,
    this.onSelectionHandleTapped,
    this.onSelectionHandleDragStart,
    this.onSelectionHandleDragUpdate,
1112
    this.onSelectionHandleDragEnd,
1113
    required this.selectionControls,
1114
    this.visibility,
1115
    required this.preferredLineHeight,
1116
    this.dragStartBehavior = DragStartBehavior.start,
1117
  });
1118

1119
  final LayerLink handleLayerLink;
1120
  final VoidCallback? onSelectionHandleTapped;
1121 1122
  final ValueChanged<DragStartDetails>? onSelectionHandleDragStart;
  final ValueChanged<DragUpdateDetails>? onSelectionHandleDragUpdate;
1123
  final ValueChanged<DragEndDetails>? onSelectionHandleDragEnd;
1124
  final TextSelectionControls selectionControls;
1125
  final ValueListenable<bool>? visibility;
1126 1127
  final double preferredLineHeight;
  final TextSelectionHandleType type;
1128
  final DragStartBehavior dragStartBehavior;
1129 1130

  @override
1131 1132
  State<_SelectionHandleOverlay> createState() => _SelectionHandleOverlayState();

1133 1134
}

1135
class _SelectionHandleOverlayState extends State<_SelectionHandleOverlay> with SingleTickerProviderStateMixin {
1136

1137
  late AnimationController _controller;
1138 1139 1140 1141 1142 1143
  Animation<double> get _opacity => _controller.view;

  @override
  void initState() {
    super.initState();

1144
    _controller = AnimationController(duration: SelectionOverlay.fadeDuration, vsync: this);
1145 1146

    _handleVisibilityChanged();
1147
    widget.visibility?.addListener(_handleVisibilityChanged);
1148 1149 1150
  }

  void _handleVisibilityChanged() {
1151
    if (widget.visibility?.value ?? true) {
1152 1153 1154 1155 1156 1157 1158
      _controller.forward();
    } else {
      _controller.reverse();
    }
  }

  @override
1159
  void didUpdateWidget(_SelectionHandleOverlay oldWidget) {
1160
    super.didUpdateWidget(oldWidget);
1161
    oldWidget.visibility?.removeListener(_handleVisibilityChanged);
1162
    _handleVisibilityChanged();
1163
    widget.visibility?.addListener(_handleVisibilityChanged);
1164 1165 1166 1167
  }

  @override
  void dispose() {
1168
    widget.visibility?.removeListener(_handleVisibilityChanged);
1169 1170 1171 1172
    _controller.dispose();
    super.dispose();
  }

1173 1174
  @override
  Widget build(BuildContext context) {
1175
    final Offset handleAnchor = widget.selectionControls.getHandleAnchor(
1176 1177
      widget.type,
      widget.preferredLineHeight,
1178
    );
1179
    final Size handleSize = widget.selectionControls.getHandleSize(
1180
      widget.preferredLineHeight,
1181
    );
1182

1183
    final Rect handleRect = Rect.fromLTWH(
1184 1185
      -handleAnchor.dx,
      -handleAnchor.dy,
1186 1187 1188 1189 1190 1191
      handleSize.width,
      handleSize.height,
    );

    // Make sure the GestureDetector is big enough to be easily interactive.
    final Rect interactiveRect = handleRect.expandToInclude(
1192
      Rect.fromCircle(center: handleRect.center, radius: kMinInteractiveDimension/ 2),
1193 1194 1195 1196 1197 1198 1199 1200
    );
    final RelativeRect padding = RelativeRect.fromLTRB(
      math.max((interactiveRect.width - handleRect.width) / 2, 0),
      math.max((interactiveRect.height - handleRect.height) / 2, 0),
      math.max((interactiveRect.width - handleRect.width) / 2, 0),
      math.max((interactiveRect.height - handleRect.height) / 2, 0),
    );

1201
    return CompositedTransformFollower(
1202
      link: widget.handleLayerLink,
1203
      offset: interactiveRect.topLeft,
1204
      showWhenUnlinked: false,
1205 1206
      child: FadeTransition(
        opacity: _opacity,
1207 1208 1209 1210 1211 1212 1213
        child: Container(
          alignment: Alignment.topLeft,
          width: interactiveRect.width,
          height: interactiveRect.height,
          child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            dragStartBehavior: widget.dragStartBehavior,
1214 1215
            onPanStart: widget.onSelectionHandleDragStart,
            onPanUpdate: widget.onSelectionHandleDragUpdate,
1216
            onPanEnd: widget.onSelectionHandleDragEnd,
1217 1218 1219 1220 1221 1222 1223
            child: Padding(
              padding: EdgeInsets.only(
                left: padding.left,
                top: padding.top,
                right: padding.right,
                bottom: padding.bottom,
              ),
1224
              child: widget.selectionControls.buildHandle(
1225
                context,
1226 1227
                widget.type,
                widget.preferredLineHeight,
1228
                widget.onSelectionHandleTapped,
xster's avatar
xster committed
1229
              ),
1230
            ),
1231
          ),
1232
        ),
1233
      ),
1234 1235 1236
    );
  }
}
1237

1238 1239
/// Delegate interface for the [TextSelectionGestureDetectorBuilder].
///
1240
/// The interface is usually implemented by text field implementations wrapping
1241 1242
/// [EditableText], that use a [TextSelectionGestureDetectorBuilder] to build a
/// [TextSelectionGestureDetector] for their [EditableText]. The delegate provides
1243
/// the builder with information about the current state of the text field.
1244 1245 1246 1247 1248
/// Based on these information, the builder adds the correct gesture handlers
/// to the gesture detector.
///
/// See also:
///
1249
///  * [TextField], which implements this delegate for the Material text field.
1250
///  * [CupertinoTextField], which implements this delegate for the Cupertino
1251
///    text field.
1252 1253 1254 1255 1256
abstract class TextSelectionGestureDetectorBuilderDelegate {
  /// [GlobalKey] to the [EditableText] for which the
  /// [TextSelectionGestureDetectorBuilder] will build a [TextSelectionGestureDetector].
  GlobalKey<EditableTextState> get editableTextKey;

1257
  /// Whether the text field should respond to force presses.
1258 1259
  bool get forcePressEnabled;

1260
  /// Whether the user may select text in the text field.
1261 1262 1263 1264 1265 1266 1267
  bool get selectionEnabled;
}

/// Builds a [TextSelectionGestureDetector] to wrap an [EditableText].
///
/// The class implements sensible defaults for many user interactions
/// with an [EditableText] (see the documentation of the various gesture handler
1268 1269
/// methods, e.g. [onTapDown], [onForcePressStart], etc.). Subclasses of
/// [TextSelectionGestureDetectorBuilder] can change the behavior performed in
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
/// responds to these gesture events by overriding the corresponding handler
/// methods of this class.
///
/// The resulting [TextSelectionGestureDetector] to wrap an [EditableText] is
/// obtained by calling [buildGestureDetector].
///
/// See also:
///
///  * [TextField], which uses a subclass to implement the Material-specific
///    gesture logic of an [EditableText].
///  * [CupertinoTextField], which uses a subclass to implement the
///    Cupertino-specific gesture logic of an [EditableText].
class TextSelectionGestureDetectorBuilder {
  /// Creates a [TextSelectionGestureDetectorBuilder].
  ///
  /// The [delegate] must not be null.
  TextSelectionGestureDetectorBuilder({
1287
    required this.delegate,
1288 1289 1290 1291 1292
  }) : assert(delegate != null);

  /// The delegate for this [TextSelectionGestureDetectorBuilder].
  ///
  /// The delegate provides the builder with information about what actions can
1293
  /// currently be performed on the text field. Based on this, the builder adds
1294 1295 1296 1297
  /// the correct gesture handlers to the gesture detector.
  @protected
  final TextSelectionGestureDetectorBuilderDelegate delegate;

1298
  /// Returns true if lastSecondaryTapDownPosition was on selection.
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
  bool get _lastSecondaryTapWasOnSelection {
    assert(renderEditable.lastSecondaryTapDownPosition != null);
    if (renderEditable.selection == null) {
      return false;
    }

    final TextPosition textPosition = renderEditable.getPositionForPoint(
      renderEditable.lastSecondaryTapDownPosition!,
    );

1309 1310
    return renderEditable.selection!.start <= textPosition.offset
        && renderEditable.selection!.end >= textPosition.offset;
1311 1312
  }

1313 1314 1315 1316 1317
  // Expand the selection to the given global position.
  //
  // Either base or extent will be moved to the last tapped position, whichever
  // is closest. The selection will never shrink or pivot, only grow.
  //
1318 1319 1320
  // If fromSelection is given, will expand from that selection instead of the
  // current selection in renderEditable.
  //
1321 1322 1323 1324
  // See also:
  //
  //   * [_extendSelection], which is similar but pivots the selection around
  //     the base.
1325
  void _expandSelection(Offset offset, SelectionChangedCause cause, [TextSelection? fromSelection]) {
1326 1327 1328 1329 1330
    assert(cause != null);
    assert(offset != null);
    assert(renderEditable.selection?.baseOffset != null);

    final TextPosition tappedPosition = renderEditable.getPositionForPoint(offset);
1331
    final TextSelection selection = fromSelection ?? renderEditable.selection!;
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
    final bool baseIsCloser =
        (tappedPosition.offset - selection.baseOffset).abs()
        < (tappedPosition.offset - selection.extentOffset).abs();
    final TextSelection nextSelection = selection.copyWith(
      baseOffset: baseIsCloser ? selection.extentOffset : selection.baseOffset,
      extentOffset: tappedPosition.offset,
    );

    editableText.userUpdateTextEditingValue(
      editableText.textEditingValue.copyWith(
        selection: nextSelection,
      ),
      cause,
    );
  }

  // Extend the selection to the given global position.
  //
  // Holds the base in place and moves the extent.
  //
  // See also:
  //
  //   * [_expandSelection], which is similar but always increases the size of
  //     the selection.
  void _extendSelection(Offset offset, SelectionChangedCause cause) {
    assert(cause != null);
    assert(offset != null);
    assert(renderEditable.selection?.baseOffset != null);

    final TextPosition tappedPosition = renderEditable.getPositionForPoint(offset);
    final TextSelection selection = renderEditable.selection!;
    final TextSelection nextSelection = selection.copyWith(
      extentOffset: tappedPosition.offset,
    );

    editableText.userUpdateTextEditingValue(
      editableText.textEditingValue.copyWith(
        selection: nextSelection,
      ),
      cause,
    );
  }

1375
  /// Whether to show the selection toolbar.
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
  ///
  /// It is based on the signal source when a [onTapDown] is called. This getter
  /// will return true if current [onTapDown] event is triggered by a touch or
  /// a stylus.
  bool get shouldShowSelectionToolbar => _shouldShowSelectionToolbar;
  bool _shouldShowSelectionToolbar = true;

  /// The [State] of the [EditableText] for which the builder will provide a
  /// [TextSelectionGestureDetector].
  @protected
1386
  EditableTextState get editableText => delegate.editableTextKey.currentState!;
1387 1388 1389 1390

  /// The [RenderObject] of the [EditableText] for which the builder will
  /// provide a [TextSelectionGestureDetector].
  @protected
1391
  RenderEditable get renderEditable => editableText.renderEditable;
1392

1393
  // The viewport offset pixels of the [RenderEditable] at the last drag start.
1394 1395
  double _dragStartViewportOffset = 0.0;

1396 1397 1398 1399 1400 1401 1402 1403 1404
  // Returns true iff either shift key is currently down.
  bool get _isShiftPressed {
    return HardwareKeyboard.instance.logicalKeysPressed
      .any(<LogicalKeyboardKey>{
        LogicalKeyboardKey.shiftLeft,
        LogicalKeyboardKey.shiftRight,
      }.contains);
  }

1405 1406 1407
  // True iff a tap + shift has been detected but the tap has not yet come up.
  bool _isShiftTapping = false;

1408 1409 1410 1411 1412
  // For a shift + tap + drag gesture, the TextSelection at the point of the
  // tap. Mac uses this value to reset to the original selection when an
  // inversion of the base and offset happens.
  TextSelection? _shiftTapDragSelection;

1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
  /// Handler for [TextSelectionGestureDetector.onTapDown].
  ///
  /// By default, it forwards the tap to [RenderEditable.handleTapDown] and sets
  /// [shouldShowSelectionToolbar] to true if the tap was initiated by a finger or stylus.
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onTapDown], which triggers this callback.
  @protected
  void onTapDown(TapDownDetails details) {
    renderEditable.handleTapDown(details);
    // The selection overlay should only be shown when the user is interacting
    // through a touch screen (via either a finger or a stylus). A mouse shouldn't
    // trigger the selection overlay.
    // For backwards-compatibility, we treat a null kind the same as touch.
1428
    final PointerDeviceKind? kind = details.kind;
1429
    _shouldShowSelectionToolbar = kind == null
1430 1431
      || kind == PointerDeviceKind.touch
      || kind == PointerDeviceKind.stylus;
1432 1433

    // Handle shift + click selection if needed.
1434
    if (_isShiftPressed && renderEditable.selection?.baseOffset != null) {
1435 1436 1437 1438
      _isShiftTapping = true;
      switch (defaultTargetPlatform) {
        case TargetPlatform.iOS:
        case TargetPlatform.macOS:
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
          // On these platforms, a shift-tapped unfocused field expands from 0,
          // not from the previous selection.
          final TextSelection? fromSelection = renderEditable.hasFocus
              ? null
              : const TextSelection.collapsed(offset: 0);
          _expandSelection(
            details.globalPosition,
            SelectionChangedCause.tap,
            fromSelection,
          );
1449 1450 1451 1452 1453 1454 1455 1456 1457
          break;
        case TargetPlatform.android:
        case TargetPlatform.fuchsia:
        case TargetPlatform.linux:
        case TargetPlatform.windows:
          _extendSelection(details.globalPosition, SelectionChangedCause.tap);
          break;
      }
    }
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
  }

  /// Handler for [TextSelectionGestureDetector.onForcePressStart].
  ///
  /// By default, it selects the word at the position of the force press,
  /// if selection is enabled.
  ///
  /// This callback is only applicable when force press is enabled.
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onForcePressStart], which triggers this
  ///    callback.
  @protected
  void onForcePressStart(ForcePressDetails details) {
    assert(delegate.forcePressEnabled);
    _shouldShowSelectionToolbar = true;
    if (delegate.selectionEnabled) {
      renderEditable.selectWordsInRange(
        from: details.globalPosition,
        cause: SelectionChangedCause.forcePress,
      );
    }
  }

  /// Handler for [TextSelectionGestureDetector.onForcePressEnd].
  ///
  /// By default, it selects words in the range specified in [details] and shows
1486
  /// toolbar if it is necessary.
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
  ///
  /// This callback is only applicable when force press is enabled.
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onForcePressEnd], which triggers this
  ///    callback.
  @protected
  void onForcePressEnd(ForcePressDetails details) {
    assert(delegate.forcePressEnabled);
    renderEditable.selectWordsInRange(
      from: details.globalPosition,
      cause: SelectionChangedCause.forcePress,
    );
    if (shouldShowSelectionToolbar)
1502
      editableText.showToolbar();
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
  }

  /// Handler for [TextSelectionGestureDetector.onSingleTapUp].
  ///
  /// By default, it selects word edge if selection is enabled.
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onSingleTapUp], which triggers
  ///    this callback.
  @protected
  void onSingleTapUp(TapUpDetails details) {
1515 1516 1517 1518 1519
    if (_isShiftTapping) {
      _isShiftTapping = false;
      return;
    }

1520
    if (delegate.selectionEnabled) {
1521 1522 1523 1524 1525
      switch (defaultTargetPlatform) {
        case TargetPlatform.iOS:
        case TargetPlatform.macOS:
          switch (details.kind) {
            case PointerDeviceKind.mouse:
1526
            case PointerDeviceKind.trackpad:
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
            case PointerDeviceKind.stylus:
            case PointerDeviceKind.invertedStylus:
              // Precise devices should place the cursor at a precise position.
              renderEditable.selectPosition(cause: SelectionChangedCause.tap);
              break;
            case PointerDeviceKind.touch:
            case PointerDeviceKind.unknown:
              // On macOS/iOS/iPadOS a touch tap places the cursor at the edge
              // of the word.
              renderEditable.selectWordEdge(cause: SelectionChangedCause.tap);
              break;
          }
          break;
        case TargetPlatform.android:
        case TargetPlatform.fuchsia:
        case TargetPlatform.linux:
        case TargetPlatform.windows:
          renderEditable.selectPosition(cause: SelectionChangedCause.tap);
          break;
      }
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
    }
  }

  /// Handler for [TextSelectionGestureDetector.onSingleTapCancel].
  ///
  /// By default, it services as place holder to enable subclass override.
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onSingleTapCancel], which triggers
  ///    this callback.
  @protected
  void onSingleTapCancel() {/* Subclass should override this method if needed. */}

  /// Handler for [TextSelectionGestureDetector.onSingleLongTapStart].
  ///
  /// By default, it selects text position specified in [details] if selection
  /// is enabled.
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onSingleLongTapStart], which triggers
  ///    this callback.
  @protected
  void onSingleLongTapStart(LongPressStartDetails details) {
    if (delegate.selectionEnabled) {
      renderEditable.selectPositionAt(
        from: details.globalPosition,
        cause: SelectionChangedCause.longPress,
      );
    }
  }

  /// Handler for [TextSelectionGestureDetector.onSingleLongTapMoveUpdate].
  ///
  /// By default, it updates the selection location specified in [details] if
  /// selection is enabled.
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onSingleLongTapMoveUpdate], which
  ///    triggers this callback.
  @protected
  void onSingleLongTapMoveUpdate(LongPressMoveUpdateDetails details) {
    if (delegate.selectionEnabled) {
      renderEditable.selectPositionAt(
        from: details.globalPosition,
        cause: SelectionChangedCause.longPress,
      );
    }
  }

  /// Handler for [TextSelectionGestureDetector.onSingleLongTapEnd].
  ///
1601
  /// By default, it shows toolbar if necessary.
1602 1603 1604 1605 1606 1607 1608 1609
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onSingleLongTapEnd], which triggers this
  ///    callback.
  @protected
  void onSingleLongTapEnd(LongPressEndDetails details) {
    if (shouldShowSelectionToolbar)
1610
      editableText.showToolbar();
1611 1612
  }

1613 1614 1615 1616 1617
  /// Handler for [TextSelectionGestureDetector.onSecondaryTap].
  ///
  /// By default, selects the word if possible and shows the toolbar.
  @protected
  void onSecondaryTap() {
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
    if (!delegate.selectionEnabled) {
      return;
    }
    switch (defaultTargetPlatform) {
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
        if (!_lastSecondaryTapWasOnSelection) {
          renderEditable.selectWord(cause: SelectionChangedCause.tap);
        }
        if (shouldShowSelectionToolbar) {
          editableText.hideToolbar();
          editableText.showToolbar();
        }
        break;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        if (!renderEditable.hasFocus) {
          renderEditable.selectPosition(cause: SelectionChangedCause.tap);
        }
        editableText.toggleToolbar();
        break;
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
    }
  }

  /// Handler for [TextSelectionGestureDetector.onSecondaryTapDown].
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onSecondaryTapDown], which triggers this
  ///    callback.
  ///  * [onSecondaryTap], which is typically called after this.
  @protected
  void onSecondaryTapDown(TapDownDetails details) {
    renderEditable.handleSecondaryTapDown(details);
    _shouldShowSelectionToolbar = true;
  }

1657 1658
  /// Handler for [TextSelectionGestureDetector.onDoubleTapDown].
  ///
1659
  /// By default, it selects a word through [RenderEditable.selectWord] if
1660
  /// selectionEnabled and shows toolbar if necessary.
1661 1662 1663 1664 1665 1666 1667 1668
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onDoubleTapDown], which triggers this
  ///    callback.
  @protected
  void onDoubleTapDown(TapDownDetails details) {
    if (delegate.selectionEnabled) {
1669
      renderEditable.selectWord(cause: SelectionChangedCause.tap);
1670
      if (shouldShowSelectionToolbar)
1671
        editableText.showToolbar();
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
    }
  }

  /// Handler for [TextSelectionGestureDetector.onDragSelectionStart].
  ///
  /// By default, it selects a text position specified in [details].
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onDragSelectionStart], which triggers
  ///    this callback.
  @protected
  void onDragSelectionStart(DragStartDetails details) {
1685 1686
    if (!delegate.selectionEnabled)
      return;
1687 1688 1689 1690 1691
    final PointerDeviceKind? kind = details.kind;
    _shouldShowSelectionToolbar = kind == null
      || kind == PointerDeviceKind.touch
      || kind == PointerDeviceKind.stylus;

1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
    if (_isShiftPressed && renderEditable.selection != null && renderEditable.selection!.isValid) {
      _isShiftTapping = true;
      switch (defaultTargetPlatform) {
        case TargetPlatform.iOS:
        case TargetPlatform.macOS:
          _expandSelection(details.globalPosition, SelectionChangedCause.drag);
          break;
        case TargetPlatform.android:
        case TargetPlatform.fuchsia:
        case TargetPlatform.linux:
        case TargetPlatform.windows:
          _extendSelection(details.globalPosition, SelectionChangedCause.drag);
          break;
      }
      _shiftTapDragSelection = renderEditable.selection;
    } else {
      renderEditable.selectPositionAt(
        from: details.globalPosition,
        cause: SelectionChangedCause.drag,
      );
    }
1713 1714

    _dragStartViewportOffset = renderEditable.offset.pixels;
1715 1716 1717 1718
  }

  /// Handler for [TextSelectionGestureDetector.onDragSelectionUpdate].
  ///
1719 1720
  /// By default, it updates the selection location specified in the provided
  /// details objects.
1721 1722 1723 1724 1725 1726 1727
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onDragSelectionUpdate], which triggers
  ///    this callback./lib/src/material/text_field.dart
  @protected
  void onDragSelectionUpdate(DragStartDetails startDetails, DragUpdateDetails updateDetails) {
1728 1729
    if (!delegate.selectionEnabled)
      return;
1730

1731 1732 1733 1734 1735
    if (!_isShiftTapping) {
      // Adjust the drag start offset for possible viewport offset changes.
      final Offset startOffset = renderEditable.maxLines == 1
          ? Offset(renderEditable.offset.pixels - _dragStartViewportOffset, 0.0)
          : Offset(0.0, renderEditable.offset.pixels - _dragStartViewportOffset);
1736

1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
      return renderEditable.selectPositionAt(
        from: startDetails.globalPosition - startOffset,
        to: updateDetails.globalPosition,
        cause: SelectionChangedCause.drag,
      );
    }

    if (_shiftTapDragSelection!.isCollapsed
        || (defaultTargetPlatform != TargetPlatform.iOS
            && defaultTargetPlatform != TargetPlatform.macOS)) {
      return _extendSelection(updateDetails.globalPosition, SelectionChangedCause.drag);
    }

    // If the drag inverts the selection, Mac and iOS revert to the initial
    // selection.
    final TextSelection selection = editableText.textEditingValue.selection;
    final TextPosition nextExtent = renderEditable.getPositionForPoint(updateDetails.globalPosition);
    final bool isShiftTapDragSelectionForward =
        _shiftTapDragSelection!.baseOffset < _shiftTapDragSelection!.extentOffset;
    final bool isInverted = isShiftTapDragSelectionForward
        ? nextExtent.offset < _shiftTapDragSelection!.baseOffset
        : nextExtent.offset > _shiftTapDragSelection!.baseOffset;
    if (isInverted && selection.baseOffset == _shiftTapDragSelection!.baseOffset) {
      editableText.userUpdateTextEditingValue(
        editableText.textEditingValue.copyWith(
          selection: TextSelection(
            baseOffset: _shiftTapDragSelection!.extentOffset,
            extentOffset: nextExtent.offset,
          ),
        ),
        SelectionChangedCause.drag,
      );
    } else if (!isInverted
        && nextExtent.offset != _shiftTapDragSelection!.baseOffset
        && selection.baseOffset != _shiftTapDragSelection!.baseOffset) {
      editableText.userUpdateTextEditingValue(
        editableText.textEditingValue.copyWith(
          selection: TextSelection(
            baseOffset: _shiftTapDragSelection!.baseOffset,
            extentOffset: nextExtent.offset,
          ),
        ),
        SelectionChangedCause.drag,
      );
    } else {
      _extendSelection(updateDetails.globalPosition, SelectionChangedCause.drag);
    }
1784 1785 1786 1787
  }

  /// Handler for [TextSelectionGestureDetector.onDragSelectionEnd].
  ///
1788 1789
  /// By default, it simply cleans up the state used for handling certain
  /// built-in behaviors.
1790 1791 1792 1793 1794 1795
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onDragSelectionEnd], which triggers this
  ///    callback.
  @protected
1796 1797 1798 1799 1800 1801
  void onDragSelectionEnd(DragEndDetails details) {
    if (_isShiftTapping) {
      _isShiftTapping = false;
      _shiftTapDragSelection = null;
    }
  }
1802 1803 1804 1805 1806 1807

  /// Returns a [TextSelectionGestureDetector] configured with the handlers
  /// provided by this builder.
  ///
  /// The [child] or its subtree should contain [EditableText].
  Widget buildGestureDetector({
1808 1809 1810
    Key? key,
    HitTestBehavior? behavior,
    required Widget child,
1811 1812 1813 1814 1815 1816
  }) {
    return TextSelectionGestureDetector(
      key: key,
      onTapDown: onTapDown,
      onForcePressStart: delegate.forcePressEnabled ? onForcePressStart : null,
      onForcePressEnd: delegate.forcePressEnabled ? onForcePressEnd : null,
1817 1818
      onSecondaryTap: onSecondaryTap,
      onSecondaryTapDown: onSecondaryTapDown,
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
      onSingleTapUp: onSingleTapUp,
      onSingleTapCancel: onSingleTapCancel,
      onSingleLongTapStart: onSingleLongTapStart,
      onSingleLongTapMoveUpdate: onSingleLongTapMoveUpdate,
      onSingleLongTapEnd: onSingleLongTapEnd,
      onDoubleTapDown: onDoubleTapDown,
      onDragSelectionStart: onDragSelectionStart,
      onDragSelectionUpdate: onDragSelectionUpdate,
      onDragSelectionEnd: onDragSelectionEnd,
      behavior: behavior,
      child: child,
    );
  }
}

1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
/// A gesture detector to respond to non-exclusive event chains for a text field.
///
/// An ordinary [GestureDetector] configured to handle events like tap and
/// double tap will only recognize one or the other. This widget detects both:
/// first the tap and then, if another tap down occurs within a time limit, the
/// double tap.
///
/// See also:
///
///  * [TextField], a Material text field which uses this gesture detector.
///  * [CupertinoTextField], a Cupertino text field which uses this gesture
///    detector.
class TextSelectionGestureDetector extends StatefulWidget {
  /// Create a [TextSelectionGestureDetector].
  ///
  /// Multiple callbacks can be called for one sequence of input gesture.
  /// The [child] parameter must not be null.
  const TextSelectionGestureDetector({
1852
    super.key,
1853
    this.onTapDown,
1854 1855
    this.onForcePressStart,
    this.onForcePressEnd,
1856 1857
    this.onSecondaryTap,
    this.onSecondaryTapDown,
1858 1859
    this.onSingleTapUp,
    this.onSingleTapCancel,
1860 1861 1862
    this.onSingleLongTapStart,
    this.onSingleLongTapMoveUpdate,
    this.onSingleLongTapEnd,
1863
    this.onDoubleTapDown,
1864 1865 1866
    this.onDragSelectionStart,
    this.onDragSelectionUpdate,
    this.onDragSelectionEnd,
1867
    this.behavior,
1868
    required this.child,
1869
  }) : assert(child != null);
1870 1871 1872 1873

  /// Called for every tap down including every tap down that's part of a
  /// double click or a long press, except touches that include enough movement
  /// to not qualify as taps (e.g. pans and flings).
1874
  final GestureTapDownCallback? onTapDown;
1875

1876
  /// Called when a pointer has tapped down and the force of the pointer has
1877
  /// just become greater than [ForcePressGestureRecognizer.startPressure].
1878
  final GestureForcePressStartCallback? onForcePressStart;
1879 1880 1881

  /// Called when a pointer that had previously triggered [onForcePressStart] is
  /// lifted off the screen.
1882
  final GestureForcePressEndCallback? onForcePressEnd;
1883

1884 1885 1886 1887 1888 1889
  /// Called for a tap event with the secondary mouse button.
  final GestureTapCallback? onSecondaryTap;

  /// Called for a tap down event with the secondary mouse button.
  final GestureTapDownCallback? onSecondaryTapDown;

1890
  /// Called for each distinct tap except for every second tap of a double tap.
1891
  /// For example, if the detector was configured with [onTapDown] and
1892 1893
  /// [onDoubleTapDown], three quick taps would be recognized as a single tap
  /// down, followed by a double tap down, followed by a single tap down.
1894
  final GestureTapUpCallback? onSingleTapUp;
1895 1896 1897 1898

  /// Called for each touch that becomes recognized as a gesture that is not a
  /// short tap, such as a long tap or drag. It is called at the moment when
  /// another gesture from the touch is recognized.
1899
  final GestureTapCancelCallback? onSingleTapCancel;
1900 1901 1902 1903

  /// Called for a single long tap that's sustained for longer than
  /// [kLongPressTimeout] but not necessarily lifted. Not called for a
  /// double-tap-hold, which calls [onDoubleTapDown] instead.
1904
  final GestureLongPressStartCallback? onSingleLongTapStart;
1905 1906

  /// Called after [onSingleLongTapStart] when the pointer is dragged.
1907
  final GestureLongPressMoveUpdateCallback? onSingleLongTapMoveUpdate;
1908 1909

  /// Called after [onSingleLongTapStart] when the pointer is lifted.
1910
  final GestureLongPressEndCallback? onSingleLongTapEnd;
1911 1912 1913

  /// Called after a momentary hold or a short tap that is close in space and
  /// time (within [kDoubleTapTimeout]) to a previous short tap.
1914
  final GestureTapDownCallback? onDoubleTapDown;
1915

1916
  /// Called when a mouse starts dragging to select text.
1917
  final GestureDragStartCallback? onDragSelectionStart;
1918 1919 1920 1921 1922 1923

  /// Called repeatedly as a mouse moves while dragging.
  ///
  /// The frequency of calls is throttled to avoid excessive text layout
  /// operations in text fields. The throttling is controlled by the constant
  /// [_kDragSelectionUpdateThrottle].
1924
  final DragSelectionUpdateCallback? onDragSelectionUpdate;
1925 1926

  /// Called when a mouse that was previously dragging is released.
1927
  final GestureDragEndCallback? onDragSelectionEnd;
1928

1929 1930 1931
  /// How this gesture detector should behave during hit testing.
  ///
  /// This defaults to [HitTestBehavior.deferToChild].
1932
  final HitTestBehavior? behavior;
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942

  /// Child below this widget.
  final Widget child;

  @override
  State<StatefulWidget> createState() => _TextSelectionGestureDetectorState();
}

class _TextSelectionGestureDetectorState extends State<TextSelectionGestureDetector> {
  // Counts down for a short duration after a previous tap. Null otherwise.
1943 1944
  Timer? _doubleTapTimer;
  Offset? _lastTapOffset;
1945 1946 1947 1948 1949 1950 1951
  // True if a second tap down of a double tap is detected. Used to discard
  // subsequent tap up / tap hold of the same tap.
  bool _isDoubleTap = false;

  @override
  void dispose() {
    _doubleTapTimer?.cancel();
1952
    _dragUpdateThrottleTimer?.cancel();
1953 1954 1955 1956 1957 1958
    super.dispose();
  }

  // The down handler is force-run on success of a single tap and optimistically
  // run before a long press success.
  void _handleTapDown(TapDownDetails details) {
1959
    widget.onTapDown?.call(details);
1960 1961 1962 1963 1964 1965 1966
    // This isn't detected as a double tap gesture in the gesture recognizer
    // because it's 2 single taps, each of which may do different things depending
    // on whether it's a single tap, the first tap of a double tap, the second
    // tap held down, a clean double tap etc.
    if (_doubleTapTimer != null && _isWithinDoubleTapTolerance(details.globalPosition)) {
      // If there was already a previous tap, the second down hold/tap is a
      // double tap down.
1967
      widget.onDoubleTapDown?.call(details);
1968

1969
      _doubleTapTimer!.cancel();
1970 1971 1972 1973 1974 1975 1976
      _doubleTapTimeout();
      _isDoubleTap = true;
    }
  }

  void _handleTapUp(TapUpDetails details) {
    if (!_isDoubleTap) {
1977
      widget.onSingleTapUp?.call(details);
1978 1979 1980 1981 1982 1983 1984
      _lastTapOffset = details.globalPosition;
      _doubleTapTimer = Timer(kDoubleTapTimeout, _doubleTapTimeout);
    }
    _isDoubleTap = false;
  }

  void _handleTapCancel() {
1985
    widget.onSingleTapCancel?.call();
1986 1987
  }

1988 1989 1990
  DragStartDetails? _lastDragStartDetails;
  DragUpdateDetails? _lastDragUpdateDetails;
  Timer? _dragUpdateThrottleTimer;
1991 1992 1993 1994

  void _handleDragStart(DragStartDetails details) {
    assert(_lastDragStartDetails == null);
    _lastDragStartDetails = details;
1995
    widget.onDragSelectionStart?.call(details);
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
  }

  void _handleDragUpdate(DragUpdateDetails details) {
    _lastDragUpdateDetails = details;
    // Only schedule a new timer if there's no one pending.
    _dragUpdateThrottleTimer ??= Timer(_kDragSelectionUpdateThrottle, _handleDragUpdateThrottled);
  }

  /// Drag updates are being throttled to avoid excessive text layouts in text
  /// fields. The frequency of invocations is controlled by the constant
  /// [_kDragSelectionUpdateThrottle].
  ///
  /// Once the drag gesture ends, any pending drag update will be fired
  /// immediately. See [_handleDragEnd].
  void _handleDragUpdateThrottled() {
    assert(_lastDragStartDetails != null);
    assert(_lastDragUpdateDetails != null);
2013
    widget.onDragSelectionUpdate?.call(_lastDragStartDetails!, _lastDragUpdateDetails!);
2014 2015 2016 2017 2018 2019 2020 2021 2022
    _dragUpdateThrottleTimer = null;
    _lastDragUpdateDetails = null;
  }

  void _handleDragEnd(DragEndDetails details) {
    assert(_lastDragStartDetails != null);
    if (_dragUpdateThrottleTimer != null) {
      // If there's already an update scheduled, trigger it immediately and
      // cancel the timer.
2023
      _dragUpdateThrottleTimer!.cancel();
2024 2025
      _handleDragUpdateThrottled();
    }
2026
    widget.onDragSelectionEnd?.call(details);
2027 2028 2029 2030 2031
    _dragUpdateThrottleTimer = null;
    _lastDragStartDetails = null;
    _lastDragUpdateDetails = null;
  }

2032 2033 2034
  void _forcePressStarted(ForcePressDetails details) {
    _doubleTapTimer?.cancel();
    _doubleTapTimer = null;
2035
    widget.onForcePressStart?.call(details);
2036 2037 2038
  }

  void _forcePressEnded(ForcePressDetails details) {
2039
    widget.onForcePressEnd?.call(details);
2040 2041
  }

2042 2043
  void _handleLongPressStart(LongPressStartDetails details) {
    if (!_isDoubleTap && widget.onSingleLongTapStart != null) {
2044
      widget.onSingleLongTapStart!(details);
2045 2046 2047 2048 2049
    }
  }

  void _handleLongPressMoveUpdate(LongPressMoveUpdateDetails details) {
    if (!_isDoubleTap && widget.onSingleLongTapMoveUpdate != null) {
2050
      widget.onSingleLongTapMoveUpdate!(details);
2051 2052 2053
    }
  }

2054
  void _handleLongPressEnd(LongPressEndDetails details) {
2055
    if (!_isDoubleTap && widget.onSingleLongTapEnd != null) {
2056
      widget.onSingleLongTapEnd!(details);
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
    }
    _isDoubleTap = false;
  }

  void _doubleTapTimeout() {
    _doubleTapTimer = null;
    _lastTapOffset = null;
  }

  bool _isWithinDoubleTapTolerance(Offset secondTapOffset) {
    assert(secondTapOffset != null);
    if (_lastTapOffset == null) {
      return false;
    }

2072
    final Offset difference = secondTapOffset - _lastTapOffset!;
2073 2074 2075 2076 2077
    return difference.distance <= kDoubleTapSlop;
  }

  @override
  Widget build(BuildContext context) {
2078 2079
    final Map<Type, GestureRecognizerFactory> gestures = <Type, GestureRecognizerFactory>{};

2080 2081 2082
    gestures[TapGestureRecognizer] = GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
      () => TapGestureRecognizer(debugOwner: this),
      (TapGestureRecognizer instance) {
2083
        instance
2084 2085
          ..onSecondaryTap = widget.onSecondaryTap
          ..onSecondaryTapDown = widget.onSecondaryTapDown
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
          ..onTapDown = _handleTapDown
          ..onTapUp = _handleTapUp
          ..onTapCancel = _handleTapCancel;
      },
    );

    if (widget.onSingleLongTapStart != null ||
        widget.onSingleLongTapMoveUpdate != null ||
        widget.onSingleLongTapEnd != null) {
      gestures[LongPressGestureRecognizer] = GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
2096 2097
        () => LongPressGestureRecognizer(debugOwner: this, kind: PointerDeviceKind.touch),
        (LongPressGestureRecognizer instance) {
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
          instance
            ..onLongPressStart = _handleLongPressStart
            ..onLongPressMoveUpdate = _handleLongPressMoveUpdate
            ..onLongPressEnd = _handleLongPressEnd;
        },
      );
    }

    if (widget.onDragSelectionStart != null ||
        widget.onDragSelectionUpdate != null ||
        widget.onDragSelectionEnd != null) {
2109 2110 2111
      gestures[PanGestureRecognizer] = GestureRecognizerFactoryWithHandlers<PanGestureRecognizer>(
        () => PanGestureRecognizer(debugOwner: this, supportedDevices: <PointerDeviceKind>{ PointerDeviceKind.mouse }),
        (PanGestureRecognizer instance) {
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
          instance
            // Text selection should start from the position of the first pointer
            // down event.
            ..dragStartBehavior = DragStartBehavior.down
            ..onStart = _handleDragStart
            ..onUpdate = _handleDragUpdate
            ..onEnd = _handleDragEnd;
        },
      );
    }

    if (widget.onForcePressStart != null || widget.onForcePressEnd != null) {
      gestures[ForcePressGestureRecognizer] = GestureRecognizerFactoryWithHandlers<ForcePressGestureRecognizer>(
2125 2126
        () => ForcePressGestureRecognizer(debugOwner: this),
        (ForcePressGestureRecognizer instance) {
2127 2128 2129 2130 2131 2132 2133 2134 2135
          instance
            ..onStart = widget.onForcePressStart != null ? _forcePressStarted : null
            ..onEnd = widget.onForcePressEnd != null ? _forcePressEnded : null;
        },
      );
    }

    return RawGestureDetector(
      gestures: gestures,
2136 2137 2138 2139 2140 2141
      excludeFromSemantics: true,
      behavior: widget.behavior,
      child: widget.child,
    );
  }
}
2142

2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
/// A [ValueNotifier] whose [value] indicates whether the current contents of
/// the clipboard can be pasted.
///
/// The contents of the clipboard can only be read asynchronously, via
/// [Clipboard.getData], so this maintains a value that can be used
/// synchronously. Call [update] to asynchronously update value if needed.
class ClipboardStatusNotifier extends ValueNotifier<ClipboardStatus> with WidgetsBindingObserver {
  /// Create a new ClipboardStatusNotifier.
  ClipboardStatusNotifier({
    ClipboardStatus value = ClipboardStatus.unknown,
  }) : super(value);

  bool _disposed = false;
2156 2157
  // TODO(chunhtai): remove this getter once migration is done.
  // https://github.com/flutter/flutter/issues/99360
2158 2159
  /// True if this instance has been disposed.
  bool get disposed => _disposed;
2160 2161

  /// Check the [Clipboard] and update [value] if needed.
2162
  Future<void> update() async {
2163 2164
    if (_disposed) {
      return;
2165 2166
    }

2167
    final bool hasStrings;
2168
    try {
2169
      hasStrings = await Clipboard.hasStrings();
2170 2171 2172 2173 2174 2175 2176
    } catch (exception, stack) {
      FlutterError.reportError(FlutterErrorDetails(
        exception: exception,
        stack: stack,
        library: 'widget library',
        context: ErrorDescription('while checking if the clipboard has strings'),
      ));
2177 2178 2179
      // In the case of an error from the Clipboard API, set the value to
      // unknown so that it will try to update again later.
      if (_disposed || value == ClipboardStatus.unknown) {
2180 2181
        return;
      }
2182 2183 2184 2185
      value = ClipboardStatus.unknown;
      return;
    }

2186
    final ClipboardStatus nextStatus = hasStrings
2187 2188
        ? ClipboardStatus.pasteable
        : ClipboardStatus.notPasteable;
2189 2190

    if (_disposed || nextStatus == value) {
2191 2192
      return;
    }
2193
    value = nextStatus;
2194 2195 2196 2197 2198
  }

  @override
  void addListener(VoidCallback listener) {
    if (!hasListeners) {
2199
      WidgetsBinding.instance.addObserver(this);
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209
    }
    if (value == ClipboardStatus.unknown) {
      update();
    }
    super.addListener(listener);
  }

  @override
  void removeListener(VoidCallback listener) {
    super.removeListener(listener);
2210
    if (!_disposed && !hasListeners) {
2211
      WidgetsBinding.instance.removeObserver(this);
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        update();
        break;
      case AppLifecycleState.detached:
      case AppLifecycleState.inactive:
      case AppLifecycleState.paused:
        // Nothing to do.
    }
  }

  @override
  void dispose() {
2230
    WidgetsBinding.instance.removeObserver(this);
2231
    _disposed = true;
2232
    super.dispose();
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
  }
}

/// An enumeration of the status of the content on the user's clipboard.
enum ClipboardStatus {
  /// The clipboard content can be pasted, such as a String of nonzero length.
  pasteable,

  /// The status of the clipboard is unknown. Since getting clipboard data is
  /// asynchronous (see [Clipboard.getData]), this status often exists while
  /// waiting to receive the clipboard contents for the first time.
  unknown,

  /// The content on the clipboard is not pasteable, such as when it is empty.
  notPasteable,
}