text_painter.dart 35.5 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, TextHeightBehavior, BoxHeightStyle, BoxWidthStyle;
7

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

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

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

19 20 21 22 23
// The default font size if none is specified. This should be kept in
// sync with the default values in text_style.dart, as well as the
// defaults set in the engine (eg, LibTxt's text_style.h, paragraph_style.h).
const double _kDefaultFontSize = 14.0;

24 25 26 27 28 29 30 31 32 33 34 35 36
/// 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.
37
///  * [RichText], a text widget that supports text inline widgets.
38 39 40 41 42 43 44
@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({
45 46
    required this.size,
    required this.alignment,
47 48 49 50 51
    this.baseline,
    this.baselineOffset,
  }) : assert(size != null),
       assert(alignment != null);

52 53 54
  /// A constant representing an empty placeholder.
  static const PlaceholderDimensions empty = PlaceholderDimensions(size: Size.zero, alignment: ui.PlaceholderAlignment.bottom);

55 56 57 58 59 60 61 62
  /// 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
63 64 65
  ///    [dart:ui.PlaceholderAlignment.baseline],
  ///    [dart:ui.PlaceholderAlignment.aboveBaseline],
  ///    or [dart:ui.PlaceholderAlignment.belowBaseline].
66 67 68 69 70 71 72
  ///  * [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].
73
  final double? baselineOffset;
74 75 76 77 78

  /// The [TextBaseline] to align to. Used with:
  ///
  ///  * [ui.PlaceholderAlignment.baseline]
  ///  * [ui.PlaceholderAlignment.aboveBaseline]
79
  ///  * [ui.PlaceholderAlignment.belowBaseline]
80
  ///  * [ui.PlaceholderAlignment.middle]
81
  final TextBaseline? baseline;
82 83 84 85 86 87 88

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

89
/// The different ways of measuring the width of one or more lines of text.
90
///
91
/// See [Text.textWidthBasis], for example.
92
enum TextWidthBasis {
93
  /// multiline text will take up the full width given by the parent. For single
94 95 96 97 98 99 100 101 102 103
  /// 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,
}

104 105 106
/// 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.
107
class _CaretMetrics {
108
  const _CaretMetrics({required this.offset, this.fullHeight});
109 110 111 112 113
  /// 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.
114
  final double? fullHeight;
115 116
}

117
/// An object that paints a [TextSpan] tree into a [Canvas].
Hixie's avatar
Hixie committed
118 119 120 121 122 123
///
/// To use a [TextPainter], follow these steps:
///
/// 1. Create a [TextSpan] tree and pass it to the [TextPainter]
///    constructor.
///
124
/// 2. Call [layout] to prepare the paragraph.
Hixie's avatar
Hixie committed
125
///
126
/// 3. Call [paint] as often as desired to paint the paragraph.
Hixie's avatar
Hixie committed
127 128 129 130
///
/// 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.
131 132 133
///
/// 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
134
class TextPainter {
135 136
  /// Creates a text painter that paints the given text.
  ///
Ian Hickson's avatar
Ian Hickson committed
137 138 139 140
  /// 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.
141 142
  ///
  /// The [maxLines] property, if non-null, must be greater than zero.
143
  TextPainter({
144
    InlineSpan? text,
145
    TextAlign textAlign = TextAlign.start,
146
    TextDirection? textDirection,
147
    double textScaleFactor = 1.0,
148 149 150 151
    int? maxLines,
    String? ellipsis,
    Locale? locale,
    StrutStyle? strutStyle,
152
    TextWidthBasis textWidthBasis = TextWidthBasis.parent,
153
    ui.TextHeightBehavior? textHeightBehavior,
154
  }) : assert(text == null || text.debugAssertIsValid()),
Ian Hickson's avatar
Ian Hickson committed
155
       assert(textAlign != null),
156
       assert(textScaleFactor != null),
157
       assert(maxLines == null || maxLines > 0),
158
       assert(textWidthBasis != null),
159 160
       _text = text,
       _textAlign = textAlign,
Ian Hickson's avatar
Ian Hickson committed
161
       _textDirection = textDirection,
162 163
       _textScaleFactor = textScaleFactor,
       _maxLines = maxLines,
164
       _ellipsis = ellipsis,
165
       _locale = locale,
166
       _strutStyle = strutStyle,
167 168
       _textWidthBasis = textWidthBasis,
       _textHeightBehavior = textHeightBehavior;
169

170
  ui.Paragraph? _paragraph;
171
  bool _needsLayout = true;
172

173 174 175 176 177 178 179 180 181
  /// 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;
182 183
    _previousCaretPosition = null;
    _previousCaretPrototype = null;
184 185
  }

