fix page counter

This commit is contained in:
Agel committed 2026-10-30 15:47:53 +01:00
1 parent 511472bc73
commit da8abf0332
13 files changed
+310 -122

No files matched your search

+4 -1
View File
@@ -110,7 +110,7 @@ Backend (C++) handles all file I/O, format parsing, text layout calculation, and
| Object | Responsibility | | Object | Responsibility |
|---|---| |---|---|
| `book` (`Book`) | Open/close book, async loading, error state, metadata (title, author, coverImageUrl). Owns `FormatReader`. | | `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`). | | `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. | | `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`). | | `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 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. - 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. - 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`. - Scrolling tracks top visible chunk and `intraOffset`.
### 2. Manga / Comic Mode (`MangaPageView.qml`) ### 2. Manga / Comic Mode (`MangaPageView.qml`)
+52 -17
View File
@@ -97,6 +97,26 @@ double ReadingModel::progress() const
int ReadingModel::currentPage() const { return m_currentPage; } int ReadingModel::currentPage() const { return m_currentPage; }
int ReadingModel::totalPages() const { return m_totalPages; } 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<int>(charsScrolled / kNormalizedCharsPerPage) + 1;
return qBound(1, page, m_totalPages);
}
void ReadingModel::setImageResolver(IBookImageResolver *resolver) void ReadingModel::setImageResolver(IBookImageResolver *resolver)
{ {
@@ -120,7 +140,7 @@ void ReadingModel::updateLayoutMetrics(int contentWidth, int fontSize, qreal lin
if (!m_isTextMode || m_chunks.isEmpty()) if (!m_isTextMode || m_chunks.isEmpty())
return; 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 (fontSizeChanged || m_preparedChunks.size() != m_chunks.size()) {
if (m_remainingLayoutTimer) if (m_remainingLayoutTimer)
m_remainingLayoutTimer->stop(); m_remainingLayoutTimer->stop();
@@ -220,24 +240,21 @@ void ReadingModel::setScrollPosition(int topChunkIndex, qreal intraOffset, qreal
return; return;
m_intraOffset = intraOffset; m_intraOffset = intraOffset;
if (m_currentChunk != topChunkIndex) {
m_currentChunk = topChunkIndex;
emit currentChunkChanged();
}
const qreal clamped = qBound(0.0, proportion, 1.0); const qreal clamped = qBound(0.0, proportion, 1.0);
if (!qFuzzyCompare(m_progress, clamped)) { if (!qFuzzyCompare(m_progress, clamped)) {
m_progress = clamped; m_progress = clamped;
emit progressChanged(); emit progressChanged();
} }
if (m_isTextMode) { const int page = calculatePageFromPosition(topChunkIndex, intraOffset);
const int page = topChunkIndex + 1; if (m_currentPage != page) {
if (m_currentPage != page) { m_currentPage = page;
m_currentPage = page; emit currentPageChanged();
emit currentPageChanged();
}
} else {
const int page = pairIndexForChunk(topChunkIndex) + 1;
if (m_currentPage != page) {
m_currentPage = page;
emit currentPageChanged();
}
} }
saveCurrentPosition(topChunkIndex, intraOffset); saveCurrentPosition(topChunkIndex, intraOffset);
@@ -457,6 +474,8 @@ void ReadingModel::setUseBookColours(bool enabled)
void ReadingModel::loadPages() void ReadingModel::loadPages()
{ {
m_pages.clear(); 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_currentPage != 0) { m_currentPage = 0; emit currentPageChanged(); }
if (m_totalPages != 0) { m_totalPages = 0; emit totalPagesChanged(); } if (m_totalPages != 0) { m_totalPages = 0; emit totalPagesChanged(); }
@@ -475,6 +494,7 @@ void ReadingModel::setReader(FormatReader *reader)
m_chunks.clear(); m_chunks.clear();
m_preparedChunks.clear(); m_preparedChunks.clear();
m_chunkLayouts.clear(); m_chunkLayouts.clear();
m_chunkCumulativeChars.clear();
endResetModel(); endResetModel();
const bool oldTextMode = m_isTextMode; const bool oldTextMode = m_isTextMode;
@@ -509,17 +529,32 @@ void ReadingModel::setReader(FormatReader *reader)
if (m_isTextMode && m_reader) { if (m_isTextMode && m_reader) {
beginResetModel(); beginResetModel();
m_chunks = m_reader->chunks(); m_chunks = m_reader->chunks();
m_totalPages = m_chunks.size(); m_chunkCumulativeChars.resize(m_chunks.size() + 1);
if (m_totalPages > 0) { m_chunkCumulativeChars[0] = 0;
restoreChunk = qBound(0, restoreChunk, m_totalPages - 1); 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<int>((totalChars + kNormalizedCharsPerPage - 1) / kNormalizedCharsPerPage));
}
if (!m_chunks.isEmpty()) {
restoreChunk = qBound(0, restoreChunk, m_chunks.size() - 1);
} else { } else {
restoreChunk = 0; restoreChunk = 0;
} }
m_currentPage = m_totalPages > 0 ? (restoreChunk + 1) : 0; m_currentChunk = restoreChunk;
m_currentPage = calculatePageFromPosition(restoreChunk, restoreIntraOffset);
endResetModel(); endResetModel();
emit totalPagesChanged(); emit totalPagesChanged();
emit currentPageChanged(); emit currentPageChanged();
emit currentChunkChanged();
startLayoutMeasurement(restoreChunk, restoreIntraOffset); startLayoutMeasurement(restoreChunk, restoreIntraOffset);
} else { } else {
+6
View File
@@ -22,6 +22,7 @@ class ReadingModel : public QAbstractListModel {
Q_PROPERTY(double progress READ progress NOTIFY progressChanged) Q_PROPERTY(double progress READ progress NOTIFY progressChanged)
Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged) Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged)
Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged) 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(int totalPagePairs READ totalPagePairs NOTIFY totalPagePairsChanged)
Q_PROPERTY(bool pageShift READ pageShift NOTIFY pageShiftChanged) Q_PROPERTY(bool pageShift READ pageShift NOTIFY pageShiftChanged)
Q_PROPERTY(bool mangaRTL READ mangaRTL NOTIFY mangaRTLChanged) Q_PROPERTY(bool mangaRTL READ mangaRTL NOTIFY mangaRTLChanged)
@@ -48,6 +49,7 @@ public:
double progress() const; double progress() const;
int currentPage() const; int currentPage() const;
int totalPages() const; int totalPages() const;
int currentChunk() const;
int totalPagePairs() const; int totalPagePairs() const;
bool pageShift() const; bool pageShift() const;
bool mangaRTL() const; bool mangaRTL() const;
@@ -84,6 +86,7 @@ signals:
void progressChanged(); void progressChanged();
void currentPageChanged(); void currentPageChanged();
void totalPagesChanged(); void totalPagesChanged();
void currentChunkChanged();
void totalPagePairsChanged(); void totalPagePairsChanged();
void pageShiftChanged(); void pageShiftChanged();
void mangaRTLChanged(); void mangaRTLChanged();
@@ -99,6 +102,7 @@ private:
void runRemainingLayout(); void runRemainingLayout();
void saveCurrentPosition(int chunkIndex, qreal intraOffset = 0.0); void saveCurrentPosition(int chunkIndex, qreal intraOffset = 0.0);
void ensureChunkLayout(int row) const; void ensureChunkLayout(int row) const;
int calculatePageFromPosition(int chunkIndex, qreal intraOffset) const;
FormatReader *m_reader = nullptr; FormatReader *m_reader = nullptr;
IBookImageResolver *m_imageResolver = nullptr; IBookImageResolver *m_imageResolver = nullptr;
@@ -106,7 +110,9 @@ private:
bool m_measuring = false; bool m_measuring = false;
int m_currentPage = 0; int m_currentPage = 0;
int m_totalPages = 0; int m_totalPages = 0;
int m_currentChunk = 0;
QVector<ContentChunk> m_chunks; QVector<ContentChunk> m_chunks;
QVector<qint64> m_chunkCumulativeChars;
mutable QVector<ChunkLayoutEngine::PreparedChunk> m_preparedChunks; mutable QVector<ChunkLayoutEngine::PreparedChunk> m_preparedChunks;
mutable QVector<ChunkLayout> m_chunkLayouts; mutable QVector<ChunkLayout> m_chunkLayouts;
int m_lastSyncStart = -1; int m_lastSyncStart = -1;
-3
View File
@@ -70,7 +70,6 @@ struct BinaryResource {
struct ContentChunkValue { struct ContentChunkValue {
QString section_href; QString section_href;
int blocks_count = 0; int blocks_count = 0;
int word_count = 0;
int char_count = 0; int char_count = 0;
int unnested_containers = 0; int unnested_containers = 0;
@@ -79,7 +78,6 @@ struct ContentChunkValue {
return ContentChunkValue{ return ContentChunkValue{
c.sectionHref, c.sectionHref,
static_cast<int>(c.blocks.size()), static_cast<int>(c.blocks.size()),
c.wordCount,
c.charCount, c.charCount,
c.unnestedContainers c.unnestedContainers
}; };
@@ -89,7 +87,6 @@ struct ContentChunkValue {
{ {
return section_href == o.section_href && return section_href == o.section_href &&
blocks_count == o.blocks_count && blocks_count == o.blocks_count &&
word_count == o.word_count &&
char_count == o.char_count && char_count == o.char_count &&
unnested_containers == o.unnested_containers; unnested_containers == o.unnested_containers;
} }
@@ -4,19 +4,18 @@
namespace { namespace {
void countInlines(const QVector<InlineItem> &inlines, int &pChars, int &pWords) int countInlines(const QVector<InlineItem> &inlines)
{ {
pChars = 0; int pChars = 0;
pWords = 0;
for (const auto &inl : inlines) { for (const auto &inl : inlines) {
if (inl.kind == InlineItem::Kind::Text) { if (inl.kind == InlineItem::Kind::Text) {
pChars += inl.text.size(); pChars += inl.text.size();
pWords += inl.text.split(QLatin1Char(' '), Qt::SkipEmptyParts).size();
} else if (inl.kind == InlineItem::Kind::Image) { } else if (inl.kind == InlineItem::Kind::Image) {
pChars += 1; const bool isSmallIcon = (inl.cssWidth > 0 && inl.cssWidth <= 48 && inl.cssHeight > 0 && inl.cssHeight <= 48);
pWords += 1; pChars += isSmallIcon ? 1 : kNormalizedCharsPerPage;
} }
} }
return pChars;
} }
} // namespace } // namespace
@@ -233,13 +232,10 @@ void DocumentChunkBuilder::finishParagraph()
return; return;
} }
int pChars = 0; const int pChars = countInlines(inlines);
int pWords = 0;
countInlines(inlines, pChars, pWords);
m_currentChunk.blocks.append(m_currentParagraph); m_currentChunk.blocks.append(m_currentParagraph);
m_currentChunk.charCount += pChars; m_currentChunk.charCount += pChars;
m_currentChunk.wordCount += pWords;
m_hasActiveParagraph = false; m_hasActiveParagraph = false;
m_currentParagraph = BlockItem(); m_currentParagraph = BlockItem();
@@ -277,12 +273,9 @@ void DocumentChunkBuilder::appendBlock(const BlockItem &block)
} else if (block.kind == BlockItem::Kind::Rule) { } else if (block.kind == BlockItem::Kind::Rule) {
appendRule(block.ruleColor); appendRule(block.ruleColor);
} else if (block.kind == BlockItem::Kind::Paragraph) { } else if (block.kind == BlockItem::Kind::Paragraph) {
int pChars = 0; const int pChars = countInlines(block.inlines);
int pWords = 0;
countInlines(block.inlines, pChars, pWords);
m_currentChunk.blocks.append(block); m_currentChunk.blocks.append(block);
m_currentChunk.charCount += pChars; m_currentChunk.charCount += pChars;
m_currentChunk.wordCount += pWords;
if (m_currentChunk.charCount >= m_targetChars) { if (m_currentChunk.charCount >= m_targetChars) {
m_pendingFlush = true; m_pendingFlush = true;
+4 -2
View File
@@ -141,10 +141,13 @@ struct ParseParams {
qreal contentWidth = 600; // px, resolves percentage lengths 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 { struct ContentChunk {
QString sectionHref; QString sectionHref;
QVector<BlockItem> blocks; QVector<BlockItem> blocks;
int wordCount = 0;
int charCount = 0; int charCount = 0;
int unnestedContainers = 0; int unnestedContainers = 0;
@@ -154,7 +157,6 @@ struct ContentChunk {
{ {
return sectionHref == o.sectionHref return sectionHref == o.sectionHref
&& blocks == o.blocks && blocks == o.blocks
&& wordCount == o.wordCount
&& charCount == o.charCount && charCount == o.charCount
&& unnestedContainers == o.unnestedContainers; && unnestedContainers == o.unnestedContainers;
} }
@@ -707,7 +707,6 @@ QVector<ContentChunk> parseChunks(const QString &html,
b.inlines.append(textItem); b.inlines.append(textItem);
chunk.blocks.append(b); chunk.blocks.append(b);
chunk.charCount = html.size(); chunk.charCount = html.size();
chunk.wordCount = html.split(QLatin1Char(' '), Qt::SkipEmptyParts).size();
return {chunk}; return {chunk};
} }
+36 -28
View File
@@ -12,6 +12,20 @@ Rectangle {
property bool restoreReady: false property bool restoreReady: false
property int initialIndex: 0 property int initialIndex: 0
property real initialOffset: 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 { gradient: Gradient {
GradientStop { position: 0.0; color: ThemeManager.currentTheme.gradientTop } GradientStop { position: 0.0; color: ThemeManager.currentTheme.gradientTop }
@@ -57,6 +71,10 @@ Rectangle {
property: "contentY" property: "contentY"
duration: 180 duration: 180
easing.type: Easing.OutQuad easing.type: Easing.OutQuad
onFinished: {
lastScrollSyncTime = Date.now();
syncScrollPosition();
}
} }
function updateContentMetrics() { function updateContentMetrics() {
@@ -68,12 +86,11 @@ Rectangle {
var probeX = chunkListView.width / 2; var probeX = chunkListView.width / 2;
var probeY = chunkListView.contentY + 10; var probeY = chunkListView.contentY + 10;
topIdx = chunkListView.indexAt(probeX, probeY); topIdx = chunkListView.indexAt(probeX, probeY);
if (topIdx < 0) { if (topIdx >= 0) {
topIdx = (readingModel.currentPage > 0) ? (readingModel.currentPage - 1) : 0; var topItem = chunkListView.itemAtIndex(topIdx);
} if (topItem && topItem.height > 0) {
var topItem = chunkListView.itemAtIndex(topIdx); intraRatio = Math.max(0.0, Math.min(1.0, (chunkListView.contentY - topItem.y) / topItem.height));
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: { onContentYChanged: {
if (contentReady && restoreReady) { 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 { ScrollBar.vertical: ScrollBar {
id: vScrollBar 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 { Connections {
target: readingModel target: readingModel
function onRestoreReady(chunkIndex, intraOffset) { function onRestoreReady(chunkIndex, intraOffset) {
+156
View File
@@ -78,6 +78,39 @@ public:
} }
}; };
class VariableCharsTextReader : public FormatReader {
public:
explicit VariableCharsTextReader(const QVector<int> &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<ContentChunk> chunks() const override { return m_chunks; }
private:
QVector<ContentChunk> m_chunks;
};
class ReadingModelTest : public QObject { class ReadingModelTest : public QObject {
Q_OBJECT Q_OBJECT
@@ -293,6 +326,129 @@ private slots:
const auto layout55 = model.data(model.index(55, 0), ReadingModel::LayoutRole).value<ChunkLayout>(); const auto layout55 = model.data(model.index(55, 0), ReadingModel::LayoutRole).value<ChunkLayout>();
QVERIFY(!layout55.lines.isEmpty()); 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<int> 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) QTEST_MAIN(ReadingModelTest)
+10 -17
View File
@@ -214,7 +214,7 @@ public:
} else { } else {
book.cover_image_url = std::nullopt; 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<ContentChunkValue>{fallbackChunk}; book.chunks = QVector<ContentChunkValue>{fallbackChunk};
book.binaries = binary_resources; book.binaries = binary_resources;
return true; return true;
@@ -324,19 +324,17 @@ private slots:
// Obligation 5: value-equality.ContentChunkValue // Obligation 5: value-equality.ContentChunkValue
void testValueEqualityContentChunkValue() void testValueEqualityContentChunkValue()
{ {
ContentChunkValue c1{QStringLiteral("sec1"), 5, 100, 500, 2}; ContentChunkValue c1{QStringLiteral("sec1"), 5, 500, 2};
ContentChunkValue c2{QStringLiteral("sec1"), 5, 100, 500, 2}; ContentChunkValue c2{QStringLiteral("sec1"), 5, 500, 2};
ContentChunkValue cDiffHref{QStringLiteral("sec2"), 5, 100, 500, 2}; ContentChunkValue cDiffHref{QStringLiteral("sec2"), 5, 500, 2};
ContentChunkValue cDiffBlocks{QStringLiteral("sec1"), 6, 100, 500, 2}; ContentChunkValue cDiffBlocks{QStringLiteral("sec1"), 6, 500, 2};
ContentChunkValue cDiffWords{QStringLiteral("sec1"), 5, 101, 500, 2}; ContentChunkValue cDiffChars{QStringLiteral("sec1"), 5, 501, 2};
ContentChunkValue cDiffChars{QStringLiteral("sec1"), 5, 100, 501, 2}; ContentChunkValue cDiffContainers{QStringLiteral("sec1"), 5, 500, 3};
ContentChunkValue cDiffContainers{QStringLiteral("sec1"), 5, 100, 500, 3};
QVERIFY(c1 == c2); QVERIFY(c1 == c2);
QVERIFY(!(c1 != c2)); QVERIFY(!(c1 != c2));
QVERIFY(c1 != cDiffHref); QVERIFY(c1 != cDiffHref);
QVERIFY(c1 != cDiffBlocks); QVERIFY(c1 != cDiffBlocks);
QVERIFY(c1 != cDiffWords);
QVERIFY(c1 != cDiffChars); QVERIFY(c1 != cDiffChars);
QVERIFY(c1 != cDiffContainers); QVERIFY(c1 != cDiffContainers);
} }
@@ -347,19 +345,16 @@ private slots:
ContentChunkValue c; ContentChunkValue c;
QVERIFY(c.section_href.isEmpty()); QVERIFY(c.section_href.isEmpty());
QCOMPARE(c.blocks_count, 0); QCOMPARE(c.blocks_count, 0);
QCOMPARE(c.word_count, 0);
QCOMPARE(c.char_count, 0); QCOMPARE(c.char_count, 0);
QCOMPARE(c.unnested_containers, 0); QCOMPARE(c.unnested_containers, 0);
c.section_href = QStringLiteral("body/s0"); c.section_href = QStringLiteral("body/s0");
c.blocks_count = 3; c.blocks_count = 3;
c.word_count = 50;
c.char_count = 250; c.char_count = 250;
c.unnested_containers = 1; c.unnested_containers = 1;
QCOMPARE(c.section_href, QStringLiteral("body/s0")); QCOMPARE(c.section_href, QStringLiteral("body/s0"));
QCOMPARE(c.blocks_count, 3); QCOMPARE(c.blocks_count, 3);
QCOMPARE(c.word_count, 50);
QCOMPARE(c.char_count, 250); QCOMPARE(c.char_count, 250);
QCOMPARE(c.unnested_containers, 1); QCOMPARE(c.unnested_containers, 1);
} }
@@ -391,7 +386,6 @@ private slots:
QCOMPARE(chunks1.size(), chunks2.size()); QCOMPARE(chunks1.size(), chunks2.size());
QVERIFY(!chunks1.isEmpty()); QVERIFY(!chunks1.isEmpty());
QCOMPARE(chunks1.first().sectionHref, chunks2.first().sectionHref); QCOMPARE(chunks1.first().sectionHref, chunks2.first().sectionHref);
QCOMPARE(chunks1.first().wordCount, chunks2.first().wordCount);
QCOMPARE(chunks1.first().charCount, chunks2.first().charCount); QCOMPARE(chunks1.first().charCount, chunks2.first().charCount);
QCOMPARE(chunks1.first().blocks.size(), chunks2.first().blocks.size()); QCOMPARE(chunks1.first().blocks.size(), chunks2.first().blocks.size());
@@ -525,7 +519,7 @@ private slots:
QCOMPARE(s.book.status, Fb2LoadStatus::loading_full); QCOMPARE(s.book.status, Fb2LoadStatus::loading_full);
// Edge 5: loading_full -> loaded // 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})); QVERIFY(s.completeFullOpenWithSections(client, "hash", "Title", "stem", {}, "Author", std::nullopt, {}, {chunk}));
QCOMPARE(s.book.status, Fb2LoadStatus::loaded); QCOMPARE(s.book.status, Fb2LoadStatus::loaded);
} }
@@ -755,7 +749,7 @@ private slots:
s.book.file_path = QStringLiteral("/books/novel.fb2"); s.book.file_path = QStringLiteral("/books/novel.fb2");
s.book.status = Fb2LoadStatus::loading_full; s.book.status = Fb2LoadStatus::loading_full;
ContentChunkValue chunk{"sec1", 2, 20, 100, 0}; ContentChunkValue chunk{"sec1", 2, 100, 0};
// Failure 1: actor != client // Failure 1: actor != client
QVERIFY(!s.completeFullOpenWithSections(c2, "hash", "Title", "stem", {}, "", std::nullopt, {}, {chunk})); 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.file_path = QStringLiteral("/books/empty.fb2");
s.book.status = Fb2LoadStatus::loading_full; s.book.status = Fb2LoadStatus::loading_full;
ContentChunkValue chunk{"sec1", 1, 0, 0, 0}; ContentChunkValue chunk{"sec1", 1, 0, 0};
// Failure 1: actor != client // Failure 1: actor != client
QVERIFY(!s.completeFullOpenWithEmptyBodyFallback(c2, "hash", "", "empty", {}, "", std::nullopt, {}, {})); QVERIFY(!s.completeFullOpenWithEmptyBodyFallback(c2, "hash", "", "empty", {}, "", std::nullopt, {}, {}));
@@ -806,7 +800,6 @@ private slots:
ContentChunkValue fallback = s.book.chunks.value().first(); ContentChunkValue fallback = s.book.chunks.value().first();
QCOMPARE(fallback.section_href, QStringLiteral("/books/empty.fb2")); QCOMPARE(fallback.section_href, QStringLiteral("/books/empty.fb2"));
QCOMPARE(fallback.blocks_count, 1); QCOMPARE(fallback.blocks_count, 1);
QCOMPARE(fallback.word_count, 0);
QCOMPARE(fallback.char_count, 0); QCOMPARE(fallback.char_count, 0);
} }
+28 -31
View File
@@ -312,6 +312,34 @@ private slots:
QVERIFY(imgTrue.pixelColor(testX, testY).alpha() > 0); QVERIFY(imgTrue.pixelColor(testX, testY).alpha() > 0);
} }
void contentChunkFontSizeScaling()
{
const QString html = QStringLiteral("<p>Testing dynamic font scaling directly on structured ContentChunk without re-parsing XML.</p>");
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() void clipRectCullingSkipsOffscreenImage()
{ {
class TrackingResolver : public IBookImageResolver { class TrackingResolver : public IBookImageResolver {
@@ -370,35 +398,6 @@ private slots:
KnuthPlassItem::setImageResolver(nullptr); KnuthPlassItem::setImageResolver(nullptr);
} }
void contentChunkFontSizeScaling()
{
const QString html = QStringLiteral("<p>Testing dynamic font scaling directly on structured ContentChunk without re-parsing XML.</p>");
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() void contentChunkPartitionAndUnnestedContainers()
{ {
const QString html = QStringLiteral( const QString html = QStringLiteral(
@@ -412,12 +411,10 @@ private slots:
QCOMPARE(chunks[0].sectionHref, QStringLiteral("section1.xhtml")); QCOMPARE(chunks[0].sectionHref, QStringLiteral("section1.xhtml"));
QCOMPARE(chunks[0].unnestedContainers, 0); QCOMPARE(chunks[0].unnestedContainers, 0);
QVERIFY(chunks[0].wordCount > 0);
QVERIFY(chunks[0].charCount > 0); QVERIFY(chunks[0].charCount > 0);
QCOMPARE(chunks[1].sectionHref, QStringLiteral("section1.xhtml")); QCOMPARE(chunks[1].sectionHref, QStringLiteral("section1.xhtml"));
QCOMPARE(chunks[1].unnestedContainers, 1); // Carries the open blockquote container QCOMPARE(chunks[1].unnestedContainers, 1); // Carries the open blockquote container
QVERIFY(chunks[1].wordCount > 0);
QVERIFY(chunks[1].charCount > 0); QVERIFY(chunks[1].charCount > 0);
// Layout both chunks and verify decorations // Layout both chunks and verify decorations
@@ -218,6 +218,9 @@ public:
QStringLiteral("<p>Content paragraph for chunk index %1 with sufficient words for layout.</p>").arg(i), QStringLiteral("<p>Content paragraph for chunk index %1 with sufficient words for layout.</p>").arg(i),
QStringLiteral("text/section_%1.xhtml").arg(i) QStringLiteral("text/section_%1.xhtml").arg(i)
); );
if (!parsed.isEmpty()) {
parsed[0].charCount = kNormalizedCharsPerPage;
}
list.append(parsed); list.append(parsed);
} }
return list; return list;
@@ -746,7 +749,6 @@ private slots:
const auto &chunk = chunks.first(); const auto &chunk = chunks.first();
QCOMPARE(chunk.sectionHref, QStringLiteral("section.xhtml")); QCOMPARE(chunk.sectionHref, QStringLiteral("section.xhtml"));
QVERIFY(chunk.wordCount > 0);
QVERIFY(chunk.charCount > 0); QVERIFY(chunk.charCount > 0);
QCOMPARE(chunk.unnestedContainers, 0); QCOMPARE(chunk.unnestedContainers, 0);
} }
@@ -929,7 +931,7 @@ private slots:
model.setScrollPosition(3, 45.0, 0.35); model.setScrollPosition(3, 45.0, 0.35);
QCOMPARE(posSpy.count(), 1); QCOMPARE(posSpy.count(), 1);
QCOMPARE(model.currentPage(), 4); QCOMPARE(model.currentChunk(), 3);
QCOMPARE(model.progress(), 0.35); QCOMPARE(model.progress(), 0.35);
BookPosition loaded = ctx.store->load(reader.contentHash()); BookPosition loaded = ctx.store->load(reader.contentHash());
@@ -1157,8 +1159,7 @@ private slots:
model.setReader(&reader); model.setReader(&reader);
model.setScrollPosition(5, 0.0, 0.5); model.setScrollPosition(5, 0.0, 0.5);
const int page = model.currentPage(); const int anchorChunk = model.currentChunk();
const int anchorChunk = page - 1;
QVERIFY(anchorChunk >= 0); QVERIFY(anchorChunk >= 0);
QVERIFY(anchorChunk < model.rowCount()); QVERIFY(anchorChunk < model.rowCount());
} }
@@ -1240,7 +1241,7 @@ private slots:
// 2. progress // 2. progress
QCOMPARE(model.progress(), 0.0); QCOMPARE(model.progress(), 0.0);
// 3. anchor_chunk // 3. anchor_chunk
QCOMPARE(model.currentPage() - 1, 0); QCOMPARE(model.currentChunk(), 0);
// 4. use_book_colours // 4. use_book_colours
QCOMPARE(model.useBookColours(), false); QCOMPARE(model.useBookColours(), false);
// 5. status // 5. status
+1 -3
View File
@@ -46,8 +46,7 @@ public:
for (int i = 0; i < m_count; ++i) { for (int i = 0; i < m_count; ++i) {
ContentChunk chunk; ContentChunk chunk;
chunk.sectionHref = QStringLiteral("text/ch_%1.xhtml").arg(i); chunk.sectionHref = QStringLiteral("text/ch_%1.xhtml").arg(i);
chunk.wordCount = 10; chunk.charCount = kNormalizedCharsPerPage;
chunk.charCount = 60;
chunk.unnestedContainers = 0; chunk.unnestedContainers = 0;
BlockItem p; BlockItem p;
@@ -411,7 +410,6 @@ private slots:
{ {
ContentChunk chunk; ContentChunk chunk;
chunk.sectionHref = QStringLiteral("sec1.xhtml"); chunk.sectionHref = QStringLiteral("sec1.xhtml");
chunk.wordCount = 100;
chunk.charCount = 500; chunk.charCount = 500;
chunk.unnestedContainers = 1; chunk.unnestedContainers = 1;
QVERIFY(chunk.isEmpty()); QVERIFY(chunk.isEmpty());