text_painter.dart 19 KB
Newer Older
1 2 3 4
// Copyright 2015 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.

5
import 'dart:ui' as ui show Paragraph, ParagraphBuilder, ParagraphConstraints, ParagraphStyle;
6

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

11
import 'basic_types.dart';
12
import 'text_span.dart';
13

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

16
/// An object that paints a [TextSpan] tree into a [Canvas].
Hixie's avatar
Hixie committed
17 18 19 20 21 22
///
/// To use a [TextPainter], follow these steps:
///
/// 1. Create a [TextSpan] tree and pass it to the [TextPainter]
///    constructor.
///
23
/// 2. Call [layout] to prepare the paragraph.
Hixie's avatar
Hixie committed
24
///
25
/// 3. Call [paint] as often as desired to paint the paragraph.
Hixie's avatar
Hixie committed
26 27 28 29
///
/// 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.
30 31 32
///
/// 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
33
class TextPainter {
34 35
  /// Creates a text painter that paints the given text.
  ///
Ian Hickson's avatar
Ian Hickson committed
36 37 38 39
  /// 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.
40 41
  ///
  /// The [maxLines] property, if non-null, must be greater than zero.
42 43
  TextPainter({
    TextSpan text,
44
    TextAlign textAlign = TextAlign.start,
Ian Hickson's avatar
Ian Hickson committed
45
    TextDirection textDirection,
46
    double textScaleFactor = 1.0,
47
    int maxLines,
48
    String ellipsis,
49
    Locale locale,
50
  }) : assert(text == null || text.debugAssertIsValid()),
Ian Hickson's avatar
Ian Hickson committed
51
       assert(textAlign != null),
52
       assert(textScaleFactor != null),
53
       assert(maxLines == null || maxLines > 0),
54 55
       _text = text,
       _textAlign = textAlign,
Ian Hickson's avatar
Ian Hickson committed
56
       _textDirection = textDirection,
57 58
       _textScaleFactor = textScaleFactor,
       _maxLines = maxLines,
59 60
       _ellipsis = ellipsis,
       _locale = locale;
61

62
  ui.Paragraph _paragraph;
63
  bool _needsLayout = true;
64

Florian Loitsch's avatar
Florian Loitsch committed
65
  /// The (potentially styled) text to paint.
66 67
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
Ian Hickson's avatar
Ian Hickson committed
68 69
  ///
  /// This and [textDirection] must be non-null before you call [layout].
70
  TextSpan get text => _text;
71
  TextSpan _text;
72
  set text(TextSpan value) {
73
    assert(value == null || value.debugAssertIsValid());
74 75
    if (_text == value)
      return;
76 77
    if (_text?.style != value?.style)
      _layoutTemplate = null;
78
    _text = value;
79 80 81 82 83
    _paragraph = null;
    _needsLayout = true;
  }

  /// How the text should be aligned horizontally.
84 85
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
Ian Hickson's avatar
Ian Hickson committed
86 87
  ///
  /// The [textAlign] property must not be null. It defaults to [TextAlign.start].
88 89
  TextAlign get textAlign => _textAlign;
  TextAlign _textAlign;
90
  set textAlign(TextAlign value) {
Ian Hickson's avatar
Ian Hickson committed
91
    assert(value != null);
92 93 94 95 96
    if (_textAlign == value)
      return;
    _textAlign = value;
    _paragraph = null;
    _needsLayout = true;
97 98
  }

Ian Hickson's avatar
Ian Hickson committed
99 100 101 102 103 104 105 106 107
  /// 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]
108
  /// context, the English phrase will be on the right and the Hebrew phrase on
Ian Hickson's avatar
Ian Hickson committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
  /// 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;
    _paragraph = null;
    _layoutTemplate = null; // Shouldn't really matter, but for strict correctness...
    _needsLayout = true;
  }

125 126 127 128
  /// 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.
129 130
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
131 132 133 134 135 136 137 138
  double get textScaleFactor => _textScaleFactor;
  double _textScaleFactor;
  set textScaleFactor(double value) {
    assert(value != null);
    if (_textScaleFactor == value)
      return;
    _textScaleFactor = value;
    _paragraph = null;
139
    _layoutTemplate = null;
140 141 142
    _needsLayout = true;
  }

143
  /// The string used to ellipsize overflowing text. Setting this to a non-empty
144
  /// string will cause this string to be substituted for the remaining text
145 146 147 148 149 150 151
  /// 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].
