From acc7e71e7b810fc1f02ffe68990ada8d7642b6a8 Mon Sep 17 00:00:00 2001 From: Agel Date: Sun, 25 Oct 2026 14:22:12 +0100 Subject: [PATCH] old render cleanup part 1 --- CMakeLists.txt | 16 -- GEMINI.md | 2 +- src/backend/AppCoordinator.cpp | 32 +-- src/backend/AppCoordinator.h | 3 - src/backend/ChunkMeasurer.cpp | 96 -------- src/backend/ChunkMeasurer.h | 16 -- src/backend/IChunkMeasurer.h | 11 - src/backend/IImageLoader.h | 10 - src/backend/IImageProvider.h | 1 - src/backend/ReadingModel.cpp | 174 +++---------- src/backend/ReadingModel.h | 62 +---- src/backend/book/Book.cpp | 11 +- src/backend/book/Book.h | 10 +- src/backend/formats/EntryImageProvider.cpp | 52 +--- src/backend/formats/EntryImageProvider.h | 9 +- src/backend/formats/FormatRegistry.cpp | 48 ---- src/backend/formats/FormatRegistry.h | 5 - src/backend/formats/ImageScaling.h | 11 +- src/backend/formats/WebImageProvider.cpp | 54 +--- src/backend/formats/WebImageProvider.h | 14 +- src/backend/reading/MeasurementController.cpp | 50 ---- src/backend/reading/MeasurementController.h | 37 --- src/backend/state/BookPositionStore.cpp | 4 +- src/backend/state/BookPositionStore.h | 3 +- src/main.cpp | 3 +- src/qml/Main.qml | 32 +-- src/qml/components/Footer.qml | 22 +- src/qml/components/MangaPageView.qml | 14 +- src/qml/components/PageView.qml | 45 ---- src/qml/components/ScrollPageView.qml | 224 ----------------- src/qml/pages/ReaderPage.qml | 4 +- tests/ChunkMeasurerTest.cpp | 81 ------ tests/EntryImageProviderTest.cpp | 72 +----- tests/FormatRegistryTest.cpp | 15 +- tests/HistoryBookModelTest.cpp | 3 +- tests/ReadingModelTest.cpp | 232 +++++------------- tests/book/BookTest.cpp | 16 +- tests/state/BookPositionStoreTest.cpp | 38 +-- 38 files changed, 166 insertions(+), 1366 deletions(-) delete mode 100644 src/backend/ChunkMeasurer.cpp delete mode 100644 src/backend/ChunkMeasurer.h delete mode 100644 src/backend/IChunkMeasurer.h delete mode 100644 src/backend/IImageLoader.h delete mode 100644 src/backend/reading/MeasurementController.cpp delete mode 100644 src/backend/reading/MeasurementController.h delete mode 100644 src/qml/components/PageView.qml delete mode 100644 src/qml/components/ScrollPageView.qml delete mode 100644 tests/ChunkMeasurerTest.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 49c77ee..a6460c7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -59,8 +59,6 @@ set(SOURCES src/backend/ReadingModel.cpp src/backend/reading/MangaPagination.h src/backend/reading/MangaPagination.cpp - src/backend/reading/MeasurementController.h - src/backend/reading/MeasurementController.cpp src/backend/state/ReadingPreferences.h src/backend/state/ReadingPreferences.cpp src/backend/state/UiState.h @@ -70,10 +68,7 @@ set(SOURCES src/backend/book/Book.h src/backend/book/Book.cpp src/backend/IImageProvider.h - src/backend/IImageLoader.h src/backend/ZipUtils.h - src/backend/ChunkMeasurer.h - src/backend/ChunkMeasurer.cpp src/backend/IFileDialogService.h src/backend/NativeFileDialogService.h src/backend/NativeFileDialogService.cpp @@ -182,8 +177,6 @@ set_source_files_properties(src/qml/ThemeManager.qml PROPERTIES QT_RESOURCE_ALIA QT_QML_SINGLETON_TYPE TRUE) set_source_files_properties(src/qml/components/Header.qml PROPERTIES QT_RESOURCE_ALIAS components/Header.qml) set_source_files_properties(src/qml/components/SideBar.qml PROPERTIES QT_RESOURCE_ALIAS components/SideBar.qml) -set_source_files_properties(src/qml/components/PageView.qml PROPERTIES QT_RESOURCE_ALIAS components/PageView.qml) -set_source_files_properties(src/qml/components/ScrollPageView.qml PROPERTIES QT_RESOURCE_ALIAS components/ScrollPageView.qml) set_source_files_properties(src/qml/components/MangaPageView.qml PROPERTIES QT_RESOURCE_ALIAS components/MangaPageView.qml) set_source_files_properties(src/qml/components/Footer.qml PROPERTIES QT_RESOURCE_ALIAS components/Footer.qml) set_source_files_properties(src/qml/components/ErrorPopup.qml PROPERTIES QT_RESOURCE_ALIAS components/ErrorPopup.qml) @@ -209,8 +202,6 @@ qt_add_qml_module(asteria-qt src/qml/ThemeManager.qml src/qml/components/Header.qml src/qml/components/SideBar.qml - src/qml/components/PageView.qml - src/qml/components/ScrollPageView.qml src/qml/components/MangaPageView.qml src/qml/components/Footer.qml src/qml/components/ErrorPopup.qml @@ -313,16 +304,9 @@ add_asteria_test(FormatRegistryTest tests/FormatRegistryTest.cpp target_link_libraries(FormatRegistryTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network) set_tests_properties(FormatRegistryTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") -add_asteria_test(ChunkMeasurerTest tests/ChunkMeasurerTest.cpp - src/backend/ChunkMeasurer.cpp) -target_link_libraries(ChunkMeasurerTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick Qt6::Network PkgConfig::MINIZIP) -set_tests_properties(ChunkMeasurerTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") - add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp src/backend/ReadingModel.cpp src/backend/reading/MangaPagination.cpp - src/backend/reading/MeasurementController.cpp - src/backend/ChunkMeasurer.cpp src/backend/formats/AsyncImageResponse.cpp src/backend/formats/sources/Fb2ByteSource.cpp src/backend/formats/WebImageProvider.cpp diff --git a/GEMINI.md b/GEMINI.md index 0ffc05c..93b1aca 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -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. diff --git a/src/backend/AppCoordinator.cpp b/src/backend/AppCoordinator.cpp index c81dcd1..92825c6 100644 --- a/src/backend/AppCoordinator.cpp +++ b/src/backend/AppCoordinator.cpp @@ -34,36 +34,22 @@ AppCoordinator::AppCoordinator(Book &book, , m_formatRegistry(formatRegistry) , m_engine(engine) { - // Typography changes → re-push font params into ReadingModel - connect(&m_readingPreferences, &ReadingPreferences::fontSizeChanged, - this, &AppCoordinator::onFontPrefsChanged); - connect(&m_readingPreferences, &ReadingPreferences::lineSpacingChanged, - this, &AppCoordinator::onFontPrefsChanged); - connect(&m_book, &Book::willOpenNewBook, this, &AppCoordinator::onWillOpenNewBook); connect(&m_book, &Book::positionSaved, this, &AppCoordinator::onPositionSaved); connect(&m_book, &Book::bookChanged, this, &AppCoordinator::onBookChanged); - connect(&m_book, &Book::contentWidthChanged, this, &AppCoordinator::onContentWidthChanged); connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, &AppCoordinator::onAboutToQuit); } -void AppCoordinator::onFontPrefsChanged() -{ - m_readingModel.setFontParams(m_readingPreferences.fontSize(), - m_readingPreferences.lineSpacing()); -} - // Before a new book open: snapshot the outgoing book's progress into the library. -// Scroll position is handled by PageView's scroll tracker via book.saveCurrentPosition(). void AppCoordinator::onWillOpenNewBook() { if (m_book.hasBook()) m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress()); } -// Real-time history update: fired by PageView's scrollTrackTimer on every scroll. +// Real-time history update: fired when position is saved. void AppCoordinator::onPositionSaved() { m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress()); @@ -87,34 +73,18 @@ void AppCoordinator::onBookChanged() m_engine.removeImageProvider(provider->scheme()); m_engine.addImageProvider(provider->scheme(), provider); provider->setFilePath(filePath); - provider->setDisplayWidth(m_contentWidth); m_currentImageProvider = provider; if (!reader->coverImagePath().isEmpty()) m_book.setCoverImageUrl(provider->coverImageUrl(reader->coverImagePath())); } - m_readingModel.setFontParams(m_readingPreferences.fontSize(), - m_readingPreferences.lineSpacing()); - m_readingModel.setImageLoader(m_formatRegistry.createImageLoader(filePath)); - m_readingModel.setCoverImageUrl(m_book.coverImageUrl()); m_readingModel.setReader(reader); - m_readingModel.measure(true); m_uiState.setLastFilePath(filePath); m_historyModel.addOrUpdateBook(filePath, -1.0); } -// Propagate content-width changes to image provider + reading model. -// Called from Book::setContentWidth which is triggered by QML's PageView. -void AppCoordinator::onContentWidthChanged(int width) -{ - m_contentWidth = width; - if (m_currentImageProvider) - m_currentImageProvider->setDisplayWidth(width); - m_readingModel.setContentWidth(width); -} - // Quit: flush everything to persistent storage. // Scroll position was last saved by PageView's scroll tracker; we save library progress here. void AppCoordinator::onAboutToQuit() diff --git a/src/backend/AppCoordinator.h b/src/backend/AppCoordinator.h index fa6a7c4..bd6a9ba 100644 --- a/src/backend/AppCoordinator.h +++ b/src/backend/AppCoordinator.h @@ -35,8 +35,6 @@ private slots: void onBookChanged(); void onWillOpenNewBook(); void onPositionSaved(); - void onContentWidthChanged(int width); - void onFontPrefsChanged(); void onAboutToQuit(); private: @@ -51,5 +49,4 @@ private: QQmlApplicationEngine &m_engine; IImageProvider *m_currentImageProvider = nullptr; - int m_contentWidth = 0; }; diff --git a/src/backend/ChunkMeasurer.cpp b/src/backend/ChunkMeasurer.cpp deleted file mode 100644 index 7d4c295..0000000 --- a/src/backend/ChunkMeasurer.cpp +++ /dev/null @@ -1,96 +0,0 @@ -#include "ChunkMeasurer.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// 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 imageLoader, - int fontSize, qreal lineSpacing) - : m_imageLoader(std::move(imageLoader)) - , m_fontSize(fontSize) - , m_lineSpacing(lineSpacing) -{} - -QVector ChunkMeasurer::measure(const QStringList &chunks, qreal textWidth) -{ - const int n = chunks.size(); - if (n == 0) return {}; - if (textWidth <= 0) textWidth = 1.0; - - QVector 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 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> futures; - futures.reserve(threadCount); - for (int t = 0; t < threadCount; ++t) - futures.append(QtConcurrent::run(worker)); - for (auto &f : futures) - f.waitForFinished(); - - return heights; -} diff --git a/src/backend/ChunkMeasurer.h b/src/backend/ChunkMeasurer.h deleted file mode 100644 index 88def7f..0000000 --- a/src/backend/ChunkMeasurer.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef CHUNKMEASURER_H -#define CHUNKMEASURER_H -#include "IChunkMeasurer.h" -#include "IImageLoader.h" -#include -class ChunkMeasurer : public IChunkMeasurer { -public: - explicit ChunkMeasurer(std::unique_ptr imageLoader = nullptr, - int fontSize = 16, qreal lineSpacing = 1.0); - QVector measure(const QStringList &chunks, qreal textWidth) override; -private: - std::unique_ptr m_imageLoader; - int m_fontSize; - qreal m_lineSpacing; -}; -#endif diff --git a/src/backend/IChunkMeasurer.h b/src/backend/IChunkMeasurer.h deleted file mode 100644 index 27e3e62..0000000 --- a/src/backend/IChunkMeasurer.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef ICHUNKMEASURER_H -#define ICHUNKMEASURER_H -#include -#include -#include -class IChunkMeasurer { -public: - virtual ~IChunkMeasurer() = default; - virtual QVector measure(const QStringList &chunks, qreal textWidth) = 0; -}; -#endif diff --git a/src/backend/IImageLoader.h b/src/backend/IImageLoader.h deleted file mode 100644 index 3ea7881..0000000 --- a/src/backend/IImageLoader.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once -#include -#include -#include -class IImageLoader { -public: - virtual ~IImageLoader() = default; - virtual QImage load(const QUrl &url, int maxWidth) const = 0; - virtual std::unique_ptr clone() const = 0; -}; diff --git a/src/backend/IImageProvider.h b/src/backend/IImageProvider.h index e52336d..d035e42 100644 --- a/src/backend/IImageProvider.h +++ b/src/backend/IImageProvider.h @@ -6,7 +6,6 @@ class IImageProvider : public QQuickAsyncImageProvider { public: virtual ~IImageProvider() = default; virtual void setFilePath(const QString &filePath) = 0; - virtual void setDisplayWidth(int width) = 0; virtual void clear() = 0; // Returns the full QML image URL for a given internal path (e.g., "image://epub/OEBPS/cover.jpg") virtual QString coverImageUrl(const QString &coverPath) const = 0; diff --git a/src/backend/ReadingModel.cpp b/src/backend/ReadingModel.cpp index 642b2fb..4279e0e 100644 --- a/src/backend/ReadingModel.cpp +++ b/src/backend/ReadingModel.cpp @@ -2,47 +2,15 @@ #include "FormatReader.h" #include #include -#include ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent) - : QAbstractListModel(parent) + : QObject(parent) , m_positions(positions) { - connect(&m_measurer, &MeasurementController::measuringChanged, - this, &ReadingModel::measuringChanged); - connect(&m_measurer, &MeasurementController::heightsReady, - this, &ReadingModel::onHeightsReady); } ReadingModel::~ReadingModel() = default; -int ReadingModel::rowCount(const QModelIndex &parent) const { - if (parent.isValid()) return 0; - return m_chunks.size(); -} - -QVariant ReadingModel::data(const QModelIndex &index, int role) const { - if (!index.isValid() || index.row() < 0 || index.row() >= (int)m_chunks.size()) - return {}; - const auto &c = m_chunks.at(index.row()); - switch (role) { - case ContentRole: return c.html; - case PixelHeightRole: return c.pixelHeight; - case ChapterRole: return c.chapterIndex; - case NaturalSizeRole: return c.naturalSize; - default: return {}; - } -} - -QHash ReadingModel::roleNames() const { - return { - {ContentRole, "content"}, - {PixelHeightRole, "pixelHeight"}, - {ChapterRole, "chapter"}, - {NaturalSizeRole, "naturalSize"}, - }; -} - QString ReadingModel::chapterTitle() const { if (m_currentChapter < 0 || m_currentChapter >= m_chapterTitles.size()) @@ -53,8 +21,6 @@ QString ReadingModel::chapterTitle() const int ReadingModel::currentChapter() const { return m_currentChapter; } int ReadingModel::totalChapters() const { return m_totalChapters; } bool ReadingModel::hasChapters() const { return m_totalChapters > 1; } -bool ReadingModel::measuring() const { return m_measurer.measuring(); } -qreal ReadingModel::totalPixelHeight() const { return m_totalPixelHeight; } int ReadingModel::totalPagePairs() const { return m_pagination.count(); } bool ReadingModel::isMangaMode() const { return m_isMangaMode; } bool ReadingModel::pageShift() const { return m_pageShift; } @@ -79,89 +45,13 @@ void ReadingModel::setScrollInfo(const int topChunkIndex, const qreal proportion emit chapterChanged(); } - recalculateCurrentPage(); -} - -void ReadingModel::measure(const bool isNew) -{ - if (!m_reader) return; - if (m_isMangaMode) { - // No measurement needed — images are sized by the view to fit the viewport. - // Queue the emission so QML's Loader has time to create MangaPageView before - // restoreReady arrives (in scroll mode the async measurement provides this gap). - QMetaObject::invokeMethod(this, [this, isNew] { - emitRestoreReady(isNew); - }, Qt::QueuedConnection); - return; + const int page = pairIndexForChunk(topChunkIndex) + 1; + if (m_currentPage != page) { + m_currentPage = page; + emit currentPageChanged(); + } } - - 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 &heights, const bool isNew) -{ - for (int i = 0; i < qMin(heights.size(), static_cast(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 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() @@ -242,7 +132,7 @@ void ReadingModel::setPageShift(bool shift, int currentPairIndex) // Persist immediately. if (m_reader) - m_positions.save(m_reader->contentHash(), currentChunk, 0, m_mangaRTL, m_pageShift); + m_positions.save(m_reader->contentHash(), currentChunk, m_mangaRTL, m_pageShift); emit pageShiftChanged(); // Tell MangaPageView the exact pair to jump to so it re-evaluates its display binding. @@ -253,8 +143,10 @@ void ReadingModel::setMangaRTL(bool rtl) { if (m_mangaRTL == rtl) return; m_mangaRTL = rtl; - if (m_reader) - m_positions.save(m_reader->contentHash(), 0, 0, m_mangaRTL, m_pageShift); + if (m_reader) { + const int currentChunk = (m_currentPage > 0) ? m_pagination.at(m_currentPage - 1).first : 0; + m_positions.save(m_reader->contentHash(), currentChunk >= 0 ? currentChunk : 0, m_mangaRTL, m_pageShift); + } emit mangaRTLChanged(); } @@ -268,29 +160,16 @@ static QString extractImageUrl(const QString &html) void ReadingModel::loadAllChapters() { - beginResetModel(); m_chunks.clear(); m_chapterStartIndices.clear(); m_chapterTitles.clear(); - m_totalPixelHeight = 0.0; - emit totalPixelHeightChanged(); m_currentChapter = 0; if (m_currentPage != 0) { m_currentPage = 0; emit currentPageChanged(); } if (m_totalPages != 0) { m_totalPages = 0; emit totalPagesChanged(); } if (m_reader) { - // In manga mode the format's first chunk is already the cover — no extra cover injection. - if (!m_isMangaMode && !m_coverImageUrl.isEmpty()) { - QString coverHtml = QStringLiteral("
") - + QStringLiteral("
"); - 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); - } + m_chapterStartIndices.append(0); for (int i = 0; i < m_totalChapters; ++i) { auto chapter = m_reader->loadChapter(i); const QVector sizes = m_reader->chapterPageSizes(i); @@ -300,18 +179,17 @@ void ReadingModel::loadAllChapters() int j = 0; for (const auto &html : chapter.contentChunks) { const QSize sz = (j < sizes.size()) ? sizes[j] : QSize(); - m_chunks.push_back({html, i, j, -1, sz, extractImageUrl(html)}); + m_chunks.push_back({i, sz, extractImageUrl(html)}); ++j; } } } - endResetModel(); if (m_isMangaMode) { rebuildPagePairs(); } else { - if (const int pages = m_chunks.size() * page_ratio; m_totalPages != pages) { - m_totalPages = pages; + if (m_totalPages != m_chunks.size()) { + m_totalPages = m_chunks.size(); emit totalPagesChanged(); } if (const int page = m_chunks.isEmpty() ? 0 : 1; m_currentPage != page) { @@ -333,10 +211,17 @@ void ReadingModel::setReader(FormatReader *reader) emit isMangaModeChanged(); // Load per-book pageShift and mangaRTL before loadAllChapters so rebuildPagePairs uses the saved values. - if (m_isMangaMode && reader) { + int restoreChunk = 0; + if (reader) { const auto pos = m_positions.load(reader->contentHash()); - m_pageShift = pos.pageShift; - m_mangaRTL = pos.mangaRTL; + restoreChunk = pos.chunkIndex; + if (m_isMangaMode) { + m_pageShift = pos.pageShift; + m_mangaRTL = pos.mangaRTL; + } else { + m_pageShift = true; + m_mangaRTL = true; + } } else { m_pageShift = true; m_mangaRTL = true; @@ -346,12 +231,11 @@ void ReadingModel::setReader(FormatReader *reader) emit totalChaptersChanged(); emit chapterChanged(); -} -void ReadingModel::setCoverImageUrl(const QString &coverImageUrl) -{ - if (m_coverImageUrl != coverImageUrl) { - m_coverImageUrl = coverImageUrl; + if (m_reader) { + QMetaObject::invokeMethod(this, [this, restoreChunk] { + emit restoreReady(restoreChunk); + }, Qt::QueuedConnection); } } diff --git a/src/backend/ReadingModel.h b/src/backend/ReadingModel.h index c1074b3..5c2c242 100644 --- a/src/backend/ReadingModel.h +++ b/src/backend/ReadingModel.h @@ -1,28 +1,23 @@ #ifndef READINGMODEL_H #define READINGMODEL_H -#include +#include #include #include +#include #include -#include -#include "IImageLoader.h" #include "reading/MangaPagination.h" -#include "reading/MeasurementController.h" #include "state/BookPositionStore.h" class FormatReader; struct ContentChunk { - QString html; // empty when unloaded (lazy streaming) - int chapterIndex = 0; // which chapter owns this chunk - int chunkInChapter = 0; // 0-based index within chapter (-1 for cover) - int pixelHeight = -1; // -1 = not yet measured - QSize naturalSize; // image pixel dimensions (null for text chunks) - QString imageUrl; // src of the chunk's img tag (empty for text chunks) + int chapterIndex = 0; + QSize naturalSize; + QString imageUrl; }; -class ReadingModel : public QAbstractListModel { +class ReadingModel : public QObject { Q_OBJECT Q_PROPERTY(QString chapterTitle READ chapterTitle NOTIFY chapterChanged) Q_PROPERTY(int currentChapter READ currentChapter NOTIFY chapterChanged) @@ -31,28 +26,15 @@ class ReadingModel : public QAbstractListModel { Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged) Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged) Q_PROPERTY(bool hasChapters READ hasChapters NOTIFY totalChaptersChanged) - Q_PROPERTY(bool measuring READ measuring NOTIFY measuringChanged) - Q_PROPERTY(qreal totalPixelHeight READ totalPixelHeight NOTIFY totalPixelHeightChanged) Q_PROPERTY(int totalPagePairs READ totalPagePairs NOTIFY totalPagePairsChanged) Q_PROPERTY(bool isMangaMode READ isMangaMode NOTIFY isMangaModeChanged) Q_PROPERTY(bool pageShift READ pageShift NOTIFY pageShiftChanged) Q_PROPERTY(bool mangaRTL READ mangaRTL NOTIFY mangaRTLChanged) public: - enum Roles { - ContentRole = Qt::UserRole + 1, - PixelHeightRole = Qt::UserRole + 2, - ChapterRole = Qt::UserRole + 3, - NaturalSizeRole = Qt::UserRole + 4, - }; - explicit ReadingModel(BookPositionStore &positions, QObject *parent = nullptr); ~ReadingModel() override; - int rowCount(const QModelIndex &parent) const override; - QVariant data(const QModelIndex &index, int role) const override; - QHash roleNames() const override; - QString chapterTitle() const; int currentChapter() const; int totalChapters() const; @@ -60,17 +42,14 @@ public: int currentPage() const; int totalPages() const; bool hasChapters() const; - bool measuring() const; - qreal totalPixelHeight() const; int totalPagePairs() const; bool isMangaMode() const; bool pageShift() const; bool mangaRTL() const; void setReader(FormatReader *reader); - void setCoverImageUrl(const QString &coverImageUrl); - // Called from QML on every scroll (real-time) + // Called from QML on every page navigation Q_INVOKABLE void setScrollInfo(int topChunkIndex, qreal proportion); Q_INVOKABLE void nextChapter(); @@ -90,19 +69,9 @@ public: Q_INVOKABLE void setPageShift(bool shift, int currentPairIndex = 0); Q_INVOKABLE void setMangaRTL(bool rtl); - // Measurement - Q_INVOKABLE void measure(bool isNew); - - // Preferences & state - void setContentWidth(int width); - Q_INVOKABLE void setFontParams(int fontSize, qreal lineSpacing); - void setImageLoader(std::unique_ptr loader); - signals: void chapterChanged(); void totalChaptersChanged(); - void measuringChanged(); - void totalPixelHeightChanged(); void currentPageChanged(); void totalPagesChanged(); void totalPagePairsChanged(); @@ -113,21 +82,13 @@ signals: void pagePairsRebuilt(int newPairIndex); void scrollToChunkRequested(int chunkIndex); - void restoreReady(int chunkIndex, int intraChunkOffset); - -private slots: - void onHeightsReady(const QVector &heights, bool isNew); + void restoreReady(int chunkIndex); private: - static constexpr qreal page_ratio = 1.5; - void loadAllChapters(); - void recalculateCurrentPage(); void rebuildPagePairs(); - void emitRestoreReady(bool isNew); FormatReader *m_reader = nullptr; - QString m_coverImageUrl; int m_currentChapter = 0; int m_totalChapters = 0; int m_currentPage = 0; @@ -141,17 +102,10 @@ private: QVector m_chapterStartIndices; QVector m_chapterTitles; - // Manga page-pair layout. In RTL mode the "left" slot is the later page visually. MangaPagination m_pagination; - - qreal m_totalPixelHeight = 0.0; qreal m_yOffset = 0.0; - int m_contentWidth = 0; - int m_fontSize = 0; - qreal m_lineSpacing = 0; BookPositionStore &m_positions; - MeasurementController m_measurer; }; #endif // READINGMODEL_H diff --git a/src/backend/book/Book.cpp b/src/backend/book/Book.cpp index d63f7a4..74dd43c 100644 --- a/src/backend/book/Book.cpp +++ b/src/backend/book/Book.cpp @@ -143,16 +143,9 @@ void Book::clearError() emit errorMessageChanged(); } -void Book::saveCurrentPosition(int chunkIndex, int intraOffset, bool pageShift) +void Book::saveCurrentPosition(int chunkIndex, bool mangaRTL, bool pageShift) { if (!m_reader) return; - m_positions.save(m_reader->contentHash(), chunkIndex, intraOffset, pageShift); + m_positions.save(m_reader->contentHash(), chunkIndex, mangaRTL, pageShift); emit positionSaved(); } - -void Book::setContentWidth(int width) -{ - if (m_contentWidth == width) return; - m_contentWidth = width; - emit contentWidthChanged(width); -} diff --git a/src/backend/book/Book.h b/src/backend/book/Book.h index b379bfd..991b0ce 100644 --- a/src/backend/book/Book.h +++ b/src/backend/book/Book.h @@ -51,12 +51,8 @@ public: Q_INVOKABLE void close(); Q_INVOKABLE void clearError(); - // Save current scroll position. Called from QML's scroll tracker; forwards to BookPositionStore. - Q_INVOKABLE void saveCurrentPosition(int chunkIndex, int intraOffset, bool pageShift = false); - - // Called from QML's PageView when its width changes. Propagates to image provider + ReadingModel - // via the contentWidthChanged signal (wired in main.cpp). - Q_INVOKABLE void setContentWidth(int width); + // Save current position. Called from QML; forwards to BookPositionStore. + Q_INVOKABLE void saveCurrentPosition(int chunkIndex, bool mangaRTL = true, bool pageShift = true); signals: // Emitted just before replacing the current reader with a new one. @@ -67,7 +63,6 @@ signals: void bookChanged(); void loadingChanged(); void errorMessageChanged(); - void contentWidthChanged(int width); private: void openImpl(const QString &filePath); @@ -80,7 +75,6 @@ private: QString m_errorMessage; bool m_loading = false; int m_openGeneration = 0; - int m_contentWidth = 0; QFuture m_openFuture; }; diff --git a/src/backend/formats/EntryImageProvider.cpp b/src/backend/formats/EntryImageProvider.cpp index d34b366..8f3a71d 100644 --- a/src/backend/formats/EntryImageProvider.cpp +++ b/src/backend/formats/EntryImageProvider.cpp @@ -11,7 +11,6 @@ QImage EntryImageProvider::loadImageFromSource(IByteSource &source, const QString &entryName, - int displayWidth, const QSize &requestedSize) { if (entryName.isEmpty()) @@ -25,7 +24,7 @@ QImage EntryImageProvider::loadImageFromSource(IByteSource &source, if (!image.loadFromData(data)) return {}; - return scaleToFit(image, displayWidth, requestedSize); + return scaleToFit(image, requestedSize); } EntryImageProvider::EntryImageProvider(SourceFactory sourceFactory, QString scheme) @@ -38,11 +37,9 @@ QQuickImageResponse *EntryImageProvider::requestImageResponse(const QString &id, const QSize &requestedSize) { QString sourcePath; - int displayWidth; { QMutexLocker lock(&m_mutex); - sourcePath = m_sourcePath; - displayWidth = m_displayWidth; + sourcePath = m_sourcePath; } // id may be "entry/name.jpg?src=" @@ -52,50 +49,16 @@ QQuickImageResponse *EntryImageProvider::requestImageResponse(const QString &id, sourcePath = parsed.sourcePath; auto *response = new AsyncImageResponse( - [factory = m_sourceFactory, sourcePath, entryName, displayWidth, requestedSize]() -> QImage { + [factory = m_sourceFactory, sourcePath, entryName, requestedSize]() -> QImage { auto source = factory(); if (!source->open(sourcePath)) return {}; - return loadImageFromSource(*source, entryName, displayWidth, requestedSize); + return loadImageFromSource(*source, entryName, requestedSize); }); QThreadPool::globalInstance()->start(response); return response; } -QImage EntryImageProvider::load(const QUrl &url, int maxWidth) const -{ - if (url.scheme() != QLatin1String("image")) - return {}; - - const ImageUrl::Parsed parsed = ImageUrl::parseImageUrl(url); - const QString entryName = parsed.entry; - if (entryName.isEmpty()) - return {}; - - QString sourcePath = parsed.sourcePath; - if (sourcePath.isEmpty()) { - QMutexLocker lock(&m_mutex); - sourcePath = m_sourcePath; - } - - auto source = m_sourceFactory(); - if (!source->open(sourcePath)) - return {}; - return loadImageFromSource(*source, entryName, maxWidth, {}); -} - -std::unique_ptr EntryImageProvider::clone() const -{ - QString sourcePath; - { - QMutexLocker lock(&m_mutex); - sourcePath = m_sourcePath; - } - auto c = std::make_unique(m_sourceFactory, m_scheme); - c->setFilePath(sourcePath); - return c; -} - void EntryImageProvider::setFilePath(const QString &filePath) { QMutexLocker lock(&m_mutex); @@ -114,15 +77,8 @@ QString EntryImageProvider::scheme() const return m_scheme; } -void EntryImageProvider::setDisplayWidth(int width) -{ - QMutexLocker lock(&m_mutex); - m_displayWidth = width; -} - void EntryImageProvider::clear() { QMutexLocker lock(&m_mutex); m_sourcePath.clear(); - m_displayWidth = 0; } diff --git a/src/backend/formats/EntryImageProvider.h b/src/backend/formats/EntryImageProvider.h index 11d8fef..f01ebfc 100644 --- a/src/backend/formats/EntryImageProvider.h +++ b/src/backend/formats/EntryImageProvider.h @@ -1,7 +1,6 @@ #pragma once #include "IByteSource.h" -#include "backend/IImageLoader.h" #include "backend/IImageProvider.h" #include @@ -9,7 +8,7 @@ #include #include -class EntryImageProvider : public IImageProvider, public IImageLoader { +class EntryImageProvider : public IImageProvider { public: using SourceFactory = std::function()>; @@ -19,17 +18,12 @@ public: const QSize &requestedSize) override; void setFilePath(const QString &filePath) override; - void setDisplayWidth(int width) override; void clear() override; QString coverImageUrl(const QString &coverPath) const override; QString scheme() const override; - QImage load(const QUrl &url, int maxWidth) const override; - std::unique_ptr clone() const override; - static QImage loadImageFromSource(IByteSource &source, const QString &entryName, - int displayWidth, const QSize &requestedSize); private: @@ -37,5 +31,4 @@ private: QString m_scheme; mutable QMutex m_mutex; QString m_sourcePath; - int m_displayWidth = 0; }; diff --git a/src/backend/formats/FormatRegistry.cpp b/src/backend/formats/FormatRegistry.cpp index 55dccbf..8f812a5 100644 --- a/src/backend/formats/FormatRegistry.cpp +++ b/src/backend/formats/FormatRegistry.cpp @@ -7,36 +7,6 @@ #include #include -// 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 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 clone() const override - { - auto c = std::make_unique(); - for (const auto &[host, loader] : m_loaders) - c->add(host, loader->clone()); - return c; - } - -private: - std::vector>> m_loaders; -}; - FormatRegistry::FormatRegistry(QVector specs) : m_specs(std::move(specs)) { @@ -69,24 +39,6 @@ IImageProvider *FormatRegistry::createImageProvider(const QString &filePath) con return new EntryImageProvider(spec->makeSource, spec->scheme); } -std::unique_ptr 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(spec->makeSource, spec->scheme); - loader->setFilePath(filePath); - - if (!spec->loaderIncludesWeb) - return loader; - - auto composite = std::make_unique(); - composite->add(spec->scheme, std::move(loader)); - composite->add(QStringLiteral("web"), std::make_unique()); - return composite; -} - QStringList FormatRegistry::supportedExtensions() const { QStringList out; diff --git a/src/backend/formats/FormatRegistry.h b/src/backend/formats/FormatRegistry.h index ed11352..b1db072 100644 --- a/src/backend/formats/FormatRegistry.h +++ b/src/backend/formats/FormatRegistry.h @@ -8,7 +8,6 @@ class FormatReader; class IByteSource; -class IImageLoader; class IImageProvider; class QQmlEngine; @@ -21,7 +20,6 @@ struct FormatSpec { QString scheme; // image:// scheme; empty = format has no images std::function()> makeReader; std::function()> makeSource; // required when scheme is set - bool loaderIncludesWeb = false; // formats whose content may reference web images (epub) }; class FormatRegistry { @@ -34,9 +32,6 @@ public: // Caller owns the pointer (the QML engine takes ownership on registration). IImageProvider *createImageProvider(const QString &filePath) const; - // Synchronous loader for measurement, or nullptr for formats without images. - std::unique_ptr createImageLoader(const QString &filePath) const; - QStringList supportedExtensions() const; // Register one provider per scheme with the QML engine (engine takes ownership). diff --git a/src/backend/formats/ImageScaling.h b/src/backend/formats/ImageScaling.h index b32b037..af383eb 100644 --- a/src/backend/formats/ImageScaling.h +++ b/src/backend/formats/ImageScaling.h @@ -3,17 +3,13 @@ #include #include -// Honor an explicit requested size (clamped to the display width), otherwise -// scale down to fit the display width — never enlarge. -inline QImage scaleToFit(QImage image, int displayWidth, const QSize &requestedSize) +// Honor an explicit requested size, otherwise keep original image dimensions — never enlarge. +inline QImage scaleToFit(QImage image, const QSize &requestedSize) { if (requestedSize.width() > 0 || requestedSize.height() > 0) { int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1; int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1; - if (displayWidth > 0 && targetW > 0 && targetW > displayWidth) - targetW = displayWidth; - if (targetW > 0 && targetH > 0) { image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio, Qt::SmoothTransformation); @@ -22,9 +18,6 @@ inline QImage scaleToFit(QImage image, int displayWidth, const QSize &requestedS } else { image = image.scaledToHeight(targetH, Qt::SmoothTransformation); } - } else { - if (displayWidth > 0 && image.width() > displayWidth) - image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation); } return image; } diff --git a/src/backend/formats/WebImageProvider.cpp b/src/backend/formats/WebImageProvider.cpp index d695646..2a3c1b1 100644 --- a/src/backend/formats/WebImageProvider.cpp +++ b/src/backend/formats/WebImageProvider.cpp @@ -39,7 +39,7 @@ QString WebImageProvider::cacheFilePath(const QString &urlString) // WebImageProvider // --------------------------------------------------------------------------- -QImage WebImageProvider::loadWebImage(const QString &urlString, int displayWidth, +QImage WebImageProvider::loadWebImage(const QString &urlString, const QSize &requestedSize) { if (urlString.isEmpty()) @@ -50,7 +50,7 @@ QImage WebImageProvider::loadWebImage(const QString &urlString, int displayWidth if (QFile::exists(cachePath)) { QImage image; if (image.load(cachePath)) - return scaleToFit(image, displayWidth, requestedSize); + return scaleToFit(image, requestedSize); } // Download — blocking, safe to call from any thread via a local event loop @@ -89,7 +89,7 @@ QImage WebImageProvider::loadWebImage(const QString &urlString, int displayWidth if (!image.loadFromData(data)) return {}; - return scaleToFit(image, displayWidth, requestedSize); + return scaleToFit(image, requestedSize); } // --------------------------------------------------------------------------- @@ -109,13 +109,8 @@ QQuickImageResponse *WebImageProvider::requestImageResponse(const QString &id, return response; } - int displayWidth; - { - QMutexLocker lock(&m_mutex); - displayWidth = m_displayWidth; - } - auto *response = new AsyncImageResponse([id, displayWidth, requestedSize] { - return loadWebImage(id, displayWidth, requestedSize); + auto *response = new AsyncImageResponse([id, requestedSize] { + return loadWebImage(id, requestedSize); }); QThreadPool::globalInstance()->start(response); return response; @@ -125,42 +120,3 @@ QString WebImageProvider::scheme() const { return QStringLiteral("web"); } - -void WebImageProvider::setDisplayWidth(int width) -{ - QMutexLocker lock(&m_mutex); - m_displayWidth = width; -} - -// --------------------------------------------------------------------------- -// WebImageProvider — IImageLoader -// --------------------------------------------------------------------------- - -QImage WebImageProvider::load(const QUrl &url, int maxWidth) const -{ - // url is image://web/ - // url.path() yields "/"; 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 WebImageProvider::clone() const -{ - auto c = std::make_unique(); - QMutexLocker lock(&m_mutex); - c->m_displayWidth = m_displayWidth; - return c; -} diff --git a/src/backend/formats/WebImageProvider.h b/src/backend/formats/WebImageProvider.h index 04ea272..482c4c6 100644 --- a/src/backend/formats/WebImageProvider.h +++ b/src/backend/formats/WebImageProvider.h @@ -1,34 +1,24 @@ #pragma once -#include #include #include -#include "backend/IImageLoader.h" #include "backend/IImageProvider.h" -class WebImageProvider : public IImageProvider, public IImageLoader { +class WebImageProvider : public IImageProvider { public: QQuickImageResponse *requestImageResponse(const QString &id, const QSize &requestedSize) override; void setFilePath(const QString &) override {} - void setDisplayWidth(int width) override; void clear() override {} QString coverImageUrl(const QString &) const override { return {}; } QString scheme() const override; - QImage load(const QUrl &url, int maxWidth) const override; - std::unique_ptr clone() const override; - // Download (or load from disk cache) a web image. Thread-safe, may block. - static QImage loadWebImage(const QString &urlString, int displayWidth, + static QImage loadWebImage(const QString &urlString, const QSize &requestedSize); static QString cacheDir(); static QString cacheFilePath(const QString &urlString); - -private: - mutable QMutex m_mutex; - int m_displayWidth = 0; }; diff --git a/src/backend/reading/MeasurementController.cpp b/src/backend/reading/MeasurementController.cpp deleted file mode 100644 index 62ac1fa..0000000 --- a/src/backend/reading/MeasurementController.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include "MeasurementController.h" - -#include "backend/ChunkMeasurer.h" - -#include - -MeasurementController::MeasurementController(QObject *parent) - : QObject(parent) -{ -} - -MeasurementController::~MeasurementController() -{ - if (m_future.isRunning()) { - m_future.cancel(); - m_future.waitForFinished(); - } -} - -void MeasurementController::setImageLoader(std::unique_ptr 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 loaderClone = m_imageLoader ? m_imageLoader->clone() : nullptr; - auto measurer = std::make_shared(std::move(loaderClone), fontSize, lineSpacing); - - m_future = QtConcurrent::run([this, htmls, measurer, contentWidth, isNew]() { - QVector heights = measurer->measure(htmls, contentWidth); - QMetaObject::invokeMethod(this, [this, heights, isNew] { - m_measuring = false; - emit measuringChanged(); - emit heightsReady(heights, isNew); - }, Qt::QueuedConnection); - }); -} diff --git a/src/backend/reading/MeasurementController.h b/src/backend/reading/MeasurementController.h deleted file mode 100644 index 36392b7..0000000 --- a/src/backend/reading/MeasurementController.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#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 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 heights, bool isNew); - -private: - std::unique_ptr m_imageLoader; - bool m_measuring = false; - QFuture m_future; -}; diff --git a/src/backend/state/BookPositionStore.cpp b/src/backend/state/BookPositionStore.cpp index 7c2aad6..08a288a 100644 --- a/src/backend/state/BookPositionStore.cpp +++ b/src/backend/state/BookPositionStore.cpp @@ -12,19 +12,17 @@ BookPosition BookPositionStore::load(const QByteArray &contentMd5) const QVariantMap d = m_state.loadSection(sectionKey(contentMd5)); BookPosition pos; pos.chunkIndex = d.value(QStringLiteral("chunkIndex"), 0).toInt(); - pos.intraOffset = d.value(QStringLiteral("intraOffset"), 0).toInt(); pos.pageShift = d.value(QStringLiteral("pageShift"), true).toBool(); pos.mangaRTL = d.value(QStringLiteral("mangaRTL"), true).toBool(); return pos; } -void BookPositionStore::save(const QByteArray &contentMd5, int chunkIndex, int intraOffset, bool mangaRTL, bool pageShift) +void BookPositionStore::save(const QByteArray &contentMd5, int chunkIndex, bool mangaRTL, bool pageShift) { if (contentMd5.isEmpty()) return; m_state.saveSection(sectionKey(contentMd5), { {QStringLiteral("chunkIndex"), chunkIndex}, - {QStringLiteral("intraOffset"), intraOffset}, {QStringLiteral("pageShift"), pageShift}, {QStringLiteral("mangaRTL"), mangaRTL}, }); diff --git a/src/backend/state/BookPositionStore.h b/src/backend/state/BookPositionStore.h index d186ebb..0a1ffe6 100644 --- a/src/backend/state/BookPositionStore.h +++ b/src/backend/state/BookPositionStore.h @@ -6,7 +6,6 @@ struct BookPosition { int chunkIndex = 0; - int intraOffset = 0; bool pageShift = true; // manga page-shift; default ON bool mangaRTL = true; // manga reading direction; default RTL }; @@ -19,7 +18,7 @@ public: BookPosition load(const QByteArray &contentMd5); // Save the current position for a book identified by MD5 of its contents. - void save(const QByteArray &contentMd5, int chunkIndex, int intraOffset, bool mangaRTL = true, bool pageShift = true); + void save(const QByteArray &contentMd5, int chunkIndex, bool mangaRTL = true, bool pageShift = true); private: AppState &m_state; diff --git a/src/main.cpp b/src/main.cpp index 0bdf932..fbb6647 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -111,8 +111,7 @@ int main(int argc, char *argv[]) [] { return std::make_unique(); }, nullptr}, {QStringLiteral("epub"), false, QStringLiteral("epub"), [] { return std::make_unique(); }, - [] { return std::make_unique(); }, - /*loaderIncludesWeb=*/true}, + [] { return std::make_unique(); }}, {QStringLiteral("fb2"), false, QStringLiteral("fb2"), [] { return std::make_unique(); }, [] { return std::make_unique(); }}, diff --git a/src/qml/Main.qml b/src/qml/Main.qml index 606bb41..ad946cc 100644 --- a/src/qml/Main.qml +++ b/src/qml/Main.qml @@ -57,13 +57,6 @@ ApplicationWindow { } } - Connections { - target: readingModel - function onMeasuringChanged() { - if (!readingModel.measuring) window._bookInitializing = false - } - } - Timer { id: geometrySaveTimer interval: 250 @@ -181,10 +174,8 @@ ApplicationWindow { // Navigate once measurement (and position restoration) is done Connections { target: readingModel - function onRestoreReady(chunkIndex, intraOffset) { + function onRestoreReady(chunkIndex) { if (!book.hasBook) return - // Reset loading overlay — in manga mode measuring is skipped so measuringChanged - // never fires; restoreReady is the definitive "ready" signal for all modes. window._bookInitializing = false if (window._startupRestore) { window._startupRestore = false @@ -218,24 +209,6 @@ ApplicationWindow { context: Qt.ApplicationShortcut onActivated: window.visibility = (window.visibility === Window.FullScreen) ? Window.Windowed : Window.FullScreen } - Shortcut { - sequence: "Up" - context: Qt.ApplicationShortcut - onActivated: { - if (currentPage === "reader" && readerPage?.pageView && !readingModel.isMangaMode) { - readerPage.pageView.handleScrollUp(); - } - } - } - Shortcut { - sequence: "Down" - context: Qt.ApplicationShortcut - onActivated: { - if (currentPage === "reader" && readerPage?.pageView && !readingModel.isMangaMode) { - readerPage.pageView.handleScrollDown(); - } - } - } Shortcut { sequence: "Left" context: Qt.ApplicationShortcut @@ -314,7 +287,7 @@ ApplicationWindow { context: Qt.ApplicationShortcut onActivated: { if (currentPage === "reader" && readingModel.isMangaMode) - readingModel.setPageShift(!readingModel.pageShift, readerPage.pageView.currentMangaPair) + readingModel.setPageShift(!readingModel.pageShift, readerPage.pageView.currentPair) } } @@ -325,7 +298,6 @@ ApplicationWindow { triggeredOnStart: false onTriggered: { window.opacity = 1 - readerPage.pageView.updateContentWidth() if (uiState.lastFilePath !== "") { window._startupRestore = true book.openFromPath(uiState.lastFilePath) diff --git a/src/qml/components/Footer.qml b/src/qml/components/Footer.qml index 6c4ab90..042e3ad 100644 --- a/src/qml/components/Footer.qml +++ b/src/qml/components/Footer.qml @@ -13,25 +13,6 @@ Rectangle { anchors.top: parent.top } - // Measuring spinner (hidden during manga mode — measurement is skipped for image formats) - Text { - anchors.left: parent.left - anchors.leftMargin: 16 - anchors.verticalCenter: parent.verticalCenter - visible: readingModel.measuring - text: "" - font.family: "Material Icons Outlined" - font.pixelSize: 14 - color: ThemeManager.currentTheme.dimText - - RotationAnimator on rotation { - from: 0; to: 360 - duration: 1200 - loops: Animation.Infinite - running: parent.visible - } - } - // RTL reading direction toggle (manga mode only). FlatIconButton { anchors.left: parent.left @@ -62,8 +43,7 @@ Rectangle { : ThemeManager.currentTheme.dimText tooltip: "Page shift (S)" onClicked: { - // currentPair lives on MangaPageView; reach it via the PageView router alias. - const pairIdx = readerPage.pageView.currentMangaPair + const pairIdx = readerPage.pageView.currentPair readingModel.setPageShift(!readingModel.pageShift, pairIdx) } } diff --git a/src/qml/components/MangaPageView.qml b/src/qml/components/MangaPageView.qml index dbb061c..096d579 100644 --- a/src/qml/components/MangaPageView.qml +++ b/src/qml/components/MangaPageView.qml @@ -6,13 +6,7 @@ Rectangle { id: root focus: true - // Keep the same public interface as ScrollPageView so PageView router delegates uniformly. property bool contentReady: false - property bool resizing: false - property bool restoreReady: false - property int initialIndex: -1 - property int initialOffset: -1 - property int currentPair: 0 readonly property bool landscape: width > height @@ -48,7 +42,7 @@ Rectangle { const firstChunk = pair[0] // Keep scroll model in sync so Footer page counter and chapter tracking work. readingModel.setScrollInfo(firstChunk, pairIndex / Math.max(1, readingModel.totalPagePairs - 1)) - book.saveCurrentPosition(firstChunk, 0, readingModel.pageShift) + book.saveCurrentPosition(firstChunk, readingModel.mangaRTL, readingModel.pageShift) } // Notify model when orientation changes (triggers pair rebuild). @@ -196,9 +190,11 @@ Rectangle { // Restore position when a new book is loaded. Connections { target: readingModel - function onRestoreReady(chunkIndex, intraOffset) { + function onRestoreReady(chunkIndex) { contentReady = true - restoreReady = true + showPair(readingModel.pairIndexForChunk(chunkIndex)) + } + function onScrollToChunkRequested(chunkIndex) { showPair(readingModel.pairIndexForChunk(chunkIndex)) } function onTotalPagePairsChanged() { diff --git a/src/qml/components/PageView.qml b/src/qml/components/PageView.qml deleted file mode 100644 index fb03236..0000000 --- a/src/qml/components/PageView.qml +++ /dev/null @@ -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 } - } -} diff --git a/src/qml/components/ScrollPageView.qml b/src/qml/components/ScrollPageView.qml deleted file mode 100644 index 2088618..0000000 --- a/src/qml/components/ScrollPageView.qml +++ /dev/null @@ -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 - } - } - -} diff --git a/src/qml/pages/ReaderPage.qml b/src/qml/pages/ReaderPage.qml index 7be3711..12cf980 100644 --- a/src/qml/pages/ReaderPage.qml +++ b/src/qml/pages/ReaderPage.qml @@ -4,8 +4,8 @@ import Asteria Item { id: readerPage property alias pageView: internalPageView - - PageView { + + MangaPageView { id: internalPageView anchors.fill: parent focus: visible diff --git a/tests/ChunkMeasurerTest.cpp b/tests/ChunkMeasurerTest.cpp deleted file mode 100644 index 0649988..0000000 --- a/tests/ChunkMeasurerTest.cpp +++ /dev/null @@ -1,81 +0,0 @@ -#include -#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 clone() const override { - return std::make_unique(m_size); - } -}; - -class ChunkMeasurerTest : public QObject { - Q_OBJECT -private slots: - void returnsOneHeightPerChunk() { - ChunkMeasurer m; - QStringList chunks = {"

First

", "

Second

", "

Third

"}; - auto h = m.measure(chunks, 800); - QCOMPARE(h.size(), 3); - } - void heightsArePositive() { - ChunkMeasurer m; - auto h = m.measure({"

Hello world

", "

Another paragraph

"}, 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({"

text

"}, 0); - QCOMPARE(h.size(), 1); - QVERIFY(h.first() > 0); - } - void narrowerWidthGivesGreaterOrEqualHeight() { - ChunkMeasurer m; - QStringList chunks = {"

A long paragraph that should wrap when the width is very narrow.

"}; - 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(QSize(600, 400)); - ChunkMeasurer m(std::move(loader)); - // Chunk with an image URL - QStringList chunks = {QStringLiteral("

")}; - 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({"

text only

"}, 800); - QCOMPARE(h.size(), 1); - QVERIFY(h.first() > 0); - } - void parallelResultsAreConsistent() { - ChunkMeasurer m; - QStringList chunks; - for (int i = 0; i < 100; ++i) - chunks << QStringLiteral("

Paragraph number %1 with some text content.

").arg(i); - auto h1 = m.measure(chunks, 600); - auto h2 = m.measure(chunks, 600); - QCOMPARE(h1, h2); - } -}; -QTEST_MAIN(ChunkMeasurerTest) -#include "ChunkMeasurerTest.moc" diff --git a/tests/EntryImageProviderTest.cpp b/tests/EntryImageProviderTest.cpp index 686a2f0..39d76f5 100644 --- a/tests/EntryImageProviderTest.cpp +++ b/tests/EntryImageProviderTest.cpp @@ -17,13 +17,12 @@ // Load one zip member through the generic byte-source pipeline (EPUBs are zips). static QImage loadFromEpub(const QString &epubPath, const QString &entry, - int displayWidth, const QSize &requestedSize) + const QSize &requestedSize) { ZipByteSource source; if (!source.open(epubPath)) return {}; - return EntryImageProvider::loadImageFromSource(source, entry, displayWidth, - requestedSize); + return EntryImageProvider::loadImageFromSource(source, entry, requestedSize); } static EntryImageProvider makeEpubProvider() @@ -96,7 +95,7 @@ private slots: QVERIFY(!epubPath.isEmpty()); const QImage img = loadFromEpub( - epubPath, QStringLiteral("OEBPS/Images/test.png"), 0, QSize()); + epubPath, QStringLiteral("OEBPS/Images/test.png"), QSize()); QFile::remove(epubPath); @@ -112,7 +111,7 @@ private slots: QVERIFY(!epubPath.isEmpty()); const QImage img = loadFromEpub( - epubPath, QStringLiteral("OEBPS/Images/nonexistent.png"), 0, QSize()); + epubPath, QStringLiteral("OEBPS/Images/nonexistent.png"), QSize()); QFile::remove(epubPath); @@ -122,7 +121,7 @@ private slots: void requestImageReturnsNullWhenNoPath() { const QImage img = loadFromEpub( - QString{}, QStringLiteral("OEBPS/Images/test.png"), 0, QSize()); + QString{}, QStringLiteral("OEBPS/Images/test.png"), QSize()); QVERIFY(img.isNull()); } @@ -133,51 +132,20 @@ private slots: // After clear the path is empty, so loadImageFromEpub with empty path returns null const QImage img = loadFromEpub( - QString{}, QStringLiteral("OEBPS/Images/test.png"), 0, QSize()); + QString{}, QStringLiteral("OEBPS/Images/test.png"), QSize()); QFile::remove(epubPath); QVERIFY(img.isNull()); } - void largeImageScaledToDisplayWidth() - { - const QString epubPath = buildEpubWithPng("img.png", 600, 400); - QVERIFY(!epubPath.isEmpty()); - - const QImage img = loadFromEpub( - epubPath, QStringLiteral("img.png"), 300, QSize()); - - QFile::remove(epubPath); - - QVERIFY(!img.isNull()); - QCOMPARE(img.width(), 300); - QCOMPARE(img.height(), 200); - QCOMPARE(img.size(), QSize(300, 200)); - } - - void smallImageNotEnlarged() - { - const QString epubPath = buildEpubWithPng("img.png", 100, 100); - QVERIFY(!epubPath.isEmpty()); - - const QImage img = loadFromEpub( - epubPath, QStringLiteral("img.png"), 300, QSize()); - - QFile::remove(epubPath); - - QVERIFY(!img.isNull()); - QCOMPARE(img.width(), 100); - QCOMPARE(img.height(), 100); - } - void requestedSizeHonored() { const QString epubPath = buildEpubWithPng("img.png", 400, 300); QVERIFY(!epubPath.isEmpty()); const QImage img = loadFromEpub( - epubPath, QStringLiteral("img.png"), 600, QSize(200, -1)); + epubPath, QStringLiteral("img.png"), QSize(200, -1)); QFile::remove(epubPath); @@ -196,7 +164,7 @@ private slots: AsyncImageResponse response([epubPath] { return loadFromEpub( - epubPath, QStringLiteral("img.png"), 0, QSize()); + epubPath, QStringLiteral("img.png"), QSize()); }); QSignalSpy spy(&response, &QQuickImageResponse::finished); response.run(); @@ -214,7 +182,7 @@ private slots: AsyncImageResponse response([epubPath] { return loadFromEpub( - epubPath, QStringLiteral("img.png"), 0, QSize()); + epubPath, QStringLiteral("img.png"), QSize()); }); QSignalSpy spy(&response, &QQuickImageResponse::finished); response.cancel(); @@ -232,7 +200,7 @@ private slots: AsyncImageResponse response([epubPath] { return loadFromEpub( - epubPath, QStringLiteral("img.png"), 0, QSize()); + epubPath, QStringLiteral("img.png"), QSize()); }); response.cancel(); response.run(); @@ -298,24 +266,6 @@ private slots: delete resp; } - void loadMethodHandlesEmbeddedUrlFormat() - { - const QString epubPath = buildEpubWithPng("img.png", 4, 4, qRgb(255, 0, 0)); - QVERIFY(!epubPath.isEmpty()); - - EntryImageProvider provider = makeEpubProvider(); - // m_epubPath is intentionally NOT set — embedded URL must supply it via query - const QString encodedPath = QString::fromUtf8(QUrl::toPercentEncoding(epubPath)); - const QUrl url(QStringLiteral("image://epub/img.png?src=") + encodedPath); - - const QImage img = provider.load(url, 0); - - QFile::remove(epubPath); - - QVERIFY(!img.isNull()); - QCOMPARE(img.pixel(0, 0), qRgb(255, 0, 0)); - } - void requestImageResponseFallsBackToProviderPath() { // Without a leading slash in id, the provider should use m_epubPath. @@ -387,7 +337,7 @@ private slots: QCOMPARE(source.listEntries(), QStringList{QStringLiteral("cover.png")}); const QImage img = EntryImageProvider::loadImageFromSource( - source, QStringLiteral("cover.png"), 0, QSize()); + source, QStringLiteral("cover.png"), QSize()); QVERIFY(!source.contentHash().isEmpty()); QFile::remove(path); diff --git a/tests/FormatRegistryTest.cpp b/tests/FormatRegistryTest.cpp index e8120cf..1b73e36 100644 --- a/tests/FormatRegistryTest.cpp +++ b/tests/FormatRegistryTest.cpp @@ -3,7 +3,6 @@ #include "backend/formats/FormatRegistry.h" #include "backend/FormatReader.h" #include "backend/IImageProvider.h" -#include "backend/IImageLoader.h" #include "backend/formats/TxtReader.h" #include "backend/formats/EpubReader.h" #include "backend/formats/comic/CbzReader.h" @@ -20,8 +19,7 @@ static FormatRegistry makeRegistry() [] { return std::make_unique(); }, nullptr}, {QStringLiteral("epub"), false, QStringLiteral("epub"), [] { return std::make_unique(); }, - [] { return std::make_unique(); }, - /*loaderIncludesWeb=*/true}, + [] { return std::make_unique(); }}, {QStringLiteral("cbz"), false, QStringLiteral("cbz"), [] { return std::make_unique(); }, [] { return std::make_unique(); }}, @@ -120,21 +118,12 @@ private slots: QCOMPARE(dir->scheme(), QStringLiteral("dir")); } - void formatsWithoutImagesHaveNoProviderOrLoader() + void formatsWithoutImagesHaveNoProvider() { auto registry = makeRegistry(); QVERIFY(registry.createImageProvider("plain.txt") == nullptr); - QVERIFY(registry.createImageLoader("plain.txt") == nullptr); QVERIFY(registry.createImageProvider("file.xyz") == nullptr); } - - void createImageLoaderReturnsLoader() - { - auto registry = makeRegistry(); - QVERIFY(registry.createImageLoader("comic.cbz") != nullptr); - // epub loader is a composite (epub + web) but still non-null - QVERIFY(registry.createImageLoader("book.epub") != nullptr); - } }; QTEST_MAIN(FormatRegistryTest) diff --git a/tests/HistoryBookModelTest.cpp b/tests/HistoryBookModelTest.cpp index 99a29c3..911daf6 100644 --- a/tests/HistoryBookModelTest.cpp +++ b/tests/HistoryBookModelTest.cpp @@ -22,8 +22,7 @@ static FormatRegistry makeRegistry() [] { return std::make_unique(); }, nullptr}, {QStringLiteral("epub"), false, QStringLiteral("epub"), [] { return std::make_unique(); }, - [] { return std::make_unique(); }, - /*loaderIncludesWeb=*/true}, + [] { return std::make_unique(); }}, }); } diff --git a/tests/ReadingModelTest.cpp b/tests/ReadingModelTest.cpp index 10e4eb9..1571b2c 100644 --- a/tests/ReadingModelTest.cpp +++ b/tests/ReadingModelTest.cpp @@ -51,6 +51,38 @@ public: QString fileType() const override { return QStringLiteral("txt"); } }; +class FakeMangaReader : public FormatReader { +public: + bool open(const QString &) override { return true; } + QString lastError() override { return {}; } + int chapterCount() override { return 1; } + + Chapter loadChapter(int index) override + { + if (index != 0) return {index, {}, {}}; + return {0, QStringLiteral("Manga Title"), + {QStringLiteral(""), + QStringLiteral(""), + QStringLiteral("")}}; + } + + QVector 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 tableOfContents() override { return {}; } + QString title() override { return QStringLiteral("Manga Title"); } + QString author() override { return QStringLiteral("Manga Author"); } + QString filePath() override { return QStringLiteral("/fake/manga.cbz"); } + QString coverImagePath() override { return QStringLiteral("0.jpg"); } + QByteArray contentHash() override { return QByteArray("mangahash"); } + bool loadMetadata(const QString &) override { return true; } + QString fileType() const override { return QStringLiteral("cbz"); } +}; + class ReadingModelTest : public QObject { Q_OBJECT @@ -78,7 +110,9 @@ private slots: QCOMPARE(model.totalChapters(), 0); QCOMPARE(model.progress(), 0.0); QVERIFY(model.chapterTitle().isEmpty()); - QCOMPARE(model.rowCount(QModelIndex()), 0); + QCOMPARE(model.currentPage(), 0); + QCOMPARE(model.totalPages(), 0); + QVERIFY(!model.isMangaMode()); } void setReaderLoadsAllChapters() @@ -87,46 +121,11 @@ private slots: FakeReader reader; model.setReader(&reader); - // All 3 chapters × 2 chunks = 6 total rows - QCOMPARE(model.rowCount(QModelIndex()), 6); QCOMPARE(model.totalChapters(), 3); QCOMPARE(model.currentChapter(), 0); QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 0")); } - void chunkContentAcrossChapters() - { - Ctx ctx; ReadingModel model(*ctx.store); - FakeReader reader; - model.setReader(&reader); - - // Chapter 0: chunks 0,1 - QCOMPARE(model.data(model.index(0, 0), ReadingModel::ContentRole).toString(), - QStringLiteral("

Chunk A of 0

")); - QCOMPARE(model.data(model.index(1, 0), ReadingModel::ContentRole).toString(), - QStringLiteral("

Chunk B of 0

")); - // Chapter 1: chunks 2,3 - QCOMPARE(model.data(model.index(2, 0), ReadingModel::ContentRole).toString(), - QStringLiteral("

Chunk A of 1

")); - QCOMPARE(model.data(model.index(3, 0), ReadingModel::ContentRole).toString(), - QStringLiteral("

Chunk B of 1

")); - // Chapter 2: chunks 4,5 - QCOMPARE(model.data(model.index(4, 0), ReadingModel::ContentRole).toString(), - QStringLiteral("

Chunk A of 2

")); - QCOMPARE(model.data(model.index(5, 0), ReadingModel::ContentRole).toString(), - QStringLiteral("

Chunk B of 2

")); - } - - void dataInvalidForOutOfRange() - { - Ctx ctx; ReadingModel model(*ctx.store); - FakeReader reader; - model.setReader(&reader); - - QModelIndex badIdx = model.index(99, 0); - QVERIFY(!model.data(badIdx, ReadingModel::ContentRole).isValid()); - } - void currentChapterDerivedFromScroll() { Ctx ctx; ReadingModel model(*ctx.store); @@ -259,39 +258,6 @@ private slots: QCOMPARE(model.totalChapters(), 0); QCOMPARE(model.progress(), 0.0); QVERIFY(model.chapterTitle().isEmpty()); - QCOMPARE(model.rowCount(QModelIndex()), 0); - } - - void roleNamesContainsContent() - { - Ctx ctx; ReadingModel model(*ctx.store); - QHash roles = model.roleNames(); - QVERIFY(roles.contains(ReadingModel::ContentRole)); - QCOMPARE(roles.value(ReadingModel::ContentRole), QByteArray("content")); - } - - void initialPageState() - { - Ctx ctx; ReadingModel model(*ctx.store); - QCOMPARE(model.currentPage(), 0); - QCOMPARE(model.totalPages(), 0); - } - - void setScrollInfoUpdatesCurrentPage() - { - Ctx ctx; ReadingModel model(*ctx.store); - FakeReader reader; - model.setReader(&reader); - - model.setScrollInfo(0, 0.0); - // If m_totalPixelHeight is 0, yOffset=0, yOffset/totalHeight is NaN. - // qBound(0, NaN, 1) is 0. 0 * 6 * 1.5 = 0. - QCOMPARE(model.currentPage(), 0); - - model.setScrollInfo(3, 100.0); - // If m_totalPixelHeight is 0, yOffset=100, yOffset/totalHeight is Infinity. - // qBound(0, Inf, 1) is 1.0. 1.0 * 6 * 1.5 = 9. - QCOMPARE(model.currentPage(), 9); } void hasChaptersFalseForSingleChapter() @@ -318,117 +284,37 @@ private slots: QVERIFY(!model.hasChapters()); } - // --- Cover image tests --- - - void coverImagePrependedToChunks() + void mangaModeDetectionAndPagination() { - FakeReader reader; Ctx ctx; ReadingModel model(*ctx.store); - model.setCoverImageUrl("image://epub/OEBPS/cover.jpg"); - model.setReader(&reader); - - // 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")); - } + FakeMangaReader reader; + QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady); - void coverImageNotAddedWhenUrlEmpty() - { - FakeReader reader; - Ctx ctx; ReadingModel model(*ctx.store); - model.setReader(&reader); - model.setCoverImageUrl(""); - - // Should have only original chunks (no cover) - QCOMPARE(model.rowCount(QModelIndex()), 6); - } - - void chapterNavigationSkipsCoverImage() - { - FakeReader reader; - Ctx ctx; ReadingModel model(*ctx.store); - model.setCoverImageUrl("image://epub/OEBPS/cover.jpg"); model.setReader(&reader); - // Chapter 0 should start at chunk 1 (after cover image) - QSignalSpy spy(&model, &ReadingModel::scrollToChunkRequested); - model.goToChapter(0); - QCOMPARE(spy.count(), 1); - QCOMPARE(spy.takeFirst().at(0).toInt(), 1); // Should scroll to chunk 1 (after cover) + QVERIFY(model.isMangaMode()); + QCOMPARE(model.imageUrlForChunk(0), QStringLiteral("image://cbz/0.jpg")); + QCOMPARE(model.imageUrlForChunk(1), QStringLiteral("image://cbz/1.jpg")); + QCOMPARE(model.imageUrlForChunk(2), QStringLiteral("image://cbz/2.jpg")); + QCOMPARE(model.totalPagePairs(), 3); // portrait mode: each chunk is solo - // Navigate to chapter 2 (last chapter in FakeReader) - model.goToChapter(2); - QCOMPARE(spy.count(), 1); - QCOMPARE(spy.takeFirst().at(0).toInt(), 5); // Should scroll to chunk 5 (chapter 2 start) - } + // restoreReady should be queued and emitted + QTRY_COMPARE(restoreSpy.count(), 1); + QCOMPARE(restoreSpy.first().at(0).toInt(), 0); - void coverImageSetAfterReaderReloadsChunks() - { - FakeReader reader; - Ctx ctx; ReadingModel model(*ctx.store); - model.setReader(&reader); - QCOMPARE(model.rowCount(QModelIndex()), 6); // no cover yet - - model.setCoverImageUrl(QStringLiteral("image://epub/OEBPS/cover.jpg")); - // setCoverImageUrl doesn't call loadAllChapters(), it only sets the URL. - // The URL is used when loadAllChapters() is called (via setReader). - // If we want to update it, we might need to re-set the reader or call a reload. - // Looking at ReadingModel.cpp, setCoverImageUrl ONLY sets the member. - - model.setReader(&reader); // Re-set to reload with cover - QCOMPARE(model.rowCount(QModelIndex()), 7); // 1 cover + 6 - QString first = model.data(model.index(0, 0), ReadingModel::ContentRole).toString(); - QVERIFY(first.contains(QStringLiteral("class=\"cover-image\""))); - QVERIFY(first.contains(QStringLiteral("image://epub/OEBPS/cover.jpg"))); - } - - void clearCoverImageUrlRemovesCover() - { - FakeReader reader; - Ctx ctx; ReadingModel model(*ctx.store); - model.setCoverImageUrl(QStringLiteral("image://epub/OEBPS/cover.jpg")); - model.setReader(&reader); - QCOMPARE(model.rowCount(QModelIndex()), 7); // 1 cover + 6 - - model.setCoverImageUrl(QStringLiteral("")); - model.setReader(&reader); // Re-set to reload without cover - - QCOMPARE(model.rowCount(QModelIndex()), 6); // cover removed - QString first = model.data(model.index(0, 0), ReadingModel::ContentRole).toString(); - QVERIFY(!first.contains(QStringLiteral("class=\"cover-image\""))); - } - - void roleNamesHasNewRoles() - { - Ctx ctx; ReadingModel model(*ctx.store); - auto roles = model.roleNames(); - QVERIFY(roles.contains(ReadingModel::PixelHeightRole)); - QVERIFY(roles.contains(ReadingModel::ChapterRole)); - QCOMPARE(roles.value(ReadingModel::PixelHeightRole), QByteArray("pixelHeight")); - QCOMPARE(roles.value(ReadingModel::ChapterRole), QByteArray("chapter")); - } - - void totalPixelHeightInitiallyZero() - { - Ctx ctx; ReadingModel model(*ctx.store); - QCOMPARE(model.totalPixelHeight(), 0.0); - } - - void totalPixelHeightResetOnReaderSet() - { - Ctx ctx; ReadingModel model(*ctx.store); - FakeReader reader; - - QSignalSpy spy(&model, &ReadingModel::totalPixelHeightChanged); - model.setReader(&reader); - - // loadAllChapters resets m_totalPixelHeight to 0 and emits the signal - QVERIFY(spy.count() >= 1); - QCOMPARE(model.totalPixelHeight(), 0.0); // unmeasured chunks have pixelHeight -1, not yet summed + // Landscape mode pairs portrait pages + model.setMangaLandscape(true); + // With pageShift ON (default): chunk 0 solo (cover), chunk 1 solo (shift), chunk 2 solo -> 3 pairs + // If pageShift OFF: chunk 0 solo (cover), chunks 1 and 2 paired -> 2 pairs + model.setPageShift(false); + QCOMPARE(model.totalPagePairs(), 2); + QVariantList pair0 = model.pagePair(0); + QCOMPARE(pair0.size(), 1); + QCOMPARE(pair0.at(0).toInt(), 0); + QVariantList pair1 = model.pagePair(1); + QCOMPARE(pair1.size(), 2); + QCOMPARE(pair1.at(0).toInt(), 1); + QCOMPARE(pair1.at(1).toInt(), 2); } }; diff --git a/tests/book/BookTest.cpp b/tests/book/BookTest.cpp index b1d9391..8e310bb 100644 --- a/tests/book/BookTest.cpp +++ b/tests/book/BookTest.cpp @@ -207,24 +207,14 @@ private slots: ctx.book->openFromPath(path); QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); - ctx.book->saveCurrentPosition(3, 17); + ctx.book->saveCurrentPosition(3, false, true); const QByteArray hash = ctx.book->reader()->contentHash(); QVERIFY(!hash.isEmpty()); const BookPosition pos = ctx.store->load(hash); QCOMPARE(pos.chunkIndex, 3); - QCOMPARE(pos.intraOffset, 17); - } - - void contentWidthSignal() - { - Ctx ctx; - QSignalSpy spy(ctx.book, &Book::contentWidthChanged); - ctx.book->setContentWidth(800); - QCOMPARE(spy.count(), 1); - QCOMPARE(spy.first().first().toInt(), 800); - ctx.book->setContentWidth(800); // no-op - QCOMPARE(spy.count(), 1); + QCOMPARE(pos.mangaRTL, false); + QCOMPARE(pos.pageShift, true); } }; diff --git a/tests/state/BookPositionStoreTest.cpp b/tests/state/BookPositionStoreTest.cpp index b51c510..7b90535 100644 --- a/tests/state/BookPositionStoreTest.cpp +++ b/tests/state/BookPositionStoreTest.cpp @@ -21,8 +21,9 @@ private slots: BookPositionStore store(appState); const BookPosition pos = store.load(QByteArray("nonexistent")); - QCOMPARE(pos.chunkIndex, 0); - QCOMPARE(pos.intraOffset, 0); + QCOMPARE(pos.chunkIndex, 0); + QCOMPARE(pos.pageShift, true); + QCOMPARE(pos.mangaRTL, true); } void saveAndLoad() @@ -35,10 +36,11 @@ private slots: BookPositionStore store(appState); const QByteArray hash = QByteArray("abc123deadbeef"); - store.save(hash, 7, 42); + store.save(hash, 7, false, false); const BookPosition pos = store.load(hash); - QCOMPARE(pos.chunkIndex, 7); - QCOMPARE(pos.intraOffset, 42); + QCOMPARE(pos.chunkIndex, 7); + QCOMPARE(pos.mangaRTL, false); + QCOMPARE(pos.pageShift, false); } void separateHashesStoredIndependently() @@ -50,13 +52,13 @@ private slots: AppState appState(s); BookPositionStore store(appState); - store.save(QByteArray("hash1"), 1, 10); - store.save(QByteArray("hash2"), 2, 20); + store.save(QByteArray("hash1"), 1, true, false); + store.save(QByteArray("hash2"), 2, false, true); - QCOMPARE(store.load(QByteArray("hash1")).chunkIndex, 1); - QCOMPARE(store.load(QByteArray("hash2")).chunkIndex, 2); - QCOMPARE(store.load(QByteArray("hash1")).intraOffset, 10); - QCOMPARE(store.load(QByteArray("hash2")).intraOffset, 20); + QCOMPARE(store.load(QByteArray("hash1")).chunkIndex, 1); + QCOMPARE(store.load(QByteArray("hash2")).chunkIndex, 2); + QCOMPARE(store.load(QByteArray("hash1")).mangaRTL, true); + QCOMPARE(store.load(QByteArray("hash2")).mangaRTL, false); } void overwriteExistingPosition() @@ -69,12 +71,13 @@ private slots: BookPositionStore store(appState); const QByteArray hash = QByteArray("overwrite-hash"); - store.save(hash, 3, 30); - store.save(hash, 5, 55); + store.save(hash, 3, true, true); + store.save(hash, 5, false, false); const BookPosition pos = store.load(hash); - QCOMPARE(pos.chunkIndex, 5); - QCOMPARE(pos.intraOffset, 55); + QCOMPARE(pos.chunkIndex, 5); + QCOMPARE(pos.mangaRTL, false); + QCOMPARE(pos.pageShift, false); } void emptyHashIgnored() @@ -87,10 +90,9 @@ private slots: BookPositionStore store(appState); // Neither save nor load should crash with an empty hash - store.save(QByteArray(), 1, 1); + store.save(QByteArray(), 1, true, true); const BookPosition pos = store.load(QByteArray()); - QCOMPARE(pos.chunkIndex, 0); - QCOMPARE(pos.intraOffset, 0); + QCOMPARE(pos.chunkIndex, 0); } };