text_selection.dart 10.7 KB
Newer Older
xster's avatar
xster committed
1 2 3 4 5 6 7 8 9 10
// Copyright 2017 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';
import 'package:flutter/rendering.dart';

import 'button.dart';
11
import 'colors.dart';
12
import 'localizations.dart';
xster's avatar
xster committed
13 14 15 16 17 18 19 20 21

// Padding around the line at the edge of the text selection that has 0 width and
// the height of the text font.
const double _kHandlesPadding = 18.0;
// Minimal padding from all edges of the selection toolbar to all edges of the
// viewport.
const double _kToolbarScreenPadding = 8.0;
const double _kToolbarHeight = 36.0;

22 23
const Color _kToolbarBackgroundColor = Color(0xFF2E2E2E);
const Color _kToolbarDividerColor = Color(0xFFB9B9B9);
24 25 26
// Read off from the output on iOS 12. This color does not vary with the
// application's theme color.
const Color _kHandlesColor = Color(0xFF136FE0);
xster's avatar
xster committed
27 28 29 30

// This offset is used to determine the center of the selection during a drag.
// It's slightly below the center of the text so the finger isn't entirely
// covering the text being selected.
31 32
const Size _kSelectionOffset = Size(20.0, 30.0);
const Size _kToolbarTriangleSize = Size(18.0, 9.0);
33
const EdgeInsets _kToolbarButtonPadding = EdgeInsets.symmetric(vertical: 10.0, horizontal: 18.0);
34
const BorderRadius _kToolbarBorderRadius = BorderRadius.all(Radius.circular(7.5));
xster's avatar
xster committed
35

36
const TextStyle _kToolbarButtonFontStyle = TextStyle(
37
  inherit: false,
xster's avatar
xster committed
38 39 40
  fontSize: 14.0,
  letterSpacing: -0.11,
  fontWeight: FontWeight.w300,
41
  color: CupertinoColors.white,
xster's avatar
xster committed
42 43 44 45 46 47
);

/// Paints a triangle below the toolbar.
class _TextSelectionToolbarNotchPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
48
    final Paint paint = Paint()
xster's avatar
xster committed
49 50
        ..color = _kToolbarBackgroundColor
        ..style = PaintingStyle.fill;
51
    final Path triangle = Path()
xster's avatar
xster committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
        ..lineTo(_kToolbarTriangleSize.width / 2, 0.0)
        ..lineTo(0.0, _kToolbarTriangleSize.height)
        ..lineTo(-(_kToolbarTriangleSize.width / 2), 0.0)
        ..close();
    canvas.drawPath(triangle, paint);
  }

  @override
  bool shouldRepaint(_TextSelectionToolbarNotchPainter oldPainter) => false;
}

/// Manages a copy/paste text selection toolbar.
class _TextSelectionToolbar extends StatelessWidget {
  const _TextSelectionToolbar({
    Key key,
    this.handleCut,
    this.handleCopy,
    this.handlePaste,
    this.handleSelectAll,
  }) : super(key: key);

  final VoidCallback handleCut;
  final VoidCallback handleCopy;
  final VoidCallback handlePaste;
  final VoidCallback handleSelectAll;

  @override
  Widget build(BuildContext context) {
    final List<Widget> items = <Widget>[];
    final Widget onePhysicalPixelVerticalDivider =
82 83
    SizedBox(width: 1.0 / MediaQuery.of(context).devicePixelRatio);
    final CupertinoLocalizations localizations = CupertinoLocalizations.of(context);
xster's avatar
xster committed
84

85
    if (handleCut != null)
86
      items.add(_buildToolbarButton(localizations.cutButtonLabel, handleCut));
87 88 89 90

    if (handleCopy != null) {
      if (items.isNotEmpty)
        items.add(onePhysicalPixelVerticalDivider);
91
      items.add(_buildToolbarButton(localizations.copyButtonLabel, handleCopy));
xster's avatar
xster committed
92 93
    }

94 95 96
    if (handlePaste != null) {
      if (items.isNotEmpty)
        items.add(onePhysicalPixelVerticalDivider);
97
      items.add(_buildToolbarButton(localizations.pasteButtonLabel, handlePaste));
98
    }
xster's avatar
xster committed
99

100 101 102
    if (handleSelectAll != null) {
      if (items.isNotEmpty)
        items.add(onePhysicalPixelVerticalDivider);
103
      items.add(_buildToolbarButton(localizations.selectAllButtonLabel, handleSelectAll));
xster's avatar
xster committed
104 105
    }

106
    final Widget triangle = SizedBox.fromSize(
xster's avatar
xster committed
107
      size: _kToolbarTriangleSize,
108 109
      child: CustomPaint(
        painter: _TextSelectionToolbarNotchPainter(),
110
      ),
xster's avatar
xster committed
111 112
    );

113
    return Column(
xster's avatar
xster committed
114 115
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
116
        ClipRRect(
xster's avatar
xster committed
117
          borderRadius: _kToolbarBorderRadius,
118
          child: DecoratedBox(
119
            decoration: BoxDecoration(
xster's avatar
xster committed
120
              color: _kToolbarDividerColor,
121 122 123 124
              borderRadius: _kToolbarBorderRadius,
              // Add a hairline border with the button color to avoid
              // antialiasing artifacts.
              border: Border.all(color: _kToolbarBackgroundColor, width: 0),
xster's avatar
xster committed
125
            ),
126
            child: Row(mainAxisSize: MainAxisSize.min, children: items),
xster's avatar
xster committed
127 128
          ),
        ),
129 130 131
        // TODO(xster): Position the triangle based on the layout delegate, and
        // avoid letting the triangle line up with any dividers.
        // https://github.com/flutter/flutter/issues/11274
xster's avatar
xster committed
132
        triangle,
133
        const Padding(padding: EdgeInsets.only(bottom: 10.0)),
xster's avatar
xster committed
134 135 136 137 138 139
      ],
    );
  }

  /// Builds a themed [CupertinoButton] for the toolbar.
  CupertinoButton _buildToolbarButton(String text, VoidCallback onPressed) {
140 141
    return CupertinoButton(
      child: Text(text, style: _kToolbarButtonFontStyle),
xster's avatar
xster committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
      color: _kToolbarBackgroundColor,
      minSize: _kToolbarHeight,
      padding: _kToolbarButtonPadding,
      borderRadius: null,
      pressedOpacity: 0.7,
      onPressed: onPressed,
    );
  }
}

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

  /// 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].
  final Offset position;

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

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

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

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

    if (y < _kToolbarScreenPadding)
      y = _kToolbarScreenPadding;
    else if (y + childSize.height > screenSize.height - _kToolbarScreenPadding)
      y = screenSize.height - childSize.height - _kToolbarScreenPadding;

