paragraph.dart 20.9 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 Gradient, Shader, TextBox;
6

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

13

14
import 'box.dart';
15
import 'debug.dart';
16
import 'object.dart';
17

18 19 20 21 22 23 24 25 26 27
/// How overflowing text should be handled.
enum TextOverflow {
  /// Clip the overflowing text to fix its container.
  clip,

  /// Fade the overflowing text to transparent.
  fade,

  /// Use an ellipsis to indicate that the text has overflowed.
  ellipsis,
28 29 30

  /// Render overflowing text outside of its container.
  visible,
31 32
}

33 34
const String _kEllipsis = '\u2026';

35
/// A render object that displays a paragraph of text
36
class RenderParagraph extends RenderBox {
37 38
  /// Creates a paragraph render object.
  ///
Ian Hickson's avatar
Ian Hickson committed
39 40
  /// The [text], [textAlign], [textDirection], [overflow], [softWrap], and
  /// [textScaleFactor] arguments must not be null.
41 42 43
  ///
  /// The [maxLines] property may be null (and indeed defaults to null), but if
  /// it is not null, it must be greater than zero.
44 45
  RenderParagraph(
    TextSpan text, {
46
    TextAlign textAlign = TextAlign.start,
Ian Hickson's avatar
Ian Hickson committed
47
    @required TextDirection textDirection,
48 49 50
    bool softWrap = true,
    TextOverflow overflow = TextOverflow.clip,
    double textScaleFactor = 1.0,
51
    int maxLines,
52
    TextWidthBasis textWidthBasis = TextWidthBasis.parent,
53
    Locale locale,
54
    StrutStyle strutStyle,
55 56
  }) : assert(text != null),
       assert(text.debugAssertIsValid()),
Ian Hickson's avatar
Ian Hickson committed
57 58
       assert(textAlign != null),
       assert(textDirection != null),
59 60 61
       assert(softWrap != null),
       assert(overflow != null),
       assert(textScaleFactor != null),
62
       assert(maxLines == null || maxLines > 0),
63
       assert(textWidthBasis != null),
64
       _softWrap = softWrap,
65
       _overflow = overflow,
66
       _textPainter = TextPainter(
67 68
         text: text,
         textAlign: textAlign,
Ian Hickson's avatar
Ian Hickson committed
69
         textDirection: textDirection,
70 71 72
         textScaleFactor: textScaleFactor,
         maxLines: maxLines,
         ellipsis: overflow == TextOverflow.ellipsis ? _kEllipsis : null,
73
         locale: locale,
74
         strutStyle: strutStyle,
75
         textWidthBasis: textWidthBasis,
76
       );
77

78
  final TextPainter _textPainter;
79

80
  /// The text to display
81
  TextSpan get text => _textPainter.text;
82
  set text(TextSpan value) {
83
    assert(value != null);
84 85 86 87 88 89 90
    switch (_textPainter.text.compareTo(value)) {
      case RenderComparison.identical:
      case RenderComparison.metadata:
        return;
      case RenderComparison.paint:
        _textPainter.text = value;
        markNeedsPaint();
91
        markNeedsSemanticsUpdate();
92 93 94 95 96 97 98
        break;
      case RenderComparison.layout:
        _textPainter.text = value;
        _overflowShader = null;
        markNeedsLayout();
        break;
    }
99 100
  }

101 102
  /// How the text should be aligned horizontally.
  TextAlign get textAlign => _textPainter.textAlign;
103
  set textAlign(TextAlign value) {
Ian Hickson's avatar
Ian Hickson committed
104
    assert(value != null);
105 106 107 108 109 110
    if (_textPainter.textAlign == value)
      return;
    _textPainter.textAlign = value;
    markNeedsPaint();
  }

Ian Hickson's avatar
Ian Hickson committed
111 112 113 114 115 116 117 118 119
  /// The directionality of the text.
  ///
  /// This decides how the [TextAlign.start], [TextAlign.end], and
  /// [TextAlign.justify] values of [textAlign] are interpreted.
  ///
  /// 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]
120
  /// context, the English phrase will be on the right and the Hebrew phrase on
Ian Hickson's avatar
Ian Hickson committed
121 122 123 124 125 126 127 128 129 130 131 132
  /// its left.
  ///
  /// This must not be null.
  TextDirection get textDirection => _textPainter.textDirection;
  set textDirection(TextDirection value) {
    assert(value != null);
    if (_textPainter.textDirection == value)
      return;
    _textPainter.textDirection = value;
    markNeedsLayout();
  }

133 134
  /// Whether the text should break at soft line breaks.
  ///
135 136 137 138 139
  /// If false, the glyphs in the text will be positioned as if there was
  /// unlimited horizontal space.
  ///
  /// If [softWrap] is false, [overflow] and [textAlign] may have unexpected
  /// effects.
140 141
  bool get softWrap => _softWrap;
  bool _softWrap;
142
  set softWrap(bool value) {
143 144 145 146 147 148 149 150 151 152
    assert(value != null);
    if (_softWrap == value)
      return;
    _softWrap = value;
    markNeedsLayout();
  }

