text_selection.dart 20.1 KB
Newer Older
1 2 3 4
// Copyright 2016 The Chromium Authors. All rights reserved.
// 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 6
import 'dart:async';

7
import 'package:flutter/rendering.dart';
8
import 'package:flutter/services.dart';
9
import 'package:flutter/scheduler.dart';
10 11

import 'basic.dart';
12
import 'container.dart';
13
import 'editable_text.dart';
14 15 16
import 'framework.dart';
import 'gesture_detector.dart';
import 'overlay.dart';
17
import 'transitions.dart';
18

19 20 21 22
/// Which type of selection handle to be displayed.
///
/// With mixed-direction text, both handles may be the same type. Examples:
///
23 24 25 26 27
/// * LTR text: 'the <quick brown> fox':
///
///   The '<' is drawn with the [left] type, the '>' with the [right]
///
/// * RTL text: 'XOF <NWORB KCIUQ> EHT':
28
///
29
///   Same as above.
30
///
31 32 33 34 35 36 37 38 39
/// * mixed text: '<the NWOR<B KCIUQ fox'
///
///   Here 'the QUICK B' is selected, but 'QUICK BROWN' is RTL. Both are drawn
///   with the [left] type.
///
/// See also:
///
///  * [TextDirection], which discusses left-to-right and right-to-left text in
///    more detail.
40 41 42
enum TextSelectionHandleType {
  /// The selection handle is to the left of the selection end point.
  left,
43

44 45 46 47 48 49 50
  /// The selection handle is to the right of the selection end point.
  right,

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

51 52 53 54
/// The text position that a give selection handle manipulates. Dragging the
/// [start] handle always moves the [start]/[baseOffset] of the selection.
enum _TextSelectionHandlePosition { start, end }

55 56 57 58
/// Signature for reporting changes to the selection component of a
/// [TextEditingValue] for the purposes of a [TextSelectionOverlay]. The
/// [caretRect] argument gives the location of the caret in the coordinate space
/// of the [RenderBox] given by the [TextSelectionOverlay.renderObject].
59 60
///
/// Used by [TextSelectionOverlay.onSelectionOverlayChanged].
61
typedef void TextSelectionOverlayChanged(TextEditingValue value, Rect caretRect);
62

63 64 65 66
/// An interface for manipulating the selection, to be used by the implementor
/// of the toolbar widget.
abstract class TextSelectionDelegate {
  /// Gets the current text input.
67
  TextEditingValue get textEditingValue;
68 69

  /// Sets the current text input (replaces the whole line).
70
  set textEditingValue(TextEditingValue value);
71 72 73

  /// Hides the text selection toolbar.
  void hideToolbar();
74 75 76 77

  /// Brings the provided [TextPosition] into the visible area of the text
  /// input.
  void bringIntoView(TextPosition position);
78 79
}

80 81
/// An interface for building the selection UI, to be provided by the
/// implementor of the toolbar widget.
xster's avatar
xster committed
82 83
///
/// Override text operations such as [handleCut] if needed.
84 85
abstract class TextSelectionControls {
  /// Builds a selection handle of the given type.
xster's avatar
xster committed
86 87 88 89
  ///
  /// The top left corner of this widget is positioned at the bottom of the
  /// selection position.
  Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight);
90 91 92 93

  /// Builds a toolbar near a text selection.
  ///
  /// Typically displays buttons for copying and pasting text.
94
  Widget buildToolbar(BuildContext context, Rect globalEditableRegion, Offset position, TextSelectionDelegate delegate);
95 96 97

  /// Returns the size of the selection handle.
  Size get handleSize;
xster's avatar
xster committed
98

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
  /// 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) {
    return !delegate.textEditingValue.selection.isCollapsed;
  }

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

  /// Whether the current [Clipboard] content can be pasted into the text field
  /// managed by the given `delegate`.
  ///
  /// Subclasses can use this to decide if they should expose the paste
  /// functionality to the user.
  bool canPaste(TextSelectionDelegate delegate) {
    // TODO(goderbauer): return false when clipboard is empty, https://github.com/flutter/flutter/issues/11254
    return true;
  }

