text_painter.dart 32.4 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.

5
import 'dart:math' show min, max;
6
import 'dart:ui' as ui show Paragraph, ParagraphBuilder, ParagraphConstraints, ParagraphStyle, PlaceholderAlignment, LineMetrics;
7

8
import 'package:flutter/foundation.dart';
9 10
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
11

12
import 'basic_types.dart';
13 14
import 'inline_span.dart';
import 'placeholder_span.dart';
15
import 'strut_style.dart';
16
import 'text_span.dart';
17

Ian Hickson's avatar
Ian Hickson committed
18 19
export 'package:flutter/services.dart' show TextRange, TextSelection;

20 21 22 23 24 25 26 27 28 29 30 31 32
/// Holds the [Size] and baseline required to represent the dimensions of
/// a placeholder in text.
///
/// Placeholders specify an empty space in the text layout, which is used
/// to later render arbitrary inline widgets into defined by a [WidgetSpan].
///
/// The [size] and [alignment] properties are required and cannot be null.
///
/// See also:
///
///  * [WidgetSpan], a subclass of [InlineSpan] and [PlaceholderSpan] that
///    represents an inline widget embedded within text. The space this
///    widget takes is indicated by a placeholder.
33
///  * [RichText], a text widget that supports text inline widgets.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 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
@immutable
class PlaceholderDimensions {
  /// Constructs a [PlaceholderDimensions] with the specified parameters.
  ///
  /// The `size` and `alignment` are required as a placeholder's dimensions
  /// require at least `size` and `alignment` to be fully defined.
  const PlaceholderDimensions({
    @required this.size,
    @required this.alignment,
    this.baseline,
    this.baselineOffset,
  }) : assert(size != null),
       assert(alignment != null);

  /// Width and height dimensions of the placeholder.
  final Size size;

  /// How to align the placeholder with the text.
  ///
  /// See also:
  ///
  ///  * [baseline], the baseline to align to when using
  ///    [ui.PlaceholderAlignment.baseline],
  ///    [ui.PlaceholderAlignment.aboveBaseline],
  ///    or [ui.PlaceholderAlignment.underBaseline].
  ///  * [baselineOffset], the distance of the alphabetic baseline from the upper
  ///    edge of the placeholder.
  final ui.PlaceholderAlignment alignment;

  /// Distance of the [baseline] from the upper edge of the placeholder.
  ///
  /// Only used when [alignment] is [ui.PlaceholderAlignment.baseline].
  final double baselineOffset;

  /// The [TextBaseline] to align to. Used with:
  ///
  ///  * [ui.PlaceholderAlignment.baseline]
  ///  * [ui.PlaceholderAlignment.aboveBaseline]
  ///  * [ui.PlaceholderAlignment.underBaseline]
  ///  * [ui.PlaceholderAlignment.middle]
  final TextBaseline baseline;

  @override
  String toString() {
    return 'PlaceholderDimensions($size, $baseline)';
  }
}

82
/// The different ways of measuring the width of one or more lines of text.
83
///
84
/// See [Text.textWidthBasis], for example.
85
enum TextWidthBasis {
86
  /// multiline text will take up the full width given by the parent. For single
87 88 89 90 91 92 93 94 95 96
  /// line text, only the minimum amount of width needed to contain the text
  /// will be used. A common use case for this is a standard series of
  /// paragraphs.
  parent,

  /// The width will be exactly enough to contain the longest line and no
  /// longer. A common use case for this is chat bubbles.
  longestLine,
}

97 98 99
/// This is used to cache and pass the computed metrics regarding the
/// caret's size and position. This is preferred due to the expensive
/// nature of the calculation.
100 101 102 103 104 105 106 107 108 109
class _CaretMetrics {
  const _CaretMetrics({this.offset, this.fullHeight});
  /// The offset of the top left corner of the caret from the top left
  /// corner of the paragraph.
  final Offset offset;

  /// The full height of the glyph at the caret position.
  final double fullHeight;
}