152 153
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
154 155 156 157 158
  ///
  /// 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 (…).
159 160 161 162 163 164 165 166 167 168 169
  String get ellipsis => _ellipsis;
  String _ellipsis;
  set ellipsis(String value) {
    assert(value == null || value.isNotEmpty);
    if (_ellipsis == value)
      return;
    _ellipsis = value;
    _paragraph = null;
    _needsLayout = true;
  }

170
  /// The locale used to select region-specific glyphs.
171 172 173
  Locale get locale => _locale;
  Locale _locale;
  set locale(Locale value) {
174 175 176 177 178 179 180
    if (_locale == value)
      return;
    _locale = value;
    _paragraph = null;
    _needsLayout = true;
  }

181 182
  /// An optional maximum number of lines for the text to span, wrapping if
  /// necessary.
183
  ///
184 185
  /// If the text exceeds the given number of lines, it is truncated such that
  /// subsequent lines are dropped.
186 187
  ///
  /// After this is set, you must call [layout] before the next call to [paint].
188 189
  int get maxLines => _maxLines;
  int _maxLines;
190
  /// The value may be null. If it is not null, then it must be greater than zero.
191
  set maxLines(int value) {
192
    assert(value == null || value > 0);
193 194 195 196 197 198 199 200
    if (_maxLines == value)
      return;
    _maxLines = value;
    _paragraph = null;
    _needsLayout = true;
  }

  ui.Paragraph _layoutTemplate;
201

Ian Hickson's avatar
Ian Hickson committed
202 203 204 205 206
  ui.ParagraphStyle _createParagraphStyle([TextDirection defaultTextDirection]) {
    // 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.');
207 208
    return _text.style?.getParagraphStyle(
      textAlign: textAlign,
Ian Hickson's avatar
Ian Hickson committed
209
      textDirection: textDirection ?? defaultTextDirection,
210 211 212
      textScaleFactor: textScaleFactor,
      maxLines: _maxLines,
      ellipsis: _ellipsis,
213
      locale: _locale,
214 215
    ) ?? new ui.ParagraphStyle(
      textAlign: textAlign,
Ian Hickson's avatar
Ian Hickson committed
216
      textDirection: textDirection ?? defaultTextDirection,
217 218
      maxLines: maxLines,
      ellipsis: ellipsis,
219
      locale: locale,
220 221 222
    );
  }

223
  /// The height of a space in [text] in logical pixels.
224
  ///
225 226
  /// 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
227
  /// relative a typical line of text.
228 229
  ///
  /// Obtaining this value does not require calling [layout].
Ian Hickson's avatar
Ian Hickson committed
230 231 232 233 234
  ///
  /// 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).
235 236
  double get preferredLineHeight {
    if (_layoutTemplate == null) {
Ian Hickson's avatar
Ian Hickson committed
237 238
      final ui.ParagraphBuilder builder = new ui.ParagraphBuilder(
        _createParagraphStyle(TextDirection.rtl),
239
      ); // direction doesn't matter, text is just a space
Ian Hickson's avatar
Ian Hickson committed
240
      if (text?.style != null)
241
        builder.pushStyle(text.style.getTextStyle(textScaleFactor: textScaleFactor));
242
      builder.addText(' ');
243
      _layoutTemplate = builder.build()
244
        ..layout(new ui.ParagraphConstraints(width: double.infinity));
245 246 247
    }
    return _layoutTemplate.height;
  }
248

249 250 251 252 253 254 255 256 257 258 259
  // 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();
  }

260 261
  /// The width at which decreasing the width of the text would prevent it from
  /// painting itself completely within its bounds.
262
  ///
263
  /// Valid only after [layout] has been called.
264
  double get minIntrinsicWidth {
265 266 267 268
    assert(!_needsLayout);
    return _applyFloatingPointHack(_paragraph.minIntrinsicWidth);
  }

Florian Loitsch's avatar
Florian Loitsch committed
269
  /// The width at which increasing the width of the text no longer decreases the height.
270
  ///
271
  /// Valid only after [layout] has been called.
272
  double get maxIntrinsicWidth {
273 274 275 276
    assert(!_needsLayout);
    return _applyFloatingPointHack(_paragraph.maxIntrinsicWidth);
  }

277 278
  /// The horizontal space required to paint this text.
  ///
279
  /// Valid only after [layout] has been called.
280 281 282 283 284
  double get width {
    assert(!_needsLayout);
    return _applyFloatingPointHack(_paragraph.width);
  }

