text_selection.dart 93.6 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 'debug.dart';
20
import 'editable_text.dart';
21 22
import 'framework.dart';
import 'gesture_detector.dart';
23
import 'magnifier.dart';
24
import 'overlay.dart';
25
import 'tap_region.dart';
26
import 'ticker_provider.dart';
27
import 'transitions.dart';
28

29
export 'package:flutter/rendering.dart' show TextSelectionPoint;
jslavitz's avatar
jslavitz committed
30 31
export 'package:flutter/services.dart' show TextSelectionDelegate;

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
/// A duration that controls how often the drag selection update callback is
/// called.
const Duration _kDragSelectionUpdateThrottle = Duration(milliseconds: 50);

/// 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);

49 50 51 52 53 54 55 56 57 58 59
/// 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);

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
/// 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';
}

76
/// An interface for building the selection UI, to be provided by the
77
/// implementer of the toolbar widget.
xster's avatar
xster committed
78 79
///
/// Override text operations such as [handleCut] if needed.
80 81 82 83 84
///
/// See also:
///
///  * [SelectionArea], which selects appropriate text selection controls
///    based on the current platform.
85
abstract class TextSelectionControls {
86
  /// Builds a selection handle of the given `type`.
xster's avatar
xster committed
87 88 89
  ///
  /// The top left corner of this widget is positioned at the bottom of the
  /// selection position.
90 91 92 93 94
  ///
  /// 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.
95
  Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]);
96

97 98 99
  /// 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.
100
  Offset getHandleAnchor(TextSelectionHandleType type, double textLineHeight);
101

102 103 104
  /// Builds a toolbar near a text selection.
  ///
  /// Typically displays buttons for copying and pasting text.
105
  ///
106 107
  /// The [globalEditableRegion] parameter is the TextField size of the global
  /// coordinate system in logical pixels.
108
  ///
109 110
  /// The [textLineHeight] parameter is the [RenderEditable.preferredLineHeight]
  /// of the [RenderEditable] we are building a toolbar for.
111
  ///
112 113 114
  /// The [selectionMidpoint] parameter is a general calculation midpoint
  /// parameter of the toolbar. More detailed position information
  /// is computable from the [endpoints] parameter.
115 116 117
  Widget buildToolbar(
    BuildContext context,
    Rect globalEditableRegion,
118
    double textLineHeight,
119
    Offset selectionMidpoint,
120 121
    List<TextSelectionPoint> endpoints,
    TextSelectionDelegate delegate,
122
    // TODO(chunhtai): Change to ValueListenable<ClipboardStatus>? once
123
    // migration is done. https://github.com/flutter/flutter/issues/99360
124
    ClipboardStatusNotifier? clipboardStatus,
125
    Offset? lastSecondaryTapDownPosition,
126
  );
127 128

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

131 132 133 134 135 136 137 138 139
  /// 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) {
140
    return delegate.cutEnabled && !delegate.textEditingValue.selection.isCollapsed;
141 142 143 144 145 146 147 148 149 150
  }

  /// 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) {
151
    return delegate.copyEnabled && !delegate.textEditingValue.selection.isCollapsed;
152 153
  }

154 155
  /// Whether the text field managed by the given `delegate` supports pasting
  /// from the clipboard.
156 157 158
  ///
  /// Subclasses can use this to decide if they should expose the paste
  /// functionality to the user.
159 160 161 162
  ///
  /// This does not consider the contents of the clipboard. Subclasses may want
  /// to, for example, disallow pasting when the clipboard contains an empty
  /// string.
163
  bool canPaste(TextSelectionDelegate delegate) {
164
    return delegate.pasteEnabled;
165 166
  }

167
  /// Whether the current selection of the text field managed by the given
168 169 170 171 172 173
  /// `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) {
174
    return delegate.selectAllEnabled && delegate.textEditingValue.text.isNotEmpty && delegate.textEditingValue.selection.isCollapsed;
175 176
  }

177
  /// Call [TextSelectionDelegate.cutSelection] to cut current selection.
178 179 180
  ///
  /// This is called by subclasses when their cut affordance is activated by
  /// the user.
181 182 183
  // TODO(chunhtai): remove optional parameter once migration is done.
  // https://github.com/flutter/flutter/issues/99360
  void handleCut(TextSelectionDelegate delegate, [ClipboardStatusNotifier? clipboardStatus]) {
184
    delegate.cutSelection(SelectionChangedCause.toolbar);
xster's avatar
xster committed
185 186
  }

187
  /// Call [TextSelectionDelegate.copySelection] to copy current selection.
188 189 190
  ///
  /// This is called by subclasses when their copy affordance is activated by
  /// the user.
191 192 193
  // TODO(chunhtai): remove optional parameter once migration is done.
  // https://github.com/flutter/flutter/issues/99360
  void handleCopy(TextSelectionDelegate delegate, [ClipboardStatusNotifier? clipboardStatus]) {
194
    delegate.copySelection(SelectionChangedCause.toolbar);
xster's avatar
xster committed
195 196
  }

197
  /// Call [TextSelectionDelegate.pasteText] to paste text.
198 199 200 201 202 203 204 205
  ///
  /// 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
206
  Future<void> handlePaste(TextSelectionDelegate delegate) async {
207
    delegate.pasteText(SelectionChangedCause.toolbar);
xster's avatar
xster committed
208 209
  }

210 211
  /// Call [TextSelectionDelegate.selectAll] to set the current selection to
  /// contain the entire text value.
212 213 214 215 216
  ///
  /// 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
217
  void handleSelectAll(TextSelectionDelegate delegate) {
218
    delegate.selectAll(SelectionChangedCause.toolbar);
xster's avatar
xster committed
219
  }
220 221
}

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
/// Text selection controls that do not show any toolbars or handles.
///
/// This is a placeholder, suitable for temporary use during development, but
/// not practical for production. For example, it provides no way for the user
/// to interact with selections: no context menus on desktop, no toolbars or
/// drag handles on mobile, etc. For production, consider using
/// [MaterialTextSelectionControls] or creating a custom subclass of
/// [TextSelectionControls].
///
/// The [emptyTextSelectionControls] global variable has a
/// suitable instance of this class.
class EmptyTextSelectionControls extends TextSelectionControls {
  @override
  Size getHandleSize(double textLineHeight) => Size.zero;

  @override
  Widget buildToolbar(
    BuildContext context,
    Rect globalEditableRegion,
    double textLineHeight,
    Offset selectionMidpoint,
    List<TextSelectionPoint> endpoints,
    TextSelectionDelegate delegate,
    ValueListenable<ClipboardStatus>? clipboardStatus,
    Offset? lastSecondaryTapDownPosition,
  ) => const SizedBox.shrink();

  @override
  Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]) {
    return const SizedBox.shrink();
  }

  @override
  Offset getHandleAnchor(TextSelectionHandleType type, double textLineHeight) {
    return Offset.zero;
  }
}

/// Text selection controls that do not show any toolbars or handles.
///
/// This is a placeholder, suitable for temporary use during development, but
/// not practical for production. For example, it provides no way for the user
/// to interact with selections: no context menus on desktop, no toolbars or
/// drag handles on mobile, etc. For production, consider using
/// [materialTextSelectionControls] or creating a custom subclass of
/// [TextSelectionControls].
final TextSelectionControls emptyTextSelectionControls = EmptyTextSelectionControls();


