text_selection.dart 8.39 KB
Newer Older
1 2 3 4 5 6 7
// 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.

import 'dart:math' as math;

import 'package:flutter/widgets.dart';
8
import 'package:flutter/rendering.dart';
9

10
import 'debug.dart';
11 12
import 'flat_button.dart';
import 'material.dart';
13
import 'material_localizations.dart';
14 15
import 'theme.dart';

xster's avatar
xster committed
16
const double _kHandleSize = 22.0;
17

xster's avatar
xster committed
18 19 20
// Minimal padding from all edges of the selection toolbar to all edges of the
// viewport.
const double _kToolbarScreenPadding = 8.0;
21
const double _kToolbarHeight = 44.0;
22 23 24
// Padding when positioning toolbar below selection.
const double _kToolbarContentDistanceBelow = 16.0;
const double _kToolbarContentDistance = 8.0;
25 26 27

/// Manages a copy/paste text selection toolbar.
class _TextSelectionToolbar extends StatelessWidget {
xster's avatar
xster committed
28 29 30 31 32 33 34
  const _TextSelectionToolbar({
    Key key,
    this.handleCut,
    this.handleCopy,
    this.handlePaste,
    this.handleSelectAll,
  }) : super(key: key);
35

xster's avatar
xster committed
36 37 38 39 40
  final VoidCallback handleCut;
  final VoidCallback handleCopy;
  final VoidCallback handlePaste;
  final VoidCallback handleSelectAll;

41 42
  @override
  Widget build(BuildContext context) {
43
    final MaterialLocalizations localizations = MaterialLocalizations.of(context);
44 45 46 47 48 49
    final List<Widget> items = <Widget>[
      if (handleCut != null) FlatButton(child: Text(localizations.cutButtonLabel), onPressed: handleCut),
      if (handleCopy != null) FlatButton(child: Text(localizations.copyButtonLabel), onPressed: handleCopy),
      if (handlePaste != null) FlatButton(child: Text(localizations.pasteButtonLabel), onPressed: handlePaste),
      if (handleSelectAll != null) FlatButton(child: Text(localizations.selectAllButtonLabel), onPressed: handleSelectAll),
    ];
50

51 52 53 54 55
    // If there is no option available, build an empty widget.
    if (items.isEmpty) {
      return Container(width: 0.0, height: 0.0);
    }

56
    return Material(
57
      elevation: 1.0,
58
      child: Container(
59
        height: _kToolbarHeight,
60 61
        child: Row(mainAxisSize: MainAxisSize.min, children: items),
      ),
62 63 64 65 66 67 68
    );
  }
}

/// Centers the toolbar around the given position, ensuring that it remains on
/// screen.
class _TextSelectionToolbarLayout extends SingleChildLayoutDelegate {
69
  _TextSelectionToolbarLayout(this.screenSize, this.globalEditableRegion, this.position);
70

71 72 73 74 75 76 77 78 79
  /// The size of the screen at the time that the toolbar was last laid out.
  final Size screenSize;

  /// Size and position of the editing region at the time the toolbar was last
  /// laid out, in global coordinates.
  final Rect globalEditableRegion;

  /// Anchor position of the toolbar, relative to the top left of the
  /// [globalEditableRegion].
80
  final Offset position;
81 82 83 84 85 86 87 88

  @override
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
    return constraints.loosen();
  }

  @override
  Offset getPositionForChild(Size size, Size childSize) {
89 90 91 92
    final Offset globalPosition = globalEditableRegion.topLeft + position;

    double x = globalPosition.dx - childSize.width / 2.0;
    double y = globalPosition.dy - childSize.height;
93 94 95

    if (x < _kToolbarScreenPadding)
      x = _kToolbarScreenPadding;
96 97 98
    else if (x + childSize.width > screenSize.width - _kToolbarScreenPadding)
      x = screenSize.width - childSize.width - _kToolbarScreenPadding;

99 100
    if (y < _kToolbarScreenPadding)
      y = _kToolbarScreenPadding;
101 102
    else if (y + childSize.height > screenSize.height - _kToolbarScreenPadding)
      y = screenSize.height - childSize.height - _kToolbarScreenPadding;
103

104
    return Offset(x, y);
105 106 107 108 109 110 111 112
  }

  @override
  bool shouldRelayout(_TextSelectionToolbarLayout oldDelegate) {
    return position != oldDelegate.position;
  }
}

113
/// Draws a single text selection handle which points up and to the left.
114 115 116 117 118 119 120
class _TextSelectionHandlePainter extends CustomPainter {
  _TextSelectionHandlePainter({ this.color });

  final Color color;

  @override
  void paint(Canvas canvas, Size size) {
121
    final Paint paint = Paint()..color = color;
122
    final double radius = size.width/2.0;
123 124
    canvas.drawCircle(Offset(radius, radius), radius, paint);
    canvas.drawRect(Rect.fromLTWH(0.0, 0.0, radius, radius), paint);
125 126 127 128 129 130 131 132
  }