  /// How visual overflow should be handled.
  TextOverflow get overflow => _overflow;
  TextOverflow _overflow;
153
  set overflow(TextOverflow value) {
154 155 156 157
    assert(value != null);
    if (_overflow == value)
      return;
    _overflow = value;
158
    _textPainter.ellipsis = value == TextOverflow.ellipsis ? _kEllipsis : null;
159
    markNeedsLayout();
160 161
  }

162 163 164 165 166 167 168 169 170 171 172 173 174 175
  /// 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.
  double get textScaleFactor => _textPainter.textScaleFactor;
  set textScaleFactor(double value) {
    assert(value != null);
    if (_textPainter.textScaleFactor == value)
      return;
    _textPainter.textScaleFactor = value;
    _overflowShader = null;
    markNeedsLayout();
  }

176 177
  /// An optional maximum number of lines for the text to span, wrapping if necessary.
  /// If the text exceeds the given number of lines, it will be truncated according
178
  /// to [overflow] and [softWrap].
179
  int get maxLines => _textPainter.maxLines;
180
  /// The value may be null. If it is not null, then it must be greater than zero.
181
  set maxLines(int value) {
182
    assert(value == null || value > 0);
183 184 185 186 187 188 189
    if (_textPainter.maxLines == value)
      return;
    _textPainter.maxLines = value;
    _overflowShader = null;
    markNeedsLayout();
  }

190 191 192 193 194 195 196 197 198 199
  /// Used by this paragraph's internal [TextPainter] to select a locale-specific
  /// font.
  ///
  /// In some cases the same Unicode character may be rendered differently depending
  /// on the locale. For example the '骨' character is rendered differently in
  /// the Chinese and Japanese locales. In these cases the [locale] may be used
  /// to select a locale-specific font.
  Locale get locale => _textPainter.locale;
  /// The value may be null.
  set locale(Locale value) {
200 201
    if (_textPainter.locale == value)
      return;
202
    _textPainter.locale = value;
203 204 205 206
    _overflowShader = null;
    markNeedsLayout();
  }

207 208 209 210 211 212 213 214 215 216 217
  /// {@macro flutter.painting.textPainter.strutStyle}
  StrutStyle get strutStyle => _textPainter.strutStyle;
  /// The value may be null.
  set strutStyle(StrutStyle value) {
    if (_textPainter.strutStyle == value)
      return;
    _textPainter.strutStyle = value;
    _overflowShader = null;
    markNeedsLayout();
  }

218 219 220 221 222 223 224 225 226 227 228
  /// {@macro flutter.widgets.basic.TextWidthBasis}
  TextWidthBasis get textWidthBasis => _textPainter.textWidthBasis;
  set textWidthBasis(TextWidthBasis value) {
    assert(value != null);
    if (_textPainter.textWidthBasis == value)
      return;
    _textPainter.textWidthBasis = value;
    _overflowShader = null;
    markNeedsLayout();
  }

229
  void _layoutText({ double minWidth = 0.0, double maxWidth = double.infinity }) {
Ian Hickson's avatar
Ian Hickson committed
230
    final bool widthMatters = softWrap || overflow == TextOverflow.ellipsis;
231
    _textPainter.layout(minWidth: minWidth, maxWidth: widthMatters ? maxWidth : double.infinity);
232 233
  }

234 235 236 237
  void _layoutTextWithConstraints(BoxConstraints constraints) {
    _layoutText(minWidth: constraints.minWidth, maxWidth: constraints.maxWidth);
  }

238
  @override
239
  double computeMinIntrinsicWidth(double height) {
240 241
    _layoutText();
    return _textPainter.minIntrinsicWidth;
242 243
  }

244
  @override
245
  double computeMaxIntrinsicWidth(double height) {
246 247
    _layoutText();
    return _textPainter.maxIntrinsicWidth;
248 249
  }

250
  double _computeIntrinsicHeight(double width) {
251 252
    _layoutText(minWidth: width, maxWidth: width);
    return _textPainter.height;
253 254
  }

255
  @override
256 257
  double computeMinIntrinsicHeight(double width) {
    return _computeIntrinsicHeight(width);
258 259
  }

260
  @override
261 262
  double computeMaxIntrinsicHeight(double width) {
    return _computeIntrinsicHeight(width);
263 264
  }

265
  @override
266
  double computeDistanceToActualBaseline(TextBaseline baseline) {
267
    assert(!debugNeedsLayout);
268 269
    assert(constraints != null);
    assert(constraints.debugAssertIsValid());
270
    _layoutTextWithConstraints(constraints);
271
    return _textPainter.computeDistanceToActualBaseline(baseline);
272 273
  }

274
  @override
275
  bool hitTestSelf(Offset position) => true;
Adam Barth's avatar
Adam Barth committed
276

277
  @override
278
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
279
    assert(debugHandleEvent(event, entry));
280 281
    if (event is! PointerDownEvent)
      return;
282
    _layoutTextWithConstraints(constraints);
283
    final Offset offset = entry.localPosition;
284 285
    final TextPosition position = _textPainter.getPositionForOffset(offset);
    final TextSpan span = _textPainter.text.getSpanForPosition(position);
286 287 288
    span?.recognizer?.addPointer(event);
  }