110
/// An object that paints a [TextSpan] tree into a [Canvas].
Hixie's avatar
Hixie committed
111 112 113 114 115 116
///
/// To use a [TextPainter], follow these steps:
///
/// 1. Create a [TextSpan] tree and pass it to the [TextPainter]
///    constructor.
///
117
/// 2. Call [layout] to prepare the paragraph.
Hixie's avatar
Hixie committed
118
///
119
/// 3. Call [paint] as often as desired to paint the paragraph.
Hixie's avatar
Hixie committed
120 121 122 123
///
/// If the width of the area into which the text is being painted
/// changes, return to step 2. If the text to be painted changes,
/// return to step 1.
124 125 126
///
/// The default text style is white. To change the color of the text,
/// pass a [TextStyle] object to the [TextSpan] in `text`.
Adam Barth's avatar
Adam Barth committed
127
class TextPainter {
128 129
  /// Creates a text painter that paints the given text.
  ///
Ian Hickson's avatar
Ian Hickson committed
130 131 132 133
  /// The `text` and `textDirection` arguments are optional but [text] and
  /// [textDirection] must be non-null before calling [layout].
  ///
  /// The [textAlign] property must not be null.
134 135
  ///
  /// The [maxLines] property, if non-null, must be greater than zero.
136
  TextPainter({
137
    InlineSpan text,
138
    TextAlign textAlign = TextAlign.start,
Ian Hickson's avatar
Ian Hickson committed
139
    TextDirection textDirection,
140
    double textScaleFactor = 1.0,
141
    int maxLines,
142
    String ellipsis,
143
    Locale locale,
144
    StrutStyle strutStyle,
145
    TextWidthBasis textWidthBasis = TextWidthBasis.parent,
146
  }) : assert(text == null || text.debugAssertIsValid()),
Ian Hickson's avatar
Ian Hickson committed
147
       assert(textAlign != null),
148
       assert(textScaleFactor != null),
149
       assert(maxLines == null || maxLines > 0),
150
       assert(textWidthBasis != null),
151 152
       _text = text,
       _textAlign = textAlign,
Ian Hickson's avatar
Ian Hickson committed
153
       _textDirection = textDirection,
154 155
       _textScaleFactor = textScaleFactor,
       _maxLines = maxLines,
156
       _ellipsis = ellipsis,
157
       _locale = locale,
158 159
       _strutStyle = strutStyle,
       _textWidthBasis = textWidthBasis;
160

161
  ui.Paragraph _paragraph;
162
  bool _needsLayout = true;
163

164 165 166 167 168 169 170 171 172
  /// Marks this text painter's layout information as dirty and removes cached
  /// information.
  ///
  /// Uses this method to notify text painter to relayout in the case of
  /// layout changes in engine. In most cases, updating text painter properties
  /// in framework will automatically invoke this method.
  void markNeedsLayout() {
    _paragraph = null;
    _needsLayout = true;
173 174
    _previousCaretPosition = null;
    _previousCaretPrototype = null;
175 176
  }

Florian Loitsch's avatar
Florian Loitsch committed
177
  /// The (potentially styled) text to paint.
178 179
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
180
  /// This and [textDirection] must be non-null before you call [layout].
181 182
  ///
  /// The [InlineSpan] this provides is in the form of a tree that may contain
183
  /// multiple instances of [TextSpan]s and [WidgetSpan]s. To obtain a plain text
184 185 186 187 188 189
  /// representation of the contents of this [TextPainter], use [InlineSpan.toPlainText]
  /// to get the full contents of all nodes in the tree. [TextSpan.text] will
  /// only provide the contents of the first node in the tree.
  InlineSpan get text => _text;
  InlineSpan _text;
  set text(InlineSpan value) {
190
    assert(value == null || value.debugAssertIsValid());
191 192
    if (_text == value)
      return;
193 194
    if (_text?.style != value?.style)
      _layoutTemplate = null;
195
    _text = value;
196
    markNeedsLayout();
197 198 199
  }

  /// How the text should be aligned horizontally.
200 201
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
Ian Hickson's avatar
Ian Hickson committed
202 203
  ///
  /// The [textAlign] property must not be null. It defaults to [TextAlign.start].
204 205
  TextAlign get textAlign => _textAlign;
  TextAlign _textAlign;
206
  set textAlign(TextAlign value) {
Ian Hickson's avatar
Ian Hickson committed
207
    assert(value != null);
208 209 210
    if (_textAlign == value)
      return;
    _textAlign = value;
211
    markNeedsLayout();
212 213
  }

Ian Hickson's avatar
Ian Hickson committed
214 215 216 217 218 219 220 221 222
  /// The default directionality of the text.
  ///
  /// This controls how the [TextAlign.start], [TextAlign.end], and
  /// [TextAlign.justify] values of [textAlign] are resolved.
  ///
  /// This is also used to disambiguate how to render bidirectional text. For
  /// example, if the [text] is an English phrase followed by a Hebrew phrase,
  /// in a [TextDirection.ltr] context the English phrase will be on the left
  /// and the Hebrew phrase to its right, while in a [TextDirection.rtl]
223
  /// context, the English phrase will be on the right and the Hebrew phrase on
Ian Hickson's avatar
Ian Hickson committed
224 225 226 227 228 229 230 231 232 233 234
  /// its left.
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
  ///
  /// This and [text] must be non-null before you call [layout].
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    if (_textDirection == value)
      return;
    _textDirection = value;
235
    markNeedsLayout();
Ian Hickson's avatar
Ian Hickson committed
236 237 238
    _layoutTemplate = null; // Shouldn't really matter, but for strict correctness...
  }