285 286
  /// The vertical space required to paint this text.
  ///
287
  /// Valid only after [layout] has been called.
288 289 290 291 292
  double get height {
    assert(!_needsLayout);
    return _applyFloatingPointHack(_paragraph.height);
  }

293 294
  /// The amount of space required to paint this text.
  ///
295
  /// Valid only after [layout] has been called.
296
  Size get size {
297
    assert(!_needsLayout);
298
    return new Size(width, height);
299 300
  }

301 302
  /// Returns the distance from the top of the text to the first baseline of the
  /// given type.
303
  ///
304
  /// Valid only after [layout] has been called.
305 306
  double computeDistanceToActualBaseline(TextBaseline baseline) {
    assert(!_needsLayout);
Ian Hickson's avatar
Ian Hickson committed
307
    assert(baseline != null);
308 309
    switch (baseline) {
      case TextBaseline.alphabetic:
310
        return _paragraph.alphabeticBaseline;
311
      case TextBaseline.ideographic:
312
        return _paragraph.ideographicBaseline;
313
    }
pq's avatar
pq committed
314
    return null;
315 316
  }

317 318 319 320 321
  /// 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.
322
  ///
323 324 325 326 327
  /// 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.
328 329 330 331 332
  bool get didExceedMaxLines {
    assert(!_needsLayout);
    return _paragraph.didExceedMaxLines;
  }

333 334
  double _lastMinWidth;
  double _lastMaxWidth;
335

Florian Loitsch's avatar
Florian Loitsch committed
336
  /// Computes the visual position of the glyphs for painting the text.
337
  ///
338
  /// The text will layout with a width that's as close to its max intrinsic
Ian Hickson's avatar
Ian Hickson committed
339 340 341 342 343
  /// 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.
344
  void layout({ double minWidth = 0.0, double maxWidth = double.infinity }) {
Ian Hickson's avatar
Ian Hickson committed
345 346
    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.');
347
    if (!_needsLayout && minWidth == _lastMinWidth && maxWidth == _lastMaxWidth)
348 349
      return;
    _needsLayout = false;
350
    if (_paragraph == null) {
351
      final ui.ParagraphBuilder builder = new ui.ParagraphBuilder(_createParagraphStyle());
352 353
      _text.build(builder, textScaleFactor: textScaleFactor);
      _paragraph = builder.build();
354
    }
355 356 357 358 359 360 361 362
    _lastMinWidth = minWidth;
    _lastMaxWidth = maxWidth;
    _paragraph.layout(new ui.ParagraphConstraints(width: maxWidth));
    if (minWidth != maxWidth) {
      final double newWidth = maxIntrinsicWidth.clamp(minWidth, maxWidth);
      if (newWidth != width)
        _paragraph.layout(new ui.ParagraphConstraints(width: newWidth));
    }
363 364
  }

Florian Loitsch's avatar
Florian Loitsch committed
365
  /// Paints the text onto the given canvas at the given offset.
366
  ///
367
  /// Valid only after [layout] has been called.
368 369 370 371 372 373 374 375 376
  ///
  /// 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.