Florian Loitsch's avatar
Florian Loitsch committed
186
  /// The (potentially styled) text to paint.
187 188
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
189
  /// This and [textDirection] must be non-null before you call [layout].
190 191
  ///
  /// The [InlineSpan] this provides is in the form of a tree that may contain
192
  /// multiple instances of [TextSpan]s and [WidgetSpan]s. To obtain a plain text
193 194 195
  /// 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.
196 197 198
  InlineSpan? get text => _text;
  InlineSpan? _text;
  set text(InlineSpan? value) {
199
    assert(value == null || value.debugAssertIsValid());
200 201
    if (_text == value)
      return;
202 203
    if (_text?.style != value?.style)
      _layoutTemplate = null;
204
    _text = value;
205
    markNeedsLayout();
206 207 208
  }

  /// How the text should be aligned horizontally.
209 210
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
Ian Hickson's avatar
Ian Hickson committed
211 212
  ///
  /// The [textAlign] property must not be null. It defaults to [TextAlign.start].
213 214
  TextAlign get textAlign => _textAlign;
  TextAlign _textAlign;
215
  set textAlign(TextAlign value) {
Ian Hickson's avatar
Ian Hickson committed
216
    assert(value != null);
217 218 219
    if (_textAlign == value)
      return;
    _textAlign = value;
220
    markNeedsLayout();
221 222
  }

Ian Hickson's avatar
Ian Hickson committed
223 224 225 226 227 228 229 230 231
  /// 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]
232
  /// context, the English phrase will be on the right and the Hebrew phrase on
Ian Hickson's avatar
Ian Hickson committed
233 234 235 236 237
  /// 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].
238 239 240
  TextDirection? get textDirection => _textDirection;
  TextDirection? _textDirection;
  set textDirection(TextDirection? value) {
Ian Hickson's avatar
Ian Hickson committed
241 242 243
    if (_textDirection == value)
      return;
    _textDirection = value;
244
    markNeedsLayout();
Ian Hickson's avatar
Ian Hickson committed
245 246 247
    _layoutTemplate = null; // Shouldn't really matter, but for strict correctness...
  }

248 249 250 251
  /// 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.
252 253
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
254 255 256 257 258 259 260
  double get textScaleFactor => _textScaleFactor;
  double _textScaleFactor;
  set textScaleFactor(double value) {
    assert(value != null);
    if (_textScaleFactor == value)
      return;
    _textScaleFactor = value;
261
    markNeedsLayout();
262
    _layoutTemplate = null;
263 264
  }

265
  /// The string used to ellipsize overflowing text. Setting this to a non-empty
266
  /// string will cause this string to be substituted for the remaining text
267 268 269 270 271 272 273
  /// 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].
274 275
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
276 277 278 279 280
  ///
  /// 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 (…).
281 282 283
  String? get ellipsis => _ellipsis;
  String? _ellipsis;
  set ellipsis(String? value) {
284 285 286 287
    assert(value == null || value.isNotEmpty);
    if (_ellipsis == value)
      return;
    _ellipsis = value;
288
    markNeedsLayout();
289 290
  }

291
  /// The locale used to select region-specific glyphs.
292 293 294
  Locale? get locale => _locale;
  Locale? _locale;
  set locale(Locale? value) {
295 296 297
    if (_locale == value)
      return;
    _locale = value;
298
    markNeedsLayout();
299 300
  }

301 302
  /// An optional maximum number of lines for the text to span, wrapping if
  /// necessary.
303
  ///
304 305
  /// If the text exceeds the given number of lines, it is truncated such that
  /// subsequent lines are dropped.
306 307
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
308 309
  int? get maxLines => _maxLines;
  int? _maxLines;
310
  /// The value may be null. If it is not null, then it must be greater than zero.
311
  set maxLines(int? value) {
312
    assert(value == null || value > 0);
313 314 315
    if (_maxLines == value)
      return;
    _maxLines = value;
316
    markNeedsLayout();
317 318
  }

319 320 321 322 323 324 325 326
  /// {@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
327
  /// [StrutStyle.fontSize].
328 329 330
  ///
  /// See [StrutStyle] for details.
  /// {@endtemplate}