239 240 241 242
  /// The number of font pixels for each logical pixel.
  ///
  /// For example, if the text scale factor is 1.5, text will be 50% larger than
  /// the specified font size.
243 244
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
245 246 247 248 249 250 251
  double get textScaleFactor => _textScaleFactor;
  double _textScaleFactor;
  set textScaleFactor(double value) {
    assert(value != null);
    if (_textScaleFactor == value)
      return;
    _textScaleFactor = value;
252
    markNeedsLayout();
253
    _layoutTemplate = null;
254 255
  }

256
  /// The string used to ellipsize overflowing text. Setting this to a non-empty
257
  /// string will cause this string to be substituted for the remaining text
258 259 260 261 262 263 264
  /// if the text can not fit within the specified maximum width.
  ///
  /// Specifically, the ellipsis is applied to the last line before the line
  /// truncated by [maxLines], if [maxLines] is non-null and that line overflows
  /// the width constraint, or to the first line that is wider than the width
  /// constraint, if [maxLines] is null. The width constraint is the `maxWidth`
  /// passed to [layout].
265 266
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
267 268 269 270 271
  ///
  /// The higher layers of the system, such as the [Text] widget, represent
  /// overflow effects using the [TextOverflow] enum. The
  /// [TextOverflow.ellipsis] value corresponds to setting this property to
  /// U+2026 HORIZONTAL ELLIPSIS (…).
272 273 274 275 276 277 278
  String get ellipsis => _ellipsis;
  String _ellipsis;
  set ellipsis(String value) {
    assert(value == null || value.isNotEmpty);
    if (_ellipsis == value)
      return;
    _ellipsis = value;
279
    markNeedsLayout();
280 281
  }

282
  /// The locale used to select region-specific glyphs.
283 284 285
  Locale get locale => _locale;
  Locale _locale;
  set locale(Locale value) {
286 287 288
    if (_locale == value)
      return;
    _locale = value;
289
    markNeedsLayout();
290 291
  }

292 293
  /// An optional maximum number of lines for the text to span, wrapping if
  /// necessary.
294
  ///
295 296
  /// If the text exceeds the given number of lines, it is truncated such that
  /// subsequent lines are dropped.
297 298
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
299 300
  int get maxLines => _maxLines;
  int _maxLines;
301
  /// The value may be null. If it is not null, then it must be greater than zero.
302
  set maxLines(int value) {
303
    assert(value == null || value > 0);
304 305 306
    if (_maxLines == value)
      return;
    _maxLines = value;
307
    markNeedsLayout();
308 309
  }

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
  /// {@template flutter.painting.textPainter.strutStyle}
  /// The strut style to use. Strut style defines the strut, which sets minimum
  /// vertical layout metrics.
  ///
  /// Omitting or providing null will disable strut.
  ///
  /// Omitting or providing null for any properties of [StrutStyle] will result in
  /// default values being used. It is highly recommended to at least specify a
  /// [fontSize].
  ///
  /// See [StrutStyle] for details.
  /// {@endtemplate}
  StrutStyle get strutStyle => _strutStyle;
  StrutStyle _strutStyle;
  set strutStyle(StrutStyle value) {
    if (_strutStyle == value)
      return;
    _strutStyle = value;
328
    markNeedsLayout();
329 330
  }

331 332 333
  /// {@template flutter.painting.textPainter.textWidthBasis}
  /// Defines how to measure the width of the rendered text.
  /// {@endtemplate}
334 335 336 337 338 339 340
  TextWidthBasis get textWidthBasis => _textWidthBasis;
  TextWidthBasis _textWidthBasis;
  set textWidthBasis(TextWidthBasis value) {
    assert(value != null);
    if (_textWidthBasis == value)
      return;
    _textWidthBasis = value;
341
    markNeedsLayout();
342 343
  }

344

345
  ui.Paragraph _layoutTemplate;