132
  /// Whether the current selection of the text field managed by the given
133 134 135 136 137 138 139 140 141
  /// `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) {
    return delegate.textEditingValue.text.isNotEmpty && delegate.textEditingValue.selection.isCollapsed;
  }

142 143 144 145 146 147
  /// Copy the current selection of the text field managed by the given
  /// `delegate` to the [Clipboard]. Then, remove the selected text from the
  /// text field and hide the toolbar.
  ///
  /// This is called by subclasses when their cut affordance is activated by
  /// the user.
xster's avatar
xster committed
148 149 150 151 152 153 154 155 156 157 158 159
  void handleCut(TextSelectionDelegate delegate) {
    final TextEditingValue value = delegate.textEditingValue;
    Clipboard.setData(new ClipboardData(
      text: value.selection.textInside(value.text),
    ));
    delegate.textEditingValue = new TextEditingValue(
      text: value.selection.textBefore(value.text)
          + value.selection.textAfter(value.text),
      selection: new TextSelection.collapsed(
        offset: value.selection.start
      ),
    );
160
    delegate.bringIntoView(delegate.textEditingValue.selection.extent);
xster's avatar
xster committed
161 162 163
    delegate.hideToolbar();
  }

164 165 166 167 168 169
  /// Copy the current selection of the text field managed by the given
  /// `delegate` to the [Clipboard]. Then, move the cursor to the end of the
  /// text (collapsing the selection in the process), and hide the toolbar.
  ///
  /// This is called by subclasses when their copy affordance is activated by
  /// the user.
xster's avatar
xster committed
170 171 172 173 174 175 176 177 178
  void handleCopy(TextSelectionDelegate delegate) {
    final TextEditingValue value = delegate.textEditingValue;
    Clipboard.setData(new ClipboardData(
      text: value.selection.textInside(value.text),
    ));
    delegate.textEditingValue = new TextEditingValue(
      text: value.text,
      selection: new TextSelection.collapsed(offset: value.selection.end),
    );
179
    delegate.bringIntoView(delegate.textEditingValue.selection.extent);
xster's avatar
xster committed
180 181 182
    delegate.hideToolbar();
  }

183 184 185 186 187 188 189 190 191 192 193
  /// Paste the current clipboard selection (obtained from [Clipboard]) into
  /// the text field managed by the given `delegate`, replacing its current
  /// selection, if any. Then, hide the toolbar.
  ///
  /// 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
xster's avatar
xster committed
194
  Future<Null> handlePaste(TextSelectionDelegate delegate) async {
195
    final TextEditingValue value = delegate.textEditingValue; // Snapshot the input before using `await`.
xster's avatar
xster committed
196 197 198 199 200 201 202 203 204 205 206
    final ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain);
    if (data != null) {
      delegate.textEditingValue = new TextEditingValue(
        text: value.selection.textBefore(value.text)
            + data.text
            + value.selection.textAfter(value.text),
        selection: new TextSelection.collapsed(
          offset: value.selection.start + data.text.length
        ),
      );
    }
207
    delegate.bringIntoView(delegate.textEditingValue.selection.extent);
xster's avatar
xster committed
208 209 210
    delegate.hideToolbar();
  }

211 212 213 214 215 216 217
  /// Adjust the selection of the text field managed by the given `delegate` so
  /// that everything is selected.
  ///
  /// 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 219 220 221 222 223 224 225
  void handleSelectAll(TextSelectionDelegate delegate) {
    delegate.textEditingValue = new TextEditingValue(
      text: delegate.textEditingValue.text,
      selection: new TextSelection(
        baseOffset: 0,
        extentOffset: delegate.textEditingValue.text.length
      ),
    );
226
    delegate.bringIntoView(delegate.textEditingValue.selection.extent);
xster's avatar
xster committed
227
  }
228 229
}