190
    return Offset(x, y);
xster's avatar
xster committed
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  }

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

/// Draws a single text selection handle with a bar and a ball.
///
/// Draws from a point of origin somewhere inside the size of the painter
/// such that the ball is below the point of origin and the bar is above the
/// point of origin.
class _TextSelectionHandlePainter extends CustomPainter {
  _TextSelectionHandlePainter({this.origin});

  final Offset origin;

  @override
  void paint(Canvas canvas, Size size) {
213
    final Paint paint = Paint()
xster's avatar
xster committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
        ..color = _kHandlesColor
        ..strokeWidth = 2.0;
    // Draw circle below the origin that slightly overlaps the bar.
    canvas.drawCircle(origin.translate(0.0, 4.0), 5.5, paint);
    // Draw up from origin leaving 10 pixels of margin on top.
    canvas.drawLine(
      origin,
      origin.translate(
        0.0,
        -(size.height - 2.0 * _kHandlesPadding),
      ),
      paint,
    );
  }

  @override
  bool shouldRepaint(_TextSelectionHandlePainter oldPainter) => origin != oldPainter.origin;
}

class _CupertinoTextSelectionControls extends TextSelectionControls {
  @override
  Size handleSize = _kSelectionOffset; // Used for drag selection offset.

  /// Builder for iOS-style copy/paste text selection toolbar.
  @override
  Widget buildToolbar(BuildContext context, Rect globalEditableRegion, Offset position, TextSelectionDelegate delegate) {
    assert(debugCheckHasMediaQuery(context));
241 242 243 244
    return ConstrainedBox(
      constraints: BoxConstraints.tight(globalEditableRegion.size),
      child: CustomSingleChildLayout(
        delegate: _TextSelectionToolbarLayout(
xster's avatar
xster committed
245 246 247 248
          MediaQuery.of(context).size,
          globalEditableRegion,
          position,
        ),
249
        child: _TextSelectionToolbar(
250 251 252 253
          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
254
        ),
255
      ),
xster's avatar
xster committed
256 257 258 259 260 261 262 263
    );
  }

  /// Builder for iOS text selection edges.
  @override
  Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight) {
    // We want a size that's a vertical line the height of the text plus a 18.0
    // padding in every direction that will constitute the selection drag area.
264
    final Size desiredSize = Size(
xster's avatar
xster committed
265
      2.0 * _kHandlesPadding,
266
      textLineHeight + 2.0 * _kHandlesPadding,
xster's avatar
xster committed
267 268
    );

269
    final Widget handle = SizedBox.fromSize(
xster's avatar
xster committed
270
      size: desiredSize,
271 272
      child: CustomPaint(
        painter: _TextSelectionHandlePainter(
xster's avatar
xster committed
273 274 275 276 277
          // We give the painter a point of origin that's at the bottom baseline
          // of the selection cursor position.
          //
          // We give it in the form of an offset from the top left of the
          // SizedBox.
278
          origin: Offset(_kHandlesPadding, textLineHeight + _kHandlesPadding),
xster's avatar
xster committed
279 280 281 282 283 284 285 286 287
        ),
      ),
    );

    // [buildHandle]'s widget is positioned at the selection cursor's bottom
    // baseline. We transform the handle such that the SizedBox is superimposed
    // on top of the text selection endpoints.
    switch (type) {
      case TextSelectionHandleType.left: // The left handle is upside down on iOS.
288 289
        return Transform(
          transform: Matrix4.rotationZ(math.pi)
xster's avatar
xster committed
290
              ..translate(-_kHandlesPadding, -_kHandlesPadding),
291
          child: handle,
xster's avatar
xster committed
292 293
        );
      case TextSelectionHandleType.right:
294 295
        return Transform(
          transform: Matrix4.translationValues(
xster's avatar
xster committed
296 297
            -_kHandlesPadding,
            -(textLineHeight + _kHandlesPadding),
298
            0.0,
xster's avatar
xster committed
299
          ),
300
          child: handle,
xster's avatar
xster committed
301
        );
302
      case TextSelectionHandleType.collapsed: // iOS doesn't draw anything for collapsed selections.
303
        return Container();
xster's avatar
xster committed
304 305 306 307 308 309 310
    }
    assert(type != null);
    return null;
  }
}

/// Text selection controls that follows iOS design conventions.
311
final TextSelectionControls cupertinoTextSelectionControls = _CupertinoTextSelectionControls();