289
  bool _needsClipping = false;
290 291
  ui.Shader _overflowShader;

292
  /// Whether this paragraph currently has a [dart:ui.Shader] for its overflow
Ian Hickson's avatar
Ian Hickson committed
293
  /// effect.
294 295
  ///
  /// Used to test this object. Not for use in production.
296 297 298
  @visibleForTesting
  bool get debugHasOverflowShader => _overflowShader != null;

299
  @override
300
  void performLayout() {
301
    _layoutTextWithConstraints(constraints);
302 303 304 305 306
    // We grab _textPainter.size and _textPainter.didExceedMaxLines here because
    // assigning to `size` will trigger us to validate our intrinsic sizes,
    // which will change _textPainter's layout because the intrinsic size
    // calculations are destructive. Other _textPainter state will also be
    // affected. See also RenderEditable which has a similar issue.
307
    final Size textSize = _textPainter.size;
308
    final bool textDidExceedMaxLines = _textPainter.didExceedMaxLines;
309
    size = constraints.constrain(textSize);
310

311
    final bool didOverflowHeight = size.height < textSize.height || textDidExceedMaxLines;
312
    final bool didOverflowWidth = size.width < textSize.width;
313 314 315 316 317
    // TODO(abarth): We're only measuring the sizes of the line boxes here. If
    // the glyphs draw outside the line boxes, we might think that there isn't
    // visual overflow when there actually is visual overflow. This can become
    // a problem if we start having horizontal overflow and introduce a clip
    // that affects the actual (but undetected) vertical overflow.
318 319
    final bool hasVisualOverflow = didOverflowWidth || didOverflowHeight;
    if (hasVisualOverflow) {
320
      switch (_overflow) {
321 322 323 324
        case TextOverflow.visible:
          _needsClipping = false;
          _overflowShader = null;
          break;
325
        case TextOverflow.clip:
326
        case TextOverflow.ellipsis:
327
          _needsClipping = true;
328 329 330
          _overflowShader = null;
          break;
        case TextOverflow.fade:
Ian Hickson's avatar
Ian Hickson committed
331
          assert(textDirection != null);
332
          _needsClipping = true;
333 334
          final TextPainter fadeSizePainter = TextPainter(
            text: TextSpan(style: _textPainter.text.style, text: '\u2026'),
Ian Hickson's avatar
Ian Hickson committed
335 336
            textDirection: textDirection,
            textScaleFactor: textScaleFactor,
337
            locale: locale,
338
          )..layout();
339
          if (didOverflowWidth) {
Ian Hickson's avatar
Ian Hickson committed
340 341 342 343 344 345 346 347 348 349 350
            double fadeEnd, fadeStart;
            switch (textDirection) {
              case TextDirection.rtl:
                fadeEnd = 0.0;
                fadeStart = fadeSizePainter.width;
                break;
              case TextDirection.ltr:
                fadeEnd = size.width;
                fadeStart = fadeEnd - fadeSizePainter.width;
                break;
            }
351 352 353
            _overflowShader = ui.Gradient.linear(
              Offset(fadeStart, 0.0),
              Offset(fadeEnd, 0.0),
354
              <Color>[const Color(0xFFFFFFFF), const Color(0x00FFFFFF)],
355 356 357 358
            );
          } else {
            final double fadeEnd = size.height;
            final double fadeStart = fadeEnd - fadeSizePainter.height / 2.0;
359 360 361
            _overflowShader = ui.Gradient.linear(
              Offset(0.0, fadeStart),
              Offset(0.0, fadeEnd),
362
              <Color>[const Color(0xFFFFFFFF), const Color(0x00FFFFFF)],
363 364
            );
          }
365 366 367
          break;
      }
    } else {
368
      _needsClipping = false;
369 370
      _overflowShader = null;
    }
371 372
  }