230 231 232 233
/// An object that manages a pair of text selection handles.
///
/// The selection handles are displayed in the [Overlay] that most closely
/// encloses the given [BuildContext].
234
class TextSelectionOverlay {
235 236 237
  /// Creates an object that manages overly entries for selection handles.
  ///
  /// The [context] must not be null and must have an [Overlay] as an ancestor.
238
  TextSelectionOverlay({
239
    @required TextEditingValue value,
240
    @required this.context,
241
    this.debugRequiredFor,
242 243
    @required this.layerLink,
    @required this.renderObject,
244
    this.selectionControls,
245
    this.selectionDelegate,
246 247 248
  }): assert(value != null),
      assert(context != null),
      _value = value {
249 250
    final OverlayState overlay = Overlay.of(context);
    assert(overlay != null);
251 252
    _handleController = new AnimationController(duration: _fadeDuration, vsync: overlay);
    _toolbarController = new AnimationController(duration: _fadeDuration, vsync: overlay);
253
  }
254

255 256 257 258
  /// 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].
259
  final BuildContext context;
260 261

  /// Debugging information for explaining why the [Overlay] is required.
262
  final Widget debugRequiredFor;
263

264 265 266 267
  /// The object supplied to the [CompositedTransformTarget] that wraps the text
  /// field.
  final LayerLink layerLink;

268 269
  // 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.
270
  /// The editable line in which the selected text is being displayed.
271
  final RenderEditable renderObject;
272

273 274
  /// Builds text selection handles and toolbar.
  final TextSelectionControls selectionControls;
275

276 277 278 279
  /// The delegate for manipulating the current selection in the owning
  /// text field.
  final TextSelectionDelegate selectionDelegate;

280
  /// Controls the fade-in animations.
281
  static const Duration _fadeDuration = Duration(milliseconds: 150);
282 283
  AnimationController _handleController;
  AnimationController _toolbarController;
284 285 286
  Animation<double> get _handleOpacity => _handleController.view;
  Animation<double> get _toolbarOpacity => _toolbarController.view;

287
  TextEditingValue _value;
288 289 290 291 292

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

293
  /// A copy/paste toolbar.
294 295
  OverlayEntry _toolbar;

296
  TextSelection get _selection => _value.selection;
297

298
  /// Shows the handles by inserting them into the [context]'s overlay.
299
  void showHandles() {
300 301
    assert(_handles == null);
    _handles = <OverlayEntry>[
302 303
      new OverlayEntry(builder: (BuildContext context) => _buildHandle(context, _TextSelectionHandlePosition.start)),
      new OverlayEntry(builder: (BuildContext context) => _buildHandle(context, _TextSelectionHandlePosition.end)),
304 305
    ];
    Overlay.of(context, debugRequiredFor: debugRequiredFor).insertAll(_handles);
306
    _handleController.forward(from: 0.0);
307 308 309 310 311 312
  }

  /// Shows the toolbar by inserting it into the [context]'s overlay.
  void showToolbar() {
    assert(_toolbar == null);
    _toolbar = new OverlayEntry(builder: _buildToolbar);
313
    Overlay.of(context, debugRequiredFor: debugRequiredFor).insert(_toolbar);
314
    _toolbarController.forward(from: 0.0);
315 316
  }

317
  /// Updates the overlay after the selection has changed.
318 319
  ///
  /// If this method is called while the [SchedulerBinding.schedulerPhase] is
320 321
  /// [SchedulerPhase.persistentCallbacks], i.e. during the build, layout, or
  /// paint phases (see [WidgetsBinding.drawFrame]), then the update is delayed
322 323 324 325
  /// 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).
326 327
  void update(TextEditingValue newValue) {
    if (_value == newValue)
328
      return;
329
    _value = newValue;
330 331 332 333 334 335 336
    if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
      SchedulerBinding.instance.addPostFrameCallback(_markNeedsBuild);
    } else {
      _markNeedsBuild();
    }
  }

337 338 339 340 341 342 343 344
  /// 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() {
    _markNeedsBuild();
  }

345
  void _markNeedsBuild([Duration duration]) {
346 347 348 349 350
    if (_handles != null) {
      _handles[0].markNeedsBuild();
      _handles[1].markNeedsBuild();
    }
    _toolbar?.markNeedsBuild();
351 352
  }