346

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
  /// An ordered list of [TextBox]es that bound the positions of the placeholders
  /// in the paragraph.
  ///
  /// Each box corresponds to a [PlaceholderSpan] in the order they were defined
  /// in the [InlineSpan] tree.
  List<TextBox> get inlinePlaceholderBoxes => _inlinePlaceholderBoxes;
  List<TextBox> _inlinePlaceholderBoxes;

  /// An ordered list of scales for each placeholder in the paragraph.
  ///
  /// The scale is used as a multiplier on the height, width and baselineOffset of
  /// the placeholder. Scale is primarily used to handle accessibility scaling.
  ///
  /// Each scale corresponds to a [PlaceholderSpan] in the order they were defined
  /// in the [InlineSpan] tree.
  List<double> get inlinePlaceholderScales => _inlinePlaceholderScales;
  List<double> _inlinePlaceholderScales;

  /// Sets the dimensions of each placeholder in [text].
  ///
  /// The number of [PlaceholderDimensions] provided should be the same as the
  /// number of [PlaceholderSpan]s in text. Passing in an empty or null `value`
  /// will do nothing.
  ///
  /// If [layout] is attempted without setting the placeholder dimensions, the
  /// placeholders will be ignored in the text layout and no valid
  /// [inlinePlaceholderBoxes] will be returned.
  void setPlaceholderDimensions(List<PlaceholderDimensions> value) {
    if (value == null || value.isEmpty || listEquals(value, _placeholderDimensions)) {
      return;
    }
    assert(() {
      int placeholderCount = 0;
      text.visitChildren((InlineSpan span) {
        if (span is PlaceholderSpan) {
          placeholderCount += 1;
        }
        return true;
      });
      return placeholderCount;
    }() == value.length);
    _placeholderDimensions = value;
389
    markNeedsLayout();
390 391 392
  }
  List<PlaceholderDimensions> _placeholderDimensions;

393
  ui.ParagraphStyle _createParagraphStyle([ TextDirection defaultTextDirection ]) {
Ian Hickson's avatar
Ian Hickson committed
394 395 396 397
    // The defaultTextDirection argument is used for preferredLineHeight in case
    // textDirection hasn't yet been set.
    assert(textAlign != null);
    assert(textDirection != null || defaultTextDirection != null, 'TextPainter.textDirection must be set to a non-null value before using the TextPainter.');
398 399
    return _text.style?.getParagraphStyle(
      textAlign: textAlign,
Ian Hickson's avatar
Ian Hickson committed
400
      textDirection: textDirection ?? defaultTextDirection,
401 402 403
      textScaleFactor: textScaleFactor,
      maxLines: _maxLines,
      ellipsis: _ellipsis,
404
      locale: _locale,
405
      strutStyle: _strutStyle,
406
    ) ?? ui.ParagraphStyle(
407
      textAlign: textAlign,
Ian Hickson's avatar
Ian Hickson committed
408
      textDirection: textDirection ?? defaultTextDirection,
409 410
      maxLines: maxLines,
      ellipsis: ellipsis,
411
      locale: locale,
412 413 414
    );
  }

415
  /// The height of a space in [text] in logical pixels.
416
  ///
417 418
  /// Not every line of text in [text] will have this height, but this height
  /// is "typical" for text in [text] and useful for sizing other objects
419
  /// relative a typical line of text.
420 421
  ///
  /// Obtaining this value does not require calling [layout].
Ian Hickson's avatar
Ian Hickson committed
422 423 424 425 426
  ///
  /// The style of the [text] property is used to determine the font settings
  /// that contribute to the [preferredLineHeight]. If [text] is null or if it
  /// specifies no styles, the default [TextStyle] values are used (a 10 pixel
  /// sans-serif font).
427 428
  double get preferredLineHeight {
    if (_layoutTemplate == null) {
429
      final ui.ParagraphBuilder builder = ui.ParagraphBuilder(
Ian Hickson's avatar
Ian Hickson committed
430
        _createParagraphStyle(TextDirection.rtl),
431
      ); // direction doesn't matter, text is just a space
Ian Hickson's avatar
Ian Hickson committed
432
      if (text?.style != null)
433
        builder.pushStyle(text.style.getTextStyle(textScaleFactor: textScaleFactor));
434
      builder.addText(' ');
435
      _layoutTemplate = builder.build()
436
        ..layout(const ui.ParagraphConstraints(width: double.infinity));
437 438 439
    }
    return _layoutTemplate.height;
  }
440

441 442 443 444 445 446 447 448 449 450 451
  // Unfortunately, using full precision floating point here causes bad layouts
  // because floating point math isn't associative. If we add and subtract
  // padding, for example, we'll get different values when we estimate sizes and
  // when we actually compute layout because the operations will end up associated
  // differently. To work around this problem for now, we round fractional pixel
  // values up to the nearest whole pixel value. The right long-term fix is to do
  // layout using fixed precision arithmetic.
  double _applyFloatingPointHack(double layoutValue) {
    return layoutValue.ceilToDouble();
  }

452 453
  /// The width at which decreasing the width of the text would prevent it from
  /// painting itself completely within its bounds.
454
  ///