331 332 333
  StrutStyle? get strutStyle => _strutStyle;
  StrutStyle? _strutStyle;
  set strutStyle(StrutStyle? value) {
334 335 336
    if (_strutStyle == value)
      return;
    _strutStyle = value;
337
    markNeedsLayout();
338 339
  }

340 341 342
  /// {@template flutter.painting.textPainter.textWidthBasis}
  /// Defines how to measure the width of the rendered text.
  /// {@endtemplate}
343 344 345 346 347 348 349
  TextWidthBasis get textWidthBasis => _textWidthBasis;
  TextWidthBasis _textWidthBasis;
  set textWidthBasis(TextWidthBasis value) {
    assert(value != null);
    if (_textWidthBasis == value)
      return;
    _textWidthBasis = value;
350
    markNeedsLayout();
351 352
  }

353
  /// {@macro flutter.dart:ui.textHeightBehavior}
354 355 356
  ui.TextHeightBehavior? get textHeightBehavior => _textHeightBehavior;
  ui.TextHeightBehavior? _textHeightBehavior;
  set textHeightBehavior(ui.TextHeightBehavior? value) {
357 358 359 360 361
    if (_textHeightBehavior == value)
      return;
    _textHeightBehavior = value;
    markNeedsLayout();
  }
362

363
  ui.Paragraph? _layoutTemplate;
364

365 366 367 368 369
  /// 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.
370 371
  List<TextBox>? get inlinePlaceholderBoxes => _inlinePlaceholderBoxes;
  List<TextBox>? _inlinePlaceholderBoxes;
372 373 374 375 376 377 378 379

  /// 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.
380 381
  List<double>? get inlinePlaceholderScales => _inlinePlaceholderScales;
  List<double>? _inlinePlaceholderScales;
382 383 384 385 386 387 388 389 390 391

  /// 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.
392
  void setPlaceholderDimensions(List<PlaceholderDimensions>? value) {
393 394 395 396 397
    if (value == null || value.isEmpty || listEquals(value, _placeholderDimensions)) {
      return;
    }
    assert(() {
      int placeholderCount = 0;
398
      text!.visitChildren((InlineSpan span) {
399 400 401 402 403 404 405 406
        if (span is PlaceholderSpan) {
          placeholderCount += 1;
        }
        return true;
      });
      return placeholderCount;
    }() == value.length);
    _placeholderDimensions = value;
407
    markNeedsLayout();
408
  }
409
  List<PlaceholderDimensions>? _placeholderDimensions;
410

411
  ui.ParagraphStyle _createParagraphStyle([ TextDirection? defaultTextDirection ]) {
Ian Hickson's avatar
Ian Hickson committed
412 413 414 415
    // 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.');
416
    return _text!.style?.getParagraphStyle(
417
      textAlign: textAlign,
Ian Hickson's avatar
Ian Hickson committed
418
      textDirection: textDirection ?? defaultTextDirection,
419 420
      textScaleFactor: textScaleFactor,
      maxLines: _maxLines,
421
      textHeightBehavior: _textHeightBehavior,
422
      ellipsis: _ellipsis,
423
      locale: _locale,
424
      strutStyle: _strutStyle,
425
    ) ?? ui.ParagraphStyle(
426
      textAlign: textAlign,
Ian Hickson's avatar
Ian Hickson committed
427
      textDirection: textDirection ?? defaultTextDirection,
428 429 430 431
      // Use the default font size to multiply by as RichText does not
      // perform inheriting [TextStyle]s and would otherwise
      // fail to apply textScaleFactor.
      fontSize: _kDefaultFontSize * textScaleFactor,
432
      maxLines: maxLines,
433
      textHeightBehavior: _textHeightBehavior,
434
      ellipsis: ellipsis,
435
      locale: locale,
436 437 438
    );
  }

439
  /// The height of a space in [text] in logical pixels.
440
  ///
441 442
  /// 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
443
  /// relative a typical line of text.
444 445
  ///
  /// Obtaining this value does not require calling [layout].
Ian Hickson's avatar
Ian Hickson committed
446 447 448 449 450
  ///
  /// 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).