271 272
/// An object that manages a pair of text selection handles for a
/// [RenderEditable].
273
///
274 275 276
/// This class is a wrapper of [SelectionOverlay] to provide APIs specific for
/// [RenderEditable]s. To manage selection handles for custom widgets, use
/// [SelectionOverlay] instead.
277
class TextSelectionOverlay {
Marc Plano-Lesay's avatar
Marc Plano-Lesay committed
278
  /// Creates an object that manages overlay entries for selection handles.
279 280
  ///
  /// The [context] must not be null and must have an [Overlay] as an ancestor.
281
  TextSelectionOverlay({
282
    required TextEditingValue value,
283
    required this.context,
284 285 286 287
    Widget? debugRequiredFor,
    required LayerLink toolbarLayerLink,
    required LayerLink startHandleLayerLink,
    required LayerLink endHandleLayerLink,
288
    required this.renderObject,
289
    this.selectionControls,
290
    bool handlesVisible = false,
291
    required this.selectionDelegate,
292 293 294
    DragStartBehavior dragStartBehavior = DragStartBehavior.start,
    VoidCallback? onSelectionHandleTapped,
    ClipboardStatusNotifier? clipboardStatus,
295
    required TextMagnifierConfiguration magnifierConfiguration,
296 297
  }) : assert(value != null),
       assert(context != null),
298 299
       assert(handlesVisible != null),
       _handlesVisible = handlesVisible,
300
       _value = value {
301 302 303
    renderObject.selectionStartInViewport.addListener(_updateTextSelectionOverlayVisibilities);
    renderObject.selectionEndInViewport.addListener(_updateTextSelectionOverlayVisibilities);
    _updateTextSelectionOverlayVisibilities();
304
    _selectionOverlay = SelectionOverlay(
305
      magnifierConfiguration: magnifierConfiguration,
306 307 308 309 310 311 312 313
      context: context,
      debugRequiredFor: debugRequiredFor,
      // The metrics will be set when show handles.
      startHandleType: TextSelectionHandleType.collapsed,
      startHandlesVisible: _effectiveStartHandleVisibility,
      lineHeightAtStart: 0.0,
      onStartHandleDragStart: _handleSelectionStartHandleDragStart,
      onStartHandleDragUpdate: _handleSelectionStartHandleDragUpdate,
314
      onEndHandleDragEnd: _handleAnyDragEnd,
315 316 317 318 319
      endHandleType: TextSelectionHandleType.collapsed,
      endHandlesVisible: _effectiveEndHandleVisibility,
      lineHeightAtEnd: 0.0,
      onEndHandleDragStart: _handleSelectionEndHandleDragStart,
      onEndHandleDragUpdate: _handleSelectionEndHandleDragUpdate,
320
      onStartHandleDragEnd: _handleAnyDragEnd,
321
      toolbarVisible: _effectiveToolbarVisibility,
322
      selectionEndpoints: const <TextSelectionPoint>[],
323 324 325 326 327 328 329 330 331 332 333 334
      selectionControls: selectionControls,
      selectionDelegate: selectionDelegate,
      clipboardStatus: clipboardStatus,
      startHandleLayerLink: startHandleLayerLink,
      endHandleLayerLink: endHandleLayerLink,
      toolbarLayerLink: toolbarLayerLink,
      onSelectionHandleTapped: onSelectionHandleTapped,
      dragStartBehavior: dragStartBehavior,
      toolbarLocation: renderObject.lastSecondaryTapDownPosition,
    );
  }

335 336 337 338 339 340 341
  /// 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;

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
  // 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);
365
  final ValueNotifier<bool> _effectiveToolbarVisibility = ValueNotifier<bool>(false);
366 367 368 369 370 371 372

  /// 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].
  final BuildContext context;

373
  void _updateTextSelectionOverlayVisibilities() {
374 375
    _effectiveStartHandleVisibility.value = _handlesVisible && renderObject.selectionStartInViewport.value;
    _effectiveEndHandleVisibility.value = _handlesVisible && renderObject.selectionEndInViewport.value;
376
    _effectiveToolbarVisibility.value = renderObject.selectionStartInViewport.value || renderObject.selectionEndInViewport.value;
377 378 379 380 381 382 383 384 385 386 387 388
  }

  /// 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);
389
    if (_handlesVisible == visible) {
390
      return;
391
    }
392
    _handlesVisible = visible;
393
    _updateTextSelectionOverlayVisibilities();
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
  }

  /// {@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();
  }

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
  /// {@macro flutter.widgets.SelectionOverlay.showMagnifier}
  void showMagnifier(Offset positionToShow) {
    final TextPosition position = renderObject.getPositionForPoint(positionToShow);
    _updateSelectionOverlay();
    _selectionOverlay.showMagnifier(
      _buildMagnifier(
        currentTextPosition: position,
        globalGesturePosition: positionToShow,
        renderEditable: renderObject,
      ),
    );
  }

  /// {@macro flutter.widgets.SelectionOverlay.updateMagnifier}
  void updateMagnifier(Offset positionToShow) {
    final TextPosition position = renderObject.getPositionForPoint(positionToShow);
    _updateSelectionOverlay();
    _selectionOverlay.updateMagnifier(
      _buildMagnifier(
        currentTextPosition: position,
        globalGesturePosition: positionToShow,
        renderEditable: renderObject,
      ),
    );
  }

  /// {@macro flutter.widgets.SelectionOverlay.hideMagnifier}
  void hideMagnifier({required bool shouldShowToolbar}) {
    _selectionOverlay.hideMagnifier(shouldShowToolbar: shouldShowToolbar);
  }

442 443 444 445 446 447 448 449 450 451
  /// 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) {
452
    if (_value == newValue) {
453
      return;
454
    }
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    _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.
475
      ..selectionEndpoints = renderObject.getEndpointsForSelection(_selection)
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
      ..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;

491 492 493
  /// Whether the magnifier is currently visible.
  bool get magnifierIsVisible => _selectionOverlay._magnifierController.shown;

494 495 496 497 498 499 500 501 502
  /// {@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();
503 504 505 506 507
    renderObject.selectionStartInViewport.removeListener(_updateTextSelectionOverlayVisibilities);
    renderObject.selectionEndInViewport.removeListener(_updateTextSelectionOverlayVisibilities);
    _effectiveToolbarVisibility.dispose();
    _effectiveStartHandleVisibility.dispose();
    _effectiveEndHandleVisibility.dispose();
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
  }

  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;
  }

546
  MagnifierInfo _buildMagnifier({
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
    required RenderEditable renderEditable,
    required Offset globalGesturePosition,
    required TextPosition currentTextPosition,
  }) {
    final Offset globalRenderEditableTopLeft = renderEditable.localToGlobal(Offset.zero);
    final Rect localCaretRect = renderEditable.getLocalRectForCaret(currentTextPosition);

    final TextSelection lineAtOffset = renderEditable.getLineAtOffset(currentTextPosition);
    final TextPosition positionAtEndOfLine = TextPosition(
        offset: lineAtOffset.extentOffset,
        affinity: TextAffinity.upstream,
    );

    // Default affinity is downstream.
    final TextPosition positionAtBeginningOfLine = TextPosition(
      offset: lineAtOffset.baseOffset,
    );

    final Rect lineBoundaries = Rect.fromPoints(
      renderEditable.getLocalRectForCaret(positionAtBeginningOfLine).topCenter,
      renderEditable.getLocalRectForCaret(positionAtEndOfLine).bottomCenter,
    );

570
    return MagnifierInfo(
571 572 573 574 575 576 577
      fieldBounds: globalRenderEditableTopLeft & renderEditable.size,
      globalGesturePosition: globalGesturePosition,
      caretRect: localCaretRect.shift(globalRenderEditableTopLeft),
      currentLineBoundaries: lineBoundaries.shift(globalRenderEditableTopLeft),
    );
  }

