text_selection.dart 94.3 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 'scrollable.dart';
26
import 'tap_region.dart';
27
import 'ticker_provider.dart';
28
import 'transitions.dart';
29

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

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
/// 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);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
/// 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();


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

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

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

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

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

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

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

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
  /// {@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);
  }

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

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

495 496 497 498 499 500 501 502 503
  /// {@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();
504 505 506 507 508
    renderObject.selectionStartInViewport.removeListener(_updateTextSelectionOverlayVisibilities);
    renderObject.selectionEndInViewport.removeListener(_updateTextSelectionOverlayVisibilities);
    _effectiveToolbarVisibility.dispose();
    _effectiveStartHandleVisibility.dispose();
    _effectiveEndHandleVisibility.dispose();
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
  }

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

547
  MagnifierInfo _buildMagnifier({
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    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,
    );

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

579 580 581
  late Offset _dragEndPosition;

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

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

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

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

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

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

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

621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
    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;
646
    }
647 648

    _handleSelectionHandleChanged(newSelection, isEnd: true);
649

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

  late Offset _dragStartPosition;

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

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

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

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

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

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
    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;
721
    }
722

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

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

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

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

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

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

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

811

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

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

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

830
  /// {@template flutter.widgets.SelectionOverlay.showMagnifier}
831 832 833 834 835
  /// 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.
  ///
836
  /// This is NOT the source of truth for if the magnifier is up or not,
837 838
  /// since magnifiers may hide themselves. If this info is needed, check
  /// [MagnifierController.shown].
839
  /// {@endtemplate}
840
  void showMagnifier(MagnifierInfo initalMagnifierInfo) {
841 842 843 844
    if (_toolbar != null) {
      hideToolbar();
    }

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

    // 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,
854
      _magnifierInfo,
855 856
    );

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

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

869
  /// {@template flutter.widgets.SelectionOverlay.hideMagnifier}
870 871 872 873
  /// Hide the current magnifier, optionally immediately showing
  /// the toolbar.
  ///
  /// This does nothing if there is no magnifier.
874
  /// {@endtemplate}
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
  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();
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
    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,
        ),
1292 1293 1294
      ),
    );
  }
1295

1296
  /// {@template flutter.widgets.SelectionOverlay.updateMagnifier}
1297 1298 1299 1300 1301 1302 1303
  /// 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.
  ///
1304
  /// If there is no magnifier in the overlay, this does nothing.
1305
  /// {@endtemplate}
1306
  void updateMagnifier(MagnifierInfo magnifierInfo) {
1307 1308 1309 1310
    if (_magnifierController.overlayEntry == null) {
      return;
    }

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

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

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

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

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

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

1443 1444
}

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

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

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

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

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

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

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

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

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

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

1510
    return CompositedTransformFollower(
1511
      link: widget.handleLayerLink,
1512
      offset: interactiveRect.topLeft,
1513
      showWhenUnlinked: false,
1514 1515
      child: FadeTransition(
        opacity: _opacity,
1516 1517 1518 1519
        child: Container(
          alignment: Alignment.topLeft,
          width: interactiveRect.width,
          height: interactiveRect.height,
1520
          child: RawGestureDetector(
1521
            behavior: HitTestBehavior.translucent,
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
            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;
                },
              ),
            },
1542 1543 1544 1545 1546 1547 1548
            child: Padding(
              padding: EdgeInsets.only(
                left: padding.left,
                top: padding.top,
                right: padding.right,
                bottom: padding.bottom,
              ),
1549
              child: widget.selectionControls.buildHandle(
1550
                context,
1551 1552
                widget.type,
                widget.preferredLineHeight,
1553
                widget.onSelectionHandleTapped,
xster's avatar
xster committed
1554
              ),
1555
            ),
1556
          ),
1557
        ),
1558
      ),
1559 1560 1561
    );
  }
}
1562

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

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

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

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

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

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

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

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

    final TextPosition tappedPosition = renderEditable.getPositionForPoint(offset);
