old render cleanup part 1

This commit is contained in:
Agel committed 2026-10-25 14:22:12 +01:00
1 parent 83968646c6
commit acc7e71e7b
38 files changed
+155 -1355

No files matched your search

-16
View File
@@ -59,8 +59,6 @@ set(SOURCES
src/backend/ReadingModel.cpp
src/backend/reading/MangaPagination.h
src/backend/reading/MangaPagination.cpp
src/backend/reading/MeasurementController.h
src/backend/reading/MeasurementController.cpp
src/backend/state/ReadingPreferences.h
src/backend/state/ReadingPreferences.cpp
src/backend/state/UiState.h
@@ -70,10 +68,7 @@ set(SOURCES
src/backend/book/Book.h
src/backend/book/Book.cpp
src/backend/IImageProvider.h
src/backend/IImageLoader.h
src/backend/ZipUtils.h
src/backend/ChunkMeasurer.h
src/backend/ChunkMeasurer.cpp
src/backend/IFileDialogService.h
src/backend/NativeFileDialogService.h
src/backend/NativeFileDialogService.cpp
@@ -182,8 +177,6 @@ set_source_files_properties(src/qml/ThemeManager.qml PROPERTIES QT_RESOURCE_ALIA
QT_QML_SINGLETON_TYPE TRUE)
set_source_files_properties(src/qml/components/Header.qml PROPERTIES QT_RESOURCE_ALIAS components/Header.qml)
set_source_files_properties(src/qml/components/SideBar.qml PROPERTIES QT_RESOURCE_ALIAS components/SideBar.qml)
set_source_files_properties(src/qml/components/PageView.qml PROPERTIES QT_RESOURCE_ALIAS components/PageView.qml)
set_source_files_properties(src/qml/components/ScrollPageView.qml PROPERTIES QT_RESOURCE_ALIAS components/ScrollPageView.qml)
set_source_files_properties(src/qml/components/MangaPageView.qml PROPERTIES QT_RESOURCE_ALIAS components/MangaPageView.qml)
set_source_files_properties(src/qml/components/Footer.qml PROPERTIES QT_RESOURCE_ALIAS components/Footer.qml)
set_source_files_properties(src/qml/components/ErrorPopup.qml PROPERTIES QT_RESOURCE_ALIAS components/ErrorPopup.qml)
@@ -209,8 +202,6 @@ qt_add_qml_module(asteria-qt
src/qml/ThemeManager.qml
src/qml/components/Header.qml
src/qml/components/SideBar.qml
src/qml/components/PageView.qml
src/qml/components/ScrollPageView.qml
src/qml/components/MangaPageView.qml
src/qml/components/Footer.qml
src/qml/components/ErrorPopup.qml
@@ -313,16 +304,9 @@ add_asteria_test(FormatRegistryTest tests/FormatRegistryTest.cpp
target_link_libraries(FormatRegistryTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network)
set_tests_properties(FormatRegistryTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(ChunkMeasurerTest tests/ChunkMeasurerTest.cpp
src/backend/ChunkMeasurer.cpp)
target_link_libraries(ChunkMeasurerTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick Qt6::Network PkgConfig::MINIZIP)
set_tests_properties(ChunkMeasurerTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp
src/backend/ReadingModel.cpp
src/backend/reading/MangaPagination.cpp
src/backend/reading/MeasurementController.cpp
src/backend/ChunkMeasurer.cpp
src/backend/formats/AsyncImageResponse.cpp
src/backend/formats/sources/Fb2ByteSource.cpp
src/backend/formats/WebImageProvider.cpp
+1 -1
View File
@@ -1,3 +1,3 @@
Read CLAUDE.md for project details.
Read AGENTS.md for project details.
ALWAYS try to compile and run tests after making code changes to ensure system integrity.
+1 -31
View File
@@ -34,36 +34,22 @@ AppCoordinator::AppCoordinator(Book &book,
, m_formatRegistry(formatRegistry)
, m_engine(engine)
{
// Typography changes → re-push font params into ReadingModel
connect(&m_readingPreferences, &ReadingPreferences::fontSizeChanged,
this, &AppCoordinator::onFontPrefsChanged);
connect(&m_readingPreferences, &ReadingPreferences::lineSpacingChanged,
this, &AppCoordinator::onFontPrefsChanged);
connect(&m_book, &Book::willOpenNewBook, this, &AppCoordinator::onWillOpenNewBook);
connect(&m_book, &Book::positionSaved, this, &AppCoordinator::onPositionSaved);
connect(&m_book, &Book::bookChanged, this, &AppCoordinator::onBookChanged);
connect(&m_book, &Book::contentWidthChanged, this, &AppCoordinator::onContentWidthChanged);
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit,
this, &AppCoordinator::onAboutToQuit);
}
void AppCoordinator::onFontPrefsChanged()
{
m_readingModel.setFontParams(m_readingPreferences.fontSize(),
m_readingPreferences.lineSpacing());
}
// Before a new book open: snapshot the outgoing book's progress into the library.
// Scroll position is handled by PageView's scroll tracker via book.saveCurrentPosition().
void AppCoordinator::onWillOpenNewBook()
{
if (m_book.hasBook())
m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress());
}
// Real-time history update: fired by PageView's scrollTrackTimer on every scroll.
// Real-time history update: fired when position is saved.
void AppCoordinator::onPositionSaved()
{
m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress());
@@ -87,34 +73,18 @@ void AppCoordinator::onBookChanged()
m_engine.removeImageProvider(provider->scheme());
m_engine.addImageProvider(provider->scheme(), provider);
provider->setFilePath(filePath);
provider->setDisplayWidth(m_contentWidth);
m_currentImageProvider = provider;
if (!reader->coverImagePath().isEmpty())
m_book.setCoverImageUrl(provider->coverImageUrl(reader->coverImagePath()));
}
m_readingModel.setFontParams(m_readingPreferences.fontSize(),
m_readingPreferences.lineSpacing());
m_readingModel.setImageLoader(m_formatRegistry.createImageLoader(filePath));
m_readingModel.setCoverImageUrl(m_book.coverImageUrl());
m_readingModel.setReader(reader);
m_readingModel.measure(true);
m_uiState.setLastFilePath(filePath);
m_historyModel.addOrUpdateBook(filePath, -1.0);
}
// Propagate content-width changes to image provider + reading model.
// Called from Book::setContentWidth which is triggered by QML's PageView.
void AppCoordinator::onContentWidthChanged(int width)
{
m_contentWidth = width;
if (m_currentImageProvider)
m_currentImageProvider->setDisplayWidth(width);
m_readingModel.setContentWidth(width);
}
// Quit: flush everything to persistent storage.
// Scroll position was last saved by PageView's scroll tracker; we save library progress here.
void AppCoordinator::onAboutToQuit()
-3
View File
@@ -35,8 +35,6 @@ private slots:
void onBookChanged();
void onWillOpenNewBook();
void onPositionSaved();
void onContentWidthChanged(int width);
void onFontPrefsChanged();
void onAboutToQuit();
private:
@@ -51,5 +49,4 @@ private:
QQmlApplicationEngine &m_engine;
IImageProvider *m_currentImageProvider = nullptr;
int m_contentWidth = 0;
};
-96
View File
@@ -1,96 +0,0 @@
#include "ChunkMeasurer.h"
#include <QFont>
#include <QFontMetricsF>
#include <QImage>
#include <QTextBlockFormat>
#include <QTextCursor>
#include <QTextDocument>
#include <QTextOption>
#include <QThread>
#include <QtConcurrent>
#include <QAtomicInt>
// Private: one instance per worker thread — owns its IImageLoader clone
class ImageLoadingDocument : public QTextDocument {
IImageLoader *m_loader = nullptr;
int m_maxWidth = 0;
public:
void setLoader(IImageLoader *loader, int maxWidth) {
m_loader = loader;
m_maxWidth = maxWidth;
}
protected:
QVariant loadResource(int type, const QUrl &url) override {
if (type == QTextDocument::ImageResource && m_loader) {
QImage img = m_loader->load(url, m_maxWidth);
if (!img.isNull()) return img;
}
return QTextDocument::loadResource(type, url);
}
};
ChunkMeasurer::ChunkMeasurer(std::unique_ptr<IImageLoader> imageLoader,
int fontSize, qreal lineSpacing)
: m_imageLoader(std::move(imageLoader))
, m_fontSize(fontSize)
, m_lineSpacing(lineSpacing)
{}
QVector<int> ChunkMeasurer::measure(const QStringList &chunks, qreal textWidth)
{
const int n = chunks.size();
if (n == 0) return {};
if (textWidth <= 0) textWidth = 1.0;
QVector<int> heights(n, 0);
QAtomicInt nextIdx(0);
const int threadCount = 2;
// Capture by value what each worker needs (no shared mutable state)
auto worker = [&]() {
std::unique_ptr<IImageLoader> loader =
m_imageLoader ? m_imageLoader->clone() : nullptr;
ImageLoadingDocument doc;
doc.setLoader(loader.get(), qRound(textWidth));
doc.setDocumentMargin(0);
doc.setUndoRedoEnabled(false);
QTextOption textOption = doc.defaultTextOption();
textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
doc.setDefaultTextOption(textOption);
QFont font;
font.setPixelSize(m_fontSize);
doc.setDefaultFont(font);
for (;;) {
const int i = nextIdx.fetchAndAddRelaxed(1);
if (i >= n) break;
doc.setHtml(chunks[i]);
doc.setTextWidth(textWidth);
QTextBlockFormat fmt;
fmt.setLineHeight(m_lineSpacing * 100.0, QTextBlockFormat::ProportionalHeight);
QTextCursor cursor(&doc);
cursor.select(QTextCursor::Document);
cursor.mergeBlockFormat(fmt);
// QTextDocument includes trailing line spacing after the last line,
// but QML's Text element does not. Subtract the correction.
QFontMetricsF fm(font);
qreal trailingCorrection = (m_lineSpacing - 1.0) * fm.lineSpacing();
heights[i] = qRound(doc.size().height() - trailingCorrection);
}
};
QList<QFuture<void>> futures;
futures.reserve(threadCount);
for (int t = 0; t < threadCount; ++t)
futures.append(QtConcurrent::run(worker));
for (auto &f : futures)
f.waitForFinished();
return heights;
}
-16
View File
@@ -1,16 +0,0 @@
#ifndef CHUNKMEASURER_H
#define CHUNKMEASURER_H
#include "IChunkMeasurer.h"
#include "IImageLoader.h"
#include <memory>
class ChunkMeasurer : public IChunkMeasurer {
public:
explicit ChunkMeasurer(std::unique_ptr<IImageLoader> imageLoader = nullptr,
int fontSize = 16, qreal lineSpacing = 1.0);
QVector<int> measure(const QStringList &chunks, qreal textWidth) override;
private:
std::unique_ptr<IImageLoader> m_imageLoader;
int m_fontSize;
qreal m_lineSpacing;
};
#endif
-11
View File
@@ -1,11 +0,0 @@
#ifndef ICHUNKMEASURER_H
#define ICHUNKMEASURER_H
#include <QStringList>
#include <QVector>
#include <QtGlobal>
class IChunkMeasurer {
public:
virtual ~IChunkMeasurer() = default;
virtual QVector<int> measure(const QStringList &chunks, qreal textWidth) = 0;
};
#endif
-10
View File
@@ -1,10 +0,0 @@
#pragma once
#include <QImage>
#include <QUrl>
#include <memory>
class IImageLoader {
public:
virtual ~IImageLoader() = default;
virtual QImage load(const QUrl &url, int maxWidth) const = 0;
virtual std::unique_ptr<IImageLoader> clone() const = 0;
};
-1
View File
@@ -6,7 +6,6 @@ class IImageProvider : public QQuickAsyncImageProvider {
public:
virtual ~IImageProvider() = default;
virtual void setFilePath(const QString &filePath) = 0;
virtual void setDisplayWidth(int width) = 0;
virtual void clear() = 0;
// Returns the full QML image URL for a given internal path (e.g., "image://epub/OEBPS/cover.jpg")
virtual QString coverImageUrl(const QString &coverPath) const = 0;
+25 -141
View File
@@ -2,47 +2,15 @@
#include "FormatReader.h"
#include <QRegularExpression>
#include <algorithm>
#include <cmath>
ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent)
: QAbstractListModel(parent)
: QObject(parent)
, m_positions(positions)
{
connect(&m_measurer, &MeasurementController::measuringChanged,
this, &ReadingModel::measuringChanged);
connect(&m_measurer, &MeasurementController::heightsReady,
this, &ReadingModel::onHeightsReady);
}
ReadingModel::~ReadingModel() = default;
int ReadingModel::rowCount(const QModelIndex &parent) const {
if (parent.isValid()) return 0;
return m_chunks.size();
}
QVariant ReadingModel::data(const QModelIndex &index, int role) const {
if (!index.isValid() || index.row() < 0 || index.row() >= (int)m_chunks.size())
return {};
const auto &c = m_chunks.at(index.row());
switch (role) {
case ContentRole: return c.html;
case PixelHeightRole: return c.pixelHeight;
case ChapterRole: return c.chapterIndex;
case NaturalSizeRole: return c.naturalSize;
default: return {};
}
}
QHash<int, QByteArray> ReadingModel::roleNames() const {
return {
{ContentRole, "content"},
{PixelHeightRole, "pixelHeight"},
{ChapterRole, "chapter"},
{NaturalSizeRole, "naturalSize"},
};
}
QString ReadingModel::chapterTitle() const
{
if (m_currentChapter < 0 || m_currentChapter >= m_chapterTitles.size())
@@ -53,8 +21,6 @@ QString ReadingModel::chapterTitle() const
int ReadingModel::currentChapter() const { return m_currentChapter; }
int ReadingModel::totalChapters() const { return m_totalChapters; }
bool ReadingModel::hasChapters() const { return m_totalChapters > 1; }
bool ReadingModel::measuring() const { return m_measurer.measuring(); }
qreal ReadingModel::totalPixelHeight() const { return m_totalPixelHeight; }
int ReadingModel::totalPagePairs() const { return m_pagination.count(); }
bool ReadingModel::isMangaMode() const { return m_isMangaMode; }
bool ReadingModel::pageShift() const { return m_pageShift; }
@@ -79,90 +45,14 @@ void ReadingModel::setScrollInfo(const int topChunkIndex, const qreal proportion
emit chapterChanged();
}
recalculateCurrentPage();
}
void ReadingModel::measure(const bool isNew)
{
if (!m_reader) return;
if (m_isMangaMode) {
// No measurement needed — images are sized by the view to fit the viewport.
// Queue the emission so QML's Loader has time to create MangaPageView before
// restoreReady arrives (in scroll mode the async measurement provides this gap).
QMetaObject::invokeMethod(this, [this, isNew] {
emitRestoreReady(isNew);
}, Qt::QueuedConnection);
return;
}
m_totalPixelHeight = 0;
QStringList htmls;
htmls.reserve(m_chunks.size());
for (const auto &c : m_chunks)
htmls.append(c.html);
const int width = m_contentWidth > 0 ? m_contentWidth : 800;
m_measurer.start(htmls, width, m_fontSize, m_lineSpacing, isNew);
}
void ReadingModel::emitRestoreReady(const bool isNew)
{
if (!isNew) return;
const auto pos = m_positions.load(m_reader->contentHash());
emit restoreReady(pos.chunkIndex, pos.intraOffset);
}
void ReadingModel::onHeightsReady(const QVector<int> &heights, const bool isNew)
{
for (int i = 0; i < qMin(heights.size(), static_cast<int>(m_chunks.size())); ++i) {
m_chunks[i].pixelHeight = heights[i];
m_totalPixelHeight += heights[i];
}
qInfo("Measured %lld chunks, total height: %f", heights.size(), m_totalPixelHeight);
emit totalPixelHeightChanged();
emit dataChanged(createIndex(0, 0),
createIndex(m_chunks.size() - 1, 0),
{PixelHeightRole});
emitRestoreReady(isNew);
}
void ReadingModel::setContentWidth(int width)
{
if (width == m_contentWidth) return;
m_contentWidth = width;
if (m_reader && !m_isMangaMode) measure(false);
}
void ReadingModel::setFontParams(int fontSize, qreal lineSpacing)
{
if (fontSize == m_fontSize && qFuzzyCompare(lineSpacing, m_lineSpacing)) return;
m_fontSize = fontSize;
m_lineSpacing = lineSpacing;
if (m_reader && !m_isMangaMode) measure(false);
}
void ReadingModel::setImageLoader(std::unique_ptr<IImageLoader> loader)
{
m_measurer.setImageLoader(std::move(loader));
}
void ReadingModel::recalculateCurrentPage()
{
// In manga mode currentPage/totalPages track pair index/count (updated by MangaPageView).
if (m_isMangaMode) return;
int page = 0;
if (!m_chunks.isEmpty()) {
page = qBound(0.0, m_yOffset / m_totalPixelHeight, 1.0) * m_chunks.size() * page_ratio;
}
if (m_currentPage == page)
return;
const int page = pairIndexForChunk(topChunkIndex) + 1;
if (m_currentPage != page) {
m_currentPage = page;
emit currentPageChanged();
}
}
}
void ReadingModel::rebuildPagePairs()
{
@@ -242,7 +132,7 @@ void ReadingModel::setPageShift(bool shift, int currentPairIndex)
// Persist immediately.
if (m_reader)
m_positions.save(m_reader->contentHash(), currentChunk, 0, m_mangaRTL, m_pageShift);
m_positions.save(m_reader->contentHash(), currentChunk, m_mangaRTL, m_pageShift);
emit pageShiftChanged();
// Tell MangaPageView the exact pair to jump to so it re-evaluates its display binding.
@@ -253,8 +143,10 @@ void ReadingModel::setMangaRTL(bool rtl)
{
if (m_mangaRTL == rtl) return;
m_mangaRTL = rtl;
if (m_reader)
m_positions.save(m_reader->contentHash(), 0, 0, m_mangaRTL, m_pageShift);
if (m_reader) {
const int currentChunk = (m_currentPage > 0) ? m_pagination.at(m_currentPage - 1).first : 0;
m_positions.save(m_reader->contentHash(), currentChunk >= 0 ? currentChunk : 0, m_mangaRTL, m_pageShift);
}
emit mangaRTLChanged();
}
@@ -268,29 +160,16 @@ static QString extractImageUrl(const QString &html)
void ReadingModel::loadAllChapters()
{
beginResetModel();
m_chunks.clear();
m_chapterStartIndices.clear();
m_chapterTitles.clear();
m_totalPixelHeight = 0.0;
emit totalPixelHeightChanged();
m_currentChapter = 0;
if (m_currentPage != 0) { m_currentPage = 0; emit currentPageChanged(); }
if (m_totalPages != 0) { m_totalPages = 0; emit totalPagesChanged(); }
if (m_reader) {
// In manga mode the format's first chunk is already the cover — no extra cover injection.
if (!m_isMangaMode && !m_coverImageUrl.isEmpty()) {
QString coverHtml = QStringLiteral("<div class=\"cover-image\" style=\"text-align: center; margin: 2em 0;\">")
+ QStringLiteral("<img src=\"") + m_coverImageUrl
+ QStringLiteral("\" style=\"max-width: 100%; max-height: 80vh;\" /></div>");
m_chunks.push_back({coverHtml, 0, -1, -1, QSize(),
extractImageUrl(coverHtml)}); // chunkInChapter=-1 = cover sentinel
m_chapterStartIndices.append(1); // chapter 0 starts after cover
} else {
m_chapterStartIndices.append(0);
}
for (int i = 0; i < m_totalChapters; ++i) {
auto chapter = m_reader->loadChapter(i);
const QVector<QSize> sizes = m_reader->chapterPageSizes(i);
@@ -300,18 +179,17 @@ void ReadingModel::loadAllChapters()
int j = 0;
for (const auto &html : chapter.contentChunks) {
const QSize sz = (j < sizes.size()) ? sizes[j] : QSize();
m_chunks.push_back({html, i, j, -1, sz, extractImageUrl(html)});
m_chunks.push_back({i, sz, extractImageUrl(html)});
++j;
}
}
}
endResetModel();
if (m_isMangaMode) {
rebuildPagePairs();
} else {
if (const int pages = m_chunks.size() * page_ratio; m_totalPages != pages) {
m_totalPages = pages;
if (m_totalPages != m_chunks.size()) {
m_totalPages = m_chunks.size();
emit totalPagesChanged();
}
if (const int page = m_chunks.isEmpty() ? 0 : 1; m_currentPage != page) {
@@ -333,25 +211,31 @@ void ReadingModel::setReader(FormatReader *reader)
emit isMangaModeChanged();
// Load per-book pageShift and mangaRTL before loadAllChapters so rebuildPagePairs uses the saved values.
if (m_isMangaMode && reader) {
int restoreChunk = 0;
if (reader) {
const auto pos = m_positions.load(reader->contentHash());
restoreChunk = pos.chunkIndex;
if (m_isMangaMode) {
m_pageShift = pos.pageShift;
m_mangaRTL = pos.mangaRTL;
} else {
m_pageShift = true;
m_mangaRTL = true;
}
} else {
m_pageShift = true;
m_mangaRTL = true;
}
loadAllChapters();
emit totalChaptersChanged();
emit chapterChanged();
}
void ReadingModel::setCoverImageUrl(const QString &coverImageUrl)
{
if (m_coverImageUrl != coverImageUrl) {
m_coverImageUrl = coverImageUrl;
if (m_reader) {
QMetaObject::invokeMethod(this, [this, restoreChunk] {
emit restoreReady(restoreChunk);
}, Qt::QueuedConnection);
}
}
+8 -54
View File
@@ -1,28 +1,23 @@
#ifndef READINGMODEL_H
#define READINGMODEL_H
#include <QAbstractListModel>
#include <QObject>
#include <QSize>
#include <QString>
#include <QVariantList>
#include <QVector>
#include <memory>
#include "IImageLoader.h"
#include "reading/MangaPagination.h"
#include "reading/MeasurementController.h"
#include "state/BookPositionStore.h"
class FormatReader;
struct ContentChunk {
QString html; // empty when unloaded (lazy streaming)
int chapterIndex = 0; // which chapter owns this chunk
int chunkInChapter = 0; // 0-based index within chapter (-1 for cover)
int pixelHeight = -1; // -1 = not yet measured
QSize naturalSize; // image pixel dimensions (null for text chunks)
QString imageUrl; // src of the chunk's img tag (empty for text chunks)
int chapterIndex = 0;
QSize naturalSize;
QString imageUrl;
};
class ReadingModel : public QAbstractListModel {
class ReadingModel : public QObject {
Q_OBJECT
Q_PROPERTY(QString chapterTitle READ chapterTitle NOTIFY chapterChanged)
Q_PROPERTY(int currentChapter READ currentChapter NOTIFY chapterChanged)
@@ -31,28 +26,15 @@ class ReadingModel : public QAbstractListModel {
Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged)
Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged)
Q_PROPERTY(bool hasChapters READ hasChapters NOTIFY totalChaptersChanged)
Q_PROPERTY(bool measuring READ measuring NOTIFY measuringChanged)
Q_PROPERTY(qreal totalPixelHeight READ totalPixelHeight NOTIFY totalPixelHeightChanged)
Q_PROPERTY(int totalPagePairs READ totalPagePairs NOTIFY totalPagePairsChanged)
Q_PROPERTY(bool isMangaMode READ isMangaMode NOTIFY isMangaModeChanged)
Q_PROPERTY(bool pageShift READ pageShift NOTIFY pageShiftChanged)
Q_PROPERTY(bool mangaRTL READ mangaRTL NOTIFY mangaRTLChanged)
public:
enum Roles {
ContentRole = Qt::UserRole + 1,
PixelHeightRole = Qt::UserRole + 2,
ChapterRole = Qt::UserRole + 3,
NaturalSizeRole = Qt::UserRole + 4,
};
explicit ReadingModel(BookPositionStore &positions, QObject *parent = nullptr);
~ReadingModel() override;
int rowCount(const QModelIndex &parent) const override;
QVariant data(const QModelIndex &index, int role) const override;
QHash<int, QByteArray> roleNames() const override;
QString chapterTitle() const;
int currentChapter() const;
int totalChapters() const;
@@ -60,17 +42,14 @@ public:
int currentPage() const;
int totalPages() const;
bool hasChapters() const;
bool measuring() const;
qreal totalPixelHeight() const;
int totalPagePairs() const;
bool isMangaMode() const;
bool pageShift() const;
bool mangaRTL() const;
void setReader(FormatReader *reader);
void setCoverImageUrl(const QString &coverImageUrl);
// Called from QML on every scroll (real-time)
// Called from QML on every page navigation
Q_INVOKABLE void setScrollInfo(int topChunkIndex, qreal proportion);
Q_INVOKABLE void nextChapter();
@@ -90,19 +69,9 @@ public:
Q_INVOKABLE void setPageShift(bool shift, int currentPairIndex = 0);
Q_INVOKABLE void setMangaRTL(bool rtl);
// Measurement
Q_INVOKABLE void measure(bool isNew);
// Preferences & state
void setContentWidth(int width);
Q_INVOKABLE void setFontParams(int fontSize, qreal lineSpacing);
void setImageLoader(std::unique_ptr<IImageLoader> loader);
signals:
void chapterChanged();
void totalChaptersChanged();
void measuringChanged();
void totalPixelHeightChanged();
void currentPageChanged();
void totalPagesChanged();
void totalPagePairsChanged();
@@ -113,21 +82,13 @@ signals:
void pagePairsRebuilt(int newPairIndex);
void scrollToChunkRequested(int chunkIndex);
void restoreReady(int chunkIndex, int intraChunkOffset);
private slots:
void onHeightsReady(const QVector<int> &heights, bool isNew);
void restoreReady(int chunkIndex);
private:
static constexpr qreal page_ratio = 1.5;
void loadAllChapters();
void recalculateCurrentPage();
void rebuildPagePairs();
void emitRestoreReady(bool isNew);
FormatReader *m_reader = nullptr;
QString m_coverImageUrl;
int m_currentChapter = 0;
int m_totalChapters = 0;
int m_currentPage = 0;
@@ -141,17 +102,10 @@ private:
QVector<int> m_chapterStartIndices;
QVector<QString> m_chapterTitles;
// Manga page-pair layout. In RTL mode the "left" slot is the later page visually.
MangaPagination m_pagination;
qreal m_totalPixelHeight = 0.0;
qreal m_yOffset = 0.0;
int m_contentWidth = 0;
int m_fontSize = 0;
qreal m_lineSpacing = 0;
BookPositionStore &m_positions;
MeasurementController m_measurer;
};
#endif // READINGMODEL_H
+2 -9
View File
@@ -143,16 +143,9 @@ void Book::clearError()
emit errorMessageChanged();
}
void Book::saveCurrentPosition(int chunkIndex, int intraOffset, bool pageShift)
void Book::saveCurrentPosition(int chunkIndex, bool mangaRTL, bool pageShift)
{
if (!m_reader) return;
m_positions.save(m_reader->contentHash(), chunkIndex, intraOffset, pageShift);
m_positions.save(m_reader->contentHash(), chunkIndex, mangaRTL, pageShift);
emit positionSaved();
}
void Book::setContentWidth(int width)
{
if (m_contentWidth == width) return;
m_contentWidth = width;
emit contentWidthChanged(width);
}
+2 -8
View File
@@ -51,12 +51,8 @@ public:
Q_INVOKABLE void close();
Q_INVOKABLE void clearError();
// Save current scroll position. Called from QML's scroll tracker; forwards to BookPositionStore.
Q_INVOKABLE void saveCurrentPosition(int chunkIndex, int intraOffset, bool pageShift = false);
// Called from QML's PageView when its width changes. Propagates to image provider + ReadingModel
// via the contentWidthChanged signal (wired in main.cpp).
Q_INVOKABLE void setContentWidth(int width);
// Save current position. Called from QML; forwards to BookPositionStore.
Q_INVOKABLE void saveCurrentPosition(int chunkIndex, bool mangaRTL = true, bool pageShift = true);
signals:
// Emitted just before replacing the current reader with a new one.
@@ -67,7 +63,6 @@ signals:
void bookChanged();
void loadingChanged();
void errorMessageChanged();
void contentWidthChanged(int width);
private:
void openImpl(const QString &filePath);
@@ -80,7 +75,6 @@ private:
QString m_errorMessage;
bool m_loading = false;
int m_openGeneration = 0;
int m_contentWidth = 0;
QFuture<void> m_openFuture;
};
+3 -47
View File
@@ -11,7 +11,6 @@
QImage EntryImageProvider::loadImageFromSource(IByteSource &source,
const QString &entryName,
int displayWidth,
const QSize &requestedSize)
{
if (entryName.isEmpty())
@@ -25,7 +24,7 @@ QImage EntryImageProvider::loadImageFromSource(IByteSource &source,
if (!image.loadFromData(data))
return {};
return scaleToFit(image, displayWidth, requestedSize);
return scaleToFit(image, requestedSize);
}
EntryImageProvider::EntryImageProvider(SourceFactory sourceFactory, QString scheme)
@@ -38,11 +37,9 @@ QQuickImageResponse *EntryImageProvider::requestImageResponse(const QString &id,
const QSize &requestedSize)
{
QString sourcePath;
int displayWidth;
{
QMutexLocker lock(&m_mutex);
sourcePath = m_sourcePath;
displayWidth = m_displayWidth;
}
// id may be "entry/name.jpg?src=<encoded-path>"
@@ -52,50 +49,16 @@ QQuickImageResponse *EntryImageProvider::requestImageResponse(const QString &id,
sourcePath = parsed.sourcePath;
auto *response = new AsyncImageResponse(
[factory = m_sourceFactory, sourcePath, entryName, displayWidth, requestedSize]() -> QImage {
[factory = m_sourceFactory, sourcePath, entryName, requestedSize]() -> QImage {
auto source = factory();
if (!source->open(sourcePath))
return {};
return loadImageFromSource(*source, entryName, displayWidth, requestedSize);
return loadImageFromSource(*source, entryName, requestedSize);
});
QThreadPool::globalInstance()->start(response);
return response;
}
QImage EntryImageProvider::load(const QUrl &url, int maxWidth) const
{
if (url.scheme() != QLatin1String("image"))
return {};
const ImageUrl::Parsed parsed = ImageUrl::parseImageUrl(url);
const QString entryName = parsed.entry;
if (entryName.isEmpty())
return {};
QString sourcePath = parsed.sourcePath;
if (sourcePath.isEmpty()) {
QMutexLocker lock(&m_mutex);
sourcePath = m_sourcePath;
}
auto source = m_sourceFactory();
if (!source->open(sourcePath))
return {};
return loadImageFromSource(*source, entryName, maxWidth, {});
}
std::unique_ptr<IImageLoader> EntryImageProvider::clone() const
{
QString sourcePath;
{
QMutexLocker lock(&m_mutex);
sourcePath = m_sourcePath;
}
auto c = std::make_unique<EntryImageProvider>(m_sourceFactory, m_scheme);
c->setFilePath(sourcePath);
return c;
}
void EntryImageProvider::setFilePath(const QString &filePath)
{
QMutexLocker lock(&m_mutex);
@@ -114,15 +77,8 @@ QString EntryImageProvider::scheme() const
return m_scheme;
}
void EntryImageProvider::setDisplayWidth(int width)
{
QMutexLocker lock(&m_mutex);
m_displayWidth = width;
}
void EntryImageProvider::clear()
{
QMutexLocker lock(&m_mutex);
m_sourcePath.clear();
m_displayWidth = 0;
}
+1 -8
View File
@@ -1,7 +1,6 @@
#pragma once
#include "IByteSource.h"
#include "backend/IImageLoader.h"
#include "backend/IImageProvider.h"
#include <functional>
@@ -9,7 +8,7 @@
#include <QMutex>
#include <QString>
class EntryImageProvider : public IImageProvider, public IImageLoader {
class EntryImageProvider : public IImageProvider {
public:
using SourceFactory = std::function<std::unique_ptr<IByteSource>()>;
@@ -19,17 +18,12 @@ public:
const QSize &requestedSize) override;
void setFilePath(const QString &filePath) override;
void setDisplayWidth(int width) override;
void clear() override;
QString coverImageUrl(const QString &coverPath) const override;
QString scheme() const override;
QImage load(const QUrl &url, int maxWidth) const override;
std::unique_ptr<IImageLoader> clone() const override;
static QImage loadImageFromSource(IByteSource &source,
const QString &entryName,
int displayWidth,
const QSize &requestedSize);
private:
@@ -37,5 +31,4 @@ private:
QString m_scheme;
mutable QMutex m_mutex;
QString m_sourcePath;
int m_displayWidth = 0;
};
-48
View File
@@ -7,36 +7,6 @@
#include <QFileInfo>
#include <QQmlEngine>
// Dispatches load() calls to the right child loader based on the image:// host (scheme name).
class CompositeImageLoader : public IImageLoader {
public:
void add(const QString &host, std::unique_ptr<IImageLoader> loader)
{
m_loaders.emplace_back(host, std::move(loader));
}
QImage load(const QUrl &url, int maxWidth) const override
{
const QString host = url.host();
for (const auto &[h, loader] : m_loaders) {
if (h == host)
return loader->load(url, maxWidth);
}
return {};
}
std::unique_ptr<IImageLoader> clone() const override
{
auto c = std::make_unique<CompositeImageLoader>();
for (const auto &[host, loader] : m_loaders)
c->add(host, loader->clone());
return c;
}
private:
std::vector<std::pair<QString, std::unique_ptr<IImageLoader>>> m_loaders;
};
FormatRegistry::FormatRegistry(QVector<FormatSpec> specs)
: m_specs(std::move(specs))
{
@@ -69,24 +39,6 @@ IImageProvider *FormatRegistry::createImageProvider(const QString &filePath) con
return new EntryImageProvider(spec->makeSource, spec->scheme);
}
std::unique_ptr<IImageLoader> FormatRegistry::createImageLoader(const QString &filePath) const
{
const FormatSpec *spec = specFor(filePath);
if (!spec || spec->scheme.isEmpty() || !spec->makeSource)
return nullptr;
auto loader = std::make_unique<EntryImageProvider>(spec->makeSource, spec->scheme);
loader->setFilePath(filePath);
if (!spec->loaderIncludesWeb)
return loader;
auto composite = std::make_unique<CompositeImageLoader>();
composite->add(spec->scheme, std::move(loader));
composite->add(QStringLiteral("web"), std::make_unique<WebImageProvider>());
return composite;
}
QStringList FormatRegistry::supportedExtensions() const
{
QStringList out;
-5
View File
@@ -8,7 +8,6 @@
class FormatReader;
class IByteSource;
class IImageLoader;
class IImageProvider;
class QQmlEngine;
@@ -21,7 +20,6 @@ struct FormatSpec {
QString scheme; // image:// scheme; empty = format has no images
std::function<std::unique_ptr<FormatReader>()> makeReader;
std::function<std::unique_ptr<IByteSource>()> makeSource; // required when scheme is set
bool loaderIncludesWeb = false; // formats whose content may reference web images (epub)
};
class FormatRegistry {
@@ -34,9 +32,6 @@ public:
// Caller owns the pointer (the QML engine takes ownership on registration).
IImageProvider *createImageProvider(const QString &filePath) const;
// Synchronous loader for measurement, or nullptr for formats without images.
std::unique_ptr<IImageLoader> createImageLoader(const QString &filePath) const;
QStringList supportedExtensions() const;
// Register one provider per scheme with the QML engine (engine takes ownership).
+2 -9
View File
@@ -3,17 +3,13 @@
#include <QImage>
#include <QSize>
// Honor an explicit requested size (clamped to the display width), otherwise
// scale down to fit the display width — never enlarge.
inline QImage scaleToFit(QImage image, int displayWidth, const QSize &requestedSize)
// Honor an explicit requested size, otherwise keep original image dimensions — never enlarge.
inline QImage scaleToFit(QImage image, const QSize &requestedSize)
{
if (requestedSize.width() > 0 || requestedSize.height() > 0) {
int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1;
int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1;
if (displayWidth > 0 && targetW > 0 && targetW > displayWidth)
targetW = displayWidth;
if (targetW > 0 && targetH > 0) {
image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio,
Qt::SmoothTransformation);
@@ -22,9 +18,6 @@ inline QImage scaleToFit(QImage image, int displayWidth, const QSize &requestedS
} else {
image = image.scaledToHeight(targetH, Qt::SmoothTransformation);
}
} else {
if (displayWidth > 0 && image.width() > displayWidth)
image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation);
}
return image;
}
+5 -49
View File
@@ -39,7 +39,7 @@ QString WebImageProvider::cacheFilePath(const QString &urlString)
// WebImageProvider
// ---------------------------------------------------------------------------
QImage WebImageProvider::loadWebImage(const QString &urlString, int displayWidth,
QImage WebImageProvider::loadWebImage(const QString &urlString,
const QSize &requestedSize)
{
if (urlString.isEmpty())
@@ -50,7 +50,7 @@ QImage WebImageProvider::loadWebImage(const QString &urlString, int displayWidth
if (QFile::exists(cachePath)) {
QImage image;
if (image.load(cachePath))
return scaleToFit(image, displayWidth, requestedSize);
return scaleToFit(image, requestedSize);
}
// Download — blocking, safe to call from any thread via a local event loop
@@ -89,7 +89,7 @@ QImage WebImageProvider::loadWebImage(const QString &urlString, int displayWidth
if (!image.loadFromData(data))
return {};
return scaleToFit(image, displayWidth, requestedSize);
return scaleToFit(image, requestedSize);
}
// ---------------------------------------------------------------------------
@@ -109,13 +109,8 @@ QQuickImageResponse *WebImageProvider::requestImageResponse(const QString &id,
return response;
}
int displayWidth;
{
QMutexLocker lock(&m_mutex);
displayWidth = m_displayWidth;
}
auto *response = new AsyncImageResponse([id, displayWidth, requestedSize] {
return loadWebImage(id, displayWidth, requestedSize);
auto *response = new AsyncImageResponse([id, requestedSize] {
return loadWebImage(id, requestedSize);
});
QThreadPool::globalInstance()->start(response);
return response;
@@ -125,42 +120,3 @@ QString WebImageProvider::scheme() const
{
return QStringLiteral("web");
}
void WebImageProvider::setDisplayWidth(int width)
{
QMutexLocker lock(&m_mutex);
m_displayWidth = width;
}
// ---------------------------------------------------------------------------
// WebImageProvider — IImageLoader
// ---------------------------------------------------------------------------
QImage WebImageProvider::load(const QUrl &url, int maxWidth) const
{
// url is image://web/<original-web-url>
// url.path() yields "/<original-web-url>"; strip leading '/'
QString webUrl = url.path();
if (webUrl.startsWith(QLatin1Char('/')))
webUrl = webUrl.mid(1);
if (webUrl.isEmpty())
return {};
int displayWidth;
{
QMutexLocker lock(&m_mutex);
displayWidth = m_displayWidth;
}
const int effective = (displayWidth > 0 && maxWidth > 0)
? qMin(displayWidth, maxWidth)
: qMax(displayWidth, maxWidth);
return loadWebImage(webUrl, effective, {});
}
std::unique_ptr<IImageLoader> WebImageProvider::clone() const
{
auto c = std::make_unique<WebImageProvider>();
QMutexLocker lock(&m_mutex);
c->m_displayWidth = m_displayWidth;
return c;
}
+2 -12
View File
@@ -1,34 +1,24 @@
#pragma once
#include <QMutex>
#include <QSize>
#include <QString>
#include "backend/IImageLoader.h"
#include "backend/IImageProvider.h"
class WebImageProvider : public IImageProvider, public IImageLoader {
class WebImageProvider : public IImageProvider {
public:
QQuickImageResponse *requestImageResponse(const QString &id,
const QSize &requestedSize) override;
void setFilePath(const QString &) override {}
void setDisplayWidth(int width) override;
void clear() override {}
QString coverImageUrl(const QString &) const override { return {}; }
QString scheme() const override;
QImage load(const QUrl &url, int maxWidth) const override;
std::unique_ptr<IImageLoader> clone() const override;
// Download (or load from disk cache) a web image. Thread-safe, may block.
static QImage loadWebImage(const QString &urlString, int displayWidth,
static QImage loadWebImage(const QString &urlString,
const QSize &requestedSize);
static QString cacheDir();
static QString cacheFilePath(const QString &urlString);
private:
mutable QMutex m_mutex;
int m_displayWidth = 0;
};
@@ -1,50 +0,0 @@
#include "MeasurementController.h"
#include "backend/ChunkMeasurer.h"
#include <QtConcurrent>
MeasurementController::MeasurementController(QObject *parent)
: QObject(parent)
{
}
MeasurementController::~MeasurementController()
{
if (m_future.isRunning()) {
m_future.cancel();
m_future.waitForFinished();
}
}
void MeasurementController::setImageLoader(std::unique_ptr<IImageLoader> loader)
{
m_imageLoader = std::move(loader);
}
bool MeasurementController::measuring() const
{
return m_measuring;
}
void MeasurementController::start(const QStringList &htmls, int contentWidth,
int fontSize, qreal lineSpacing, bool isNew)
{
if (m_future.isRunning())
m_future.cancel();
m_measuring = true;
emit measuringChanged();
std::unique_ptr<IImageLoader> loaderClone = m_imageLoader ? m_imageLoader->clone() : nullptr;
auto measurer = std::make_shared<ChunkMeasurer>(std::move(loaderClone), fontSize, lineSpacing);
m_future = QtConcurrent::run([this, htmls, measurer, contentWidth, isNew]() {
QVector<int> heights = measurer->measure(htmls, contentWidth);
QMetaObject::invokeMethod(this, [this, heights, isNew] {
m_measuring = false;
emit measuringChanged();
emit heightsReady(heights, isNew);
}, Qt::QueuedConnection);
});
}
@@ -1,37 +0,0 @@
#pragma once
#include <QFuture>
#include <QObject>
#include <QStringList>
#include <QVector>
#include <memory>
#include "backend/IImageLoader.h"
// Runs chunk height measurement off the GUI thread and reports the results
// back on it. Owns the image loader used to resolve embedded images and the
// lifetime of the in-flight measurement.
class MeasurementController : public QObject {
Q_OBJECT
public:
explicit MeasurementController(QObject *parent = nullptr);
~MeasurementController() override;
void setImageLoader(std::unique_ptr<IImageLoader> loader);
// isNew is passed through untouched to heightsReady so the owner knows
// whether this measurement should trigger a position restore.
void start(const QStringList &htmls, int contentWidth,
int fontSize, qreal lineSpacing, bool isNew);
bool measuring() const;
signals:
void measuringChanged();
void heightsReady(QVector<int> heights, bool isNew);
private:
std::unique_ptr<IImageLoader> m_imageLoader;
bool m_measuring = false;
QFuture<void> m_future;
};
+1 -3
View File
@@ -12,19 +12,17 @@ BookPosition BookPositionStore::load(const QByteArray &contentMd5)
const QVariantMap d = m_state.loadSection(sectionKey(contentMd5));
BookPosition pos;
pos.chunkIndex = d.value(QStringLiteral("chunkIndex"), 0).toInt();
pos.intraOffset = d.value(QStringLiteral("intraOffset"), 0).toInt();
pos.pageShift = d.value(QStringLiteral("pageShift"), true).toBool();
pos.mangaRTL = d.value(QStringLiteral("mangaRTL"), true).toBool();
return pos;
}
void BookPositionStore::save(const QByteArray &contentMd5, int chunkIndex, int intraOffset, bool mangaRTL, bool pageShift)
void BookPositionStore::save(const QByteArray &contentMd5, int chunkIndex, bool mangaRTL, bool pageShift)
{
if (contentMd5.isEmpty())
return;
m_state.saveSection(sectionKey(contentMd5), {
{QStringLiteral("chunkIndex"), chunkIndex},
{QStringLiteral("intraOffset"), intraOffset},
{QStringLiteral("pageShift"), pageShift},
{QStringLiteral("mangaRTL"), mangaRTL},
});
+1 -2
View File
@@ -6,7 +6,6 @@
struct BookPosition {
int chunkIndex = 0;
int intraOffset = 0;
bool pageShift = true; // manga page-shift; default ON
bool mangaRTL = true; // manga reading direction; default RTL
};
@@ -19,7 +18,7 @@ public:
BookPosition load(const QByteArray &contentMd5);
// Save the current position for a book identified by MD5 of its contents.
void save(const QByteArray &contentMd5, int chunkIndex, int intraOffset, bool mangaRTL = true, bool pageShift = true);
void save(const QByteArray &contentMd5, int chunkIndex, bool mangaRTL = true, bool pageShift = true);
private:
AppState &m_state;
+1 -2
View File
@@ -111,8 +111,7 @@ int main(int argc, char *argv[])
[] { return std::make_unique<TxtReader>(); }, nullptr},
{QStringLiteral("epub"), false, QStringLiteral("epub"),
[] { return std::make_unique<EpubReader>(); },
[] { return std::make_unique<ZipByteSource>(); },
/*loaderIncludesWeb=*/true},
[] { return std::make_unique<ZipByteSource>(); }},
{QStringLiteral("fb2"), false, QStringLiteral("fb2"),
[] { return std::make_unique<Fb2Reader>(); },
[] { return std::make_unique<Fb2ByteSource>(); }},
+2 -30
View File
@@ -57,13 +57,6 @@ ApplicationWindow {
}
}
Connections {
target: readingModel
function onMeasuringChanged() {
if (!readingModel.measuring) window._bookInitializing = false
}
}
Timer {
id: geometrySaveTimer
interval: 250
@@ -181,10 +174,8 @@ ApplicationWindow {
// Navigate once measurement (and position restoration) is done
Connections {
target: readingModel
function onRestoreReady(chunkIndex, intraOffset) {
function onRestoreReady(chunkIndex) {
if (!book.hasBook) return
// Reset loading overlay — in manga mode measuring is skipped so measuringChanged
// never fires; restoreReady is the definitive "ready" signal for all modes.
window._bookInitializing = false
if (window._startupRestore) {
window._startupRestore = false
@@ -218,24 +209,6 @@ ApplicationWindow {
context: Qt.ApplicationShortcut
onActivated: window.visibility = (window.visibility === Window.FullScreen) ? Window.Windowed : Window.FullScreen
}
Shortcut {
sequence: "Up"
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader" && readerPage?.pageView && !readingModel.isMangaMode) {
readerPage.pageView.handleScrollUp();
}
}
}
Shortcut {
sequence: "Down"
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader" && readerPage?.pageView && !readingModel.isMangaMode) {
readerPage.pageView.handleScrollDown();
}
}
}
Shortcut {
sequence: "Left"
context: Qt.ApplicationShortcut
@@ -314,7 +287,7 @@ ApplicationWindow {
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader" && readingModel.isMangaMode)
readingModel.setPageShift(!readingModel.pageShift, readerPage.pageView.currentMangaPair)
readingModel.setPageShift(!readingModel.pageShift, readerPage.pageView.currentPair)
}
}
@@ -325,7 +298,6 @@ ApplicationWindow {
triggeredOnStart: false
onTriggered: {
window.opacity = 1
readerPage.pageView.updateContentWidth()
if (uiState.lastFilePath !== "") {
window._startupRestore = true
book.openFromPath(uiState.lastFilePath)
+1 -21
View File
@@ -13,25 +13,6 @@ Rectangle {
anchors.top: parent.top
}
// Measuring spinner (hidden during manga mode — measurement is skipped for image formats)
Text {
anchors.left: parent.left
anchors.leftMargin: 16
anchors.verticalCenter: parent.verticalCenter
visible: readingModel.measuring
text: ""
font.family: "Material Icons Outlined"
font.pixelSize: 14
color: ThemeManager.currentTheme.dimText
RotationAnimator on rotation {
from: 0; to: 360
duration: 1200
loops: Animation.Infinite
running: parent.visible
}
}
// RTL reading direction toggle (manga mode only).
FlatIconButton {
anchors.left: parent.left
@@ -62,8 +43,7 @@ Rectangle {
: ThemeManager.currentTheme.dimText
tooltip: "Page shift (S)"
onClicked: {
// currentPair lives on MangaPageView; reach it via the PageView router alias.
const pairIdx = readerPage.pageView.currentMangaPair
const pairIdx = readerPage.pageView.currentPair
readingModel.setPageShift(!readingModel.pageShift, pairIdx)
}
}
+5 -9
View File
@@ -6,13 +6,7 @@ Rectangle {
id: root
focus: true
// Keep the same public interface as ScrollPageView so PageView router delegates uniformly.
property bool contentReady: false
property bool resizing: false
property bool restoreReady: false
property int initialIndex: -1
property int initialOffset: -1
property int currentPair: 0
readonly property bool landscape: width > height
@@ -48,7 +42,7 @@ Rectangle {
const firstChunk = pair[0]
// Keep scroll model in sync so Footer page counter and chapter tracking work.
readingModel.setScrollInfo(firstChunk, pairIndex / Math.max(1, readingModel.totalPagePairs - 1))
book.saveCurrentPosition(firstChunk, 0, readingModel.pageShift)
book.saveCurrentPosition(firstChunk, readingModel.mangaRTL, readingModel.pageShift)
}
// Notify model when orientation changes (triggers pair rebuild).
@@ -196,9 +190,11 @@ Rectangle {
// Restore position when a new book is loaded.
Connections {
target: readingModel
function onRestoreReady(chunkIndex, intraOffset) {
function onRestoreReady(chunkIndex) {
contentReady = true
restoreReady = true
showPair(readingModel.pairIndexForChunk(chunkIndex))
}
function onScrollToChunkRequested(chunkIndex) {
showPair(readingModel.pairIndexForChunk(chunkIndex))
}
function onTotalPagePairsChanged() {
-45
View File
@@ -1,45 +0,0 @@
import QtQuick
import QtQuick.Controls
import Asteria
Item {
id: root
focus: true
// Mirror the public properties ScrollPageView exposes so callers stay unchanged.
property bool contentReady: false
property bool resizing: false
property bool restoreReady: false
property int initialIndex: -1
property int initialOffset: -1
// Current pair index in the active MangaPageView; -1 when in scroll mode.
readonly property int currentMangaPair: (loader.item && loader.item.hasOwnProperty("currentPair"))
? loader.item.currentPair : -1
// Delegate all navigation calls to whichever view is active.
function handlePageUp() { if (loader.item) loader.item.handlePageUp() }
function handlePageDown() { if (loader.item) loader.item.handlePageDown() }
function handleScrollUp() { if (loader.item) loader.item.handleScrollUp() }
function handleScrollDown() { if (loader.item) loader.item.handleScrollDown() }
function updateContentWidth() {
if (loader.item && typeof loader.item.updateContentWidth === "function")
loader.item.updateContentWidth()
}
Loader {
id: loader
anchors.fill: parent
sourceComponent: readingModel.isMangaMode ? mangaViewComp : scrollViewComp
}
Component {
id: scrollViewComp
ScrollPageView { anchors.fill: parent; focus: true }
}
Component {
id: mangaViewComp
MangaPageView { anchors.fill: parent; focus: true }
}
}
-224
View File
@@ -1,224 +0,0 @@
import QtQuick
import QtQuick.Controls
import Asteria
Rectangle {
focus: true
// Width reserved for the vertical scrollbar on the right edge.
readonly property int scrollbarWidth: 18
property bool contentReady: false
property bool resizing: false
property bool restoreReady: false
property int initialIndex: -1
property int initialOffset: -1
// Animation for smooth scrolling
property Animation scrollAnimation: PropertyAnimation {
target: chunkListView
property: "contentY"
duration: 200
easing.type: Easing.InOutQuad
}
// Public methods for global keyboard navigation
function handlePageUp() {
var scrollAmount = chunkListView.height * 0.95;
var targetY = Math.max(0, chunkListView.contentY - scrollAmount);
animateScrollTo(targetY);
}
function handlePageDown() {
var scrollAmount = chunkListView.height * 0.95;
var maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height);
var targetY = Math.min(maxY, chunkListView.contentY + scrollAmount);
animateScrollTo(targetY);
}
function handleScrollUp() {
var lineHeight = readingPreferences.fontSize * readingPreferences.lineSpacing;
var scrollAmount = lineHeight * 3;
var targetY = Math.max(0, chunkListView.contentY - scrollAmount);
animateScrollTo(targetY);
}
function handleScrollDown() {
var lineHeight = readingPreferences.fontSize * readingPreferences.lineSpacing;
var scrollAmount = lineHeight * 3;
var maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height);
var targetY = Math.min(maxY, chunkListView.contentY + scrollAmount);
animateScrollTo(targetY);
}
function animateScrollTo(targetY) {
scrollAnimation.stop();
scrollAnimation.to = targetY;
scrollAnimation.start();
}
gradient: Gradient {
GradientStop { position: 0.0; color: ThemeManager.currentTheme.gradientTop }
GradientStop { position: 1.0; color: ThemeManager.currentTheme.gradientBottom }
}
function updateContentWidth() {
book.setContentWidth(chunkListView.width - scrollbarWidth - 2 * readingPreferences.horizontalMargin)
}
Component.onCompleted: updateContentWidth()
onWidthChanged: {
resizing = true;
remeasureTimer.restart()
}
Timer {
id: remeasureTimer
interval: 150
repeat: false
onTriggered: {
updateContentWidth()
resizing = false;
}
}
ListView {
id: chunkListView
anchors.fill: parent
anchors.topMargin: readingPreferences.verticalMargin
anchors.bottomMargin: readingPreferences.verticalMargin
model: contentReady ? readingModel : null
cacheBuffer: 20
clip: true
maximumFlickVelocity: 99999
delegate: Item {
id: chunkDelegate
readonly property int chunkIdx: model.index
width: chunkListView.width
height: resizing || readingModel.measuring ? contentText.implicitHeight : model.pixelHeight
Text {
visible: isDebugBuild
leftPadding: 0
text: model.index
color: "#FFFFFF"
height: 0
}
Text {
id: contentText
width: parent.width - scrollbarWidth
leftPadding: readingPreferences.horizontalMargin
rightPadding: readingPreferences.horizontalMargin
wrapMode: Text.WrapAtWordBoundaryOrAnywhere
textFormat: Text.RichText
font.pixelSize: readingPreferences.fontSize
lineHeight: readingPreferences.lineSpacing
color: ThemeManager.currentTheme.readingText
text: model.content
visible: model.content !== ""
onImplicitHeightChanged: {
if (isDebugBuild && model.pixelHeight > 0 && implicitHeight > 0) {
const diff = model.pixelHeight - implicitHeight
if (Math.abs(diff) > 1) {
console.warn("Chunk", model.index,
"height mismatch: measured=" + model.pixelHeight,
"actual=" + Math.round(implicitHeight),
"diff=" + Math.round(diff))
}
}
}
}
}
onContentYChanged: {
scrollTrackTimer.restart()
}
ScrollBar.vertical: ScrollBar {
policy: ScrollBar.AsNeeded
padding: 0
contentItem: Rectangle {
implicitWidth: scrollbarWidth
radius: 3
color: ThemeManager.currentTheme.scrollbarThumb
}
background: Rectangle {
implicitWidth: scrollbarWidth
color: ThemeManager.currentTheme.scrollbarTrack
}
}
MouseArea {
anchors.fill: parent
anchors.rightMargin: scrollbarWidth
z: 1
onClicked: clickDebounce.restart()
onDoubleClicked: {
clickDebounce.stop()
window.visibility = (window.visibility === Window.FullScreen) ? Window.Windowed : Window.FullScreen
}
}
Timer {
id: clickDebounce
interval: 150
onTriggered: {
window.barsVisible = !window.barsVisible
uiState.sidebarOpen = !uiState.sidebarOpen
}
}
}
Timer {
id: scrollTrackTimer
interval: 300
repeat: false
onTriggered: {
if (book.hasBook && contentReady && restoreReady) {
var topIdx = chunkListView.indexAt(0, chunkListView.contentY)
if (topIdx < 0) topIdx = 0
var topItem = chunkListView.itemAtIndex(topIdx)
var intraOffset = topItem ? (chunkListView.contentY - topItem.y) : 0
readingModel.setScrollInfo(topIdx, chunkListView.visibleArea.yPosition)
book.saveCurrentPosition(topIdx, intraOffset)
}
}
}
Connections {
target: book
function onLoadingChanged() {
if (book.loading)
contentReady = false
}
}
Connections {
target: readingModel
function onRestoreReady(chunkIndex, intraOffset) {
contentReady = true
initialIndex = chunkIndex
initialOffset = intraOffset
restoreTimer.start()
}
function onScrollToChunkRequested(chunkIndex) {
chunkListView.positionViewAtIndex(chunkIndex, ListView.Beginning)
}
}
Timer {
id: restoreTimer
interval: 1
repeat: false
onTriggered: {
if (isDebugBuild)
console.info("Restoring contentHeight:", chunkListView.contentHeight, "originY:", chunkListView.originY, "chunkIndex:", initialIndex, "intraOffset:", initialOffset)
chunkListView.positionViewAtIndex(initialIndex, ListView.Beginning)
chunkListView.contentY += initialOffset
restoreReady = true
}
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ Item {
id: readerPage
property alias pageView: internalPageView
PageView {
MangaPageView {
id: internalPageView
anchors.fill: parent
focus: visible
-81
View File
@@ -1,81 +0,0 @@
#include <QtTest>
#include "backend/ChunkMeasurer.h"
#include "backend/IImageLoader.h"
// A mock image loader that returns a solid-color image of a fixed size
class FixedSizeImageLoader : public IImageLoader {
QSize m_size;
public:
explicit FixedSizeImageLoader(const QSize &size) : m_size(size) {}
QImage load(const QUrl &, int maxWidth) const override {
int w = qMin(m_size.width(), maxWidth);
int h = m_size.height();
if (w <= 0 || h <= 0) return {};
QImage img(w, h, QImage::Format_RGB32);
img.fill(Qt::red);
return img;
}
std::unique_ptr<IImageLoader> clone() const override {
return std::make_unique<FixedSizeImageLoader>(m_size);
}
};
class ChunkMeasurerTest : public QObject {
Q_OBJECT
private slots:
void returnsOneHeightPerChunk() {
ChunkMeasurer m;
QStringList chunks = {"<p>First</p>", "<p>Second</p>", "<p>Third</p>"};
auto h = m.measure(chunks, 800);
QCOMPARE(h.size(), 3);
}
void heightsArePositive() {
ChunkMeasurer m;
auto h = m.measure({"<p>Hello world</p>", "<p>Another paragraph</p>"}, 800);
for (int v : h) QVERIFY(v > 0);
}
void emptyInputReturnsEmpty() {
ChunkMeasurer m;
QVERIFY(m.measure({}, 800).isEmpty());
}
void zeroWidthClampedToOne() {
ChunkMeasurer m;
auto h = m.measure({"<p>text</p>"}, 0);
QCOMPARE(h.size(), 1);
QVERIFY(h.first() > 0);
}
void narrowerWidthGivesGreaterOrEqualHeight() {
ChunkMeasurer m;
QStringList chunks = {"<p>A long paragraph that should wrap when the width is very narrow.</p>"};
int h800 = m.measure(chunks, 800).first();
int h200 = m.measure(chunks, 200).first();
QVERIFY(h200 >= h800);
}
void imageChunkMeasuredWithLoader() {
// 600x400 image, but maxWidth=400 so it gets scaled to 400x267
auto loader = std::make_unique<FixedSizeImageLoader>(QSize(600, 400));
ChunkMeasurer m(std::move(loader));
// Chunk with an image URL
QStringList chunks = {QStringLiteral("<p><img src=\"image://epub/test.jpg\"/></p>")};
auto h = m.measure(chunks, 400);
QCOMPARE(h.size(), 1);
QVERIFY(h.first() > 0); // should include image height
}
void nullLoaderTextOnlyWorks() {
ChunkMeasurer m(nullptr);
auto h = m.measure({"<p>text only</p>"}, 800);
QCOMPARE(h.size(), 1);
QVERIFY(h.first() > 0);
}
void parallelResultsAreConsistent() {
ChunkMeasurer m;
QStringList chunks;
for (int i = 0; i < 100; ++i)
chunks << QStringLiteral("<p>Paragraph number %1 with some text content.</p>").arg(i);
auto h1 = m.measure(chunks, 600);
auto h2 = m.measure(chunks, 600);
QCOMPARE(h1, h2);
}
};
QTEST_MAIN(ChunkMeasurerTest)
#include "ChunkMeasurerTest.moc"
+11 -61
View File
@@ -17,13 +17,12 @@
// Load one zip member through the generic byte-source pipeline (EPUBs are zips).
static QImage loadFromEpub(const QString &epubPath, const QString &entry,
int displayWidth, const QSize &requestedSize)
const QSize &requestedSize)
{
ZipByteSource source;
if (!source.open(epubPath))
return {};
return EntryImageProvider::loadImageFromSource(source, entry, displayWidth,
requestedSize);
return EntryImageProvider::loadImageFromSource(source, entry, requestedSize);
}
static EntryImageProvider makeEpubProvider()
@@ -96,7 +95,7 @@ private slots:
QVERIFY(!epubPath.isEmpty());
const QImage img = loadFromEpub(
epubPath, QStringLiteral("OEBPS/Images/test.png"), 0, QSize());
epubPath, QStringLiteral("OEBPS/Images/test.png"), QSize());
QFile::remove(epubPath);
@@ -112,7 +111,7 @@ private slots:
QVERIFY(!epubPath.isEmpty());
const QImage img = loadFromEpub(
epubPath, QStringLiteral("OEBPS/Images/nonexistent.png"), 0, QSize());
epubPath, QStringLiteral("OEBPS/Images/nonexistent.png"), QSize());
QFile::remove(epubPath);
@@ -122,7 +121,7 @@ private slots:
void requestImageReturnsNullWhenNoPath()
{
const QImage img = loadFromEpub(
QString{}, QStringLiteral("OEBPS/Images/test.png"), 0, QSize());
QString{}, QStringLiteral("OEBPS/Images/test.png"), QSize());
QVERIFY(img.isNull());
}
@@ -133,51 +132,20 @@ private slots:
// After clear the path is empty, so loadImageFromEpub with empty path returns null
const QImage img = loadFromEpub(
QString{}, QStringLiteral("OEBPS/Images/test.png"), 0, QSize());
QString{}, QStringLiteral("OEBPS/Images/test.png"), QSize());
QFile::remove(epubPath);
QVERIFY(img.isNull());
}
void largeImageScaledToDisplayWidth()
{
const QString epubPath = buildEpubWithPng("img.png", 600, 400);
QVERIFY(!epubPath.isEmpty());
const QImage img = loadFromEpub(
epubPath, QStringLiteral("img.png"), 300, QSize());
QFile::remove(epubPath);
QVERIFY(!img.isNull());
QCOMPARE(img.width(), 300);
QCOMPARE(img.height(), 200);
QCOMPARE(img.size(), QSize(300, 200));
}
void smallImageNotEnlarged()
{
const QString epubPath = buildEpubWithPng("img.png", 100, 100);
QVERIFY(!epubPath.isEmpty());
const QImage img = loadFromEpub(
epubPath, QStringLiteral("img.png"), 300, QSize());
QFile::remove(epubPath);
QVERIFY(!img.isNull());
QCOMPARE(img.width(), 100);
QCOMPARE(img.height(), 100);
}
void requestedSizeHonored()
{
const QString epubPath = buildEpubWithPng("img.png", 400, 300);
QVERIFY(!epubPath.isEmpty());
const QImage img = loadFromEpub(
epubPath, QStringLiteral("img.png"), 600, QSize(200, -1));
epubPath, QStringLiteral("img.png"), QSize(200, -1));
QFile::remove(epubPath);
@@ -196,7 +164,7 @@ private slots:
AsyncImageResponse response([epubPath] {
return loadFromEpub(
epubPath, QStringLiteral("img.png"), 0, QSize());
epubPath, QStringLiteral("img.png"), QSize());
});
QSignalSpy spy(&response, &QQuickImageResponse::finished);
response.run();
@@ -214,7 +182,7 @@ private slots:
AsyncImageResponse response([epubPath] {
return loadFromEpub(
epubPath, QStringLiteral("img.png"), 0, QSize());
epubPath, QStringLiteral("img.png"), QSize());
});
QSignalSpy spy(&response, &QQuickImageResponse::finished);
response.cancel();
@@ -232,7 +200,7 @@ private slots:
AsyncImageResponse response([epubPath] {
return loadFromEpub(
epubPath, QStringLiteral("img.png"), 0, QSize());
epubPath, QStringLiteral("img.png"), QSize());
});
response.cancel();
response.run();
@@ -298,24 +266,6 @@ private slots:
delete resp;
}
void loadMethodHandlesEmbeddedUrlFormat()
{
const QString epubPath = buildEpubWithPng("img.png", 4, 4, qRgb(255, 0, 0));
QVERIFY(!epubPath.isEmpty());
EntryImageProvider provider = makeEpubProvider();
// m_epubPath is intentionally NOT set — embedded URL must supply it via query
const QString encodedPath = QString::fromUtf8(QUrl::toPercentEncoding(epubPath));
const QUrl url(QStringLiteral("image://epub/img.png?src=") + encodedPath);
const QImage img = provider.load(url, 0);
QFile::remove(epubPath);
QVERIFY(!img.isNull());
QCOMPARE(img.pixel(0, 0), qRgb(255, 0, 0));
}
void requestImageResponseFallsBackToProviderPath()
{
// Without a leading slash in id, the provider should use m_epubPath.
@@ -387,7 +337,7 @@ private slots:
QCOMPARE(source.listEntries(), QStringList{QStringLiteral("cover.png")});
const QImage img = EntryImageProvider::loadImageFromSource(
source, QStringLiteral("cover.png"), 0, QSize());
source, QStringLiteral("cover.png"), QSize());
QVERIFY(!source.contentHash().isEmpty());
QFile::remove(path);
+2 -13
View File
@@ -3,7 +3,6 @@
#include "backend/formats/FormatRegistry.h"
#include "backend/FormatReader.h"
#include "backend/IImageProvider.h"
#include "backend/IImageLoader.h"
#include "backend/formats/TxtReader.h"
#include "backend/formats/EpubReader.h"
#include "backend/formats/comic/CbzReader.h"
@@ -20,8 +19,7 @@ static FormatRegistry makeRegistry()
[] { return std::make_unique<TxtReader>(); }, nullptr},
{QStringLiteral("epub"), false, QStringLiteral("epub"),
[] { return std::make_unique<EpubReader>(); },
[] { return std::make_unique<ZipByteSource>(); },
/*loaderIncludesWeb=*/true},
[] { return std::make_unique<ZipByteSource>(); }},
{QStringLiteral("cbz"), false, QStringLiteral("cbz"),
[] { return std::make_unique<CbzReader>(); },
[] { return std::make_unique<ZipByteSource>(); }},
@@ -120,21 +118,12 @@ private slots:
QCOMPARE(dir->scheme(), QStringLiteral("dir"));
}
void formatsWithoutImagesHaveNoProviderOrLoader()
void formatsWithoutImagesHaveNoProvider()
{
auto registry = makeRegistry();
QVERIFY(registry.createImageProvider("plain.txt") == nullptr);
QVERIFY(registry.createImageLoader("plain.txt") == nullptr);
QVERIFY(registry.createImageProvider("file.xyz") == nullptr);
}
void createImageLoaderReturnsLoader()
{
auto registry = makeRegistry();
QVERIFY(registry.createImageLoader("comic.cbz") != nullptr);
// epub loader is a composite (epub + web) but still non-null
QVERIFY(registry.createImageLoader("book.epub") != nullptr);
}
};
QTEST_MAIN(FormatRegistryTest)
+1 -2
View File
@@ -22,8 +22,7 @@ static FormatRegistry makeRegistry()
[] { return std::make_unique<TxtReader>(); }, nullptr},
{QStringLiteral("epub"), false, QStringLiteral("epub"),
[] { return std::make_unique<EpubReader>(); },
[] { return std::make_unique<ZipByteSource>(); },
/*loaderIncludesWeb=*/true},
[] { return std::make_unique<ZipByteSource>(); }},
});
}
+60 -174
View File
@@ -51,6 +51,38 @@ public:
QString fileType() const override { return QStringLiteral("txt"); }
};
class FakeMangaReader : public FormatReader {
public:
bool open(const QString &) override { return true; }
QString lastError() override { return {}; }
int chapterCount() override { return 1; }
Chapter loadChapter(int index) override
{
if (index != 0) return {index, {}, {}};
return {0, QStringLiteral("Manga Title"),
{QStringLiteral("<img src=\"image://cbz/0.jpg\"/>"),
QStringLiteral("<img src=\"image://cbz/1.jpg\"/>"),
QStringLiteral("<img src=\"image://cbz/2.jpg\"/>")}};
}
QVector<QSize> chapterPageSizes(int index) const override
{
if (index != 0) return {};
return {QSize(800, 1200), QSize(800, 1200), QSize(800, 1200)};
}
RenderingMode preferredRenderingMode() const override { return RenderingMode::Manga; }
QList<TocEntry> tableOfContents() override { return {}; }
QString title() override { return QStringLiteral("Manga Title"); }
QString author() override { return QStringLiteral("Manga Author"); }
QString filePath() override { return QStringLiteral("/fake/manga.cbz"); }
QString coverImagePath() override { return QStringLiteral("0.jpg"); }
QByteArray contentHash() override { return QByteArray("mangahash"); }
bool loadMetadata(const QString &) override { return true; }
QString fileType() const override { return QStringLiteral("cbz"); }
};
class ReadingModelTest : public QObject {
Q_OBJECT
@@ -78,7 +110,9 @@ private slots:
QCOMPARE(model.totalChapters(), 0);
QCOMPARE(model.progress(), 0.0);
QVERIFY(model.chapterTitle().isEmpty());
QCOMPARE(model.rowCount(QModelIndex()), 0);
QCOMPARE(model.currentPage(), 0);
QCOMPARE(model.totalPages(), 0);
QVERIFY(!model.isMangaMode());
}
void setReaderLoadsAllChapters()
@@ -87,46 +121,11 @@ private slots:
FakeReader reader;
model.setReader(&reader);
// All 3 chapters × 2 chunks = 6 total rows
QCOMPARE(model.rowCount(QModelIndex()), 6);
QCOMPARE(model.totalChapters(), 3);
QCOMPARE(model.currentChapter(), 0);
QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 0"));
}
void chunkContentAcrossChapters()
{
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
// Chapter 0: chunks 0,1
QCOMPARE(model.data(model.index(0, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk A of 0</p>"));
QCOMPARE(model.data(model.index(1, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk B of 0</p>"));
// Chapter 1: chunks 2,3
QCOMPARE(model.data(model.index(2, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk A of 1</p>"));
QCOMPARE(model.data(model.index(3, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk B of 1</p>"));
// Chapter 2: chunks 4,5
QCOMPARE(model.data(model.index(4, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk A of 2</p>"));
QCOMPARE(model.data(model.index(5, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk B of 2</p>"));
}
void dataInvalidForOutOfRange()
{
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
QModelIndex badIdx = model.index(99, 0);
QVERIFY(!model.data(badIdx, ReadingModel::ContentRole).isValid());
}
void currentChapterDerivedFromScroll()
{
Ctx ctx; ReadingModel model(*ctx.store);
@@ -259,39 +258,6 @@ private slots:
QCOMPARE(model.totalChapters(), 0);
QCOMPARE(model.progress(), 0.0);
QVERIFY(model.chapterTitle().isEmpty());
QCOMPARE(model.rowCount(QModelIndex()), 0);
}
void roleNamesContainsContent()
{
Ctx ctx; ReadingModel model(*ctx.store);
QHash<int, QByteArray> roles = model.roleNames();
QVERIFY(roles.contains(ReadingModel::ContentRole));
QCOMPARE(roles.value(ReadingModel::ContentRole), QByteArray("content"));
}
void initialPageState()
{
Ctx ctx; ReadingModel model(*ctx.store);
QCOMPARE(model.currentPage(), 0);
QCOMPARE(model.totalPages(), 0);
}
void setScrollInfoUpdatesCurrentPage()
{
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
model.setScrollInfo(0, 0.0);
// If m_totalPixelHeight is 0, yOffset=0, yOffset/totalHeight is NaN.
// qBound(0, NaN, 1) is 0. 0 * 6 * 1.5 = 0.
QCOMPARE(model.currentPage(), 0);
model.setScrollInfo(3, 100.0);
// If m_totalPixelHeight is 0, yOffset=100, yOffset/totalHeight is Infinity.
// qBound(0, Inf, 1) is 1.0. 1.0 * 6 * 1.5 = 9.
QCOMPARE(model.currentPage(), 9);
}
void hasChaptersFalseForSingleChapter()
@@ -318,117 +284,37 @@ private slots:
QVERIFY(!model.hasChapters());
}
// --- Cover image tests ---
void coverImagePrependedToChunks()
void mangaModeDetectionAndPagination()
{
FakeReader reader;
Ctx ctx; ReadingModel model(*ctx.store);
model.setCoverImageUrl("image://epub/OEBPS/cover.jpg");
FakeMangaReader reader;
QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady);
model.setReader(&reader);
// Should have cover image chunk + original chunks
QCOMPARE(model.rowCount(QModelIndex()), 7); // 1 cover + 6 original
QVERIFY(model.isMangaMode());
QCOMPARE(model.imageUrlForChunk(0), QStringLiteral("image://cbz/0.jpg"));
QCOMPARE(model.imageUrlForChunk(1), QStringLiteral("image://cbz/1.jpg"));
QCOMPARE(model.imageUrlForChunk(2), QStringLiteral("image://cbz/2.jpg"));
QCOMPARE(model.totalPagePairs(), 3); // portrait mode: each chunk is solo
// First chunk should contain cover image HTML
QString firstChunk = model.data(model.index(0, 0), ReadingModel::ContentRole).toString();
QVERIFY(firstChunk.contains("class=\"cover-image\""));
QVERIFY(firstChunk.contains("image://epub/OEBPS/cover.jpg"));
}
// restoreReady should be queued and emitted
QTRY_COMPARE(restoreSpy.count(), 1);
QCOMPARE(restoreSpy.first().at(0).toInt(), 0);
void coverImageNotAddedWhenUrlEmpty()
{
FakeReader reader;
Ctx ctx; ReadingModel model(*ctx.store);
model.setReader(&reader);
model.setCoverImageUrl("");
// Should have only original chunks (no cover)
QCOMPARE(model.rowCount(QModelIndex()), 6);
}
void chapterNavigationSkipsCoverImage()
{
FakeReader reader;
Ctx ctx; ReadingModel model(*ctx.store);
model.setCoverImageUrl("image://epub/OEBPS/cover.jpg");
model.setReader(&reader);
// Chapter 0 should start at chunk 1 (after cover image)
QSignalSpy spy(&model, &ReadingModel::scrollToChunkRequested);
model.goToChapter(0);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.takeFirst().at(0).toInt(), 1); // Should scroll to chunk 1 (after cover)
// Navigate to chapter 2 (last chapter in FakeReader)
model.goToChapter(2);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.takeFirst().at(0).toInt(), 5); // Should scroll to chunk 5 (chapter 2 start)
}
void coverImageSetAfterReaderReloadsChunks()
{
FakeReader reader;
Ctx ctx; ReadingModel model(*ctx.store);
model.setReader(&reader);
QCOMPARE(model.rowCount(QModelIndex()), 6); // no cover yet
model.setCoverImageUrl(QStringLiteral("image://epub/OEBPS/cover.jpg"));
// setCoverImageUrl doesn't call loadAllChapters(), it only sets the URL.
// The URL is used when loadAllChapters() is called (via setReader).
// If we want to update it, we might need to re-set the reader or call a reload.
// Looking at ReadingModel.cpp, setCoverImageUrl ONLY sets the member.
model.setReader(&reader); // Re-set to reload with cover
QCOMPARE(model.rowCount(QModelIndex()), 7); // 1 cover + 6
QString first = model.data(model.index(0, 0), ReadingModel::ContentRole).toString();
QVERIFY(first.contains(QStringLiteral("class=\"cover-image\"")));
QVERIFY(first.contains(QStringLiteral("image://epub/OEBPS/cover.jpg")));
}
void clearCoverImageUrlRemovesCover()
{
FakeReader reader;
Ctx ctx; ReadingModel model(*ctx.store);
model.setCoverImageUrl(QStringLiteral("image://epub/OEBPS/cover.jpg"));
model.setReader(&reader);
QCOMPARE(model.rowCount(QModelIndex()), 7); // 1 cover + 6
model.setCoverImageUrl(QStringLiteral(""));
model.setReader(&reader); // Re-set to reload without cover
QCOMPARE(model.rowCount(QModelIndex()), 6); // cover removed
QString first = model.data(model.index(0, 0), ReadingModel::ContentRole).toString();
QVERIFY(!first.contains(QStringLiteral("class=\"cover-image\"")));
}
void roleNamesHasNewRoles()
{
Ctx ctx; ReadingModel model(*ctx.store);
auto roles = model.roleNames();
QVERIFY(roles.contains(ReadingModel::PixelHeightRole));
QVERIFY(roles.contains(ReadingModel::ChapterRole));
QCOMPARE(roles.value(ReadingModel::PixelHeightRole), QByteArray("pixelHeight"));
QCOMPARE(roles.value(ReadingModel::ChapterRole), QByteArray("chapter"));
}
void totalPixelHeightInitiallyZero()
{
Ctx ctx; ReadingModel model(*ctx.store);
QCOMPARE(model.totalPixelHeight(), 0.0);
}
void totalPixelHeightResetOnReaderSet()
{
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
QSignalSpy spy(&model, &ReadingModel::totalPixelHeightChanged);
model.setReader(&reader);
// loadAllChapters resets m_totalPixelHeight to 0 and emits the signal
QVERIFY(spy.count() >= 1);
QCOMPARE(model.totalPixelHeight(), 0.0); // unmeasured chunks have pixelHeight -1, not yet summed
// Landscape mode pairs portrait pages
model.setMangaLandscape(true);
// With pageShift ON (default): chunk 0 solo (cover), chunk 1 solo (shift), chunk 2 solo -> 3 pairs
// If pageShift OFF: chunk 0 solo (cover), chunks 1 and 2 paired -> 2 pairs
model.setPageShift(false);
QCOMPARE(model.totalPagePairs(), 2);
QVariantList pair0 = model.pagePair(0);
QCOMPARE(pair0.size(), 1);
QCOMPARE(pair0.at(0).toInt(), 0);
QVariantList pair1 = model.pagePair(1);
QCOMPARE(pair1.size(), 2);
QCOMPARE(pair1.at(0).toInt(), 1);
QCOMPARE(pair1.at(1).toInt(), 2);
}
};
+3 -13
View File
@@ -207,24 +207,14 @@ private slots:
ctx.book->openFromPath(path);
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000);
ctx.book->saveCurrentPosition(3, 17);
ctx.book->saveCurrentPosition(3, false, true);
const QByteArray hash = ctx.book->reader()->contentHash();
QVERIFY(!hash.isEmpty());
const BookPosition pos = ctx.store->load(hash);
QCOMPARE(pos.chunkIndex, 3);
QCOMPARE(pos.intraOffset, 17);
}
void contentWidthSignal()
{
Ctx ctx;
QSignalSpy spy(ctx.book, &Book::contentWidthChanged);
ctx.book->setContentWidth(800);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.first().first().toInt(), 800);
ctx.book->setContentWidth(800); // no-op
QCOMPARE(spy.count(), 1);
QCOMPARE(pos.mangaRTL, false);
QCOMPARE(pos.pageShift, true);
}
};
+14 -12
View File
@@ -22,7 +22,8 @@ private slots:
const BookPosition pos = store.load(QByteArray("nonexistent"));
QCOMPARE(pos.chunkIndex, 0);
QCOMPARE(pos.intraOffset, 0);
QCOMPARE(pos.pageShift, true);
QCOMPARE(pos.mangaRTL, true);
}
void saveAndLoad()
@@ -35,10 +36,11 @@ private slots:
BookPositionStore store(appState);
const QByteArray hash = QByteArray("abc123deadbeef");
store.save(hash, 7, 42);
store.save(hash, 7, false, false);
const BookPosition pos = store.load(hash);
QCOMPARE(pos.chunkIndex, 7);
QCOMPARE(pos.intraOffset, 42);
QCOMPARE(pos.mangaRTL, false);
QCOMPARE(pos.pageShift, false);
}
void separateHashesStoredIndependently()
@@ -50,13 +52,13 @@ private slots:
AppState appState(s);
BookPositionStore store(appState);
store.save(QByteArray("hash1"), 1, 10);
store.save(QByteArray("hash2"), 2, 20);
store.save(QByteArray("hash1"), 1, true, false);
store.save(QByteArray("hash2"), 2, false, true);
QCOMPARE(store.load(QByteArray("hash1")).chunkIndex, 1);
QCOMPARE(store.load(QByteArray("hash2")).chunkIndex, 2);
QCOMPARE(store.load(QByteArray("hash1")).intraOffset, 10);
QCOMPARE(store.load(QByteArray("hash2")).intraOffset, 20);
QCOMPARE(store.load(QByteArray("hash1")).mangaRTL, true);
QCOMPARE(store.load(QByteArray("hash2")).mangaRTL, false);
}
void overwriteExistingPosition()
@@ -69,12 +71,13 @@ private slots:
BookPositionStore store(appState);
const QByteArray hash = QByteArray("overwrite-hash");
store.save(hash, 3, 30);
store.save(hash, 5, 55);
store.save(hash, 3, true, true);
store.save(hash, 5, false, false);
const BookPosition pos = store.load(hash);
QCOMPARE(pos.chunkIndex, 5);
QCOMPARE(pos.intraOffset, 55);
QCOMPARE(pos.mangaRTL, false);
QCOMPARE(pos.pageShift, false);
}
void emptyHashIgnored()
@@ -87,10 +90,9 @@ private slots:
BookPositionStore store(appState);
// Neither save nor load should crash with an empty hash
store.save(QByteArray(), 1, 1);
store.save(QByteArray(), 1, true, true);
const BookPosition pos = store.load(QByteArray());
QCOMPARE(pos.chunkIndex, 0);
QCOMPARE(pos.intraOffset, 0);
}
};