diff --git a/AGENTS.md b/AGENTS.md index 45e737b..200c3d3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -159,6 +159,7 @@ public: ### 1. Text Mode (`ScrollPageView.qml`) - `ReadingModel` manages a list of HTML chunks. + - `EpubReader` unwraps unstyled structural containers (`
`, `
`, `
`, etc.) that contain block-level children and partitions documents into fine-grained block/paragraph chunks (~512 chars max), propagating inherited CSS declarations. Paragraph `
`s containing inline markup (``, ``, ``, etc.) are preserved intact as atomic blocks without fragmenting text or punctuation. - When viewport geometry or font preferences change, `ReadingModel::updateLayoutMetrics()` runs `ChunkLayoutEngine` off-thread: - `HtmlBlockParser` extracts structured blocks (`Paragraph`, `ImageBlock`, `Rule`, `Container`). - Block-level `background` sets `BoxStyle::background` (emitted as `PositionedDecoration`), while inline spans apply to `TextStyle::background` (individual word runs). @@ -167,7 +168,10 @@ public: - `KnuthPlass` computes optimal justified/aligned line breaks. - `BookImageResolver` resolves embedded image dimensions and URLs. - Off-thread calculation stores `ChunkLayout` and pixel heights. -- Rendered in a virtualized `ListView` (`cacheBuffer: 600`, high flick velocity) using `KnuthPlassItem`. +- **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. +- Rendered in a strictly virtualized `ListView` (`cacheBuffer: 0`, `reuseItems: true`, high flick velocity) using `KnuthPlassItem` as the direct delegate, preserving smooth scrolling without allocating off-screen delegate textures. + - **Debug Chunk Index**: In debug builds (`isDebugBuild`), displays the chunk index at the top-left of each list item (`x: 4, y: 2`), ignoring `horizontalMargin`. +- **Clip-Rect Culling in `KnuthPlassItem`**: `paint()` inspects `painter->clipBoundingRect()`, skips decorations/rules outside the clip, uses $O(\log N)$ binary search (`std::lower_bound`) to draw only lines intersecting the clip, and skips off-screen image decoding/resolution completely. - **Publisher Colours vs Theme**: Controlled by per-book `useBookColours` setting (default `false`). - When off: paints with theme palette (`readingText`, `dimText`, `buttonAccent`), omitting publisher backgrounds and border boxes (semantic blockquote bars with only `borderLeft` and no explicit border colour are drawn in `dimText`). - When on: paints publisher backgrounds and border colours, using WCAG contrast calculation (`contrastRatio < 3.0`) to automatically select high-contrast black or white text when publisher or theme text colours would be unreadable on the effective background. diff --git a/src/backend/ReadingModel.cpp b/src/backend/ReadingModel.cpp index d8d1a15..f7a2742 100644 --- a/src/backend/ReadingModel.cpp +++ b/src/backend/ReadingModel.cpp @@ -38,13 +38,41 @@ QVariant ReadingModel::data(const QModelIndex &index, int role) const return {}; if (role == ContentRole) return m_chunks.at(index.row()); - if (role == LayoutRole && index.row() < m_chunkLayouts.size()) + if (role == LayoutRole && index.row() < m_chunks.size()) { + ensureChunkLayout(index.row()); return QVariant::fromValue(m_chunkLayouts.at(index.row())); - if (role == PixelHeightRole && index.row() < m_chunkLayouts.size()) + } + if (role == PixelHeightRole && index.row() < m_chunks.size()) { + if (index.row() < m_chunkLayouts.size() && m_chunkLayouts.at(index.row()).totalHeight > 0 && !m_chunkLayouts.at(index.row()).lines.isEmpty()) + return m_chunkLayouts.at(index.row()).totalHeight; + ensureChunkLayout(index.row()); return m_chunkLayouts.at(index.row()).totalHeight; + } return {}; } +void ReadingModel::ensureChunkLayout(int row) const +{ + if (row < 0 || row >= m_chunks.size()) + return; + if (row < m_chunkLayouts.size() && m_chunkLayouts[row].totalHeight > 0 && !m_chunkLayouts[row].lines.isEmpty()) + return; + if (row >= m_preparedChunks.size()) + m_preparedChunks.resize(m_chunks.size()); + if (row >= m_chunkLayouts.size()) + m_chunkLayouts.resize(m_chunks.size()); + + LayoutParams params; + params.contentWidth = m_layoutContentWidth; + params.fontSize = m_layoutFontSize; + params.lineSpacing = m_layoutLineSpacing; + + if (m_preparedChunks[row].blocks.isEmpty() && !m_chunks[row].isEmpty()) { + m_preparedChunks[row] = ChunkLayoutEngine::prepareChunk(m_chunks[row], params.fontSize, m_imageResolver); + } + m_chunkLayouts[row] = ChunkLayoutEngine::layoutPreparedChunk(m_preparedChunks[row], params); +} + QHash ReadingModel::roleNames() const { return { @@ -107,8 +135,11 @@ void ReadingModel::updateLayoutMetrics(int contentWidth, int fontSize, qreal lin params.fontSize = m_layoutFontSize; params.lineSpacing = m_layoutLineSpacing; - const int startIdx = std::max(0, targetChunk - 2); - const int endIdx = std::min(int(m_preparedChunks.size() - 1), targetChunk + 4); + const int startIdx = std::max(0, targetChunk - 5); + const int endIdx = std::min(int(m_preparedChunks.size() - 1), targetChunk + 25); + + m_lastSyncStart = startIdx; + m_lastSyncEnd = endIdx; if (m_chunkLayouts.size() != m_preparedChunks.size()) { m_chunkLayouts.resize(m_preparedChunks.size()); @@ -141,9 +172,11 @@ void ReadingModel::runRemainingLayout() params.contentWidth = m_layoutContentWidth; params.fontSize = m_layoutFontSize; params.lineSpacing = m_layoutLineSpacing; + const int syncStart = m_lastSyncStart; + const int syncEnd = m_lastSyncEnd; QPointer self(this); - m_layoutFuture = QtConcurrent::run([self, generation, prepared, params]() { + m_layoutFuture = QtConcurrent::run([self, generation, prepared, params, syncStart, syncEnd]() { QVector newLayouts = QtConcurrent::blockingMapped( prepared, [params](const ChunkLayoutEngine::PreparedChunk &prep) { @@ -153,12 +186,20 @@ void ReadingModel::runRemainingLayout() if (!self || self->m_layoutGeneration != generation) return; - QMetaObject::invokeMethod(self.data(), [self, generation, newLayouts = std::move(newLayouts)]() mutable { + QMetaObject::invokeMethod(self.data(), [self, generation, newLayouts = std::move(newLayouts), syncStart, syncEnd]() mutable { if (!self || generation != self->m_layoutGeneration) return; self->m_chunkLayouts = std::move(newLayouts); if (!self->m_chunkLayouts.isEmpty()) { - emit self->dataChanged(self->index(0, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole}); + if (syncStart > 0) { + emit self->dataChanged(self->index(0, 0), self->index(syncStart - 1, 0), {LayoutRole, PixelHeightRole}); + } + if (syncEnd >= 0 && syncEnd + 1 < self->m_chunkLayouts.size()) { + emit self->dataChanged(self->index(syncEnd + 1, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole}); + } + if (syncStart < 0 && syncEnd < 0) { + emit self->dataChanged(self->index(0, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole}); + } } }, Qt::QueuedConnection); }); @@ -235,8 +276,40 @@ void ReadingModel::startLayoutMeasurement(int restoreChunk, qreal restoreIntraOf params.lineSpacing = m_layoutLineSpacing; auto *resolver = m_imageResolver; + // Phase 1: Immediately prepare and layout the visible window synchronously (<1ms) + const int startIdx = std::max(0, restoreChunk - 5); + const int endIdx = std::min(int(chunks.size() - 1), restoreChunk + 25); + + m_preparedChunks.resize(chunks.size()); + m_chunkLayouts.resize(chunks.size()); + + for (int i = startIdx; i <= endIdx; ++i) { + m_preparedChunks[i] = ChunkLayoutEngine::prepareChunk(chunks[i], params.fontSize, resolver); + m_chunkLayouts[i] = ChunkLayoutEngine::layoutPreparedChunk(m_preparedChunks[i], params); + } + for (int i = 0; i < chunks.size(); ++i) { + if (i < startIdx || i > endIdx) { + m_chunkLayouts[i].totalHeight = 60.0; + } + } + + m_lastSyncStart = startIdx; + m_lastSyncEnd = endIdx; + + if (startIdx <= endIdx) { + emit dataChanged(index(startIdx, 0), index(endIdx, 0), {LayoutRole, PixelHeightRole}); + } + emit restoreReady(restoreChunk, restoreIntraOffset); + + if (startIdx == 0 && endIdx == chunks.size() - 1) { + m_measuring = false; + emit measuringChanged(); + return; + } + + // Phase 2: Compute remaining chunks in the background QPointer self(this); - m_layoutFuture = QtConcurrent::run([self, generation, chunks, params, resolver, restoreChunk, restoreIntraOffset]() { + m_layoutFuture = QtConcurrent::run([self, generation, chunks, params, resolver, startIdx, endIdx]() { auto prepared = QtConcurrent::blockingMapped(chunks, [params, resolver](const QString &chunkHtml) { return ChunkLayoutEngine::prepareChunk(chunkHtml, params.fontSize, resolver); }); @@ -251,17 +324,19 @@ void ReadingModel::startLayoutMeasurement(int restoreChunk, qreal restoreIntraOf if (!self || self->m_layoutGeneration != generation) return; - QMetaObject::invokeMethod(self.data(), [self, generation, prepared = std::move(prepared), layouts = std::move(layouts), restoreChunk, restoreIntraOffset]() mutable { + QMetaObject::invokeMethod(self.data(), [self, generation, prepared = std::move(prepared), layouts = std::move(layouts), startIdx, endIdx]() mutable { if (!self || generation != self->m_layoutGeneration) return; self->m_preparedChunks = std::move(prepared); self->m_chunkLayouts = std::move(layouts); self->m_measuring = false; emit self->measuringChanged(); - if (!self->m_chunkLayouts.isEmpty()) { - emit self->dataChanged(self->index(0, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole}); + if (startIdx > 0) { + emit self->dataChanged(self->index(0, 0), self->index(startIdx - 1, 0), {LayoutRole, PixelHeightRole}); + } + if (endIdx + 1 < self->m_chunkLayouts.size()) { + emit self->dataChanged(self->index(endIdx + 1, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole}); } - emit self->restoreReady(restoreChunk, restoreIntraOffset); }, Qt::QueuedConnection); }); } diff --git a/src/backend/ReadingModel.h b/src/backend/ReadingModel.h index cc5794f..edd9f96 100644 --- a/src/backend/ReadingModel.h +++ b/src/backend/ReadingModel.h @@ -98,6 +98,7 @@ private: void startLayoutMeasurement(int restoreChunk = 0, qreal restoreIntraOffset = 0.0); void runRemainingLayout(); void saveCurrentPosition(int chunkIndex, qreal intraOffset = 0.0); + void ensureChunkLayout(int row) const; FormatReader *m_reader = nullptr; IBookImageResolver *m_imageResolver = nullptr; @@ -106,8 +107,10 @@ private: int m_currentPage = 0; int m_totalPages = 0; QStringList m_chunks; - QVector m_preparedChunks; - QVector m_chunkLayouts; + mutable QVector m_preparedChunks; + mutable QVector m_chunkLayouts; + int m_lastSyncStart = -1; + int m_lastSyncEnd = -1; int m_layoutContentWidth = 600; int m_layoutFontSize = 16; diff --git a/src/backend/formats/EpubReader.cpp b/src/backend/formats/EpubReader.cpp index a3c4f26..e57069f 100644 --- a/src/backend/formats/EpubReader.cpp +++ b/src/backend/formats/EpubReader.cpp @@ -220,10 +220,155 @@ void EpubReader::appendSpineChunks(const QString &xhtml, } QDomElement body = bodies.at(0).toElement(); - QString currentChunk; - static constexpr int kChunkTargetSize = 4096; - for (QDomNode node = body.firstChild(); !node.isNull(); node = node.nextSibling()) { + auto hasBoxDecoration = [](const QDomElement &el) -> bool { + const QString style = el.attribute(QStringLiteral("style")).toLower(); + if (style.isEmpty()) + return false; + const auto decls = Css::parseDeclarations(style); + for (const auto &d : decls) { + const QString p = d.property.toLower(); + if (p.contains(QLatin1String("background")) && d.value != QLatin1String("none") && d.value != QLatin1String("transparent")) + return true; + if (p.contains(QLatin1String("border")) && !d.value.startsWith(QLatin1String("none")) && !d.value.startsWith(QLatin1String("0"))) + return true; + } + return false; + }; + + static const QStringList kInheritableProperties = { + QStringLiteral("color"), + QStringLiteral("font-family"), + QStringLiteral("font-size"), + QStringLiteral("font-style"), + QStringLiteral("font-weight"), + QStringLiteral("line-height"), + QStringLiteral("text-align"), + QStringLiteral("letter-spacing"), + QStringLiteral("text-transform") + }; + + auto propagateInheritedStyles = [](const QDomElement &parentEl, QDomElement &childEl) { + const auto parentDecls = Css::parseDeclarations(parentEl.attribute(QStringLiteral("style"))); + if (parentDecls.isEmpty()) + return; + auto childDecls = Css::parseDeclarations(childEl.attribute(QStringLiteral("style"))); + QSet childProps; + for (const auto &cd : childDecls) { + childProps.insert(cd.property.toLower()); + } + bool modified = false; + for (const auto &pd : parentDecls) { + const QString prop = pd.property.toLower(); + if (kInheritableProperties.contains(prop) && !childProps.contains(prop)) { + childDecls.append(pd); + childProps.insert(prop); + modified = true; + } + } + if (modified) { + childEl.setAttribute(QStringLiteral("style"), Css::serialize(childDecls)); + } + }; + + static const QSet kBlockTags = { + QStringLiteral("p"), QStringLiteral("div"), + QStringLiteral("h1"), QStringLiteral("h2"), + QStringLiteral("h3"), QStringLiteral("h4"), + QStringLiteral("h5"), QStringLiteral("h6"), + QStringLiteral("blockquote"), QStringLiteral("pre"), + QStringLiteral("ul"), QStringLiteral("ol"), + QStringLiteral("li"), QStringLiteral("table"), + QStringLiteral("hr"), QStringLiteral("figure"), + QStringLiteral("section"), QStringLiteral("article"), + QStringLiteral("header"), QStringLiteral("footer"), + QStringLiteral("aside") + }; + + static const QSet kStructuralTags = { + QStringLiteral("div"), + QStringLiteral("section"), + QStringLiteral("article"), + QStringLiteral("main"), + QStringLiteral("header"), + QStringLiteral("footer"), + QStringLiteral("aside") + }; + + std::function hasBlockChild = [&](const QDomElement &el) { + for (QDomNode n = el.firstChild(); !n.isNull(); n = n.nextSibling()) { + if (n.isElement()) { + const QString childTag = n.toElement().tagName().toLower(); + if (kBlockTags.contains(childTag)) { + return true; + } + } + } + return false; + }; + + QVector blockNodes; + std::function collectBlocks = [&](const QDomElement &parent) { + QDomDocument parentDoc = parent.ownerDocument(); + QDomElement pendingInlinePara; + + auto flushPendingInline = [&]() { + if (!pendingInlinePara.isNull()) { + if (!pendingInlinePara.text().trimmed().isEmpty() || pendingInlinePara.elementsByTagName(QStringLiteral("img")).size() > 0) { + blockNodes.append(pendingInlinePara); + } + pendingInlinePara = QDomElement(); + } + }; + + for (QDomNode child = parent.firstChild(); !child.isNull(); child = child.nextSibling()) { + if (!child.isElement()) { + if (child.isText() && !child.toText().data().trimmed().isEmpty()) { + if (pendingInlinePara.isNull()) { + pendingInlinePara = parentDoc.createElement(QStringLiteral("p")); + } + pendingInlinePara.appendChild(child.cloneNode(true)); + } + continue; + } + + QDomElement childEl = child.toElement(); + const QString tag = childEl.tagName().toLower(); + + if (!kBlockTags.contains(tag)) { + // Inline element (e.g. , , , ) directly in container + if (pendingInlinePara.isNull()) { + pendingInlinePara = parentDoc.createElement(QStringLiteral("p")); + } + pendingInlinePara.appendChild(childEl.cloneNode(true)); + continue; + } + + // Child is a block element: flush any preceding inline nodes into their own block + flushPendingInline(); + + // Unwrap only structural containers that have block-level children and no box decoration + if (kStructuralTags.contains(tag) && !hasBoxDecoration(childEl) && hasBlockChild(childEl)) { + for (QDomNode n = childEl.firstChild(); !n.isNull(); n = n.nextSibling()) { + if (n.isElement()) { + QDomElement subEl = n.toElement(); + propagateInheritedStyles(childEl, subEl); + } + } + collectBlocks(childEl); + } else { + blockNodes.append(childEl); + } + } + + flushPendingInline(); + }; + collectBlocks(body); + + QString currentChunk; + static constexpr int kChunkTargetSize = 512; + + for (const QDomNode &node : blockNodes) { QString serialized; QTextStream ts(&serialized); node.save(ts, 0); diff --git a/src/backend/reading/KnuthPlassItem.cpp b/src/backend/reading/KnuthPlassItem.cpp index d19b171..dee999a 100644 --- a/src/backend/reading/KnuthPlassItem.cpp +++ b/src/backend/reading/KnuthPlassItem.cpp @@ -4,7 +4,7 @@ #include "BookImageResolver.h" -BookImageResolver *KnuthPlassItem::s_imageResolver = nullptr; +IBookImageResolver *KnuthPlassItem::s_imageResolver = nullptr; KnuthPlassItem::KnuthPlassItem(QQuickItem *parent) : QQuickPaintedItem(parent) @@ -13,7 +13,7 @@ KnuthPlassItem::KnuthPlassItem(QQuickItem *parent) setRenderTarget(QQuickPaintedItem::Image); } -void KnuthPlassItem::setImageResolver(BookImageResolver *resolver) +void KnuthPlassItem::setImageResolver(IBookImageResolver *resolver) { s_imageResolver = resolver; } @@ -124,11 +124,19 @@ void KnuthPlassItem::paint(QPainter *painter) const qreal offX = m_horizontalMargin; + QRectF clip = painter->clipBoundingRect(); + if (clip.isEmpty()) { + clip = QRectF(0, 0, width(), height()); + } + // 1. Draw block decorations (backgrounds & borders) for (const auto &dec : m_layout.decorations) { QRectF r = dec.rect; r.translate(offX, 0); + if (r.bottom() < clip.top() || r.top() > clip.bottom()) + continue; + if (m_useBookColours) { if (dec.background.isValid() && dec.background.alpha() > 0) { painter->fillRect(r, dec.background); @@ -160,6 +168,10 @@ void KnuthPlassItem::paint(QPainter *painter) for (const auto &rule : m_layout.rules) { QRectF r = rule.rect; r.translate(offX, 0); + + if (r.bottom() < clip.top() || r.top() > clip.bottom()) + continue; + QColor rc = (m_useBookColours && rule.color.isValid()) ? rule.color : m_dimColor; painter->fillRect(r, rc); } @@ -172,7 +184,16 @@ void KnuthPlassItem::paint(QPainter *painter) const QColor baseSurface = m_surfaceColor.isValid() ? m_surfaceColor : QColor(25, 29, 53); - for (const auto &line : m_layout.lines) { + auto it = std::lower_bound(m_layout.lines.begin(), m_layout.lines.end(), clip.top(), + [](const PositionedLine &line, qreal clipTop) { + return line.rect.bottom() < clipTop; + }); + + for (; it != m_layout.lines.end(); ++it) { + const auto &line = *it; + if (line.rect.top() > clip.bottom()) + break; + for (const auto &run : line.runs) { QRectF r = run.rect; r.translate(offX, 0); @@ -236,6 +257,9 @@ void KnuthPlassItem::paint(QPainter *painter) QRectF r = imgItem.targetRect; r.translate(offX, 0); + if (r.bottom() < clip.top() || r.top() > clip.bottom()) + continue; + QImage img; if (s_imageResolver) { img = s_imageResolver->resolveImage(imgItem.url); diff --git a/src/backend/reading/KnuthPlassItem.h b/src/backend/reading/KnuthPlassItem.h index c388603..38cda47 100644 --- a/src/backend/reading/KnuthPlassItem.h +++ b/src/backend/reading/KnuthPlassItem.h @@ -7,7 +7,7 @@ #include "layout/ChunkLayoutEngine.h" -class BookImageResolver; +class IBookImageResolver; class KnuthPlassItem : public QQuickPaintedItem { Q_OBJECT @@ -48,7 +48,7 @@ public: void paint(QPainter *painter) override; - static void setImageResolver(BookImageResolver *resolver); + static void setImageResolver(IBookImageResolver *resolver); protected: void geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry) override; @@ -70,6 +70,6 @@ private: bool m_useBookColours = false; qreal m_horizontalMargin = 0; - static BookImageResolver *s_imageResolver; + static IBookImageResolver *s_imageResolver; }; diff --git a/src/qml/components/ScrollPageView.qml b/src/qml/components/ScrollPageView.qml index 41debb2..d573f50 100644 --- a/src/qml/components/ScrollPageView.qml +++ b/src/qml/components/ScrollPageView.qml @@ -107,25 +107,37 @@ Rectangle { anchors.topMargin: readingPreferences.verticalMargin anchors.bottomMargin: readingPreferences.verticalMargin model: contentReady ? readingModel : null - cacheBuffer: 600 + cacheBuffer: 0 + reuseItems: true clip: true maximumFlickVelocity: 99999 - delegate: Item { + delegate: KnuthPlassItem { id: chunkDelegate width: chunkListView.width - height: model.pixelHeight > 0 ? model.pixelHeight : 30 + height: (model && model.pixelHeight > 0) ? model.pixelHeight : 30 + layout: model ? model.layout : null + textColor: ThemeManager.currentTheme.readingText + linkColor: ThemeManager.currentTheme.buttonAccent + dimColor: ThemeManager.currentTheme.dimText + surfaceColor: ThemeManager.currentTheme.surface + useBookColours: readingModel.useBookColours + horizontalMargin: readingPreferences.horizontalMargin - KnuthPlassItem { - width: parent.width - height: parent.height - layout: model.layout - textColor: ThemeManager.currentTheme.readingText - linkColor: ThemeManager.currentTheme.buttonAccent - dimColor: ThemeManager.currentTheme.dimText - surfaceColor: ThemeManager.currentTheme.surface - useBookColours: readingModel.useBookColours - horizontalMargin: readingPreferences.horizontalMargin + Loader { + active: isDebugBuild + visible: isDebugBuild + sourceComponent: Text { + text: index !== undefined ? index.toString() : "" + font.pixelSize: 10 + font.family: "monospace" + font.bold: true + color: ThemeManager.currentTheme.buttonAccent + opacity: 0.85 + x: 4 + y: 2 + z: 10 + } } } diff --git a/tests/ReadingModelTest.cpp b/tests/ReadingModelTest.cpp index 2130670..4beafc0 100644 --- a/tests/ReadingModelTest.cpp +++ b/tests/ReadingModelTest.cpp @@ -51,6 +51,29 @@ public: } }; +class ManyChunksTextReader : public FormatReader { +public: + ReadingMode mode() const override { return ReadingMode::Text; } + bool open(const QString &) override { return true; } + QString lastError() const override { return {}; } + QString title() const override { return QStringLiteral("Many Chunks"); } + QString author() const override { return QStringLiteral("Author"); } + QString filePath() const override { return QStringLiteral("/fake/many.epub"); } + QString coverImageUrl() const override { return {}; } + QByteArray contentHash() const override { return QByteArray("manychunks"); } + bool loadMetadata(const QString &) override { return true; } + + QStringList chunks() const override + { + QStringList list; + list.reserve(60); + for (int i = 0; i < 60; ++i) { + list.append(QStringLiteral("

Paragraph chunk number %1 with some text content.

").arg(i)); + } + return list; + } +}; + class ReadingModelTest : public QObject { Q_OBJECT @@ -243,6 +266,29 @@ private slots: model.setReader(nullptr); QCOMPARE(model.useBookColours(), false); } + + void visibleFirstLayoutAndOnDemandLayout() + { + Ctx ctx; + ReadingModel model(*ctx.store); + ManyChunksTextReader reader; + QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady); + + model.setReader(&reader); + + // restoreReady must be emitted immediately from Phase 1 (<1ms) + QCOMPARE(restoreSpy.count(), 1); + QCOMPARE(restoreSpy.first().at(0).toInt(), 0); + + // Row 0..25 are laid out immediately + QVERIFY(model.data(model.index(0, 0), ReadingModel::PixelHeightRole).toReal() > 0); + QVERIFY(!model.data(model.index(0, 0), ReadingModel::LayoutRole).value().lines.isEmpty()); + + // Far-away row (e.g. 55) layout should be computed on-demand if queried + QVERIFY(model.data(model.index(55, 0), ReadingModel::PixelHeightRole).toReal() > 0); + const auto layout55 = model.data(model.index(55, 0), ReadingModel::LayoutRole).value(); + QVERIFY(!layout55.lines.isEmpty()); + } }; QTEST_MAIN(ReadingModelTest) diff --git a/tests/formats/EpubReaderTest.cpp b/tests/formats/EpubReaderTest.cpp index ba42af7..2ae5ee0 100644 --- a/tests/formats/EpubReaderTest.cpp +++ b/tests/formats/EpubReaderTest.cpp @@ -189,6 +189,124 @@ private slots: QVERIFY(!reader.chunks().isEmpty()); QVERIFY(reader.chunks().first().contains(QStringLiteral("Hello EPUB 3"))); } + + void chapterWrapperUnwrappedIntoGranularChunks() + { + auto src = std::make_unique(); + + src->m_entries.insert(QStringLiteral("META-INF/container.xml"), + "\n" + " \n" + " \n" + " \n" + ""); + + src->m_entries.insert(QStringLiteral("EPUB/package.opf"), + "\n" + " \n" + " Unwrap Test\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + ""); + + // Generates several long paragraphs inside a single wrapper div + QString xhtml = QStringLiteral( + "\n" + "
\n" + ); + for (int i = 0; i < 10; ++i) { + xhtml += QStringLiteral("

This is paragraph %1 with sufficient text to exceed the target chunk size when combined together with other paragraphs in the chapter.

\n").arg(i); + } + xhtml += QStringLiteral("
"); + + src->m_entries.insert(QStringLiteral("EPUB/ch1.xhtml"), xhtml.toUtf8()); + + auto sharedEntries = std::make_shared>(src->m_entries); + auto factory = [sharedEntries]() { + auto s = std::make_unique(); + s->m_entries = *sharedEntries; + return s; + }; + + EpubReader reader(factory, QStringLiteral("epub")); + QVERIFY(reader.open(QStringLiteral("/virtual/unwrap.epub"))); + + // Must be split into multiple granular chunks instead of one single monolithic chunk + QVERIFY(reader.chunks().size() >= 3); + // Children must inherit text-align: justify + for (const QString &c : reader.chunks()) { + QVERIFY(c.contains(QStringLiteral("text-align:justify")) || c.contains(QStringLiteral("text-align: justify"))); + } + } + + void divParagraphWithInlineElementsNotBroken() + { + auto src = std::make_unique(); + + src->m_entries.insert(QStringLiteral("META-INF/container.xml"), + "\n" + " \n" + " \n" + " \n" + ""); + + src->m_entries.insert(QStringLiteral("EPUB/package.opf"), + "\n" + " \n" + " Inline Div Test\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + ""); + + QString xhtml = QStringLiteral( + "\n" + "
\n" + "
«Одноглазый».
\n" + "
«Когда я умру, они съедят меня и оставят только кости», — эта мысль странным образом утешала.
\n" + "
" + ); + src->m_entries.insert(QStringLiteral("EPUB/ch1.xhtml"), xhtml.toUtf8()); + + auto sharedEntries = std::make_shared>(src->m_entries); + auto factory = [sharedEntries]() { + auto s = std::make_unique(); + s->m_entries = *sharedEntries; + return s; + }; + + EpubReader reader(factory, QStringLiteral("epub")); + QVERIFY(reader.open(QStringLiteral("/virtual/inline_div.epub"))); + + bool foundOdnoglazyiTogether = false; + bool foundThoughtTogether = false; + + for (const QString &chunk : reader.chunks()) { + if (chunk.contains(QStringLiteral("Одноглазый"))) { + // Must have both opening and closing quotes together in the same chunk + QVERIFY(chunk.contains(QStringLiteral("«"))); + QVERIFY(chunk.contains(QStringLiteral("»"))); + foundOdnoglazyiTogether = true; + } + if (chunk.contains(QStringLiteral("Когда я умру"))) { + // Must have the attribution text in the same chunk + QVERIFY(chunk.contains(QStringLiteral("эта мысль странным образом утешала"))); + foundThoughtTogether = true; + } + } + + QVERIFY(foundOdnoglazyiTogether); + QVERIFY(foundThoughtTogether); + } }; QTEST_MAIN(EpubReaderTest) diff --git a/tests/reading/ChunkLayoutEngineTest.cpp b/tests/reading/ChunkLayoutEngineTest.cpp index e6f7686..f92fecf 100644 --- a/tests/reading/ChunkLayoutEngineTest.cpp +++ b/tests/reading/ChunkLayoutEngineTest.cpp @@ -311,6 +311,64 @@ private slots: // With useBookColours = true, (testX, testY) is drawn with border or background QVERIFY(imgTrue.pixelColor(testX, testY).alpha() > 0); } + + void clipRectCullingSkipsOffscreenImage() + { + class TrackingResolver : public IBookImageResolver { + public: + int resolveCount = 0; + QImage resolveImage(const QString &) override { + ++resolveCount; + QImage img(100, 100, QImage::Format_RGB32); + img.fill(Qt::blue); + return img; + } + QSizeF imageSize(const QString &) override { + return QSizeF(100, 100); + } + }; + + TrackingResolver resolver; + KnuthPlassItem::setImageResolver(&resolver); + + const QString html = QStringLiteral( + "

First paragraph taking vertical space

" + "

" + ); + LayoutParams params; + params.contentWidth = 400; + params.fontSize = 16; + params.lineSpacing = 1.0; + + auto layout = ChunkLayoutEngine::layoutChunk(html, params, &resolver); + QVERIFY(!layout.images.isEmpty()); + const qreal imageTop = layout.images[0].targetRect.top(); + QVERIFY(imageTop > 20.0); + + KnuthPlassItem item; + item.setSize(QSizeF(400, layout.totalHeight)); + item.setLayout(QVariant::fromValue(layout)); + + // 1. Paint with clip above the image: image resolver must NOT be called + QImage img(400, int(layout.totalHeight), QImage::Format_ARGB32_Premultiplied); + img.fill(Qt::transparent); + { + QPainter p(&img); + p.setClipRect(QRectF(0, 0, 400, imageTop - 5.0)); + item.paint(&p); + } + QCOMPARE(resolver.resolveCount, 0); + + // 2. Paint with clip covering the image: image resolver must be called + { + QPainter p(&img); + p.setClipRect(QRectF(0, 0, 400, imageTop + 50.0)); + item.paint(&p); + } + QVERIFY(resolver.resolveCount >= 1); + + KnuthPlassItem::setImageResolver(nullptr); + } }; QTEST_MAIN(ChunkLayoutEngineTest)