1656
    final TextSelection selection = fromSelection ?? renderEditable.selection!;
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 1699
    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,
    );
  }

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

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

1718 1719 1720 1721 1722
  /// The viewport offset pixels of any [Scrollable] containing the
  /// [RenderEditable] at the last drag start.
  double _dragStartScrollOffset = 0.0;

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

1725 1726 1727 1728 1729 1730 1731 1732 1733
  // Returns true iff either shift key is currently down.
  bool get _isShiftPressed {
    return HardwareKeyboard.instance.logicalKeysPressed
      .any(<LogicalKeyboardKey>{
        LogicalKeyboardKey.shiftLeft,
        LogicalKeyboardKey.shiftRight,
      }.contains);
  }

1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
  double get _scrollPosition {
    final ScrollableState? scrollableState =
        delegate.editableTextKey.currentContext == null
            ? null
            : Scrollable.of(delegate.editableTextKey.currentContext!);
    return scrollableState == null
        ? 0.0
        : scrollableState.position.pixels;
  }

1744 1745 1746
  // True iff a tap + shift has been detected but the tap has not yet come up.
  bool _isShiftTapping = false;

1747 1748 1749 1750 1751
  // 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;

1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
  /// 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) {
1762 1763 1764
    if (!delegate.selectionEnabled) {
      return;
    }
1765 1766 1767 1768 1769
    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.
1770
    final PointerDeviceKind? kind = details.kind;
1771
    _shouldShowSelectionToolbar = kind == null
1772 1773
      || kind == PointerDeviceKind.touch
      || kind == PointerDeviceKind.stylus;
1774 1775

    // Handle shift + click selection if needed.
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
    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;
1791 1792 1793 1794 1795 1796 1797 1798
          final TextSelection? fromSelection = renderEditable.hasFocus
              ? null
              : const TextSelection.collapsed(offset: 0);
          _expandSelection(
            details.globalPosition,
            SelectionChangedCause.tap,
            fromSelection,
          );
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
          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;
1811
          _extendSelection(details.globalPosition, SelectionChangedCause.tap);
1812 1813 1814 1815
          return;
        }
        renderEditable.selectPosition(cause: SelectionChangedCause.tap);
        break;
1816
    }
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
  }

  /// 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
1845
  /// toolbar if it is necessary.
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
  ///
  /// 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,
    );
1860
    if (shouldShowSelectionToolbar) {
1861
      editableText.showToolbar();
1862
    }
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
  }

  /// 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) {
1876 1877
      // Handle shift + click selection if needed.
      final bool isShiftPressedValid = _isShiftPressed && renderEditable.selection?.baseOffset != null;
1878
      switch (defaultTargetPlatform) {
1879
        case TargetPlatform.linux:
1880
        case TargetPlatform.macOS:
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
        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;
          }
1911 1912
          switch (details.kind) {
            case PointerDeviceKind.mouse:
1913
            case PointerDeviceKind.trackpad:
1914 1915 1916 1917 1918 1919 1920
            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:
1921
              // On iOS/iPadOS a touch tap places the cursor at the edge of the word.
1922
              renderEditable.selectWordEdge(cause: SelectionChangedCause.tap);
1923 1924 1925 1926
              break;
          }
          break;
      }
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
    }
  }

  /// 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,
      );
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968

      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;
      }
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
    }
  }

  /// 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,
      );
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999

      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;
      }
2000 2001 2002 2003 2004
    }
  }

  /// Handler for [TextSelectionGestureDetector.onSingleLongTapEnd].
  ///
2005
  /// By default, it shows toolbar if necessary.
2006 2007 2008 2009 2010 2011 2012
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onSingleLongTapEnd], which triggers this
  ///    callback.
  @protected
  void onSingleLongTapEnd(LongPressEndDetails details) {
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
    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;
    }
