diff --git a/AGENTS.md b/AGENTS.md index 6282179..5193404 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -110,7 +110,7 @@ Backend (C++) handles all file I/O, format parsing, text layout calculation, and | Object | Responsibility | |---|---| | `book` (`Book`) | Open/close book, async loading, error state, metadata (title, author, coverImageUrl). Owns `FormatReader`. | -| `readingModel` (`ReadingModel`) | `QAbstractListModel` exposing chunks (`ContentRole`, `LayoutRole`, `PixelHeightRole`), layout updates, reading mode (`isTextMode`, `isMangaMode`), manga page pairs, and per-book toggles (`pageShift`, `mangaRTL`, `useBookColours`). | +| `readingModel` (`ReadingModel`) | `QAbstractListModel` exposing chunks (`ContentRole`, `LayoutRole`, `PixelHeightRole`), layout updates, reading mode (`isTextMode`, `isMangaMode`), normalized pagination (`currentPage`, `totalPages`, `currentChunk`), manga page pairs, and per-book toggles (`pageShift`, `mangaRTL`, `useBookColours`). | | `readingPreferences` (`ReadingPreferences`) | Font size, line spacing, horizontal margin, vertical margin (`QSettings`). | | `uiState` (`UiState`) | Current theme, last page, sidebar open state, reader bars visibility (`barsVisible`), last file path, custom theme colors, window geometry. | | `historyModel` (`HistoryModel`) | `QAbstractListModel` of recent books with async metadata extraction and reading progress. Entries store strongly-typed `QDateTime lastOpened`, immediately drop bogus/unparseable dates on deserialization, and are maintained strictly in descending chronological order (`lastOpened desc`). | @@ -181,6 +181,9 @@ public: - 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. - Toggling `useBookColours` operates entirely at paint time in `KnuthPlassItem`—zero off-thread relayout, zero position shift, and instant response. +- **Normalized Page Counting & Viewport Invariance**: In text mode, `totalPages` and `currentPage` report normalized pages based on publishing standards (1,800 characters per page "Normopage" / 30 lines × 60 characters, ~250–300 words). + - Derived from an $O(1)$ prefix sum array (`m_chunkCumulativeChars`) and the intra-chunk scroll offset (`intraFraction = intraOffset / totalHeight`), ensuring page numbers and total page counts remain 100% constant across window resizing, maximizing, font scaling, and line spacing adjustments. Standalone illustration images are weighted as 1 standard page (1,800 characters). + - `ReadingModel::currentChunk` exposes the internal 0-based layout chunk index (`0 .. rowCount - 1`) used by `ScrollPageView.qml` and `ChunkLayoutEngine` for layout calculations and scroll anchoring, cleanly decoupled from user-facing `currentPage`. - Scrolling tracks top visible chunk and `intraOffset`. ### 2. Manga / Comic Mode (`MangaPageView.qml`) diff --git a/src/backend/ReadingModel.cpp b/src/backend/ReadingModel.cpp index aade6a8..e03b40a 100644 --- a/src/backend/ReadingModel.cpp +++ b/src/backend/ReadingModel.cpp @@ -97,6 +97,26 @@ double ReadingModel::progress() const int ReadingModel::currentPage() const { return m_currentPage; } int ReadingModel::totalPages() const { return m_totalPages; } +int ReadingModel::currentChunk() const { return m_currentChunk; } + +int ReadingModel::calculatePageFromPosition(int chunkIndex, qreal intraOffset) const +{ + if (!m_isTextMode) { + return pairIndexForChunk(chunkIndex) + 1; + } + if (m_chunks.isEmpty() || m_totalPages <= 0) { + return 0; + } + const int safeChunk = qBound(0, chunkIndex, m_chunks.size() - 1); + qreal intraFraction = 0.0; + if (safeChunk < m_chunkLayouts.size() && m_chunkLayouts[safeChunk].totalHeight > 0.0) { + intraFraction = qBound(0.0, intraOffset / m_chunkLayouts[safeChunk].totalHeight, 1.0); + } + const qreal charsScrolled = (safeChunk < m_chunkCumulativeChars.size() ? m_chunkCumulativeChars[safeChunk] : 0) + + intraFraction * m_chunks[safeChunk].charCount; + const int page = static_cast(charsScrolled / kNormalizedCharsPerPage) + 1; + return qBound(1, page, m_totalPages); +} void ReadingModel::setImageResolver(IBookImageResolver *resolver) { @@ -120,7 +140,7 @@ void ReadingModel::updateLayoutMetrics(int contentWidth, int fontSize, qreal lin if (!m_isTextMode || m_chunks.isEmpty()) return; - const int targetChunk = (anchorChunk >= 0) ? anchorChunk : (m_currentPage > 0 ? (m_currentPage - 1) : 0); + const int targetChunk = (anchorChunk >= 0) ? anchorChunk : (m_currentChunk >= 0 ? m_currentChunk : 0); if (fontSizeChanged || m_preparedChunks.size() != m_chunks.size()) { if (m_remainingLayoutTimer) m_remainingLayoutTimer->stop(); @@ -220,24 +240,21 @@ void ReadingModel::setScrollPosition(int topChunkIndex, qreal intraOffset, qreal return; m_intraOffset = intraOffset; + if (m_currentChunk != topChunkIndex) { + m_currentChunk = topChunkIndex; + emit currentChunkChanged(); + } + const qreal clamped = qBound(0.0, proportion, 1.0); if (!qFuzzyCompare(m_progress, clamped)) { m_progress = clamped; emit progressChanged(); } - if (m_isTextMode) { - const int page = topChunkIndex + 1; - if (m_currentPage != page) { - m_currentPage = page; - emit currentPageChanged(); - } - } else { - const int page = pairIndexForChunk(topChunkIndex) + 1; - if (m_currentPage != page) { - m_currentPage = page; - emit currentPageChanged(); - } + const int page = calculatePageFromPosition(topChunkIndex, intraOffset); + if (m_currentPage != page) { + m_currentPage = page; + emit currentPageChanged(); } saveCurrentPosition(topChunkIndex, intraOffset); @@ -457,6 +474,8 @@ void ReadingModel::setUseBookColours(bool enabled) void ReadingModel::loadPages() { m_pages.clear(); + m_chunkCumulativeChars.clear(); + if (m_currentChunk != 0) { m_currentChunk = 0; emit currentChunkChanged(); } if (m_currentPage != 0) { m_currentPage = 0; emit currentPageChanged(); } if (m_totalPages != 0) { m_totalPages = 0; emit totalPagesChanged(); } @@ -475,6 +494,7 @@ void ReadingModel::setReader(FormatReader *reader) m_chunks.clear(); m_preparedChunks.clear(); m_chunkLayouts.clear(); + m_chunkCumulativeChars.clear(); endResetModel(); const bool oldTextMode = m_isTextMode; @@ -509,17 +529,32 @@ void ReadingModel::setReader(FormatReader *reader) if (m_isTextMode && m_reader) { beginResetModel(); m_chunks = m_reader->chunks(); - m_totalPages = m_chunks.size(); - if (m_totalPages > 0) { - restoreChunk = qBound(0, restoreChunk, m_totalPages - 1); + m_chunkCumulativeChars.resize(m_chunks.size() + 1); + m_chunkCumulativeChars[0] = 0; + for (int i = 0; i < m_chunks.size(); ++i) { + m_chunkCumulativeChars[i + 1] = m_chunkCumulativeChars[i] + m_chunks[i].charCount; + } + const qint64 totalChars = m_chunkCumulativeChars.isEmpty() ? 0 : m_chunkCumulativeChars.last(); + if (m_chunks.isEmpty()) { + m_totalPages = 0; + } else if (totalChars <= 0) { + m_totalPages = 1; + } else { + m_totalPages = std::max(1, static_cast((totalChars + kNormalizedCharsPerPage - 1) / kNormalizedCharsPerPage)); + } + + if (!m_chunks.isEmpty()) { + restoreChunk = qBound(0, restoreChunk, m_chunks.size() - 1); } else { restoreChunk = 0; } - m_currentPage = m_totalPages > 0 ? (restoreChunk + 1) : 0; + m_currentChunk = restoreChunk; + m_currentPage = calculatePageFromPosition(restoreChunk, restoreIntraOffset); endResetModel(); emit totalPagesChanged(); emit currentPageChanged(); + emit currentChunkChanged(); startLayoutMeasurement(restoreChunk, restoreIntraOffset); } else { diff --git a/src/backend/ReadingModel.h b/src/backend/ReadingModel.h index b614da4..4e1bbb4 100644 --- a/src/backend/ReadingModel.h +++ b/src/backend/ReadingModel.h @@ -22,6 +22,7 @@ class ReadingModel : public QAbstractListModel { Q_PROPERTY(double progress READ progress NOTIFY progressChanged) Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged) Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged) + Q_PROPERTY(int currentChunk READ currentChunk NOTIFY currentChunkChanged) Q_PROPERTY(int totalPagePairs READ totalPagePairs NOTIFY totalPagePairsChanged) Q_PROPERTY(bool pageShift READ pageShift NOTIFY pageShiftChanged) Q_PROPERTY(bool mangaRTL READ mangaRTL NOTIFY mangaRTLChanged) @@ -48,6 +49,7 @@ public: double progress() const; int currentPage() const; int totalPages() const; + int currentChunk() const; int totalPagePairs() const; bool pageShift() const; bool mangaRTL() const; @@ -84,6 +86,7 @@ signals: void progressChanged(); void currentPageChanged(); void totalPagesChanged(); + void currentChunkChanged(); void totalPagePairsChanged(); void pageShiftChanged(); void mangaRTLChanged(); @@ -99,6 +102,7 @@ private: void runRemainingLayout(); void saveCurrentPosition(int chunkIndex, qreal intraOffset = 0.0); void ensureChunkLayout(int row) const; + int calculatePageFromPosition(int chunkIndex, qreal intraOffset) const; FormatReader *m_reader = nullptr; IBookImageResolver *m_imageResolver = nullptr; @@ -106,7 +110,9 @@ private: bool m_measuring = false; int m_currentPage = 0; int m_totalPages = 0; + int m_currentChunk = 0; QVector m_chunks; + QVector m_chunkCumulativeChars; mutable QVector m_preparedChunks; mutable QVector m_chunkLayouts; int m_lastSyncStart = -1; diff --git a/src/backend/formats/Fb2Types.h b/src/backend/formats/Fb2Types.h index d2c1fef..c994df9 100644 --- a/src/backend/formats/Fb2Types.h +++ b/src/backend/formats/Fb2Types.h @@ -70,7 +70,6 @@ struct BinaryResource { struct ContentChunkValue { QString section_href; int blocks_count = 0; - int word_count = 0; int char_count = 0; int unnested_containers = 0; @@ -79,7 +78,6 @@ struct ContentChunkValue { return ContentChunkValue{ c.sectionHref, static_cast(c.blocks.size()), - c.wordCount, c.charCount, c.unnestedContainers }; @@ -89,7 +87,6 @@ struct ContentChunkValue { { return section_href == o.section_href && blocks_count == o.blocks_count && - word_count == o.word_count && char_count == o.char_count && unnested_containers == o.unnested_containers; } diff --git a/src/backend/reading/layout/DocumentChunkBuilder.cpp b/src/backend/reading/layout/DocumentChunkBuilder.cpp index 7fda514..c970d91 100644 --- a/src/backend/reading/layout/DocumentChunkBuilder.cpp +++ b/src/backend/reading/layout/DocumentChunkBuilder.cpp @@ -4,19 +4,18 @@ namespace { -void countInlines(const QVector &inlines, int &pChars, int &pWords) +int countInlines(const QVector &inlines) { - pChars = 0; - pWords = 0; + int pChars = 0; for (const auto &inl : inlines) { if (inl.kind == InlineItem::Kind::Text) { pChars += inl.text.size(); - pWords += inl.text.split(QLatin1Char(' '), Qt::SkipEmptyParts).size(); } else if (inl.kind == InlineItem::Kind::Image) { - pChars += 1; - pWords += 1; + const bool isSmallIcon = (inl.cssWidth > 0 && inl.cssWidth <= 48 && inl.cssHeight > 0 && inl.cssHeight <= 48); + pChars += isSmallIcon ? 1 : kNormalizedCharsPerPage; } } + return pChars; } } // namespace @@ -233,13 +232,10 @@ void DocumentChunkBuilder::finishParagraph() return; } - int pChars = 0; - int pWords = 0; - countInlines(inlines, pChars, pWords); + const int pChars = countInlines(inlines); m_currentChunk.blocks.append(m_currentParagraph); m_currentChunk.charCount += pChars; - m_currentChunk.wordCount += pWords; m_hasActiveParagraph = false; m_currentParagraph = BlockItem(); @@ -277,12 +273,9 @@ void DocumentChunkBuilder::appendBlock(const BlockItem &block) } else if (block.kind == BlockItem::Kind::Rule) { appendRule(block.ruleColor); } else if (block.kind == BlockItem::Kind::Paragraph) { - int pChars = 0; - int pWords = 0; - countInlines(block.inlines, pChars, pWords); + const int pChars = countInlines(block.inlines); m_currentChunk.blocks.append(block); m_currentChunk.charCount += pChars; - m_currentChunk.wordCount += pWords; if (m_currentChunk.charCount >= m_targetChars) { m_pendingFlush = true; diff --git a/src/backend/reading/layout/DocumentIr.h b/src/backend/reading/layout/DocumentIr.h index 845cc88..83057f5 100644 --- a/src/backend/reading/layout/DocumentIr.h +++ b/src/backend/reading/layout/DocumentIr.h @@ -141,10 +141,13 @@ struct ParseParams { qreal contentWidth = 600; // px, resolves percentage lengths }; +// Standard normalized page size based on publishing / typography Normseite: +// 1,800 characters with spaces (30 lines x 60 characters, ~250-300 words). +static constexpr int kNormalizedCharsPerPage = 1800; + struct ContentChunk { QString sectionHref; QVector blocks; - int wordCount = 0; int charCount = 0; int unnestedContainers = 0; @@ -154,7 +157,6 @@ struct ContentChunk { { return sectionHref == o.sectionHref && blocks == o.blocks - && wordCount == o.wordCount && charCount == o.charCount && unnestedContainers == o.unnestedContainers; } diff --git a/src/backend/reading/layout/HtmlBlockParser.cpp b/src/backend/reading/layout/HtmlBlockParser.cpp index 02d8c21..83f0111 100644 --- a/src/backend/reading/layout/HtmlBlockParser.cpp +++ b/src/backend/reading/layout/HtmlBlockParser.cpp @@ -707,7 +707,6 @@ QVector parseChunks(const QString &html, b.inlines.append(textItem); chunk.blocks.append(b); chunk.charCount = html.size(); - chunk.wordCount = html.split(QLatin1Char(' '), Qt::SkipEmptyParts).size(); return {chunk}; } diff --git a/src/qml/components/ScrollPageView.qml b/src/qml/components/ScrollPageView.qml index d573f50..06b8f6f 100644 --- a/src/qml/components/ScrollPageView.qml +++ b/src/qml/components/ScrollPageView.qml @@ -12,6 +12,20 @@ Rectangle { property bool restoreReady: false property int initialIndex: 0 property real initialOffset: 0 + property real lastScrollSyncTime: 0 + + function syncScrollPosition() { + var probeX = chunkListView.width / 2; + var probeY = chunkListView.contentY + 10; + var topIdx = chunkListView.indexAt(probeX, probeY); + if (topIdx < 0) + return; + var topItem = chunkListView.itemAtIndex(topIdx); + var intraOffset = topItem ? (chunkListView.contentY - topItem.y) : 0; + var maxScroll = Math.max(1, chunkListView.contentHeight - chunkListView.height); + var prop = Math.min(1.0, Math.max(0.0, chunkListView.contentY / maxScroll)); + readingModel.setScrollPosition(topIdx, intraOffset, prop); + } gradient: Gradient { GradientStop { position: 0.0; color: ThemeManager.currentTheme.gradientTop } @@ -57,6 +71,10 @@ Rectangle { property: "contentY" duration: 180 easing.type: Easing.OutQuad + onFinished: { + lastScrollSyncTime = Date.now(); + syncScrollPosition(); + } } function updateContentMetrics() { @@ -68,12 +86,11 @@ Rectangle { var probeX = chunkListView.width / 2; var probeY = chunkListView.contentY + 10; topIdx = chunkListView.indexAt(probeX, probeY); - if (topIdx < 0) { - topIdx = (readingModel.currentPage > 0) ? (readingModel.currentPage - 1) : 0; - } - var topItem = chunkListView.itemAtIndex(topIdx); - if (topItem && topItem.height > 0) { - intraRatio = Math.max(0.0, Math.min(1.0, (chunkListView.contentY - topItem.y) / topItem.height)); + if (topIdx >= 0) { + var topItem = chunkListView.itemAtIndex(topIdx); + if (topItem && topItem.height > 0) { + intraRatio = Math.max(0.0, Math.min(1.0, (chunkListView.contentY - topItem.y) / topItem.height)); + } } } @@ -143,9 +160,21 @@ Rectangle { onContentYChanged: { if (contentReady && restoreReady) { - scrollTrackTimer.restart(); + var now = Date.now(); + if (now - lastScrollSyncTime >= 250) { + lastScrollSyncTime = now; + syncScrollPosition(); + } } } + onMovementEnded: { + lastScrollSyncTime = Date.now(); + syncScrollPosition(); + } + onFlickEnded: { + lastScrollSyncTime = Date.now(); + syncScrollPosition(); + } ScrollBar.vertical: ScrollBar { id: vScrollBar @@ -180,27 +209,6 @@ Rectangle { } } - Timer { - id: scrollTrackTimer - interval: 150 - repeat: false - onTriggered: { - if (contentReady && restoreReady && readingModel.isTextMode) { - var probeX = chunkListView.width / 2; - var probeY = chunkListView.contentY + 10; - var topIdx = chunkListView.indexAt(probeX, probeY); - if (topIdx < 0) { - topIdx = (readingModel.currentPage > 0) ? (readingModel.currentPage - 1) : 0; - } - var topItem = chunkListView.itemAtIndex(topIdx); - var intraOffset = topItem ? (chunkListView.contentY - topItem.y) : 0; - var maxScroll = Math.max(1, chunkListView.contentHeight - chunkListView.height); - var prop = Math.min(1.0, Math.max(0.0, chunkListView.contentY / maxScroll)); - readingModel.setScrollPosition(topIdx, intraOffset, prop); - } - } - } - Connections { target: readingModel function onRestoreReady(chunkIndex, intraOffset) { diff --git a/tests/ReadingModelTest.cpp b/tests/ReadingModelTest.cpp index cb996fd..3693c80 100644 --- a/tests/ReadingModelTest.cpp +++ b/tests/ReadingModelTest.cpp @@ -78,6 +78,39 @@ public: } }; +class VariableCharsTextReader : public FormatReader { +public: + explicit VariableCharsTextReader(const QVector &charsPerChunk) + { + m_chunks.reserve(charsPerChunk.size()); + for (int i = 0; i < charsPerChunk.size(); ++i) { + ContentChunk chunk; + chunk.sectionHref = QStringLiteral("sec_%1.xhtml").arg(i); + chunk.charCount = charsPerChunk[i]; + BlockItem p; + p.kind = BlockItem::Kind::Paragraph; + InlineItem t; + t.kind = InlineItem::Kind::Text; + t.text = QString(charsPerChunk[i], QLatin1Char('A')); + p.inlines.append(t); + chunk.blocks.append(p); + m_chunks.append(chunk); + } + } + 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("Norm Reader"); } + QString author() const override { return QStringLiteral("Author"); } + QString filePath() const override { return QStringLiteral("/fake/norm.epub"); } + QString coverImageUrl() const override { return {}; } + QByteArray contentHash() const override { return QByteArray("normhash"); } + bool loadMetadata(const QString &) override { return true; } + QVector chunks() const override { return m_chunks; } +private: + QVector m_chunks; +}; + class ReadingModelTest : public QObject { Q_OBJECT @@ -293,6 +326,129 @@ private slots: const auto layout55 = model.data(model.index(55, 0), ReadingModel::LayoutRole).value(); QVERIFY(!layout55.lines.isEmpty()); } + + void normalizedPageCountCalculations() + { + Ctx ctx; + ReadingModel model(*ctx.store); + + // 1. Empty book + QCOMPARE(model.totalPages(), 0); + QCOMPARE(model.currentPage(), 0); + QCOMPARE(model.currentChunk(), 0); + + // 2. Short book: 500 characters (< 1800) -> 1 page + VariableCharsTextReader shortReader({500}); + model.setReader(&shortReader); + QCOMPARE(model.totalPages(), 1); + QCOMPARE(model.currentPage(), 1); + QCOMPARE(model.currentChunk(), 0); + + // 3. Exactly 1800 characters -> 1 page + VariableCharsTextReader exactReader({1800}); + model.setReader(&exactReader); + QCOMPARE(model.totalPages(), 1); + QCOMPARE(model.currentPage(), 1); + + // 4. 1801 characters -> 2 pages + VariableCharsTextReader splitReader({1801}); + model.setReader(&splitReader); + QCOMPARE(model.totalPages(), 2); + QCOMPARE(model.currentPage(), 1); + + // 5. Multi-chunk book: 5 chunks with 720 chars each (3600 chars total) -> 2 pages + VariableCharsTextReader multiChunk({720, 720, 720, 720, 720}); + model.setReader(&multiChunk); + QCOMPARE(model.rowCount(), 5); + QCOMPARE(model.totalPages(), 2); + QCOMPARE(model.currentPage(), 1); + } + + void normalizedPageCurrentPageProgression() + { + Ctx ctx; + ReadingModel model(*ctx.store); + + // 6 chunks of 900 chars each = 5400 chars = 3 normalized pages (1800 chars/page) + // Chunk 0: 0..900 (Page 1) + // Chunk 1: 900..1800 (Page 1) + // Chunk 2: 1800..2700 (Page 2) + // Chunk 3: 2700..3600 (Page 2) + // Chunk 4: 3600..4500 (Page 3) + // Chunk 5: 4500..5400 (Page 3) + VariableCharsTextReader reader({900, 900, 900, 900, 900, 900}); + model.setReader(&reader); + QCOMPARE(model.totalPages(), 3); + QCOMPARE(model.currentPage(), 1); + QCOMPARE(model.currentChunk(), 0); + + QSignalSpy pageSpy(&model, &ReadingModel::currentPageChanged); + QSignalSpy chunkSpy(&model, &ReadingModel::currentChunkChanged); + + // Scroll to chunk 1: 900 chars scrolled -> still Page 1 + model.setScrollPosition(1, 0.0, 0.16); + QCOMPARE(model.currentChunk(), 1); + QCOMPARE(model.currentPage(), 1); + QCOMPARE(chunkSpy.count(), 1); + QCOMPARE(pageSpy.count(), 0); + + // Scroll to chunk 2: 1800 chars scrolled -> Page 2 + model.setScrollPosition(2, 0.0, 0.33); + QCOMPARE(model.currentChunk(), 2); + QCOMPARE(model.currentPage(), 2); + QCOMPARE(pageSpy.count(), 1); + + // Scroll to chunk 3: 2700 chars scrolled -> Page 2 + model.setScrollPosition(3, 0.0, 0.50); + QCOMPARE(model.currentChunk(), 3); + QCOMPARE(model.currentPage(), 2); + + // Scroll to chunk 4: 3600 chars scrolled -> Page 3 + model.setScrollPosition(4, 0.0, 0.67); + QCOMPARE(model.currentChunk(), 4); + QCOMPARE(model.currentPage(), 3); + QCOMPARE(pageSpy.count(), 2); + + // Scroll to end of chunk 5: Page 3 (clamped to totalPages) + model.setScrollPosition(5, 100.0, 1.0); + QCOMPARE(model.currentChunk(), 5); + QCOMPARE(model.currentPage(), 3); + } + + void viewportGeometryInvariance() + { + Ctx ctx; + ReadingModel model(*ctx.store); + + // 10 chunks of 1800 chars each = 18000 chars = 10 normalized pages + QVector chunkSizes(10, 1800); + VariableCharsTextReader reader(chunkSizes); + model.setReader(&reader); + + QCOMPARE(model.totalPages(), 10); + QCOMPARE(model.currentPage(), 1); + + // Scroll to chunk 3 (Page 4) + model.setScrollPosition(3, 0.0, 0.3); + QCOMPARE(model.currentPage(), 4); + QCOMPARE(model.currentChunk(), 3); + + // Simulate resizing viewport width and changing font preferences + model.updateLayoutMetrics(300, 12, 1.0, 3); + QCOMPARE(model.totalPages(), 10); + QCOMPARE(model.currentPage(), 4); + QCOMPARE(model.currentChunk(), 3); + + model.updateLayoutMetrics(1400, 28, 1.8, 3); + QCOMPARE(model.totalPages(), 10); + QCOMPARE(model.currentPage(), 4); + QCOMPARE(model.currentChunk(), 3); + + model.updateLayoutMetrics(800, 16, 1.2, 3); + QCOMPARE(model.totalPages(), 10); + QCOMPARE(model.currentPage(), 4); + QCOMPARE(model.currentChunk(), 3); + } }; QTEST_MAIN(ReadingModelTest) diff --git a/tests/formats/Fb2ReaderTest.cpp b/tests/formats/Fb2ReaderTest.cpp index b438e17..fa6608b 100644 --- a/tests/formats/Fb2ReaderTest.cpp +++ b/tests/formats/Fb2ReaderTest.cpp @@ -214,7 +214,7 @@ public: } else { book.cover_image_url = std::nullopt; } - ContentChunkValue fallbackChunk{book.file_path, 1, 0, 0, 0}; + ContentChunkValue fallbackChunk{book.file_path, 1, 0, 0}; book.chunks = QVector{fallbackChunk}; book.binaries = binary_resources; return true; @@ -324,19 +324,17 @@ private slots: // Obligation 5: value-equality.ContentChunkValue void testValueEqualityContentChunkValue() { - ContentChunkValue c1{QStringLiteral("sec1"), 5, 100, 500, 2}; - ContentChunkValue c2{QStringLiteral("sec1"), 5, 100, 500, 2}; - ContentChunkValue cDiffHref{QStringLiteral("sec2"), 5, 100, 500, 2}; - ContentChunkValue cDiffBlocks{QStringLiteral("sec1"), 6, 100, 500, 2}; - ContentChunkValue cDiffWords{QStringLiteral("sec1"), 5, 101, 500, 2}; - ContentChunkValue cDiffChars{QStringLiteral("sec1"), 5, 100, 501, 2}; - ContentChunkValue cDiffContainers{QStringLiteral("sec1"), 5, 100, 500, 3}; + ContentChunkValue c1{QStringLiteral("sec1"), 5, 500, 2}; + ContentChunkValue c2{QStringLiteral("sec1"), 5, 500, 2}; + ContentChunkValue cDiffHref{QStringLiteral("sec2"), 5, 500, 2}; + ContentChunkValue cDiffBlocks{QStringLiteral("sec1"), 6, 500, 2}; + ContentChunkValue cDiffChars{QStringLiteral("sec1"), 5, 501, 2}; + ContentChunkValue cDiffContainers{QStringLiteral("sec1"), 5, 500, 3}; QVERIFY(c1 == c2); QVERIFY(!(c1 != c2)); QVERIFY(c1 != cDiffHref); QVERIFY(c1 != cDiffBlocks); - QVERIFY(c1 != cDiffWords); QVERIFY(c1 != cDiffChars); QVERIFY(c1 != cDiffContainers); } @@ -347,19 +345,16 @@ private slots: ContentChunkValue c; QVERIFY(c.section_href.isEmpty()); QCOMPARE(c.blocks_count, 0); - QCOMPARE(c.word_count, 0); QCOMPARE(c.char_count, 0); QCOMPARE(c.unnested_containers, 0); c.section_href = QStringLiteral("body/s0"); c.blocks_count = 3; - c.word_count = 50; c.char_count = 250; c.unnested_containers = 1; QCOMPARE(c.section_href, QStringLiteral("body/s0")); QCOMPARE(c.blocks_count, 3); - QCOMPARE(c.word_count, 50); QCOMPARE(c.char_count, 250); QCOMPARE(c.unnested_containers, 1); } @@ -391,7 +386,6 @@ private slots: QCOMPARE(chunks1.size(), chunks2.size()); QVERIFY(!chunks1.isEmpty()); QCOMPARE(chunks1.first().sectionHref, chunks2.first().sectionHref); - QCOMPARE(chunks1.first().wordCount, chunks2.first().wordCount); QCOMPARE(chunks1.first().charCount, chunks2.first().charCount); QCOMPARE(chunks1.first().blocks.size(), chunks2.first().blocks.size()); @@ -525,7 +519,7 @@ private slots: QCOMPARE(s.book.status, Fb2LoadStatus::loading_full); // Edge 5: loading_full -> loaded - ContentChunkValue chunk{"sec1", 1, 10, 50, 0}; + ContentChunkValue chunk{"sec1", 1, 50, 0}; QVERIFY(s.completeFullOpenWithSections(client, "hash", "Title", "stem", {}, "Author", std::nullopt, {}, {chunk})); QCOMPARE(s.book.status, Fb2LoadStatus::loaded); } @@ -755,7 +749,7 @@ private slots: s.book.file_path = QStringLiteral("/books/novel.fb2"); s.book.status = Fb2LoadStatus::loading_full; - ContentChunkValue chunk{"sec1", 2, 20, 100, 0}; + ContentChunkValue chunk{"sec1", 2, 100, 0}; // Failure 1: actor != client QVERIFY(!s.completeFullOpenWithSections(c2, "hash", "Title", "stem", {}, "", std::nullopt, {}, {chunk})); @@ -786,7 +780,7 @@ private slots: s.book.file_path = QStringLiteral("/books/empty.fb2"); s.book.status = Fb2LoadStatus::loading_full; - ContentChunkValue chunk{"sec1", 1, 0, 0, 0}; + ContentChunkValue chunk{"sec1", 1, 0, 0}; // Failure 1: actor != client QVERIFY(!s.completeFullOpenWithEmptyBodyFallback(c2, "hash", "", "empty", {}, "", std::nullopt, {}, {})); @@ -806,7 +800,6 @@ private slots: ContentChunkValue fallback = s.book.chunks.value().first(); QCOMPARE(fallback.section_href, QStringLiteral("/books/empty.fb2")); QCOMPARE(fallback.blocks_count, 1); - QCOMPARE(fallback.word_count, 0); QCOMPARE(fallback.char_count, 0); } diff --git a/tests/reading/ChunkLayoutEngineTest.cpp b/tests/reading/ChunkLayoutEngineTest.cpp index a57b1bb..437b33c 100644 --- a/tests/reading/ChunkLayoutEngineTest.cpp +++ b/tests/reading/ChunkLayoutEngineTest.cpp @@ -312,6 +312,34 @@ private slots: QVERIFY(imgTrue.pixelColor(testX, testY).alpha() > 0); } + void contentChunkFontSizeScaling() + { + const QString html = QStringLiteral("

