[web] Eagerly calculate relevant indices during line break detection (flutter/engine#20278)

This commit is contained in:
Mouad Debbar
2020-08-06 19:29:11 -07:00
committed by GitHub
parent a5ea2aeba5
commit 901440373d
3 changed files with 281 additions and 81 deletions

View File

@@ -21,11 +21,93 @@ enum LineBreakType {
}
/// Acts as a tuple that encapsulates information about a line break.
///
/// It contains multiple indices that are helpful when it comes to measuring the
/// width of a line of text.
///
/// [indexWithoutTrailingSpaces] <= [indexWithoutTrailingNewlines] <= [index]
///
/// Example: for the string "foo \nbar " here are the indices:
/// ```
/// f o o \n b a r
/// ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
/// 0 1 2 3 4 5 6 7 8 9
/// ```
/// It contains two line breaks:
/// ```
/// // The first line break:
/// LineBreakResult(5, 4, 3, LineBreakType.mandatory)
///
/// // Second line break:
/// LineBreakResult(9, 9, 8, LineBreakType.mandatory)
/// ```
class LineBreakResult {
LineBreakResult(this.index, this.type);
const LineBreakResult(
this.index,
this.indexWithoutTrailingNewlines,
this.indexWithoutTrailingSpaces,
this.type,
): assert(indexWithoutTrailingSpaces <= indexWithoutTrailingNewlines),
assert(indexWithoutTrailingNewlines <= index);
/// Creates a [LineBreakResult] where all indices are the same (i.e. there are
/// no trailing spaces or new lines).
const LineBreakResult.sameIndex(this.index, this.type)
: indexWithoutTrailingNewlines = index,
indexWithoutTrailingSpaces = index;
/// The true index at which the line break should occur, including all spaces
/// and new lines.
final int index;
/// The index of the line break excluding any trailing new lines.
final int indexWithoutTrailingNewlines;
/// The index of the line break excluding any trailing spaces.
final int indexWithoutTrailingSpaces;
/// The type of line break is useful to determine the behavior in text
/// measurement.
///
/// For example, a mandatory line break always causes a line break regardless
/// of width constraints. But a line break opportunity requires further checks
/// to decide whether to take the line break or not.
final LineBreakType type;
@override
int get hashCode => ui.hashValues(
index,
indexWithoutTrailingNewlines,
indexWithoutTrailingSpaces,
type,
);
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is LineBreakResult &&
other.index == index &&
other.indexWithoutTrailingNewlines == indexWithoutTrailingNewlines &&
other.indexWithoutTrailingSpaces == indexWithoutTrailingSpaces &&
other.type == type;
}
@override
String toString() {
if (assertionsEnabled) {
return 'LineBreakResult(index: $index, '
'without new lines: $indexWithoutTrailingNewlines, '
'without spaces: $indexWithoutTrailingSpaces, '
'type: $type)';
} else {
return super.toString();
}
}
}
bool _isHardBreak(LineCharProperty? prop) {
@@ -49,7 +131,7 @@ bool _isKoreanSyllable(LineCharProperty? prop) {
prop == LineCharProperty.H3;
}
/// Whether the given char code has an Easter Asian width property of F, W or H.
/// Whether the given char code has an Eastern Asian width property of F, W or H.
///
/// See:
/// - https://www.unicode.org/reports/tr14/tr14-45.html#LB30
@@ -62,6 +144,18 @@ bool _hasEastAsianWidthFWH(int charCode) {
/// Finds the next line break in the given [text] starting from [index].
///
/// Wethink about indices as pointing between characters, and they go all the
/// way from 0 to the string length. For example, here are the indices for the
/// string "foo bar":
///
/// ```
/// f o o b a r
/// ^ ^ ^ ^ ^ ^ ^ ^
/// 0 1 2 3 4 5 6 7
/// ```
///
/// This way the indices work well with [String.substring()].
///
/// Useful resources:
///
/// * https://www.unicode.org/reports/tr14/tr14-45.html#Algorithm
@@ -80,6 +174,12 @@ LineBreakResult nextLineBreak(String text, int index) {
// sequence.
LineCharProperty? baseOfSpaceSequence;
/// The index of the last character that wasn't a space.
int lastNonSpaceIndex = index;
/// The index of the last character that wasn't a new line.
int lastNonNewlineIndex = index;
// When the text/line starts with SP, we should treat the begining of text/line
// as if it were a WJ (word joiner).
if (curr == LineCharProperty.SP) {
@@ -131,12 +231,15 @@ LineBreakResult nextLineBreak(String text, int index) {
// LB4: BK !
//
// Treat CR followed by LF, as well as CR, LF, and NL as hard line breaks.
// LB5: CR × LF
// CR !
// LF !
// LB5: LF !
// NL !
if (_isHardBreak(prev1)) {
return LineBreakResult(index, LineBreakType.mandatory);
return LineBreakResult(
index,
lastNonNewlineIndex,
lastNonSpaceIndex,
LineBreakType.mandatory,
);
}
if (prev1 == LineCharProperty.CR) {
@@ -145,10 +248,21 @@ LineBreakResult nextLineBreak(String text, int index) {
continue;
} else {
// LB5: CR !
return LineBreakResult(index, LineBreakType.mandatory);
return LineBreakResult(
index,
lastNonNewlineIndex,
lastNonSpaceIndex,
LineBreakType.mandatory,
);
}
}
// At this point, we know for sure the prev character wasn't a new line.
lastNonNewlineIndex = index;
if (prev1 != LineCharProperty.SP) {
lastNonSpaceIndex = index;
}
// Do not break before hard line breaks.
// LB6: × ( BK | CR | LF | NL )
if (_isHardBreak(curr) || curr == LineCharProperty.CR) {
@@ -158,7 +272,12 @@ LineBreakResult nextLineBreak(String text, int index) {
// Always break at the end of text.
// LB3: ! eot
if (index >= text.length) {
return LineBreakResult(text.length, LineBreakType.endOfText);
return LineBreakResult(
text.length,
lastNonNewlineIndex,
lastNonSpaceIndex,
LineBreakType.endOfText,
);
}
// Do not break before spaces or zero width space.
@@ -186,7 +305,12 @@ LineBreakResult nextLineBreak(String text, int index) {
// LB8: ZW SP* ÷
if (prev1 == LineCharProperty.ZW ||
baseOfSpaceSequence == LineCharProperty.ZW) {
return LineBreakResult(index, LineBreakType.opportunity);
return LineBreakResult(
index,
lastNonNewlineIndex,
lastNonSpaceIndex,
LineBreakType.opportunity,
);
}
// Do not break a combining character sequence; treat it as if it has the
@@ -292,7 +416,12 @@ LineBreakResult nextLineBreak(String text, int index) {
// Break after spaces.
// LB18: SP ÷
if (prev1 == LineCharProperty.SP) {
return LineBreakResult(index, LineBreakType.opportunity);
return LineBreakResult(
index,
lastNonNewlineIndex,
lastNonSpaceIndex,
LineBreakType.opportunity,
);
}
// Do not break before or after quotation marks, such as ‘”’.
@@ -306,7 +435,12 @@ LineBreakResult nextLineBreak(String text, int index) {
// LB20: ÷ CB
// CB ÷
if (prev1 == LineCharProperty.CB || curr == LineCharProperty.CB) {
return LineBreakResult(index, LineBreakType.opportunity);
return LineBreakResult(
index,
lastNonNewlineIndex,
lastNonSpaceIndex,
LineBreakType.opportunity,
);
}
// Do not break before hyphen-minus, other hyphens, fixed-width spaces,
@@ -471,7 +605,12 @@ LineBreakResult nextLineBreak(String text, int index) {
if (regionalIndicatorCount.isOdd) {
continue;
} else {
return LineBreakResult(index, LineBreakType.opportunity);
return LineBreakResult(
index,
lastNonNewlineIndex,
lastNonSpaceIndex,
LineBreakType.opportunity,
);
}
}
@@ -484,7 +623,17 @@ LineBreakResult nextLineBreak(String text, int index) {
// Break everywhere else.
// LB31: ALL ÷
// ÷ ALL
return LineBreakResult(index, LineBreakType.opportunity);
return LineBreakResult(
index,
lastNonNewlineIndex,
lastNonSpaceIndex,
LineBreakType.opportunity,
);
}
return LineBreakResult(text.length, LineBreakType.endOfText);
return LineBreakResult(
text.length,
lastNonNewlineIndex,
lastNonSpaceIndex,
LineBreakType.endOfText,
);
}

View File

@@ -16,17 +16,11 @@ 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 _whitespacePredicate(int char) {
final LineCharProperty prop = lineLookup.findForChar(char);
return prop == LineCharProperty.SP ||
prop == LineCharProperty.BK ||
prop == LineCharProperty.LF ||
prop == LineCharProperty.CR;
}
bool _newlinePredicate(int char) {
final LineCharProperty prop = lineLookup.findForChar(char);
return prop == LineCharProperty.BK || prop == LineCharProperty.LF || prop == LineCharProperty.CR;
return prop == LineCharProperty.BK ||
prop == LineCharProperty.LF ||
prop == LineCharProperty.CR;
}
/// Manages [ParagraphRuler] instances and caches them per unique
@@ -689,8 +683,8 @@ double _measureSubstring(
final double letterSpacing = style.letterSpacing ?? 0.0;
final String sub =
start == 0 && end == text.length ? text : text.substring(start, end);
final double width =
_canvasContext.measureText(sub).width! + letterSpacing * sub.length as double;
final double width = _canvasContext.measureText(sub).width! +
letterSpacing * sub.length as double;
// What we are doing here is we are rounding to the nearest 2nd decimal
// point. So 39.999423 becomes 40, and 11.243982 becomes 11.24.
@@ -737,8 +731,17 @@ class LinesCalculator {
/// The lines that have been consumed so far.
List<EngineLineMetrics> lines = <EngineLineMetrics>[];
int _lineStart = 0;
int _chunkStart = 0;
/// 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;
@@ -756,8 +759,8 @@ class LinesCalculator {
final bool isHardBreak = brk.type == LineBreakType.mandatory ||
brk.type == LineBreakType.endOfText;
final int chunkEnd = brk.index;
final int chunkEndWithoutSpace =
_excludeTrailing(_text!, _chunkStart, chunkEnd, _whitespacePredicate);
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.
@@ -801,8 +804,7 @@ class LinesCalculator {
_text!.substring(_lineStart, breakingPoint) + _style.ellipsis!,
startIndex: _lineStart,
endIndex: chunkEnd,
endIndexWithoutNewlines:
_excludeTrailing(_text!, _chunkStart, chunkEnd, _newlinePredicate),
endIndexWithoutNewlines: chunkEndWithoutNewlines,
hardBreak: false,
width: widthOfResultingLine,
widthWithTrailingSpaces: widthOfResultingLine,
@@ -823,12 +825,14 @@ class LinesCalculator {
// [isHardBreak] check below) to break the line.
break;
}
_addLineBreak(lineEnd: breakingPoint, isHardBreak: false);
_chunkStart = breakingPoint;
_addLineBreak(LineBreakResult.sameIndex(
breakingPoint,
LineBreakType.opportunity,
));
} else {
// The control case of current line exceeding [_maxWidth], we break the
// line.
_addLineBreak(lineEnd: _chunkStart, isHardBreak: false);
_addLineBreak(_lastBreak);
}
}
@@ -837,41 +841,30 @@ class LinesCalculator {
}
if (isHardBreak) {
_addLineBreak(lineEnd: chunkEnd, isHardBreak: true);
_addLineBreak(brk);
}
_chunkStart = chunkEnd;
_lastBreak = brk;
}
void _addLineBreak({
required int lineEnd,
required bool isHardBreak,
}) {
final int endWithoutNewlines = _excludeTrailing(
_text!,
_lineStart,
lineEnd,
_newlinePredicate,
);
final int endWithoutSpace = _excludeTrailing(
_text!,
_lineStart,
endWithoutNewlines,
_whitespacePredicate,
);
void _addLineBreak(LineBreakResult brk) {
final int lineNumber = lines.length;
final double lineWidth = measureSubstring(_lineStart, endWithoutSpace);
final double lineWidth =
measureSubstring(_lineStart, brk.indexWithoutTrailingSpaces);
final double lineWidthWithTrailingSpaces =
measureSubstring(_lineStart, endWithoutNewlines);
measureSubstring(_lineStart, brk.indexWithoutTrailingNewlines);
final double alignOffset = _calculateAlignOffsetForLine(
paragraph: _paragraph,
lineWidth: lineWidth,
maxWidth: _maxWidth,
);
final bool isHardBreak = brk.type == LineBreakType.mandatory ||
brk.type == LineBreakType.endOfText;
final EngineLineMetrics metrics = EngineLineMetrics.withText(
_text!.substring(_lineStart, endWithoutNewlines),
_text!.substring(_lineStart, brk.indexWithoutTrailingNewlines),
startIndex: _lineStart,
endIndex: lineEnd,
endIndexWithoutNewlines: endWithoutNewlines,
endIndex: brk.index,
endIndexWithoutNewlines: brk.indexWithoutTrailingNewlines,
hardBreak: isHardBreak,
width: lineWidth,
widthWithTrailingSpaces: lineWidthWithTrailingSpaces,
@@ -879,7 +872,7 @@ class LinesCalculator {
lineNumber: lineNumber,
);
lines.add(metrics);
_lineStart = lineEnd;
_lastTakenBreak = _lastBreak = brk;
if (lines.length == _style.maxLines) {
_reachedMaxLines = true;
}
@@ -948,10 +941,13 @@ class MinIntrinsicCalculator {
/// [value] will contain the final minimum intrinsic width.
void update(LineBreakResult brk) {
final int chunkEnd = brk.index;
final int chunkEndWithoutSpace =
_excludeTrailing(_text, _lastChunkEnd, chunkEnd, _whitespacePredicate);
final double width = _measureSubstring(
_canvasContext, _style, _text, _lastChunkEnd, chunkEndWithoutSpace);
_canvasContext,
_style,
_text,
_lastChunkEnd,
brk.indexWithoutTrailingSpaces,
);
if (width > value) {
value = width;
}
@@ -982,24 +978,17 @@ class MaxIntrinsicCalculator {
return;
}
final int hardLineEnd = brk.index;
final int hardLineEndWithoutNewlines = _excludeTrailing(
_text,
_lastHardLineEnd,
hardLineEnd,
_newlinePredicate,
);
final double lineWidth = _measureSubstring(
_canvasContext,
_style,
_text,
_lastHardLineEnd,
hardLineEndWithoutNewlines,
brk.indexWithoutTrailingNewlines,
);
if (lineWidth > value) {
value = lineWidth;
}
_lastHardLineEnd = hardLineEnd;
_lastHardLineEnd = brk.index;
}
}

View File

@@ -162,6 +162,62 @@ void main() {
]);
});
test('trailing spaces and new lines', () {
expect(
findBreaks('foo bar '),
<LineBreakResult>[
LineBreakResult(4, 4, 3, LineBreakType.opportunity),
LineBreakResult(9, 9, 7, LineBreakType.endOfText),
],
);
expect(
findBreaks('foo \nbar\nbaz \n'),
<LineBreakResult>[
LineBreakResult(6, 5, 3, LineBreakType.mandatory),
LineBreakResult(10, 9, 9, LineBreakType.mandatory),
LineBreakResult(17, 16, 13, LineBreakType.mandatory),
LineBreakResult(17, 17, 17, LineBreakType.endOfText),
],
);
});
test('leading spaces', () {
expect(
findBreaks(' foo'),
<LineBreakResult>[
LineBreakResult(1, 1, 0, LineBreakType.opportunity),
LineBreakResult(4, 4, 4, LineBreakType.endOfText),
],
);
expect(
findBreaks(' foo'),
<LineBreakResult>[
LineBreakResult(3, 3, 0, LineBreakType.opportunity),
LineBreakResult(6, 6, 6, LineBreakType.endOfText),
],
);
expect(
findBreaks(' foo bar'),
<LineBreakResult>[
LineBreakResult(2, 2, 0, LineBreakType.opportunity),
LineBreakResult(8, 8, 5, LineBreakType.opportunity),
LineBreakResult(11, 11, 11, LineBreakType.endOfText),
],
);
expect(
findBreaks(' \n foo'),
<LineBreakResult>[
LineBreakResult(3, 2, 0, LineBreakType.mandatory),
LineBreakResult(6, 6, 3, LineBreakType.opportunity),
LineBreakResult(9, 9, 9, LineBreakType.endOfText),
],
);
});
test('comprehensive test', () {
for (int t = 0; t < data.length; t++) {
final TestCase testCase = data[t];
@@ -220,9 +276,7 @@ class Line {
@override
bool operator ==(Object other) {
return other is Line
&& other.text == text
&& other.breakType == breakType;
return other is Line && other.text == text && other.breakType == breakType;
}
String get escapedText {
@@ -245,14 +299,22 @@ class Line {
List<Line> split(String text) {
final List<Line> lines = <Line>[];
int i = 0;
LineBreakType? breakType;
while (breakType != LineBreakType.endOfText) {
final LineBreakResult result = nextLineBreak(text, i);
lines.add(Line(text.substring(i, result.index), result.type));
i = result.index;
breakType = result.type;
int lastIndex = 0;
for (LineBreakResult brk in findBreaks(text)) {
lines.add(Line(text.substring(lastIndex, brk.index), brk.type));
lastIndex = brk.index;
}
return lines;
}
List<LineBreakResult> findBreaks(String text) {
final List<LineBreakResult> breaks = <LineBreakResult>[];
LineBreakResult brk = nextLineBreak(text, 0);
breaks.add(brk);
while (brk.type != LineBreakType.endOfText) {
brk = nextLineBreak(text, brk.index);
breaks.add(brk);
}
return breaks;
}