2024
    if (shouldShowSelectionToolbar) {
2025
      editableText.showToolbar();
2026
    }
2027 2028
  }

2029 2030 2031 2032 2033
  /// Handler for [TextSelectionGestureDetector.onSecondaryTap].
  ///
  /// By default, selects the word if possible and shows the toolbar.
  @protected
  void onSecondaryTap() {
2034 2035 2036 2037 2038 2039
    if (!delegate.selectionEnabled) {
      return;
    }
    switch (defaultTargetPlatform) {
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
2040
        if (!_lastSecondaryTapWasOnSelection || !renderEditable.hasFocus) {
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
          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;
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
    }
  }

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

2073 2074
  /// Handler for [TextSelectionGestureDetector.onDoubleTapDown].
  ///
2075
  /// By default, it selects a word through [RenderEditable.selectWord] if
2076
  /// selectionEnabled and shows toolbar if necessary.
2077 2078 2079 2080 2081 2082 2083 2084
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onDoubleTapDown], which triggers this
  ///    callback.
  @protected
  void onDoubleTapDown(TapDownDetails details) {
    if (delegate.selectionEnabled) {
2085
      renderEditable.selectWord(cause: SelectionChangedCause.tap);
2086
      if (shouldShowSelectionToolbar) {
2087
        editableText.showToolbar();
2088
      }
2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
    }
  }

  /// 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) {
2102
    if (!delegate.selectionEnabled) {
2103
      return;
2104
    }
2105 2106 2107 2108 2109
    final PointerDeviceKind? kind = details.kind;
    _shouldShowSelectionToolbar = kind == null
      || kind == PointerDeviceKind.touch
      || kind == PointerDeviceKind.stylus;

2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
    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,
      );
    }
2131

2132
    _dragStartScrollOffset = _scrollPosition;
2133
    _dragStartViewportOffset = renderEditable.offset.pixels;
2134 2135 2136 2137
  }

  /// Handler for [TextSelectionGestureDetector.onDragSelectionUpdate].
  ///
2138 2139
  /// By default, it updates the selection location specified in the provided
  /// details objects.
2140 2141 2142 2143 2144 2145 2146
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onDragSelectionUpdate], which triggers
  ///    this callback./lib/src/material/text_field.dart
  @protected
  void onDragSelectionUpdate(DragStartDetails startDetails, DragUpdateDetails updateDetails) {
2147
    if (!delegate.selectionEnabled) {
2148
      return;
2149
    }
2150

2151 2152
    if (!_isShiftTapping) {
      // Adjust the drag start offset for possible viewport offset changes.
2153
      final Offset editableOffset = renderEditable.maxLines == 1
2154 2155
          ? Offset(renderEditable.offset.pixels - _dragStartViewportOffset, 0.0)
          : Offset(0.0, renderEditable.offset.pixels - _dragStartViewportOffset);
2156 2157 2158 2159
      final Offset scrollableOffset = Offset(
        0.0,
        _scrollPosition - _dragStartScrollOffset,
      );
2160
      return renderEditable.selectPositionAt(
2161
        from: startDetails.globalPosition - editableOffset - scrollableOffset,
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 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
        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);
    }
2207 2208 2209 2210
  }

  /// Handler for [TextSelectionGestureDetector.onDragSelectionEnd].
  ///
2211 2212
  /// By default, it simply cleans up the state used for handling certain
  /// built-in behaviors.
2213 2214 2215 2216 2217 2218
  ///
  /// See also:
  ///
  ///  * [TextSelectionGestureDetector.onDragSelectionEnd], which triggers this
  ///    callback.
  @protected
2219 2220 2221 2222 2223 2224
  void onDragSelectionEnd(DragEndDetails details) {
    if (_isShiftTapping) {
      _isShiftTapping = false;
      _shiftTapDragSelection = null;
    }
  }
