Skip to content

Commit f1586fc

Browse files
Rusinomdebbar
andauthored
[web_paragraph] Honor TextHeightBehavior.applyHeightToFirstAscent and applyHeightToLastDescent (flutter#193773)
Honors `TextHeightBehavior.applyHeightToFirstAscent` and `applyHeightToLastDescent` when computing `WebParagraph` line metrics (for non-empty paragraphs). Part of flutter#193731. > [!NOTE] > Split out from flutter#193403 to keep each change small and focused. ### Problem Both `applyHeightToFirstAscent` and `applyHeightToLastDescent` were ignored: the first line always kept its height-scaled ascent and the last line always kept its height-scaled descent. ### Fix - `TextLine.rawFontBoundingBoxAscent` / `rawFontBoundingBoxDescent`: accumulate unscaled font metrics alongside height-scaled metrics in `TextLine.updateBoundingBox` (and copy them in `TextLine.inheritMetricsFrom`). - **Identifying the first and last lines**: - `isFirstLine` is determined in `TextLayout._finishLine` via `lines.isEmpty` before the line is appended. - `isLastLine` is passed from `_LineBuilder.build` (`wrapper.dart`) and stored on `line.lastLine` in `_finishLine`: a content line is the last line when it hits the `maxLines` limit or reaches the artificial EOF cluster without a trailing newline; when a trailing `\n` is present (and `maxLines` is not yet reached), the synthetic empty line added after `\n` is marked `isLastLine: true`. - **Single-pass metric adjustment (`TextLayout._finishLine` -> `TextLine.applyTextHeightBehavior`)**: before computing `line.advance`, `isFirstLine && !applyHeightToFirstAscent` sets `usesRawAscent = true` and reverts `fontBoundingBoxAscent` to `rawFontBoundingBoxAscent`, and `isLastLine && !applyHeightToLastDescent` sets `usesRawDescent = true` and reverts `fontBoundingBoxDescent` to `rawFontBoundingBoxDescent`. Because this happens before `line.advance` is returned to the wrapper, line tops and paragraph height are accumulated in a single pass. - **Placeholders & backgrounds**: `PlaceholderBlock.positionInLine` positions placeholders after `applyTextHeightBehavior` so first-line placeholders align against the reverted ascent, and `WebParagraphPainter._paintAllBlocks` bounds background rects by raw ascent/descent when `usesRawAscent`/`usesRawDescent` are set. - **Trailing newline**: the synthetic empty line created after a trailing `\n` inherits the preceding line's scaled and raw metrics via `inheritMetricsFrom`, so the synthetic last line drops its scaled descent while the preceding text line keeps its scaled descent — matching `SkParagraph`. ### Tests - `paragraph_line_height_test.dart` (+6 tests): - `TextHeightBehavior reverts a single line to the unscaled font metrics` - `TextHeightBehavior affects only the first line ascent and the last line descent` - `TextHeightBehavior treats the empty line after a trailing newline as the last line` - `TextHeightBehavior applies applyHeightToLastDescent to the maxLines limit line` - `TextHeightBehavior positions first-line placeholders against the reverted ascent` - `TextHeightBehavior bounds background rects by reverted first ascent and last descent` - **WebParagraph corpus (`preferWebParagraph` + `forceTestFonts` vs `origin/master` `2e53c3af41a`)**: - Part 1 (`web_ui` `test/webparagraph/*` + `test/ui/*`): **+6 new tests passing (`207` vs `201`), 0 regressions**. - Part 2 (`packages/flutter`): **+2 tests fixed (`test/painting/text_painter_test.dart: TextHeightBehavior with strut on empty paragraph` and `test/painting/text_painter_test.dart: TextPainter widget span`), 0 regressions**. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant in-code documentation (doc comments with `///`). - [x] If this PR introduces a new feature or capability, I created and linked a website documentation issue or PR in [flutter/website] (or verified none is needed). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [flutter/website]: https://github.com/flutter/website [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: Mouad Debbar <[email protected]>
1 parent 4c6f72f commit f1586fc

4 files changed

Lines changed: 326 additions & 44 deletions

File tree

‎engine/src/flutter/lib/web_ui/lib/src/engine/web_paragraph/layout.dart‎

Lines changed: 120 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -202,10 +202,6 @@ class TextLayout {
202202
// but it only makes sense if we have one line
203203
paragraph.alphabeticBaseline = lines.first.fontBoundingBoxAscent;
204204
paragraph.ideographicBaseline = lines.first.height;
205-
// We only know now which line is the last and we need this information for later
206-
if (lines.isNotEmpty) {
207-
lines.last.lastLine = true;
208-
}
209205
}
210206

211207
double addLine(
@@ -214,6 +210,7 @@ class TextLayout {
214210
ClusterRange hardlineClusterRange,
215211
double top, {
216212
required bool isSyntheticEmptyLine,
213+
required bool isLastLine,
217214
}) {
218215
assert(contentClusterRange.end == whitespaceClusterRange.start);
219216
assert(whitespaceClusterRange.end == hardlineClusterRange.start);
@@ -277,16 +274,18 @@ class TextLayout {
277274
);
278275

279276
if (isSyntheticEmptyLine) {
277+
// A synthetic line after a trailing newline has no text blocks of its own
278+
// and inherits the preceding line's vertical metrics (like SkParagraph's fEndLine).
280279
if (lines.isNotEmpty) {
281-
line.fontBoundingBoxAscent = lines.last.fontBoundingBoxAscent;
282-
line.fontBoundingBoxDescent = lines.last.fontBoundingBoxDescent;
283-
line.paintBoundsAscent = lines.last.paintBoundsAscent;
284-
line.paintBoundsDescent = lines.last.paintBoundsDescent;
280+
line.inheritMetricsFrom(lines.last);
285281
}
286-
line.advance = ui.Rect.fromLTWH(0, top, 0, line.height);
287-
line.trailingSpacesWidth = 0.0;
288-
lines.add(line);
289-
return line.advance.height;
282+
return _finishLine(
283+
line,
284+
top: top,
285+
width: 0.0,
286+
trailingSpacesWidth: 0.0,
287+
isLastLine: isLastLine,
288+
);
290289
}
291290

292291
// Get logical bidi levels belonging to the line.
@@ -481,24 +480,45 @@ class TextLayout {
481480
line.updateBoundingBox(block);
482481
}
483482

484-
// Position each placeholder only after all placeholders have folded their ascent into the line
483+
return _finishLine(
484+
line,
485+
top: top,
486+
// Line advance.width should not include trailing spaces (that are counted as a part of a block)
487+
width: blockShiftFromLineStart - trailingSpacesWidth,
488+
trailingSpacesWidth: trailingSpacesWidth,
489+
isLastLine: isLastLine,
490+
);
491+
}
492+
493+
/// Finalizes [line] vertical metrics and horizontal advance, appends it to
494+
/// [lines], and returns the resulting line height.
495+
double _finishLine(
496+
TextLine line, {
497+
required double top,
498+
required double width,
499+
required double trailingSpacesWidth,
500+
required bool isLastLine,
501+
}) {
502+
// Apply TextHeightBehavior before computing the advance rect so line.height
503+
// already reflects any first-ascent or last-descent override.
504+
line.applyTextHeightBehavior(
505+
paragraph.paragraphStyle.textHeightBehavior,
506+
// Check lines.isEmpty before appending line below.
507+
isFirstLine: lines.isEmpty,
508+
isLastLine: isLastLine,
509+
);
510+
// Position each placeholder only after all placeholders have folded their
511+
// ascent into the line and TextHeightBehavior has potentially reverted the
512+
// first line's ascent.
485513
for (final LineBlock block in line.visualBlocks) {
486514
if (block is PlaceholderBlock) {
487515
block.calculatePlaceholderTop(line.fontBoundingBoxAscent);
488516
}
489517
}
490-
491-
line.advance = ui.Rect.fromLTWH(
492-
0,
493-
top,
494-
// Line advance.width should not include trailing spaces (that are counted as a part of a block)
495-
blockShiftFromLineStart - trailingSpacesWidth,
496-
// At the end this shift is equal to the entire line width
497-
line.height,
498-
);
518+
line.advance = ui.Rect.fromLTWH(0, top, width, line.height);
499519
line.trailingSpacesWidth = trailingSpacesWidth;
520+
line.lastLine = isLastLine;
500521
lines.add(line);
501-
502522
return line.advance.height;
503523
}
504524

@@ -1399,6 +1419,8 @@ class PlaceholderBlock extends LineBlock {
13991419
}
14001420
}
14011421

1422+
/// Positions the placeholder vertically within the line once the final
1423+
/// [lineAscent] is known.
14021424
void calculatePlaceholderTop(double lineAscent) {
14031425
final double top = lineAscent - ascent;
14041426
// The advance needs to be calculated relative to the line. In order to do that, we need to start
@@ -1496,6 +1518,22 @@ class TextLine {
14961518
ui.Rect advance = ui.Rect.zero;
14971519
double fontBoundingBoxAscent = 0.0;
14981520
double fontBoundingBoxDescent = 0.0;
1521+
1522+
/// Unscaled font ascent (without height multipliers) so [ui.TextHeightBehavior]
1523+
/// can revert the first line's ascent.
1524+
double rawFontBoundingBoxAscent = 0.0;
1525+
1526+
/// Unscaled font descent (without height multipliers) so [ui.TextHeightBehavior]
1527+
/// can revert the last line's descent.
1528+
double rawFontBoundingBoxDescent = 0.0;
1529+
1530+
/// True when [ui.TextHeightBehavior.applyHeightToFirstAscent] is false on the
1531+
/// first line, causing the line and its backgrounds to use unscaled ascent.
1532+
bool usesRawAscent = false;
1533+
1534+
/// True when [ui.TextHeightBehavior.applyHeightToLastDescent] is false on the
1535+
/// last line, causing the line and its backgrounds to use unscaled descent.
1536+
bool usesRawDescent = false;
14991537
bool _hasLineMetrics = false;
15001538

15011539
double paintBoundsAscent = 0.0;
@@ -1510,33 +1548,76 @@ class TextLine {
15101548

15111549
List<LineBlock> visualBlocks = <LineBlock>[];
15121550

1551+
/// Copies vertical font and paint metrics from [other].
1552+
///
1553+
/// Used for the synthetic empty line after a trailing newline, which inherits
1554+
/// the preceding line's metrics just like SkParagraph's fEndLine.
1555+
void inheritMetricsFrom(TextLine other) {
1556+
fontBoundingBoxAscent = other.fontBoundingBoxAscent;
1557+
fontBoundingBoxDescent = other.fontBoundingBoxDescent;
1558+
rawFontBoundingBoxAscent = other.rawFontBoundingBoxAscent;
1559+
rawFontBoundingBoxDescent = other.rawFontBoundingBoxDescent;
1560+
paintBoundsAscent = other.paintBoundsAscent;
1561+
paintBoundsDescent = other.paintBoundsDescent;
1562+
_hasLineMetrics = other._hasLineMetrics;
1563+
}
1564+
1565+
/// Applies [textHeightBehavior] overrides to the first line's ascent and the
1566+
/// last line's descent.
1567+
void applyTextHeightBehavior(
1568+
ui.TextHeightBehavior? textHeightBehavior, {
1569+
required bool isFirstLine,
1570+
required bool isLastLine,
1571+
}) {
1572+
if (textHeightBehavior == null) {
1573+
return;
1574+
}
1575+
usesRawAscent = isFirstLine && !textHeightBehavior.applyHeightToFirstAscent;
1576+
usesRawDescent = isLastLine && !textHeightBehavior.applyHeightToLastDescent;
1577+
// Strip the height multiplier from the first line's ascent when disabled.
1578+
if (usesRawAscent) {
1579+
fontBoundingBoxAscent = rawFontBoundingBoxAscent;
1580+
}
1581+
// Strip the height multiplier from the last line's descent when disabled.
1582+
// A single-line paragraph is both first and last, so both branches apply.
1583+
if (usesRawDescent) {
1584+
fontBoundingBoxDescent = rawFontBoundingBoxDescent;
1585+
}
1586+
}
1587+
15131588
void updateBoundingBox(LineBlock block) {
1514-
final double blockAscent;
1515-
final double blockDescent;
1589+
// Only text blocks have painted glyphs; placeholders are not painted by the paragraph.
15161590
if (block is TextBlock) {
1517-
// Line always counts multiplied metrics.
1518-
blockAscent = block.multipliedFontBoundingBoxAscent;
1519-
blockDescent = block.multipliedFontBoundingBoxDescent;
15201591
paintBoundsAscent = math.max(paintBoundsAscent, block.paintBoundsAscent);
15211592
paintBoundsDescent = math.max(paintBoundsDescent, block.paintBoundsDescent);
15221593
paintBoundsLeft = math.min(paintBoundsLeft, block.paintBounds.left);
15231594
paintBoundsRight = math.max(paintBoundsRight, block.paintBounds.right);
1524-
} else if (block is PlaceholderBlock) {
1525-
blockAscent = block.ascent;
1526-
blockDescent = block.descent;
1527-
// There's no need to update paint bounds because placeholders aren't painted by the
1528-
// paragraph.
1529-
} else {
1530-
throw UnsupportedError('Unknown block type: $block');
15311595
}
15321596

1597+
final (double ascent, double descent, double rawAscent, double rawDescent) = switch (block) {
1598+
// Text blocks carry both height-scaled and unscaled font metrics.
1599+
TextBlock() => (
1600+
block.multipliedFontBoundingBoxAscent,
1601+
block.multipliedFontBoundingBoxDescent,
1602+
block.rawFontBoundingBoxAscent,
1603+
block.rawFontBoundingBoxDescent,
1604+
),
1605+
// Placeholders have no height multiplier, so their raw and scaled metrics match.
1606+
PlaceholderBlock() => (block.ascent, block.descent, block.ascent, block.descent),
1607+
_ => throw UnsupportedError('Unknown block type: $block'),
1608+
};
1609+
15331610
if (!_hasLineMetrics) {
1534-
fontBoundingBoxAscent = blockAscent;
1535-
fontBoundingBoxDescent = blockDescent;
1611+
fontBoundingBoxAscent = ascent;
1612+
fontBoundingBoxDescent = descent;
1613+
rawFontBoundingBoxAscent = rawAscent;
1614+
rawFontBoundingBoxDescent = rawDescent;
15361615
_hasLineMetrics = true;
15371616
} else {
1538-
fontBoundingBoxAscent = math.max(fontBoundingBoxAscent, blockAscent);
1539-
fontBoundingBoxDescent = math.max(fontBoundingBoxDescent, blockDescent);
1617+
fontBoundingBoxAscent = math.max(fontBoundingBoxAscent, ascent);
1618+
fontBoundingBoxDescent = math.max(fontBoundingBoxDescent, descent);
1619+
rawFontBoundingBoxAscent = math.max(rawFontBoundingBoxAscent, rawAscent);
1620+
rawFontBoundingBoxDescent = math.max(rawFontBoundingBoxDescent, rawDescent);
15401621
}
15411622
}
15421623
}

‎engine/src/flutter/lib/web_ui/lib/src/engine/web_paragraph/painter.dart‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -231,11 +231,18 @@ abstract class WebParagraphPainter {
231231
// TODO(jlavrova): We use calculateBlock in several places and it may need to calculate the rect height
232232
// differently for background blocks (to include the entire line height instead of just the text height).
233233
// I correct the value in place for now, but it may need to be fixed in calculateBlock itself.
234-
final correctedTargetRect = ui.Rect.fromLTWH(
234+
final double baseline = offset.dy + line.baseline;
235+
final correctedTargetRect = ui.Rect.fromLTRB(
235236
targetRect.left,
236-
targetRect.top,
237-
targetRect.width,
238-
block.multipliedHeight,
237+
baseline -
238+
(line.usesRawAscent
239+
? block.rawFontBoundingBoxAscent
240+
: block.multipliedFontBoundingBoxAscent),
241+
targetRect.right,
242+
baseline +
243+
(line.usesRawDescent
244+
? block.rawFontBoundingBoxDescent
245+
: block.multipliedFontBoundingBoxDescent),
239246
);
240247
_paintBlockBackground(canvas, correctedTargetRect, block.style.background!, transform);
241248
case StyleElements.decorations:

‎engine/src/flutter/lib/web_ui/lib/src/engine/web_paragraph/wrapper.dart‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,12 +365,20 @@ class _LineBuilder {
365365
_widthConsumedText + _widthWhitespaces,
366366
);
367367

368+
final int? maxLines = _layout.paragraph.paragraphStyle.maxLines;
369+
// Check + 1 because this line has not been appended to _layout.lines yet.
370+
final bool willReachMaxLines = maxLines != null && _layout.lines.length + 1 >= maxLines;
371+
// This content line is the last line when it hits maxLines or reaches the
372+
// artificial EOF cluster without a trailing newline.
373+
final bool isLastLine =
374+
willReachMaxLines || (!hasTrailingNewline && _newlineEnd == _layout.allClusters.length - 1);
368375
final double height = _layout.addLine(
369376
ClusterRange(start: start, end: _whitespaceStart),
370377
ClusterRange(start: _whitespaceStart, end: _whitespaceEnd),
371378
ClusterRange(start: _whitespaceEnd, end: _newlineEnd),
372379
_top,
373380
isSyntheticEmptyLine: false,
381+
isLastLine: isLastLine,
374382
);
375383
_top += height;
376384

@@ -385,6 +393,9 @@ class _LineBuilder {
385393
ClusterRange(start: _newlineEnd, end: _newlineEnd),
386394
_top,
387395
isSyntheticEmptyLine: true,
396+
// A trailing newline occurs only at the end of the text, so this
397+
// synthetic empty line is always the last line of the paragraph.
398+
isLastLine: true,
388399
);
389400
} else {
390401
_layout.paragraph.didExceedMaxLines = true;

0 commit comments

Comments
 (0)