451 452
  double get preferredLineHeight {
    if (_layoutTemplate == null) {
453
      final ui.ParagraphBuilder builder = ui.ParagraphBuilder(
Ian Hickson's avatar
Ian Hickson committed
454
        _createParagraphStyle(TextDirection.rtl),
455
      ); // direction doesn't matter, text is just a space
Ian Hickson's avatar
Ian Hickson committed
456
      if (text?.style != null)
457
        builder.pushStyle(text!.style!.getTextStyle(textScaleFactor: textScaleFactor));
458
      builder.addText(' ');
459
      _layoutTemplate = builder.build()
460
        ..layout(const ui.ParagraphConstraints(width: double.infinity));
461
    }
462
    return _layoutTemplate!.height;
463
  }
464

465 466 467 468 469 470 471 472 473 474 475
  // 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();
  }

476 477
  /// The width at which decreasing the width of the text would prevent it from
  /// painting itself completely within its bounds.
478
  ///
479
  /// Valid only after [layout] has been called.
480
  double get minIntrinsicWidth {
481
    assert(!_needsLayout);
482
    return _applyFloatingPointHack(_paragraph!.minIntrinsicWidth);
483 484
  }

Florian Loitsch's avatar
Florian Loitsch committed
485
  /// The width at which increasing the width of the text no longer decreases the height.
486
  ///
487
  /// Valid only after [layout] has been called.
488
  double get maxIntrinsicWidth {
489
    assert(!_needsLayout);
490
    return _applyFloatingPointHack(_paragraph!.maxIntrinsicWidth);
491 492
  }

493 494
  /// The horizontal space required to paint this text.
  ///
495
  /// Valid only after [layout] has been called.
496 497
  double get width {
    assert(!_needsLayout);
498
    return _applyFloatingPointHack(
499
      textWidthBasis == TextWidthBasis.longestLine ? _paragraph!.longestLine : _paragraph!.width,
500
    );
501 502
  }

503 504
  /// The vertical space required to paint this text.
  ///
505
  /// Valid only after [layout] has been called.
506 507
  double get height {
    assert(!_needsLayout);
508
    return _applyFloatingPointHack(_paragraph!.height);
509 510
  }

511 512
  /// The amount of space required to paint this text.
  ///
513
  /// Valid only after [layout] has been called.
514
  Size get size {
515
    assert(!_needsLayout);
516
    return Size(width, height);
517 518
  }

519 520
  /// Returns the distance from the top of the text to the first baseline of the
  /// given type.
521
  ///
522
  /// Valid only after [layout] has been called.
523 524
  double computeDistanceToActualBaseline(TextBaseline baseline) {
    assert(!_needsLayout);
Ian Hickson's avatar
Ian Hickson committed
525
    assert(baseline != null);
526 527
    switch (baseline) {
      case TextBaseline.alphabetic:
528
        return _paragraph!.alphabeticBaseline;
529
      case TextBaseline.ideographic:
530
        return _paragraph!.ideographicBaseline;
531 532 533
    }
  }

534 535 536 537 538
  /// 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.
539
  ///
540 541 542 543 544
  /// 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.
545 546
  bool get didExceedMaxLines {
    assert(!_needsLayout);
547
    return _paragraph!.didExceedMaxLines;
548 549
  }

550 551
  double? _lastMinWidth;
  double? _lastMaxWidth;
552

Florian Loitsch's avatar
Florian Loitsch committed
553
  /// Computes the visual position of the glyphs for painting the text.
554
  ///
555
  /// The text will layout with a width that's as close to its max intrinsic
Ian Hickson's avatar
Ian Hickson committed
556 557 558 559 560
  /// 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.
561
  void layout({ double minWidth = 0.0, double maxWidth = double.infinity }) {
Ian Hickson's avatar
Ian Hickson committed
562 563
    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.');
564
    if (!_needsLayout && minWidth == _lastMinWidth && maxWidth == _lastMaxWidth)
565 566
      return;
    _needsLayout = false;
567
    if (_paragraph == null) {
568
      final ui.ParagraphBuilder builder = ui.ParagraphBuilder(_createParagraphStyle());
569
      _text!.build(builder, textScaleFactor: textScaleFactor, dimensions: _placeholderDimensions);
570
      _inlinePlaceholderScales = builder.placeholderScales;
571
      _paragraph = builder.build();
572
    }
573 574
    _lastMinWidth = minWidth;
    _lastMaxWidth = maxWidth;
575 576 577
    // A change in layout invalidates the cached caret metrics as well.
    _previousCaretPosition = null;
    _previousCaretPrototype = null;
578
    _paragraph!.layout(ui.ParagraphConstraints(width: maxWidth));
579
    if (minWidth != maxWidth) {
580 581 582 583 584 585 586 587
      double newWidth;
      switch (textWidthBasis) {
        case TextWidthBasis.longestLine:
          // The parent widget expects the paragraph to be exactly
          // `TextPainter.width` wide, if that value satisfies the constraints
          // it gave to the TextPainter. So when `textWidthBasis` is longestLine,
          // the paragraph's width needs to be as close to the width of its
          // longest line as possible.
588
          newWidth = _applyFloatingPointHack(_paragraph!.longestLine);
589 590 591 592 593
          break;
        case TextWidthBasis.parent:
          newWidth = maxIntrinsicWidth;
          break;
      }
594
      newWidth = newWidth.clamp(minWidth, maxWidth);
595 596
      if (newWidth != _applyFloatingPointHack(_paragraph!.width)) {
        _paragraph!.layout(ui.ParagraphConstraints(width: newWidth));
597
      }
598
    }
599
    _inlinePlaceholderBoxes = _paragraph!.getBoxesForPlaceholders();
600 601
  }