2225 2226 2227 2228 2229 2230

  /// Returns a [TextSelectionGestureDetector] configured with the handlers
  /// provided by this builder.
  ///
  /// The [child] or its subtree should contain [EditableText].
  Widget buildGestureDetector({
2231 2232 2233
    Key? key,
    HitTestBehavior? behavior,
    required Widget child,
2234 2235 2236 2237 2238 2239
  }) {
    return TextSelectionGestureDetector(
      key: key,
      onTapDown: onTapDown,
      onForcePressStart: delegate.forcePressEnabled ? onForcePressStart : null,
      onForcePressEnd: delegate.forcePressEnabled ? onForcePressEnd : null,
2240 2241
      onSecondaryTap: onSecondaryTap,
      onSecondaryTapDown: onSecondaryTapDown,
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
      onSingleTapUp: onSingleTapUp,
      onSingleTapCancel: onSingleTapCancel,
      onSingleLongTapStart: onSingleLongTapStart,
      onSingleLongTapMoveUpdate: onSingleLongTapMoveUpdate,
      onSingleLongTapEnd: onSingleLongTapEnd,
      onDoubleTapDown: onDoubleTapDown,
      onDragSelectionStart: onDragSelectionStart,
      onDragSelectionUpdate: onDragSelectionUpdate,
      onDragSelectionEnd: onDragSelectionEnd,
      behavior: behavior,
      child: child,
    );
  }
}

2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
/// 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({
2275
    super.key,
2276
    this.onTapDown,
2277 2278
    this.onForcePressStart,
    this.onForcePressEnd,
2279 2280
    this.onSecondaryTap,
    this.onSecondaryTapDown,
2281 2282
    this.onSingleTapUp,
    this.onSingleTapCancel,
2283 2284 2285
    this.onSingleLongTapStart,
    this.onSingleLongTapMoveUpdate,
    this.onSingleLongTapEnd,
2286
    this.onDoubleTapDown,
2287 2288 2289
    this.onDragSelectionStart,
    this.onDragSelectionUpdate,
    this.onDragSelectionEnd,
2290
    this.behavior,
2291
    required this.child,
2292
  }) : assert(child != null);
2293 2294 2295 2296

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

2299
  /// Called when a pointer has tapped down and the force of the pointer has
2300
  /// just become greater than [ForcePressGestureRecognizer.startPressure].
2301
  final GestureForcePressStartCallback? onForcePressStart;
2302 2303 2304

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

2307 2308 2309 2310 2311 2312
  /// 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;

2313
  /// Called for each distinct tap except for every second tap of a double tap.
2314
  /// For example, if the detector was configured with [onTapDown] and
2315 2316
  /// [onDoubleTapDown], three quick taps would be recognized as a single tap
  /// down, followed by a double tap down, followed by a single tap down.
2317
  final GestureTapUpCallback? onSingleTapUp;
2318 2319 2320 2321

  /// 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.
2322
  final GestureTapCancelCallback? onSingleTapCancel;
2323 2324 2325 2326

  /// 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.
2327
  final GestureLongPressStartCallback? onSingleLongTapStart;
2328 2329

  /// Called after [onSingleLongTapStart] when the pointer is dragged.
2330
  final GestureLongPressMoveUpdateCallback? onSingleLongTapMoveUpdate;
2331 2332

  /// Called after [onSingleLongTapStart] when the pointer is lifted.
2333
  final GestureLongPressEndCallback? onSingleLongTapEnd;
2334 2335 2336

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

2339
  /// Called when a mouse starts dragging to select text.
2340
  final GestureDragStartCallback? onDragSelectionStart;
2341 2342 2343 2344 2345 2346

  /// 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].
2347
  final DragSelectionUpdateCallback? onDragSelectionUpdate;
2348 2349

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

2352 2353 2354
  /// How this gesture detector should behave during hit testing.
  ///
  /// This defaults to [HitTestBehavior.deferToChild].
2355
  final HitTestBehavior? behavior;
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365

  /// 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.
