[web] Clean up legacy Paragraph implementation (flutter/engine#28050)
This commit is contained in:
@@ -16,7 +16,6 @@ import 'keyboard_binding.dart';
|
||||
import 'platform_dispatcher.dart';
|
||||
import 'pointer_binding.dart';
|
||||
import 'semantics.dart';
|
||||
import 'text/measurement.dart';
|
||||
import 'text_editing/text_editing.dart';
|
||||
import 'util.dart';
|
||||
import 'window.dart';
|
||||
@@ -29,11 +28,6 @@ class DomRenderer {
|
||||
|
||||
reset();
|
||||
|
||||
TextMeasurementService.initialize(
|
||||
rulerCacheCapacity: 10,
|
||||
root: _glassPaneShadow!.node,
|
||||
);
|
||||
|
||||
assert(() {
|
||||
_setupHotRestart();
|
||||
return true;
|
||||
|
||||
@@ -15,11 +15,13 @@ import 'paint_service.dart';
|
||||
import 'paragraph.dart';
|
||||
import 'word_breaker.dart';
|
||||
|
||||
const ui.Color _defaultTextColor = ui.Color(0xFFFF0000);
|
||||
|
||||
/// A paragraph made up of a flat list of text spans and placeholders.
|
||||
///
|
||||
/// As opposed to [DomParagraph], a [CanvasParagraph] doesn't use a DOM element
|
||||
/// to represent the structure of its spans and styles. Instead it uses a flat
|
||||
/// list of [ParagraphSpan] objects.
|
||||
/// [CanvasParagraph] doesn't use a DOM element to represent the structure of
|
||||
/// its spans and styles. Instead it uses a flat list of [ParagraphSpan]
|
||||
/// objects.
|
||||
class CanvasParagraph implements EngineParagraph {
|
||||
/// This class is created by the engine, and should not be instantiated
|
||||
/// or extended directly.
|
||||
@@ -574,7 +576,7 @@ class RootStyleNode extends StyleNode {
|
||||
final EngineParagraphStyle paragraphStyle;
|
||||
|
||||
@override
|
||||
final ui.Color _color = defaultTextColor;
|
||||
final ui.Color _color = _defaultTextColor;
|
||||
|
||||
@override
|
||||
ui.TextDecoration? get _decoration => null;
|
||||
|
||||
@@ -12,7 +12,6 @@ import '../assets.dart';
|
||||
import '../browser_detection.dart';
|
||||
import '../util.dart';
|
||||
import 'layout_service.dart';
|
||||
import 'measurement.dart';
|
||||
|
||||
const String ahemFontFamily = 'Ahem';
|
||||
const String ahemFontUrl = 'packages/ui/assets/ahem.ttf';
|
||||
@@ -215,7 +214,6 @@ class FontManager {
|
||||
// There might be paragraph measurements for this new font before it is
|
||||
// loaded. They were measured using fallback font, so we should clear the
|
||||
// cache.
|
||||
TextMeasurementService.clearCache();
|
||||
Spanometer.clearRulersCache();
|
||||
}, onError: (dynamic exception) {
|
||||
// Failures here will throw an html.DomException which confusingly
|
||||
|
||||
@@ -2,22 +2,10 @@
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:html' as html;
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:ui/ui.dart' as ui;
|
||||
|
||||
import '../../engine.dart' show registerHotRestartListener;
|
||||
import '../dom_renderer.dart';
|
||||
import '../util.dart';
|
||||
import '../web_experiments.dart';
|
||||
import '../window.dart';
|
||||
import 'line_break_properties.dart';
|
||||
import 'line_breaker.dart';
|
||||
import 'paragraph.dart';
|
||||
import 'ruler.dart';
|
||||
|
||||
// TODO(yjbanov): this is a hack we use to compute ideographic baseline; this
|
||||
// number is the ratio ideographic/alphabetic for font Ahem,
|
||||
@@ -27,16 +15,6 @@ import 'ruler.dart';
|
||||
// anything as of this writing.
|
||||
const double baselineRatioHack = 1.1662499904632568;
|
||||
|
||||
/// Signature of a function that takes a character and returns true or false.
|
||||
typedef CharPredicate = bool Function(int char);
|
||||
|
||||
bool _newlinePredicate(int char) {
|
||||
final LineCharProperty prop = lineLookup.findForChar(char);
|
||||
return prop == LineCharProperty.BK ||
|
||||
prop == LineCharProperty.LF ||
|
||||
prop == LineCharProperty.CR;
|
||||
}
|
||||
|
||||
/// Hosts ruler DOM elements in a hidden container under a `root` [html.Node].
|
||||
///
|
||||
/// The `root` [html.Node] is optional. Defaults to [domRenderer.glassPaneShadow].
|
||||
@@ -76,606 +54,6 @@ class RulerHost {
|
||||
}
|
||||
}
|
||||
|
||||
/// Manages [ParagraphRuler] instances and caches them per unique
|
||||
/// [ParagraphGeometricStyle].
|
||||
///
|
||||
/// All instances of [ParagraphRuler] should be created through this class.
|
||||
///
|
||||
/// An optional `root` [html.Node] can be passed, under which the DOM required
|
||||
/// to perform measurements will be hosted.
|
||||
class RulerManager extends RulerHost {
|
||||
RulerManager({
|
||||
required this.rulerCacheCapacity,
|
||||
html.Node? root,
|
||||
}) : super(root: root);
|
||||
|
||||
final int rulerCacheCapacity;
|
||||
|
||||
/// The cache of rulers used to measure text.
|
||||
///
|
||||
/// Each ruler is keyed by paragraph style. This allows us to set up the
|
||||
/// ruler's DOM structure once during the very first measurement of a given
|
||||
/// paragraph style. Subsequent measurements could reuse the same ruler and
|
||||
/// only swap the text contents. This minimizes the amount of work a browser
|
||||
/// needs to do when measure many pieces of text with the same style.
|
||||
///
|
||||
/// What makes this cache effective is the fact that a typical application
|
||||
/// only uses a limited number of text styles. Using too many text styles on
|
||||
/// the same screen is considered bad for user experience.
|
||||
Map<ParagraphGeometricStyle, ParagraphRuler> get rulers => _rulers;
|
||||
Map<ParagraphGeometricStyle, ParagraphRuler> _rulers =
|
||||
<ParagraphGeometricStyle, ParagraphRuler>{};
|
||||
|
||||
bool _rulerCacheCleanupScheduled = false;
|
||||
|
||||
void _scheduleRulerCacheCleanup() {
|
||||
if (!_rulerCacheCleanupScheduled) {
|
||||
_rulerCacheCleanupScheduled = true;
|
||||
scheduleMicrotask(() {
|
||||
_rulerCacheCleanupScheduled = false;
|
||||
cleanUpRulerCache();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Evicts all rulers from the cache.
|
||||
void _evictAllRulers() {
|
||||
_rulers.forEach((ParagraphGeometricStyle style, ParagraphRuler ruler) {
|
||||
ruler.dispose();
|
||||
});
|
||||
_rulers = <ParagraphGeometricStyle, ParagraphRuler>{};
|
||||
}
|
||||
|
||||
/// If [window._isPhysicalSizeActuallyEmpty], evicts all rulers from the cache.
|
||||
/// If ruler cache size exceeds [rulerCacheCapacity], evicts those rulers that
|
||||
/// were used the least.
|
||||
///
|
||||
/// Resets hit counts back to zero.
|
||||
@visibleForTesting
|
||||
void cleanUpRulerCache() {
|
||||
// Measurements performed (and cached) inside a hidden iframe (with
|
||||
// display:none) are wrong.
|
||||
// Evict all rulers, so text gets re-measured when the iframe becomes
|
||||
// visible.
|
||||
// see: https://github.com/flutter/flutter/issues/36341
|
||||
if (window.physicalSize.isEmpty) {
|
||||
_evictAllRulers();
|
||||
return;
|
||||
}
|
||||
if (_rulers.length > rulerCacheCapacity) {
|
||||
final List<ParagraphRuler> sortedByUsage = _rulers.values.toList();
|
||||
sortedByUsage.sort((ParagraphRuler a, ParagraphRuler b) {
|
||||
return b.hitCount - a.hitCount;
|
||||
});
|
||||
_rulers = <ParagraphGeometricStyle, ParagraphRuler>{};
|
||||
for (int i = 0; i < sortedByUsage.length; i++) {
|
||||
final ParagraphRuler ruler = sortedByUsage[i];
|
||||
ruler.resetHitCount();
|
||||
if (i < rulerCacheCapacity) {
|
||||
// Retain this ruler.
|
||||
_rulers[ruler.style] = ruler;
|
||||
} else {
|
||||
// This ruler did not have enough usage this frame to be retained.
|
||||
ruler.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs a cache lookup to find an existing [ParagraphRuler] for the given
|
||||
/// [style] and if it can't find one in the cache, it would create one.
|
||||
///
|
||||
/// The returned ruler is marked as hit so there's no need to do that
|
||||
/// elsewhere.
|
||||
@visibleForTesting
|
||||
ParagraphRuler findOrCreateRuler(ParagraphGeometricStyle style) {
|
||||
ParagraphRuler? ruler = _rulers[style];
|
||||
if (ruler == null) {
|
||||
if (assertionsEnabled) {
|
||||
domRenderer.debugRulerCacheMiss();
|
||||
}
|
||||
ruler = _rulers[style] = ParagraphRuler(style, this);
|
||||
_scheduleRulerCacheCleanup();
|
||||
} else {
|
||||
if (assertionsEnabled) {
|
||||
domRenderer.debugRulerCacheHit();
|
||||
}
|
||||
}
|
||||
ruler.hit();
|
||||
return ruler;
|
||||
}
|
||||
}
|
||||
|
||||
/// Provides various text measurement APIs using either a dom-based approach
|
||||
/// in [DomTextMeasurementService], or a canvas-based approach in
|
||||
/// [CanvasTextMeasurementService].
|
||||
abstract class TextMeasurementService {
|
||||
/// Whether this service uses a canvas to make the text measurements.
|
||||
///
|
||||
/// If [isCanvas] is false, it indicates that this service uses DOM elements
|
||||
/// to make the text measurements.
|
||||
bool get isCanvas;
|
||||
|
||||
/// Initializes the text measurement service with a specific
|
||||
/// [rulerCacheCapacity] that gets passed to the [RulerManager].
|
||||
///
|
||||
/// An optional `root` [html.Node] can be passed, under which the DOM required
|
||||
/// to perform measurements will be hosted. Defaults to [domRenderer.glassPaneShadow].
|
||||
static void initialize({required int rulerCacheCapacity, html.Node? root}) {
|
||||
rulerManager?.dispose();
|
||||
rulerManager = null;
|
||||
rulerManager = RulerManager(
|
||||
rulerCacheCapacity: rulerCacheCapacity,
|
||||
root: root,
|
||||
);
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
static RulerManager? rulerManager;
|
||||
|
||||
/// The DOM-based text measurement service.
|
||||
@visibleForTesting
|
||||
static TextMeasurementService get domInstance =>
|
||||
DomTextMeasurementService.instance;
|
||||
|
||||
/// The canvas-based text measurement service.
|
||||
@visibleForTesting
|
||||
static TextMeasurementService get canvasInstance =>
|
||||
CanvasTextMeasurementService.instance;
|
||||
|
||||
/// Gets the appropriate [TextMeasurementService] instance for the given
|
||||
/// [paragraph].
|
||||
static TextMeasurementService forParagraph(ui.Paragraph paragraph) {
|
||||
// TODO(mdebbar): https://github.com/flutter/flutter/issues/33523
|
||||
// When the canvas-based implementation is complete and passes all the
|
||||
// tests, get rid of [_experimentalEnableCanvasImplementation].
|
||||
// We need to check [window.physicalSize.isEmpty] because some canvas
|
||||
// commands don't work as expected when they run inside a hidden iframe
|
||||
// (with display:none)
|
||||
// Skip using canvas measurements until the iframe becomes visible.
|
||||
// see: https://github.com/flutter/flutter/issues/36341
|
||||
if (!window.physicalSize.isEmpty &&
|
||||
WebExperiments.instance!.useCanvasText &&
|
||||
_canUseCanvasMeasurement(paragraph as DomParagraph)) {
|
||||
return canvasInstance;
|
||||
}
|
||||
return domInstance;
|
||||
}
|
||||
|
||||
/// Clears the cache of paragraph rulers that are used for measuring paragraph
|
||||
/// metrics.
|
||||
static void clearCache() {
|
||||
rulerManager?._evictAllRulers();
|
||||
}
|
||||
|
||||
static bool _canUseCanvasMeasurement(DomParagraph paragraph) {
|
||||
// Currently, the canvas-based approach only works on plain text that
|
||||
// doesn't have any of the following styles:
|
||||
// - decoration
|
||||
// - word spacing
|
||||
final ParagraphGeometricStyle style = paragraph.geometricStyle;
|
||||
return paragraph.plainText != null &&
|
||||
style.decoration == null &&
|
||||
style.wordSpacing == null;
|
||||
}
|
||||
|
||||
/// Measures the paragraph and returns a [MeasurementResult] object.
|
||||
MeasurementResult? measure(
|
||||
DomParagraph paragraph,
|
||||
ui.ParagraphConstraints constraints,
|
||||
) {
|
||||
assert(rulerManager != null);
|
||||
final ParagraphGeometricStyle style = paragraph.geometricStyle;
|
||||
final ParagraphRuler ruler =
|
||||
TextMeasurementService.rulerManager!.findOrCreateRuler(style);
|
||||
|
||||
if (assertionsEnabled) {
|
||||
if (paragraph.plainText == null) {
|
||||
domRenderer.debugRichTextLayout();
|
||||
} else {
|
||||
domRenderer.debugPlainTextLayout();
|
||||
}
|
||||
}
|
||||
|
||||
MeasurementResult? result = ruler.cacheLookup(paragraph, constraints);
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
|
||||
result = _doMeasure(paragraph, constraints, ruler);
|
||||
ruler.cacheMeasurement(paragraph, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Measures the width of a substring of the given [paragraph] with no
|
||||
/// constraints.
|
||||
double measureSubstringWidth(DomParagraph paragraph, int start, int end);
|
||||
|
||||
/// Returns text position given a paragraph, constraints and offset.
|
||||
ui.TextPosition getTextPositionForOffset(DomParagraph paragraph,
|
||||
ui.ParagraphConstraints? constraints, ui.Offset offset);
|
||||
|
||||
/// Delegates to a [ParagraphRuler] to measure a list of text boxes that
|
||||
/// enclose the given range of text.
|
||||
List<ui.TextBox> measureBoxesForRange(
|
||||
DomParagraph paragraph,
|
||||
ui.ParagraphConstraints constraints, {
|
||||
required int start,
|
||||
required int end,
|
||||
required double alignOffset,
|
||||
required ui.TextDirection textDirection,
|
||||
}) {
|
||||
final ParagraphGeometricStyle style = paragraph.geometricStyle;
|
||||
final ParagraphRuler ruler =
|
||||
TextMeasurementService.rulerManager!.findOrCreateRuler(style);
|
||||
|
||||
return ruler.measureBoxesForRange(
|
||||
paragraph.plainText!,
|
||||
constraints,
|
||||
start: start,
|
||||
end: end,
|
||||
alignOffset: alignOffset,
|
||||
textDirection: textDirection,
|
||||
);
|
||||
}
|
||||
|
||||
/// Performs the actual measurement of the following values for the given
|
||||
/// paragraph:
|
||||
///
|
||||
/// * isSingleLine: whether the paragraph can be rendered in a single line.
|
||||
/// * height: constrained measure of the entire paragraph's height.
|
||||
/// * lineHeight: the height of a single line of the paragraph.
|
||||
/// * alphabeticBaseline: single line measure.
|
||||
/// * ideographicBaseline: based on [alphabeticBaseline].
|
||||
/// * maxIntrinsicWidth: the width of the paragraph with no line-wrapping.
|
||||
/// * minIntrinsicWidth: the min width the paragraph fits in without overflowing.
|
||||
///
|
||||
/// [MeasurementResult.width] is set to the same value of [constraints.width].
|
||||
///
|
||||
/// It also optionally computes [MeasurementResult.lines] in the given
|
||||
/// paragraph. When that's available, it can be used by a canvas to render
|
||||
/// the text line.
|
||||
MeasurementResult _doMeasure(
|
||||
DomParagraph paragraph,
|
||||
ui.ParagraphConstraints constraints,
|
||||
ParagraphRuler ruler,
|
||||
);
|
||||
}
|
||||
|
||||
/// A DOM-based text measurement implementation.
|
||||
///
|
||||
/// This implementation is slower than [CanvasTextMeasurementService] but it's
|
||||
/// needed for some cases that aren't yet supported in the canvas-based
|
||||
/// implementation such as letter-spacing, word-spacing, etc.
|
||||
class DomTextMeasurementService extends TextMeasurementService {
|
||||
@override
|
||||
final bool isCanvas = false;
|
||||
|
||||
/// The text measurement service singleton.
|
||||
static DomTextMeasurementService get instance =>
|
||||
_instance ??= DomTextMeasurementService();
|
||||
|
||||
static DomTextMeasurementService? _instance;
|
||||
|
||||
@override
|
||||
MeasurementResult _doMeasure(
|
||||
DomParagraph paragraph,
|
||||
ui.ParagraphConstraints constraints,
|
||||
ParagraphRuler ruler,
|
||||
) {
|
||||
ruler.willMeasure(paragraph);
|
||||
final String? plainText = paragraph.plainText;
|
||||
|
||||
ruler.measureAll(constraints);
|
||||
|
||||
MeasurementResult result;
|
||||
// When the text has a new line, we should always use multi-line mode.
|
||||
final bool hasNewline = plainText?.contains('\n') ?? false;
|
||||
if (!hasNewline && ruler.singleLineDimensions.width <= constraints.width) {
|
||||
result = _measureSingleLineParagraph(ruler, paragraph, constraints);
|
||||
} else {
|
||||
// Assert: If text doesn't have new line for infinite constraints we
|
||||
// should have called single line measure paragraph instead.
|
||||
assert(hasNewline || constraints.width != double.infinity);
|
||||
result = _measureMultiLineParagraph(ruler, paragraph, constraints);
|
||||
}
|
||||
ruler.didMeasure();
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
double measureSubstringWidth(DomParagraph paragraph, int start, int end) {
|
||||
assert(paragraph.plainText != null);
|
||||
final ParagraphGeometricStyle style = paragraph.geometricStyle;
|
||||
final ParagraphRuler ruler =
|
||||
TextMeasurementService.rulerManager!.findOrCreateRuler(style);
|
||||
|
||||
final String text = paragraph.plainText!.substring(start, end);
|
||||
final ui.Paragraph substringParagraph = paragraph.cloneWithText(text);
|
||||
|
||||
ruler.willMeasure(substringParagraph as DomParagraph);
|
||||
ruler.measureAsSingleLine();
|
||||
final TextDimensions dimensions = ruler.singleLineDimensions;
|
||||
ruler.didMeasure();
|
||||
return dimensions.width;
|
||||
}
|
||||
|
||||
@override
|
||||
ui.TextPosition getTextPositionForOffset(DomParagraph paragraph,
|
||||
ui.ParagraphConstraints? constraints, ui.Offset offset) {
|
||||
assert(
|
||||
paragraph.measurementResult!.lines == null,
|
||||
'should only be called when the faster lines-based approach is not possible',
|
||||
);
|
||||
|
||||
final ParagraphGeometricStyle style = paragraph.geometricStyle;
|
||||
final ParagraphRuler ruler =
|
||||
TextMeasurementService.rulerManager!.findOrCreateRuler(style);
|
||||
ruler.willMeasure(paragraph);
|
||||
final int position = ruler.hitTest(constraints!, offset);
|
||||
ruler.didMeasure();
|
||||
return ui.TextPosition(offset: position);
|
||||
}
|
||||
|
||||
/// Called when we have determined that the paragraph fits the [constraints]
|
||||
/// without wrapping.
|
||||
///
|
||||
/// This means that:
|
||||
/// * `width == maxIntrinsicWidth` - we gave it more horizontal space than
|
||||
/// it needs and so the paragraph won't expand beyond `maxIntrinsicWidth`.
|
||||
/// * `height` is the height computed by `measureAsSingleLine`; giving the
|
||||
/// paragraph the width constraint won't change its height as we already
|
||||
/// determined that it fits within the constraint without wrapping.
|
||||
/// * `alphabeticBaseline` is also final for the same reason as the `height`
|
||||
/// value.
|
||||
///
|
||||
/// This method still needs to measure `minIntrinsicWidth`.
|
||||
MeasurementResult _measureSingleLineParagraph(
|
||||
ParagraphRuler ruler,
|
||||
DomParagraph paragraph,
|
||||
ui.ParagraphConstraints constraints,
|
||||
) {
|
||||
final double width = constraints.width;
|
||||
final double minIntrinsicWidth = ruler.minIntrinsicDimensions.width;
|
||||
double maxIntrinsicWidth = ruler.singleLineDimensions.width;
|
||||
final double alphabeticBaseline = ruler.alphabeticBaseline;
|
||||
final double height = ruler.singleLineDimensions.height;
|
||||
|
||||
maxIntrinsicWidth =
|
||||
_applySubPixelRoundingHack(minIntrinsicWidth, maxIntrinsicWidth);
|
||||
final double ideographicBaseline = alphabeticBaseline * baselineRatioHack;
|
||||
|
||||
final String? text = paragraph.plainText;
|
||||
List<EngineLineMetrics>? lines;
|
||||
if (text != null) {
|
||||
final double lineWidth = maxIntrinsicWidth;
|
||||
final double alignOffset = _calculateAlignOffsetForLine(
|
||||
paragraph: paragraph,
|
||||
lineWidth: lineWidth,
|
||||
maxWidth: width,
|
||||
);
|
||||
lines = <EngineLineMetrics>[
|
||||
EngineLineMetrics.withText(
|
||||
text,
|
||||
startIndex: 0,
|
||||
endIndex: text.length,
|
||||
endIndexWithoutNewlines:
|
||||
_excludeTrailing(text, 0, text.length, _newlinePredicate),
|
||||
hardBreak: true,
|
||||
width: lineWidth,
|
||||
widthWithTrailingSpaces: lineWidth,
|
||||
left: alignOffset,
|
||||
lineNumber: 0,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
return MeasurementResult(
|
||||
constraints.width,
|
||||
isSingleLine: true,
|
||||
width: width,
|
||||
height: height,
|
||||
naturalHeight: height,
|
||||
lineHeight: height,
|
||||
minIntrinsicWidth: minIntrinsicWidth,
|
||||
maxIntrinsicWidth: maxIntrinsicWidth,
|
||||
alphabeticBaseline: alphabeticBaseline,
|
||||
ideographicBaseline: ideographicBaseline,
|
||||
lines: lines,
|
||||
placeholderBoxes: ruler.measurePlaceholderBoxes(),
|
||||
textAlign: paragraph.textAlign,
|
||||
textDirection: paragraph.textDirection,
|
||||
);
|
||||
}
|
||||
|
||||
/// Called when we have determined that the paragraph needs to wrap into
|
||||
/// multiple lines to fit the [constraints], i.e. its `maxIntrinsicWidth` is
|
||||
/// bigger than the available horizontal space.
|
||||
///
|
||||
/// While `maxIntrinsicWidth` is still good from the call to
|
||||
/// `measureAsSingleLine`, we need to re-measure with the width constraint
|
||||
/// and get new values for width, height and alphabetic baseline. We also need
|
||||
/// to measure `minIntrinsicWidth`.
|
||||
MeasurementResult _measureMultiLineParagraph(ParagraphRuler ruler,
|
||||
DomParagraph paragraph, ui.ParagraphConstraints constraints) {
|
||||
// If constraint is infinite, we must use _measureSingleLineParagraph
|
||||
final double width = constraints.width;
|
||||
final double minIntrinsicWidth = ruler.minIntrinsicDimensions.width;
|
||||
double maxIntrinsicWidth = ruler.singleLineDimensions.width;
|
||||
final double alphabeticBaseline = ruler.alphabeticBaseline;
|
||||
// Natural height is the full height of text ignoring height constraints.
|
||||
final double naturalHeight = ruler.constrainedDimensions.height;
|
||||
|
||||
double height;
|
||||
double? lineHeight;
|
||||
final int? maxLines = paragraph.geometricStyle.maxLines;
|
||||
if (maxLines == null) {
|
||||
height = naturalHeight;
|
||||
} else {
|
||||
// Lazily compute [lineHeight] when [maxLines] is not null.
|
||||
lineHeight = ruler.lineHeight;
|
||||
height = math.min(naturalHeight, maxLines * lineHeight);
|
||||
}
|
||||
|
||||
maxIntrinsicWidth =
|
||||
_applySubPixelRoundingHack(minIntrinsicWidth, maxIntrinsicWidth);
|
||||
assert(minIntrinsicWidth <= maxIntrinsicWidth);
|
||||
final double ideographicBaseline = alphabeticBaseline * baselineRatioHack;
|
||||
return MeasurementResult(
|
||||
constraints.width,
|
||||
isSingleLine: false,
|
||||
width: width,
|
||||
height: height,
|
||||
lineHeight: lineHeight,
|
||||
naturalHeight: naturalHeight,
|
||||
minIntrinsicWidth: minIntrinsicWidth,
|
||||
maxIntrinsicWidth: maxIntrinsicWidth,
|
||||
alphabeticBaseline: alphabeticBaseline,
|
||||
ideographicBaseline: ideographicBaseline,
|
||||
lines: null,
|
||||
placeholderBoxes: ruler.measurePlaceholderBoxes(),
|
||||
textAlign: paragraph.textAlign,
|
||||
textDirection: paragraph.textDirection,
|
||||
);
|
||||
}
|
||||
|
||||
/// This hack is needed because `offsetWidth` rounds the value to the nearest
|
||||
/// whole number. On a very rare occasion the minimum intrinsic width reported
|
||||
/// by the browser is slightly bigger than the reported maximum intrinsic
|
||||
/// width. If the discrepancy overlaps 0.5 then the rounding happens in
|
||||
/// opposite directions.
|
||||
///
|
||||
/// For example, if minIntrinsicWidth == 99.5 and maxIntrinsicWidth == 99.48,
|
||||
/// then minIntrinsicWidth is rounded up to 100, and maxIntrinsicWidth is
|
||||
/// rounded down to 99.
|
||||
// TODO(yjbanov): remove the need for this hack.
|
||||
static double _applySubPixelRoundingHack(
|
||||
double minIntrinsicWidth, double maxIntrinsicWidth) {
|
||||
if (minIntrinsicWidth <= maxIntrinsicWidth) {
|
||||
return maxIntrinsicWidth;
|
||||
}
|
||||
|
||||
if (minIntrinsicWidth - maxIntrinsicWidth < 2.0) {
|
||||
return minIntrinsicWidth;
|
||||
}
|
||||
|
||||
throw Exception('minIntrinsicWidth ($minIntrinsicWidth) is greater than '
|
||||
'maxIntrinsicWidth ($maxIntrinsicWidth).');
|
||||
}
|
||||
}
|
||||
|
||||
/// A canvas-based text measurement implementation.
|
||||
///
|
||||
/// This is a faster implementation than [DomTextMeasurementService] and
|
||||
/// provides line breaks information that can be useful for multi-line text.
|
||||
class CanvasTextMeasurementService extends TextMeasurementService {
|
||||
@override
|
||||
final bool isCanvas = true;
|
||||
|
||||
/// The text measurement service singleton.
|
||||
static CanvasTextMeasurementService get instance =>
|
||||
_instance ??= CanvasTextMeasurementService();
|
||||
|
||||
static CanvasTextMeasurementService? _instance;
|
||||
|
||||
final html.CanvasRenderingContext2D _canvasContext =
|
||||
html.CanvasElement().context2D;
|
||||
|
||||
@override
|
||||
MeasurementResult _doMeasure(
|
||||
DomParagraph paragraph,
|
||||
ui.ParagraphConstraints constraints,
|
||||
ParagraphRuler ruler,
|
||||
) {
|
||||
final String text = paragraph.plainText!;
|
||||
final ParagraphGeometricStyle style = paragraph.geometricStyle;
|
||||
assert(text != null); // ignore: unnecessary_null_comparison
|
||||
|
||||
// TODO(mdebbar): Check if the whole text can fit in a single-line. Then avoid all this ceremony.
|
||||
_canvasContext.font = style.cssFontString;
|
||||
final LinesCalculator linesCalculator =
|
||||
LinesCalculator(_canvasContext, paragraph, constraints.width);
|
||||
final MinIntrinsicCalculator minIntrinsicCalculator =
|
||||
MinIntrinsicCalculator(_canvasContext, text, style);
|
||||
final MaxIntrinsicCalculator maxIntrinsicCalculator =
|
||||
MaxIntrinsicCalculator(_canvasContext, text, style);
|
||||
|
||||
// Indicates whether we've reached the end of text or not. Even if the index
|
||||
// [i] reaches the end of text, we don't want to stop looping until we hit
|
||||
// [LineBreakType.endOfText] because there could be a "\n" at the end of the
|
||||
// string and that would mess things up.
|
||||
bool reachedEndOfText = false;
|
||||
|
||||
// TODO(mdebbar): Chrome & Safari return more info from [canvasContext.measureText].
|
||||
int i = 0;
|
||||
while (!reachedEndOfText) {
|
||||
final LineBreakResult brk = nextLineBreak(text, i);
|
||||
|
||||
linesCalculator.update(brk);
|
||||
minIntrinsicCalculator.update(brk);
|
||||
maxIntrinsicCalculator.update(brk);
|
||||
|
||||
i = brk.index;
|
||||
if (brk.type == LineBreakType.endOfText) {
|
||||
reachedEndOfText = true;
|
||||
}
|
||||
}
|
||||
|
||||
final double alphabeticBaseline = ruler.alphabeticBaseline;
|
||||
final int lineCount = linesCalculator.lines.length;
|
||||
final double lineHeight = ruler.lineHeight;
|
||||
final double naturalHeight = lineCount * lineHeight;
|
||||
final int? maxLines = style.maxLines;
|
||||
final double height = maxLines == null
|
||||
? naturalHeight
|
||||
: math.min<int>(lineCount, maxLines) * lineHeight;
|
||||
|
||||
final MeasurementResult result = MeasurementResult(
|
||||
constraints.width,
|
||||
isSingleLine: lineCount == 1,
|
||||
alphabeticBaseline: alphabeticBaseline,
|
||||
ideographicBaseline: alphabeticBaseline * baselineRatioHack,
|
||||
height: height,
|
||||
naturalHeight: naturalHeight,
|
||||
lineHeight: lineHeight,
|
||||
// `minIntrinsicWidth` is the greatest width of text that can't
|
||||
// be broken down into multiple lines.
|
||||
minIntrinsicWidth: minIntrinsicCalculator.value,
|
||||
// `maxIntrinsicWidth` is the width of the widest piece of text
|
||||
// that doesn't contain mandatory line breaks.
|
||||
maxIntrinsicWidth: maxIntrinsicCalculator.value,
|
||||
width: constraints.width,
|
||||
lines: linesCalculator.lines,
|
||||
placeholderBoxes: const <ui.TextBox>[],
|
||||
textAlign: paragraph.textAlign,
|
||||
textDirection: paragraph.textDirection,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
double measureSubstringWidth(DomParagraph paragraph, int start, int end) {
|
||||
assert(paragraph.plainText != null);
|
||||
final String text = paragraph.plainText!;
|
||||
final ParagraphGeometricStyle style = paragraph.geometricStyle;
|
||||
_canvasContext.font = style.cssFontString;
|
||||
return measureSubstring(
|
||||
_canvasContext,
|
||||
text,
|
||||
start,
|
||||
end,
|
||||
letterSpacing: paragraph.geometricStyle.letterSpacing,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
ui.TextPosition getTextPositionForOffset(EngineParagraph paragraph,
|
||||
ui.ParagraphConstraints? constraints, ui.Offset offset) {
|
||||
// TODO(mdebbar): implement.
|
||||
return const ui.TextPosition(offset: 0);
|
||||
}
|
||||
}
|
||||
|
||||
// These global variables are used to memoize calls to [measureSubstring]. They
|
||||
// are used to remember the last arguments passed to it, and the last return
|
||||
// value.
|
||||
@@ -746,327 +124,3 @@ double measureSubstring(
|
||||
double _roundWidth(double width) {
|
||||
return (width * 100).round() / 100;
|
||||
}
|
||||
|
||||
/// From the substring defined by [text], [start] (inclusive) and [end]
|
||||
/// (exclusive), exclude trailing characters that satisfy the given [predicate].
|
||||
///
|
||||
/// The return value is the new end of the substring after excluding the
|
||||
/// trailing characters.
|
||||
int _excludeTrailing(String text, int start, int end, CharPredicate predicate) {
|
||||
assert(0 <= start);
|
||||
assert(start <= end);
|
||||
assert(end <= text.length);
|
||||
|
||||
while (start < end && predicate(text.codeUnitAt(end - 1))) {
|
||||
end--;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
/// During the text layout phase, this class splits the lines of text so that it
|
||||
/// ends up fitting into the given width constraint.
|
||||
///
|
||||
/// It implements the Flutter engine's behavior when it comes to handling
|
||||
/// ellipsis and max lines.
|
||||
class LinesCalculator {
|
||||
LinesCalculator(this._canvasContext, this._paragraph, this._maxWidth);
|
||||
|
||||
final html.CanvasRenderingContext2D _canvasContext;
|
||||
final DomParagraph _paragraph;
|
||||
final double _maxWidth;
|
||||
|
||||
String? get _text => _paragraph.plainText;
|
||||
ParagraphGeometricStyle get _style => _paragraph.geometricStyle;
|
||||
|
||||
/// The lines that have been consumed so far.
|
||||
List<EngineLineMetrics> lines = <EngineLineMetrics>[];
|
||||
|
||||
/// The last line break regardless of whether it was optional or mandatory, or
|
||||
/// whether we took it or not.
|
||||
LineBreakResult _lastBreak =
|
||||
const LineBreakResult.sameIndex(0, LineBreakType.mandatory);
|
||||
|
||||
/// The last line break that actually caused a new line to exist.
|
||||
LineBreakResult _lastTakenBreak =
|
||||
const LineBreakResult.sameIndex(0, LineBreakType.mandatory);
|
||||
|
||||
int get _lineStart => _lastTakenBreak.index;
|
||||
int get _chunkStart => _lastBreak.index;
|
||||
bool _reachedMaxLines = false;
|
||||
|
||||
double? _cachedEllipsisWidth;
|
||||
double get _ellipsisWidth => _cachedEllipsisWidth ??=
|
||||
_roundWidth(_canvasContext.measureText(_style.ellipsis!).width! as double);
|
||||
|
||||
bool get hasEllipsis => _style.ellipsis != null;
|
||||
bool get unlimitedLines => _style.maxLines == null;
|
||||
|
||||
/// Consumes the next line break opportunity in [_text].
|
||||
///
|
||||
/// This method should be called for every line break. As soon as it reaches
|
||||
/// the maximum number of lines required
|
||||
void update(LineBreakResult brk) {
|
||||
final int chunkEnd = brk.index;
|
||||
final int chunkEndWithoutNewlines = brk.indexWithoutTrailingNewlines;
|
||||
final int chunkEndWithoutSpace = brk.indexWithoutTrailingSpaces;
|
||||
|
||||
// A single chunk of text could be force-broken into multiple lines if it
|
||||
// doesn't fit in a single line. That's why we need a loop.
|
||||
while (!_reachedMaxLines) {
|
||||
final double lineWidth =
|
||||
measureSubstringWidth(_lineStart, chunkEndWithoutSpace);
|
||||
|
||||
// The current chunk doesn't reach the maximum width, so we stop here and
|
||||
// wait for the next line break.
|
||||
if (lineWidth <= _maxWidth) {
|
||||
break;
|
||||
}
|
||||
|
||||
// If the current chunk starts at the beginning of the line and exceeds
|
||||
// [maxWidth], then we will need to force-break it.
|
||||
final bool isChunkTooLong = _chunkStart == _lineStart;
|
||||
|
||||
// When ellipsis is set, and maxLines is null, we stop at the first line
|
||||
// that exceeds [maxWidth].
|
||||
final bool isLastLine = _reachedMaxLines =
|
||||
(hasEllipsis && unlimitedLines) ||
|
||||
lines.length + 1 == _style.maxLines;
|
||||
|
||||
if (isLastLine && hasEllipsis) {
|
||||
// When there's an ellipsis, truncate text to leave enough space for
|
||||
// the ellipsis.
|
||||
final double availableWidth = _maxWidth - _ellipsisWidth;
|
||||
final int breakingPoint = forceBreakSubstring(
|
||||
maxWidth: availableWidth,
|
||||
start: _lineStart,
|
||||
end: chunkEndWithoutSpace,
|
||||
);
|
||||
final double widthOfResultingLine =
|
||||
measureSubstringWidth(_lineStart, breakingPoint) + _ellipsisWidth;
|
||||
final double alignOffset = _calculateAlignOffsetForLine(
|
||||
paragraph: _paragraph,
|
||||
lineWidth: widthOfResultingLine,
|
||||
maxWidth: _maxWidth,
|
||||
);
|
||||
lines.add(EngineLineMetrics.withText(
|
||||
_text!.substring(_lineStart, breakingPoint) + _style.ellipsis!,
|
||||
startIndex: _lineStart,
|
||||
endIndex: chunkEnd,
|
||||
endIndexWithoutNewlines: chunkEndWithoutNewlines,
|
||||
hardBreak: false,
|
||||
width: widthOfResultingLine,
|
||||
widthWithTrailingSpaces: widthOfResultingLine,
|
||||
left: alignOffset,
|
||||
lineNumber: lines.length,
|
||||
));
|
||||
} else if (isChunkTooLong) {
|
||||
final int breakingPoint = forceBreakSubstring(
|
||||
maxWidth: _maxWidth,
|
||||
start: _lineStart,
|
||||
end: chunkEndWithoutSpace,
|
||||
);
|
||||
if (breakingPoint == chunkEndWithoutSpace) {
|
||||
// We couldn't force-break the chunk any further which means we reached
|
||||
// the last character and there isn't enough space for it to fit in
|
||||
// its own line. Since this is the last character in the chunk, we
|
||||
// don't do anything here and we rely on the next iteration (or the
|
||||
// [isHardBreak] check below) to break the line.
|
||||
break;
|
||||
}
|
||||
_addLineBreak(LineBreakResult.sameIndex(
|
||||
breakingPoint,
|
||||
LineBreakType.opportunity,
|
||||
));
|
||||
} else {
|
||||
// The control case of current line exceeding [_maxWidth], we break the
|
||||
// line.
|
||||
_addLineBreak(_lastBreak);
|
||||
}
|
||||
}
|
||||
|
||||
if (_reachedMaxLines) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (brk.isHard) {
|
||||
_addLineBreak(brk);
|
||||
}
|
||||
_lastBreak = brk;
|
||||
}
|
||||
|
||||
void _addLineBreak(LineBreakResult brk) {
|
||||
final int lineNumber = lines.length;
|
||||
final double lineWidth =
|
||||
measureSubstringWidth(_lineStart, brk.indexWithoutTrailingSpaces);
|
||||
final double lineWidthWithTrailingSpaces =
|
||||
measureSubstringWidth(_lineStart, brk.indexWithoutTrailingNewlines);
|
||||
final double alignOffset = _calculateAlignOffsetForLine(
|
||||
paragraph: _paragraph,
|
||||
lineWidth: lineWidth,
|
||||
maxWidth: _maxWidth,
|
||||
);
|
||||
|
||||
final EngineLineMetrics metrics = EngineLineMetrics.withText(
|
||||
_text!.substring(_lineStart, brk.indexWithoutTrailingNewlines),
|
||||
startIndex: _lineStart,
|
||||
endIndex: brk.index,
|
||||
endIndexWithoutNewlines: brk.indexWithoutTrailingNewlines,
|
||||
hardBreak: brk.isHard,
|
||||
width: lineWidth,
|
||||
widthWithTrailingSpaces: lineWidthWithTrailingSpaces,
|
||||
left: alignOffset,
|
||||
lineNumber: lineNumber,
|
||||
);
|
||||
lines.add(metrics);
|
||||
_lastTakenBreak = _lastBreak = brk;
|
||||
if (lines.length == _style.maxLines) {
|
||||
_reachedMaxLines = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Measures the width of a substring of [_text] starting from the index
|
||||
/// [start] (inclusive) to [end] (exclusive).
|
||||
///
|
||||
/// This method uses [_text], [_style] and [_canvasContext] to perform the
|
||||
/// measurement.
|
||||
double measureSubstringWidth(int start, int end) {
|
||||
return measureSubstring(
|
||||
_canvasContext,
|
||||
_text!,
|
||||
start,
|
||||
end,
|
||||
letterSpacing: _style.letterSpacing,
|
||||
);
|
||||
}
|
||||
|
||||
/// In a continuous block of text, finds the point where text can be broken to
|
||||
/// fit in the given constraint [maxWidth].
|
||||
///
|
||||
/// This always returns at least one character even if there isn't enough
|
||||
/// space for it.
|
||||
int forceBreakSubstring({
|
||||
required double maxWidth,
|
||||
required int start,
|
||||
required int end,
|
||||
}) {
|
||||
assert(0 <= start);
|
||||
assert(start < end);
|
||||
assert(end <= _text!.length);
|
||||
|
||||
// When there's no ellipsis, the breaking point should be at least one
|
||||
// character away from [start].
|
||||
int low = hasEllipsis ? start : start + 1;
|
||||
int high = end;
|
||||
do {
|
||||
final int mid = (low + high) ~/ 2;
|
||||
final double width = measureSubstringWidth(start, mid);
|
||||
if (width < maxWidth) {
|
||||
low = mid;
|
||||
} else if (width > maxWidth) {
|
||||
high = mid;
|
||||
} else {
|
||||
low = high = mid;
|
||||
}
|
||||
} while (high - low > 1);
|
||||
|
||||
return low;
|
||||
}
|
||||
}
|
||||
|
||||
/// During the text layout phase, this class takes care of calculating the
|
||||
/// minimum intrinsic width of the given text.
|
||||
class MinIntrinsicCalculator {
|
||||
MinIntrinsicCalculator(this._canvasContext, this._text, this._style);
|
||||
|
||||
final html.CanvasRenderingContext2D _canvasContext;
|
||||
final String _text;
|
||||
final ParagraphGeometricStyle _style;
|
||||
|
||||
/// The value of minimum intrinsic width calculated so far.
|
||||
double value = 0.0;
|
||||
int _lastChunkEnd = 0;
|
||||
|
||||
/// Consumes the next line break opportunity in [_text].
|
||||
///
|
||||
/// As this method gets called, it updates the [value] to the minimum
|
||||
/// intrinsic width calculated so far. When the whole text is consumed,
|
||||
/// [value] will contain the final minimum intrinsic width.
|
||||
void update(LineBreakResult brk) {
|
||||
final int chunkEnd = brk.index;
|
||||
final double width = measureSubstring(
|
||||
_canvasContext,
|
||||
_text,
|
||||
_lastChunkEnd,
|
||||
brk.indexWithoutTrailingSpaces,
|
||||
letterSpacing: _style.letterSpacing,
|
||||
);
|
||||
if (width > value) {
|
||||
value = width;
|
||||
}
|
||||
_lastChunkEnd = chunkEnd;
|
||||
}
|
||||
}
|
||||
|
||||
/// During text layout, this class is responsible for calculating the maximum
|
||||
/// intrinsic width of the given text.
|
||||
class MaxIntrinsicCalculator {
|
||||
MaxIntrinsicCalculator(this._canvasContext, this._text, this._style);
|
||||
|
||||
final html.CanvasRenderingContext2D _canvasContext;
|
||||
final String _text;
|
||||
final ParagraphGeometricStyle _style;
|
||||
|
||||
/// The value of maximum intrinsic width calculated so far.
|
||||
double value = 0.0;
|
||||
int _lastHardLineEnd = 0;
|
||||
|
||||
/// Consumes the next line break opportunity in [_text].
|
||||
///
|
||||
/// As this method gets called, it updates the [value] to the maximum
|
||||
/// intrinsic width calculated so far. When the whole text is consumed,
|
||||
/// [value] will contain the final maximum intrinsic width.
|
||||
void update(LineBreakResult brk) {
|
||||
if (!brk.isHard) {
|
||||
return;
|
||||
}
|
||||
|
||||
final double lineWidth = measureSubstring(
|
||||
_canvasContext,
|
||||
_text,
|
||||
_lastHardLineEnd,
|
||||
brk.indexWithoutTrailingNewlines,
|
||||
letterSpacing: _style.letterSpacing,
|
||||
);
|
||||
if (lineWidth > value) {
|
||||
value = lineWidth;
|
||||
}
|
||||
_lastHardLineEnd = brk.index;
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculates the offset necessary for the given line to be correctly aligned.
|
||||
double _calculateAlignOffsetForLine({
|
||||
required DomParagraph paragraph,
|
||||
required double lineWidth,
|
||||
required double maxWidth,
|
||||
}) {
|
||||
final double emptySpace = maxWidth - lineWidth;
|
||||
// WARNING: the [paragraph] may not be laid out yet at this point. This
|
||||
// function must not use layout metrics, such as [paragraph.height].
|
||||
switch (paragraph.textAlign) {
|
||||
case ui.TextAlign.center:
|
||||
return emptySpace / 2.0;
|
||||
case ui.TextAlign.right:
|
||||
return emptySpace;
|
||||
case ui.TextAlign.start:
|
||||
return paragraph.textDirection == ui.TextDirection.rtl
|
||||
? emptySpace
|
||||
: 0.0;
|
||||
case ui.TextAlign.end:
|
||||
return paragraph.textDirection == ui.TextDirection.rtl
|
||||
? 0.0
|
||||
: emptySpace;
|
||||
default:
|
||||
return 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,6 @@
|
||||
|
||||
import 'dart:html' as html;
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:ui/ui.dart' as ui;
|
||||
|
||||
import '../browser_detection.dart';
|
||||
@@ -247,73 +246,6 @@ class TextDimensions {
|
||||
final html.HtmlElement _element;
|
||||
html.Rectangle<num>? _cachedBoundingClientRect;
|
||||
|
||||
/// Attempts to efficiently copy text from [from].
|
||||
///
|
||||
/// The primary efficiency gain is from rare occurrence of rich text in
|
||||
/// typical apps.
|
||||
void updateText(DomParagraph from, ParagraphGeometricStyle style) {
|
||||
assert(from != null); // ignore: unnecessary_null_comparison
|
||||
assert(_element != null); // ignore: unnecessary_null_comparison
|
||||
assert(from.debugHasSameRootStyle(style));
|
||||
assert(() {
|
||||
final bool wasEmptyOrPlainText = _element.childNodes.isEmpty ||
|
||||
(_element.childNodes.length == 1 &&
|
||||
_element.childNodes.first is html.Text);
|
||||
if (!wasEmptyOrPlainText) {
|
||||
throw Exception(
|
||||
'Failed to copy text into the paragraph measuring element. The '
|
||||
'element already contains rich text "${_element.innerHtml}". It is '
|
||||
'likely that a previous measurement did not clean up after '
|
||||
'itself.');
|
||||
}
|
||||
return true;
|
||||
}());
|
||||
|
||||
_invalidateBoundsCache();
|
||||
final String? plainText = from.plainText;
|
||||
if (plainText != null) {
|
||||
// Plain text: just set the string. The paragraph's style is assumed to
|
||||
// match the style set on the `element`. Setting text as plain string is
|
||||
// faster because it doesn't change the DOM structure or CSS attributes,
|
||||
// and therefore doesn't trigger style recalculations in the browser.
|
||||
if (plainText.endsWith('\n')) {
|
||||
// On the web the last newline is ignored. To be consistent with
|
||||
// native engine implementation we add extra newline to get correct
|
||||
// height measurement.
|
||||
_element.text = '$plainText\n';
|
||||
} else {
|
||||
_element.text = plainText;
|
||||
}
|
||||
} else {
|
||||
// Rich text: deeply copy contents. This is the slow case that should be
|
||||
// avoided if fast layout performance is desired.
|
||||
final html.Element copy = from.paragraphElement.clone(true) as html.Element;
|
||||
_element.nodes.addAll(copy.nodes);
|
||||
}
|
||||
}
|
||||
|
||||
/// Updated element style width.
|
||||
void updateConstraintWidth(double width, String? ellipsis) {
|
||||
_invalidateBoundsCache();
|
||||
|
||||
if (width.isInfinite) {
|
||||
_element.style
|
||||
..width = null
|
||||
..whiteSpace = 'pre';
|
||||
} else if (ellipsis != null) {
|
||||
// Width is finite, but we don't want to let the text soft-wrap when
|
||||
// ellipsis overflow is enabled.
|
||||
_element.style
|
||||
..width = '${width}px'
|
||||
..whiteSpace = 'pre';
|
||||
} else {
|
||||
// Width is finite and there's no ellipsis overflow.
|
||||
_element.style
|
||||
..width = '${width}px'
|
||||
..whiteSpace = 'pre-wrap';
|
||||
}
|
||||
}
|
||||
|
||||
void _invalidateBoundsCache() {
|
||||
_cachedBoundingClientRect = null;
|
||||
}
|
||||
@@ -324,36 +256,6 @@ class TextDimensions {
|
||||
_element.text = ' ';
|
||||
}
|
||||
|
||||
/// Applies geometric style properties to the [element].
|
||||
void applyStyle(ParagraphGeometricStyle style) {
|
||||
final html.CssStyleDeclaration elementStyle = _element.style;
|
||||
elementStyle
|
||||
..direction = textDirectionToCss(style.textDirection)
|
||||
..textAlign = textAlignToCssValue(style.textAlign, style.textDirection)
|
||||
..fontSize = style.fontSize != null ? '${style.fontSize!.floor()}px' : null
|
||||
..fontFamily = canonicalizeFontFamily(style.effectiveFontFamily)
|
||||
..fontWeight =
|
||||
style.fontWeight != null ? fontWeightToCss(style.fontWeight) : null
|
||||
..fontStyle = style.fontStyle != null
|
||||
? style.fontStyle == ui.FontStyle.normal ? 'normal' : 'italic'
|
||||
: null
|
||||
..letterSpacing =
|
||||
style.letterSpacing != null ? '${style.letterSpacing}px' : null
|
||||
..wordSpacing =
|
||||
style.wordSpacing != null ? '${style.wordSpacing}px' : null;
|
||||
final String? decoration = style.decoration;
|
||||
if (browserEngine == BrowserEngine.webkit) {
|
||||
DomRenderer.setElementStyle(
|
||||
_element, '-webkit-text-decoration', decoration);
|
||||
} else {
|
||||
elementStyle.textDecoration = decoration;
|
||||
}
|
||||
if (style.lineHeight != null) {
|
||||
elementStyle.lineHeight = style.lineHeight!.toString();
|
||||
}
|
||||
_invalidateBoundsCache();
|
||||
}
|
||||
|
||||
void applyHeightStyle(TextHeightStyle textHeightStyle) {
|
||||
final String fontFamily = textHeightStyle.fontFamily;
|
||||
final double fontSize = textHeightStyle.fontSize;
|
||||
@@ -379,9 +281,6 @@ class TextDimensions {
|
||||
html.Rectangle<num> _readAndCacheMetrics() =>
|
||||
_cachedBoundingClientRect ??= _element.getBoundingClientRect();
|
||||
|
||||
/// The width of the paragraph being measured.
|
||||
double get width => _readAndCacheMetrics().width as double;
|
||||
|
||||
/// The height of the paragraph being measured.
|
||||
double get height {
|
||||
double cachedHeight = _readAndCacheMetrics().height as double;
|
||||
@@ -464,624 +363,3 @@ class TextHeightRuler {
|
||||
return probe;
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs 4 types of measurements:
|
||||
///
|
||||
/// 1. Single line: can be prepared by calling [measureAsSingleLine].
|
||||
/// Measurement values will be available at [singleLineDimensions].
|
||||
///
|
||||
/// 2. Minimum intrinsic width: can be prepared by calling
|
||||
/// [measureMinIntrinsicWidth]. Measurement values will be available at
|
||||
/// [minIntrinsicDimensions].
|
||||
///
|
||||
/// 3. Constrained: can be prepared by calling [measureWithConstraints] and
|
||||
/// passing the constraints. Measurement values will be available at
|
||||
/// [constrainedDimensions].
|
||||
///
|
||||
/// 4. Boxes: within a paragraph, it measures a list of text boxes that enclose
|
||||
/// a given range of text.
|
||||
///
|
||||
/// For performance reasons, it's advised to use [measureAll] and then reading
|
||||
/// whatever measurements are needed. This causes the browser to only reflow
|
||||
/// once instead of many times.
|
||||
///
|
||||
/// The [measureAll] method performs the first 3 stateful measurements but not
|
||||
/// the 4th one.
|
||||
///
|
||||
/// This class is both reusable and stateful. Use it carefully. The correct
|
||||
/// usage is as follows:
|
||||
///
|
||||
/// * First, call [willMeasure] passing it the paragraph to be measured.
|
||||
/// * Call any of the [measureAsSingleLine], [measureMinIntrinsicWidth],
|
||||
/// [measureWithConstraints], or [measureAll], to prepare the respective
|
||||
/// measurement. These methods can be called any number of times.
|
||||
/// * Call [didMeasure] to indicate that you are done with the paragraph passed
|
||||
/// to the [willMeasure] method.
|
||||
///
|
||||
/// It is safe to reuse this object as long as paragraphs passed to the
|
||||
/// [measure] method have the same style.
|
||||
///
|
||||
/// The only stateless method provided by this class is [measureBoxesForRange]
|
||||
/// that doesn't rely on [willMeasure] and [didMeasure] lifecycle methods.
|
||||
///
|
||||
/// This class optimizes for plain text paragraphs, which should constitute the
|
||||
/// majority of paragraphs in typical apps.
|
||||
class ParagraphRuler {
|
||||
/// The only style that this [ParagraphRuler] measures text.
|
||||
final ParagraphGeometricStyle style;
|
||||
|
||||
/// A [RulerManager] owns the host DOM element that this ruler can add
|
||||
/// elements to.
|
||||
///
|
||||
/// The [rulerManager] keeps a cache of multiple [ParagraphRuler] instances,
|
||||
/// but a [ParagraphRuler] can only belong to one [RulerManager].
|
||||
final RulerManager rulerManager;
|
||||
|
||||
ParagraphRuler(this.style, this.rulerManager) {
|
||||
_configureSingleLineHostElements();
|
||||
_configureMinIntrinsicHostElements();
|
||||
_configureConstrainedHostElements();
|
||||
}
|
||||
|
||||
/// The alphabetic baseline of the paragraph being measured.
|
||||
double get alphabeticBaseline => _textHeightRuler.alphabeticBaseline;
|
||||
|
||||
// Elements used to measure single-line metrics.
|
||||
final html.DivElement _singleLineHost = html.DivElement();
|
||||
final TextDimensions singleLineDimensions =
|
||||
TextDimensions(html.ParagraphElement());
|
||||
|
||||
// Elements used to measure minIntrinsicWidth.
|
||||
final html.DivElement _minIntrinsicHost = html.DivElement();
|
||||
TextDimensions minIntrinsicDimensions =
|
||||
TextDimensions(html.ParagraphElement());
|
||||
|
||||
// Elements used to measure metrics under a width constraint.
|
||||
final html.DivElement _constrainedHost = html.DivElement();
|
||||
TextDimensions constrainedDimensions =
|
||||
TextDimensions(html.ParagraphElement());
|
||||
|
||||
// Elements used to measure the line-height metric.
|
||||
late final TextHeightRuler _textHeightRuler =
|
||||
TextHeightRuler(style.textHeightStyle, rulerManager);
|
||||
double get lineHeight {
|
||||
return _textHeightRuler.height;
|
||||
}
|
||||
|
||||
/// The number of times this ruler was used this frame.
|
||||
///
|
||||
/// This value is used to determine which rulers are rarely used and should be
|
||||
/// evicted from the ruler cache.
|
||||
int get hitCount => _hitCount;
|
||||
int _hitCount = 0;
|
||||
|
||||
/// This method should be called whenever this ruler is being used to perform
|
||||
/// measurements.
|
||||
///
|
||||
/// It increases the hit count of this ruler which is used when clearing the
|
||||
/// [rulerManager]'s cache to find the least used rulers.
|
||||
void hit() {
|
||||
_hitCount++;
|
||||
}
|
||||
|
||||
/// Resets the hit count back to zero.
|
||||
void resetHitCount() {
|
||||
_hitCount = 0;
|
||||
}
|
||||
|
||||
/// Makes sure this ruler is not used again after it has been disposed of,
|
||||
/// which would indicate a bug.
|
||||
@visibleForTesting
|
||||
bool get debugIsDisposed => _debugIsDisposed;
|
||||
bool _debugIsDisposed = false;
|
||||
|
||||
void _configureSingleLineHostElements() {
|
||||
_singleLineHost.style
|
||||
..visibility = 'hidden'
|
||||
..position = 'absolute'
|
||||
..top = '0' // this is important as baseline == probe.bottom
|
||||
..left = '0'
|
||||
..display = 'flex'
|
||||
..flexDirection = 'row'
|
||||
..alignItems = 'baseline'
|
||||
..margin = '0'
|
||||
..border = '0'
|
||||
..padding = '0';
|
||||
|
||||
if (assertionsEnabled) {
|
||||
_singleLineHost.setAttribute('data-ruler', 'single-line');
|
||||
}
|
||||
|
||||
singleLineDimensions.applyStyle(style);
|
||||
|
||||
// Force single-line (even if wider than screen) and preserve whitespaces.
|
||||
singleLineDimensions._element.style.whiteSpace = 'pre';
|
||||
|
||||
singleLineDimensions.appendToHost(_singleLineHost);
|
||||
rulerManager.addElement(_singleLineHost);
|
||||
}
|
||||
|
||||
void _configureMinIntrinsicHostElements() {
|
||||
// Configure min intrinsic host elements.
|
||||
_minIntrinsicHost.style
|
||||
..visibility = 'hidden'
|
||||
..position = 'absolute'
|
||||
..top = '0' // this is important as baseline == probe.bottom
|
||||
..left = '0'
|
||||
..display = 'flex'
|
||||
..flexDirection = 'row'
|
||||
..margin = '0'
|
||||
..border = '0'
|
||||
..padding = '0';
|
||||
|
||||
if (assertionsEnabled) {
|
||||
_minIntrinsicHost.setAttribute('data-ruler', 'min-intrinsic');
|
||||
}
|
||||
|
||||
minIntrinsicDimensions.applyStyle(style);
|
||||
|
||||
// "flex: 0" causes the paragraph element to shrink horizontally, exposing
|
||||
// its minimum intrinsic width.
|
||||
minIntrinsicDimensions._element.style
|
||||
..flex = '0'
|
||||
..display = 'inline'
|
||||
// Preserve newlines, wrap text, remove end of line spaces.
|
||||
// Not using pre-wrap here since end of line space hang measurement
|
||||
// changed in Chrome 77 Beta.
|
||||
..whiteSpace = 'pre-line';
|
||||
|
||||
_minIntrinsicHost.append(minIntrinsicDimensions._element);
|
||||
rulerManager.addElement(_minIntrinsicHost);
|
||||
}
|
||||
|
||||
void _configureConstrainedHostElements() {
|
||||
_constrainedHost.style
|
||||
..visibility = 'hidden'
|
||||
..position = 'absolute'
|
||||
..top = '0' // this is important as baseline == probe.bottom
|
||||
..left = '0'
|
||||
..display = 'flex'
|
||||
..flexDirection = 'row'
|
||||
..alignItems = 'baseline'
|
||||
..margin = '0'
|
||||
..border = '0'
|
||||
..padding = '0';
|
||||
|
||||
if (assertionsEnabled) {
|
||||
_constrainedHost.setAttribute('data-ruler', 'constrained');
|
||||
}
|
||||
|
||||
constrainedDimensions.applyStyle(style);
|
||||
final html.CssStyleDeclaration elementStyle =
|
||||
constrainedDimensions._element.style;
|
||||
elementStyle
|
||||
..display = 'block'
|
||||
..overflowWrap = 'break-word';
|
||||
|
||||
if (style.ellipsis != null) {
|
||||
elementStyle
|
||||
..overflow = 'hidden'
|
||||
..textOverflow = 'ellipsis';
|
||||
}
|
||||
|
||||
constrainedDimensions.appendToHost(_constrainedHost);
|
||||
rulerManager.addElement(_constrainedHost);
|
||||
}
|
||||
|
||||
/// The paragraph being measured.
|
||||
DomParagraph? _paragraph;
|
||||
|
||||
/// Prepares this ruler for measuring the given [paragraph].
|
||||
///
|
||||
/// This method must be called before calling any of the `measure*` methods.
|
||||
void willMeasure(DomParagraph paragraph) {
|
||||
assert(paragraph != null); // ignore: unnecessary_null_comparison
|
||||
assert(() {
|
||||
if (_paragraph != null) {
|
||||
throw Exception(
|
||||
'Attempted to reuse a $ParagraphRuler but it is currently '
|
||||
'measuring another paragraph ($_paragraph). It is possible that ');
|
||||
}
|
||||
return true;
|
||||
}());
|
||||
assert(paragraph.debugHasSameRootStyle(style));
|
||||
_paragraph = paragraph;
|
||||
}
|
||||
|
||||
/// Prepares all 3 measurements:
|
||||
/// 1. single line.
|
||||
/// 2. minimum intrinsic width.
|
||||
/// 3. constrained.
|
||||
void measureAll(ui.ParagraphConstraints constraints) {
|
||||
measureAsSingleLine();
|
||||
measureMinIntrinsicWidth();
|
||||
measureWithConstraints(constraints);
|
||||
}
|
||||
|
||||
/// Lays out the paragraph in a single line, giving it infinite amount of
|
||||
/// horizontal space.
|
||||
///
|
||||
/// Measures [width], [height], and [alphabeticBaseline].
|
||||
void measureAsSingleLine() {
|
||||
assert(!_debugIsDisposed);
|
||||
assert(_paragraph != null);
|
||||
|
||||
// HACK(mdebbar): TextField uses an empty string to measure the line height,
|
||||
// which doesn't work. So we need to replace it with a whitespace. The
|
||||
// correct fix would be to do line height and baseline measurements and
|
||||
// cache them separately.
|
||||
if (_paragraph!.plainText == '') {
|
||||
singleLineDimensions.updateTextToSpace();
|
||||
} else {
|
||||
singleLineDimensions.updateText(_paragraph!, style);
|
||||
}
|
||||
}
|
||||
|
||||
/// Lays out the paragraph inside a flex row and sets "flex: 0", which
|
||||
/// squeezes the paragraph, forcing it to occupy minimum intrinsic width.
|
||||
///
|
||||
/// Measures [width] and [height].
|
||||
void measureMinIntrinsicWidth() {
|
||||
assert(!_debugIsDisposed);
|
||||
assert(_paragraph != null);
|
||||
|
||||
minIntrinsicDimensions.updateText(_paragraph!, style);
|
||||
}
|
||||
|
||||
/// Lays out the paragraph giving it a width constraint.
|
||||
///
|
||||
/// Measures [width], [height], and [alphabeticBaseline].
|
||||
void measureWithConstraints(ui.ParagraphConstraints constraints) {
|
||||
assert(!_debugIsDisposed);
|
||||
assert(_paragraph != null);
|
||||
|
||||
constrainedDimensions.updateText(_paragraph!, style);
|
||||
|
||||
// The extra 0.5 is because sometimes the browser needs slightly more space
|
||||
// than the size it reports back. When that happens the text may be wrap
|
||||
// when we thought it didn't.
|
||||
constrainedDimensions.updateConstraintWidth(
|
||||
constraints.width + 0.5,
|
||||
style.ellipsis,
|
||||
);
|
||||
}
|
||||
|
||||
List<ui.TextBox> measurePlaceholderBoxes() {
|
||||
assert(!_debugIsDisposed);
|
||||
|
||||
final DomParagraph? paragraph = _paragraph;
|
||||
assert(paragraph != null);
|
||||
|
||||
if (paragraph!.placeholderCount == 0) {
|
||||
return const <ui.TextBox>[];
|
||||
}
|
||||
|
||||
final List<html.Element> placeholderElements =
|
||||
constrainedDimensions._element.querySelectorAll('.$placeholderClass');
|
||||
final List<ui.TextBox> boxes = <ui.TextBox>[];
|
||||
|
||||
for (final html.Element element in placeholderElements) {
|
||||
final html.Rectangle<num> rect = element.getBoundingClientRect();
|
||||
boxes.add(ui.TextBox.fromLTRBD(
|
||||
rect.left as double,
|
||||
rect.top as double,
|
||||
rect.right as double,
|
||||
rect.bottom as double,
|
||||
paragraph.textDirection,
|
||||
));
|
||||
}
|
||||
return boxes;
|
||||
}
|
||||
|
||||
/// Returns text position in a paragraph that contains multiple
|
||||
/// nested spans given an offset.
|
||||
int hitTest(ui.ParagraphConstraints constraints, ui.Offset offset) {
|
||||
measureWithConstraints(constraints);
|
||||
// Get paragraph element root used to measure constrainedDimensions.
|
||||
final html.HtmlElement el = constrainedDimensions._element;
|
||||
final List<html.Node> textNodes = <html.Node>[];
|
||||
// Collect all text nodes (breadth first traversal).
|
||||
// Since there is no api to get bounds of text nodes directly we work
|
||||
// upwards and measure span elements and finally the paragraph.
|
||||
_collectTextNodes(el.childNodes, textNodes);
|
||||
// Hit test spans starting from leaf nodes up (backwards).
|
||||
for (int i = textNodes.length - 1; i >= 0; i--) {
|
||||
final html.Node node = textNodes[i];
|
||||
// Check if offset is within client rect bounds of text node's
|
||||
// parent element.
|
||||
final html.Element parent = node.parentNode! as html.Element;
|
||||
final html.Rectangle<num> bounds = parent.getBoundingClientRect();
|
||||
final double dx = offset.dx;
|
||||
final double dy = offset.dy;
|
||||
if (dx >= bounds.left &&
|
||||
dx < bounds.right &&
|
||||
dy >= bounds.top &&
|
||||
dy < bounds.bottom) {
|
||||
// We found the element bounds that contains offset.
|
||||
// Calculate text position for this node.
|
||||
return _countTextPosition(el.childNodes, textNodes[i]);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void _collectTextNodes(Iterable<html.Node> nodes, List<html.Node> textNodes) {
|
||||
if (nodes.isEmpty) {
|
||||
return;
|
||||
}
|
||||
final List<html.Node> childNodes = <html.Node>[];
|
||||
for (final html.Node node in nodes) {
|
||||
if (node.nodeType == html.Node.TEXT_NODE) {
|
||||
textNodes.add(node);
|
||||
}
|
||||
childNodes.addAll(node.childNodes);
|
||||
}
|
||||
_collectTextNodes(childNodes, textNodes);
|
||||
}
|
||||
|
||||
int _countTextPosition(List<html.Node> nodes, html.Node endNode) {
|
||||
int position = 0;
|
||||
final List<html.Node> stack = nodes.reversed.toList();
|
||||
while (true) {
|
||||
final html.Node node = stack.removeLast();
|
||||
stack.addAll(node.childNodes.reversed);
|
||||
if (node == endNode) {
|
||||
break;
|
||||
}
|
||||
if (node.nodeType == html.Node.TEXT_NODE) {
|
||||
position += node.text!.length;
|
||||
}
|
||||
}
|
||||
return position;
|
||||
}
|
||||
|
||||
/// Performs clean-up after a measurement is done, preparing this ruler for
|
||||
/// a future reuse.
|
||||
///
|
||||
/// Call this method immediately after calling `measure*` methods for a
|
||||
/// particular [paragraph]. This ruler is not reusable until [didMeasure] is
|
||||
/// called.
|
||||
void didMeasure() {
|
||||
assert(_paragraph != null);
|
||||
// Remove any rich text we set during layout for the following reasons:
|
||||
// - there won't be any text for the browser to lay out when we commit the
|
||||
// current frame.
|
||||
// - this keeps the cost of removing content together with the measurement
|
||||
// in the profile. Otherwise, the cost of removing will be paid by a
|
||||
// random next paragraph measured in the future, and make the performance
|
||||
// profile hard to understand.
|
||||
//
|
||||
// We do not do this for plain text, because replacing plain text is more
|
||||
// expensive than paying the cost of the DOM mutation to clean it.
|
||||
if (_paragraph!.plainText == null) {
|
||||
domRenderer
|
||||
..clearDom(singleLineDimensions._element)
|
||||
..clearDom(minIntrinsicDimensions._element)
|
||||
..clearDom(constrainedDimensions._element);
|
||||
}
|
||||
_paragraph = null;
|
||||
}
|
||||
|
||||
/// Performs stateless measurement of text boxes for a given range of text.
|
||||
///
|
||||
/// This method doesn't depend on [willMeasure] and [didMeasure] lifecycle
|
||||
/// methods.
|
||||
List<ui.TextBox> measureBoxesForRange(
|
||||
String plainText,
|
||||
ui.ParagraphConstraints constraints, {
|
||||
required int start,
|
||||
required int end,
|
||||
required double alignOffset,
|
||||
required ui.TextDirection textDirection,
|
||||
}) {
|
||||
assert(!_debugIsDisposed);
|
||||
assert(start >= 0 && start <= plainText.length);
|
||||
assert(end >= 0 && end <= plainText.length);
|
||||
assert(start <= end);
|
||||
|
||||
final String before = plainText.substring(0, start);
|
||||
final String rangeText = plainText.substring(start, end);
|
||||
final String after = plainText.substring(end);
|
||||
|
||||
final html.SpanElement rangeSpan = html.SpanElement()..text = rangeText;
|
||||
|
||||
// Setup the [ruler.constrainedDimensions] element to be used for measurement.
|
||||
domRenderer.clearDom(constrainedDimensions._element);
|
||||
constrainedDimensions._element
|
||||
..appendText(before)
|
||||
..append(rangeSpan)
|
||||
..appendText(after);
|
||||
constrainedDimensions.updateConstraintWidth(constraints.width, null);
|
||||
|
||||
// Measure the rects of [rangeSpan].
|
||||
final List<html.Rectangle<num>> clientRects = rangeSpan.getClientRects();
|
||||
final List<ui.TextBox> boxes = <ui.TextBox>[];
|
||||
|
||||
final double maxLinesLimit = style.maxLines == null
|
||||
? double.infinity
|
||||
: style.maxLines! * lineHeight;
|
||||
|
||||
html.Rectangle<num>? previousRect;
|
||||
for (final html.Rectangle<num> rect in clientRects) {
|
||||
// If [rect] is an empty box on the same line as the previous box, don't
|
||||
// include it in the result.
|
||||
if (rect.top == previousRect?.top && rect.left == rect.right) {
|
||||
continue;
|
||||
}
|
||||
// As soon as we go beyond [maxLines], stop adding boxes.
|
||||
if (rect.top >= maxLinesLimit) {
|
||||
break;
|
||||
}
|
||||
|
||||
boxes.add(ui.TextBox.fromLTRBD(
|
||||
rect.left.toDouble() + alignOffset,
|
||||
rect.top as double,
|
||||
rect.right.toDouble() + alignOffset,
|
||||
rect.bottom as double,
|
||||
textDirection,
|
||||
));
|
||||
previousRect = rect;
|
||||
}
|
||||
|
||||
// Cleanup after measuring the boxes.
|
||||
domRenderer.clearDom(constrainedDimensions._element);
|
||||
return boxes;
|
||||
}
|
||||
|
||||
/// Detaches this ruler from the DOM and makes it unusable for future
|
||||
/// measurements.
|
||||
///
|
||||
/// Disposed rulers should be garbage collected after calling this method.
|
||||
void dispose() {
|
||||
assert(() {
|
||||
if (_paragraph != null) {
|
||||
throw Exception('Attempted to dispose of a ruler in the middle of '
|
||||
'measurement. This is likely a bug in the framework.');
|
||||
}
|
||||
return true;
|
||||
}());
|
||||
_singleLineHost.remove();
|
||||
_minIntrinsicHost.remove();
|
||||
_constrainedHost.remove();
|
||||
_textHeightRuler.dispose();
|
||||
assert(() {
|
||||
_debugIsDisposed = true;
|
||||
return true;
|
||||
}());
|
||||
}
|
||||
|
||||
// Bounded cache for text measurement for a particular width constraint.
|
||||
Map<String?, List<MeasurementResult?>> _measurementCache =
|
||||
<String?, List<MeasurementResult?>>{};
|
||||
// Mru list for cache.
|
||||
final List<String?> _mruList = <String?>[];
|
||||
static const int _cacheLimit = 2400;
|
||||
// Number of items to evict when cache limit is reached.
|
||||
static const int _cacheBlockFactor = 100;
|
||||
// Number of constraint results per unique text item.
|
||||
// This limit prevents growth during animation where the size of a container
|
||||
// is changing.
|
||||
static const int _constraintCacheSize = 8;
|
||||
|
||||
void cacheMeasurement(DomParagraph paragraph, MeasurementResult? item) {
|
||||
final String? plainText = paragraph.plainText;
|
||||
final List<MeasurementResult?> constraintCache =
|
||||
_measurementCache[plainText] ??= <MeasurementResult?>[];
|
||||
constraintCache.add(item);
|
||||
if (constraintCache.length > _constraintCacheSize) {
|
||||
constraintCache.removeAt(0);
|
||||
}
|
||||
_mruList.add(plainText);
|
||||
if (_mruList.length > _cacheLimit) {
|
||||
// Evict a range.
|
||||
for (int i = 0; i < _cacheBlockFactor; i++) {
|
||||
_measurementCache.remove(_mruList[i]);
|
||||
}
|
||||
_mruList.removeRange(0, _cacheBlockFactor);
|
||||
}
|
||||
}
|
||||
|
||||
MeasurementResult? cacheLookup(
|
||||
DomParagraph paragraph, ui.ParagraphConstraints constraints) {
|
||||
final String? plainText = paragraph.plainText;
|
||||
if (plainText == null) {
|
||||
// Multi span paragraph, do not use cache item.
|
||||
return null;
|
||||
}
|
||||
final List<MeasurementResult?>? constraintCache =
|
||||
_measurementCache[plainText];
|
||||
if (constraintCache == null) {
|
||||
return null;
|
||||
}
|
||||
final int len = constraintCache.length;
|
||||
for (int i = 0; i < len; i++) {
|
||||
final MeasurementResult item = constraintCache[i]!;
|
||||
if (item.constraintWidth == constraints.width &&
|
||||
item.textAlign == paragraph.textAlign &&
|
||||
item.textDirection == paragraph.textDirection) {
|
||||
return item;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// The result that contains all measurements of a paragraph at the given
|
||||
/// constraint width.
|
||||
@immutable
|
||||
class MeasurementResult {
|
||||
/// The width that was given as a constraint when the paragraph was laid out.
|
||||
final double constraintWidth;
|
||||
|
||||
/// Whether the paragraph can fit in a single line given [constraintWidth].
|
||||
final bool isSingleLine;
|
||||
|
||||
/// The amount of horizontal space the paragraph occupies.
|
||||
final double width;
|
||||
|
||||
/// The amount of vertical space the paragraph occupies.
|
||||
final double height;
|
||||
|
||||
/// {@macro dart.ui.paragraph.naturalHeight}
|
||||
///
|
||||
/// When [ParagraphGeometricStyle.maxLines] is null, [naturalHeight] and
|
||||
/// [height] should be equal.
|
||||
final double naturalHeight;
|
||||
|
||||
/// The amount of vertical space each line of the paragraph occupies.
|
||||
///
|
||||
/// In some cases, measuring [lineHeight] is unnecessary, so it's nullable. If
|
||||
/// present, it should be equal to [height] when [isSingleLine] is true.
|
||||
final double? lineHeight;
|
||||
|
||||
/// {@macro dart.ui.paragraph.minIntrinsicWidth}
|
||||
final double minIntrinsicWidth;
|
||||
|
||||
/// {@macro dart.ui.paragraph.maxIntrinsicWidth}
|
||||
final double maxIntrinsicWidth;
|
||||
|
||||
/// {@macro dart.ui.paragraph.alphabeticBaseline}
|
||||
final double alphabeticBaseline;
|
||||
|
||||
/// {@macro dart.ui.paragraph.ideographicBaseline}
|
||||
final double ideographicBaseline;
|
||||
|
||||
/// The full list of [EngineLineMetrics] that describe in detail the various metrics
|
||||
/// of each laid out line.
|
||||
final List<EngineLineMetrics>? lines;
|
||||
|
||||
final List<ui.TextBox> placeholderBoxes;
|
||||
|
||||
/// The text align value of the paragraph.
|
||||
final ui.TextAlign textAlign;
|
||||
|
||||
/// The text direction of the paragraph.
|
||||
final ui.TextDirection textDirection;
|
||||
|
||||
const MeasurementResult(
|
||||
this.constraintWidth, {
|
||||
required this.isSingleLine,
|
||||
required this.width,
|
||||
required this.height,
|
||||
required this.naturalHeight,
|
||||
required this.lineHeight,
|
||||
required this.minIntrinsicWidth,
|
||||
required this.maxIntrinsicWidth,
|
||||
required this.alphabeticBaseline,
|
||||
required this.ideographicBaseline,
|
||||
required this.lines,
|
||||
required this.placeholderBoxes,
|
||||
required ui.TextAlign? textAlign,
|
||||
required ui.TextDirection? textDirection,
|
||||
}) : assert(constraintWidth != null), // ignore: unnecessary_null_comparison
|
||||
assert(isSingleLine != null), // ignore: unnecessary_null_comparison
|
||||
assert(width != null), // ignore: unnecessary_null_comparison
|
||||
assert(height != null), // ignore: unnecessary_null_comparison
|
||||
assert(naturalHeight != null), // ignore: unnecessary_null_comparison
|
||||
assert(minIntrinsicWidth != null), // ignore: unnecessary_null_comparison
|
||||
assert(maxIntrinsicWidth != null), // ignore: unnecessary_null_comparison
|
||||
assert(alphabeticBaseline != null), // ignore: unnecessary_null_comparison
|
||||
assert(ideographicBaseline != null), // ignore: unnecessary_null_comparison
|
||||
this.textAlign = textAlign ?? ui.TextAlign.start,// ignore: unnecessary_this
|
||||
this.textDirection = textDirection ?? ui.TextDirection.ltr;// ignore: unnecessary_this
|
||||
}
|
||||
|
||||
@@ -19,53 +19,15 @@ class WebExperiments {
|
||||
}
|
||||
|
||||
static WebExperiments ensureInitialized() {
|
||||
return WebExperiments.instance ?? (WebExperiments.instance = WebExperiments._());
|
||||
return WebExperiments.instance ??
|
||||
(WebExperiments.instance = WebExperiments._());
|
||||
}
|
||||
|
||||
static WebExperiments? instance;
|
||||
|
||||
/// Experiment flag for using canvas-based text measurement.
|
||||
bool get useCanvasText => _useCanvasText;
|
||||
set useCanvasText(bool? enabled) {
|
||||
_useCanvasText = enabled ?? _defaultUseCanvasText;
|
||||
}
|
||||
|
||||
static const bool _defaultUseCanvasText = bool.fromEnvironment(
|
||||
'FLUTTER_WEB_USE_EXPERIMENTAL_CANVAS_TEXT',
|
||||
defaultValue: true,
|
||||
);
|
||||
|
||||
bool _useCanvasText = _defaultUseCanvasText;
|
||||
|
||||
// TODO(mdebbar): Clean up https://github.com/flutter/flutter/issues/71952
|
||||
/// Experiment flag for using canvas-based measurement for rich text.
|
||||
bool get useCanvasRichText => _useCanvasRichText;
|
||||
set useCanvasRichText(bool? enabled) {
|
||||
_useCanvasRichText = enabled ?? _defaultUseCanvasRichText;
|
||||
}
|
||||
|
||||
static const bool _defaultUseCanvasRichText = bool.fromEnvironment(
|
||||
'FLUTTER_WEB_USE_EXPERIMENTAL_CANVAS_RICH_TEXT',
|
||||
defaultValue: true,
|
||||
);
|
||||
|
||||
bool _useCanvasRichText = _defaultUseCanvasRichText;
|
||||
|
||||
/// Reset all experimental flags to their default values.
|
||||
void reset() {
|
||||
_useCanvasText = _defaultUseCanvasText;
|
||||
_useCanvasRichText = _defaultUseCanvasRichText;
|
||||
}
|
||||
void reset() {}
|
||||
|
||||
/// Used to enable/disable experimental flags in the web engine.
|
||||
void updateExperiment(String name, bool? enabled) {
|
||||
switch (name) {
|
||||
case 'useCanvasText':
|
||||
useCanvasText = enabled;
|
||||
break;
|
||||
case 'useCanvasRichText':
|
||||
useCanvasRichText = enabled;
|
||||
break;
|
||||
}
|
||||
}
|
||||
void updateExperiment(String name, bool? enabled) {}
|
||||
}
|
||||
|
||||
@@ -706,12 +706,8 @@ abstract class ParagraphBuilder {
|
||||
factory ParagraphBuilder(ParagraphStyle style) {
|
||||
if (engine.useCanvasKit) {
|
||||
return engine.CkParagraphBuilder(style);
|
||||
} else if (engine.WebExperiments.instance!.useCanvasRichText) {
|
||||
return engine.CanvasParagraphBuilder(
|
||||
style as engine.EngineParagraphStyle);
|
||||
} else {
|
||||
return engine.DomParagraphBuilder(style as engine.EngineParagraphStyle);
|
||||
}
|
||||
return engine.CanvasParagraphBuilder(style as engine.EngineParagraphStyle);
|
||||
}
|
||||
void pushStyle(TextStyle style);
|
||||
void pop();
|
||||
|
||||
@@ -468,7 +468,10 @@ void testMain() {
|
||||
final bool useOffset = int.tryParse(char) == null;
|
||||
final EnginePictureRecorder recorder = EnginePictureRecorder();
|
||||
final RecordingCanvas canvas = recorder.beginRecording(const ui.Rect.fromLTRB(0, 0, 400, 400));
|
||||
final DomParagraph paragraph = (DomParagraphBuilder(EngineParagraphStyle())..addText(char)).build() as DomParagraph;
|
||||
final ui.Paragraph paragraph = (ui.ParagraphBuilder(ui.ParagraphStyle())
|
||||
..pushStyle(ui.TextStyle(decoration: ui.TextDecoration.lineThrough))
|
||||
..addText(char))
|
||||
.build();
|
||||
paragraph.layout(const ui.ParagraphConstraints(width: 1000));
|
||||
canvas.drawParagraph(paragraph, ui.Offset.zero);
|
||||
final ui.EngineLayer newLayer = useOffset
|
||||
|
||||
@@ -9,9 +9,6 @@ import 'package:test/bootstrap/browser.dart';
|
||||
import 'package:test/test.dart';
|
||||
import 'package:ui/src/engine/web_experiments.dart';
|
||||
|
||||
const bool _defaultUseCanvasText = true;
|
||||
const bool _defaultUseCanvasRichText = true;
|
||||
|
||||
void main() {
|
||||
internalBootstrapBrowserTest(() => testMain);
|
||||
}
|
||||
@@ -25,70 +22,6 @@ void testMain() {
|
||||
WebExperiments.instance!.reset();
|
||||
});
|
||||
|
||||
test('default web experiment values', () {
|
||||
expect(WebExperiments.instance!.useCanvasText, _defaultUseCanvasText);
|
||||
expect(WebExperiments.instance!.useCanvasRichText, _defaultUseCanvasRichText);
|
||||
});
|
||||
|
||||
test('can turn on/off web experiments', () {
|
||||
WebExperiments.instance!.updateExperiment('useCanvasText', true);
|
||||
WebExperiments.instance!.updateExperiment('useCanvasRichText', true);
|
||||
expect(WebExperiments.instance!.useCanvasText, isTrue);
|
||||
expect(WebExperiments.instance!.useCanvasRichText, isTrue);
|
||||
|
||||
WebExperiments.instance!.updateExperiment('useCanvasText', false);
|
||||
WebExperiments.instance!.updateExperiment('useCanvasRichText', false);
|
||||
expect(WebExperiments.instance!.useCanvasText, isFalse);
|
||||
expect(WebExperiments.instance!.useCanvasRichText, isFalse);
|
||||
|
||||
WebExperiments.instance!.updateExperiment('useCanvasText', null);
|
||||
WebExperiments.instance!.updateExperiment('useCanvasRichText', null);
|
||||
// Goes back to default value.
|
||||
expect(WebExperiments.instance!.useCanvasText, _defaultUseCanvasText);
|
||||
expect(WebExperiments.instance!.useCanvasRichText, _defaultUseCanvasRichText);
|
||||
});
|
||||
|
||||
test('ignores unknown experiments', () {
|
||||
expect(WebExperiments.instance!.useCanvasText, _defaultUseCanvasText);
|
||||
expect(WebExperiments.instance!.useCanvasRichText, _defaultUseCanvasRichText);
|
||||
WebExperiments.instance!.updateExperiment('foobarbazqux', true);
|
||||
expect(WebExperiments.instance!.useCanvasText, _defaultUseCanvasText);
|
||||
expect(WebExperiments.instance!.useCanvasRichText, _defaultUseCanvasRichText);
|
||||
WebExperiments.instance!.updateExperiment('foobarbazqux', false);
|
||||
expect(WebExperiments.instance!.useCanvasText, _defaultUseCanvasText);
|
||||
expect(WebExperiments.instance!.useCanvasRichText, _defaultUseCanvasRichText);
|
||||
});
|
||||
|
||||
test('can reset web experiments', () {
|
||||
WebExperiments.instance!.updateExperiment('useCanvasText', false);
|
||||
WebExperiments.instance!.updateExperiment('useCanvasRichText', false);
|
||||
WebExperiments.instance!.reset();
|
||||
expect(WebExperiments.instance!.useCanvasText, _defaultUseCanvasText);
|
||||
expect(WebExperiments.instance!.useCanvasRichText, _defaultUseCanvasRichText);
|
||||
|
||||
WebExperiments.instance!.updateExperiment('useCanvasText', false);
|
||||
WebExperiments.instance!.updateExperiment('useCanvasRichText', false);
|
||||
WebExperiments.instance!.updateExperiment('foobarbazqux', true);
|
||||
WebExperiments.instance!.reset();
|
||||
expect(WebExperiments.instance!.useCanvasText, _defaultUseCanvasText);
|
||||
expect(WebExperiments.instance!.useCanvasRichText, _defaultUseCanvasRichText);
|
||||
});
|
||||
|
||||
test('js interop also works', () {
|
||||
expect(WebExperiments.instance!.useCanvasText, _defaultUseCanvasText);
|
||||
expect(WebExperiments.instance!.useCanvasRichText, _defaultUseCanvasRichText);
|
||||
|
||||
expect(() => jsUpdateExperiment('useCanvasText', true), returnsNormally);
|
||||
expect(() => jsUpdateExperiment('useCanvasRichText', true), returnsNormally);
|
||||
expect(WebExperiments.instance!.useCanvasText, isTrue);
|
||||
expect(WebExperiments.instance!.useCanvasRichText, isTrue);
|
||||
|
||||
expect(() => jsUpdateExperiment('useCanvasText', null), returnsNormally);
|
||||
expect(() => jsUpdateExperiment('useCanvasRichText', null), returnsNormally);
|
||||
expect(WebExperiments.instance!.useCanvasText, _defaultUseCanvasText);
|
||||
expect(WebExperiments.instance!.useCanvasRichText, _defaultUseCanvasRichText);
|
||||
});
|
||||
|
||||
test('js interop throws on wrong type', () {
|
||||
expect(() => jsUpdateExperiment(123, true), throwsA(anything));
|
||||
expect(() => jsUpdateExperiment('foo', 123), throwsA(anything));
|
||||
|
||||
@@ -818,10 +818,12 @@ void _testCullRectComputation() {
|
||||
'renders clipped text with high quality',
|
||||
() async {
|
||||
// To reproduce blurriness we need real clipping.
|
||||
final DomParagraph paragraph =
|
||||
(DomParagraphBuilder(EngineParagraphStyle(fontFamily: 'Roboto'))
|
||||
final CanvasParagraph paragraph =
|
||||
(ui.ParagraphBuilder(ui.ParagraphStyle(fontFamily: 'Roboto'))
|
||||
// Use a decoration to force rendering in DOM mode.
|
||||
..pushStyle(ui.TextStyle(decoration: ui.TextDecoration.lineThrough, decorationColor: const ui.Color(0x00000000)))
|
||||
..addText('Am I blurry?'))
|
||||
.build() as DomParagraph;
|
||||
.build() as CanvasParagraph;
|
||||
paragraph.layout(const ui.ParagraphConstraints(width: 1000));
|
||||
|
||||
final ui.Rect canvasSize = ui.Rect.fromLTRB(
|
||||
@@ -843,7 +845,7 @@ void _testCullRectComputation() {
|
||||
final RecordingCanvas canvas = recorder.beginRecording(outerClip);
|
||||
canvas.drawParagraph(paragraph, const ui.Offset(8.5, 8.5));
|
||||
final ui.Picture picture = recorder.endRecording();
|
||||
expect(canvas.renderStrategy.hasArbitraryPaint, isFalse);
|
||||
expect(paragraph.drawOnCanvas, isFalse);
|
||||
|
||||
builder.addPicture(
|
||||
ui.Offset.zero,
|
||||
@@ -857,7 +859,7 @@ void _testCullRectComputation() {
|
||||
final RecordingCanvas canvas = recorder.beginRecording(innerClip);
|
||||
canvas.drawParagraph(paragraph, ui.Offset(8.5, 8.5 + innerClip.top));
|
||||
final ui.Picture picture = recorder.endRecording();
|
||||
expect(canvas.renderStrategy.hasArbitraryPaint, isFalse);
|
||||
expect(paragraph.drawOnCanvas, isFalse);
|
||||
|
||||
builder.addPicture(
|
||||
ui.Offset.zero,
|
||||
|
||||
@@ -13,10 +13,6 @@ import 'text_scuba.dart';
|
||||
typedef CanvasTest = FutureOr<void> Function(EngineCanvas canvas);
|
||||
|
||||
const String threeLines = 'First\nSecond\nThird';
|
||||
const String veryLongWithShortPrefix =
|
||||
'Lorem ipsum dolor\nsit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
|
||||
const String veryLongWithShortSuffix =
|
||||
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et\ndolore magna aliqua.';
|
||||
const String veryLong =
|
||||
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
|
||||
const String longUnbreakable = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
|
||||
@@ -30,18 +26,8 @@ Future<void> testMain() async {
|
||||
viewportSize: const Size(800, 800),
|
||||
);
|
||||
|
||||
final TextStyle warningStyle = TextStyle(
|
||||
color: const Color(0xFFFF0000),
|
||||
fontFamily: 'Roboto',
|
||||
fontSize: 10,
|
||||
);
|
||||
|
||||
setUpStableTestFonts();
|
||||
|
||||
EngineParagraph warning(String text) {
|
||||
return paragraph(text, textStyle: warningStyle);
|
||||
}
|
||||
|
||||
testEachCanvas('maxLines clipping', (EngineCanvas canvas) {
|
||||
Offset offset = Offset.zero;
|
||||
EngineParagraph p;
|
||||
@@ -69,93 +55,4 @@ Future<void> testMain() async {
|
||||
|
||||
return scuba.diffCanvasScreenshot(canvas, 'text_max_lines');
|
||||
});
|
||||
|
||||
testEachCanvas('maxLines with overflow', (EngineCanvas canvas) {
|
||||
Offset offset = Offset.zero;
|
||||
EngineParagraph p;
|
||||
|
||||
// Only the first line is rendered with no ellipsis because the first line
|
||||
// doesn't overflow.
|
||||
p = paragraph(
|
||||
threeLines,
|
||||
paragraphStyle: ParagraphStyle(ellipsis: '...'),
|
||||
);
|
||||
canvas.drawParagraph(p, offset);
|
||||
offset = offset.translate(0, p.height + 10);
|
||||
|
||||
// The first two lines are rendered with an ellipsis on the 2nd line.
|
||||
p = paragraph(
|
||||
veryLongWithShortPrefix,
|
||||
paragraphStyle: ParagraphStyle(ellipsis: '...'),
|
||||
maxWidth: 200,
|
||||
);
|
||||
canvas.drawParagraph(p, offset);
|
||||
offset = offset.translate(0, p.height + 10);
|
||||
|
||||
// Only the first line is rendered with an ellipsis.
|
||||
if (!WebExperiments.instance!.useCanvasText) {
|
||||
// This is now correct with the canvas-based measurement, so we shouldn't
|
||||
// print the "(wrong)" warning.
|
||||
p = warning('(wrong)');
|
||||
canvas.drawParagraph(p, offset);
|
||||
offset = offset.translate(0, p.height);
|
||||
}
|
||||
p = paragraph(
|
||||
veryLongWithShortSuffix,
|
||||
paragraphStyle: ParagraphStyle(ellipsis: '...'),
|
||||
maxWidth: 200,
|
||||
);
|
||||
canvas.drawParagraph(p, offset);
|
||||
offset = offset.translate(0, p.height + 10);
|
||||
|
||||
// Only the first two lines are rendered and the ellipsis appears on the 2nd
|
||||
// line.
|
||||
if (!WebExperiments.instance!.useCanvasText) {
|
||||
// This is now correct with the canvas-based measurement, so we shouldn't
|
||||
// print the "(wrong)" warning.
|
||||
p = warning('(wrong)');
|
||||
canvas.drawParagraph(p, offset);
|
||||
offset = offset.translate(0, p.height);
|
||||
}
|
||||
p = paragraph(
|
||||
veryLong,
|
||||
paragraphStyle: ParagraphStyle(maxLines: 2, ellipsis: '...'),
|
||||
maxWidth: 200,
|
||||
);
|
||||
canvas.drawParagraph(p, offset);
|
||||
offset = offset.translate(0, p.height + 10);
|
||||
|
||||
return scuba.diffCanvasScreenshot(canvas, 'text_max_lines_with_ellipsis');
|
||||
});
|
||||
|
||||
testEachCanvas('long unbreakable text', (EngineCanvas canvas) {
|
||||
Offset offset = Offset.zero;
|
||||
EngineParagraph p;
|
||||
|
||||
// The whole line is rendered unbroken when there are no constraints.
|
||||
p = paragraph(longUnbreakable);
|
||||
canvas.drawParagraph(p, offset);
|
||||
offset = offset.translate(0, p.height + 10);
|
||||
|
||||
// The whole line is rendered with an ellipsis.
|
||||
p = paragraph(
|
||||
longUnbreakable,
|
||||
paragraphStyle: ParagraphStyle(ellipsis: '...'),
|
||||
maxWidth: 200,
|
||||
);
|
||||
canvas.drawParagraph(p, offset);
|
||||
offset = offset.translate(0, p.height + 10);
|
||||
|
||||
// The text is broken into multiple lines.
|
||||
p = paragraph(longUnbreakable, maxWidth: 200);
|
||||
canvas.drawParagraph(p, offset);
|
||||
offset = offset.translate(0, p.height + 10);
|
||||
|
||||
// Very narrow constraint (less than one character's width).
|
||||
p = paragraph('AA', maxWidth: 7);
|
||||
canvas.drawParagraph(p, offset);
|
||||
offset = offset.translate(0, p.height + 10);
|
||||
|
||||
return scuba.diffCanvasScreenshot(canvas, 'text_long_unbreakable');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ class EngineScubaTester {
|
||||
sceneElement.append(canvas.rootElement);
|
||||
html.document.body!.append(sceneElement);
|
||||
String screenshotName = '${fileName}_${canvas.runtimeType}';
|
||||
if (WebExperiments.instance!.useCanvasText) {
|
||||
if (canvas is BitmapCanvas) {
|
||||
screenshotName += '+canvas_measurement';
|
||||
}
|
||||
await diffScreenshot(
|
||||
@@ -94,41 +94,11 @@ typedef CanvasTest = FutureOr<void> Function(EngineCanvas canvas);
|
||||
void testEachCanvas(String description, CanvasTest body,
|
||||
{double? maxDiffRate}) {
|
||||
const ui.Rect bounds = ui.Rect.fromLTWH(0, 0, 600, 800);
|
||||
test('$description (bitmap)', () {
|
||||
try {
|
||||
TextMeasurementService.initialize(rulerCacheCapacity: 2);
|
||||
WebExperiments.instance!.useCanvasText = false;
|
||||
WebExperiments.instance!.useCanvasRichText = false;
|
||||
return body(BitmapCanvas(bounds, RenderStrategy()));
|
||||
} finally {
|
||||
WebExperiments.instance!.useCanvasText = null;
|
||||
WebExperiments.instance!.useCanvasRichText = null;
|
||||
TextMeasurementService.clearCache();
|
||||
}
|
||||
});
|
||||
test('$description (bitmap + canvas measurement)', () async {
|
||||
try {
|
||||
TextMeasurementService.initialize(rulerCacheCapacity: 2);
|
||||
WebExperiments.instance!.useCanvasText = true;
|
||||
WebExperiments.instance!.useCanvasRichText = false;
|
||||
await body(BitmapCanvas(bounds, RenderStrategy()));
|
||||
} finally {
|
||||
WebExperiments.instance!.useCanvasText = null;
|
||||
WebExperiments.instance!.useCanvasRichText = null;
|
||||
TextMeasurementService.clearCache();
|
||||
}
|
||||
return body(BitmapCanvas(bounds, RenderStrategy()));
|
||||
});
|
||||
test('$description (dom)', () {
|
||||
try {
|
||||
TextMeasurementService.initialize(rulerCacheCapacity: 2);
|
||||
WebExperiments.instance!.useCanvasText = false;
|
||||
WebExperiments.instance!.useCanvasRichText = false;
|
||||
return body(DomCanvas(domRenderer.createElement('flt-picture')));
|
||||
} finally {
|
||||
WebExperiments.instance!.useCanvasText = null;
|
||||
WebExperiments.instance!.useCanvasRichText = null;
|
||||
TextMeasurementService.clearCache();
|
||||
}
|
||||
return body(DomCanvas(domRenderer.createElement('flt-picture')));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,248 +0,0 @@
|
||||
// Copyright 2013 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:test/bootstrap/browser.dart';
|
||||
import 'package:ui/src/engine.dart';
|
||||
import 'package:ui/ui.dart';
|
||||
|
||||
import 'text_scuba.dart';
|
||||
|
||||
void main() {
|
||||
internalBootstrapBrowserTest(() => testMain);
|
||||
}
|
||||
|
||||
Future<void> testMain() async {
|
||||
final EngineScubaTester scuba = await EngineScubaTester.initialize(
|
||||
viewportSize: const Size(800, 800),
|
||||
);
|
||||
|
||||
setUpStableTestFonts();
|
||||
|
||||
void drawLetterAndWordSpacing(EngineCanvas canvas) {
|
||||
Offset offset = Offset.zero;
|
||||
|
||||
for (double spacing = 0; spacing < 15; spacing += 5) {
|
||||
canvas.drawParagraph(
|
||||
paragraph('HelloWorld',
|
||||
textStyle: TextStyle(
|
||||
color: const Color(0xFF000000),
|
||||
decoration: TextDecoration.none,
|
||||
fontFamily: 'Roboto',
|
||||
fontSize: 30,
|
||||
letterSpacing: spacing)),
|
||||
offset,
|
||||
);
|
||||
offset = offset.translate(0, 40);
|
||||
}
|
||||
for (double spacing = 0; spacing < 30; spacing += 10) {
|
||||
final TextStyle textStyle = TextStyle(
|
||||
color: const Color(0xFF00FF00),
|
||||
decoration: TextDecoration.none,
|
||||
fontFamily: 'Roboto',
|
||||
fontSize: 30,
|
||||
wordSpacing: spacing);
|
||||
canvas.drawParagraph(
|
||||
paragraph('Hello World', textStyle: textStyle, maxWidth: 600),
|
||||
offset,
|
||||
);
|
||||
offset = offset.translate(0, 40);
|
||||
}
|
||||
}
|
||||
|
||||
testEachCanvas('draws text with letter/word spacing', (EngineCanvas canvas) {
|
||||
drawLetterAndWordSpacing(canvas);
|
||||
return scuba.diffCanvasScreenshot(
|
||||
canvas, 'paint_bounds_for_text_style_letter_spacing');
|
||||
});
|
||||
|
||||
void drawTextDecorationStyle(EngineCanvas canvas) {
|
||||
final List<TextDecorationStyle> decorationStyles = <TextDecorationStyle>[
|
||||
TextDecorationStyle.solid,
|
||||
TextDecorationStyle.double,
|
||||
TextDecorationStyle.dotted,
|
||||
TextDecorationStyle.dashed,
|
||||
TextDecorationStyle.wavy,
|
||||
];
|
||||
|
||||
Offset offset = Offset.zero;
|
||||
|
||||
for (final TextDecorationStyle decorationStyle in decorationStyles) {
|
||||
final TextStyle textStyle = TextStyle(
|
||||
color: const Color.fromRGBO(50, 50, 255, 1.0),
|
||||
decoration: TextDecoration.underline,
|
||||
decorationStyle: decorationStyle,
|
||||
decorationColor: const Color.fromRGBO(50, 50, 50, 1.0),
|
||||
fontFamily: 'Roboto',
|
||||
fontSize: 30,
|
||||
);
|
||||
canvas.drawParagraph(
|
||||
paragraph('Hello World', textStyle: textStyle, maxWidth: 600),
|
||||
offset,
|
||||
);
|
||||
offset = offset.translate(0, 40);
|
||||
}
|
||||
}
|
||||
|
||||
testEachCanvas('draws text decoration style', (EngineCanvas canvas) {
|
||||
drawTextDecorationStyle(canvas);
|
||||
return scuba.diffCanvasScreenshot(
|
||||
canvas, 'paint_bounds_for_text_decorationStyle');
|
||||
});
|
||||
|
||||
void drawTextDecoration(EngineCanvas canvas) {
|
||||
final List<TextDecoration> decorations = <TextDecoration>[
|
||||
TextDecoration.overline,
|
||||
TextDecoration.underline,
|
||||
TextDecoration.combine(<TextDecoration>[
|
||||
TextDecoration.underline,
|
||||
TextDecoration.lineThrough
|
||||
]),
|
||||
TextDecoration.combine(
|
||||
<TextDecoration>[TextDecoration.underline, TextDecoration.overline]),
|
||||
TextDecoration.combine(
|
||||
<TextDecoration>[TextDecoration.overline, TextDecoration.lineThrough])
|
||||
];
|
||||
|
||||
Offset offset = Offset.zero;
|
||||
|
||||
for (final TextDecoration decoration in decorations) {
|
||||
final TextStyle textStyle = TextStyle(
|
||||
color: const Color.fromRGBO(50, 50, 255, 1.0),
|
||||
decoration: decoration,
|
||||
decorationStyle: TextDecorationStyle.solid,
|
||||
decorationColor: const Color.fromRGBO(255, 160, 0, 1.0),
|
||||
fontFamily: 'Roboto',
|
||||
fontSize: 20,
|
||||
);
|
||||
canvas.drawParagraph(
|
||||
paragraph(
|
||||
'Hello World $decoration',
|
||||
textStyle: textStyle,
|
||||
maxWidth: 600,
|
||||
),
|
||||
offset,
|
||||
);
|
||||
offset = offset.translate(0, 40);
|
||||
}
|
||||
}
|
||||
|
||||
testEachCanvas('draws text decoration', (EngineCanvas canvas) {
|
||||
drawTextDecoration(canvas);
|
||||
return scuba.diffCanvasScreenshot(
|
||||
canvas, 'paint_bounds_for_text_decoration');
|
||||
});
|
||||
|
||||
void drawTextWithBackground(EngineCanvas canvas) {
|
||||
// Single-line text.
|
||||
canvas.drawParagraph(
|
||||
paragraph(
|
||||
'Hello World',
|
||||
maxWidth: 600,
|
||||
textStyle: TextStyle(
|
||||
color: const Color.fromRGBO(0, 0, 0, 1.0),
|
||||
background: Paint()..color = const Color.fromRGBO(255, 50, 50, 1.0),
|
||||
fontFamily: 'Roboto',
|
||||
fontSize: 30,
|
||||
),
|
||||
),
|
||||
Offset.zero,
|
||||
);
|
||||
|
||||
// Multi-line text.
|
||||
canvas.drawParagraph(
|
||||
paragraph(
|
||||
'Multi line Hello World paragraph',
|
||||
maxWidth: 200,
|
||||
textStyle: TextStyle(
|
||||
color: const Color.fromRGBO(0, 0, 0, 1.0),
|
||||
background: Paint()..color = const Color.fromRGBO(50, 50, 255, 1.0),
|
||||
fontFamily: 'Roboto',
|
||||
fontSize: 30,
|
||||
),
|
||||
),
|
||||
const Offset(0, 40),
|
||||
);
|
||||
}
|
||||
|
||||
void drawTextWithShadow(EngineCanvas canvas) {
|
||||
// Single-line text.
|
||||
canvas.drawParagraph(
|
||||
paragraph(
|
||||
'Hello World',
|
||||
maxWidth: 600,
|
||||
textStyle: TextStyle(
|
||||
color: const Color.fromRGBO(0, 0, 0, 1.0),
|
||||
background: Paint()..color = const Color.fromRGBO(255, 50, 50, 1.0),
|
||||
fontFamily: 'Roboto',
|
||||
fontSize: 30,
|
||||
shadows: <Shadow>[
|
||||
const Shadow(
|
||||
blurRadius: 0,
|
||||
color: Color.fromRGBO(255, 0, 255, 1.0),
|
||||
offset: Offset(10, 5),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Offset.zero,
|
||||
);
|
||||
|
||||
// Multi-line text.
|
||||
canvas.drawParagraph(
|
||||
paragraph(
|
||||
'Multi line Hello World paragraph',
|
||||
maxWidth: 200,
|
||||
textStyle: TextStyle(
|
||||
color: const Color.fromRGBO(0, 0, 0, 1.0),
|
||||
background: Paint()..color = const Color.fromRGBO(50, 50, 255, 1.0),
|
||||
fontFamily: 'Roboto',
|
||||
fontSize: 30,
|
||||
shadows: <Shadow>[
|
||||
const Shadow(
|
||||
blurRadius: 0,
|
||||
color: Color.fromRGBO(255, 0, 255, 1.0),
|
||||
offset: Offset(10, 5),
|
||||
),
|
||||
const Shadow(
|
||||
blurRadius: 0,
|
||||
color: Color.fromRGBO(0, 255, 255, 1.0),
|
||||
offset: Offset(-10, -5),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Offset(0, 40),
|
||||
);
|
||||
}
|
||||
|
||||
testEachCanvas('draws text with a background', (EngineCanvas canvas) {
|
||||
drawTextWithBackground(canvas);
|
||||
return scuba.diffCanvasScreenshot(canvas, 'text_background');
|
||||
});
|
||||
|
||||
testEachCanvas('draws text with a shadow', (EngineCanvas canvas) {
|
||||
drawTextWithShadow(canvas);
|
||||
return scuba.diffCanvasScreenshot(canvas, 'text_shadow', maxDiffRatePercent: 0.2);
|
||||
});
|
||||
|
||||
testEachCanvas('Handles disabled strut style', (EngineCanvas canvas) {
|
||||
// Flutter uses [StrutStyle.disabled] for the [SelectableText] widget. This
|
||||
// translates into a strut style with a [height] of 0, which wasn't being
|
||||
// handled correctly by the web engine.
|
||||
final StrutStyle disabled = StrutStyle(height: 0, leading: 0);
|
||||
canvas.drawParagraph(
|
||||
paragraph(
|
||||
'Hello\nWorld',
|
||||
paragraphStyle: ParagraphStyle(strutStyle: disabled),
|
||||
),
|
||||
Offset.zero,
|
||||
);
|
||||
return scuba.diffCanvasScreenshot(
|
||||
canvas,
|
||||
'text_strut_style_disabled',
|
||||
region: const Rect.fromLTRB(0, 0, 100, 100),
|
||||
maxDiffRatePercent: 0.0,
|
||||
);
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,6 +7,8 @@ import 'package:test/test.dart';
|
||||
import 'package:ui/src/engine.dart';
|
||||
import 'package:ui/ui.dart' as ui;
|
||||
|
||||
import '../html/paragraph/helper.dart';
|
||||
|
||||
const ui.Color white = ui.Color(0xFFFFFFFF);
|
||||
const ui.Color black = ui.Color(0xFF000000);
|
||||
const ui.Color red = ui.Color(0xFFFF0000);
|
||||
@@ -22,15 +24,6 @@ ui.ParagraphConstraints constrain(double width) {
|
||||
return ui.ParagraphConstraints(width: width);
|
||||
}
|
||||
|
||||
CanvasParagraph rich(
|
||||
EngineParagraphStyle style,
|
||||
void Function(CanvasParagraphBuilder) callback,
|
||||
) {
|
||||
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style);
|
||||
callback(builder);
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
void main() {
|
||||
internalBootstrapBrowserTest(() => testMain);
|
||||
}
|
||||
@@ -686,6 +679,54 @@ Future<void> testMain() async {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('$CanvasParagraph.getWordBoundary', () {
|
||||
final ui.Paragraph paragraph = plain(ahemStyle, 'Lorem ipsum dolor');
|
||||
|
||||
const ui.TextRange loremRange = ui.TextRange(start: 0, end: 5);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 0)), loremRange);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 1)), loremRange);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 2)), loremRange);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 3)), loremRange);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 4)), loremRange);
|
||||
|
||||
const ui.TextRange firstSpace = ui.TextRange(start: 5, end: 6);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 5)), firstSpace);
|
||||
|
||||
const ui.TextRange ipsumRange = ui.TextRange(start: 6, end: 11);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 6)), ipsumRange);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 7)), ipsumRange);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 8)), ipsumRange);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 9)), ipsumRange);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 10)), ipsumRange);
|
||||
|
||||
const ui.TextRange secondSpace = ui.TextRange(start: 11, end: 12);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 11)), secondSpace);
|
||||
|
||||
const ui.TextRange dolorRange = ui.TextRange(start: 12, end: 17);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 12)), dolorRange);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 13)), dolorRange);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 14)), dolorRange);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 15)), dolorRange);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 16)), dolorRange);
|
||||
|
||||
const ui.TextRange endRange = ui.TextRange(start: 17, end: 17);
|
||||
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 17)), endRange);
|
||||
});
|
||||
|
||||
test('$CanvasParagraph.longestLine', () {
|
||||
final ui.Paragraph paragraph = plain(ahemStyle, 'abcd\nabcde abc');
|
||||
paragraph.layout(const ui.ParagraphConstraints(width: 80.0));
|
||||
expect(paragraph.longestLine, 50.0);
|
||||
});
|
||||
|
||||
test('$CanvasParagraph.width should be a whole integer', () {
|
||||
final ui.Paragraph paragraph = plain(ahemStyle, 'abc');
|
||||
paragraph.layout(const ui.ParagraphConstraints(width: 30.8));
|
||||
|
||||
expect(paragraph.width, 30);
|
||||
expect(paragraph.height, 10);
|
||||
});
|
||||
}
|
||||
|
||||
/// Shortcut to create a [ui.TextBox] with an optional [ui.TextDirection].
|
||||
|
||||
@@ -56,12 +56,6 @@ Future<void> testMain() async {
|
||||
const ui.ParagraphConstraints constraints =
|
||||
ui.ParagraphConstraints(width: 30.0);
|
||||
|
||||
final DomParagraphBuilder domBuilder = DomParagraphBuilder(style);
|
||||
domBuilder.addText('test');
|
||||
// Triggers the measuring and verifies the result has been cached.
|
||||
domBuilder.build().layout(constraints);
|
||||
expect(TextMeasurementService.rulerManager!.rulers.length, 1);
|
||||
|
||||
final CanvasParagraphBuilder canvasBuilder = CanvasParagraphBuilder(style);
|
||||
canvasBuilder.addText('test');
|
||||
// Triggers the measuring and verifies the ruler cache has been populated.
|
||||
@@ -78,7 +72,6 @@ Future<void> testMain() async {
|
||||
|
||||
// Verifies the font is loaded, and the cache is cleaned.
|
||||
expect(_containsFontFamily('Blehm'), isTrue);
|
||||
expect(TextMeasurementService.rulerManager!.rulers.length, 0);
|
||||
expect(Spanometer.rulers.length, 0);
|
||||
},
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/56702
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -10,6 +10,7 @@ import 'package:test/test.dart';
|
||||
import 'package:ui/src/engine.dart';
|
||||
import 'package:ui/ui.dart';
|
||||
|
||||
import 'html/paragraph/helper.dart';
|
||||
import 'matchers.dart';
|
||||
|
||||
void main() {
|
||||
@@ -88,16 +89,13 @@ Future<void> testMain() async {
|
||||
});
|
||||
|
||||
test('lay out unattached paragraph', () {
|
||||
final DomParagraphBuilder builder = DomParagraphBuilder(EngineParagraphStyle(
|
||||
final CanvasParagraph paragraph = plain(EngineParagraphStyle(
|
||||
fontFamily: 'sans-serif',
|
||||
fontStyle: FontStyle.normal,
|
||||
fontWeight: FontWeight.normal,
|
||||
fontSize: 14.0,
|
||||
));
|
||||
builder.addText('How do you do this fine morning?');
|
||||
final DomParagraph paragraph = builder.build() as DomParagraph;
|
||||
), 'How do you do this fine morning?');
|
||||
|
||||
expect(paragraph.paragraphElement.parent, isNull);
|
||||
expect(paragraph.height, 0.0);
|
||||
expect(paragraph.width, -1.0);
|
||||
expect(paragraph.minIntrinsicWidth, 0.0);
|
||||
@@ -107,7 +105,6 @@ Future<void> testMain() async {
|
||||
|
||||
paragraph.layout(const ParagraphConstraints(width: 60.0));
|
||||
|
||||
expect(paragraph.paragraphElement.parent, isNull);
|
||||
expect(paragraph.height, greaterThan(0.0));
|
||||
expect(paragraph.width, greaterThan(0.0));
|
||||
expect(paragraph.minIntrinsicWidth, greaterThan(0.0));
|
||||
@@ -154,18 +151,18 @@ Future<void> testMain() async {
|
||||
});
|
||||
|
||||
test('$ParagraphBuilder detects plain text', () {
|
||||
DomParagraphBuilder builder = DomParagraphBuilder(EngineParagraphStyle(
|
||||
ParagraphBuilder builder = ParagraphBuilder(EngineParagraphStyle(
|
||||
fontFamily: 'sans-serif',
|
||||
fontStyle: FontStyle.normal,
|
||||
fontWeight: FontWeight.normal,
|
||||
fontSize: 15.0,
|
||||
));
|
||||
builder.addText('hi');
|
||||
DomParagraph paragraph = builder.build() as DomParagraph;
|
||||
CanvasParagraph paragraph = builder.build() as CanvasParagraph;
|
||||
expect(paragraph.plainText, isNotNull);
|
||||
expect(paragraph.geometricStyle.fontWeight, FontWeight.normal);
|
||||
expect(paragraph.paragraphStyle.fontWeight, FontWeight.normal);
|
||||
|
||||
builder = DomParagraphBuilder(EngineParagraphStyle(
|
||||
builder = ParagraphBuilder(EngineParagraphStyle(
|
||||
fontFamily: 'sans-serif',
|
||||
fontStyle: FontStyle.normal,
|
||||
fontWeight: FontWeight.normal,
|
||||
@@ -173,13 +170,12 @@ Future<void> testMain() async {
|
||||
));
|
||||
builder.pushStyle(TextStyle(fontWeight: FontWeight.bold));
|
||||
builder.addText('hi');
|
||||
paragraph = builder.build() as DomParagraph;
|
||||
paragraph = builder.build() as CanvasParagraph;
|
||||
expect(paragraph.plainText, isNotNull);
|
||||
expect(paragraph.geometricStyle.fontWeight, FontWeight.bold);
|
||||
});
|
||||
|
||||
test('$ParagraphBuilder detects rich text', () {
|
||||
final DomParagraphBuilder builder = DomParagraphBuilder(EngineParagraphStyle(
|
||||
final ParagraphBuilder builder = ParagraphBuilder(EngineParagraphStyle(
|
||||
fontFamily: 'sans-serif',
|
||||
fontStyle: FontStyle.normal,
|
||||
fontWeight: FontWeight.normal,
|
||||
@@ -188,176 +184,27 @@ Future<void> testMain() async {
|
||||
builder.addText('h');
|
||||
builder.pushStyle(TextStyle(fontWeight: FontWeight.bold));
|
||||
builder.addText('i');
|
||||
final DomParagraph paragraph = builder.build() as DomParagraph;
|
||||
expect(paragraph.plainText, isNull);
|
||||
expect(paragraph.geometricStyle.fontWeight, FontWeight.normal);
|
||||
final CanvasParagraph paragraph = builder.build() as CanvasParagraph;
|
||||
expect(paragraph.plainText, 'hi');
|
||||
});
|
||||
|
||||
test('$ParagraphBuilder treats empty text as plain', () {
|
||||
final DomParagraphBuilder builder = DomParagraphBuilder(EngineParagraphStyle(
|
||||
final ParagraphBuilder builder = ParagraphBuilder(EngineParagraphStyle(
|
||||
fontFamily: 'sans-serif',
|
||||
fontStyle: FontStyle.normal,
|
||||
fontWeight: FontWeight.normal,
|
||||
fontSize: 15.0,
|
||||
));
|
||||
builder.pushStyle(TextStyle(fontWeight: FontWeight.bold));
|
||||
final DomParagraph paragraph = builder.build() as DomParagraph;
|
||||
final CanvasParagraph paragraph = builder.build() as CanvasParagraph;
|
||||
expect(paragraph.plainText, '');
|
||||
expect(paragraph.geometricStyle.fontWeight, FontWeight.bold);
|
||||
});
|
||||
|
||||
// Regression test for https://github.com/flutter/flutter/issues/34931.
|
||||
test('hit test on styled text returns correct span offset', () {
|
||||
final DomParagraphBuilder builder = DomParagraphBuilder(EngineParagraphStyle(
|
||||
fontFamily: 'sans-serif',
|
||||
fontStyle: FontStyle.normal,
|
||||
fontWeight: FontWeight.normal,
|
||||
fontSize: 15.0,
|
||||
));
|
||||
builder.pushStyle(TextStyle(fontWeight: FontWeight.bold));
|
||||
const String firstSpanText = 'XYZ';
|
||||
builder.addText(firstSpanText);
|
||||
builder.pushStyle(TextStyle(fontWeight: FontWeight.normal));
|
||||
const String secondSpanText = '1234';
|
||||
builder.addText(secondSpanText);
|
||||
builder.pushStyle(TextStyle(fontStyle: FontStyle.italic));
|
||||
builder.addText('followed by a link');
|
||||
final DomParagraph paragraph = builder.build() as DomParagraph;
|
||||
paragraph.layout(const ParagraphConstraints(width: 800.0));
|
||||
expect(paragraph.plainText, isNull);
|
||||
const int secondSpanStartPosition = firstSpanText.length;
|
||||
const int thirdSpanStartPosition =
|
||||
firstSpanText.length + secondSpanText.length;
|
||||
expect(paragraph.getPositionForOffset(const Offset(50, 0)).offset,
|
||||
secondSpanStartPosition);
|
||||
expect(paragraph.getPositionForOffset(const Offset(150, 0)).offset,
|
||||
thirdSpanStartPosition);
|
||||
});
|
||||
|
||||
test('hit test on the nested text span and returns correct span offset', () {
|
||||
const String fontFamily = 'sans-serif';
|
||||
const double fontSize = 20.0;
|
||||
final TextStyle style = TextStyle(fontFamily: fontFamily, fontSize: fontSize);
|
||||
final DomParagraphBuilder builder = DomParagraphBuilder(EngineParagraphStyle(
|
||||
fontFamily: fontFamily,
|
||||
fontSize: fontSize,
|
||||
));
|
||||
|
||||
const String text00 = 'test test test test test te00 ';
|
||||
const String text010 = 'test010 ';
|
||||
const String text02 = 'test test test test te02 ';
|
||||
const String text030 = 'test030 ';
|
||||
const String text04 = 'test test test test test test test test test test te04 ';
|
||||
const String text050 = 'test050 ';
|
||||
|
||||
/* Logical arrangement: Tree
|
||||
|
||||
Root TextSpan: 0
|
||||
*/
|
||||
builder.pushStyle(style);
|
||||
{
|
||||
// 1st child TextSpan of Root: 0.0
|
||||
builder.pushStyle(style);
|
||||
builder.addText(text00);
|
||||
builder.pop();
|
||||
|
||||
// 2nd child TextSpan of Root: 0.1
|
||||
builder.pushStyle(style);
|
||||
{
|
||||
// 1st child TextSpan of 0.1: 0.1.0
|
||||
builder.pushStyle(style);
|
||||
builder.addText(text010);
|
||||
builder.pop();
|
||||
}
|
||||
builder.pop();
|
||||
|
||||
// 3rd child TextSpan of Root: 0.2
|
||||
builder.pushStyle(style);
|
||||
builder.addText(text02);
|
||||
builder.pop();
|
||||
|
||||
// 4th child TextSpan of Root: 0.3
|
||||
builder.pushStyle(style);
|
||||
{
|
||||
// 1st child TextSpan of 0.3: 0.3.0
|
||||
builder.pushStyle(style);
|
||||
builder.addText(text030);
|
||||
builder.pop();
|
||||
}
|
||||
builder.pop();
|
||||
|
||||
// 5th child TextSpan of Root: 0.4
|
||||
builder.pushStyle(style);
|
||||
builder.addText(text04);
|
||||
builder.pop();
|
||||
|
||||
// 6th child TextSpan of Root: 0.5
|
||||
builder.pushStyle(style);
|
||||
{
|
||||
// 1st child TextSpan of 0.5: 0.5.0
|
||||
builder.pushStyle(style);
|
||||
builder.addText(text050);
|
||||
builder.pop();
|
||||
}
|
||||
builder.pop();
|
||||
}
|
||||
builder.pop();
|
||||
|
||||
/* Display arrangement: Visible texts
|
||||
|
||||
Because `const fontSize = 20.0`, the width of each character is 20 and the
|
||||
height is 20. `Display arrangement` squashes `Logical arrangement` to the
|
||||
(x, y) plane. That means `Display arrangement` only shows the visible texts.
|
||||
The order of texts is text00 --> text010 --> text02 --> text030 --> text04
|
||||
--> text050.
|
||||
|
||||
The output is like that.
|
||||
|
||||
|------------ 600 ------------| Begin of test010
|
||||
|--------------- 760 ----------------| End of test010
|
||||
|---------- 500 ---------| Begin of test030
|
||||
|------------- 660 -------------| End of test030
|
||||
|-- 180 --| Begin of test050
|
||||
|------ 360 -----| End of test050
|
||||
'test test test test test te00 test010 '
|
||||
'test test test test te02 test030 test '
|
||||
'test test test test test test test test '
|
||||
'test te04 test050 '
|
||||
*/
|
||||
|
||||
final DomParagraph paragraph = builder.build() as DomParagraph;
|
||||
paragraph.layout(const ParagraphConstraints(width: 800));
|
||||
|
||||
// Reference the offsets with the output of `Display arrangement`.
|
||||
const int offset010 = text00.length;
|
||||
const int offset030 = offset010 + text010.length + text02.length;
|
||||
const int offset04 = offset030 + text030.length;
|
||||
const int offset050 = offset04 + text04.length;
|
||||
// Tap text010.
|
||||
expect(paragraph.getPositionForOffset(const Offset(700, 10)).offset, offset010);
|
||||
// Tap text030
|
||||
expect(paragraph.getPositionForOffset(const Offset(600, 30)).offset, offset030);
|
||||
// Tap text050
|
||||
expect(paragraph.getPositionForOffset(const Offset(220, 70)).offset, offset050);
|
||||
// Tap the left neighbor of text050
|
||||
expect(paragraph.getPositionForOffset(const Offset(199, 70)).offset, offset04);
|
||||
// Tap the right neighbor of text050. No matter who the right neighbor of
|
||||
// text0505 is, it must not be text050 itself.
|
||||
expect(paragraph.getPositionForOffset(const Offset(360, 70)).offset,
|
||||
isNot(offset050));
|
||||
// Tap the neighbor above text050
|
||||
expect(paragraph.getPositionForOffset(const Offset(220, 59)).offset, offset04);
|
||||
// Tap the neighbor below text050. No matter who the neighbor above text050,
|
||||
// it must not be text050 itself.
|
||||
expect(paragraph.getPositionForOffset(const Offset(220, 80)).offset,
|
||||
isNot(offset050));
|
||||
});
|
||||
|
||||
// Regression test for https://github.com/flutter/flutter/issues/38972
|
||||
test(
|
||||
'should not set fontFamily to effectiveFontFamily for spans in rich text',
|
||||
() {
|
||||
final DomParagraphBuilder builder = DomParagraphBuilder(EngineParagraphStyle(
|
||||
final ParagraphBuilder builder = ParagraphBuilder(EngineParagraphStyle(
|
||||
fontFamily: 'Roboto',
|
||||
fontStyle: FontStyle.normal,
|
||||
fontWeight: FontWeight.normal,
|
||||
@@ -370,11 +217,11 @@ Future<void> testMain() async {
|
||||
builder.pushStyle(TextStyle(fontSize: 30.0, fontWeight: FontWeight.normal));
|
||||
const String secondSpanText = 'def';
|
||||
builder.addText(secondSpanText);
|
||||
final DomParagraph paragraph = builder.build() as DomParagraph;
|
||||
final CanvasParagraph paragraph = builder.build() as CanvasParagraph;
|
||||
paragraph.layout(const ParagraphConstraints(width: 800.0));
|
||||
expect(paragraph.plainText, isNull);
|
||||
expect(paragraph.plainText, 'abcdef');
|
||||
final List<SpanElement> spans =
|
||||
paragraph.paragraphElement.querySelectorAll('span');
|
||||
paragraph.toDomElement().querySelectorAll('span');
|
||||
expect(spans[0].style.fontFamily, 'Ahem, $fallback, sans-serif');
|
||||
// The nested span here should not set it's family to default sans-serif.
|
||||
expect(spans[1].style.fontFamily, 'Ahem, $fallback, sans-serif');
|
||||
@@ -388,15 +235,13 @@ Future<void> testMain() async {
|
||||
// Set this to false so it doesn't default to 'Ahem' font.
|
||||
debugEmulateFlutterTesterEnvironment = false;
|
||||
|
||||
final DomParagraphBuilder builder = DomParagraphBuilder(EngineParagraphStyle(
|
||||
final CanvasParagraph paragraph = plain(EngineParagraphStyle(
|
||||
fontFamily: 'SomeFont',
|
||||
fontSize: 12.0,
|
||||
));
|
||||
), 'Hello');
|
||||
|
||||
builder.addText('Hello');
|
||||
|
||||
final DomParagraph paragraph = builder.build() as DomParagraph;
|
||||
expect(paragraph.paragraphElement.style.fontFamily,
|
||||
paragraph.layout(constrain(double.infinity));
|
||||
expect(paragraph.toDomElement().style.fontFamily,
|
||||
'SomeFont, $fallback, sans-serif');
|
||||
|
||||
debugEmulateFlutterTesterEnvironment = true;
|
||||
@@ -410,15 +255,13 @@ Future<void> testMain() async {
|
||||
// Set this to false so it doesn't default to 'Ahem' font.
|
||||
debugEmulateFlutterTesterEnvironment = false;
|
||||
|
||||
final DomParagraphBuilder builder = DomParagraphBuilder(EngineParagraphStyle(
|
||||
final CanvasParagraph paragraph = plain(EngineParagraphStyle(
|
||||
fontFamily: 'serif',
|
||||
fontSize: 12.0,
|
||||
));
|
||||
), 'Hello');
|
||||
|
||||
builder.addText('Hello');
|
||||
|
||||
final DomParagraph paragraph = builder.build() as DomParagraph;
|
||||
expect(paragraph.paragraphElement.style.fontFamily, 'serif');
|
||||
paragraph.layout(constrain(double.infinity));
|
||||
expect(paragraph.toDomElement().style.fontFamily, 'serif');
|
||||
|
||||
debugEmulateFlutterTesterEnvironment = true;
|
||||
});
|
||||
@@ -427,15 +270,13 @@ Future<void> testMain() async {
|
||||
// Set this to false so it doesn't default to 'Ahem' font.
|
||||
debugEmulateFlutterTesterEnvironment = false;
|
||||
|
||||
final DomParagraphBuilder builder = DomParagraphBuilder(EngineParagraphStyle(
|
||||
final CanvasParagraph paragraph = plain(EngineParagraphStyle(
|
||||
fontFamily: 'MyFont 2000',
|
||||
fontSize: 12.0,
|
||||
));
|
||||
), 'Hello');
|
||||
|
||||
builder.addText('Hello');
|
||||
|
||||
final DomParagraph paragraph = builder.build() as DomParagraph;
|
||||
expect(paragraph.paragraphElement.style.fontFamily,
|
||||
paragraph.layout(constrain(double.infinity));
|
||||
expect(paragraph.toDomElement().style.fontFamily,
|
||||
'"MyFont 2000", $fallback, sans-serif');
|
||||
|
||||
debugEmulateFlutterTesterEnvironment = true;
|
||||
|
||||
Reference in New Issue
Block a user