fixed paragraph layout to handle forced breaks

This commit is contained in:
Agel committed 2026-11-01 12:01:26 +01:00
1 parent 8782a3be8a
commit 1ad2f5446b
6 files changed
+142 -11

No files matched your search

+2 -1
View File
@@ -190,7 +190,8 @@ public:
- Headings (`h1`..`h6`) default to left-aligned (`TextAlign::Left`) without first-line indentation (`textIndent = 0`). In `Fb2Reader`, `<title>` flattens child `<p>` lines separated by `<br/>` with `text-align: left; text-indent: 0;`, preventing nested paragraph indent on titles. Scene transitions via FB2 `<empty-line>` use explicit margins to provide intended section gaps.
- When viewport geometry or font preferences change, `ReadingModel::updateLayoutMetrics()` runs `ChunkLayoutEngine` off-thread:
- Pre-parsed `BlockItem`s in `ContentChunk` scale dynamically with user font preferences in `ChunkLayoutEngine::prepareBlocks()` with zero HTML/XML re-parsing.
- `KnuthPlass` computes optimal justified/aligned line breaks.
- `KnuthPlass` computes optimal justified/aligned line breaks. Inline forced breaks (`<br/>`, `InlineItem::Kind::LineBreak`) use `finishLine()` to append infinite stretch glue (`kInfiniteStretch`), ensuring short lines ending at `<br/>` are not justified to full width and do not push the paragraph into loose/emergency fallback passes.
- Overly stretched line fallback: When a line's stretch ratio in a justified paragraph exceeds `tolerance` (`line.ratio > 2.0`), `ChunkLayoutEngine` falls back to natural inter-word spacing (left alignment) rather than stretching words across the viewport with large gaps.
- `BookImageResolver` resolves embedded image dimensions and URLs.
- Off-thread calculation stores `ChunkLayout` and pixel heights.
- **Two-Phase Visible-First Layout**: On book open and font changes, `ReadingModel::startLayoutMeasurement()` computes layout for the visible window around the anchor chunk synchronously (<1ms) and emits `restoreReady(chunkIndex, intraOffset)` immediately so the visible screen renders on the first frame, while the background thread computes remaining off-screen chunks and updates only non-visible model ranges. On-demand layout guards ensure any chunk scrolled to before background completion is measured instantly.
@@ -314,10 +314,18 @@ private:
return;
qreal lineMultiplier = p.lineHeight > 0 ? p.lineHeight : m_params.lineSpacing;
constexpr qreal kMaxJustifyStretchRatio = 2.0;
for (int lIdx = 0; lIdx < lines.size(); ++lIdx) {
const auto &line = lines[lIdx];
const bool isLastLine = (lIdx == lines.size() - 1);
const bool isForcedBreak = (line.end < kpItems.size()
&& kpItems[line.end].type == KnuthPlass::ItemType::Penalty
&& kpItems[line.end].penalty <= -KnuthPlass::kInfinity);
const bool shouldJustifyStretch = (p.align == TextAlign::Justify)
&& !isLastLine
&& !isForcedBreak
&& (line.ratio <= kMaxJustifyStretchRatio);
qreal maxAscent = p.fontSize * 0.8;
qreal maxDescent = p.fontSize * 0.2;
@@ -340,11 +348,13 @@ private:
if (it.type == KnuthPlass::ItemType::Box) {
contentW += it.width;
} else if (it.type == KnuthPlass::ItemType::Glue) {
if (isLastLine || p.align != TextAlign::Justify) {
if (isLastLine || isForcedBreak || p.align != TextAlign::Justify) {
contentW += it.width;
} else if (line.ratio >= 0) {
contentW += it.width + (shouldJustifyStretch ? (line.ratio * it.stretch) : 0.0);
} else {
qreal adj = (line.ratio >= 0) ? (line.ratio * it.stretch) : (line.ratio * it.shrink);
contentW += (std::max)(0.0, it.width + adj);
// Allow normal glue shrink so tight lines fit
contentW += (std::max)(0.0, it.width + line.ratio * it.shrink);
}
}
}
@@ -405,9 +415,14 @@ private:
curX += it.width;
} else if (it.type == KnuthPlass::ItemType::Glue) {
qreal spaceW = it.width;
if (!isLastLine && p.align == TextAlign::Justify) {
qreal adj = (line.ratio >= 0) ? (line.ratio * it.stretch) : (line.ratio * it.shrink);
spaceW = (std::max)(0.0, it.width + adj);
if (!isLastLine && !isForcedBreak && p.align == TextAlign::Justify) {
if (line.ratio >= 0) {
if (shouldJustifyStretch) {
spaceW += line.ratio * it.stretch;
}
} else {
spaceW = (std::max)(0.0, it.width + line.ratio * it.shrink);
}
}
curX += spaceW;
}
@@ -552,7 +567,7 @@ PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
for (const auto &item : b.inlines) {
if (item.kind == InlineItem::Kind::LineBreak) {
pb.paragraph.kpItems.append(KnuthPlass::Item::penaltyItem(0, -KnuthPlass::kInfinity, false));
KnuthPlass::finishLine(pb.paragraph.kpItems);
continue;
}
+14 -3
View File
@@ -131,7 +131,7 @@ public:
if (r < -1 || r > tolerance)
continue;
const qreal badness = (std::min)(100.0 * std::pow(std::abs(r), 3), kInfinity);
const qreal badness = (std::min)(100.0 * std::pow(std::abs(r), 3), 1e7);
qreal d = m_params.linePenalty + badness;
d *= d;
if (brk.type == ItemType::Penalty) {
@@ -230,16 +230,27 @@ private:
} // namespace
void finishParagraph(QVector<Item> &items)
void finishLine(QVector<Item> &items)
{
// A trailing glue would otherwise become a legal break before the end.
// A trailing glue would otherwise become a legal break before the line end.
while (!items.isEmpty() && items.last().type == ItemType::Glue)
items.removeLast();
// If there is no content on this line (e.g. leading break or consecutive <br/><br/>),
// append a zero-width box so that subsequent finishing glue contributes to the ratio.
if (items.isEmpty() || isForced(items.last()))
items.append(Item::box(0, -1));
items.append(Item::penaltyItem(0, kInfinity, false));
items.append(Item::glue(0, kInfiniteStretch, 0));
items.append(Item::penaltyItem(0, -kInfinity, false));
}
void finishParagraph(QVector<Item> &items)
{
finishLine(items);
}
QVector<Line> breakLines(const QVector<Item> &items, qreal lineWidth, const Params &params)
{
if (items.isEmpty())
+3
View File
@@ -64,6 +64,9 @@ struct Line {
bool hyphenated = false; // ended at a flagged penalty with width (draw a hyphen)
};
// Appends an inline line ending: finishing glue + forced break (e.g. for <br/>).
void finishLine(QVector<Item> &items);
// Appends the standard paragraph ending: finishing glue + forced break.
void finishParagraph(QVector<Item> &items);
+63
View File
@@ -462,6 +462,69 @@ private slots:
QCOMPARE(styledBlocks[1].textIndent, 0.0);
QCOMPARE(styledBlocks[2].kind, BlockItem::Kind::ContainerEnd);
}
void lineBreakBeforeParagraphEndDoesNotStretch()
{
// Simulating the Protector.epub Summary block:
// A paragraph with short lines separated by <br/>, with text-align: justify
const QString html = QStringLiteral(
"<p style=\"text-align: justify;\">"
"This does not contain non-con or Loki treating Tony like a slave.<br/>"
"It's a hurt/comfort-story."
"</p>"
);
LayoutParams params;
params.contentWidth = 800; // Wide viewport where each line easily fits on one line
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QCOMPARE(layout.lines.size(), 2);
// Neither line should stretch to fill the 800px width.
// The first line has text ending at its natural width, not reaching anywhere near 800.
const auto &line1 = layout.lines[0];
QVERIFY(!line1.runs.isEmpty());
const qreal line1Right = line1.runs.last().rect.right();
QVERIFY(line1Right < 700.0);
const auto &line2 = layout.lines[1];
QVERIFY(!line2.runs.isEmpty());
const qreal line2Right = line2.runs.last().rect.right();
QVERIFY(line2Right < 400.0);
}
void overstretchedJustifiedLineFallsBackToNaturalSpacing()
{
// When a line in a justified paragraph has an extreme ratio (> 2.0),
// e.g. because the next word is slightly too wide to fit on the line,
// it must not stretch spaces across the line to fill the container.
// E.g.: "WordA WordB" (fits in ~120px) followed by "MediumLengthWord" (fits on next line in 200px width).
// 120px in 200px line width: shortfall = 80px, glue stretch = ~2-3px -> ratio = 80/2 = 40.0 >> 2.0!
BlockItem p;
p.kind = BlockItem::Kind::Paragraph;
p.align = TextAlign::Justify;
p.fontSize = 16.0;
InlineItem t1;
t1.kind = InlineItem::Kind::Text;
t1.text = QStringLiteral("WordA WordB MediumLengthWordThatCannotFitOnLineOne");
p.inlines.append(t1);
LayoutParams params;
params.contentWidth = 200;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutBlocks({p}, params);
QVERIFY(layout.lines.size() >= 2);
// First line has "WordA WordB". Since ratio > 2.0, it should NOT be stretched to fill 200px.
const auto &line0 = layout.lines[0];
QVERIFY(!line0.runs.isEmpty());
// Natural width of "WordA WordB" is ~120px; stretched to 200px it would be 200px.
QVERIFY(line0.runs.last().rect.right() < 160.0);
}
};
QTEST_MAIN(ChunkLayoutEngineTest)
+38
View File
@@ -80,6 +80,44 @@ private slots:
auto lines = KnuthPlass::breakLines(items, 100);
QCOMPARE(lines.size(), 1);
}
void inlineLineBreakFinishLine()
{
// "Line 1" <br/> "Line 2"
QVector<KnuthPlass::Item> items;
items.append(KnuthPlass::Item::box(30, 0));
items.append(KnuthPlass::Item::glue(10, 5, 3, -1));
items.append(KnuthPlass::Item::box(30, 1));
KnuthPlass::finishLine(items);
items.append(KnuthPlass::Item::box(40, 2));
items.append(KnuthPlass::Item::glue(10, 5, 3, -1));
items.append(KnuthPlass::Item::box(40, 3));
KnuthPlass::finishParagraph(items);
// Line width 200: both lines are short.
// Because finishLine inserted infinite stretch glue, line 1 must have ratio 0.0 (like line 2).
auto lines = KnuthPlass::breakLines(items, 200);
QCOMPARE(lines.size(), 2);
QCOMPARE(lines[0].ratio, 0.0);
QCOMPARE(lines[1].ratio, 0.0);
}
void consecutiveLineBreaks()
{
// "Line 1" <br/> <br/> "Line 2"
QVector<KnuthPlass::Item> items;
items.append(KnuthPlass::Item::box(30, 0));
KnuthPlass::finishLine(items);
KnuthPlass::finishLine(items); // consecutive break with empty line
items.append(KnuthPlass::Item::box(40, 1));
KnuthPlass::finishParagraph(items);
auto lines = KnuthPlass::breakLines(items, 200);
QCOMPARE(lines.size(), 3);
QCOMPARE(lines[0].ratio, 0.0);
QCOMPARE(lines[1].ratio, 0.0);
QCOMPARE(lines[2].ratio, 0.0);
}
};
QTEST_MAIN(KnuthPlassTest)