2366 2367
  Timer? _doubleTapTimer;
  Offset? _lastTapOffset;
2368 2369 2370 2371 2372 2373 2374
  // 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();
2375
    _dragUpdateThrottleTimer?.cancel();
2376 2377 2378 2379 2380 2381
    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) {
2382
    widget.onTapDown?.call(details);
2383 2384 2385 2386 2387 2388 2389
    // 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.
2390
      widget.onDoubleTapDown?.call(details);
2391

2392
      _doubleTapTimer!.cancel();
2393 2394 2395 2396 2397 2398 2399
      _doubleTapTimeout();
      _isDoubleTap = true;
    }
  }

  void _handleTapUp(TapUpDetails details) {
    if (!_isDoubleTap) {
2400
      widget.onSingleTapUp?.call(details);
2401 2402 2403 2404 2405 2406 2407
      _lastTapOffset = details.globalPosition;
      _doubleTapTimer = Timer(kDoubleTapTimeout, _doubleTapTimeout);
    }
    _isDoubleTap = false;
  }

  void _handleTapCancel() {
2408
    widget.onSingleTapCancel?.call();
2409 2410
  }

2411 2412 2413
  DragStartDetails? _lastDragStartDetails;
  DragUpdateDetails? _lastDragUpdateDetails;
  Timer? _dragUpdateThrottleTimer;
2414 2415 2416 2417

  void _handleDragStart(DragStartDetails details) {
    assert(_lastDragStartDetails == null);
    _lastDragStartDetails = details;
2418
    widget.onDragSelectionStart?.call(details);
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
  }

  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);
2436
    widget.onDragSelectionUpdate?.call(_lastDragStartDetails!, _lastDragUpdateDetails!);
2437 2438 2439 2440 2441 2442 2443 2444 2445
    _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.
2446
      _dragUpdateThrottleTimer!.cancel();
2447 2448
      _handleDragUpdateThrottled();
    }
2449
    widget.onDragSelectionEnd?.call(details);
2450 2451 2452 2453 2454
    _dragUpdateThrottleTimer = null;
    _lastDragStartDetails = null;
    _lastDragUpdateDetails = null;
  }

2455 2456 2457
  void _forcePressStarted(ForcePressDetails details) {
    _doubleTapTimer?.cancel();
    _doubleTapTimer = null;
2458
    widget.onForcePressStart?.call(details);
2459 2460 2461
  }

  void _forcePressEnded(ForcePressDetails details) {
2462
    widget.onForcePressEnd?.call(details);
2463 2464
  }

2465 2466
  void _handleLongPressStart(LongPressStartDetails details) {
    if (!_isDoubleTap && widget.onSingleLongTapStart != null) {
2467
      widget.onSingleLongTapStart!(details);
2468 2469 2470 2471 2472
    }
  }

  void _handleLongPressMoveUpdate(LongPressMoveUpdateDetails details) {
    if (!_isDoubleTap && widget.onSingleLongTapMoveUpdate != null) {
2473
      widget.onSingleLongTapMoveUpdate!(details);
2474 2475 2476
    }
  }

2477
  void _handleLongPressEnd(LongPressEndDetails details) {
2478
    if (!_isDoubleTap && widget.onSingleLongTapEnd != null) {
2479
      widget.onSingleLongTapEnd!(details);
2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
    }
    _isDoubleTap = false;
  }

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

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

2495
    final Offset difference = secondTapOffset - _lastTapOffset!;
2496 2497 2498 2499 2500
    return difference.distance <= kDoubleTapSlop;
  }

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