  @override
  bool shouldRepaint(_TextSelectionHandlePainter oldPainter) {
    return color != oldPainter.color;
  }
}

133
class _MaterialTextSelectionControls extends TextSelectionControls {
134
  /// Returns the size of the Material handle.
135
  @override
136
  Size getHandleSize(double textLineHeight) => const Size(_kHandleSize, _kHandleSize);
137

138 139
  /// Builder for material-style copy/paste text selection toolbar.
  @override
140 141 142
  Widget buildToolbar(
    BuildContext context,
    Rect globalEditableRegion,
143
    double textLineHeight,
144 145 146 147
    Offset position,
    List<TextSelectionPoint> endpoints,
    TextSelectionDelegate delegate,
  ) {
148
    assert(debugCheckHasMediaQuery(context));
149
    assert(debugCheckHasMaterialLocalizations(context));
150 151 152 153

    // The toolbar should appear below the TextField
    // when there is not enough space above the TextField to show it.
    final TextSelectionPoint startTextSelectionPoint = endpoints[0];
154 155 156 157 158 159 160 161 162 163
    final double toolbarHeightNeeded = MediaQuery.of(context).padding.top
      + _kToolbarScreenPadding
      + _kToolbarHeight
      + _kToolbarContentDistance;
    final double availableHeight = globalEditableRegion.top + endpoints.first.point.dy - textLineHeight;
    final bool fitsAbove = toolbarHeightNeeded <= availableHeight;
    final double y = fitsAbove
        ? startTextSelectionPoint.point.dy - _kToolbarContentDistance - textLineHeight
        : startTextSelectionPoint.point.dy + _kToolbarHeight + _kToolbarContentDistanceBelow;
    final Offset preciseMidpoint = Offset(position.dx, y);
164

165 166 167 168
    return ConstrainedBox(
      constraints: BoxConstraints.tight(globalEditableRegion.size),
      child: CustomSingleChildLayout(
        delegate: _TextSelectionToolbarLayout(
169 170
          MediaQuery.of(context).size,
          globalEditableRegion,
171
          preciseMidpoint,
172
        ),
173
        child: _TextSelectionToolbar(
174 175 176 177
          handleCut: canCut(delegate) ? () => handleCut(delegate) : null,
          handleCopy: canCopy(delegate) ? () => handleCopy(delegate) : null,
          handlePaste: canPaste(delegate) ? () => handlePaste(delegate) : null,
          handleSelectAll: canSelectAll(delegate) ? () => handleSelectAll(delegate) : null,
xster's avatar
xster committed
178
        ),
179
      ),
180 181 182 183 184
    );
  }

  /// Builder for material-style text selection handles.
  @override
xster's avatar
xster committed
185
  Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textHeight) {
186 187 188 189 190 191
    final Widget handle = SizedBox(
      width: _kHandleSize,
      height: _kHandleSize,
      child: CustomPaint(
        painter: _TextSelectionHandlePainter(
          color: Theme.of(context).textSelectionHandleColor
192 193
        ),
      ),
194 195 196 197 198 199
    );

    // [handle] is a circle, with a rectangle in the top left quadrant of that
    // circle (an onion pointing to 10:30). We rotate [handle] to point
    // straight up or up-right depending on the handle type.
    switch (type) {
200
      case TextSelectionHandleType.left: // points up-right
201 202
        return Transform.rotate(
          angle: math.pi / 2.0,
203
          child: handle,
204
        );
205
      case TextSelectionHandleType.right: // points up-left
206
        return handle;
207
      case TextSelectionHandleType.collapsed: // points up
208 209
        return Transform.rotate(
          angle: math.pi / 4.0,
210
          child: handle,
211 212 213 214
        );
    }
    assert(type != null);
    return null;
215
  }
216

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
  /// Gets anchor for material-style text selection handles.
  ///
  /// See [TextSelectionControls.getHandleAnchor].
  @override
  Offset getHandleAnchor(TextSelectionHandleType type, double textLineHeight) {
    switch (type) {
      case TextSelectionHandleType.left:
        return const Offset(_kHandleSize, 0);
      case TextSelectionHandleType.right:
        return Offset.zero;
      default:
        return const Offset(_kHandleSize / 2, -4);
    }
  }

232 233 234 235 236
  @override
  bool canSelectAll(TextSelectionDelegate delegate) {
    // Android allows SelectAll when selection is not collapsed, unless
    // everything has already been selected.
    final TextEditingValue value = delegate.textEditingValue;
237 238 239
    return delegate.selectAllEnabled &&
           value.text.isNotEmpty &&
           !(value.selection.start == 0 && value.selection.end == value.text.length);
240
  }
241
}
242

Adam Barth's avatar
Adam Barth committed
243
/// Text selection controls that follow the Material Design specification.
244
final TextSelectionControls materialTextSelectionControls = _MaterialTextSelectionControls();