455
  /// Valid only after [layout] has been called.
456
  double get minIntrinsicWidth {
457 458 459 460
    assert(!_needsLayout);
    return _applyFloatingPointHack(_paragraph.minIntrinsicWidth);
  }

Florian Loitsch's avatar
Florian Loitsch committed
461
  /// The width at which increasing the width of the text no longer decreases the height.
462
  ///
463
  /// Valid only after [layout] has been called.
464
  double get maxIntrinsicWidth {
465 466 467 468
    assert(!_needsLayout);
    return _applyFloatingPointHack(_paragraph.maxIntrinsicWidth);
  }

469 470
  /// The horizontal space required to paint this text.
  ///
471
  /// Valid only after [layout] has been called.
472 473
  double get width {
    assert(!_needsLayout);
474 475 476
    return _applyFloatingPointHack(
      textWidthBasis == TextWidthBasis.longestLine ? _paragraph.longestLine : _paragraph.width,
    );
477 478
  }

479 480
  /// The vertical space required to paint this text.
  ///
481
  /// Valid only after [layout] has been called.
482 483 484 485 486
  double get height {
    assert(!_needsLayout);
    return _applyFloatingPointHack(_paragraph.height);
  }

487 488
  /// The amount of space required to paint this text.
  ///
489
  /// Valid only after [layout] has been called.
490
  Size get size {
491
    assert(!_needsLayout);
492
    return Size(width, height);
493 494
  }

495 496
  /// Returns the distance from the top of the text to the first baseline of the
  /// given type.
497
  ///
498
  /// Valid only after [layout] has been called.
499 500
  double computeDistanceToActualBaseline(TextBaseline baseline) {
    assert(!_needsLayout);
Ian Hickson's avatar
Ian Hickson committed
501
    assert(baseline != null);
502 503
    switch (baseline) {
      case TextBaseline.alphabetic:
504
        return _paragraph.alphabeticBaseline;
505
      case TextBaseline.ideographic:
506
        return _paragraph.ideographicBaseline;
507
    }
pq's avatar
pq committed
508
    return null;
509 510
  }

511 512 513 514 515
  /// Whether any text was truncated or ellipsized.
  ///
  /// If [maxLines] is not null, this is true if there were more lines to be
  /// drawn than the given [maxLines], and thus at least one line was omitted in
  /// the output; otherwise it is false.
516
  ///
517 518 519 520 521
  /// If [maxLines] is null, this is true if [ellipsis] is not the empty string
  /// and there was a line that overflowed the `maxWidth` argument passed to
  /// [layout]; otherwise it is false.
  ///
  /// Valid only after [layout] has been called.
522 523 524 525 526
  bool get didExceedMaxLines {
    assert(!_needsLayout);
    return _paragraph.didExceedMaxLines;
  }

527 528
  double _lastMinWidth;
  double _lastMaxWidth;
529

Florian Loitsch's avatar
Florian Loitsch committed
530
  /// Computes the visual position of the glyphs for painting the text.
531
  ///
532
  /// The text will layout with a width that's as close to its max intrinsic
Ian Hickson's avatar
Ian Hickson committed
533 534 535 536 537
  /// width as possible while still being greater than or equal to `minWidth` and
  /// less than or equal to `maxWidth`.
  ///
  /// The [text] and [textDirection] properties must be non-null before this is
  /// called.
538
  void layout({ double minWidth = 0.0, double maxWidth = double.infinity }) {
Ian Hickson's avatar
Ian Hickson committed
539 540
    assert(text != null, 'TextPainter.text must be set to a non-null value before using the TextPainter.');
    assert(textDirection != null, 'TextPainter.textDirection must be set to a non-null value before using the TextPainter.');
541
    if (!_needsLayout && minWidth == _lastMinWidth && maxWidth == _lastMaxWidth)
542 543
      return;
    _needsLayout = false;
544
    if (_paragraph == null) {
545
      final ui.ParagraphBuilder builder = ui.ParagraphBuilder(_createParagraphStyle());
546 547
      _text.build(builder, textScaleFactor: textScaleFactor, dimensions: _placeholderDimensions);
      _inlinePlaceholderScales = builder.placeholderScales;
548
      _paragraph = builder.build();
549
    }
550 551
    _lastMinWidth = minWidth;
    _lastMaxWidth = maxWidth;
552
    _paragraph.layout(ui.ParagraphConstraints(width: maxWidth));
553
    if (minWidth != maxWidth) {
554
      final double newWidth = maxIntrinsicWidth.clamp(minWidth, maxWidth) as double;
555
      if (newWidth != width) {
556
        _paragraph.layout(ui.ParagraphConstraints(width: newWidth));
557
      }
558
    }
559
    _inlinePlaceholderBoxes = _paragraph.getBoxesForPlaceholders();
560 561
  }