Testing dynamic font scaling directly on structured ContentChunk without re-parsing XML.

"); + auto chunks = HtmlBlockParser::parseChunks(html, QStringLiteral("section.xhtml")); + QCOMPARE(chunks.size(), 1); + const auto &chunk = chunks.first(); + + QVERIFY(chunk.charCount > 20); + + LayoutParams p16; + p16.contentWidth = 400; + p16.fontSize = 16; + p16.lineSpacing = 1.0; + auto prep16 = ChunkLayoutEngine::prepareChunk(chunk, 16); + auto l16 = ChunkLayoutEngine::layoutPreparedChunk(prep16, p16); + + LayoutParams p24; + p24.contentWidth = 400; + p24.fontSize = 24; + p24.lineSpacing = 1.0; + auto prep24 = ChunkLayoutEngine::prepareChunk(chunk, 24); + auto l24 = ChunkLayoutEngine::layoutPreparedChunk(prep24, p24); + + QVERIFY(l24.totalHeight > l16.totalHeight); + QVERIFY(!l24.lines.isEmpty()); + QVERIFY(l24.lines[0].runs[0].font.pixelSize() > l16.lines[0].runs[0].font.pixelSize()); + } + void clipRectCullingSkipsOffscreenImage() { class TrackingResolver : public IBookImageResolver { @@ -370,35 +398,6 @@ private slots: KnuthPlassItem::setImageResolver(nullptr); } - void contentChunkFontSizeScaling() - { - const QString html = QStringLiteral("