373
  @override
374
  void paint(PaintingContext context, Offset offset) {
375 376
    // Ideally we could compute the min/max intrinsic width/height with a
    // non-destructive operation. However, currently, computing these values
377
    // will destroy state inside the painter. If that happens, we need to
378 379 380 381
    // get back the correct state by calling _layout again.
    //
    // TODO(abarth): Make computing the min/max intrinsic width/height
    // a non-destructive operation.
382 383 384
    //
    // If you remove this call, make sure that changing the textAlign still
    // works properly.
385
    _layoutTextWithConstraints(constraints);
386
    final Canvas canvas = context.canvas;
387 388 389

    assert(() {
      if (debugRepaintTextRainbowEnabled) {
390
        final Paint paint = Paint()
391 392 393 394
          ..color = debugCurrentRepaintColor.toColor();
        canvas.drawRect(offset & size, paint);
      }
      return true;
395
    }());
396

397
    if (_needsClipping) {
398
      final Rect bounds = offset & size;
399 400 401
      if (_overflowShader != null) {
        // This layer limits what the shader below blends with to be just the text
        // (as opposed to the text and its background).
402
        canvas.saveLayer(bounds, Paint());
403
      } else {
404
        canvas.save();
405
      }
406 407 408
      canvas.clipRect(bounds);
    }
    _textPainter.paint(canvas, offset);
409
    if (_needsClipping) {
410 411
      if (_overflowShader != null) {
        canvas.translate(offset.dx, offset.dy);
412
        final Paint paint = Paint()
413
          ..blendMode = BlendMode.modulate
414
          ..shader = _overflowShader;
415
        canvas.drawRect(Offset.zero & size, paint);
416 417 418
      }
      canvas.restore();
    }
419 420
  }