Florian Loitsch's avatar
Florian Loitsch committed
562
  /// Paints the text onto the given canvas at the given offset.
563
  ///
564
  /// Valid only after [layout] has been called.
565 566 567 568 569 570 571 572 573
  ///
  /// If you cannot see the text being painted, check that your text color does
  /// not conflict with the background on which you are drawing. The default
  /// text color is white (to contrast with the default black background color),
  /// so if you are writing an application with a white background, the text
  /// will not be visible by default.
  ///
  /// To set the text style, specify a [TextStyle] when creating the [TextSpan]
  /// that you pass to the [TextPainter] constructor or to the [text] property.
574
  void paint(Canvas canvas, Offset offset) {
575 576
    assert(() {
      if (_needsLayout) {
577
        throw FlutterError(
578 579 580 581 582
          'TextPainter.paint called when text geometry was not yet calculated.\n'
          'Please call layout() before paint() to position the text before painting it.'
        );
      }
      return true;
583
    }());
Adam Barth's avatar
Adam Barth committed
584
    canvas.drawParagraph(_paragraph, offset);
585
  }
586

587 588
  // Complex glyphs can be represented by two or more UTF16 codepoints. This
  // checks if the value represents a UTF16 glyph by itself or is a 'surrogate'.
589 590 591 592
  bool _isUtf16Surrogate(int value) {
    return value & 0xF800 == 0xD800;
  }

593
  /// Returns the closest offset after `offset` at which the input cursor can be
594 595 596 597 598
  /// positioned.
  int getOffsetAfter(int offset) {
    final int nextCodeUnit = _text.codeUnitAt(offset);
    if (nextCodeUnit == null)
      return null;
599
    // TODO(goderbauer): doesn't handle extended grapheme clusters with more than one Unicode scalar value (https://github.com/flutter/flutter/issues/13404).
600 601 602
    return _isUtf16Surrogate(nextCodeUnit) ? offset + 2 : offset + 1;
  }

603
  /// Returns the closest offset before `offset` at which the input cursor can
604 605 606 607 608
  /// be positioned.
  int getOffsetBefore(int offset) {
    final int prevCodeUnit = _text.codeUnitAt(offset - 1);
    if (prevCodeUnit == null)
      return null;
609
    // TODO(goderbauer): doesn't handle extended grapheme clusters with more than one Unicode scalar value (https://github.com/flutter/flutter/issues/13404).
610 611 612
    return _isUtf16Surrogate(prevCodeUnit) ? offset - 2 : offset - 1;
  }

613 614 615
  // Unicode value for a zero width joiner character.
  static const int _zwjUtf16 = 0x200d;

616
  // Get the Rect of the cursor (in logical pixels) based off the near edge
617
  // of the character upstream from the given string offset.
618 619
  // TODO(garyq): Use actual extended grapheme cluster length instead of
  // an increasing cluster length amount to achieve deterministic performance.
620
  Rect _getRectFromUpstream(int offset, Rect caretPrototype) {
621
    final String flattenedText = _text.toPlainText(includePlaceholders: false);
622
    final int prevCodeUnit = _text.codeUnitAt(max(0, offset - 1));
623 624
    if (prevCodeUnit == null)
      return null;
625

626 627 628 629
    // Check for multi-code-unit glyphs such as emojis or zero width joiner
    final bool needsSearch = _isUtf16Surrogate(prevCodeUnit) || _text.codeUnitAt(offset) == _zwjUtf16;
    int graphemeClusterLength = needsSearch ? 2 : 1;
    List<TextBox> boxes = <TextBox>[];
630
    while (boxes.isEmpty && flattenedText != null) {
631 632 633 634 635 636
      final int prevRuneOffset = offset - graphemeClusterLength;
      boxes = _paragraph.getBoxesForRange(prevRuneOffset, offset);
      // When the range does not include a full cluster, no boxes will be returned.
      if (boxes.isEmpty) {
        // When we are at the beginning of the line, a non-surrogate position will
        // return empty boxes. We break and try from downstream instead.
637
        if (!needsSearch) {
638
          break; // Only perform one iteration if no search is required.
639 640
        }
        if (prevRuneOffset < -flattenedText.length) {
641
          break; // Stop iterating when beyond the max length of the text.
642
        }
643 644 645 646 647 648 649
        // Multiply by two to log(n) time cover the entire text span. This allows
        // faster discovery of very long clusters and reduces the possibility
        // of certain large clusters taking much longer than others, which can
        // cause jank.
        graphemeClusterLength *= 2;
        continue;
      }
650
      final TextBox box = boxes.first;
651 652 653 654

      // If the upstream character is a newline, cursor is at start of next line
      const int NEWLINE_CODE_UNIT = 10;
      if (prevCodeUnit == NEWLINE_CODE_UNIT) {
655
        return Rect.fromLTRB(_emptyOffset.dx, box.bottom, _emptyOffset.dx, box.bottom + box.bottom - box.top);
656 657
      }

658 659
      final double caretEnd = box.end;
      final double dx = box.direction == TextDirection.rtl ? caretEnd - caretPrototype.width : caretEnd;
660
      return Rect.fromLTRB(min(dx, _paragraph.width), box.top, min(dx, _paragraph.width), box.bottom);
661 662
    }
    return null;
663 664
  }