578 579 580
  late Offset _dragEndPosition;

  void _handleSelectionEndHandleDragStart(DragStartDetails details) {
581 582 583
    if (!renderObject.attached) {
      return;
    }
584 585 586
    final Size handleSize = selectionControls!.getHandleSize(
      renderObject.preferredLineHeight,
    );
587

588
    _dragEndPosition = details.globalPosition + Offset(0.0, -handleSize.height);
589 590
    final TextPosition position = renderObject.getPositionForPoint(_dragEndPosition);

591 592 593 594 595 596 597
    _selectionOverlay.showMagnifier(
      _buildMagnifier(
        currentTextPosition: position,
        globalGesturePosition: details.globalPosition,
        renderEditable: renderObject,
      ),
    );
598 599 600
  }

  void _handleSelectionEndHandleDragUpdate(DragUpdateDetails details) {
601 602 603
    if (!renderObject.attached) {
      return;
    }
604
    _dragEndPosition += details.delta;
605

606
    final TextPosition position = renderObject.getPositionForPoint(_dragEndPosition);
607
    final TextSelection currentSelection = TextSelection.fromPosition(position);
608 609

    if (_selection.isCollapsed) {
610
      _selectionOverlay.updateMagnifier(_buildMagnifier(
611 612 613 614 615 616
        currentTextPosition: position,
        globalGesturePosition: details.globalPosition,
        renderEditable: renderObject,
      ));

      _handleSelectionHandleChanged(currentSelection, isEnd: true);
617 618 619
      return;
    }

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
    final TextSelection newSelection;
    switch (defaultTargetPlatform) {
      // On Apple platforms, dragging the base handle makes it the extent.
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
        newSelection = TextSelection(
          extentOffset: position.offset,
          baseOffset: _selection.start,
        );
        if (position.offset <= _selection.start) {
          return; // Don't allow order swapping.
        }
        break;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        newSelection = TextSelection(
          baseOffset: _selection.baseOffset,
          extentOffset: position.offset,
        );
        if (newSelection.baseOffset >= newSelection.extentOffset) {
          return; // Don't allow order swapping.
        }
        break;
645
    }
646 647

    _handleSelectionHandleChanged(newSelection, isEnd: true);
648

649
     _selectionOverlay.updateMagnifier(_buildMagnifier(
650 651 652 653
      currentTextPosition: newSelection.extent,
      globalGesturePosition: details.globalPosition,
      renderEditable: renderObject,
    ));
654 655 656 657 658
  }

  late Offset _dragStartPosition;

  void _handleSelectionStartHandleDragStart(DragStartDetails details) {
659 660 661
    if (!renderObject.attached) {
      return;
    }
662 663 664 665
    final Size handleSize = selectionControls!.getHandleSize(
      renderObject.preferredLineHeight,
    );
    _dragStartPosition = details.globalPosition + Offset(0.0, -handleSize.height);
666 667
    final TextPosition position = renderObject.getPositionForPoint(_dragStartPosition);

668 669 670 671 672 673 674
    _selectionOverlay.showMagnifier(
      _buildMagnifier(
        currentTextPosition: position,
        globalGesturePosition: details.globalPosition,
        renderEditable: renderObject,
      ),
    );
675 676 677
  }

  void _handleSelectionStartHandleDragUpdate(DragUpdateDetails details) {
678 679 680
    if (!renderObject.attached) {
      return;
    }
681 682 683 684
    _dragStartPosition += details.delta;
    final TextPosition position = renderObject.getPositionForPoint(_dragStartPosition);

    if (_selection.isCollapsed) {
685
      _selectionOverlay.updateMagnifier(_buildMagnifier(
686 687 688 689 690
        currentTextPosition: position,
        globalGesturePosition: details.globalPosition,
        renderEditable: renderObject,
      ));

691 692 693 694
      _handleSelectionHandleChanged(TextSelection.fromPosition(position), isEnd: false);
      return;
    }

695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
    final TextSelection newSelection;
    switch (defaultTargetPlatform) {
      // On Apple platforms, dragging the base handle makes it the extent.
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
        newSelection = TextSelection(
          extentOffset: position.offset,
          baseOffset: _selection.end,
        );
        if (newSelection.extentOffset >= _selection.end) {
          return; // Don't allow order swapping.
        }
        break;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        newSelection = TextSelection(
          baseOffset: position.offset,
          extentOffset: _selection.extentOffset,
        );
        if (newSelection.baseOffset >= newSelection.extentOffset) {
          return; // Don't allow order swapping.
        }
        break;
720
    }
721

722
    _selectionOverlay.updateMagnifier(_buildMagnifier(
723 724 725 726 727
      currentTextPosition: newSelection.extent.offset < newSelection.base.offset ? newSelection.extent : newSelection.base,
      globalGesturePosition: details.globalPosition,
      renderEditable: renderObject,
    ));

728 729 730
    _handleSelectionHandleChanged(newSelection, isEnd: false);
  }

731 732
  void _handleAnyDragEnd(DragEndDetails details) => _selectionOverlay.hideMagnifier(shouldShowToolbar: !_selection.isCollapsed);

733 734 735 736 737 738 739 740 741 742 743 744 745 746
  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,
      ) {
747
    if (_selection.isCollapsed) {
748
      return TextSelectionHandleType.collapsed;
749
    }
750 751 752 753 754 755 756 757 758 759 760

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

761
/// An object that manages a pair of selection handles and a toolbar.
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
///
/// 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,
784
    this.toolbarVisible,
785
    required List<TextSelectionPoint> selectionEndpoints,
786 787 788 789 790 791 792 793 794
    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,
795
    this.magnifierConfiguration = TextMagnifierConfiguration.disabled,
796 797 798 799
  }) : _startHandleType = startHandleType,
       _lineHeightAtStart = lineHeightAtStart,
       _endHandleType = endHandleType,
       _lineHeightAtEnd = lineHeightAtEnd,
800
       _selectionEndpoints = selectionEndpoints,
801 802
       _toolbarLocation = toolbarLocation,
       assert(debugCheckHasOverlay(context));
803

804 805 806 807
  /// 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].
808
  final BuildContext context;
809

810

811 812
  final ValueNotifier<MagnifierInfo> _magnifierInfo =
      ValueNotifier<MagnifierInfo>(MagnifierInfo.empty);
813 814 815 816 817 818 819

  /// [MagnifierController.show] and [MagnifierController.hide] should not be called directly, except
  /// from inside [showMagnifier] and [hideMagnifier]. If it is desired to show or hide the magnifier,
  /// call [showMagnifier] or [hideMagnifier]. This is because the magnifier needs to orchestrate
  /// with other properties in [SelectionOverlay].
  final MagnifierController _magnifierController = MagnifierController();

820
  /// {@macro flutter.widgets.magnifier.TextMagnifierConfiguration.intro}
821 822 823 824 825
  ///
  /// {@macro flutter.widgets.magnifier.intro}
  ///
  /// By default, [SelectionOverlay]'s [TextMagnifierConfiguration] is disabled.
  ///
826
  /// {@macro flutter.widgets.magnifier.TextMagnifierConfiguration.details}
827 828
  final TextMagnifierConfiguration magnifierConfiguration;

829
  /// {@template flutter.widgets.SelectionOverlay.showMagnifier}
830 831 832 833 834
  /// Shows the magnifier, and hides the toolbar if it was showing when [showMagnifier]
  /// was called. This is safe to call on platforms not mobile, since
  /// a magnifierBuilder will not be provided, or the magnifierBuilder will return null
  /// on platforms not mobile.
  ///
835
  /// This is NOT the source of truth for if the magnifier is up or not,
836 837
  /// since magnifiers may hide themselves. If this info is needed, check
  /// [MagnifierController.shown].
838
  /// {@endtemplate}
839
  void showMagnifier(MagnifierInfo initalMagnifierInfo) {
840 841 842 843
    if (_toolbar != null) {
      hideToolbar();
    }

844 845
    // Start from empty, so we don't utilize any rememnant values.
    _magnifierInfo.value = initalMagnifierInfo;
846 847 848 849 850 851 852

    // Pre-build the magnifiers so we can tell if we've built something
    // or not. If we don't build a magnifiers, then we should not
    // insert anything in the overlay.
    final Widget? builtMagnifier = magnifierConfiguration.magnifierBuilder(
      context,
      _magnifierController,
853
      _magnifierInfo,
854 855
    );

856
    if (builtMagnifier == null) {
857 858 859 860 861 862 863
      return;
    }

    _magnifierController.show(
        context: context,
        below: magnifierConfiguration.shouldDisplayHandlesInMagnifier
            ? null
864
            : _handles?.first,
865 866 867
        builder: (_) => builtMagnifier);
  }

868
  /// {@template flutter.widgets.SelectionOverlay.hideMagnifier}
869 870 871 872
  /// Hide the current magnifier, optionally immediately showing
  /// the toolbar.
  ///
  /// This does nothing if there is no magnifier.
873
  /// {@endtemplate}
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
  void hideMagnifier({required bool shouldShowToolbar}) {
    // This cannot be a check on `MagnifierController.shown`, since
    // it's possible that the magnifier is still in the overlay, but
    // not shown in cases where the magnifier hides itself.
    if (_magnifierController.overlayEntry == null) {
      return;
    }

    _magnifierController.hide();

    if (shouldShowToolbar) {
      showToolbar();
    }
  }

889 890 891 892 893 894
  /// 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) {
895
    if (_startHandleType == value) {
896
      return;
897
    }