Florian Loitsch's avatar
Florian Loitsch committed
602
  /// Paints the text onto the given canvas at the given offset.
603
  ///
604
  /// Valid only after [layout] has been called.
605 606 607 608 609 610 611 612 613
  ///
  /// 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.
614
  void paint(Canvas canvas, Offset offset) {
615 616
    assert(() {
      if (_needsLayout) {
617
        throw FlutterError(
618 619 620 621 622
          '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;
623
    }());
624
    canvas.drawParagraph(_paragraph!, offset);
625
  }
626

627 628 629 630 631
  // Returns true iff the given value is a valid UTF-16 surrogate. The value
  // must be a UTF-16 code unit, meaning it must be in the range 0x0000-0xFFFF.
  //
  // See also:
  //   * https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF
632
  static bool _isUtf16Surrogate(int value) {
633 634 635
    return value & 0xF800 == 0xD800;
  }

636 637 638 639
  // Checks if the glyph is either [Unicode.RLM] or [Unicode.LRM]. These values take
  // up zero space and do not have valid bounding boxes around them.
  //
  // We do not directly use the [Unicode] constants since they are strings.
640
  static bool _isUnicodeDirectionality(int value) {
641 642 643
    return value == 0x200F || value == 0x200E;
  }

644
  /// Returns the closest offset after `offset` at which the input cursor can be
645
  /// positioned.
646 647
  int? getOffsetAfter(int offset) {
    final int? nextCodeUnit = _text!.codeUnitAt(offset);
648 649
    if (nextCodeUnit == null)
      return null;
650
    // TODO(goderbauer): doesn't handle extended grapheme clusters with more than one Unicode scalar value (https://github.com/flutter/flutter/issues/13404).
651 652 653
    return _isUtf16Surrogate(nextCodeUnit) ? offset + 2 : offset + 1;
  }

654
  /// Returns the closest offset before `offset` at which the input cursor can
655
  /// be positioned.
656 657
  int? getOffsetBefore(int offset) {
    final int? prevCodeUnit = _text!.codeUnitAt(offset - 1);
658 659
    if (prevCodeUnit == null)
      return null;
660
    // TODO(goderbauer): doesn't handle extended grapheme clusters with more than one Unicode scalar value (https://github.com/flutter/flutter/issues/13404).
661 662 663
    return _isUtf16Surrogate(prevCodeUnit) ? offset - 2 : offset - 1;
  }

664 665 666
  // Unicode value for a zero width joiner character.
  static const int _zwjUtf16 = 0x200d;

667
  // Get the Rect of the cursor (in logical pixels) based off the near edge
668
  // of the character upstream from the given string offset.
669 670 671
  Rect? _getRectFromUpstream(int offset, Rect caretPrototype) {
    final String flattenedText = _text!.toPlainText(includePlaceholders: false);
    final int? prevCodeUnit = _text!.codeUnitAt(max(0, offset - 1));
672 673
    if (prevCodeUnit == null)
      return null;
674

675
    // Check for multi-code-unit glyphs such as emojis or zero width joiner.
676
    final bool needsSearch = _isUtf16Surrogate(prevCodeUnit) || _text!.codeUnitAt(offset) == _zwjUtf16 || _isUnicodeDirectionality(prevCodeUnit);
677 678
    int graphemeClusterLength = needsSearch ? 2 : 1;
    List<TextBox> boxes = <TextBox>[];
679
    while (boxes.isEmpty) {
680
      final int prevRuneOffset = offset - graphemeClusterLength;
681 682
      // Use BoxHeightStyle.strut to ensure that the caret's height fits within
      // the line's height and is consistent throughout the line.
683
      boxes = _paragraph!.getBoxesForRange(prevRuneOffset, offset, boxHeightStyle: ui.BoxHeightStyle.strut);
684 685 686 687
      // 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.
688
        if (!needsSearch) {
689
          break; // Only perform one iteration if no search is required.
690 691
        }
        if (prevRuneOffset < -flattenedText.length) {
692
          break; // Stop iterating when beyond the max length of the text.
693
        }
694 695 696 697 698 699 700
        // 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;
      }
701
      final TextBox box = boxes.first;
702 703 704 705

      // 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) {
706
        return Rect.fromLTRB(_emptyOffset.dx, box.bottom, _emptyOffset.dx, box.bottom + box.bottom - box.top);
707 708
      }

709 710
      final double caretEnd = box.end;
      final double dx = box.direction == TextDirection.rtl ? caretEnd - caretPrototype.width : caretEnd;
711
      return Rect.fromLTRB(min(dx, _paragraph!.width), box.top, min(dx, _paragraph!.width), box.bottom);
712 713
    }
    return null;
714 715
  }