665
  // Get the Rect of the cursor (in logical pixels) based off the near edge
666
  // of the character downstream from the given string offset.
667 668
  // TODO(garyq): Use actual extended grapheme cluster length instead of
  // an increasing cluster length amount to achieve deterministic performance.
669
  Rect _getRectFromDownstream(int offset, Rect caretPrototype) {
670
    final String flattenedText = _text.toPlainText(includePlaceholders: false);
671
    // We cap the offset at the final index of the _text.
672
    final int nextCodeUnit = _text.codeUnitAt(min(offset, flattenedText == null ? 0 : flattenedText.length - 1));
673 674
    if (nextCodeUnit == null)
      return null;
675 676 677 678
    // Check for multi-code-unit glyphs such as emojis or zero width joiner
    final bool needsSearch = _isUtf16Surrogate(nextCodeUnit) || nextCodeUnit == _zwjUtf16;
    int graphemeClusterLength = needsSearch ? 2 : 1;
    List<TextBox> boxes = <TextBox>[];
679
    while (boxes.isEmpty && flattenedText != null) {
680 681 682 683 684 685
      final int nextRuneOffset = offset + graphemeClusterLength;
      boxes = _paragraph.getBoxesForRange(offset, nextRuneOffset);
      // When the range does not include a full cluster, no boxes will be returned.
      if (boxes.isEmpty) {
        // When we are at the end of the line, a non-surrogate position will
        // return empty boxes. We break and try from upstream instead.
686
        if (!needsSearch) {
687
          break; // Only perform one iteration if no search is required.
688 689
        }
        if (nextRuneOffset >= flattenedText.length << 1) {
690
          break; // Stop iterating when beyond the max length of the text.
691
        }
692 693 694 695 696 697 698
        // Multiply by two to log(n) time cover the entire text span. This allows
        // faster discovery of very long clusters and reduces the possibility
        // of certain large clusters taking much longer than others, which can
        // cause jank.
        graphemeClusterLength *= 2;
        continue;
      }
699
      final TextBox box = boxes.last;
700 701
      final double caretStart = box.start;
      final double dx = box.direction == TextDirection.rtl ? caretStart - caretPrototype.width : caretStart;
702
      return Rect.fromLTRB(min(dx, _paragraph.width), box.top, min(dx, _paragraph.width), box.bottom);
703 704
    }
    return null;
705 706
  }

707
  Offset get _emptyOffset {
Ian Hickson's avatar
Ian Hickson committed
708 709 710
    assert(!_needsLayout); // implies textDirection is non-null
    assert(textAlign != null);
    switch (textAlign) {
711 712 713
      case TextAlign.left:
        return Offset.zero;
      case TextAlign.right:
714
        return Offset(width, 0.0);
715
      case TextAlign.center:
716
        return Offset(width / 2.0, 0.0);
Ian Hickson's avatar
Ian Hickson committed
717 718 719 720 721
      case TextAlign.justify:
      case TextAlign.start:
        assert(textDirection != null);
        switch (textDirection) {
          case TextDirection.rtl:
722
            return Offset(width, 0.0);
Ian Hickson's avatar
Ian Hickson committed
723 724 725 726 727 728 729 730 731 732
          case TextDirection.ltr:
            return Offset.zero;
        }
        return null;
      case TextAlign.end:
        assert(textDirection != null);
        switch (textDirection) {
          case TextDirection.rtl:
            return Offset.zero;
          case TextDirection.ltr:
733
            return Offset(width, 0.0);
Ian Hickson's avatar
Ian Hickson committed
734 735
        }
        return null;
736 737 738 739
    }
    return null;
  }

740
  /// Returns the offset at which to paint the caret.
741
  ///
742
  /// Valid only after [layout] has been called.