898 899 900 901 902 903 904 905 906 907 908 909
    _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) {
910
    if (_lineHeightAtStart == value) {
911
      return;
912
    }
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
    _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) {
941
    if (_endHandleType == value) {
942
      return;
943
    }
944 945 946 947 948 949 950 951 952 953 954 955
    _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) {
956
    if (_lineHeightAtEnd == value) {
957
      return;
958
    }
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
    _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;

981 982 983 984 985 986 987 988
  /// 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;

989
  /// The text selection positions of selection start and end.
990 991 992 993
  List<TextSelectionPoint> get selectionEndpoints => _selectionEndpoints;
  List<TextSelectionPoint> _selectionEndpoints;
  set selectionEndpoints(List<TextSelectionPoint> value) {
    if (!listEquals(_selectionEndpoints, value)) {
994 995
      _markNeedsBuild();
    }
996
    _selectionEndpoints = value;
997 998
  }

999
  /// Debugging information for explaining why the [Overlay] is required.
1000
  final Widget? debugRequiredFor;
1001

1002 1003
  /// The object supplied to the [CompositedTransformTarget] that wraps the text
  /// field.
1004 1005 1006 1007 1008 1009 1010 1011 1012
  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;
1013

1014
  /// {@template flutter.widgets.SelectionOverlay.selectionControls}
1015
  /// Builds text selection handles and toolbar.
1016
  /// {@endtemplate}
1017
  final TextSelectionControls? selectionControls;
1018

1019
  /// {@template flutter.widgets.SelectionOverlay.selectionDelegate}
1020 1021
  /// The delegate for manipulating the current selection in the owning
  /// text field.
1022
  /// {@endtemplate}
1023
  final TextSelectionDelegate selectionDelegate;
1024

1025 1026 1027
  /// Determines the way that drag start behavior is handled.
  ///
  /// If set to [DragStartBehavior.start], handle drag behavior will
1028 1029 1030
  /// 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.
1031 1032 1033 1034 1035
  ///
  /// 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.
  ///
1036
  /// By default, the drag start behavior is [DragStartBehavior.start].
1037 1038 1039 1040 1041 1042
  ///
  /// See also:
  ///
  ///  * [DragGestureRecognizer.dragStartBehavior], which gives an example for the different behaviors.
  final DragStartBehavior dragStartBehavior;

1043
  /// {@template flutter.widgets.SelectionOverlay.onSelectionHandleTapped}
1044 1045 1046
  /// 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
1047
  /// uses decides where the handle's tap "hotspot" is, or whether the
1048 1049 1050 1051 1052 1053
  /// 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.
1054
  /// {@endtemplate}
1055 1056
  // See https://github.com/flutter/flutter/issues/39376#issuecomment-848406415
  // for provenance.
1057
  final VoidCallback? onSelectionHandleTapped;
1058

1059 1060 1061 1062 1063
  /// 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]).
1064
  final ClipboardStatusNotifier? clipboardStatus;
1065

1066 1067 1068
  /// The location of where the toolbar should be drawn in relative to the
  /// location of [toolbarLayerLink].
  ///
1069
  /// If this is null, the toolbar is drawn based on [selectionEndpoints] and
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
  /// 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();
  }

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

1087 1088
  /// A pair of handles. If this is non-null, there are always 2, though the
  /// second is hidden when the selection is collapsed.
1089
  List<OverlayEntry>? _handles;
1090

1091
  /// A copy/paste toolbar.
1092
  OverlayEntry? _toolbar;
1093

1094
  /// {@template flutter.widgets.SelectionOverlay.showHandles}
1095
  /// Builds the handles by inserting them into the [context]'s overlay.
1096
  /// {@endtemplate}
1097
  void showHandles() {
1098
    if (_handles != null) {
1099
      return;
1100
    }
1101

1102
    _handles = <OverlayEntry>[
1103 1104
      OverlayEntry(builder: _buildStartHandle),
      OverlayEntry(builder: _buildEndHandle),
1105
    ];
1106

1107
    Overlay.of(context, rootOverlay: true, debugRequiredFor: debugRequiredFor).insertAll(_handles!);
1108 1109
  }

1110
  /// {@template flutter.widgets.SelectionOverlay.hideHandles}
1111
  /// Destroys the handles by removing them from overlay.
1112
  /// {@endtemplate}
1113 1114
  void hideHandles() {
    if (_handles != null) {
1115 1116
      _handles![0].remove();
      _handles![1].remove();
1117 1118 1119 1120
      _handles = null;
    }
  }

1121
  /// {@template flutter.widgets.SelectionOverlay.showToolbar}
1122
  /// Shows the toolbar by inserting it into the [context]'s overlay.
1123
  /// {@endtemplate}
1124
  void showToolbar() {
1125
    if (_toolbar != null) {
1126 1127
      return;
    }
1128
    _toolbar = OverlayEntry(builder: _buildToolbar);
1129
    Overlay.of(context, rootOverlay: true, debugRequiredFor: debugRequiredFor).insert(_toolbar!);
1130 1131
  }

1132 1133
  bool _buildScheduled = false;
  void _markNeedsBuild() {
1134
    if (_handles == null && _toolbar == null) {
1135
      return;
1136
    }
1137 1138
    // If we are in build state, it will be too late to update visibility.
    // We will need to schedule the build in next frame.
1139
    if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
1140
      if (_buildScheduled) {
1141
        return;
1142
      }
1143 1144 1145 1146 1147 1148 1149 1150 1151
      _buildScheduled = true;
      SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
        _buildScheduled = false;
        if (_handles != null) {
          _handles![0].markNeedsBuild();
          _handles![1].markNeedsBuild();
        }
        _toolbar?.markNeedsBuild();
      });
1152
    } else {
1153 1154 1155 1156 1157
      if (_handles != null) {
        _handles![0].markNeedsBuild();
        _handles![1].markNeedsBuild();
      }
      _toolbar?.markNeedsBuild();
1158
    }
1159 1160
  }

1161
  /// {@template flutter.widgets.SelectionOverlay.hide}
1162
  /// Hides the entire overlay including the toolbar and the handles.
1163
  /// {@endtemplate}
1164
  void hide() {
1165
    _magnifierController.hide();
1166
    if (_handles != null) {
1167 1168
      _handles![0].remove();
      _handles![1].remove();
1169 1170
      _handles = null;
    }
1171 1172 1173 1174
    if (_toolbar != null) {
      hideToolbar();
    }
  }
1175

1176
  /// {@template flutter.widgets.SelectionOverlay.hideToolbar}
1177 1178 1179
  /// Hides the toolbar part of the overlay.
  ///
  /// To hide the whole overlay, see [hide].
1180
  /// {@endtemplate}
1181
  void hideToolbar() {
1182
    if (_toolbar == null) {
1183
      return;
1184
    }
1185
    _toolbar?.remove();
1186
    _toolbar = null;
1187 1188
  }

1189 1190 1191
  /// {@template flutter.widgets.SelectionOverlay.dispose}
  /// Disposes this object and release resources.
  /// {@endtemplate}
1192 1193
  void dispose() {
    hide();
1194 1195
  }

1196
  Widget _buildStartHandle(BuildContext context) {
1197 1198
    final Widget handle;
    final TextSelectionControls? selectionControls = this.selectionControls;
1199
    if (selectionControls == null) {
1200
      handle = const SizedBox.shrink();
1201
    } else {
1202
      handle = _SelectionHandleOverlay(
1203
        type: _startHandleType,
1204 1205
        handleLayerLink: startHandleLayerLink,
        onSelectionHandleTapped: onSelectionHandleTapped,
1206
        onSelectionHandleDragStart: onStartHandleDragStart,
1207
        onSelectionHandleDragUpdate: onStartHandleDragUpdate,
1208
        onSelectionHandleDragEnd: onStartHandleDragEnd,
1209
        selectionControls: selectionControls,
1210 1211
        visibility: startHandlesVisible,
        preferredLineHeight: _lineHeightAtStart,
1212
        dragStartBehavior: dragStartBehavior,
1213 1214
      );
    }
1215 1216 1217 1218
    return TextFieldTapRegion(
      child: ExcludeSemantics(
        child: handle,
      ),
1219 1220 1221 1222 1223 1224
    );
  }

  Widget _buildEndHandle(BuildContext context) {
    final Widget handle;
    final TextSelectionControls? selectionControls = this.selectionControls;
1225 1226
    if (selectionControls == null || _startHandleType == TextSelectionHandleType.collapsed) {
      // Hide the second handle when collapsed.
1227
      handle = const SizedBox.shrink();
1228
    } else {
1229
      handle = _SelectionHandleOverlay(
1230
        type: _endHandleType,
1231 1232
        handleLayerLink: endHandleLayerLink,
        onSelectionHandleTapped: onSelectionHandleTapped,
1233
        onSelectionHandleDragStart: onEndHandleDragStart,
1234
        onSelectionHandleDragUpdate: onEndHandleDragUpdate,
1235
        onSelectionHandleDragEnd: onEndHandleDragEnd,
1236
        selectionControls: selectionControls,
1237 1238
        visibility: endHandlesVisible,
        preferredLineHeight: _lineHeightAtEnd,
1239
        dragStartBehavior: dragStartBehavior,
1240 1241
      );
    }
1242 1243 1244 1245
    return TextFieldTapRegion(
      child: ExcludeSemantics(
        child: handle,
      ),
1246
    );
1247 1248
  }