716
  // Get the Rect of the cursor (in logical pixels) based off the near edge
717
  // of the character downstream from the given string offset.
718 719
  Rect? _getRectFromDownstream(int offset, Rect caretPrototype) {
    final String flattenedText = _text!.toPlainText(includePlaceholders: false);
720
    // We cap the offset at the final index of the _text.
721
    final int? nextCodeUnit = _text!.codeUnitAt(min(offset, flattenedText.length - 1));
722 723
    if (nextCodeUnit == null)
      return null;
724
    // Check for multi-code-unit glyphs such as emojis or zero width joiner
725
    final bool needsSearch = _isUtf16Surrogate(nextCodeUnit) || nextCodeUnit == _zwjUtf16 || _isUnicodeDirectionality(nextCodeUnit);
726 727
    int graphemeClusterLength = needsSearch ? 2 : 1;
    List<TextBox> boxes = <TextBox>[];
728
    while (boxes.isEmpty) {
729
      final int nextRuneOffset = offset + graphemeClusterLength;
730 731
      // Use BoxHeightStyle.strut to ensure that the caret's height fits within
      // the line's height and is consistent throughout the line.
732
      boxes = _paragraph!.getBoxesForRange(offset, nextRuneOffset, boxHeightStyle: ui.BoxHeightStyle.strut);
733 734 735 736
      // 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.
737
        if (!needsSearch) {
738
          break; // Only perform one iteration if no search is required.
739 740
        }
        if (nextRuneOffset >= flattenedText.length << 1) {
741
          break; // Stop iterating when beyond the max length of the text.
742
        }
743 744 745 746 747 748 749
        // 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;
      }
750
      final TextBox box = boxes.last;
751 752
      final double caretStart = box.start;
      final double dx = box.direction == TextDirection.rtl ? caretStart - caretPrototype.width : caretStart;
753
      return Rect.fromLTRB(min(dx, _paragraph!.width), box.top, min(dx, _paragraph!.width), box.bottom);
754 755
    }
    return null;
756 757
  }

758
  Offset get _emptyOffset {
Ian Hickson's avatar
Ian Hickson committed
759 760 761
    assert(!_needsLayout); // implies textDirection is non-null
    assert(textAlign != null);
    switch (textAlign) {
762 763 764
      case TextAlign.left:
        return Offset.zero;
      case TextAlign.right:
765
        return Offset(width, 0.0);
766
      case TextAlign.center:
767
        return Offset(width / 2.0, 0.0);
Ian Hickson's avatar
Ian Hickson committed
768 769 770
      case TextAlign.justify:
      case TextAlign.start:
        assert(textDirection != null);
771
        switch (textDirection!) {
Ian Hickson's avatar
Ian Hickson committed
772
          case TextDirection.rtl:
773
            return Offset(width, 0.0);
Ian Hickson's avatar
Ian Hickson committed
774 775 776 777 778
          case TextDirection.ltr:
            return Offset.zero;
        }
      case TextAlign.end:
        assert(textDirection != null);
779
        switch (textDirection!) {
Ian Hickson's avatar
Ian Hickson committed
780 781 782
          case TextDirection.rtl:
            return Offset.zero;
          case TextDirection.ltr:
783
            return Offset(width, 0.0);
Ian Hickson's avatar
Ian Hickson committed
784
        }
785 786 787
    }
  }