743
  Offset getOffsetForCaret(TextPosition position, Rect caretPrototype) {
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
    _computeCaretMetrics(position, caretPrototype);
    return _caretMetrics.offset;
  }

  /// Returns the tight bounded height of the glyph at the given [position].
  ///
  /// Valid only after [layout] has been called.
  double getFullHeightForCaret(TextPosition position, Rect caretPrototype) {
    _computeCaretMetrics(position, caretPrototype);
    return _caretMetrics.fullHeight;
  }

  // Cached caret metrics. This allows multiple invokes of [getOffsetForCaret] and
  // [getFullHeightForCaret] in a row without performing redundant and expensive
  // get rect calls to the paragraph.
  _CaretMetrics _caretMetrics;

  // Holds the TextPosition and caretPrototype the last caret metrics were
  // computed with. When new values are passed in, we recompute the caret metrics.
Chris Bracken's avatar
Chris Bracken committed
763
  // only as necessary.
764 765 766 767 768 769
  TextPosition _previousCaretPosition;
  Rect _previousCaretPrototype;

  // Checks if the [position] and [caretPrototype] have changed from the cached
  // version and recomputes the metrics required to position the caret.
  void _computeCaretMetrics(TextPosition position, Rect caretPrototype) {
770
    assert(!_needsLayout);
771 772
    if (position == _previousCaretPosition && caretPrototype == _previousCaretPrototype)
      return;
773
    final int offset = position.offset;
Ian Hickson's avatar
Ian Hickson committed
774
    assert(position.affinity != null);
775
    Rect rect;
776
    switch (position.affinity) {
777 778 779 780 781 782 783 784
      case TextAffinity.upstream: {
        rect = _getRectFromUpstream(offset, caretPrototype) ?? _getRectFromDownstream(offset, caretPrototype);
        break;
      }
      case TextAffinity.downstream: {
        rect = _getRectFromDownstream(offset, caretPrototype) ??  _getRectFromUpstream(offset, caretPrototype);
        break;
      }
785
    }
786 787 788 789
    _caretMetrics = _CaretMetrics(
      offset: rect != null ? Offset(rect.left, rect.top) : _emptyOffset,
      fullHeight: rect != null ? rect.bottom - rect.top : null,
    );
790 791 792 793

    // Cache the input parameters to prevent repeat work later.
    _previousCaretPosition = position;
    _previousCaretPrototype = caretPrototype;
794 795 796 797 798 799 800
  }

  /// Returns a list of rects that bound the given selection.
  ///
  /// A given selection might have more than one rect if this text painter
  /// contains bidirectional text because logically contiguous text might not be
  /// visually contiguous.
Ian Hickson's avatar
Ian Hickson committed
801
  List<TextBox> getBoxesForSelection(TextSelection selection) {
802 803 804 805
    assert(!_needsLayout);
    return _paragraph.getBoxesForRange(selection.start, selection.end);
  }

806
  /// Returns the position within the text for the given pixel offset.
807 808 809 810 811
  TextPosition getPositionForOffset(Offset offset) {
    assert(!_needsLayout);
    return _paragraph.getPositionForOffset(offset);
  }

812 813 814 815 816 817 818
  /// Returns the text range of the word at the given offset. Characters not
  /// part of a word, such as spaces, symbols, and punctuation, have word breaks
  /// on both sides. In such cases, this method will return a text range that
  /// contains the given text position.
  ///
  /// Word boundaries are defined more precisely in Unicode Standard Annex #29
  /// <http://www.unicode.org/reports/tr29/#Word_Boundaries>.
819 820
  TextRange getWordBoundary(TextPosition position) {
    assert(!_needsLayout);
821 822 823
    return _paragraph.getWordBoundary(position);
  }

824
  /// Returns the text range of the line at the given offset.
825
  ///
826
  /// The newline, if any, is included in the range.
827 828 829
  TextRange getLineBoundary(TextPosition position) {
    assert(!_needsLayout);
    return _paragraph.getLineBoundary(position);
830
  }
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845

  /// Returns the full list of [LineMetrics] that describe in detail the various
  /// metrics of each laid out line.
  ///
  /// The [LineMetrics] list is presented in the order of the lines they represent.
  /// For example, the first line is in the zeroth index.
  ///
  /// [LineMetrics] contains measurements such as ascent, descent, baseline, and
  /// width for the line as a whole, and may be useful for aligning additional
  /// widgets to a particular line.
  ///
  /// Valid only after [layout] has been called.
  ///
  /// This can potentially return a large amount of data, so it is not recommended
  /// to repeatedly call this. Instead, cache the results. The cached results
846
  /// should be invalidated upon the next successful [layout].
847 848 849 850
  List<ui.LineMetrics> computeLineMetrics() {
    assert(!_needsLayout);
    return _paragraph.computeLineMetrics();
  }
851
}