421 422 423 424
  /// Returns the offset at which to paint the caret.
  ///
  /// Valid only after [layout].
  Offset getOffsetForCaret(TextPosition position, Rect caretPrototype) {
425
    assert(!debugNeedsLayout);
426 427 428 429 430 431 432 433 434 435 436 437
    _layoutTextWithConstraints(constraints);
    return _textPainter.getOffsetForCaret(position, caretPrototype);
  }

  /// 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.
  ///
  /// Valid only after [layout].
  List<ui.TextBox> getBoxesForSelection(TextSelection selection) {
438
    assert(!debugNeedsLayout);
439 440 441 442 443 444 445 446
    _layoutTextWithConstraints(constraints);
    return _textPainter.getBoxesForSelection(selection);
  }

  /// Returns the position within the text for the given pixel offset.
  ///
  /// Valid only after [layout].
  TextPosition getPositionForOffset(Offset offset) {
447
    assert(!debugNeedsLayout);
448 449 450 451 452 453 454 455 456 457 458 459 460 461
    _layoutTextWithConstraints(constraints);
    return _textPainter.getPositionForOffset(offset);
  }

  /// 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>.
  ///
  /// Valid only after [layout].
  TextRange getWordBoundary(TextPosition position) {
462
    assert(!debugNeedsLayout);
463 464 465 466
    _layoutTextWithConstraints(constraints);
    return _textPainter.getWordBoundary(position);
  }

467 468 469 470 471 472 473 474 475 476 477 478 479 480
  /// Returns the size of the text as laid out.
  ///
  /// This can differ from [size] if the text overflowed or if the [constraints]
  /// provided by the parent [RenderObject] forced the layout to be bigger than
  /// necessary for the given [text].
  ///
  /// This returns the [TextPainter.size] of the underlying [TextPainter].
  ///
  /// Valid only after [layout].
  Size get textSize {
    assert(!debugNeedsLayout);
    return _textPainter.size;
  }

481 482 483
  final List<int> _recognizerOffsets = <int>[];
  final List<GestureRecognizer> _recognizers = <GestureRecognizer>[];

484
  @override