1249
  Widget _buildToolbar(BuildContext context) {
1250
    if (selectionControls == null) {
1251
      return const SizedBox.shrink();
1252
    }
1253

1254
    final RenderBox renderBox = this.context.findRenderObject()! as RenderBox;
1255

1256
    final Rect editingRegion = Rect.fromPoints(
1257 1258
      renderBox.localToGlobal(Offset.zero),
      renderBox.localToGlobal(renderBox.size.bottomRight(Offset.zero)),
1259 1260
    );

1261
    final bool isMultiline = selectionEndpoints.last.point.dy - selectionEndpoints.first.point.dy >
1262
        lineHeightAtEnd / 2;
1263 1264 1265 1266 1267

    // 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
1268
      : (selectionEndpoints.first.point.dx + selectionEndpoints.last.point.dx) / 2;
1269 1270 1271 1272

    final Offset midpoint = Offset(
      midX,
      // The y-coordinate won't be made use of most likely.
1273
      selectionEndpoints.first.point.dy - lineHeightAtStart,
1274 1275
    );

1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
    return TextFieldTapRegion(
      child: Directionality(
        textDirection: Directionality.of(this.context),
        child: _SelectionToolbarOverlay(
          preferredLineHeight: lineHeightAtStart,
          toolbarLocation: toolbarLocation,
          layerLink: toolbarLayerLink,
          editingRegion: editingRegion,
          selectionControls: selectionControls,
          midpoint: midpoint,
          selectionEndpoints: selectionEndpoints,
          visibility: toolbarVisible,
          selectionDelegate: selectionDelegate,
          clipboardStatus: clipboardStatus,
        ),
1291 1292 1293
      ),
    );
  }
1294

1295
  /// {@template flutter.widgets.SelectionOverlay.updateMagnifier}
1296 1297 1298 1299 1300 1301 1302
  /// Update the current magnifier with new selection data, so the magnifier
  /// can respond accordingly.
  ///
  /// If the magnifier is not shown, this still updates the magnifier position
  /// because the magnifier may have hidden itself and is looking for a cue to reshow
  /// itself.
  ///
1303
  /// If there is no magnifier in the overlay, this does nothing.
1304
  /// {@endtemplate}
1305
  void updateMagnifier(MagnifierInfo magnifierInfo) {
1306 1307 1308 1309
    if (_magnifierController.overlayEntry == null) {
      return;
    }

1310
    _magnifierInfo.value = magnifierInfo;
1311
  }
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
}

/// 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,
1328
  });
1329 1330 1331 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 1375 1376 1377

  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() {
1378
    if (widget.visibility?.value ?? true) {
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
      _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!,
1402
              widget.clipboardStatus,
1403 1404 1405
              widget.toolbarLocation,
            );
          },
1406
        ),
1407
      ),
1408
    );
1409
  }
1410 1411
}

1412 1413 1414 1415 1416 1417 1418 1419 1420
/// 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,
1421
    this.onSelectionHandleDragEnd,
1422
    required this.selectionControls,
1423
    this.visibility,
1424
    required this.preferredLineHeight,
1425
    this.dragStartBehavior = DragStartBehavior.start,
1426
  });
1427

1428
  final LayerLink handleLayerLink;
1429
  final VoidCallback? onSelectionHandleTapped;
1430 1431
  final ValueChanged<DragStartDetails>? onSelectionHandleDragStart;
  final ValueChanged<DragUpdateDetails>? onSelectionHandleDragUpdate;
1432
  final ValueChanged<DragEndDetails>? onSelectionHandleDragEnd;
1433
  final TextSelectionControls selectionControls;
1434
  final ValueListenable<bool>? visibility;
1435 1436
  final double preferredLineHeight;
  final TextSelectionHandleType type;
1437
  final DragStartBehavior dragStartBehavior;
1438 1439

  @override
1440 1441
  State<_SelectionHandleOverlay> createState() => _SelectionHandleOverlayState();

1442 1443
}

1444
class _SelectionHandleOverlayState extends State<_SelectionHandleOverlay> with SingleTickerProviderStateMixin {
1445
  late AnimationController _controller;
1446 1447 1448 1449 1450 1451
  Animation<double> get _opacity => _controller.view;

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

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

    _handleVisibilityChanged();
1455
    widget.visibility?.addListener(_handleVisibilityChanged);
1456 1457 1458
  }

  void _handleVisibilityChanged() {
1459
    if (widget.visibility?.value ?? true) {
1460 1461 1462 1463 1464 1465 1466
      _controller.forward();
    } else {
      _controller.reverse();
    }
  }

  @override
1467
  void didUpdateWidget(_SelectionHandleOverlay oldWidget) {
1468
    super.didUpdateWidget(oldWidget);
1469
    oldWidget.visibility?.removeListener(_handleVisibilityChanged);
1470
    _handleVisibilityChanged();
1471
    widget.visibility?.addListener(_handleVisibilityChanged);
1472 1473 1474 1475
  }

  @override
  void dispose() {
1476
    widget.visibility?.removeListener(_handleVisibilityChanged);
1477 1478 1479 1480
    _controller.dispose();
    super.dispose();
  }

1481 1482
  @override
  Widget build(BuildContext context) {
1483
    final Offset handleAnchor = widget.selectionControls.getHandleAnchor(
1484 1485
      widget.type,
      widget.preferredLineHeight,
1486
    );
1487
    final Size handleSize = widget.selectionControls.getHandleSize(
1488
      widget.preferredLineHeight,
1489
    );
1490

1491
    final Rect handleRect = Rect.fromLTWH(
1492 1493
      -handleAnchor.dx,
      -handleAnchor.dy,
1494 1495 1496 1497 1498 1499
      handleSize.width,
      handleSize.height,
    );

    // Make sure the GestureDetector is big enough to be easily interactive.
    final Rect interactiveRect = handleRect.expandToInclude(
1500
      Rect.fromCircle(center: handleRect.center, radius: kMinInteractiveDimension/ 2),
1501 1502 1503 1504 1505 1506 1507 1508
    );
    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),
    );

1509
    return CompositedTransformFollower(
1510
      link: widget.handleLayerLink,
1511
      offset: interactiveRect.topLeft,
1512
      showWhenUnlinked: false,
1513 1514
      child: FadeTransition(
        opacity: _opacity,
1515 1516 1517 1518
        child: Container(
          alignment: Alignment.topLeft,
          width: interactiveRect.width,
          height: interactiveRect.height,
1519
          child: RawGestureDetector(
1520
            behavior: HitTestBehavior.translucent,
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
            gestures: <Type, GestureRecognizerFactory>{
              PanGestureRecognizer: GestureRecognizerFactoryWithHandlers<PanGestureRecognizer>(
                () => PanGestureRecognizer(
                  debugOwner: this,
                  // Mouse events select the text and do not drag the cursor.
                  supportedDevices: <PointerDeviceKind>{
                    PointerDeviceKind.touch,
                    PointerDeviceKind.stylus,
                    PointerDeviceKind.unknown,
                  },
                ),
                (PanGestureRecognizer instance) {
                  instance
                    ..dragStartBehavior = widget.dragStartBehavior
                    ..onStart = widget.onSelectionHandleDragStart
                    ..onUpdate = widget.onSelectionHandleDragUpdate
                    ..onEnd = widget.onSelectionHandleDragEnd;
                },
              ),
            },
1541 1542 1543 1544 1545 1546 1547
            child: Padding(
              padding: EdgeInsets.only(
                left: padding.left,
                top: padding.top,
                right: padding.right,
                bottom: padding.bottom,
              ),
1548
              child: widget.selectionControls.buildHandle(
1549
                context,
1550 1551
                widget.type,
                widget.preferredLineHeight,
1552
                widget.onSelectionHandleTapped,
xster's avatar
xster committed
1553
              ),
1554
            ),
1555
          ),
1556
        ),
1557
      ),
1558 1559 1560
    );
  }
}
1561