788
  /// Returns the offset at which to paint the caret.
789
  ///
790
  /// Valid only after [layout] has been called.
791
  Offset getOffsetForCaret(TextPosition position, Rect caretPrototype) {
792 793 794 795
    _computeCaretMetrics(position, caretPrototype);
    return _caretMetrics.offset;
  }

796 797 798
  /// {@template flutter.painting.textPainter.getFullHeightForCaret}
  /// Returns the strut bounded height of the glyph at the given `position`.
  /// {@endtemplate}
799 800
  ///
  /// Valid only after [layout] has been called.
801
  double? getFullHeightForCaret(TextPosition position, Rect caretPrototype) {
802 803 804 805 806 807 808
    _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.
809
  late _CaretMetrics _caretMetrics;
810 811 812

  // 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
813
  // only as necessary.
814 815
  TextPosition? _previousCaretPosition;
  Rect? _previousCaretPrototype;
816 817 818 819

  // 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) {
820
    assert(!_needsLayout);
821 822
    if (position == _previousCaretPosition && caretPrototype == _previousCaretPrototype)
      return;
823
    final int offset = position.offset;
Ian Hickson's avatar
Ian Hickson committed
824
    assert(position.affinity != null);
825
    Rect? rect;
826
    switch (position.affinity) {
827 828 829 830 831 832 833 834
      case TextAffinity.upstream: {
        rect = _getRectFromUpstream(offset, caretPrototype) ?? _getRectFromDownstream(offset, caretPrototype);
        break;
      }
      case TextAffinity.downstream: {
        rect = _getRectFromDownstream(offset, caretPrototype) ??  _getRectFromUpstream(offset, caretPrototype);
        break;
      }
835
    }
836 837 838 839
    _caretMetrics = _CaretMetrics(
      offset: rect != null ? Offset(rect.left, rect.top) : _emptyOffset,
      fullHeight: rect != null ? rect.bottom - rect.top : null,
    );
840 841 842 843

    // Cache the input parameters to prevent repeat work later.
    _previousCaretPosition = position;
    _previousCaretPrototype = caretPrototype;
844 845 846 847
  }

  /// Returns a list of rects that bound the given selection.
  ///
848 849 850 851 852
  /// The [boxHeightStyle] and [boxWidthStyle] arguments may be used to select
  /// the shape of the [TextBox]s. These properties default to
  /// [ui.BoxHeightStyle.tight] and [ui.BoxWidthStyle.tight] respectively and
  /// must not be null.
  ///
853 854 855
  /// 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.
856 857 858 859 860
  List<TextBox> getBoxesForSelection(
    TextSelection selection, {
    ui.BoxHeightStyle boxHeightStyle = ui.BoxHeightStyle.tight,
    ui.BoxWidthStyle boxWidthStyle = ui.BoxWidthStyle.tight,
  }) {
861
    assert(!_needsLayout);
862 863
    assert(boxHeightStyle != null);
    assert(boxWidthStyle != null);
864
    return _paragraph!.getBoxesForRange(
865 866 867 868 869
      selection.start,
      selection.end,
      boxHeightStyle: boxHeightStyle,
      boxWidthStyle: boxWidthStyle
    );
870 871
  }

872
  /// Returns the position within the text for the given pixel offset.
873 874
  TextPosition getPositionForOffset(Offset offset) {
    assert(!_needsLayout);
875
    return _paragraph!.getPositionForOffset(offset);
876 877
  }

878 879 880 881 882 883 884
  /// 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>.
885 886
  TextRange getWordBoundary(TextPosition position) {
    assert(!_needsLayout);
887
    return _paragraph!.getWordBoundary(position);
888 889
  }

890
  /// Returns the text range of the line at the given offset.
891
  ///
892
  /// The newline, if any, is included in the range.
893 894
  TextRange getLineBoundary(TextPosition position) {
    assert(!_needsLayout);
895
    return _paragraph!.getLineBoundary(position);
896
  }
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911

  /// 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
912
  /// should be invalidated upon the next successful [layout].
913 914
  List<ui.LineMetrics> computeLineMetrics() {
    assert(!_needsLayout);
915
    return _paragraph!.computeLineMetrics();
916
  }
917
}