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
+166 -1366

No files matched your search

-16
View File
@@ -59,8 +59,6 @@ set(SOURCES
src/backend/ReadingModel.cpp src/backend/ReadingModel.cpp
src/backend/reading/MangaPagination.h src/backend/reading/MangaPagination.h
src/backend/reading/MangaPagination.cpp src/backend/reading/MangaPagination.cpp
src/backend/reading/MeasurementController.h
src/backend/reading/MeasurementController.cpp
src/backend/state/ReadingPreferences.h src/backend/state/ReadingPreferences.h
src/backend/state/ReadingPreferences.cpp src/backend/state/ReadingPreferences.cpp
src/backend/state/UiState.h src/backend/state/UiState.h
@@ -70,10 +68,7 @@ set(SOURCES
src/backend/book/Book.h src/backend/book/Book.h
src/backend/book/Book.cpp src/backend/book/Book.cpp
src/backend/IImageProvider.h src/backend/IImageProvider.h
src/backend/IImageLoader.h
src/backend/ZipUtils.h src/backend/ZipUtils.h
src/backend/ChunkMeasurer.h
src/backend/ChunkMeasurer.cpp
src/backend/IFileDialogService.h src/backend/IFileDialogService.h
src/backend/NativeFileDialogService.h src/backend/NativeFileDialogService.h
src/backend/NativeFileDialogService.cpp 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) 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/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/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/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/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) 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/ThemeManager.qml
src/qml/components/Header.qml src/qml/components/Header.qml
src/qml/components/SideBar.qml src/qml/components/SideBar.qml
src/qml/components/PageView.qml
src/qml/components/ScrollPageView.qml
src/qml/components/MangaPageView.qml src/qml/components/MangaPageView.qml
src/qml/components/Footer.qml src/qml/components/Footer.qml
src/qml/components/ErrorPopup.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) 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") 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 add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp
src/backend/ReadingModel.cpp src/backend/ReadingModel.cpp
src/backend/reading/MangaPagination.cpp src/backend/reading/MangaPagination.cpp
src/backend/reading/MeasurementController.cpp
src/backend/ChunkMeasurer.cpp
src/backend/formats/AsyncImageResponse.cpp src/backend/formats/AsyncImageResponse.cpp
src/backend/formats/sources/Fb2ByteSource.cpp src/backend/formats/sources/Fb2ByteSource.cpp
src/backend/formats/WebImageProvider.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. 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_formatRegistry(formatRegistry)
, m_engine(engine) , 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::willOpenNewBook, this, &AppCoordinator::onWillOpenNewBook);
connect(&m_book, &Book::positionSaved, this, &AppCoordinator::onPositionSaved); connect(&m_book, &Book::positionSaved, this, &AppCoordinator::onPositionSaved);
connect(&m_book, &Book::bookChanged, this, &AppCoordinator::onBookChanged); connect(&m_book, &Book::bookChanged, this, &AppCoordinator::onBookChanged);
connect(&m_book, &Book::contentWidthChanged, this, &AppCoordinator::onContentWidthChanged);
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit,
this, &AppCoordinator::onAboutToQuit); 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. // 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() void AppCoordinator::onWillOpenNewBook()
{ {
if (m_book.hasBook()) if (m_book.hasBook())
m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress()); 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() void AppCoordinator::onPositionSaved()
{ {
m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress()); m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress());
@@ -87,34 +73,18 @@ void AppCoordinator::onBookChanged()
m_engine.removeImageProvider(provider->scheme()); m_engine.removeImageProvider(provider->scheme());
m_engine.addImageProvider(provider->scheme(), provider); m_engine.addImageProvider(provider->scheme(), provider);
provider->setFilePath(filePath); provider->setFilePath(filePath);
provider->setDisplayWidth(m_contentWidth);
m_currentImageProvider = provider; m_currentImageProvider = provider;
if (!reader->coverImagePath().isEmpty()) if (!reader->coverImagePath().isEmpty())
m_book.setCoverImageUrl(provider->coverImageUrl(reader->coverImagePath())); 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.setReader(reader);
m_readingModel.measure(true);
m_uiState.setLastFilePath(filePath); m_uiState.setLastFilePath(filePath);
m_historyModel.addOrUpdateBook(filePath, -1.0); 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. // Quit: flush everything to persistent storage.
// Scroll position was last saved by PageView's scroll tracker; we save library progress here. // Scroll position was last saved by PageView's scroll tracker; we save library progress here.
void AppCoordinator::onAboutToQuit() void AppCoordinator::onAboutToQuit()
-3
View File
@@ -35,8 +35,6 @@ private slots:
void onBookChanged(); void onBookChanged();
void onWillOpenNewBook(); void onWillOpenNewBook();
void onPositionSaved(); void onPositionSaved();
void onContentWidthChanged(int width);
void onFontPrefsChanged();
void onAboutToQuit(); void onAboutToQuit();
private: private:
@@ -51,5 +49,4 @@ private:
QQmlApplicationEngine &m_engine; QQmlApplicationEngine &m_engine;
IImageProvider *m_currentImageProvider = nullptr; 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: public:
virtual ~IImageProvider() = default; virtual ~IImageProvider() = default;
virtual void setFilePath(const QString &filePath) = 0; virtual void setFilePath(const QString &filePath) = 0;
virtual void setDisplayWidth(int width) = 0;
virtual void clear() = 0; virtual void clear() = 0;
// Returns the full QML image URL for a given internal path (e.g., "image://epub/OEBPS/cover.jpg") // 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; virtual QString coverImageUrl(const QString &coverPath) const = 0;
+29 -145
View File
@@ -2,47 +2,15 @@
#include "FormatReader.h" #include "FormatReader.h"
#include <QRegularExpression> #include <QRegularExpression>
#include <algorithm> #include <algorithm>
#include <cmath>
ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent) ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent)
: QAbstractListModel(parent) : QObject(parent)
, m_positions(positions) , m_positions(positions)
{ {
connect(&m_measurer, &MeasurementController::measuringChanged,
this, &ReadingModel::measuringChanged);
connect(&m_measurer, &MeasurementController::heightsReady,
this, &ReadingModel::onHeightsReady);
} }
ReadingModel::~ReadingModel() = default; 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 QString ReadingModel::chapterTitle() const
{ {
if (m_currentChapter < 0 || m_currentChapter >= m_chapterTitles.size()) 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::currentChapter() const { return m_currentChapter; }
int ReadingModel::totalChapters() const { return m_totalChapters; } int ReadingModel::totalChapters() const { return m_totalChapters; }
bool ReadingModel::hasChapters() const { return m_totalChapters > 1; } 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(); } int ReadingModel::totalPagePairs() const { return m_pagination.count(); }
bool ReadingModel::isMangaMode() const { return m_isMangaMode; } bool ReadingModel::isMangaMode() const { return m_isMangaMode; }
bool ReadingModel::pageShift() const { return m_pageShift; } bool ReadingModel::pageShift() const { return m_pageShift; }
@@ -79,89 +45,13 @@ void ReadingModel::setScrollInfo(const int topChunkIndex, const qreal proportion
emit chapterChanged(); emit chapterChanged();
} }
recalculateCurrentPage();
}
void ReadingModel::measure(const bool isNew)
{
if (!m_reader) return;
if (m_isMangaMode) { if (m_isMangaMode) {
// No measurement needed — images are sized by the view to fit the viewport. const int page = pairIndexForChunk(topChunkIndex) + 1;
// Queue the emission so QML's Loader has time to create MangaPageView before if (m_currentPage != page) {
// restoreReady arrives (in scroll mode the async measurement provides this gap). m_currentPage = page;
QMetaObject::invokeMethod(this, [this, isNew] { emit currentPageChanged();
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;
m_currentPage = page;
emit currentPageChanged();
} }
void ReadingModel::rebuildPagePairs() void ReadingModel::rebuildPagePairs()
@@ -242,7 +132,7 @@ void ReadingModel::setPageShift(bool shift, int currentPairIndex)
// Persist immediately. // Persist immediately.
if (m_reader) 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(); emit pageShiftChanged();
// Tell MangaPageView the exact pair to jump to so it re-evaluates its display binding. // 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; if (m_mangaRTL == rtl) return;
m_mangaRTL = rtl; m_mangaRTL = rtl;
if (m_reader) if (m_reader) {
m_positions.save(m_reader->contentHash(), 0, 0, m_mangaRTL, m_pageShift); 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(); emit mangaRTLChanged();
} }
@@ -268,29 +160,16 @@ static QString extractImageUrl(const QString &html)
void ReadingModel::loadAllChapters() void ReadingModel::loadAllChapters()
{ {
beginResetModel();
m_chunks.clear(); m_chunks.clear();
m_chapterStartIndices.clear(); m_chapterStartIndices.clear();
m_chapterTitles.clear(); m_chapterTitles.clear();
m_totalPixelHeight = 0.0;
emit totalPixelHeightChanged();
m_currentChapter = 0; m_currentChapter = 0;
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(); }
if (m_reader) { if (m_reader) {
// In manga mode the format's first chunk is already the cover — no extra cover injection. m_chapterStartIndices.append(0);
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) { for (int i = 0; i < m_totalChapters; ++i) {
auto chapter = m_reader->loadChapter(i); auto chapter = m_reader->loadChapter(i);
const QVector<QSize> sizes = m_reader->chapterPageSizes(i); const QVector<QSize> sizes = m_reader->chapterPageSizes(i);
@@ -300,18 +179,17 @@ void ReadingModel::loadAllChapters()
int j = 0; int j = 0;
for (const auto &html : chapter.contentChunks) { for (const auto &html : chapter.contentChunks) {
const QSize sz = (j < sizes.size()) ? sizes[j] : QSize(); 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; ++j;
} }
} }
} }
endResetModel();
if (m_isMangaMode) { if (m_isMangaMode) {
rebuildPagePairs(); rebuildPagePairs();
} else { } else {
if (const int pages = m_chunks.size() * page_ratio; m_totalPages != pages) { if (m_totalPages != m_chunks.size()) {
m_totalPages = pages; m_totalPages = m_chunks.size();
emit totalPagesChanged(); emit totalPagesChanged();
} }
if (const int page = m_chunks.isEmpty() ? 0 : 1; m_currentPage != page) { if (const int page = m_chunks.isEmpty() ? 0 : 1; m_currentPage != page) {
@@ -333,10 +211,17 @@ void ReadingModel::setReader(FormatReader *reader)
emit isMangaModeChanged(); emit isMangaModeChanged();
// Load per-book pageShift and mangaRTL before loadAllChapters so rebuildPagePairs uses the saved values. // 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()); const auto pos = m_positions.load(reader->contentHash());
m_pageShift = pos.pageShift; restoreChunk = pos.chunkIndex;
m_mangaRTL = pos.mangaRTL; if (m_isMangaMode) {
m_pageShift = pos.pageShift;
m_mangaRTL = pos.mangaRTL;
} else {
m_pageShift = true;
m_mangaRTL = true;
}
} else { } else {
m_pageShift = true; m_pageShift = true;
m_mangaRTL = true; m_mangaRTL = true;
@@ -346,12 +231,11 @@ void ReadingModel::setReader(FormatReader *reader)
emit totalChaptersChanged(); emit totalChaptersChanged();
emit chapterChanged(); emit chapterChanged();
}
void ReadingModel::setCoverImageUrl(const QString &coverImageUrl) if (m_reader) {
{ QMetaObject::invokeMethod(this, [this, restoreChunk] {
if (m_coverImageUrl != coverImageUrl) { emit restoreReady(restoreChunk);
m_coverImageUrl = coverImageUrl; }, Qt::QueuedConnection);
} }
} }
+8 -54
View File
@@ -1,28 +1,23 @@
#ifndef READINGMODEL_H #ifndef READINGMODEL_H
#define READINGMODEL_H #define READINGMODEL_H
#include <QAbstractListModel> #include <QObject>
#include <QSize> #include <QSize>
#include <QString> #include <QString>
#include <QVariantList>
#include <QVector> #include <QVector>
#include <memory>
#include "IImageLoader.h"
#include "reading/MangaPagination.h" #include "reading/MangaPagination.h"
#include "reading/MeasurementController.h"
#include "state/BookPositionStore.h" #include "state/BookPositionStore.h"
class FormatReader; class FormatReader;
struct ContentChunk { struct ContentChunk {
QString html; // empty when unloaded (lazy streaming) int chapterIndex = 0;
int chapterIndex = 0; // which chapter owns this chunk QSize naturalSize;
int chunkInChapter = 0; // 0-based index within chapter (-1 for cover) QString imageUrl;
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)
}; };
class ReadingModel : public QAbstractListModel { class ReadingModel : public QObject {
Q_OBJECT Q_OBJECT
Q_PROPERTY(QString chapterTitle READ chapterTitle NOTIFY chapterChanged) Q_PROPERTY(QString chapterTitle READ chapterTitle NOTIFY chapterChanged)
Q_PROPERTY(int currentChapter READ currentChapter 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 currentPage READ currentPage NOTIFY currentPageChanged)
Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged) Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged)
Q_PROPERTY(bool hasChapters READ hasChapters NOTIFY totalChaptersChanged) 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(int totalPagePairs READ totalPagePairs NOTIFY totalPagePairsChanged)
Q_PROPERTY(bool isMangaMode READ isMangaMode NOTIFY isMangaModeChanged) Q_PROPERTY(bool isMangaMode READ isMangaMode NOTIFY isMangaModeChanged)
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)
public: 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); explicit ReadingModel(BookPositionStore &positions, QObject *parent = nullptr);
~ReadingModel() override; ~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; QString chapterTitle() const;
int currentChapter() const; int currentChapter() const;
int totalChapters() const; int totalChapters() const;
@@ -60,17 +42,14 @@ public:
int currentPage() const; int currentPage() const;
int totalPages() const; int totalPages() const;
bool hasChapters() const; bool hasChapters() const;
bool measuring() const;
qreal totalPixelHeight() const;
int totalPagePairs() const; int totalPagePairs() const;
bool isMangaMode() const; bool isMangaMode() const;
bool pageShift() const; bool pageShift() const;
bool mangaRTL() const; bool mangaRTL() const;
void setReader(FormatReader *reader); 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 setScrollInfo(int topChunkIndex, qreal proportion);
Q_INVOKABLE void nextChapter(); Q_INVOKABLE void nextChapter();
@@ -90,19 +69,9 @@ public:
Q_INVOKABLE void setPageShift(bool shift, int currentPairIndex = 0); Q_INVOKABLE void setPageShift(bool shift, int currentPairIndex = 0);
Q_INVOKABLE void setMangaRTL(bool rtl); 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: signals:
void chapterChanged(); void chapterChanged();
void totalChaptersChanged(); void totalChaptersChanged();
void measuringChanged();
void totalPixelHeightChanged();
void currentPageChanged(); void currentPageChanged();
void totalPagesChanged(); void totalPagesChanged();
void totalPagePairsChanged(); void totalPagePairsChanged();
@@ -113,21 +82,13 @@ signals:
void pagePairsRebuilt(int newPairIndex); void pagePairsRebuilt(int newPairIndex);
void scrollToChunkRequested(int chunkIndex); void scrollToChunkRequested(int chunkIndex);
void restoreReady(int chunkIndex, int intraChunkOffset); void restoreReady(int chunkIndex);
private slots:
void onHeightsReady(const QVector<int> &heights, bool isNew);
private: private:
static constexpr qreal page_ratio = 1.5;
void loadAllChapters(); void loadAllChapters();
void recalculateCurrentPage();
void rebuildPagePairs(); void rebuildPagePairs();
void emitRestoreReady(bool isNew);
FormatReader *m_reader = nullptr; FormatReader *m_reader = nullptr;
QString m_coverImageUrl;
int m_currentChapter = 0; int m_currentChapter = 0;
int m_totalChapters = 0; int m_totalChapters = 0;
int m_currentPage = 0; int m_currentPage = 0;
@@ -141,17 +102,10 @@ private:
QVector<int> m_chapterStartIndices; QVector<int> m_chapterStartIndices;
QVector<QString> m_chapterTitles; QVector<QString> m_chapterTitles;
// Manga page-pair layout. In RTL mode the "left" slot is the later page visually.
MangaPagination m_pagination; MangaPagination m_pagination;
qreal m_totalPixelHeight = 0.0;
qreal m_yOffset = 0.0; qreal m_yOffset = 0.0;
int m_contentWidth = 0;
int m_fontSize = 0;
qreal m_lineSpacing = 0;
BookPositionStore &m_positions; BookPositionStore &m_positions;
MeasurementController m_measurer;
}; };
#endif // READINGMODEL_H #endif // READINGMODEL_H
+2 -9
View File
@@ -143,16 +143,9 @@ void Book::clearError()
emit errorMessageChanged(); emit errorMessageChanged();
} }
void Book::saveCurrentPosition(int chunkIndex, int intraOffset, bool pageShift) void Book::saveCurrentPosition(int chunkIndex, bool mangaRTL, bool pageShift)
{ {
if (!m_reader) return; if (!m_reader) return;
m_positions.save(m_reader->contentHash(), chunkIndex, intraOffset, pageShift); m_positions.save(m_reader->contentHash(), chunkIndex, mangaRTL, pageShift);
emit positionSaved(); 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 close();
Q_INVOKABLE void clearError(); Q_INVOKABLE void clearError();
// Save current scroll position. Called from QML's scroll tracker; forwards to BookPositionStore. // Save current position. Called from QML; forwards to BookPositionStore.
Q_INVOKABLE void saveCurrentPosition(int chunkIndex, int intraOffset, bool pageShift = false); Q_INVOKABLE void saveCurrentPosition(int chunkIndex, bool mangaRTL = true, bool pageShift = true);
// 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);
signals: signals:
// Emitted just before replacing the current reader with a new one. // Emitted just before replacing the current reader with a new one.
@@ -67,7 +63,6 @@ signals:
void bookChanged(); void bookChanged();
void loadingChanged(); void loadingChanged();
void errorMessageChanged(); void errorMessageChanged();
void contentWidthChanged(int width);
private: private:
void openImpl(const QString &filePath); void openImpl(const QString &filePath);
@@ -80,7 +75,6 @@ private:
QString m_errorMessage; QString m_errorMessage;
bool m_loading = false; bool m_loading = false;
int m_openGeneration = 0; int m_openGeneration = 0;
int m_contentWidth = 0;
QFuture<void> m_openFuture; QFuture<void> m_openFuture;
}; };
+4 -48
View File
@@ -11,7 +11,6 @@
QImage EntryImageProvider::loadImageFromSource(IByteSource &source, QImage EntryImageProvider::loadImageFromSource(IByteSource &source,
const QString &entryName, const QString &entryName,
int displayWidth,
const QSize &requestedSize) const QSize &requestedSize)
{ {
if (entryName.isEmpty()) if (entryName.isEmpty())
@@ -25,7 +24,7 @@ QImage EntryImageProvider::loadImageFromSource(IByteSource &source,
if (!image.loadFromData(data)) if (!image.loadFromData(data))
return {}; return {};
return scaleToFit(image, displayWidth, requestedSize); return scaleToFit(image, requestedSize);
} }
EntryImageProvider::EntryImageProvider(SourceFactory sourceFactory, QString scheme) EntryImageProvider::EntryImageProvider(SourceFactory sourceFactory, QString scheme)
@@ -38,11 +37,9 @@ QQuickImageResponse *EntryImageProvider::requestImageResponse(const QString &id,
const QSize &requestedSize) const QSize &requestedSize)
{ {
QString sourcePath; QString sourcePath;
int displayWidth;
{ {
QMutexLocker lock(&m_mutex); QMutexLocker lock(&m_mutex);
sourcePath = m_sourcePath; sourcePath = m_sourcePath;
displayWidth = m_displayWidth;
} }
// id may be "entry/name.jpg?src=<encoded-path>" // id may be "entry/name.jpg?src=<encoded-path>"
@@ -52,50 +49,16 @@ QQuickImageResponse *EntryImageProvider::requestImageResponse(const QString &id,
sourcePath = parsed.sourcePath; sourcePath = parsed.sourcePath;
auto *response = new AsyncImageResponse( auto *response = new AsyncImageResponse(
[factory = m_sourceFactory, sourcePath, entryName, displayWidth, requestedSize]() -> QImage { [factory = m_sourceFactory, sourcePath, entryName, requestedSize]() -> QImage {
auto source = factory(); auto source = factory();
if (!source->open(sourcePath)) if (!source->open(sourcePath))
return {}; return {};
return loadImageFromSource(*source, entryName, displayWidth, requestedSize); return loadImageFromSource(*source, entryName, requestedSize);
}); });
QThreadPool::globalInstance()->start(response); QThreadPool::globalInstance()->start(response);
return 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) void EntryImageProvider::setFilePath(const QString &filePath)
{ {
QMutexLocker lock(&m_mutex); QMutexLocker lock(&m_mutex);
@@ -114,15 +77,8 @@ QString EntryImageProvider::scheme() const
return m_scheme; return m_scheme;
} }
void EntryImageProvider::setDisplayWidth(int width)
{
QMutexLocker lock(&m_mutex);
m_displayWidth = width;
}
void EntryImageProvider::clear() void EntryImageProvider::clear()
{ {
QMutexLocker lock(&m_mutex); QMutexLocker lock(&m_mutex);
m_sourcePath.clear(); m_sourcePath.clear();
m_displayWidth = 0;
} }
+1 -8
View File
@@ -1,7 +1,6 @@
#pragma once #pragma once
#include "IByteSource.h" #include "IByteSource.h"
#include "backend/IImageLoader.h"
#include "backend/IImageProvider.h" #include "backend/IImageProvider.h"
#include <functional> #include <functional>
@@ -9,7 +8,7 @@
#include <QMutex> #include <QMutex>
#include <QString> #include <QString>
class EntryImageProvider : public IImageProvider, public IImageLoader { class EntryImageProvider : public IImageProvider {
public: public:
using SourceFactory = std::function<std::unique_ptr<IByteSource>()>; using SourceFactory = std::function<std::unique_ptr<IByteSource>()>;
@@ -19,17 +18,12 @@ public:
const QSize &requestedSize) override; const QSize &requestedSize) override;
void setFilePath(const QString &filePath) override; void setFilePath(const QString &filePath) override;
void setDisplayWidth(int width) override;
void clear() override; void clear() override;
QString coverImageUrl(const QString &coverPath) const override; QString coverImageUrl(const QString &coverPath) const override;
QString scheme() 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, static QImage loadImageFromSource(IByteSource &source,
const QString &entryName, const QString &entryName,
int displayWidth,
const QSize &requestedSize); const QSize &requestedSize);
private: private:
@@ -37,5 +31,4 @@ private:
QString m_scheme; QString m_scheme;
mutable QMutex m_mutex; mutable QMutex m_mutex;
QString m_sourcePath; QString m_sourcePath;
int m_displayWidth = 0;
}; };
-48
View File
@@ -7,36 +7,6 @@
#include <QFileInfo> #include <QFileInfo>
#include <QQmlEngine> #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) FormatRegistry::FormatRegistry(QVector<FormatSpec> specs)
: m_specs(std::move(specs)) : m_specs(std::move(specs))
{ {
@@ -69,24 +39,6 @@ IImageProvider *FormatRegistry::createImageProvider(const QString &filePath) con
return new EntryImageProvider(spec->makeSource, spec->scheme); 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 FormatRegistry::supportedExtensions() const
{ {
QStringList out; QStringList out;
-5
View File
@@ -8,7 +8,6 @@
class FormatReader; class FormatReader;
class IByteSource; class IByteSource;
class IImageLoader;
class IImageProvider; class IImageProvider;
class QQmlEngine; class QQmlEngine;
@@ -21,7 +20,6 @@ struct FormatSpec {
QString scheme; // image:// scheme; empty = format has no images QString scheme; // image:// scheme; empty = format has no images
std::function<std::unique_ptr<FormatReader>()> makeReader; std::function<std::unique_ptr<FormatReader>()> makeReader;
std::function<std::unique_ptr<IByteSource>()> makeSource; // required when scheme is set 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 { class FormatRegistry {
@@ -34,9 +32,6 @@ public:
// Caller owns the pointer (the QML engine takes ownership on registration). // Caller owns the pointer (the QML engine takes ownership on registration).
IImageProvider *createImageProvider(const QString &filePath) const; 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; QStringList supportedExtensions() const;
// Register one provider per scheme with the QML engine (engine takes ownership). // Register one provider per scheme with the QML engine (engine takes ownership).
+2 -9
View File
@@ -3,17 +3,13 @@
#include <QImage> #include <QImage>
#include <QSize> #include <QSize>
// Honor an explicit requested size (clamped to the display width), otherwise // Honor an explicit requested size, otherwise keep original image dimensions — never enlarge.
// scale down to fit the display width — never enlarge. inline QImage scaleToFit(QImage image, const QSize &requestedSize)
inline QImage scaleToFit(QImage image, int displayWidth, const QSize &requestedSize)
{ {
if (requestedSize.width() > 0 || requestedSize.height() > 0) { if (requestedSize.width() > 0 || requestedSize.height() > 0) {
int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1; int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1;
int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1; int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1;
if (displayWidth > 0 && targetW > 0 && targetW > displayWidth)
targetW = displayWidth;
if (targetW > 0 && targetH > 0) { if (targetW > 0 && targetH > 0) {
image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio, image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio,
Qt::SmoothTransformation); Qt::SmoothTransformation);
@@ -22,9 +18,6 @@ inline QImage scaleToFit(QImage image, int displayWidth, const QSize &requestedS
} else { } else {
image = image.scaledToHeight(targetH, Qt::SmoothTransformation); image = image.scaledToHeight(targetH, Qt::SmoothTransformation);
} }
} else {
if (displayWidth > 0 && image.width() > displayWidth)
image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation);
} }
return image; return image;
} }
+5 -49
View File
@@ -39,7 +39,7 @@ QString WebImageProvider::cacheFilePath(const QString &urlString)
// WebImageProvider // WebImageProvider
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
QImage WebImageProvider::loadWebImage(const QString &urlString, int displayWidth, QImage WebImageProvider::loadWebImage(const QString &urlString,
const QSize &requestedSize) const QSize &requestedSize)
{ {
if (urlString.isEmpty()) if (urlString.isEmpty())
@@ -50,7 +50,7 @@ QImage WebImageProvider::loadWebImage(const QString &urlString, int displayWidth
if (QFile::exists(cachePath)) { if (QFile::exists(cachePath)) {
QImage image; QImage image;
if (image.load(cachePath)) 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 // 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)) if (!image.loadFromData(data))
return {}; return {};
return scaleToFit(image, displayWidth, requestedSize); return scaleToFit(image, requestedSize);
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -109,13 +109,8 @@ QQuickImageResponse *WebImageProvider::requestImageResponse(const QString &id,
return response; return response;
} }
int displayWidth; auto *response = new AsyncImageResponse([id, requestedSize] {
{ return loadWebImage(id, requestedSize);
QMutexLocker lock(&m_mutex);
displayWidth = m_displayWidth;
}
auto *response = new AsyncImageResponse([id, displayWidth, requestedSize] {
return loadWebImage(id, displayWidth, requestedSize);
}); });
QThreadPool::globalInstance()->start(response); QThreadPool::globalInstance()->start(response);
return response; return response;
@@ -125,42 +120,3 @@ QString WebImageProvider::scheme() const
{ {
return QStringLiteral("web"); 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 #pragma once
#include <QMutex>
#include <QSize> #include <QSize>
#include <QString> #include <QString>
#include "backend/IImageLoader.h"
#include "backend/IImageProvider.h" #include "backend/IImageProvider.h"
class WebImageProvider : public IImageProvider, public IImageLoader { class WebImageProvider : public IImageProvider {
public: public:
QQuickImageResponse *requestImageResponse(const QString &id, QQuickImageResponse *requestImageResponse(const QString &id,
const QSize &requestedSize) override; const QSize &requestedSize) override;
void setFilePath(const QString &) override {} void setFilePath(const QString &) override {}
void setDisplayWidth(int width) override;
void clear() override {} void clear() override {}
QString coverImageUrl(const QString &) const override { return {}; } QString coverImageUrl(const QString &) const override { return {}; }
QString scheme() const override; 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. // 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); const QSize &requestedSize);
static QString cacheDir(); static QString cacheDir();
static QString cacheFilePath(const QString &urlString); 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)); const QVariantMap d = m_state.loadSection(sectionKey(contentMd5));
BookPosition pos; BookPosition pos;
pos.chunkIndex = d.value(QStringLiteral("chunkIndex"), 0).toInt(); 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.pageShift = d.value(QStringLiteral("pageShift"), true).toBool();
pos.mangaRTL = d.value(QStringLiteral("mangaRTL"), true).toBool(); pos.mangaRTL = d.value(QStringLiteral("mangaRTL"), true).toBool();
return pos; 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()) if (contentMd5.isEmpty())
return; return;
m_state.saveSection(sectionKey(contentMd5), { m_state.saveSection(sectionKey(contentMd5), {
{QStringLiteral("chunkIndex"), chunkIndex}, {QStringLiteral("chunkIndex"), chunkIndex},
{QStringLiteral("intraOffset"), intraOffset},
{QStringLiteral("pageShift"), pageShift}, {QStringLiteral("pageShift"), pageShift},
{QStringLiteral("mangaRTL"), mangaRTL}, {QStringLiteral("mangaRTL"), mangaRTL},
}); });
+1 -2
View File
@@ -6,7 +6,6 @@
struct BookPosition { struct BookPosition {
int chunkIndex = 0; int chunkIndex = 0;
int intraOffset = 0;
bool pageShift = true; // manga page-shift; default ON bool pageShift = true; // manga page-shift; default ON
bool mangaRTL = true; // manga reading direction; default RTL bool mangaRTL = true; // manga reading direction; default RTL
}; };
@@ -19,7 +18,7 @@ public:
BookPosition load(const QByteArray &contentMd5); BookPosition load(const QByteArray &contentMd5);
// Save the current position for a book identified by MD5 of its contents. // 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: private:
AppState &m_state; AppState &m_state;
+1 -2
View File
@@ -111,8 +111,7 @@ int main(int argc, char *argv[])
[] { return std::make_unique<TxtReader>(); }, nullptr}, [] { return std::make_unique<TxtReader>(); }, nullptr},
{QStringLiteral("epub"), false, QStringLiteral("epub"), {QStringLiteral("epub"), false, QStringLiteral("epub"),
[] { return std::make_unique<EpubReader>(); }, [] { return std::make_unique<EpubReader>(); },
[] { return std::make_unique<ZipByteSource>(); }, [] { return std::make_unique<ZipByteSource>(); }},
/*loaderIncludesWeb=*/true},
{QStringLiteral("fb2"), false, QStringLiteral("fb2"), {QStringLiteral("fb2"), false, QStringLiteral("fb2"),
[] { return std::make_unique<Fb2Reader>(); }, [] { return std::make_unique<Fb2Reader>(); },
[] { return std::make_unique<Fb2ByteSource>(); }}, [] { 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 { Timer {
id: geometrySaveTimer id: geometrySaveTimer
interval: 250 interval: 250
@@ -181,10 +174,8 @@ ApplicationWindow {
// Navigate once measurement (and position restoration) is done // Navigate once measurement (and position restoration) is done
Connections { Connections {
target: readingModel target: readingModel
function onRestoreReady(chunkIndex, intraOffset) { function onRestoreReady(chunkIndex) {
if (!book.hasBook) return 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 window._bookInitializing = false
if (window._startupRestore) { if (window._startupRestore) {
window._startupRestore = false window._startupRestore = false
@@ -218,24 +209,6 @@ ApplicationWindow {
context: Qt.ApplicationShortcut context: Qt.ApplicationShortcut
onActivated: window.visibility = (window.visibility === Window.FullScreen) ? Window.Windowed : Window.FullScreen 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 { Shortcut {
sequence: "Left" sequence: "Left"
context: Qt.ApplicationShortcut context: Qt.ApplicationShortcut
@@ -314,7 +287,7 @@ ApplicationWindow {
context: Qt.ApplicationShortcut context: Qt.ApplicationShortcut
onActivated: { onActivated: {
if (currentPage === "reader" && readingModel.isMangaMode) 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 triggeredOnStart: false
onTriggered: { onTriggered: {
window.opacity = 1 window.opacity = 1
readerPage.pageView.updateContentWidth()
if (uiState.lastFilePath !== "") { if (uiState.lastFilePath !== "") {
window._startupRestore = true window._startupRestore = true
book.openFromPath(uiState.lastFilePath) book.openFromPath(uiState.lastFilePath)
+1 -21
View File
@@ -13,25 +13,6 @@ Rectangle {
anchors.top: parent.top 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). // RTL reading direction toggle (manga mode only).
FlatIconButton { FlatIconButton {
anchors.left: parent.left anchors.left: parent.left
@@ -62,8 +43,7 @@ Rectangle {
: ThemeManager.currentTheme.dimText : ThemeManager.currentTheme.dimText
tooltip: "Page shift (S)" tooltip: "Page shift (S)"
onClicked: { onClicked: {
// currentPair lives on MangaPageView; reach it via the PageView router alias. const pairIdx = readerPage.pageView.currentPair
const pairIdx = readerPage.pageView.currentMangaPair
readingModel.setPageShift(!readingModel.pageShift, pairIdx) readingModel.setPageShift(!readingModel.pageShift, pairIdx)
} }
} }
+5 -9
View File
@@ -6,13 +6,7 @@ Rectangle {
id: root id: root
focus: true focus: true
// Keep the same public interface as ScrollPageView so PageView router delegates uniformly.
property bool contentReady: false property bool contentReady: false
property bool resizing: false
property bool restoreReady: false
property int initialIndex: -1
property int initialOffset: -1
property int currentPair: 0 property int currentPair: 0
readonly property bool landscape: width > height readonly property bool landscape: width > height
@@ -48,7 +42,7 @@ Rectangle {
const firstChunk = pair[0] const firstChunk = pair[0]
// Keep scroll model in sync so Footer page counter and chapter tracking work. // Keep scroll model in sync so Footer page counter and chapter tracking work.
readingModel.setScrollInfo(firstChunk, pairIndex / Math.max(1, readingModel.totalPagePairs - 1)) 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). // Notify model when orientation changes (triggers pair rebuild).
@@ -196,9 +190,11 @@ Rectangle {
// Restore position when a new book is loaded. // Restore position when a new book is loaded.
Connections { Connections {
target: readingModel target: readingModel
function onRestoreReady(chunkIndex, intraOffset) { function onRestoreReady(chunkIndex) {
contentReady = true contentReady = true
restoreReady = true showPair(readingModel.pairIndexForChunk(chunkIndex))
}
function onScrollToChunkRequested(chunkIndex) {
showPair(readingModel.pairIndexForChunk(chunkIndex)) showPair(readingModel.pairIndexForChunk(chunkIndex))
} }
function onTotalPagePairsChanged() { 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
}
}
}
+2 -2
View File
@@ -4,8 +4,8 @@ import Asteria
Item { Item {
id: readerPage id: readerPage
property alias pageView: internalPageView property alias pageView: internalPageView
PageView { MangaPageView {
id: internalPageView id: internalPageView
anchors.fill: parent anchors.fill: parent
focus: visible 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). // Load one zip member through the generic byte-source pipeline (EPUBs are zips).
static QImage loadFromEpub(const QString &epubPath, const QString &entry, static QImage loadFromEpub(const QString &epubPath, const QString &entry,
int displayWidth, const QSize &requestedSize) const QSize &requestedSize)
{ {
ZipByteSource source; ZipByteSource source;
if (!source.open(epubPath)) if (!source.open(epubPath))
return {}; return {};
return EntryImageProvider::loadImageFromSource(source, entry, displayWidth, return EntryImageProvider::loadImageFromSource(source, entry, requestedSize);
requestedSize);
} }
static EntryImageProvider makeEpubProvider() static EntryImageProvider makeEpubProvider()
@@ -96,7 +95,7 @@ private slots:
QVERIFY(!epubPath.isEmpty()); QVERIFY(!epubPath.isEmpty());
const QImage img = loadFromEpub( const QImage img = loadFromEpub(
epubPath, QStringLiteral("OEBPS/Images/test.png"), 0, QSize()); epubPath, QStringLiteral("OEBPS/Images/test.png"), QSize());
QFile::remove(epubPath); QFile::remove(epubPath);
@@ -112,7 +111,7 @@ private slots:
QVERIFY(!epubPath.isEmpty()); QVERIFY(!epubPath.isEmpty());
const QImage img = loadFromEpub( const QImage img = loadFromEpub(
epubPath, QStringLiteral("OEBPS/Images/nonexistent.png"), 0, QSize()); epubPath, QStringLiteral("OEBPS/Images/nonexistent.png"), QSize());
QFile::remove(epubPath); QFile::remove(epubPath);
@@ -122,7 +121,7 @@ private slots:
void requestImageReturnsNullWhenNoPath() void requestImageReturnsNullWhenNoPath()
{ {
const QImage img = loadFromEpub( const QImage img = loadFromEpub(
QString{}, QStringLiteral("OEBPS/Images/test.png"), 0, QSize()); QString{}, QStringLiteral("OEBPS/Images/test.png"), QSize());
QVERIFY(img.isNull()); QVERIFY(img.isNull());
} }
@@ -133,51 +132,20 @@ private slots:
// After clear the path is empty, so loadImageFromEpub with empty path returns null // After clear the path is empty, so loadImageFromEpub with empty path returns null
const QImage img = loadFromEpub( const QImage img = loadFromEpub(
QString{}, QStringLiteral("OEBPS/Images/test.png"), 0, QSize()); QString{}, QStringLiteral("OEBPS/Images/test.png"), QSize());
QFile::remove(epubPath); QFile::remove(epubPath);
QVERIFY(img.isNull()); 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() void requestedSizeHonored()
{ {
const QString epubPath = buildEpubWithPng("img.png", 400, 300); const QString epubPath = buildEpubWithPng("img.png", 400, 300);
QVERIFY(!epubPath.isEmpty()); QVERIFY(!epubPath.isEmpty());
const QImage img = loadFromEpub( const QImage img = loadFromEpub(
epubPath, QStringLiteral("img.png"), 600, QSize(200, -1)); epubPath, QStringLiteral("img.png"), QSize(200, -1));
QFile::remove(epubPath); QFile::remove(epubPath);
@@ -196,7 +164,7 @@ private slots:
AsyncImageResponse response([epubPath] { AsyncImageResponse response([epubPath] {
return loadFromEpub( return loadFromEpub(
epubPath, QStringLiteral("img.png"), 0, QSize()); epubPath, QStringLiteral("img.png"), QSize());
}); });
QSignalSpy spy(&response, &QQuickImageResponse::finished); QSignalSpy spy(&response, &QQuickImageResponse::finished);
response.run(); response.run();
@@ -214,7 +182,7 @@ private slots:
AsyncImageResponse response([epubPath] { AsyncImageResponse response([epubPath] {
return loadFromEpub( return loadFromEpub(
epubPath, QStringLiteral("img.png"), 0, QSize()); epubPath, QStringLiteral("img.png"), QSize());
}); });
QSignalSpy spy(&response, &QQuickImageResponse::finished); QSignalSpy spy(&response, &QQuickImageResponse::finished);
response.cancel(); response.cancel();
@@ -232,7 +200,7 @@ private slots:
AsyncImageResponse response([epubPath] { AsyncImageResponse response([epubPath] {
return loadFromEpub( return loadFromEpub(
epubPath, QStringLiteral("img.png"), 0, QSize()); epubPath, QStringLiteral("img.png"), QSize());
}); });
response.cancel(); response.cancel();
response.run(); response.run();
@@ -298,24 +266,6 @@ private slots:
delete resp; 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() void requestImageResponseFallsBackToProviderPath()
{ {
// Without a leading slash in id, the provider should use m_epubPath. // 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")}); QCOMPARE(source.listEntries(), QStringList{QStringLiteral("cover.png")});
const QImage img = EntryImageProvider::loadImageFromSource( const QImage img = EntryImageProvider::loadImageFromSource(
source, QStringLiteral("cover.png"), 0, QSize()); source, QStringLiteral("cover.png"), QSize());
QVERIFY(!source.contentHash().isEmpty()); QVERIFY(!source.contentHash().isEmpty());
QFile::remove(path); QFile::remove(path);
+2 -13
View File
@@ -3,7 +3,6 @@
#include "backend/formats/FormatRegistry.h" #include "backend/formats/FormatRegistry.h"
#include "backend/FormatReader.h" #include "backend/FormatReader.h"
#include "backend/IImageProvider.h" #include "backend/IImageProvider.h"
#include "backend/IImageLoader.h"
#include "backend/formats/TxtReader.h" #include "backend/formats/TxtReader.h"
#include "backend/formats/EpubReader.h" #include "backend/formats/EpubReader.h"
#include "backend/formats/comic/CbzReader.h" #include "backend/formats/comic/CbzReader.h"
@@ -20,8 +19,7 @@ static FormatRegistry makeRegistry()
[] { return std::make_unique<TxtReader>(); }, nullptr}, [] { return std::make_unique<TxtReader>(); }, nullptr},
{QStringLiteral("epub"), false, QStringLiteral("epub"), {QStringLiteral("epub"), false, QStringLiteral("epub"),
[] { return std::make_unique<EpubReader>(); }, [] { return std::make_unique<EpubReader>(); },
[] { return std::make_unique<ZipByteSource>(); }, [] { return std::make_unique<ZipByteSource>(); }},
/*loaderIncludesWeb=*/true},
{QStringLiteral("cbz"), false, QStringLiteral("cbz"), {QStringLiteral("cbz"), false, QStringLiteral("cbz"),
[] { return std::make_unique<CbzReader>(); }, [] { return std::make_unique<CbzReader>(); },
[] { return std::make_unique<ZipByteSource>(); }}, [] { return std::make_unique<ZipByteSource>(); }},
@@ -120,21 +118,12 @@ private slots:
QCOMPARE(dir->scheme(), QStringLiteral("dir")); QCOMPARE(dir->scheme(), QStringLiteral("dir"));
} }
void formatsWithoutImagesHaveNoProviderOrLoader() void formatsWithoutImagesHaveNoProvider()
{ {
auto registry = makeRegistry(); auto registry = makeRegistry();
QVERIFY(registry.createImageProvider("plain.txt") == nullptr); QVERIFY(registry.createImageProvider("plain.txt") == nullptr);
QVERIFY(registry.createImageLoader("plain.txt") == nullptr);
QVERIFY(registry.createImageProvider("file.xyz") == 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) QTEST_MAIN(FormatRegistryTest)
+1 -2
View File
@@ -22,8 +22,7 @@ static FormatRegistry makeRegistry()
[] { return std::make_unique<TxtReader>(); }, nullptr}, [] { return std::make_unique<TxtReader>(); }, nullptr},
{QStringLiteral("epub"), false, QStringLiteral("epub"), {QStringLiteral("epub"), false, QStringLiteral("epub"),
[] { return std::make_unique<EpubReader>(); }, [] { return std::make_unique<EpubReader>(); },
[] { return std::make_unique<ZipByteSource>(); }, [] { return std::make_unique<ZipByteSource>(); }},
/*loaderIncludesWeb=*/true},
}); });
} }
+59 -173
View File
@@ -51,6 +51,38 @@ public:
QString fileType() const override { return QStringLiteral("txt"); } 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 { class ReadingModelTest : public QObject {
Q_OBJECT Q_OBJECT
@@ -78,7 +110,9 @@ private slots:
QCOMPARE(model.totalChapters(), 0); QCOMPARE(model.totalChapters(), 0);
QCOMPARE(model.progress(), 0.0); QCOMPARE(model.progress(), 0.0);
QVERIFY(model.chapterTitle().isEmpty()); QVERIFY(model.chapterTitle().isEmpty());
QCOMPARE(model.rowCount(QModelIndex()), 0); QCOMPARE(model.currentPage(), 0);
QCOMPARE(model.totalPages(), 0);
QVERIFY(!model.isMangaMode());
} }
void setReaderLoadsAllChapters() void setReaderLoadsAllChapters()
@@ -87,46 +121,11 @@ private slots:
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
// All 3 chapters × 2 chunks = 6 total rows
QCOMPARE(model.rowCount(QModelIndex()), 6);
QCOMPARE(model.totalChapters(), 3); QCOMPARE(model.totalChapters(), 3);
QCOMPARE(model.currentChapter(), 0); QCOMPARE(model.currentChapter(), 0);
QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 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() void currentChapterDerivedFromScroll()
{ {
Ctx ctx; ReadingModel model(*ctx.store); Ctx ctx; ReadingModel model(*ctx.store);
@@ -259,39 +258,6 @@ private slots:
QCOMPARE(model.totalChapters(), 0); QCOMPARE(model.totalChapters(), 0);
QCOMPARE(model.progress(), 0.0); QCOMPARE(model.progress(), 0.0);
QVERIFY(model.chapterTitle().isEmpty()); 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() void hasChaptersFalseForSingleChapter()
@@ -318,117 +284,37 @@ private slots:
QVERIFY(!model.hasChapters()); QVERIFY(!model.hasChapters());
} }
// --- Cover image tests --- void mangaModeDetectionAndPagination()
void coverImagePrependedToChunks()
{ {
FakeReader reader;
Ctx ctx; ReadingModel model(*ctx.store); Ctx ctx; ReadingModel model(*ctx.store);
model.setCoverImageUrl("image://epub/OEBPS/cover.jpg"); FakeMangaReader reader;
model.setReader(&reader); QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady);
// Should have cover image chunk + original chunks
QCOMPARE(model.rowCount(QModelIndex()), 7); // 1 cover + 6 original
// 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"));
}
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); model.setReader(&reader);
// Chapter 0 should start at chunk 1 (after cover image) QVERIFY(model.isMangaMode());
QSignalSpy spy(&model, &ReadingModel::scrollToChunkRequested); QCOMPARE(model.imageUrlForChunk(0), QStringLiteral("image://cbz/0.jpg"));
model.goToChapter(0); QCOMPARE(model.imageUrlForChunk(1), QStringLiteral("image://cbz/1.jpg"));
QCOMPARE(spy.count(), 1); QCOMPARE(model.imageUrlForChunk(2), QStringLiteral("image://cbz/2.jpg"));
QCOMPARE(spy.takeFirst().at(0).toInt(), 1); // Should scroll to chunk 1 (after cover) QCOMPARE(model.totalPagePairs(), 3); // portrait mode: each chunk is solo
// Navigate to chapter 2 (last chapter in FakeReader) // restoreReady should be queued and emitted
model.goToChapter(2); QTRY_COMPARE(restoreSpy.count(), 1);
QCOMPARE(spy.count(), 1); QCOMPARE(restoreSpy.first().at(0).toInt(), 0);
QCOMPARE(spy.takeFirst().at(0).toInt(), 5); // Should scroll to chunk 5 (chapter 2 start)
}
void coverImageSetAfterReaderReloadsChunks() // Landscape mode pairs portrait pages
{ model.setMangaLandscape(true);
FakeReader reader; // With pageShift ON (default): chunk 0 solo (cover), chunk 1 solo (shift), chunk 2 solo -> 3 pairs
Ctx ctx; ReadingModel model(*ctx.store); // If pageShift OFF: chunk 0 solo (cover), chunks 1 and 2 paired -> 2 pairs
model.setReader(&reader); model.setPageShift(false);
QCOMPARE(model.rowCount(QModelIndex()), 6); // no cover yet QCOMPARE(model.totalPagePairs(), 2);
QVariantList pair0 = model.pagePair(0);
model.setCoverImageUrl(QStringLiteral("image://epub/OEBPS/cover.jpg")); QCOMPARE(pair0.size(), 1);
// setCoverImageUrl doesn't call loadAllChapters(), it only sets the URL. QCOMPARE(pair0.at(0).toInt(), 0);
// The URL is used when loadAllChapters() is called (via setReader). QVariantList pair1 = model.pagePair(1);
// If we want to update it, we might need to re-set the reader or call a reload. QCOMPARE(pair1.size(), 2);
// Looking at ReadingModel.cpp, setCoverImageUrl ONLY sets the member. QCOMPARE(pair1.at(0).toInt(), 1);
QCOMPARE(pair1.at(1).toInt(), 2);
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
} }
}; };
+3 -13
View File
@@ -207,24 +207,14 @@ private slots:
ctx.book->openFromPath(path); ctx.book->openFromPath(path);
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); 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(); const QByteArray hash = ctx.book->reader()->contentHash();
QVERIFY(!hash.isEmpty()); QVERIFY(!hash.isEmpty());
const BookPosition pos = ctx.store->load(hash); const BookPosition pos = ctx.store->load(hash);
QCOMPARE(pos.chunkIndex, 3); QCOMPARE(pos.chunkIndex, 3);
QCOMPARE(pos.intraOffset, 17); QCOMPARE(pos.mangaRTL, false);
} QCOMPARE(pos.pageShift, true);
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);
} }
}; };
+20 -18
View File
@@ -21,8 +21,9 @@ private slots:
BookPositionStore store(appState); BookPositionStore store(appState);
const BookPosition pos = store.load(QByteArray("nonexistent")); const BookPosition pos = store.load(QByteArray("nonexistent"));
QCOMPARE(pos.chunkIndex, 0); QCOMPARE(pos.chunkIndex, 0);
QCOMPARE(pos.intraOffset, 0); QCOMPARE(pos.pageShift, true);
QCOMPARE(pos.mangaRTL, true);
} }
void saveAndLoad() void saveAndLoad()
@@ -35,10 +36,11 @@ private slots:
BookPositionStore store(appState); BookPositionStore store(appState);
const QByteArray hash = QByteArray("abc123deadbeef"); const QByteArray hash = QByteArray("abc123deadbeef");
store.save(hash, 7, 42); store.save(hash, 7, false, false);
const BookPosition pos = store.load(hash); const BookPosition pos = store.load(hash);
QCOMPARE(pos.chunkIndex, 7); QCOMPARE(pos.chunkIndex, 7);
QCOMPARE(pos.intraOffset, 42); QCOMPARE(pos.mangaRTL, false);
QCOMPARE(pos.pageShift, false);
} }
void separateHashesStoredIndependently() void separateHashesStoredIndependently()
@@ -50,13 +52,13 @@ private slots:
AppState appState(s); AppState appState(s);
BookPositionStore store(appState); BookPositionStore store(appState);
store.save(QByteArray("hash1"), 1, 10); store.save(QByteArray("hash1"), 1, true, false);
store.save(QByteArray("hash2"), 2, 20); store.save(QByteArray("hash2"), 2, false, true);
QCOMPARE(store.load(QByteArray("hash1")).chunkIndex, 1); QCOMPARE(store.load(QByteArray("hash1")).chunkIndex, 1);
QCOMPARE(store.load(QByteArray("hash2")).chunkIndex, 2); QCOMPARE(store.load(QByteArray("hash2")).chunkIndex, 2);
QCOMPARE(store.load(QByteArray("hash1")).intraOffset, 10); QCOMPARE(store.load(QByteArray("hash1")).mangaRTL, true);
QCOMPARE(store.load(QByteArray("hash2")).intraOffset, 20); QCOMPARE(store.load(QByteArray("hash2")).mangaRTL, false);
} }
void overwriteExistingPosition() void overwriteExistingPosition()
@@ -69,12 +71,13 @@ private slots:
BookPositionStore store(appState); BookPositionStore store(appState);
const QByteArray hash = QByteArray("overwrite-hash"); const QByteArray hash = QByteArray("overwrite-hash");
store.save(hash, 3, 30); store.save(hash, 3, true, true);
store.save(hash, 5, 55); store.save(hash, 5, false, false);
const BookPosition pos = store.load(hash); const BookPosition pos = store.load(hash);
QCOMPARE(pos.chunkIndex, 5); QCOMPARE(pos.chunkIndex, 5);
QCOMPARE(pos.intraOffset, 55); QCOMPARE(pos.mangaRTL, false);
QCOMPARE(pos.pageShift, false);
} }
void emptyHashIgnored() void emptyHashIgnored()
@@ -87,10 +90,9 @@ private slots:
BookPositionStore store(appState); BookPositionStore store(appState);
// Neither save nor load should crash with an empty hash // 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()); const BookPosition pos = store.load(QByteArray());
QCOMPARE(pos.chunkIndex, 0); QCOMPARE(pos.chunkIndex, 0);
QCOMPARE(pos.intraOffset, 0);
} }
}; };