Testing dynamic font scaling directly on structured ContentChunk without re-parsing XML.

"); - auto chunks = HtmlBlockParser::parseChunks(html, QStringLiteral("section.xhtml")); - QCOMPARE(chunks.size(), 1); - const auto &chunk = chunks.first(); - - QVERIFY(chunk.wordCount > 5); - QVERIFY(chunk.charCount > 20); - - LayoutParams p16; - p16.contentWidth = 400; - p16.fontSize = 16; - p16.lineSpacing = 1.0; - auto prep16 = ChunkLayoutEngine::prepareChunk(chunk, 16); - auto l16 = ChunkLayoutEngine::layoutPreparedChunk(prep16, p16); - - LayoutParams p24; - p24.contentWidth = 400; - p24.fontSize = 24; - p24.lineSpacing = 1.0; - auto prep24 = ChunkLayoutEngine::prepareChunk(chunk, 24); - auto l24 = ChunkLayoutEngine::layoutPreparedChunk(prep24, p24); - - QVERIFY(l24.totalHeight > l16.totalHeight); - QVERIFY(!l24.lines.isEmpty()); - QVERIFY(l24.lines[0].runs[0].font.pixelSize() > l16.lines[0].runs[0].font.pixelSize()); - } - void contentChunkPartitionAndUnnestedContainers() { const QString html = QStringLiteral( @@ -412,12 +411,10 @@ private slots: QCOMPARE(chunks[0].sectionHref, QStringLiteral("section1.xhtml")); QCOMPARE(chunks[0].unnestedContainers, 0); - QVERIFY(chunks[0].wordCount > 0); QVERIFY(chunks[0].charCount > 0); QCOMPARE(chunks[1].sectionHref, QStringLiteral("section1.xhtml")); QCOMPARE(chunks[1].unnestedContainers, 1); // Carries the open blockquote container - QVERIFY(chunks[1].wordCount > 0); QVERIFY(chunks[1].charCount > 0); // Layout both chunks and verify decorations diff --git a/tests/reading/KnuthPlassRenderingSpecTest.cpp b/tests/reading/KnuthPlassRenderingSpecTest.cpp index 4bcffc3..af6fc3f 100644 --- a/tests/reading/KnuthPlassRenderingSpecTest.cpp +++ b/tests/reading/KnuthPlassRenderingSpecTest.cpp @@ -218,6 +218,9 @@ public: QStringLiteral("