485 486
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
487 488 489 490 491
    _recognizerOffsets.clear();
    _recognizers.clear();
    int offset = 0;
    text.visitTextSpan((TextSpan span) {
      if (span.recognizer != null && (span.recognizer is TapGestureRecognizer || span.recognizer is LongPressGestureRecognizer)) {
492
        final int length = span.semanticsLabel?.length ?? span.text.length;
493
        _recognizerOffsets.add(offset);
494
        _recognizerOffsets.add(offset + length);
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
        _recognizers.add(span.recognizer);
      }
      offset += span.text.length;
      return true;
    });
    if (_recognizerOffsets.isNotEmpty) {
      config.explicitChildNodes = true;
      config.isSemanticBoundary = true;
    } else {
      config.label = text.toPlainText();
      config.textDirection = textDirection;
    }
  }

  @override
  void assembleSemanticsNode(SemanticsNode node, SemanticsConfiguration config, Iterable<SemanticsNode> children) {
    assert(_recognizerOffsets.isNotEmpty);
    assert(_recognizerOffsets.length.isEven);
    assert(_recognizers.isNotEmpty);
    assert(children.isEmpty);
    final List<SemanticsNode> newChildren = <SemanticsNode>[];
    final String rawLabel = text.toPlainText();
    int current = 0;
    double order = -1.0;
    TextDirection currentDirection = textDirection;
    Rect currentRect;

    SemanticsConfiguration buildSemanticsConfig(int start, int end) {
      final TextDirection initialDirection = currentDirection;
524
      final TextSelection selection = TextSelection(baseOffset: start, extentOffset: end);
525 526 527 528 529 530 531 532 533 534
      final List<ui.TextBox> rects = getBoxesForSelection(selection);
      Rect rect;
      for (ui.TextBox textBox in rects) {
        rect ??= textBox.toRect();
        rect = rect.expandToInclude(textBox.toRect());
        currentDirection = textBox.direction;
      }
      // round the current rectangle to make this API testable and add some
      // padding so that the accessibility rects do not overlap with the text.
      // TODO(jonahwilliams): implement this for all text accessibility rects.
535
      currentRect = Rect.fromLTRB(
536 537 538 539 540 541
        rect.left.floorToDouble() - 4.0,
        rect.top.floorToDouble() - 4.0,
        rect.right.ceilToDouble() + 4.0,
        rect.bottom.ceilToDouble() + 4.0,
      );
      order += 1;
542 543
      return SemanticsConfiguration()
        ..sortKey = OrdinalSortKey(order)
544 545 546 547 548 549 550 551
        ..textDirection = initialDirection
        ..label = rawLabel.substring(start, end);
    }

    for (int i = 0, j = 0; i < _recognizerOffsets.length; i += 2, j++) {
      final int start = _recognizerOffsets[i];
      final int end = _recognizerOffsets[i + 1];
      if (current != start) {
552
        final SemanticsNode node = SemanticsNode();
553 554 555 556 557
        final SemanticsConfiguration configuration = buildSemanticsConfig(current, start);
        node.updateWith(config: configuration);
        node.rect = currentRect;
        newChildren.add(node);
      }
558
      final SemanticsNode node = SemanticsNode();
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
      final SemanticsConfiguration configuration = buildSemanticsConfig(start, end);
      final GestureRecognizer recognizer = _recognizers[j];
      if (recognizer is TapGestureRecognizer) {
        configuration.onTap = recognizer.onTap;
      } else if (recognizer is LongPressGestureRecognizer) {
        configuration.onLongPress = recognizer.onLongPress;
      } else {
        assert(false);
      }
      node.updateWith(config: configuration);
      node.rect = currentRect;
      newChildren.add(node);
      current = end;
    }
    if (current < rawLabel.length) {
574
      final SemanticsNode node = SemanticsNode();
575 576 577 578 579 580
      final SemanticsConfiguration configuration = buildSemanticsConfig(current, rawLabel.length);
      node.updateWith(config: configuration);
      node.rect = currentRect;
      newChildren.add(node);
    }
    node.updateWith(config: config, childrenInInversePaintOrder: newChildren);
Hixie's avatar
Hixie committed
581
  }
582

583
  @override
584 585
  List<DiagnosticsNode> debugDescribeChildren() {
    return <DiagnosticsNode>[text.toDiagnosticsNode(name: 'text', style: DiagnosticsTreeStyle.transition)];
586
  }
Ian Hickson's avatar
Ian Hickson committed
587 588

  @override
589 590
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
591 592 593 594 595 596 597
    properties.add(EnumProperty<TextAlign>('textAlign', textAlign));
    properties.add(EnumProperty<TextDirection>('textDirection', textDirection));
    properties.add(FlagProperty('softWrap', value: softWrap, ifTrue: 'wrapping at box width', ifFalse: 'no wrapping except at line break characters', showName: true));
    properties.add(EnumProperty<TextOverflow>('overflow', overflow));
    properties.add(DoubleProperty('textScaleFactor', textScaleFactor, defaultValue: 1.0));
    properties.add(DiagnosticsProperty<Locale>('locale', locale, defaultValue: null));
    properties.add(IntProperty('maxLines', maxLines, ifNull: 'unlimited'));
Ian Hickson's avatar
Ian Hickson committed
598
  }
599
}