2503 2504 2505
    gestures[TapGestureRecognizer] = GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
      () => TapGestureRecognizer(debugOwner: this),
      (TapGestureRecognizer instance) {
2506
        instance
2507 2508
          ..onSecondaryTap = widget.onSecondaryTap
          ..onSecondaryTapDown = widget.onSecondaryTapDown
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518
          ..onTapDown = _handleTapDown
          ..onTapUp = _handleTapUp
          ..onTapCancel = _handleTapCancel;
      },
    );

    if (widget.onSingleLongTapStart != null ||
        widget.onSingleLongTapMoveUpdate != null ||
        widget.onSingleLongTapEnd != null) {
      gestures[LongPressGestureRecognizer] = GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
2519 2520
        () => LongPressGestureRecognizer(debugOwner: this, kind: PointerDeviceKind.touch),
        (LongPressGestureRecognizer instance) {
2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
          instance
            ..onLongPressStart = _handleLongPressStart
            ..onLongPressMoveUpdate = _handleLongPressMoveUpdate
            ..onLongPressEnd = _handleLongPressEnd;
        },
      );
    }

    if (widget.onDragSelectionStart != null ||
        widget.onDragSelectionUpdate != null ||
        widget.onDragSelectionEnd != null) {
2532 2533 2534
      gestures[PanGestureRecognizer] = GestureRecognizerFactoryWithHandlers<PanGestureRecognizer>(
        () => PanGestureRecognizer(debugOwner: this, supportedDevices: <PointerDeviceKind>{ PointerDeviceKind.mouse }),
        (PanGestureRecognizer instance) {
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547
          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>(
2548 2549
        () => ForcePressGestureRecognizer(debugOwner: this),
        (ForcePressGestureRecognizer instance) {
2550 2551 2552 2553 2554 2555 2556 2557 2558
          instance
            ..onStart = widget.onForcePressStart != null ? _forcePressStarted : null
            ..onEnd = widget.onForcePressEnd != null ? _forcePressEnded : null;
        },
      );
    }

    return RawGestureDetector(
      gestures: gestures,
2559 2560 2561 2562 2563 2564
      excludeFromSemantics: true,
      behavior: widget.behavior,
      child: widget.child,
    );
  }
}
2565

2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577
/// 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);

2578 2579 2580 2581 2582 2583
  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;

2584
  /// Check the [Clipboard] and update [value] if needed.
2585
  Future<void> update() async {
2586 2587 2588 2589
    if (_disposed) {
      return;
    }

2590
    final bool hasStrings;
2591
    try {
2592
      hasStrings = await Clipboard.hasStrings();
2593 2594 2595 2596 2597 2598 2599
    } catch (exception, stack) {
      FlutterError.reportError(FlutterErrorDetails(
        exception: exception,
        stack: stack,
        library: 'widget library',
        context: ErrorDescription('while checking if the clipboard has strings'),
      ));
2600 2601
      // In the case of an error from the Clipboard API, set the value to
      // unknown so that it will try to update again later.
2602
      if (_disposed || value == ClipboardStatus.unknown) {
2603 2604
        return;
      }
2605 2606 2607 2608
      value = ClipboardStatus.unknown;
      return;
    }

2609
    final ClipboardStatus nextStatus = hasStrings
2610 2611
        ? ClipboardStatus.pasteable
        : ClipboardStatus.notPasteable;
2612

2613
    if (_disposed || nextStatus == value) {
2614 2615
      return;
    }
2616
    value = nextStatus;
2617 2618 2619 2620 2621
  }

  @override
  void addListener(VoidCallback listener) {
    if (!hasListeners) {
2622
      WidgetsBinding.instance.addObserver(this);
2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
    }
    if (value == ClipboardStatus.unknown) {
      update();
    }
    super.addListener(listener);
  }

  @override
  void removeListener(VoidCallback listener) {
    super.removeListener(listener);
2633
    if (!_disposed && !hasListeners) {
2634
      WidgetsBinding.instance.removeObserver(this);
2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
    }
  }

  @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() {
2653
    WidgetsBinding.instance.removeObserver(this);
2654
    _disposed = true;
2655
    super.dispose();
2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668
  }
}

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

2669
  /// The content on the clipboard is not pastable, such as when it is empty.
2670 2671
  notPasteable,
}