377
  void paint(Canvas canvas, Offset offset) {
378 379 380 381 382 383 384 385
    assert(() {
      if (_needsLayout) {
        throw new FlutterError(
          '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;
386
    }());
Adam Barth's avatar
Adam Barth committed
387
    canvas.drawParagraph(_paragraph, offset);
388
  }
389

390 391 392 393
  bool _isUtf16Surrogate(int value) {
    return value & 0xF800 == 0xD800;
  }

394
  /// Returns the closest offset after `offset` at which the input cursor can be
395 396 397 398 399
  /// positioned.
  int getOffsetAfter(int offset) {
    final int nextCodeUnit = _text.codeUnitAt(offset);
    if (nextCodeUnit == null)
      return null;
400
    // TODO(goderbauer): doesn't handle extended grapheme clusters with more than one Unicode scalar value (https://github.com/flutter/flutter/issues/13404).
401 402 403 404 405 406 407 408 409
    return _isUtf16Surrogate(nextCodeUnit) ? offset + 2 : offset + 1;
  }

  /// Returns the closest offset before `offset` at which the inout cursor can
  /// be positioned.
  int getOffsetBefore(int offset) {
    final int prevCodeUnit = _text.codeUnitAt(offset - 1);
    if (prevCodeUnit == null)
      return null;
410
    // TODO(goderbauer): doesn't handle extended grapheme clusters with more than one Unicode scalar value (https://github.com/flutter/flutter/issues/13404).
411 412 413
    return _isUtf16Surrogate(prevCodeUnit) ? offset - 2 : offset - 1;
  }

414
  Offset _getOffsetFromUpstream(int offset, Rect caretPrototype) {
415
    final int prevCodeUnit = _text.codeUnitAt(offset - 1);
416 417
    if (prevCodeUnit == null)
      return null;
418
    final int prevRuneOffset = _isUtf16Surrogate(prevCodeUnit) ? offset - 2 : offset - 1;
Ian Hickson's avatar
Ian Hickson committed
419
    final List<TextBox> boxes = _paragraph.getBoxesForRange(prevRuneOffset, offset);
420 421
    if (boxes.isEmpty)
      return null;
Ian Hickson's avatar
Ian Hickson committed
422
    final TextBox box = boxes[0];
423 424
    final double caretEnd = box.end;
    final double dx = box.direction == TextDirection.rtl ? caretEnd : caretEnd - caretPrototype.width;
425
    return new Offset(dx, box.top);
426 427 428
  }

  Offset _getOffsetFromDownstream(int offset, Rect caretPrototype) {
429
    final int nextCodeUnit = _text.codeUnitAt(offset - 1);
430 431
    if (nextCodeUnit == null)
      return null;
432
    final int nextRuneOffset = _isUtf16Surrogate(nextCodeUnit) ? offset + 2 : offset + 1;
Ian Hickson's avatar
Ian Hickson committed
433
    final List<TextBox> boxes = _paragraph.getBoxesForRange(offset, nextRuneOffset);
434 435
    if (boxes.isEmpty)
      return null;
Ian Hickson's avatar
Ian Hickson committed
436
    final TextBox box = boxes[0];
437 438
    final double caretStart = box.start;
    final double dx = box.direction == TextDirection.rtl ? caretStart - caretPrototype.width : caretStart;
439
    return new Offset(dx, box.top);
440 441
  }

442
  Offset get _emptyOffset {
Ian Hickson's avatar
Ian Hickson committed
443 444 445
    assert(!_needsLayout); // implies textDirection is non-null
    assert(textAlign != null);
    switch (textAlign) {
446 447 448 449 450 451
      case TextAlign.left:
        return Offset.zero;
      case TextAlign.right:
        return new Offset(width, 0.0);
      case TextAlign.center:
        return new Offset(width / 2.0, 0.0);
Ian Hickson's avatar
Ian Hickson committed
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
      case TextAlign.justify:
      case TextAlign.start:
        assert(textDirection != null);
        switch (textDirection) {
          case TextDirection.rtl:
            return new Offset(width, 0.0);
          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:
            return new Offset(width, 0.0);
        }
        return null;
471 472 473 474
    }
    return null;
  }

475
  /// Returns the offset at which to paint the caret.
476
  ///
477
  /// Valid only after [layout] has been called.
478 479
  Offset getOffsetForCaret(TextPosition position, Rect caretPrototype) {
    assert(!_needsLayout);
480
    final int offset = position.offset;
Ian Hickson's avatar
Ian Hickson committed
481
    assert(position.affinity != null);
482 483 484 485
    switch (position.affinity) {
      case TextAffinity.upstream:
        return _getOffsetFromUpstream(offset, caretPrototype)
            ?? _getOffsetFromDownstream(offset, caretPrototype)
486
            ?? _emptyOffset;
487 488 489
      case TextAffinity.downstream:
        return _getOffsetFromDownstream(offset, caretPrototype)
            ?? _getOffsetFromUpstream(offset, caretPrototype)
490
            ?? _emptyOffset;
491
    }
pq's avatar
pq committed
492
    return null;
493 494 495 496 497 498 499
  }

  /// 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
500
  List<TextBox> getBoxesForSelection(TextSelection selection) {
501 502 503 504
    assert(!_needsLayout);
    return _paragraph.getBoxesForRange(selection.start, selection.end);
  }

505
  /// Returns the position within the text for the given pixel offset.
506 507 508 509 510
  TextPosition getPositionForOffset(Offset offset) {
    assert(!_needsLayout);
    return _paragraph.getPositionForOffset(offset);
  }

511 512 513 514 515 516 517
  /// 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>.
518 519
  TextRange getWordBoundary(TextPosition position) {
    assert(!_needsLayout);
520
    final List<int> indices = _paragraph.getWordBoundary(position.offset);
521 522
    return new TextRange(start: indices[0], end: indices[1]);
  }
523
}