1562 1563
/// Delegate interface for the [TextSelectionGestureDetectorBuilder].
///
1564
/// The interface is usually implemented by text field implementations wrapping
1565 1566
/// [EditableText], that use a [TextSelectionGestureDetectorBuilder] to build a
/// [TextSelectionGestureDetector] for their [EditableText]. The delegate provides
1567
/// the builder with information about the current state of the text field.
1568 1569 1570 1571 1572
/// Based on these information, the builder adds the correct gesture handlers
/// to the gesture detector.
///
/// See also:
///
1573
///  * [TextField], which implements this delegate for the Material text field.
1574
///  * [CupertinoTextField], which implements this delegate for the Cupertino
1575
///    text field.
1576 1577 1578 1579 1580
abstract class TextSelectionGestureDetectorBuilderDelegate {
  /// [GlobalKey] to the [EditableText] for which the
  /// [TextSelectionGestureDetectorBuilder] will build a [TextSelectionGestureDetector].
  GlobalKey<EditableTextState> get editableTextKey;

1581
  /// Whether the text field should respond to force presses.
1582 1583
  bool get forcePressEnabled;

1584
  /// Whether the user may select text in the text field.
1585 1586 1587 1588 1589 1590 1591
  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
1592 1593
/// methods, e.g. [onTapDown], [onForcePressStart], etc.). Subclasses of
/// [TextSelectionGestureDetectorBuilder] can change the behavior performed in
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
/// 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({
1611
    required this.delegate,
1612 1613 1614 1615 1616
  }) : assert(delegate != null);

  /// The delegate for this [TextSelectionGestureDetectorBuilder].
  ///
  /// The delegate provides the builder with information about what actions can
1617
  /// currently be performed on the text field. Based on this, the builder adds
1618 1619 1620 1621
  /// the correct gesture handlers to the gesture detector.
  @protected
  final TextSelectionGestureDetectorBuilderDelegate delegate;

1622
  /// Returns true if lastSecondaryTapDownPosition was on selection.
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
  bool get _lastSecondaryTapWasOnSelection {
    assert(renderEditable.lastSecondaryTapDownPosition != null);
    if (renderEditable.selection == null) {
      return false;
    }

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

1633 1634
    return renderEditable.selection!.start <= textPosition.offset
        && renderEditable.selection!.end >= textPosition.offset;
1635 1636
  }

1637 1638 1639 1640 1641
  // 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.
  //
1642 1643 1644
  // If fromSelection is given, will expand from that selection instead of the
  // current selection in renderEditable.
  //
1645 1646 1647 1648
  // See also:
  //
  //   * [_extendSelection], which is similar but pivots the selection around
  //     the base.
1649
  void _expandSelection(Offset offset, SelectionChangedCause cause, [TextSelection? fromSelection]) {
1650 1651 1652 1653 1654
    assert(cause != null);
    assert(offset != null);
    assert(renderEditable.selection?.baseOffset != null);

    final TextPosition tappedPosition = renderEditable.getPositionForPoint(offset);
1655
    final TextSelection selection = fromSelection ?? renderEditable.selection!;
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
    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,
    );
  }

1699
  /// Whether to show the selection toolbar.
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
  ///
  /// 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
1710
  EditableTextState get editableText => delegate.editableTextKey.currentState!;
1711 1712 1713 1714

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

1717
  // The viewport offset pixels of the [RenderEditable] at the last drag start.
1718 1719
  double _dragStartViewportOffset = 0.0;

1720 1721 1722 1723 1724 1725 1726 1727 1728
  // Returns true iff either shift key is currently down.
  bool get _isShiftPressed {
    return HardwareKeyboard.instance.logicalKeysPressed
      .any(<LogicalKeyboardKey>{
        LogicalKeyboardKey.shiftLeft,
        LogicalKeyboardKey.shiftRight,
      }.contains);
  }

1729 1730 1731
  // True iff a tap + shift has been detected but the tap has not yet come up.
  bool _isShiftTapping = false;

1732 1733 1734 1735 1736
  // 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;

1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
  /// 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) {
1747 1748 1749
    if (!delegate.selectionEnabled) {
      return;
    }
1750 1751 1752 1753 1754
    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.
1755
    final PointerDeviceKind? kind = details.kind;
1756
    _shouldShowSelectionToolbar = kind == null
1757 1758
      || kind == PointerDeviceKind.touch
      || kind == PointerDeviceKind.stylus;
1759 1760

    // Handle shift + click selection if needed.
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
    final bool isShiftPressedValid = _isShiftPressed && renderEditable.selection?.baseOffset != null;
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.iOS:
        // On mobile platforms the selection is set on tap up.
        if (_isShiftTapping) {
          _isShiftTapping = false;
        }
        break;
      case TargetPlatform.macOS:
        // On macOS, a shift-tapped unfocused field expands from 0, not from the
        // previous selection.
        if (isShiftPressedValid) {
          _isShiftTapping = true;
1776 1777 1778 1779 1780 1781 1782 1783
          final TextSelection? fromSelection = renderEditable.hasFocus
              ? null
              : const TextSelection.collapsed(offset: 0);
          _expandSelection(
            details.globalPosition,
            SelectionChangedCause.tap,
            fromSelection,
          );
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
          return;
        }
        // On macOS, a tap/click places the selection in a precise position.
        // This differs from iOS/iPadOS, where if the gesture is done by a touch
        // then the selection moves to the closest word edge, instead of a
        // precise position.
        renderEditable.selectPosition(cause: SelectionChangedCause.tap);
        break;
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        if (isShiftPressedValid) {
          _isShiftTapping = true;
1796
          _extendSelection(details.globalPosition, SelectionChangedCause.tap);
1797 1798 1799 1800
          return;
        }
        renderEditable.selectPosition(cause: SelectionChangedCause.tap);
        break;
1801
    }
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
  }

  /// 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
1830
  /// toolbar if it is necessary.
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
  ///
  /// 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,
    );
1845
    if (shouldShowSelectionToolbar) {
1846
      editableText.showToolbar();
1847
    }
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
  }

  /// 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) {
    if (delegate.selectionEnabled) {
1861 1862
      // Handle shift + click selection if needed.
      final bool isShiftPressedValid = _isShiftPressed && renderEditable.selection?.baseOffset != null;
1863
      switch (defaultTargetPlatform) {
1864
        case TargetPlatform.linux:
1865
        case TargetPlatform.macOS:
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
        case TargetPlatform.windows:
          // On desktop platforms the selection is set on tap down.
          if (_isShiftTapping) {
            _isShiftTapping = false;
          }
          break;
        case TargetPlatform.android:
        case TargetPlatform.fuchsia:
          if (isShiftPressedValid) {
            _isShiftTapping = true;
            _extendSelection(details.globalPosition, SelectionChangedCause.tap);
            return;
          }
          renderEditable.selectPosition(cause: SelectionChangedCause.tap);
          break;
        case TargetPlatform.iOS:
          if (isShiftPressedValid) {
            // On iOS, a shift-tapped unfocused field expands from 0, not from
            // the previous selection.
            _isShiftTapping = true;
            final TextSelection? fromSelection = renderEditable.hasFocus
                ? null
                : const TextSelection.collapsed(offset: 0);
            _expandSelection(
              details.globalPosition,
              SelectionChangedCause.tap,
              fromSelection,
            );
            return;
          }
1896 1897
          switch (details.kind) {
            case PointerDeviceKind.mouse:
1898
            case PointerDeviceKind.trackpad:
1899 1900 1901 1902 1903 1904 1905
            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:
1906
              // On iOS/iPadOS a touch tap places the cursor at the edge of the word.
1907
              renderEditable.selectWordEdge(cause: SelectionChangedCause.tap);
1908 1909 1910 1911
              break;
          }
          break;
      }
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
    }
  }

  /// 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,
      );
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953

      switch (defaultTargetPlatform) {
        case TargetPlatform.android:
        case TargetPlatform.iOS:
          editableText.showMagnifier(details.globalPosition);
          break;
        case TargetPlatform.fuchsia:
        case TargetPlatform.linux:
        case TargetPlatform.macOS:
        case TargetPlatform.windows:
          break;
      }
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
    }
  }

  /// 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,
      );
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984

      switch (defaultTargetPlatform) {
        case TargetPlatform.android:
        case TargetPlatform.iOS:
          editableText.showMagnifier(details.globalPosition);
          break;
        case TargetPlatform.fuchsia:
        case TargetPlatform.linux:
        case TargetPlatform.macOS:
        case TargetPlatform.windows:
          break;
      }