353 354 355 356 357 358
  /// Whether the handles are currently visible.
  bool get handlesAreVisible => _handles != null;

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

359
  /// Hides the overlay.
360
  void hide() {
361 362 363 364 365 366
    if (_handles != null) {
      _handles[0].remove();
      _handles[1].remove();
      _handles = null;
    }
    _toolbar?.remove();
367
    _toolbar = null;
368 369 370 371 372 373 374 375 376 377

    _handleController.stop();
    _toolbarController.stop();
  }

  /// Final cleanup.
  void dispose() {
    hide();
    _handleController.dispose();
    _toolbarController.dispose();
378 379
  }

380
  Widget _buildHandle(BuildContext context, _TextSelectionHandlePosition position) {
381
    if ((_selection.isCollapsed && position == _TextSelectionHandlePosition.end) ||
382
        selectionControls == null)
383
      return new Container(); // hide the second handle when collapsed
384 385 386 387

    return new FadeTransition(
      opacity: _handleOpacity,
      child: new _TextSelectionHandleOverlay(
388
        onSelectionHandleChanged: (TextSelection newSelection) { _handleSelectionHandleChanged(newSelection, position); },
389
        onSelectionHandleTapped: _handleSelectionHandleTapped,
390
        layerLink: layerLink,
391 392
        renderObject: renderObject,
        selection: _selection,
393
        selectionControls: selectionControls,
394
        position: position,
395
      )
396 397 398
    );
  }

399
  Widget _buildToolbar(BuildContext context) {
400
    if (selectionControls == null)
401 402 403
      return new Container();

    // Find the horizontal midpoint, just above the selected text.
404
    final List<TextSelectionPoint> endpoints = renderObject.getEndpointsForSelection(_selection);
405
    final Offset midpoint = new Offset(
406
      (endpoints.length == 1) ?
407 408
        endpoints[0].point.dx :
        (endpoints[0].point.dx + endpoints[1].point.dx) / 2.0,
409
      endpoints[0].point.dy - renderObject.preferredLineHeight,
410 411 412 413 414
    );

    final Rect editingRegion = new Rect.fromPoints(
      renderObject.localToGlobal(Offset.zero),
      renderObject.localToGlobal(renderObject.size.bottomRight(Offset.zero)),
415 416
    );

417 418
    return new FadeTransition(
      opacity: _toolbarOpacity,
419 420 421 422
      child: new CompositedTransformFollower(
        link: layerLink,
        showWhenUnlinked: false,
        offset: -editingRegion.topLeft,
423
        child: selectionControls.buildToolbar(context, editingRegion, midpoint, selectionDelegate),
424
      ),
425
    );
426 427
  }

428
  void _handleSelectionHandleChanged(TextSelection newSelection, _TextSelectionHandlePosition position) {
429
    TextPosition textPosition;
430 431
    switch (position) {
      case _TextSelectionHandlePosition.start:
432
        textPosition = newSelection.base;
433 434
        break;
      case _TextSelectionHandlePosition.end:
435
        textPosition =newSelection.extent;
436 437
        break;
    }
438 439
    selectionDelegate.textEditingValue = _value.copyWith(selection: newSelection, composing: TextRange.empty);
    selectionDelegate.bringIntoView(textPosition);
440 441
  }

442
  void _handleSelectionHandleTapped() {
443
    if (_value.selection.isCollapsed) {
444 445 446 447 448 449 450 451
      if (_toolbar != null) {
        _toolbar?.remove();
        _toolbar = null;
      } else {
        showToolbar();
      }
    }
  }
452 453 454 455
}

/// This widget represents a single draggable text selection handle.
class _TextSelectionHandleOverlay extends StatefulWidget {
456
  const _TextSelectionHandleOverlay({
457
    Key key,
458 459 460 461 462 463 464
    @required this.selection,
    @required this.position,
    @required this.layerLink,
    @required this.renderObject,
    @required this.onSelectionHandleChanged,
    @required this.onSelectionHandleTapped,
    @required this.selectionControls
465 466 467 468
  }) : super(key: key);

