diff --git a/AGENTS.md b/AGENTS.md index 9627991..775a673 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -190,7 +190,8 @@ public: - Headings (`h1`..`h6`) default to left-aligned (`TextAlign::Left`) without first-line indentation (`textIndent = 0`). In `Fb2Reader`, `` 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. diff --git a/src/backend/reading/layout/ChunkLayoutEngine.cpp b/src/backend/reading/layout/ChunkLayoutEngine.cpp index ec05cb5..e2509e9 100644 --- a/src/backend/reading/layout/ChunkLayoutEngine.cpp +++ b/src/backend/reading/layout/ChunkLayoutEngine.cpp @@ -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; } diff --git a/src/backend/reading/layout/KnuthPlass.cpp b/src/backend/reading/layout/KnuthPlass.cpp index 8c0cac5..69db301 100644 --- a/src/backend/reading/layout/KnuthPlass.cpp +++ b/src/backend/reading/layout/KnuthPlass.cpp @@ -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 ¶ms) { if (items.isEmpty()) diff --git a/src/backend/reading/layout/KnuthPlass.h b/src/backend/reading/layout/KnuthPlass.h index d8db627..5e7ff1f 100644 --- a/src/backend/reading/layout/KnuthPlass.h +++ b/src/backend/reading/layout/KnuthPlass.h @@ -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); diff --git a/tests/reading/ChunkLayoutEngineTest.cpp b/tests/reading/ChunkLayoutEngineTest.cpp index 437b33c..279e3d9 100644 --- a/tests/reading/ChunkLayoutEngineTest.cpp +++ b/tests/reading/ChunkLayoutEngineTest.cpp @@ -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) diff --git a/tests/reading/KnuthPlassTest.cpp b/tests/reading/KnuthPlassTest.cpp index 740d414..10abd9a 100644 --- a/tests/reading/KnuthPlassTest.cpp +++ b/tests/reading/KnuthPlassTest.cpp @@ -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)