1985 1986 1987 1988 1989
    }
  }

  /// Handler for [TextSelectionGestureDetector.onSingleLongTapEnd].
  ///
1990
  /// By default, it shows toolbar if necessary.
1991 1992 1993 1994 1995 1996 1997
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onSingleLongTapEnd], which triggers this
  ///    callback.
  @protected
  void onSingleLongTapEnd(LongPressEndDetails details) {
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
      case TargetPlatform.iOS:
        editableText.hideMagnifier(shouldShowToolbar: false);
        break;
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
        break;
    }
2009
    if (shouldShowSelectionToolbar) {
2010
      editableText.showToolbar();
2011
    }
2012 2013
  }

2014 2015 2016 2017 2018
  /// Handler for [TextSelectionGestureDetector.onSecondaryTap].
  ///
  /// By default, selects the word if possible and shows the toolbar.
  @protected
  void onSecondaryTap() {
2019 2020 2021 2022 2023 2024
    if (!delegate.selectionEnabled) {
      return;
    }
    switch (defaultTargetPlatform) {
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
2025
        if (!_lastSecondaryTapWasOnSelection || !renderEditable.hasFocus) {
2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
          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;
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
    }
  }

  /// 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;
  }

2058 2059
  /// Handler for [TextSelectionGestureDetector.onDoubleTapDown].
  ///
2060
  /// By default, it selects a word through [RenderEditable.selectWord] if
2061
  /// selectionEnabled and shows toolbar if necessary.
2062 2063 2064 2065 2066 2067 2068 2069
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onDoubleTapDown], which triggers this
  ///    callback.
  @protected
  void onDoubleTapDown(TapDownDetails details) {
    if (delegate.selectionEnabled) {
2070
      renderEditable.selectWord(cause: SelectionChangedCause.tap);
2071
      if (shouldShowSelectionToolbar) {
2072
        editableText.showToolbar();
2073
      }
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
    }
  }

  /// 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) {
2087
    if (!delegate.selectionEnabled) {
2088
      return;
2089
    }
2090 2091 2092 2093 2094
    final PointerDeviceKind? kind = details.kind;
    _shouldShowSelectionToolbar = kind == null
      || kind == PointerDeviceKind.touch
      || kind == PointerDeviceKind.stylus;

2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
    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,
      );
    }
2116 2117

    _dragStartViewportOffset = renderEditable.offset.pixels;
2118 2119 2120 2121
  }

  /// Handler for [TextSelectionGestureDetector.onDragSelectionUpdate].
  ///
2122 2123
  /// By default, it updates the selection location specified in the provided
  /// details objects.
2124 2125 2126 2127 2128 2129 2130
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onDragSelectionUpdate], which triggers
  ///    this callback./lib/src/material/text_field.dart
  @protected
  void onDragSelectionUpdate(DragStartDetails startDetails, DragUpdateDetails updateDetails) {
2131
    if (!delegate.selectionEnabled) {
2132
      return;
2133
    }
2134

2135 2136 2137 2138 2139
    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);
2140

2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
      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);
    }
2188 2189 2190 2191
  }

  /// Handler for [TextSelectionGestureDetector.onDragSelectionEnd].
  ///
2192 2193
  /// By default, it simply cleans up the state used for handling certain
  /// built-in behaviors.
2194 2195 2196 2197 2198 2199
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onDragSelectionEnd], which triggers this
  ///    callback.
  @protected
2200 2201 2202 2203 2204 2205
  void onDragSelectionEnd(DragEndDetails details) {
    if (_isShiftTapping) {
      _isShiftTapping = false;
      _shiftTapDragSelection = null;
    }
  }
2206 2207 2208 2209 2210 2211

  /// Returns a [TextSelectionGestureDetector] configured with the handlers
  /// provided by this builder.
  ///
  /// The [child] or its subtree should contain [EditableText].
  Widget buildGestureDetector({
2212 2213 2214
    Key? key,
    HitTestBehavior? behavior,
    required Widget child,
2215 2216 2217 2218 2219 2220
  }) {
    return TextSelectionGestureDetector(
      key: key,
      onTapDown: onTapDown,
      onForcePressStart: delegate.forcePressEnabled ? onForcePressStart : null,
      onForcePressEnd: delegate.forcePressEnabled ? onForcePressEnd : null,
2221 2222
      onSecondaryTap: onSecondaryTap,
      onSecondaryTapDown: onSecondaryTapDown,
2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
      onSingleTapUp: onSingleTapUp,
      onSingleTapCancel: onSingleTapCancel,
      onSingleLongTapStart: onSingleLongTapStart,
      onSingleLongTapMoveUpdate: onSingleLongTapMoveUpdate,
      onSingleLongTapEnd: onSingleLongTapEnd,
      onDoubleTapDown: onDoubleTapDown,
      onDragSelectionStart: onDragSelectionStart,
      onDragSelectionUpdate: onDragSelectionUpdate,
      onDragSelectionEnd: onDragSelectionEnd,
      behavior: behavior,
      child: child,
    );
  }
}

2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
/// 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({
2256
    super.key,
2257
    this.onTapDown,
2258 2259
    this.onForcePressStart,
    this.onForcePressEnd,
2260 2261
    this.onSecondaryTap,
    this.onSecondaryTapDown,
2262 2263
    this.onSingleTapUp,
    this.onSingleTapCancel,
2264 2265 2266
    this.onSingleLongTapStart,
    this.onSingleLongTapMoveUpdate,
    this.onSingleLongTapEnd,
2267
    this.onDoubleTapDown,
2268 2269 2270
    this.onDragSelectionStart,
    this.onDragSelectionUpdate,
    this.onDragSelectionEnd,
2271
    this.behavior,
2272
    required this.child,
2273
  }) : assert(child != null);
2274 2275 2276 2277

  /// 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).
2278
  final GestureTapDownCallback? onTapDown;
2279

2280
  /// Called when a pointer has tapped down and the force of the pointer has
2281
  /// just become greater than [ForcePressGestureRecognizer.startPressure].
2282
  final GestureForcePressStartCallback? onForcePressStart;
2283 2284 2285

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

2288 2289 2290 2291 2292 2293
  /// 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;

2294
  /// Called for each distinct tap except for every second tap of a double tap.
2295
  /// For example, if the detector was configured with [onTapDown] and
2296 2297
  /// [onDoubleTapDown], three quick taps would be recognized as a single tap
  /// down, followed by a double tap down, followed by a single tap down.
2298
  final GestureTapUpCallback? onSingleTapUp;
2299 2300 2301 2302

  /// 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.
2303
  final GestureTapCancelCallback? onSingleTapCancel;
2304 2305 2306 2307

  /// 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.
2308
  final GestureLongPressStartCallback? onSingleLongTapStart;
2309 2310

  /// Called after [onSingleLongTapStart] when the pointer is dragged.
2311
  final GestureLongPressMoveUpdateCallback? onSingleLongTapMoveUpdate;
2312 2313

  /// Called after [onSingleLongTapStart] when the pointer is lifted.
2314
  final GestureLongPressEndCallback? onSingleLongTapEnd;
2315 2316 2317

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

2320
  /// Called when a mouse starts dragging to select text.
2321
  final GestureDragStartCallback? onDragSelectionStart;
2322 2323 2324 2325 2326 2327

  /// 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].
2328
  final DragSelectionUpdateCallback? onDragSelectionUpdate;