  final TextSelection selection;
  final _TextSelectionHandlePosition position;
469
  final LayerLink layerLink;
470
  final RenderEditable renderObject;
471
  final ValueChanged<TextSelection> onSelectionHandleChanged;
472
  final VoidCallback onSelectionHandleTapped;
473
  final TextSelectionControls selectionControls;
474 475 476 477 478 479

  @override
  _TextSelectionHandleOverlayState createState() => new _TextSelectionHandleOverlayState();
}

class _TextSelectionHandleOverlayState extends State<_TextSelectionHandleOverlay> {
480
  Offset _dragPosition;
481

482
  void _handleDragStart(DragStartDetails details) {
483
    _dragPosition = details.globalPosition + new Offset(0.0, -widget.selectionControls.handleSize.height);
484 485
  }

486 487
  void _handleDragUpdate(DragUpdateDetails details) {
    _dragPosition += details.delta;
488
    final TextPosition position = widget.renderObject.getPositionForPoint(_dragPosition);
489

490 491
    if (widget.selection.isCollapsed) {
      widget.onSelectionHandleChanged(new TextSelection.fromPosition(position));
492 493 494 495
      return;
    }

    TextSelection newSelection;
496
    switch (widget.position) {
497 498 499
      case _TextSelectionHandlePosition.start:
        newSelection = new TextSelection(
          baseOffset: position.offset,
500
          extentOffset: widget.selection.extentOffset
501 502 503 504
        );
        break;
      case _TextSelectionHandlePosition.end:
        newSelection = new TextSelection(
505
          baseOffset: widget.selection.baseOffset,
506 507 508 509 510 511 512 513
          extentOffset: position.offset
        );
        break;
    }

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

514
    widget.onSelectionHandleChanged(newSelection);
515 516
  }

517
  void _handleTap() {
518
    widget.onSelectionHandleTapped();
519 520
  }

521 522
  @override
  Widget build(BuildContext context) {
523
    final List<TextSelectionPoint> endpoints = widget.renderObject.getEndpointsForSelection(widget.selection);
524
    Offset point;
525 526
    TextSelectionHandleType type;

527
    switch (widget.position) {
528 529 530 531 532 533 534 535 536 537 538 539 540
      case _TextSelectionHandlePosition.start:
        point = endpoints[0].point;
        type = _chooseType(endpoints[0], TextSelectionHandleType.left, TextSelectionHandleType.right);
        break;
      case _TextSelectionHandlePosition.end:
        // [endpoints] will only contain 1 point for collapsed selections, in
        // which case we shouldn't be building the [end] handle.
        assert(endpoints.length == 2);
        point = endpoints[1].point;
        type = _chooseType(endpoints[1], TextSelectionHandleType.right, TextSelectionHandleType.left);
        break;
    }

541 542 543 544 545 546 547 548 549 550 551 552
    return new CompositedTransformFollower(
      link: widget.layerLink,
      showWhenUnlinked: false,
      child: new GestureDetector(
        onPanStart: _handleDragStart,
        onPanUpdate: _handleDragUpdate,
        onTap: _handleTap,
        child: new Stack(
          children: <Widget>[
            new Positioned(
              left: point.dx,
              top: point.dy,
xster's avatar
xster committed
553 554 555
              child: widget.selectionControls.buildHandle(
                context,
                type,
556
                widget.renderObject.preferredLineHeight,
xster's avatar
xster committed
557
              ),
558 559 560 561
            ),
          ],
        ),
      ),
562 563 564 565 566 567 568 569
    );
  }

  TextSelectionHandleType _chooseType(
    TextSelectionPoint endpoint,
    TextSelectionHandleType ltrType,
    TextSelectionHandleType rtlType
  ) {
570
    if (widget.selection.isCollapsed)
571 572
      return TextSelectionHandleType.collapsed;

573
    assert(endpoint.direction != null);
574
    switch (endpoint.direction) {
575 576 577 578 579
      case TextDirection.ltr:
        return ltrType;
      case TextDirection.rtl:
        return rtlType;
    }
pq's avatar
pq committed
580
    return null;
581 582
  }
}