Content paragraph for chunk index %1 with sufficient words for layout.

").arg(i), QStringLiteral("text/section_%1.xhtml").arg(i) ); + if (!parsed.isEmpty()) { + parsed[0].charCount = kNormalizedCharsPerPage; + } list.append(parsed); } return list; @@ -746,7 +749,6 @@ private slots: const auto &chunk = chunks.first(); QCOMPARE(chunk.sectionHref, QStringLiteral("section.xhtml")); - QVERIFY(chunk.wordCount > 0); QVERIFY(chunk.charCount > 0); QCOMPARE(chunk.unnestedContainers, 0); } @@ -929,7 +931,7 @@ private slots: model.setScrollPosition(3, 45.0, 0.35); QCOMPARE(posSpy.count(), 1); - QCOMPARE(model.currentPage(), 4); + QCOMPARE(model.currentChunk(), 3); QCOMPARE(model.progress(), 0.35); BookPosition loaded = ctx.store->load(reader.contentHash()); @@ -1157,8 +1159,7 @@ private slots: model.setReader(&reader); model.setScrollPosition(5, 0.0, 0.5); - const int page = model.currentPage(); - const int anchorChunk = page - 1; + const int anchorChunk = model.currentChunk(); QVERIFY(anchorChunk >= 0); QVERIFY(anchorChunk < model.rowCount()); } @@ -1240,7 +1241,7 @@ private slots: // 2. progress QCOMPARE(model.progress(), 0.0); // 3. anchor_chunk - QCOMPARE(model.currentPage() - 1, 0); + QCOMPARE(model.currentChunk(), 0); // 4. use_book_colours QCOMPARE(model.useBookColours(), false); // 5. status diff --git a/tests/reading/TextLayoutEngineSpecTest.cpp b/tests/reading/TextLayoutEngineSpecTest.cpp index d6d3752..aac82b5 100644 --- a/tests/reading/TextLayoutEngineSpecTest.cpp +++ b/tests/reading/TextLayoutEngineSpecTest.cpp @@ -46,8 +46,7 @@ public: for (int i = 0; i < m_count; ++i) { ContentChunk chunk; chunk.sectionHref = QStringLiteral("text/ch_%1.xhtml").arg(i); - chunk.wordCount = 10; - chunk.charCount = 60; + chunk.charCount = kNormalizedCharsPerPage; chunk.unnestedContainers = 0; BlockItem p; @@ -411,7 +410,6 @@ private slots: { ContentChunk chunk; chunk.sectionHref = QStringLiteral("sec1.xhtml"); - chunk.wordCount = 100; chunk.charCount = 500; chunk.unnestedContainers = 1; QVERIFY(chunk.isEmpty());