2329 2330

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

2333 2334 2335
  /// How this gesture detector should behave during hit testing.
  ///
  /// This defaults to [HitTestBehavior.deferToChild].
2336
  final HitTestBehavior? behavior;
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346

  /// 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.
2347 2348
  Timer? _doubleTapTimer;
  Offset? _lastTapOffset;
2349 2350 2351 2352 2353 2354 2355
  // 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();
2356
    _dragUpdateThrottleTimer?.cancel();
2357 2358 2359 2360 2361 2362
    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) {
2363
    widget.onTapDown?.call(details);
2364 2365 2366 2367 2368 2369 2370
    // 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.
2371
      widget.onDoubleTapDown?.call(details);
2372

2373
      _doubleTapTimer!.cancel();
2374 2375 2376 2377 2378 2379 2380
      _doubleTapTimeout();
      _isDoubleTap = true;
    }
  }

  void _handleTapUp(TapUpDetails details) {
    if (!_isDoubleTap) {
2381
      widget.onSingleTapUp?.call(details);
2382 2383 2384 2385 2386 2387 2388
      _lastTapOffset = details.globalPosition;
      _doubleTapTimer = Timer(kDoubleTapTimeout, _doubleTapTimeout);
    }
    _isDoubleTap = false;
  }

  void _handleTapCancel() {
2389
    widget.onSingleTapCancel?.call();
2390 2391
  }

2392 2393 2394
  DragStartDetails? _lastDragStartDetails;
  DragUpdateDetails? _lastDragUpdateDetails;
  Timer? _dragUpdateThrottleTimer;
2395 2396 2397 2398

  void _handleDragStart(DragStartDetails details) {
    assert(_lastDragStartDetails == null);
    _lastDragStartDetails = details;
2399
    widget.onDragSelectionStart?.call(details);
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
  }

  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);
2417
    widget.onDragSelectionUpdate?.call(_lastDragStartDetails!, _lastDragUpdateDetails!);
2418 2419 2420 2421 2422 2423 2424 2425 2426
    _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.
2427
      _dragUpdateThrottleTimer!.cancel();
2428 2429
      _handleDragUpdateThrottled();
    }
2430
    widget.onDragSelectionEnd?.call(details);
2431 2432 2433 2434 2435
    _dragUpdateThrottleTimer = null;
    _lastDragStartDetails = null;
    _lastDragUpdateDetails = null;
  }

2436 2437 2438
  void _forcePressStarted(ForcePressDetails details) {
    _doubleTapTimer?.cancel();
    _doubleTapTimer = null;
2439
    widget.onForcePressStart?.call(details);
2440 2441 2442
  }

  void _forcePressEnded(ForcePressDetails details) {
2443
    widget.onForcePressEnd?.call(details);
2444 2445
  }

2446 2447
  void _handleLongPressStart(LongPressStartDetails details) {
    if (!_isDoubleTap && widget.onSingleLongTapStart != null) {
2448
      widget.onSingleLongTapStart!(details);
2449 2450 2451 2452 2453
    }
  }

  void _handleLongPressMoveUpdate(LongPressMoveUpdateDetails details) {
    if (!_isDoubleTap && widget.onSingleLongTapMoveUpdate != null) {
2454
      widget.onSingleLongTapMoveUpdate!(details);
2455 2456 2457
    }
  }

2458
  void _handleLongPressEnd(LongPressEndDetails details) {
2459
    if (!_isDoubleTap && widget.onSingleLongTapEnd != null) {
2460
      widget.onSingleLongTapEnd!(details);
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475
    }
    _isDoubleTap = false;
  }

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

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

2476
    final Offset difference = secondTapOffset - _lastTapOffset!;
2477 2478 2479 2480 2481
    return difference.distance <= kDoubleTapSlop;
  }

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

2484 2485 2486
    gestures[TapGestureRecognizer] = GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
      () => TapGestureRecognizer(debugOwner: this),
      (TapGestureRecognizer instance) {
2487
        instance
2488 2489
          ..onSecondaryTap = widget.onSecondaryTap
          ..onSecondaryTapDown = widget.onSecondaryTapDown
2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
          ..onTapDown = _handleTapDown
          ..onTapUp = _handleTapUp
          ..onTapCancel = _handleTapCancel;
      },
    );

    if (widget.onSingleLongTapStart != null ||
        widget.onSingleLongTapMoveUpdate != null ||
        widget.onSingleLongTapEnd != null) {
      gestures[LongPressGestureRecognizer] = GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
2500 2501
        () => LongPressGestureRecognizer(debugOwner: this, kind: PointerDeviceKind.touch),
        (LongPressGestureRecognizer instance) {
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512
          instance
            ..onLongPressStart = _handleLongPressStart
            ..onLongPressMoveUpdate = _handleLongPressMoveUpdate
            ..onLongPressEnd = _handleLongPressEnd;
        },
      );
    }

    if (widget.onDragSelectionStart != null ||
        widget.onDragSelectionUpdate != null ||
        widget.onDragSelectionEnd != null) {
2513 2514 2515
      gestures[PanGestureRecognizer] = GestureRecognizerFactoryWithHandlers<PanGestureRecognizer>(
        () => PanGestureRecognizer(debugOwner: this, supportedDevices: <PointerDeviceKind>{ PointerDeviceKind.mouse }),
        (PanGestureRecognizer instance) {
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
          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>(
2529 2530
        () => ForcePressGestureRecognizer(debugOwner: this),
        (ForcePressGestureRecognizer instance) {
2531 2532 2533 2534 2535 2536 2537 2538 2539
          instance
            ..onStart = widget.onForcePressStart != null ? _forcePressStarted : null
            ..onEnd = widget.onForcePressEnd != null ? _forcePressEnded : null;
        },
      );
    }

    return RawGestureDetector(
      gestures: gestures,
2540 2541 2542 2543 2544 2545
      excludeFromSemantics: true,
      behavior: widget.behavior,
      child: widget.child,
    );
  }
}
2546

2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558
/// 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);

2559 2560 2561 2562 2563 2564
  bool _disposed = false;
  // TODO(chunhtai): remove this getter once migration is done.
  // https://github.com/flutter/flutter/issues/99360
  /// True if this instance has been disposed.
  bool get disposed => _disposed;

2565
  /// Check the [Clipboard] and update [value] if needed.
2566
  Future<void> update() async {
2567 2568 2569 2570
    if (_disposed) {
      return;
    }

2571
    final bool hasStrings;
2572
    try {
2573
      hasStrings = await Clipboard.hasStrings();
2574 2575 2576 2577 2578 2579 2580
    } catch (exception, stack) {
      FlutterError.reportError(FlutterErrorDetails(
        exception: exception,
        stack: stack,
        library: 'widget library',
        context: ErrorDescription('while checking if the clipboard has strings'),
      ));
2581 2582
      // In the case of an error from the Clipboard API, set the value to
      // unknown so that it will try to update again later.
2583
      if (_disposed || value == ClipboardStatus.unknown) {
2584 2585
        return;
      }
2586 2587 2588 2589
      value = ClipboardStatus.unknown;
      return;
    }

2590
    final ClipboardStatus nextStatus = hasStrings
2591 2592
        ? ClipboardStatus.pasteable
        : ClipboardStatus.notPasteable;
2593

2594
    if (_disposed || nextStatus == value) {
2595 2596
      return;
    }
2597
    value = nextStatus;
2598 2599 2600 2601 2602
  }

  @override
  void addListener(VoidCallback listener) {
    if (!hasListeners) {
2603
      WidgetsBinding.instance.addObserver(this);
2604 2605 2606 2607 2608 2609 2610 2611 2612 2613
    }
    if (value == ClipboardStatus.unknown) {
      update();
    }
    super.addListener(listener);
  }

  @override
  void removeListener(VoidCallback listener) {
    super.removeListener(listener);
2614
    if (!_disposed && !hasListeners) {
2615
      WidgetsBinding.instance.removeObserver(this);
2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633
    }
  }

  @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() {
2634
    WidgetsBinding.instance.removeObserver(this);
2635
    _disposed = true;
2636
    super.dispose();
2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
  }
}

/// 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,

2650
  /// The content on the clipboard is not pastable, such as when it is empty.
2651 2652
  notPasteable,
}