diff --git a/CMakeLists.txt b/CMakeLists.txt index cba044c..f8059e7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -41,8 +41,6 @@ set(SOURCES src/backend/AppState.cpp src/backend/AppCoordinator.h src/backend/AppCoordinator.cpp - src/backend/HistoryBookModel.h - src/backend/HistoryBookModel.cpp src/backend/HistoryModel.h src/backend/HistoryModel.cpp src/backend/ReadingModel.h @@ -57,8 +55,6 @@ set(SOURCES src/backend/state/BookPositionStore.cpp src/backend/book/Book.h src/backend/book/Book.cpp - src/backend/IImageProvider.h - src/backend/ZipUtils.h src/backend/IFileDialogService.h src/backend/NativeFileDialogService.h src/backend/NativeFileDialogService.cpp @@ -73,9 +69,6 @@ set(SOURCES src/backend/formats/sources/DirByteSource.cpp src/backend/formats/comic/ComicReader.h src/backend/formats/comic/ComicReader.cpp - src/backend/formats/comic/CbzReader.h - src/backend/formats/comic/CbrReader.h - src/backend/formats/comic/FolderReader.h src/backend/formats/AsyncImageResponse.h src/backend/formats/AsyncImageResponse.cpp src/backend/formats/ImageUrl.h @@ -261,7 +254,6 @@ add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp src/backend/formats/FormatRegistry.cpp src/backend/AppState.cpp src/backend/state/BookPositionStore.cpp - src/backend/HistoryBookModel.cpp src/backend/HistoryModel.cpp ${COMIC_SOURCES}) target_link_libraries(ReadingModelTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml) @@ -286,14 +278,11 @@ add_asteria_test(BookPositionStoreTest tests/state/BookPositionStoreTest.cpp add_asteria_test(BookTest tests/book/BookTest.cpp src/backend/book/Book.cpp - src/backend/AppState.cpp - src/backend/state/BookPositionStore.cpp src/backend/formats/FormatRegistry.cpp src/backend/formats/AsyncImageResponse.cpp - src/backend/formats/EntryImageProvider.cpp src/backend/IFileDialogService.h src/backend/NativeFileDialogService.cpp - ${COMIC_READER_SOURCES}) + ${COMIC_SOURCES}) target_link_libraries(BookTest PRIVATE Qt6::Concurrent Qt6::Widgets PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui Qt6::Quick) set_tests_properties(BookTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") @@ -305,14 +294,15 @@ add_asteria_test(EntryImageProviderTest tests/EntryImageProviderTest.cpp target_link_libraries(EntryImageProviderTest PRIVATE PkgConfig::MINIZIP Qt6::Quick Qt6::Gui) set_tests_properties(EntryImageProviderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") -add_asteria_test(HistoryBookModelTest tests/HistoryBookModelTest.cpp - src/backend/HistoryBookModel.cpp +add_asteria_test(HistoryModelTest tests/HistoryModelTest.cpp + src/backend/HistoryModel.cpp + src/backend/AppState.cpp src/backend/formats/AsyncImageResponse.cpp src/backend/formats/FormatRegistry.cpp ${COMIC_SOURCES}) -target_link_libraries(HistoryBookModelTest PRIVATE +target_link_libraries(HistoryModelTest PRIVATE Qt6::Concurrent Qt6::Quick Qt6::Gui Qt6::Xml PkgConfig::MINIZIP PkgConfig::LIBARCHIVE) -set_tests_properties(HistoryBookModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") +set_tests_properties(HistoryModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") add_asteria_test(FileIconProviderTest tests/FileIconProviderTest.cpp src/backend/formats/FileIconProvider.cpp) diff --git a/src/backend/AppCoordinator.cpp b/src/backend/AppCoordinator.cpp index 92825c6..31862c7 100644 --- a/src/backend/AppCoordinator.cpp +++ b/src/backend/AppCoordinator.cpp @@ -2,15 +2,12 @@ #include "AppState.h" #include "HistoryModel.h" -#include "IImageProvider.h" #include "ReadingModel.h" #include "book/Book.h" -#include "formats/FormatRegistry.h" #include "state/ReadingPreferences.h" #include "state/UiState.h" #include -#include #include AppCoordinator::AppCoordinator(Book &book, @@ -20,8 +17,6 @@ AppCoordinator::AppCoordinator(Book &book, ReadingPreferences &readingPreferences, AppState &appState, QSettings &settings, - FormatRegistry &formatRegistry, - QQmlApplicationEngine &engine, QObject *parent) : QObject(parent) , m_book(book) @@ -31,11 +26,9 @@ AppCoordinator::AppCoordinator(Book &book, , m_readingPreferences(readingPreferences) , m_appState(appState) , m_settings(settings) - , m_formatRegistry(formatRegistry) - , m_engine(engine) { connect(&m_book, &Book::willOpenNewBook, this, &AppCoordinator::onWillOpenNewBook); - connect(&m_book, &Book::positionSaved, this, &AppCoordinator::onPositionSaved); + connect(&m_readingModel, &ReadingModel::positionSaved, this, &AppCoordinator::onPositionSaved); connect(&m_book, &Book::bookChanged, this, &AppCoordinator::onBookChanged); connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, @@ -52,14 +45,13 @@ void AppCoordinator::onWillOpenNewBook() // Real-time history update: fired when position is saved. void AppCoordinator::onPositionSaved() { - m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress()); + if (m_book.hasBook()) + m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress()); } -// After the new reader is installed: wire up image provider + ReadingModel +// After the new reader is installed: configure ReadingModel void AppCoordinator::onBookChanged() { - m_currentImageProvider = nullptr; - if (!m_book.hasBook()) { m_readingModel.setReader(nullptr); return; @@ -67,26 +59,12 @@ void AppCoordinator::onBookChanged() FormatReader *reader = m_book.reader(); const QString filePath = reader->filePath(); - - IImageProvider *provider = m_formatRegistry.createImageProvider(filePath); - if (provider) { - m_engine.removeImageProvider(provider->scheme()); - m_engine.addImageProvider(provider->scheme(), provider); - provider->setFilePath(filePath); - m_currentImageProvider = provider; - - if (!reader->coverImagePath().isEmpty()) - m_book.setCoverImageUrl(provider->coverImageUrl(reader->coverImagePath())); - } - m_readingModel.setReader(reader); - m_uiState.setLastFilePath(filePath); m_historyModel.addOrUpdateBook(filePath, -1.0); } // Quit: flush everything to persistent storage. -// Scroll position was last saved by PageView's scroll tracker; we save library progress here. void AppCoordinator::onAboutToQuit() { if (m_book.hasBook()) { @@ -96,18 +74,9 @@ void AppCoordinator::onAboutToQuit() m_uiState.setLastFilePath(QString()); } + m_historyModel.save(m_appState); m_readingPreferences.save(); m_uiState.save(); - QList items; - for (int i = 0; i < m_historyModel.rowCount(); ++i) { - items.append({ - {QStringLiteral("filePath"), m_historyModel.filePath(i)}, - {QStringLiteral("progress"), m_historyModel.progress(i)}, - {QStringLiteral("lastOpened"), m_historyModel.lastOpened(i)}, - }); - } - m_appState.saveArray(QStringLiteral("history"), items); - qInfo() << "Settings saved to:" << m_settings.fileName(); } diff --git a/src/backend/AppCoordinator.h b/src/backend/AppCoordinator.h index bd6a9ba..06017e6 100644 --- a/src/backend/AppCoordinator.h +++ b/src/backend/AppCoordinator.h @@ -4,19 +4,14 @@ class AppState; class Book; -class FormatRegistry; class HistoryModel; -class IImageProvider; -class QQmlApplicationEngine; class QSettings; class ReadingModel; class ReadingPreferences; class UiState; -// Wires the top-level objects together: reacts to book changes by swapping -// image providers and configuring the reading model, keeps history and -// persistent state in sync, and flushes everything on quit. main() only -// constructs the object graph; the coordination lives here. +// Wires the top-level objects together: reacts to book changes, +// keeps history and persistent state in sync, and flushes everything on quit. class AppCoordinator : public QObject { Q_OBJECT public: @@ -27,8 +22,6 @@ public: ReadingPreferences &readingPreferences, AppState &appState, QSettings &settings, - FormatRegistry &formatRegistry, - QQmlApplicationEngine &engine, QObject *parent = nullptr); private slots: @@ -45,8 +38,4 @@ private: ReadingPreferences &m_readingPreferences; AppState &m_appState; QSettings &m_settings; - FormatRegistry &m_formatRegistry; - QQmlApplicationEngine &m_engine; - - IImageProvider *m_currentImageProvider = nullptr; }; diff --git a/src/backend/FormatReader.h b/src/backend/FormatReader.h index 99cb549..c5dfea1 100644 --- a/src/backend/FormatReader.h +++ b/src/backend/FormatReader.h @@ -4,31 +4,55 @@ #include #include #include +#include #include +enum class ReadingMode { + Comic, // Paged / paired image mode (CBZ, CBR, Folder) + Text // Continuous / chaptered text mode (EPUB, FB2, TXT) +}; + struct PageInfo { QString imageUrl; QSize naturalSize; }; +struct TocEntry { + QString title; + int chapterIndex = 0; + int depth = 0; +}; + +struct Chapter { + int index = 0; + QString title; + QStringList chunks; // Standalone HTML/text fragments for virtualized rendering +}; + class FormatReader { public: virtual ~FormatReader() = default; + virtual ReadingMode mode() const = 0; virtual bool open(const QString &filePath) = 0; - virtual bool loadMetadata(const QString &filePath) = 0; - virtual QString lastError() = 0; - virtual QString filePath() = 0; - virtual QString title() = 0; - virtual QString author() = 0; - virtual QString coverImagePath() = 0; - // MD5 of file contents, computed once during open(). Used as a stable key for - // per-book state (bookmarks, etc.) that survives file renames. - virtual QByteArray contentHash() = 0; - // Returns the lowercase file extension this reader handles (e.g. "cbz", "cbr"). - virtual QString fileType() const = 0; + virtual bool loadMetadata(const QString &filePath) { return open(filePath); } + virtual QString lastError() const = 0; - virtual QVector pages() const = 0; + virtual QString filePath() const = 0; + virtual QString title() const = 0; + virtual QString author() const { return {}; } + virtual QString coverImageUrl() const { return {}; } + // MD5 of file contents, computed once during open(). Used as a stable key for + // per-book state (bookmarks, position, etc.) that survives file renames. + virtual QByteArray contentHash() const = 0; + + // Comic mode (default empty for text readers) + virtual QVector pages() const { return {}; } + + // Text mode (default empty for comic readers) + virtual int chapterCount() const { return 0; } + virtual Chapter loadChapter(int index) const { Q_UNUSED(index); return {}; } + virtual QVector tableOfContents() const { return {}; } }; #endif // FORMATREADER_H diff --git a/src/backend/HistoryBookModel.cpp b/src/backend/HistoryBookModel.cpp deleted file mode 100644 index 7ee5abe..0000000 --- a/src/backend/HistoryBookModel.cpp +++ /dev/null @@ -1,120 +0,0 @@ -#include "HistoryBookModel.h" -#include "FormatReader.h" -#include "IImageProvider.h" -#include -#include -#include - -HistoryBookModel::HistoryBookModel(const QString &filePath, double progress, const QString &lastOpened, FormatRegistry ®istry, QObject *parent) - : QObject(parent) - , m_filePath(filePath) - , m_progress(progress) - , m_lastOpened(lastOpened) - , m_registry(registry) -{ -} - -HistoryBookModel::~HistoryBookModel() -{ - if (m_metadataFuture.isRunning()) - m_metadataFuture.waitForFinished(); -} - -QString HistoryBookModel::filePath() const -{ - return m_filePath; -} - -double HistoryBookModel::progress() const -{ - return m_progress; -} - -void HistoryBookModel::setProgress(double progress) -{ - if (qFuzzyCompare(m_progress, progress)) - return; - m_progress = progress; - emit progressChanged(); -} - -QString HistoryBookModel::lastOpened() const -{ - return m_lastOpened; -} - -void HistoryBookModel::setLastOpened(const QString &lastOpened) -{ - if (m_lastOpened == lastOpened) - return; - m_lastOpened = lastOpened; - emit lastOpenedChanged(); -} - -QString HistoryBookModel::title() const -{ - return m_title; -} - -QString HistoryBookModel::author() const -{ - return m_author; -} - -QString HistoryBookModel::format() const -{ - if (QFileInfo(m_filePath).isDir()) - return QStringLiteral("Folder"); - return m_filePath.section('.', -1).toUpper(); -} - -QString HistoryBookModel::coverImageUrl() const -{ - return m_coverImageUrl; -} - -void HistoryBookModel::loadMetadata() -{ - if (m_metadataLoaded || m_filePath.isEmpty() || m_metadataFuture.isRunning()) - return; - - QPointer self = this; - QString filePath = m_filePath; - - FormatRegistry *registry = &m_registry; - m_metadataFuture = QtConcurrent::run([self, filePath, registry]() { - auto reader = registry->createReader(filePath); - QString title; - QString author; - bool success = false; - - if (reader && reader->loadMetadata(filePath)) { - title = reader->title(); - author = reader->author(); - success = true; - } - - QString coverImageUrl; - if (success) { - QString coverPath = reader->coverImagePath(); - if (!coverPath.isEmpty()) { - std::unique_ptr provider(registry->createImageProvider(filePath)); - if (provider) { - provider->setFilePath(filePath); - coverImageUrl = provider->coverImageUrl(coverPath); - } - } - } - - QMetaObject::invokeMethod(self.data(), [self, title, author, coverImageUrl, success]() { - if (!self || !success) - return; - self->m_title = title; - self->m_author = author; - self->m_coverImageUrl = coverImageUrl; - self->m_metadataLoaded = true; - emit self->coverImageLoaded(); - emit self->metadataLoaded(); - }, Qt::QueuedConnection); - }); -} \ No newline at end of file diff --git a/src/backend/HistoryBookModel.h b/src/backend/HistoryBookModel.h deleted file mode 100644 index e3ba0a9..0000000 --- a/src/backend/HistoryBookModel.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef HISTORYBOOKMODEL_H -#define HISTORYBOOKMODEL_H - -#include -#include -#include -#include - -#include "formats/FormatRegistry.h" - -class FormatReader; - -class HistoryBookModel : public QObject { - Q_OBJECT - Q_PROPERTY(QString filePath READ filePath CONSTANT) - Q_PROPERTY(double progress READ progress WRITE setProgress NOTIFY progressChanged) - Q_PROPERTY(QString lastOpened READ lastOpened WRITE setLastOpened NOTIFY lastOpenedChanged) - Q_PROPERTY(QString title READ title NOTIFY metadataLoaded) - Q_PROPERTY(QString author READ author NOTIFY metadataLoaded) - Q_PROPERTY(QString format READ format NOTIFY metadataLoaded) - Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY coverImageLoaded) - -public: - explicit HistoryBookModel(const QString &filePath, double progress, const QString &lastOpened, FormatRegistry ®istry, QObject *parent = nullptr); - ~HistoryBookModel() override; - - QString filePath() const; - double progress() const; - void setProgress(double progress); - - QString lastOpened() const; - void setLastOpened(const QString &lastOpened); - - QString title() const; - QString author() const; - QString format() const; - QString coverImageUrl() const; - - void loadMetadata(); - -signals: - void progressChanged(); - void lastOpenedChanged(); - void metadataLoaded(); - void coverImageLoaded(); - -private: - QString m_filePath; - double m_progress = 0.0; - QString m_lastOpened; - QString m_title; - QString m_author; - QString m_coverImageUrl; - bool m_metadataLoaded = false; - QFuture m_metadataFuture; - FormatRegistry &m_registry; -}; - -#endif // HISTORYBOOKMODEL_H \ No newline at end of file diff --git a/src/backend/HistoryModel.cpp b/src/backend/HistoryModel.cpp index 8f5e851..e697a0d 100644 --- a/src/backend/HistoryModel.cpp +++ b/src/backend/HistoryModel.cpp @@ -1,100 +1,133 @@ #include "HistoryModel.h" -#include "HistoryBookModel.h" +#include "AppState.h" +#include "FormatReader.h" +#include "formats/FormatRegistry.h" + #include +#include +#include +#include + +namespace { +QString formatForPath(const QString &filePath) +{ + if (QFileInfo(filePath).isDir()) + return QStringLiteral("Folder"); + return filePath.section('.', -1).toUpper(); +} +} HistoryModel::HistoryModel(FormatRegistry ®istry, QObject *parent) : QAbstractListModel(parent) , m_registry(registry) { - // Initialize role names - m_roleNames[FilePathRole] = "filePath"; - m_roleNames[TitleRole] = "title"; - m_roleNames[AuthorRole] = "author"; - m_roleNames[FormatRole] = "format"; - m_roleNames[ProgressRole] = "progress"; - m_roleNames[LastOpenedRole] = "lastOpened"; - m_roleNames[CoverImageUrlRole] = "coverImageUrl"; } -HistoryModel::~HistoryModel() -{ - clear(); -} +HistoryModel::~HistoryModel() = default; int HistoryModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; - return m_books.count(); + return m_entries.size(); } QVariant HistoryModel::data(const QModelIndex &index, int role) const { - if (!index.isValid() || index.row() < 0 || index.row() >= m_books.count()) - return QVariant(); + if (!index.isValid() || index.row() < 0 || index.row() >= m_entries.size()) + return {}; - HistoryBookModel* book = m_books.at(index.row()); - if (!book) - return QVariant(); - + const auto &entry = m_entries.at(index.row()); switch (role) { - case FilePathRole: - return book->filePath(); - case TitleRole: - return book->title(); - case AuthorRole: - return book->author(); - case FormatRole: - return book->format(); - case ProgressRole: - return book->progress(); - case LastOpenedRole: - return book->lastOpened(); - case CoverImageUrlRole: - return book->coverImageUrl(); - default: - return QVariant(); + case FilePathRole: + return entry.filePath; + case TitleRole: + return entry.title; + case AuthorRole: + return entry.author; + case FormatRole: + return entry.format; + case ProgressRole: + return entry.progress; + case LastOpenedRole: + return entry.lastOpened; + case CoverImageUrlRole: + return entry.coverImageUrl; + default: + return {}; } } bool HistoryModel::setData(const QModelIndex &index, const QVariant &value, int role) { - if (!index.isValid() || index.row() < 0 || index.row() >= m_books.count()) + if (!index.isValid() || index.row() < 0 || index.row() >= m_entries.size()) return false; - HistoryBookModel* book = m_books.at(index.row()); - + auto &entry = m_entries[index.row()]; switch (role) { - case ProgressRole: - book->setProgress(value.toDouble()); - emit dataChanged(index, index, {ProgressRole}); - return true; - case LastOpenedRole: - book->setLastOpened(value.toString()); - emit dataChanged(index, index, {LastOpenedRole}); - return true; - default: - return false; + case ProgressRole: + entry.progress = value.toDouble(); + emit dataChanged(index, index, {ProgressRole}); + return true; + case LastOpenedRole: + entry.lastOpened = value.toString(); + emit dataChanged(index, index, {LastOpenedRole}); + return true; + default: + return false; } } QHash HistoryModel::roleNames() const { - return m_roleNames; + return { + {FilePathRole, "filePath"}, + {TitleRole, "title"}, + {AuthorRole, "author"}, + {FormatRole, "format"}, + {ProgressRole, "progress"}, + {LastOpenedRole, "lastOpened"}, + {CoverImageUrlRole, "coverImageUrl"} + }; +} + +void HistoryModel::load(AppState &state) +{ + clear(); + for (const QVariantMap &item : state.loadArray(QStringLiteral("history"))) { + const QString fp = item.value(QStringLiteral("filePath")).toString(); + if (fp.isEmpty()) continue; + double progress = item.value(QStringLiteral("progress"), 0.0).toDouble(); + progress = qBound(0.0, progress, 1.0); + const QString lo = item.value(QStringLiteral("lastOpened")).toString(); + addOrUpdateBook(fp, progress, lo); + } +} + +void HistoryModel::save(AppState &state) const +{ + QList items; + items.reserve(m_entries.size()); + for (const auto &entry : m_entries) { + items.append({ + {QStringLiteral("filePath"), entry.filePath}, + {QStringLiteral("progress"), entry.progress}, + {QStringLiteral("lastOpened"), entry.lastOpened}, + }); + } + state.saveArray(QStringLiteral("history"), items); } void HistoryModel::addOrUpdateBook(const QString &filePath, double progress, const QString &lastOpened) { - // Check if book already exists - for (int i = 0; i < m_books.size(); i++) { - if (m_books[i]->filePath() == filePath) { - HistoryBookModel* existingBook = m_books[i]; - existingBook->setProgress(progress); - existingBook->setLastOpened(lastOpened); + for (int i = 0; i < m_entries.size(); ++i) { + if (m_entries[i].filePath == filePath) { + m_entries[i].progress = progress; + m_entries[i].lastOpened = lastOpened; if (i != 0) { beginMoveRows(QModelIndex(), i, i, QModelIndex(), 0); - m_books.move(i, 0); + m_entries.move(i, 0); endMoveRows(); } emit dataChanged(createIndex(0, 0), createIndex(0, 0), {ProgressRole, LastOpenedRole}); @@ -102,106 +135,114 @@ void HistoryModel::addOrUpdateBook(const QString &filePath, double progress, con } } - // New book — HistoryModel takes ownership via parent - auto* book = new HistoryBookModel(filePath, progress, lastOpened, m_registry, this); - connect(book, &HistoryBookModel::metadataLoaded, this, &HistoryModel::onBookMetadataLoaded); + HistoryEntry entry; + entry.filePath = filePath; + entry.progress = progress; + entry.lastOpened = lastOpened; + entry.format = formatForPath(filePath); beginInsertRows(QModelIndex(), 0, 0); - m_books.prepend(book); + m_entries.prepend(entry); endInsertRows(); - emit countChanged(); - book->loadMetadata(); + + requestMetadata(filePath); +} + +void HistoryModel::addOrUpdateBook(const QString &filePath, double progress) +{ + double resolvedProgress = progress; + if (progress < 0.0) { + for (const auto &entry : m_entries) { + if (entry.filePath == filePath) { + resolvedProgress = entry.progress; + break; + } + } + if (resolvedProgress < 0.0) + resolvedProgress = 0.0; + } + addOrUpdateBook(filePath, resolvedProgress, + QDateTime::currentDateTime().toString(Qt::ISODate)); } void HistoryModel::removeBook(const QString &filePath) { - for (int i = 0; i < m_books.size(); i++) { - if (m_books[i]->filePath() == filePath) { - HistoryBookModel* book = m_books[i]; - + for (int i = 0; i < m_entries.size(); ++i) { + if (m_entries[i].filePath == filePath) { beginRemoveRows(QModelIndex(), i, i); - m_books.removeAt(i); + m_entries.removeAt(i); endRemoveRows(); - - book->deleteLater(); emit countChanged(); return; } } } -HistoryBookModel* HistoryModel::findBook(const QString &filePath) const -{ - for (HistoryBookModel* book : m_books) { - if (book->filePath() == filePath) { - return book; - } - } - return nullptr; -} - void HistoryModel::clear() { - if (m_books.isEmpty()) + if (m_entries.isEmpty()) return; - beginRemoveRows(QModelIndex(), 0, m_books.size() - 1); - - for (HistoryBookModel* book : m_books) - book->deleteLater(); - - m_books.clear(); + beginRemoveRows(QModelIndex(), 0, m_entries.size() - 1); + m_entries.clear(); endRemoveRows(); - emit countChanged(); } -void HistoryModel::addOrUpdateBook(const QString &filePath, double progress) -{ - // Sentinel: progress < 0 means "preserve the existing progress value" - double resolvedProgress = progress; - if (progress < 0.0) { - HistoryBookModel *existing = findBook(filePath); - resolvedProgress = existing ? existing->progress() : 0.0; - } - addOrUpdateBook(filePath, resolvedProgress, - QDateTime::currentDateTime().toString(Qt::ISODate)); -} - QString HistoryModel::filePath(int index) const { - if (index < 0 || index >= m_books.size()) return {}; - return m_books.at(index)->filePath(); + if (index < 0 || index >= m_entries.size()) return {}; + return m_entries.at(index).filePath; } double HistoryModel::progress(int index) const { - if (index < 0 || index >= m_books.size()) return 0.0; - return m_books.at(index)->progress(); + if (index < 0 || index >= m_entries.size()) return 0.0; + return m_entries.at(index).progress; } QString HistoryModel::lastOpened(int index) const { - if (index < 0 || index >= m_books.size()) return {}; - return m_books.at(index)->lastOpened(); + if (index < 0 || index >= m_entries.size()) return {}; + return m_entries.at(index).lastOpened; } -QList HistoryModel::books() const +void HistoryModel::requestMetadata(const QString &filePath) { - return m_books; + FormatRegistry *registry = &m_registry; + QPointer self(this); + + (void)QtConcurrent::run([self, filePath, registry]() { + auto reader = registry->createReader(filePath); + QString title; + QString author; + QString coverUrl; + bool ok = false; + + if (reader && reader->loadMetadata(filePath)) { + title = reader->title(); + author = reader->author(); + coverUrl = reader->coverImageUrl(); + ok = true; + } + + if (!self) + return; + + QMetaObject::invokeMethod(self.data(), [self, filePath, title, author, coverUrl, ok]() { + if (!self || !ok) return; + for (int i = 0; i < self->m_entries.size(); ++i) { + if (self->m_entries[i].filePath == filePath) { + self->m_entries[i].title = title; + self->m_entries[i].author = author; + self->m_entries[i].coverImageUrl = coverUrl; + self->m_entries[i].metadataLoaded = true; + const QModelIndex idx = self->createIndex(i, 0); + emit self->dataChanged(idx, idx, {TitleRole, AuthorRole, CoverImageUrlRole}); + break; + } + } + }, Qt::QueuedConnection); + }); } - -void HistoryModel::onBookMetadataLoaded() -{ - HistoryBookModel* book = qobject_cast(sender()); - if (!book) - return; - - int row = m_books.indexOf(book); - if (row >= 0) { - QModelIndex index = this->index(row); - // Update all metadata-related roles when metadata is loaded - emit dataChanged(index, index, {TitleRole, AuthorRole, CoverImageUrlRole}); - } -} \ No newline at end of file diff --git a/src/backend/HistoryModel.h b/src/backend/HistoryModel.h index 62b704f..46c97a1 100644 --- a/src/backend/HistoryModel.h +++ b/src/backend/HistoryModel.h @@ -2,12 +2,23 @@ #define HISTORYMODEL_H #include -#include #include +#include +#include -#include "formats/FormatRegistry.h" +class AppState; +class FormatRegistry; -class HistoryBookModel; +struct HistoryEntry { + QString filePath; + double progress = 0.0; + QString lastOpened; + QString title; + QString author; + QString format; + QString coverImageUrl; + bool metadataLoaded = false; +}; class HistoryModel : public QAbstractListModel { @@ -29,40 +40,32 @@ public: explicit HistoryModel(FormatRegistry ®istry, QObject *parent = nullptr); ~HistoryModel() override; - // QAbstractItemModel interface int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::DisplayRole) override; - - // Add QHash for role names QHash roleNames() const override; - // Methods to manage books + // Persistence with AppState + void load(AppState &state); + void save(AppState &state) const; + Q_INVOKABLE void addOrUpdateBook(const QString &filePath, double progress, const QString &lastOpened); - // Convenience overload: sentinel progress < 0 preserves the existing progress value. Q_INVOKABLE void addOrUpdateBook(const QString &filePath, double progress); Q_INVOKABLE void removeBook(const QString &filePath); - Q_INVOKABLE HistoryBookModel* findBook(const QString &filePath) const; Q_INVOKABLE void clear(); - // Indexed accessors for persistence (e.g., main.cpp's aboutToQuit loop). QString filePath(int index) const; double progress(int index) const; QString lastOpened(int index) const; - // Access to books for saving/loading - QList books() const; - signals: void countChanged(); -private slots: - void onBookMetadataLoaded(); - private: - QList m_books; - QHash m_roleNames; + void requestMetadata(const QString &filePath); + + QList m_entries; FormatRegistry &m_registry; }; -#endif // HISTORYMODEL_H \ No newline at end of file +#endif // HISTORYMODEL_H diff --git a/src/backend/IImageProvider.h b/src/backend/IImageProvider.h deleted file mode 100644 index d035e42..0000000 --- a/src/backend/IImageProvider.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once -#include -#include - -class IImageProvider : public QQuickAsyncImageProvider { -public: - virtual ~IImageProvider() = default; - virtual void setFilePath(const QString &filePath) = 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; - // The scheme this provider is registered under with the QML engine (e.g., "epub") - virtual QString scheme() const = 0; -}; diff --git a/src/backend/ReadingModel.cpp b/src/backend/ReadingModel.cpp index 12883e1..db3cf1c 100644 --- a/src/backend/ReadingModel.cpp +++ b/src/backend/ReadingModel.cpp @@ -2,20 +2,45 @@ #include ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent) - : QObject(parent) + : QAbstractListModel(parent) , m_positions(positions) { } ReadingModel::~ReadingModel() = default; +int ReadingModel::rowCount(const QModelIndex &parent) const +{ + if (parent.isValid() || !m_isTextMode) + return 0; + return m_currentChapterData.chunks.size(); +} + +QVariant ReadingModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid() || !m_isTextMode || index.row() < 0 || index.row() >= m_currentChapterData.chunks.size()) + return {}; + if (role == ContentRole) + return m_currentChapterData.chunks.at(index.row()); + return {}; +} + +QHash ReadingModel::roleNames() const +{ + return {{ContentRole, "content"}}; +} + +bool ReadingModel::isTextMode() const { return m_isTextMode; } int ReadingModel::totalPagePairs() const { return m_pagination.count(); } bool ReadingModel::pageShift() const { return m_pageShift; } bool ReadingModel::mangaRTL() const { return m_mangaRTL; } +int ReadingModel::currentChapter() const { return m_currentChapter; } +int ReadingModel::chapterCount() const { return m_chapterCount; } +QString ReadingModel::chapterTitle() const { return m_currentChapterData.title; } double ReadingModel::progress() const { - return qBound(0.0, m_yOffset, 1.0); + return qBound(0.0, m_progress, 1.0); } int ReadingModel::currentPage() const { return m_currentPage; } @@ -23,12 +48,74 @@ int ReadingModel::totalPages() const { return m_totalPages; } void ReadingModel::setScrollInfo(const int topChunkIndex, const qreal proportion) { - m_yOffset = proportion; + const qreal clamped = qBound(0.0, proportion, 1.0); + if (!qFuzzyCompare(m_progress, clamped)) { + m_progress = clamped; + emit progressChanged(); + } - const int page = pairIndexForChunk(topChunkIndex) + 1; - if (m_currentPage != page) { - m_currentPage = page; - emit currentPageChanged(); + if (m_isTextMode) { + const int page = topChunkIndex + 1; + if (m_currentPage != page) { + m_currentPage = page; + emit currentPageChanged(); + } + } else { + const int page = pairIndexForChunk(topChunkIndex) + 1; + if (m_currentPage != page) { + m_currentPage = page; + emit currentPageChanged(); + } + } + + saveCurrentPosition(topChunkIndex); +} + +void ReadingModel::saveCurrentPosition(int chunkIndex) +{ + if (!m_reader) return; + BookPosition pos; + pos.chapterIndex = m_currentChapter; + pos.chunkIndex = chunkIndex; + pos.progress = m_progress; + pos.pageShift = m_pageShift; + pos.mangaRTL = m_mangaRTL; + m_positions.save(m_reader->contentHash(), pos); + emit positionSaved(); +} + +void ReadingModel::loadChapter(int index) +{ + if (!m_reader || !m_isTextMode) + return; + if (index < 0 || index >= m_chapterCount) + return; + + beginResetModel(); + m_currentChapter = index; + m_currentChapterData = m_reader->loadChapter(index); + m_totalPages = m_currentChapterData.chunks.size(); + m_currentPage = qMin(1, m_totalPages); + endResetModel(); + + emit currentChapterChanged(); + emit totalPagesChanged(); + emit currentPageChanged(); +} + +void ReadingModel::nextChapter() +{ + if (m_isTextMode && m_currentChapter + 1 < m_chapterCount) { + loadChapter(m_currentChapter + 1); + saveCurrentPosition(0); + } +} + +void ReadingModel::previousChapter() +{ + if (m_isTextMode && m_currentChapter > 0) { + loadChapter(m_currentChapter - 1); + saveCurrentPosition(0); } } @@ -108,8 +195,7 @@ void ReadingModel::setPageShift(bool shift, int currentPairIndex) emit currentPageChanged(); } - if (m_reader) - m_positions.save(m_reader->contentHash(), currentChunk, m_mangaRTL, m_pageShift); + saveCurrentPosition(currentChunk); emit pageShiftChanged(); emit pagePairsRebuilt(newPair); @@ -121,7 +207,7 @@ void ReadingModel::setMangaRTL(bool rtl) m_mangaRTL = rtl; 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); + saveCurrentPosition(currentChunk >= 0 ? currentChunk : 0); } emit mangaRTLChanged(); } @@ -132,7 +218,7 @@ void ReadingModel::loadPages() if (m_currentPage != 0) { m_currentPage = 0; emit currentPageChanged(); } if (m_totalPages != 0) { m_totalPages = 0; emit totalPagesChanged(); } - if (m_reader) { + if (m_reader && !m_isTextMode) { m_pages = m_reader->pages(); } @@ -143,18 +229,44 @@ void ReadingModel::setReader(FormatReader *reader) { m_reader = reader; + beginResetModel(); + m_currentChapterData = {}; + endResetModel(); + + const bool oldTextMode = m_isTextMode; + m_isTextMode = (reader && reader->mode() == ReadingMode::Text); + if (oldTextMode != m_isTextMode) + emit modeChanged(); + int restoreChunk = 0; + int restoreChapter = 0; + if (reader) { const auto pos = m_positions.load(reader->contentHash()); - restoreChunk = pos.chunkIndex; - m_pageShift = pos.pageShift; - m_mangaRTL = pos.mangaRTL; + restoreChunk = pos.chunkIndex; + restoreChapter = pos.chapterIndex; + m_progress = pos.progress; + m_pageShift = pos.pageShift; + m_mangaRTL = pos.mangaRTL; + emit progressChanged(); } else { + m_progress = 0.0; m_pageShift = true; m_mangaRTL = true; + emit progressChanged(); } - loadPages(); + if (m_isTextMode && m_reader) { + m_chapterCount = m_reader->chapterCount(); + emit chapterCountChanged(); + loadChapter(qBound(0, restoreChapter, qMax(0, m_chapterCount - 1))); + } else { + m_chapterCount = 0; + m_currentChapter = 0; + emit chapterCountChanged(); + emit currentChapterChanged(); + loadPages(); + } if (m_reader) { QMetaObject::invokeMethod(this, [this, restoreChunk] { diff --git a/src/backend/ReadingModel.h b/src/backend/ReadingModel.h index ceafb0c..a70eb07 100644 --- a/src/backend/ReadingModel.h +++ b/src/backend/ReadingModel.h @@ -1,7 +1,7 @@ #ifndef READINGMODEL_H #define READINGMODEL_H -#include +#include #include #include #include @@ -10,31 +10,53 @@ #include "reading/MangaPagination.h" #include "state/BookPositionStore.h" -class ReadingModel : public QObject { +class ReadingModel : public QAbstractListModel { Q_OBJECT - Q_PROPERTY(double progress READ progress NOTIFY currentPageChanged) + Q_PROPERTY(bool isTextMode READ isTextMode NOTIFY modeChanged) + Q_PROPERTY(double progress READ progress NOTIFY progressChanged) Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged) Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged) + Q_PROPERTY(int currentChapter READ currentChapter NOTIFY currentChapterChanged) + Q_PROPERTY(int chapterCount READ chapterCount NOTIFY chapterCountChanged) + Q_PROPERTY(QString chapterTitle READ chapterTitle NOTIFY currentChapterChanged) Q_PROPERTY(int totalPagePairs READ totalPagePairs NOTIFY totalPagePairsChanged) Q_PROPERTY(bool pageShift READ pageShift NOTIFY pageShiftChanged) Q_PROPERTY(bool mangaRTL READ mangaRTL NOTIFY mangaRTLChanged) public: + enum ReadingRoles { + ContentRole = Qt::UserRole + 1 + }; + Q_ENUM(ReadingRoles) + explicit ReadingModel(BookPositionStore &positions, QObject *parent = nullptr); ~ReadingModel() override; + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QHash roleNames() const override; + + bool isTextMode() const; double progress() const; int currentPage() const; int totalPages() const; + int currentChapter() const; + int chapterCount() const; + QString chapterTitle() const; int totalPagePairs() const; bool pageShift() const; bool mangaRTL() const; void setReader(FormatReader *reader); - // Called from QML on every page navigation + // Called on navigation Q_INVOKABLE void setScrollInfo(int topChunkIndex, qreal proportion); + // Text chapter navigation + Q_INVOKABLE void loadChapter(int index); + Q_INVOKABLE void nextChapter(); + Q_INVOKABLE void previousChapter(); + // Manga page-pair API Q_INVOKABLE QVariantList pagePair(int pairIndex) const; Q_INVOKABLE int pairIndexForChunk(int chunkIndex) const; @@ -43,36 +65,44 @@ public: // Called from MangaPageView when window orientation changes Q_INVOKABLE void setMangaLandscape(bool landscape); - // Per-book page-shift toggle: when ON, page 1 is shown alone after the cover. - // currentPairIndex must be the pair the view is currently displaying. + // Per-book page-shift toggle Q_INVOKABLE void setPageShift(bool shift, int currentPairIndex = 0); Q_INVOKABLE void setMangaRTL(bool rtl); signals: + void modeChanged(); + void progressChanged(); void currentPageChanged(); void totalPagesChanged(); + void currentChapterChanged(); + void chapterCountChanged(); void totalPagePairsChanged(); void pageShiftChanged(); void mangaRTLChanged(); - // Fired after setPageShift rebuilds pairs; carries the new pair index to display. void pagePairsRebuilt(int newPairIndex); - void restoreReady(int chunkIndex); + void positionSaved(); private: void loadPages(); void rebuildPagePairs(); + void saveCurrentPosition(int chunkIndex); FormatReader *m_reader = nullptr; + bool m_isTextMode = false; int m_currentPage = 0; int m_totalPages = 0; + int m_currentChapter = 0; + int m_chapterCount = 0; + Chapter m_currentChapterData; + bool m_mangaLandscape = false; bool m_pageShift = true; bool m_mangaRTL = true; QVector m_pages; MangaPagination m_pagination; - qreal m_yOffset = 0.0; + qreal m_progress = 0.0; BookPositionStore &m_positions; }; diff --git a/src/backend/ZipUtils.h b/src/backend/ZipUtils.h deleted file mode 100644 index e7c5966..0000000 --- a/src/backend/ZipUtils.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace ZipUtils { - -// Read a single file from an open unzFile handle by name. -// Returns empty QByteArray on failure. -inline QByteArray readZipEntry(unzFile zf, const char *entryName) -{ - if (unzLocateFile(zf, entryName, 0) != UNZ_OK) - return {}; - if (unzOpenCurrentFile(zf) != UNZ_OK) - return {}; - - QByteArray result; - char buf[4096]; - int bytesRead; - while ((bytesRead = unzReadCurrentFile(zf, buf, sizeof(buf))) > 0) - result.append(buf, bytesRead); - - unzCloseCurrentFile(zf); - return (bytesRead == 0) ? result : QByteArray{}; -} - -// List all entry names in an open unzFile handle. -inline QStringList listZipEntries(unzFile zf) -{ - QStringList entries; - if (unzGoToFirstFile(zf) != UNZ_OK) - return entries; - do { - char name[4096]; - unz_file_info64 info{}; - if (unzGetCurrentFileInfo64(zf, &info, name, static_cast(sizeof(name) - 1), - nullptr, 0, nullptr, 0) == UNZ_OK) { - name[sizeof(name) - 1] = '\0'; - entries.append(QString::fromUtf8(name)); - } - } while (unzGoToNextFile(zf) == UNZ_OK); - return entries; -} - -} // namespace ZipUtils diff --git a/src/backend/book/Book.cpp b/src/backend/book/Book.cpp index c7570f3..f6db73f 100644 --- a/src/backend/book/Book.cpp +++ b/src/backend/book/Book.cpp @@ -5,12 +5,10 @@ #include "backend/formats/ImageExtensions.h" Book::Book(IFileDialogService &dialog, - BookPositionStore &positions, FormatRegistry ®istry, QObject *parent) : QObject(parent) , m_dialog(dialog) - , m_positions(positions) , m_registry(registry) { connect(&m_dialog, &IFileDialogService::fileSelected, @@ -28,24 +26,34 @@ Book::~Book() bool Book::hasBook() const { return m_reader != nullptr; } bool Book::loading() const { return m_loading; } QString Book::errorMessage() const { return m_errorMessage; } -QString Book::coverImageUrl() const { return m_coverImageUrl; } QString Book::title() const { return m_reader ? m_reader->title() : QString(); } QString Book::author() const { return m_reader ? m_reader->author() : QString(); } QString Book::filePath() const { return m_reader ? m_reader->filePath() : QString(); } +QString Book::coverImageUrl() const { return m_reader ? m_reader->coverImageUrl() : QString(); } + +QVariantList Book::tableOfContents() const +{ + if (!m_reader) + return {}; + const auto toc = m_reader->tableOfContents(); + QVariantList list; + list.reserve(toc.size()); + for (const auto &entry : toc) { + list.append(QVariantMap{ + {QStringLiteral("title"), entry.title}, + {QStringLiteral("chapterIndex"), entry.chapterIndex}, + {QStringLiteral("depth"), entry.depth} + }); + } + return list; +} FormatReader *Book::reader() const { return m_reader.get(); } -void Book::setCoverImageUrl(const QString &url) -{ - m_coverImageUrl = url; - // bookChanged is already emitted after book open; no extra emit needed here. - // If needed by QML after provider setup, a separate signal or re-emit can be added. -} - void Book::openFromUrl(const QUrl &url) { openFromPath(url.toLocalFile()); @@ -114,7 +122,6 @@ void Book::openImpl(const QString &filePath) if (generation != m_openGeneration) return; m_reader = std::move(*readerBox); - m_coverImageUrl.clear(); m_loading = false; emit loadingChanged(); @@ -127,7 +134,6 @@ void Book::close() { if (!m_reader) return; m_reader.reset(); - m_coverImageUrl.clear(); emit bookChanged(); } @@ -137,10 +143,3 @@ void Book::clearError() m_errorMessage.clear(); emit errorMessageChanged(); } - -void Book::saveCurrentPosition(int chunkIndex, bool mangaRTL, bool pageShift) -{ - if (!m_reader) return; - m_positions.save(m_reader->contentHash(), chunkIndex, mangaRTL, pageShift); - emit positionSaved(); -} diff --git a/src/backend/book/Book.h b/src/backend/book/Book.h index 0fa4580..1d6cf73 100644 --- a/src/backend/book/Book.h +++ b/src/backend/book/Book.h @@ -6,41 +6,40 @@ #include #include #include +#include #include #include "backend/FormatReader.h" #include "backend/IFileDialogService.h" #include "backend/formats/FormatRegistry.h" -#include "backend/state/BookPositionStore.h" class Book : public QObject { Q_OBJECT - Q_PROPERTY(bool hasBook READ hasBook NOTIFY bookChanged) - Q_PROPERTY(bool loading READ loading NOTIFY loadingChanged) - Q_PROPERTY(QString title READ title NOTIFY bookChanged) - Q_PROPERTY(QString author READ author NOTIFY bookChanged) - Q_PROPERTY(QString filePath READ filePath NOTIFY bookChanged) - Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY bookChanged) - Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorMessageChanged) + Q_PROPERTY(bool hasBook READ hasBook NOTIFY bookChanged) + Q_PROPERTY(bool loading READ loading NOTIFY loadingChanged) + Q_PROPERTY(QString title READ title NOTIFY bookChanged) + Q_PROPERTY(QString author READ author NOTIFY bookChanged) + Q_PROPERTY(QString filePath READ filePath NOTIFY bookChanged) + Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY bookChanged) + Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorMessageChanged) + Q_PROPERTY(QVariantList tableOfContents READ tableOfContents NOTIFY bookChanged) + public: Book(IFileDialogService &dialog, - BookPositionStore &positions, FormatRegistry ®istry, QObject *parent = nullptr); ~Book() override; - bool hasBook() const; - bool loading() const; - QString title() const; - QString author() const; - QString filePath() const; - QString coverImageUrl() const; - QString errorMessage() const; + bool hasBook() const; + bool loading() const; + QString title() const; + QString author() const; + QString filePath() const; + QString coverImageUrl() const; + QString errorMessage() const; + QVariantList tableOfContents() const; - // Called by AppCoordinator::onBookChanged after the image provider resolves the cover URL. - void setCoverImageUrl(const QString &url); - - // Access the underlying reader for wiring purposes (e.g., to push into ReadingModel). + // Access the underlying reader (e.g. to push into ReadingModel). FormatReader *reader() const; Q_INVOKABLE void openFromUrl(const QUrl &url); @@ -49,14 +48,9 @@ public: Q_INVOKABLE void close(); Q_INVOKABLE void clearError(); - // 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. - // Listeners can snapshot the outgoing book's progress before the swap. void willOpenNewBook(); - void positionSaved(); void bookChanged(); void loadingChanged(); @@ -66,10 +60,8 @@ private: void openImpl(const QString &filePath); IFileDialogService &m_dialog; - BookPositionStore &m_positions; FormatRegistry &m_registry; std::unique_ptr m_reader; - QString m_coverImageUrl; QString m_errorMessage; bool m_loading = false; int m_openGeneration = 0; diff --git a/src/backend/formats/EntryImageProvider.cpp b/src/backend/formats/EntryImageProvider.cpp index 8f3a71d..dabe668 100644 --- a/src/backend/formats/EntryImageProvider.cpp +++ b/src/backend/formats/EntryImageProvider.cpp @@ -1,9 +1,7 @@ #include "EntryImageProvider.h" #include -#include #include -#include #include "AsyncImageResponse.h" #include "ImageScaling.h" @@ -36,20 +34,14 @@ EntryImageProvider::EntryImageProvider(SourceFactory sourceFactory, QString sche QQuickImageResponse *EntryImageProvider::requestImageResponse(const QString &id, const QSize &requestedSize) { - QString sourcePath; - { - QMutexLocker lock(&m_mutex); - sourcePath = m_sourcePath; - } - - // id may be "entry/name.jpg?src=" const ImageUrl::Parsed parsed = ImageUrl::parseProviderId(id); const QString entryName = parsed.entry; - if (!parsed.sourcePath.isEmpty()) - sourcePath = parsed.sourcePath; + const QString sourcePath = parsed.sourcePath; auto *response = new AsyncImageResponse( [factory = m_sourceFactory, sourcePath, entryName, requestedSize]() -> QImage { + if (sourcePath.isEmpty()) + return {}; auto source = factory(); if (!source->open(sourcePath)) return {}; @@ -58,27 +50,3 @@ QQuickImageResponse *EntryImageProvider::requestImageResponse(const QString &id, QThreadPool::globalInstance()->start(response); return response; } - -void EntryImageProvider::setFilePath(const QString &filePath) -{ - QMutexLocker lock(&m_mutex); - m_sourcePath = filePath; -} - -QString EntryImageProvider::coverImageUrl(const QString &coverPath) const -{ - QString sourcePath; - { QMutexLocker lock(&m_mutex); sourcePath = m_sourcePath; } - return ImageUrl::build(m_scheme, coverPath, sourcePath); -} - -QString EntryImageProvider::scheme() const -{ - return m_scheme; -} - -void EntryImageProvider::clear() -{ - QMutexLocker lock(&m_mutex); - m_sourcePath.clear(); -} diff --git a/src/backend/formats/EntryImageProvider.h b/src/backend/formats/EntryImageProvider.h index f01ebfc..84a08aa 100644 --- a/src/backend/formats/EntryImageProvider.h +++ b/src/backend/formats/EntryImageProvider.h @@ -1,14 +1,13 @@ #pragma once #include "IByteSource.h" -#include "backend/IImageProvider.h" +#include #include #include -#include #include -class EntryImageProvider : public IImageProvider { +class EntryImageProvider : public QQuickAsyncImageProvider { public: using SourceFactory = std::function()>; @@ -17,10 +16,7 @@ public: QQuickImageResponse *requestImageResponse(const QString &id, const QSize &requestedSize) override; - void setFilePath(const QString &filePath) override; - void clear() override; - QString coverImageUrl(const QString &coverPath) const override; - QString scheme() const override; + QString scheme() const { return m_scheme; } static QImage loadImageFromSource(IByteSource &source, const QString &entryName, @@ -29,6 +25,4 @@ public: private: SourceFactory m_sourceFactory; QString m_scheme; - mutable QMutex m_mutex; - QString m_sourcePath; }; diff --git a/src/backend/formats/FormatRegistry.cpp b/src/backend/formats/FormatRegistry.cpp index cdd381b..4a64d58 100644 --- a/src/backend/formats/FormatRegistry.cpp +++ b/src/backend/formats/FormatRegistry.cpp @@ -2,10 +2,23 @@ #include "EntryImageProvider.h" #include "backend/FormatReader.h" +#include "backend/formats/comic/ComicReader.h" #include #include +FormatSpec FormatSpec::comic(const QString &ext, bool matchesDirectory, const QString &scheme, + SourceFactory makeSource) +{ + return FormatSpec{ + ext, + matchesDirectory, + scheme, + [makeSource, scheme] { return std::make_unique(makeSource, scheme); }, + makeSource + }; +} + FormatRegistry::FormatRegistry(QVector specs) : m_specs(std::move(specs)) { @@ -30,14 +43,6 @@ std::unique_ptr FormatRegistry::createReader(const QString &filePa return spec ? spec->makeReader() : nullptr; } -IImageProvider *FormatRegistry::createImageProvider(const QString &filePath) const -{ - const FormatSpec *spec = specFor(filePath); - if (!spec || spec->scheme.isEmpty() || !spec->makeSource) - return nullptr; - return new EntryImageProvider(spec->makeSource, spec->scheme); -} - QStringList FormatRegistry::supportedExtensions() const { QStringList out; @@ -49,8 +54,9 @@ QStringList FormatRegistry::supportedExtensions() const void FormatRegistry::registerImageProviders(QQmlEngine &engine) const { - for (const FormatSpec &spec : m_specs) + for (const FormatSpec &spec : m_specs) { if (!spec.scheme.isEmpty() && spec.makeSource) engine.addImageProvider(spec.scheme, new EntryImageProvider(spec.makeSource, spec.scheme)); + } } diff --git a/src/backend/formats/FormatRegistry.h b/src/backend/formats/FormatRegistry.h index b1db072..1409a48 100644 --- a/src/backend/formats/FormatRegistry.h +++ b/src/backend/formats/FormatRegistry.h @@ -8,18 +8,23 @@ class FormatReader; class IByteSource; -class IImageProvider; class QQmlEngine; // One row per supported format. Everything a format needs — reader, image // byte source, provider scheme — is declared in one place; adding a format // means adding one row to the table built in main(). struct FormatSpec { + using ReaderFactory = std::function()>; + using SourceFactory = std::function()>; + QString extension; // lowercase, without dot; unused when matchesDirectory bool matchesDirectory = false; QString scheme; // image:// scheme; empty = format has no images - std::function()> makeReader; - std::function()> makeSource; // required when scheme is set + ReaderFactory makeReader; + SourceFactory makeSource; // required when scheme is set + + static FormatSpec comic(const QString &ext, bool matchesDirectory, const QString &scheme, + SourceFactory makeSource); }; class FormatRegistry { @@ -27,11 +32,6 @@ public: explicit FormatRegistry(QVector specs); std::unique_ptr createReader(const QString &filePath) const; - - // New provider for the format, or nullptr for formats without images. - // Caller owns the pointer (the QML engine takes ownership on registration). - IImageProvider *createImageProvider(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/IByteSource.h b/src/backend/formats/IByteSource.h index 8cce60d..910a611 100644 --- a/src/backend/formats/IByteSource.h +++ b/src/backend/formats/IByteSource.h @@ -1,6 +1,8 @@ #pragma once #include +#include +#include #include #include @@ -22,4 +24,15 @@ public: // MD5 of the source. For archives: MD5 of file bytes. // For directories: MD5 of sorted "name:size\n" lines. virtual QByteArray contentHash() const = 0; + + // Shared MD5 calculation for files on disk. + static QByteArray hashFileMd5(const QString &filePath) + { + if (filePath.isEmpty()) + return {}; + QFile f(filePath); + if (f.open(QIODevice::ReadOnly)) + return QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5); + return {}; + } }; diff --git a/src/backend/formats/ImageUrl.cpp b/src/backend/formats/ImageUrl.cpp index c51297e..52b3072 100644 --- a/src/backend/formats/ImageUrl.cpp +++ b/src/backend/formats/ImageUrl.cpp @@ -1,29 +1,57 @@ #include "ImageUrl.h" +#include #include #include #include namespace { const QLatin1String kSrcKey("src="); - -QString querySuffix(const QString &sourcePath) -{ - return QStringLiteral("?src=") - + QString::fromUtf8(QUrl::toPercentEncoding(sourcePath)); -} } namespace ImageUrl { -QString build(const QString &scheme, const QString &entry) +QString querySuffix(const QString &sourcePath) { - return QStringLiteral("image://") + scheme + QLatin1Char('/') + entry; + if (sourcePath.isEmpty()) + return {}; + return QStringLiteral("?src=") + + QString::fromUtf8(QUrl::toPercentEncoding(sourcePath)); } QString build(const QString &scheme, const QString &entry, const QString &sourcePath) { - return build(scheme, entry) + querySuffix(sourcePath); + QString url = QStringLiteral("image://") + scheme + QLatin1Char('/') + entry; + if (!sourcePath.isEmpty()) + url += querySuffix(sourcePath); + return url; +} + +QString resolve(const QString &scheme, + const QString &href, + const QString &sourcePath, + const QString &baseDir) +{ + if (href.isEmpty()) + return {}; + + if (href.startsWith(QLatin1String("http://")) || href.startsWith(QLatin1String("https://"))) + return QStringLiteral("image://web/") + href; + + if (href.startsWith(QLatin1String("image://"))) + return href; + + QString entry = href; + if (entry.startsWith(QLatin1Char('#'))) + entry.remove(0, 1); + + if (!baseDir.isEmpty()) + entry = QDir::cleanPath(baseDir + entry); + + while (entry.startsWith(QLatin1Char('/'))) + entry.remove(0, 1); + + return build(scheme, entry, sourcePath); } Parsed parseProviderId(const QString &id) diff --git a/src/backend/formats/ImageUrl.h b/src/backend/formats/ImageUrl.h index b4a93a4..bc059e9 100644 --- a/src/backend/formats/ImageUrl.h +++ b/src/backend/formats/ImageUrl.h @@ -5,15 +5,23 @@ // Single authority for the image-provider URL grammar: // image:///[?src=] // The optional src query names the container file (archive, document) the -// entry lives in; when absent, providers fall back to their current file. +// entry lives in. namespace ImageUrl { -QString build(const QString &scheme, const QString &entry); -QString build(const QString &scheme, const QString &entry, const QString &sourcePath); +QString querySuffix(const QString &sourcePath); +QString build(const QString &scheme, const QString &entry, const QString &sourcePath = {}); + +// Resolves an image reference from a book (relative path, #fragment, or http/https URL): +// - "http://..." or "https://..." -> "image://web/http..." +// - embedded entry (resolved against optional baseDir for EPUB XHTML) -> "image:///?src=" +QString resolve(const QString &scheme, + const QString &href, + const QString &sourcePath, + const QString &baseDir = {}); struct Parsed { QString entry; - QString sourcePath; // empty = use the provider's current file + QString sourcePath; // empty if no source parameter was present }; // Parse the id handed to QQuickAsyncImageProvider (scheme already stripped, diff --git a/src/backend/formats/comic/CbrReader.h b/src/backend/formats/comic/CbrReader.h deleted file mode 100644 index b492dc6..0000000 --- a/src/backend/formats/comic/CbrReader.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include "ComicReader.h" -#include "backend/formats/sources/RarByteSource.h" - -class CbrReader : public ComicReader { -public: - CbrReader() - : ComicReader([] { return std::make_unique(); }, - QStringLiteral("cbr"), - QStringLiteral("cbr")) {} -}; diff --git a/src/backend/formats/comic/CbzReader.h b/src/backend/formats/comic/CbzReader.h deleted file mode 100644 index 8bf6128..0000000 --- a/src/backend/formats/comic/CbzReader.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include "ComicReader.h" -#include "backend/formats/sources/ZipByteSource.h" - -class CbzReader : public ComicReader { -public: - CbzReader() - : ComicReader([] { return std::make_unique(); }, - QStringLiteral("cbz"), - QStringLiteral("cbz")) {} -}; diff --git a/src/backend/formats/comic/ComicReader.cpp b/src/backend/formats/comic/ComicReader.cpp index 287c2b4..cc8512e 100644 --- a/src/backend/formats/comic/ComicReader.cpp +++ b/src/backend/formats/comic/ComicReader.cpp @@ -57,25 +57,13 @@ static void parseComicInfo(const QByteArray &data, // ComicReader // --------------------------------------------------------------------------- -ComicReader::ComicReader(SourceFactory sourceFactory, QString fileType, QString scheme) +ComicReader::ComicReader(SourceFactory sourceFactory, QString scheme) : m_sourceFactory(std::move(sourceFactory)) - , m_fileType(std::move(fileType)) , m_scheme(std::move(scheme)) { } -// Shared parsing logic given an already-opened source. -bool ComicReader::parseSource(const QString &filePath) -{ - auto source = m_sourceFactory(); - if (!source->open(filePath)) { - m_error = QStringLiteral("Cannot open comic source: ") + filePath; - return false; - } - return parseOpenSource(filePath, *source); -} - -bool ComicReader::parseOpenSource(const QString &filePath, IByteSource &source) +bool ComicReader::parseOpenSource(const QString &filePath, IByteSource &source, bool metadataOnly) { const QStringList allEntries = source.listEntries(); @@ -92,25 +80,27 @@ bool ComicReader::parseOpenSource(const QString &filePath, IByteSource &source) } imageEntries.sort(); + if (imageEntries.isEmpty()) { + m_error = QStringLiteral("No images found: ") + filePath; + return false; + } + m_pageEntries.reserve(imageEntries.size()); for (const QString &entry : imageEntries) { QSize naturalSize; - const QByteArray data = source.readEntry(entry); - if (!data.isEmpty()) { - QBuffer buf; - buf.setData(data); - buf.open(QIODevice::ReadOnly); - QImageReader reader(&buf); - naturalSize = reader.size(); + if (!metadataOnly) { + const QByteArray data = source.readEntry(entry); + if (!data.isEmpty()) { + QBuffer buf; + buf.setData(data); + buf.open(QIODevice::ReadOnly); + QImageReader reader(&buf); + naturalSize = reader.size(); + } } m_pageEntries.append({entry, naturalSize}); } - if (m_pageEntries.isEmpty()) { - m_error = QStringLiteral("No images found: ") + filePath; - return false; - } - m_coverEntry = m_pageEntries.first().entry; // ComicInfo.xml: archive root only, case-insensitive @@ -150,7 +140,7 @@ bool ComicReader::open(const QString &filePath) return false; } m_contentHash = source->contentHash(); - return parseOpenSource(filePath, *source); + return parseOpenSource(filePath, *source, false); } bool ComicReader::loadMetadata(const QString &filePath) @@ -160,8 +150,22 @@ bool ComicReader::loadMetadata(const QString &filePath) m_error.clear(); m_pageEntries.clear(); m_coverEntry.clear(); + m_contentHash.clear(); m_filePath.clear(); - return parseSource(filePath); + + auto source = m_sourceFactory(); + if (!source->open(filePath)) { + m_error = QStringLiteral("Cannot open comic source: ") + filePath; + return false; + } + return parseOpenSource(filePath, *source, true); +} + +QString ComicReader::coverImageUrl() const +{ + if (m_coverEntry.isEmpty()) + return {}; + return ImageUrl::build(m_scheme, m_coverEntry, m_filePath); } QVector ComicReader::pages() const @@ -169,15 +173,7 @@ QVector ComicReader::pages() const QVector result; result.reserve(m_pageEntries.size()); for (const PageEntry &page : m_pageEntries) { - result.append({ImageUrl::build(m_scheme, page.entry), page.naturalSize}); + result.append({ImageUrl::build(m_scheme, page.entry, m_filePath), page.naturalSize}); } return result; } - -QString ComicReader::lastError() { return m_error; } -QString ComicReader::title() { return m_title; } -QString ComicReader::author() { return m_author; } -QString ComicReader::coverImagePath() { return m_coverEntry; } -QString ComicReader::filePath() { return m_filePath; } -QByteArray ComicReader::contentHash() { return m_contentHash; } -QString ComicReader::fileType() const { return m_fileType; } diff --git a/src/backend/formats/comic/ComicReader.h b/src/backend/formats/comic/ComicReader.h index acf6503..7dd6912 100644 --- a/src/backend/formats/comic/ComicReader.h +++ b/src/backend/formats/comic/ComicReader.h @@ -14,17 +14,17 @@ class ComicReader : public FormatReader { public: using SourceFactory = std::function()>; - ComicReader(SourceFactory sourceFactory, QString fileType, QString scheme); + ComicReader(SourceFactory sourceFactory, QString scheme); + ReadingMode mode() const override { return ReadingMode::Comic; } bool open(const QString &filePath) override; bool loadMetadata(const QString &filePath) override; - QString lastError() override; - QString filePath() override; - QString title() override; - QString author() override; - QString coverImagePath() override; - QByteArray contentHash() override; - QString fileType() const override; + QString lastError() const override { return m_error; } + QString filePath() const override { return m_filePath; } + QString title() const override { return m_title; } + QString author() const override { return m_author; } + QString coverImageUrl() const override; + QByteArray contentHash() const override { return m_contentHash; } QVector pages() const override; @@ -34,11 +34,9 @@ private: QSize naturalSize; }; - bool parseSource(const QString &filePath); - bool parseOpenSource(const QString &filePath, IByteSource &source); + bool parseOpenSource(const QString &filePath, IByteSource &source, bool metadataOnly = false); SourceFactory m_sourceFactory; - QString m_fileType; QString m_scheme; QString m_filePath; diff --git a/src/backend/formats/comic/FolderReader.h b/src/backend/formats/comic/FolderReader.h deleted file mode 100644 index 983ab20..0000000 --- a/src/backend/formats/comic/FolderReader.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include "ComicReader.h" -#include "backend/formats/sources/DirByteSource.h" - -class FolderReader : public ComicReader { -public: - FolderReader() - : ComicReader([] { return std::make_unique(); }, - QStringLiteral("folder"), - QStringLiteral("dir")) {} -}; diff --git a/src/backend/formats/sources/RarByteSource.cpp b/src/backend/formats/sources/RarByteSource.cpp index 6960fd7..5786f19 100644 --- a/src/backend/formats/sources/RarByteSource.cpp +++ b/src/backend/formats/sources/RarByteSource.cpp @@ -1,8 +1,5 @@ #include "RarByteSource.h" -#include -#include - #include #include @@ -75,12 +72,7 @@ QByteArray RarByteSource::readEntry(const QString &entryName) const QByteArray RarByteSource::contentHash() const { - // Computed lazily: hashing reads the whole file, which providers opening - // a source per image request must not pay for. - if (m_hash.isEmpty() && !m_path.isEmpty()) { - QFile f(m_path); - if (f.open(QIODevice::ReadOnly)) - m_hash = QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5); - } + if (m_hash.isEmpty()) + m_hash = IByteSource::hashFileMd5(m_path); return m_hash; } diff --git a/src/backend/formats/sources/ZipByteSource.cpp b/src/backend/formats/sources/ZipByteSource.cpp index e547b49..088fe0c 100644 --- a/src/backend/formats/sources/ZipByteSource.cpp +++ b/src/backend/formats/sources/ZipByteSource.cpp @@ -1,11 +1,45 @@ #include "ZipByteSource.h" -#include "backend/ZipUtils.h" - -#include -#include - #include +#include + +namespace { + +QByteArray readZipEntry(unzFile zf, const char *entryName) +{ + if (unzLocateFile(zf, entryName, 0) != UNZ_OK) + return {}; + if (unzOpenCurrentFile(zf) != UNZ_OK) + return {}; + + QByteArray result; + char buf[4096]; + int bytesRead; + while ((bytesRead = unzReadCurrentFile(zf, buf, sizeof(buf))) > 0) + result.append(buf, bytesRead); + + unzCloseCurrentFile(zf); + return (bytesRead == 0) ? result : QByteArray{}; +} + +QStringList listZipEntries(unzFile zf) +{ + QStringList entries; + if (unzGoToFirstFile(zf) != UNZ_OK) + return entries; + do { + char name[4096]; + unz_file_info64 info{}; + if (unzGetCurrentFileInfo64(zf, &info, name, static_cast(sizeof(name) - 1), + nullptr, 0, nullptr, 0) == UNZ_OK) { + name[sizeof(name) - 1] = '\0'; + entries.append(QString::fromUtf8(name)); + } + } while (unzGoToNextFile(zf) == UNZ_OK); + return entries; +} + +} // namespace bool ZipByteSource::open(const QString &path) { @@ -16,7 +50,7 @@ bool ZipByteSource::open(const QString &path) unzFile zf = unzOpen(path.toUtf8().constData()); if (!zf) return false; - m_entries = ZipUtils::listZipEntries(zf); + m_entries = listZipEntries(zf); unzClose(zf); m_path = path; @@ -37,17 +71,12 @@ QByteArray ZipByteSource::readEntry(const QString &entryName) const return {}; auto closeGuard = [](void *p) { unzClose(static_cast(p)); }; std::unique_ptr guard(zf, closeGuard); - return ZipUtils::readZipEntry(zf, entryName.toUtf8().constData()); + return readZipEntry(zf, entryName.toUtf8().constData()); } QByteArray ZipByteSource::contentHash() const { - // Computed lazily: hashing reads the whole file, which providers opening - // a source per image request must not pay for. - if (m_hash.isEmpty() && !m_path.isEmpty()) { - QFile f(m_path); - if (f.open(QIODevice::ReadOnly)) - m_hash = QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5); - } + if (m_hash.isEmpty()) + m_hash = IByteSource::hashFileMd5(m_path); return m_hash; } diff --git a/src/backend/state/BookPositionStore.cpp b/src/backend/state/BookPositionStore.cpp index 08a288a..7a7f6c6 100644 --- a/src/backend/state/BookPositionStore.cpp +++ b/src/backend/state/BookPositionStore.cpp @@ -11,20 +11,24 @@ BookPosition BookPositionStore::load(const QByteArray &contentMd5) return {}; const QVariantMap d = m_state.loadSection(sectionKey(contentMd5)); BookPosition pos; - pos.chunkIndex = d.value(QStringLiteral("chunkIndex"), 0).toInt(); - pos.pageShift = d.value(QStringLiteral("pageShift"), true).toBool(); - pos.mangaRTL = d.value(QStringLiteral("mangaRTL"), true).toBool(); + pos.chapterIndex = d.value(QStringLiteral("chapterIndex"), 0).toInt(); + pos.chunkIndex = d.value(QStringLiteral("chunkIndex"), 0).toInt(); + pos.progress = d.value(QStringLiteral("progress"), 0.0).toReal(); + 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, bool mangaRTL, bool pageShift) +void BookPositionStore::save(const QByteArray &contentMd5, const BookPosition &pos) { if (contentMd5.isEmpty()) return; m_state.saveSection(sectionKey(contentMd5), { - {QStringLiteral("chunkIndex"), chunkIndex}, - {QStringLiteral("pageShift"), pageShift}, - {QStringLiteral("mangaRTL"), mangaRTL}, + {QStringLiteral("chapterIndex"), pos.chapterIndex}, + {QStringLiteral("chunkIndex"), pos.chunkIndex}, + {QStringLiteral("progress"), pos.progress}, + {QStringLiteral("pageShift"), pos.pageShift}, + {QStringLiteral("mangaRTL"), pos.mangaRTL}, }); } diff --git a/src/backend/state/BookPositionStore.h b/src/backend/state/BookPositionStore.h index 0a1ffe6..59b959d 100644 --- a/src/backend/state/BookPositionStore.h +++ b/src/backend/state/BookPositionStore.h @@ -5,9 +5,11 @@ #include "backend/AppState.h" struct BookPosition { - int chunkIndex = 0; - bool pageShift = true; // manga page-shift; default ON - bool mangaRTL = true; // manga reading direction; default RTL + int chapterIndex = 0; // Text mode: current chapter (0 for single-chapter / comic) + int chunkIndex = 0; // Comic mode: page index; Text mode: top chunk index + qreal progress = 0.0; // Normalized [0..1] scroll/reading progress + bool pageShift = true; // Comic mode only + bool mangaRTL = true; // Comic mode only }; class BookPositionStore { @@ -18,7 +20,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, bool mangaRTL = true, bool pageShift = true); + void save(const QByteArray &contentMd5, const BookPosition &pos); private: AppState &m_state; diff --git a/src/main.cpp b/src/main.cpp index 56bf55f..e7ad5be 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -20,9 +20,6 @@ #include "backend/ReadingModel.h" #include "backend/NativeFileDialogService.h" #include "backend/book/Book.h" -#include "backend/formats/comic/CbzReader.h" -#include "backend/formats/comic/CbrReader.h" -#include "backend/formats/comic/FolderReader.h" #include "backend/state/BookPositionStore.h" #include "backend/state/ReadingPreferences.h" #include "backend/state/UiState.h" @@ -102,26 +99,16 @@ int main(int argc, char *argv[]) // The format table: one row declares everything a format needs. FormatRegistry formatRegistry({ - {QStringLiteral("cbz"), false, QStringLiteral("cbz"), - [] { return std::make_unique(); }, - [] { return std::make_unique(); }}, - {QStringLiteral("cbr"), false, QStringLiteral("cbr"), - [] { return std::make_unique(); }, - [] { return std::make_unique(); }}, - {{}, /*matchesDirectory=*/true, QStringLiteral("dir"), - [] { return std::make_unique(); }, - [] { return std::make_unique(); }}, + FormatSpec::comic(QStringLiteral("cbz"), false, QStringLiteral("cbz"), + [] { return std::make_unique(); }), + FormatSpec::comic(QStringLiteral("cbr"), false, QStringLiteral("cbr"), + [] { return std::make_unique(); }), + FormatSpec::comic({}, /*matchesDirectory=*/true, QStringLiteral("dir"), + [] { return std::make_unique(); }), }); HistoryModel historyModel(formatRegistry); - for (const QVariantMap &entry : appState.loadArray(QStringLiteral("history"))) { - const QString fp = entry.value(QStringLiteral("filePath")).toString(); - if (fp.isEmpty()) continue; - double progress = entry.value(QStringLiteral("progress"), 0.0).toDouble(); - progress = qBound(0.0, progress, 1.0); - const QString lo = entry.value(QStringLiteral("lastOpened")).toString(); - historyModel.addOrUpdateBook(fp, progress, lo); - } + historyModel.load(appState); // Command-line override: treat first argument as the file to open on startup if (const QStringList args = QCoreApplication::arguments(); args.size() > 1) { @@ -141,7 +128,7 @@ int main(int argc, char *argv[]) IFileDialogService *fileDialogService = new NativeFileDialogService(nullptr); #endif - Book book(*fileDialogService, bookPositions, formatRegistry); + Book book(*fileDialogService, formatRegistry); ReadingModel readingModel(bookPositions); // --- QML engine --- @@ -164,8 +151,7 @@ int main(int argc, char *argv[]) // All cross-class signal wiring lives in the coordinator. AppCoordinator coordinator(book, readingModel, historyModel, uiState, - readingPreferences, appState, settings, - formatRegistry, engine); + readingPreferences, appState, settings); const QUrl url(QStringLiteral("qrc:/Asteria/Main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed, diff --git a/src/qml/Main.qml b/src/qml/Main.qml index 2923efa..0e8f127 100644 --- a/src/qml/Main.qml +++ b/src/qml/Main.qml @@ -55,6 +55,10 @@ ApplicationWindow { function onErrorMessageChanged() { if (book.errorMessage !== "") window._bookInitializing = false } + function onBookChanged() { + if (!book.hasBook && window.currentPage === "reader") + window.currentPage = "history" + } } Timer { @@ -166,7 +170,7 @@ ApplicationWindow { anchors.fill: parent z: 3000 } - + // Pre-warms QQuickPixmapReader on the main thread so the render thread // never creates it first (which logs a QObject parent-thread warning). Image { width: 0; height: 0; visible: false; source: "image://web/__warmup__" } @@ -190,22 +194,9 @@ ApplicationWindow { } } - Connections { - target: book - function onBookChanged() { - if (!book.hasBook && window.currentPage === "reader") - window.currentPage = "history" - } - } - // Global keyboard shortcuts - work regardless of focus Shortcut { - sequence: "F" - context: Qt.ApplicationShortcut - onActivated: window.visibility = (window.visibility === Window.FullScreen) ? Window.Windowed : Window.FullScreen - } - Shortcut { - sequence: "F11" + sequences: ["F", "F11"] context: Qt.ApplicationShortcut onActivated: window.visibility = (window.visibility === Window.FullScreen) ? Window.Windowed : Window.FullScreen } @@ -230,7 +221,7 @@ ApplicationWindow { } } Shortcut { - sequence: "PgUp" + sequences: ["PgUp", "Prior"] context: Qt.ApplicationShortcut onActivated: { if (currentPage === "reader" && readerPage?.pageView) { @@ -239,7 +230,7 @@ ApplicationWindow { } } Shortcut { - sequence: "PgDown" + sequences: ["PgDown", "Next", "Space"] context: Qt.ApplicationShortcut onActivated: { if (currentPage === "reader" && readerPage?.pageView) { @@ -247,33 +238,6 @@ ApplicationWindow { } } } - Shortcut { - sequence: "Prior" - context: Qt.ApplicationShortcut - onActivated: { - if (currentPage === "reader" && readerPage?.pageView) { - readerPage.pageView.handlePageUp(); - } - } - } - Shortcut { - sequence: "Next" - context: Qt.ApplicationShortcut - onActivated: { - if (currentPage === "reader" && readerPage?.pageView) { - readerPage.pageView.handlePageDown(); - } - } - } - Shortcut { - sequence: "Space" - context: Qt.ApplicationShortcut - onActivated: { - if (currentPage === "reader" && readerPage) { - readerPage.pageView.handlePageDown(); - } - } - } Shortcut { sequence: "M" context: Qt.ApplicationShortcut diff --git a/src/qml/components/Footer.qml b/src/qml/components/Footer.qml index 2f26ac7..77d72cb 100644 --- a/src/qml/components/Footer.qml +++ b/src/qml/components/Footer.qml @@ -15,6 +15,7 @@ Rectangle { // RTL reading direction toggle. FlatIconButton { + visible: !readingModel.isTextMode anchors.left: parent.left anchors.leftMargin: 16 anchors.verticalCenter: parent.verticalCenter @@ -30,6 +31,7 @@ Rectangle { // Page-shift toggle. Shifts page 1 to be displayed alone after the cover. FlatIconButton { + visible: !readingModel.isTextMode anchors.left: parent.left anchors.leftMargin: 44 anchors.verticalCenter: parent.verticalCenter diff --git a/src/qml/components/MangaPageView.qml b/src/qml/components/MangaPageView.qml index f496343..b5e52eb 100644 --- a/src/qml/components/MangaPageView.qml +++ b/src/qml/components/MangaPageView.qml @@ -42,7 +42,6 @@ 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, readingModel.mangaRTL, readingModel.pageShift) } // Notify model when orientation changes (triggers pair rebuild). diff --git a/src/qml/pages/ReaderPage.qml b/src/qml/pages/ReaderPage.qml index 12cf980..2d6ae88 100644 --- a/src/qml/pages/ReaderPage.qml +++ b/src/qml/pages/ReaderPage.qml @@ -8,6 +8,7 @@ Item { MangaPageView { id: internalPageView anchors.fill: parent + visible: !readingModel.isTextMode focus: visible } } diff --git a/tests/EntryImageProviderTest.cpp b/tests/EntryImageProviderTest.cpp index 4f1a4cc..9e7bd1f 100644 --- a/tests/EntryImageProviderTest.cpp +++ b/tests/EntryImageProviderTest.cpp @@ -48,7 +48,6 @@ static bool addZipEntry(zipFile zf, const char *name, const QByteArray &data) return zipCloseFileInZip(zf) == ZIP_OK; } -// Create a QByteArray containing a valid PNG for an image of given size and color. static QByteArray makePng(int w, int h, QRgb color = qRgb(255, 0, 0)) { QImage img(w, h, QImage::Format_RGB32); @@ -60,8 +59,6 @@ static QByteArray makePng(int w, int h, QRgb color = qRgb(255, 0, 0)) return data; } -// Build a minimal CBZ containing a single image entry. -// Returns the path of the temp file (caller removes). static QString buildCbzWithPng(const char *entryPath, int imgW, int imgH, QRgb color = qRgb(255, 0, 0)) { @@ -124,19 +121,6 @@ private slots: QVERIFY(img.isNull()); } - void clearResetsState() - { - const QString cbzPath = buildCbzWithPng("images/test.png", 4, 4); - QVERIFY(!cbzPath.isEmpty()); - - const QImage img = loadFromCbz( - QString{}, QStringLiteral("images/test.png"), QSize()); - - QFile::remove(cbzPath); - - QVERIFY(img.isNull()); - } - void requestedSizeHonored() { const QString cbzPath = buildCbzWithPng("img.png", 400, 300); @@ -209,28 +193,9 @@ private slots: } // ----------------------------------------------------------------------- - // Embedded-path URL format tests + // Embedded-path URL format tests (stateless provider) // ----------------------------------------------------------------------- - void coverImageUrlEmbedsCbzPath() - { - const QString cbzPath = buildCbzWithPng("img.png", 4, 4); - QVERIFY(!cbzPath.isEmpty()); - - EntryImageProvider provider = makeCbzProvider(); - provider.setFilePath(cbzPath); - - const QString url = provider.coverImageUrl(QStringLiteral("cover.jpg")); - - QFile::remove(cbzPath); - - QVERIFY2(url.startsWith(QStringLiteral("image://cbz/cover.jpg?src=")), - qPrintable("Expected query-param URL, got: " + url)); - const QString encodedPath = QString::fromUtf8(QUrl::toPercentEncoding(cbzPath)); - QVERIFY2(url.contains(encodedPath), - qPrintable("URL should contain encoded cbz path. URL: " + url)); - } - void requestImageResponseUsesEmbeddedPath() { const QString cbzA = buildCbzWithPng("img.png", 4, 4, qRgb(255, 0, 0)); @@ -238,7 +203,6 @@ private slots: QVERIFY(!cbzA.isEmpty() && !cbzB.isEmpty()); EntryImageProvider provider = makeCbzProvider(); - provider.setFilePath(cbzA); // configured for A // Build an embedded-format id pointing to B via query parameter const QString encodedB = QString::fromUtf8(QUrl::toPercentEncoding(cbzB)); @@ -260,45 +224,15 @@ private slots: delete resp; } - void requestImageResponseFallsBackToProviderPath() + void requestImageResponseWithoutSourcePathReturnsNull() { - const QString cbzA = buildCbzWithPng("img.png", 4, 4, qRgb(255, 0, 0)); - QVERIFY(!cbzA.isEmpty()); - EntryImageProvider provider = makeCbzProvider(); - provider.setFilePath(cbzA); - - QQuickImageResponse *resp = provider.requestImageResponse( - QStringLiteral("img.png"), QSize()); - QSignalSpy spy(resp, &QQuickImageResponse::finished); - QThreadPool::globalInstance()->waitForDone(); - if (spy.isEmpty()) spy.wait(5000); - - QFile::remove(cbzA); - - QVERIFY(resp->textureFactory() != nullptr); - const QImage img = resp->textureFactory()->image(); - QVERIFY(!img.isNull()); - QCOMPARE(img.pixel(0, 0), qRgb(255, 0, 0)); - - delete resp; - } - - void responseAfterClearIsNull() - { - const QString cbzPath = buildCbzWithPng("img.png", 4, 4); - QVERIFY(!cbzPath.isEmpty()); - - EntryImageProvider provider = makeCbzProvider(); - provider.setFilePath(cbzPath); - provider.clear(); + // Id without ?src= has no container to load from QQuickImageResponse *resp = provider.requestImageResponse( QStringLiteral("img.png"), QSize()); QThreadPool::globalInstance()->waitForDone(); - QFile::remove(cbzPath); - QVERIFY(resp->textureFactory() == nullptr); delete resp; } diff --git a/tests/FormatRegistryTest.cpp b/tests/FormatRegistryTest.cpp index 496767f..d5346d5 100644 --- a/tests/FormatRegistryTest.cpp +++ b/tests/FormatRegistryTest.cpp @@ -1,11 +1,8 @@ #include #include +#include #include "backend/formats/FormatRegistry.h" #include "backend/FormatReader.h" -#include "backend/IImageProvider.h" -#include "backend/formats/comic/CbzReader.h" -#include "backend/formats/comic/CbrReader.h" -#include "backend/formats/comic/FolderReader.h" #include "backend/formats/sources/DirByteSource.h" #include "backend/formats/sources/RarByteSource.h" #include "backend/formats/sources/ZipByteSource.h" @@ -13,15 +10,12 @@ static FormatRegistry makeRegistry() { return FormatRegistry({ - {QStringLiteral("cbz"), false, QStringLiteral("cbz"), - [] { return std::make_unique(); }, - [] { return std::make_unique(); }}, - {QStringLiteral("cbr"), false, QStringLiteral("cbr"), - [] { return std::make_unique(); }, - [] { return std::make_unique(); }}, - {{}, /*matchesDirectory=*/true, QStringLiteral("dir"), - [] { return std::make_unique(); }, - [] { return std::make_unique(); }}, + FormatSpec::comic(QStringLiteral("cbz"), false, QStringLiteral("cbz"), + [] { return std::make_unique(); }), + FormatSpec::comic(QStringLiteral("cbr"), false, QStringLiteral("cbr"), + [] { return std::make_unique(); }), + FormatSpec::comic({}, /*matchesDirectory=*/true, QStringLiteral("dir"), + [] { return std::make_unique(); }), }); } @@ -32,7 +26,9 @@ private slots: void createCbzReader() { auto registry = makeRegistry(); - QVERIFY(registry.createReader("file.cbz") != nullptr); + auto reader = registry.createReader("file.cbz"); + QVERIFY(reader != nullptr); + QCOMPARE(reader->mode(), ReadingMode::Comic); } void createCbzReaderUpperCase() @@ -72,7 +68,7 @@ private slots: auto registry = makeRegistry(); auto reader = registry.createReader(tmp.path()); QVERIFY(reader != nullptr); - QCOMPARE(reader->fileType(), QStringLiteral("folder")); + QCOMPARE(reader->mode(), ReadingMode::Comic); } void supportedExtensions() @@ -85,24 +81,16 @@ private slots: QCOMPARE(exts.size(), 2); } - void imageProviderSchemesMatchTable() + void registerImageProvidersRegistersSchemes() { auto registry = makeRegistry(); + QQmlEngine engine; + registry.registerImageProviders(engine); - std::unique_ptr cbz(registry.createImageProvider("comic.cbz")); - QVERIFY(cbz); - QCOMPARE(cbz->scheme(), QStringLiteral("cbz")); - - QTemporaryDir tmp; - std::unique_ptr dir(registry.createImageProvider(tmp.path())); - QVERIFY(dir); - QCOMPARE(dir->scheme(), QStringLiteral("dir")); - } - - void formatsWithoutImagesHaveNoProvider() - { - auto registry = makeRegistry(); - QVERIFY(registry.createImageProvider("file.xyz") == nullptr); + QVERIFY(engine.imageProvider(QStringLiteral("cbz")) != nullptr); + QVERIFY(engine.imageProvider(QStringLiteral("cbr")) != nullptr); + QVERIFY(engine.imageProvider(QStringLiteral("dir")) != nullptr); + QVERIFY(engine.imageProvider(QStringLiteral("unknown")) == nullptr); } }; diff --git a/tests/HistoryBookModelTest.cpp b/tests/HistoryBookModelTest.cpp deleted file mode 100644 index 8fdda54..0000000 --- a/tests/HistoryBookModelTest.cpp +++ /dev/null @@ -1,150 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "backend/HistoryBookModel.h" -#include "backend/FormatReader.h" -#include "backend/formats/comic/CbzReader.h" -#include "backend/formats/FormatRegistry.h" -#include "backend/formats/sources/ZipByteSource.h" - -static FormatRegistry makeRegistry() -{ - return FormatRegistry({ - {QStringLiteral("cbz"), false, QStringLiteral("cbz"), - [] { return std::make_unique(); }, - [] { return std::make_unique(); }}, - }); -} - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -static bool addEntry(zipFile zf, const char *name, const QByteArray &data) -{ - zip_fileinfo fi{}; - if (zipOpenNewFileInZip(zf, name, &fi, - nullptr, 0, nullptr, 0, nullptr, - Z_DEFLATED, Z_DEFAULT_COMPRESSION) != ZIP_OK) - return false; - if (zipWriteInFileInZip(zf, data.constData(), (unsigned)data.size()) != ZIP_OK) { - zipCloseFileInZip(zf); - return false; - } - return zipCloseFileInZip(zf) == ZIP_OK; -} - -static QByteArray makePng(int w = 4, int h = 4, QRgb color = qRgb(255, 0, 0)) -{ - QImage img(w, h, QImage::Format_RGB32); - img.fill(color); - QByteArray data; - QBuffer buf(&data); - buf.open(QIODevice::WriteOnly); - img.save(&buf, "PNG"); - return data; -} - -static QString buildCbzWithCover() -{ - static const char kComicInfo[] = - "" - "" - " Cover Test Book" - " Test Author" - ""; - - QTemporaryFile tmp; - tmp.setFileTemplate(QDir::tempPath() + "/hbm_cover_test_XXXXXX.cbz"); - tmp.setAutoRemove(false); - if (!tmp.open()) return {}; - const QString path = tmp.fileName(); - tmp.close(); - - zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE); - if (!zf) return {}; - - bool ok = true; - ok = ok && addEntry(zf, "ComicInfo.xml", QByteArray(kComicInfo)); - ok = ok && addEntry(zf, "001_cover.png", makePng()); - - zipClose(zf, nullptr); - return ok ? path : QString{}; -} - -// --------------------------------------------------------------------------- -// Test class -// --------------------------------------------------------------------------- - -class HistoryBookModelTest : public QObject { - Q_OBJECT - -private slots: - void loadMetadataPopulatesCoverImageUrlForCbz() - { - const QString cbzPath = buildCbzWithCover(); - QVERIFY(!cbzPath.isEmpty()); - - FormatRegistry registry = makeRegistry(); - HistoryBookModel model(cbzPath, 0.0, QString(), registry); - - QSignalSpy spy(&model, &HistoryBookModel::metadataLoaded); - QSignalSpy coverSpy(&model, &HistoryBookModel::coverImageLoaded); - model.loadMetadata(); - - QVERIFY(spy.wait(5000)); - - QFile::remove(cbzPath); - - QCOMPARE(coverSpy.count(), 1); - - const QString url = model.coverImageUrl(); - QVERIFY2(!url.isEmpty(), "coverImageUrl should be set after loadMetadata for a CBZ with cover"); - QVERIFY2(url.startsWith(QStringLiteral("image://cbz/001_cover.png?src=")), - qPrintable("Expected query-param URL format, got: " + url)); - const QString encodedPath = QString::fromUtf8(QUrl::toPercentEncoding(cbzPath)); - QVERIFY2(url.contains(encodedPath), - qPrintable("URL should contain encoded cbz path. URL: " + url)); - } - - void loadMetadataLeavesCoverImageUrlEmptyForMissingFile() - { - FormatRegistry registry = makeRegistry(); - HistoryBookModel model(QStringLiteral("/nonexistent/file.cbz"), 0.0, QString(), registry); - - QSignalSpy spy(&model, &HistoryBookModel::metadataLoaded); - model.loadMetadata(); - - // Should finish or not crash, coverImageUrl remains empty - QVERIFY2(model.coverImageUrl().isEmpty(), - "Missing files have no cover; coverImageUrl should remain empty"); - } - - void loadMetadataPopulatesTitle() - { - const QString cbzPath = buildCbzWithCover(); - QVERIFY(!cbzPath.isEmpty()); - - FormatRegistry registry = makeRegistry(); - HistoryBookModel model(cbzPath, 0.0, QString(), registry); - - QSignalSpy spy(&model, &HistoryBookModel::metadataLoaded); - model.loadMetadata(); - QVERIFY(spy.wait(5000)); - - QFile::remove(cbzPath); - - QCOMPARE(model.title(), QStringLiteral("Cover Test Book")); - QCOMPARE(model.author(), QStringLiteral("Test Author")); - } -}; - -QTEST_MAIN(HistoryBookModelTest) -#include "HistoryBookModelTest.moc" diff --git a/tests/HistoryModelTest.cpp b/tests/HistoryModelTest.cpp new file mode 100644 index 0000000..046d420 --- /dev/null +++ b/tests/HistoryModelTest.cpp @@ -0,0 +1,175 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "backend/AppState.h" +#include "backend/FormatReader.h" +#include "backend/HistoryModel.h" +#include "backend/formats/FormatRegistry.h" +#include "backend/formats/sources/ZipByteSource.h" + +static FormatRegistry makeRegistry() +{ + return FormatRegistry({ + FormatSpec::comic(QStringLiteral("cbz"), false, QStringLiteral("cbz"), + [] { return std::make_unique(); }), + }); +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +static bool addEntry(zipFile zf, const char *name, const QByteArray &data) +{ + zip_fileinfo fi{}; + if (zipOpenNewFileInZip(zf, name, &fi, + nullptr, 0, nullptr, 0, nullptr, + Z_DEFLATED, Z_DEFAULT_COMPRESSION) != ZIP_OK) + return false; + if (zipWriteInFileInZip(zf, data.constData(), (unsigned)data.size()) != ZIP_OK) { + zipCloseFileInZip(zf); + return false; + } + return zipCloseFileInZip(zf) == ZIP_OK; +} + +static QByteArray makePng(int w = 4, int h = 4, QRgb color = qRgb(255, 0, 0)) +{ + QImage img(w, h, QImage::Format_RGB32); + img.fill(color); + QByteArray data; + QBuffer buf(&data); + buf.open(QIODevice::WriteOnly); + img.save(&buf, "PNG"); + return data; +} + +static QString buildCbzWithCover() +{ + static const char kComicInfo[] = + "" + "" + " Cover Test Book" + " Test Author" + ""; + + QTemporaryFile tmp; + tmp.setFileTemplate(QDir::tempPath() + "/hbm_cover_test_XXXXXX.cbz"); + tmp.setAutoRemove(false); + if (!tmp.open()) return {}; + const QString path = tmp.fileName(); + tmp.close(); + + zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE); + if (!zf) return {}; + + bool ok = true; + ok = ok && addEntry(zf, "ComicInfo.xml", QByteArray(kComicInfo)); + ok = ok && addEntry(zf, "001_cover.png", makePng()); + + zipClose(zf, nullptr); + return ok ? path : QString{}; +} + +// --------------------------------------------------------------------------- +// Test class +// --------------------------------------------------------------------------- + +class HistoryModelTest : public QObject { + Q_OBJECT + +private slots: + void addOrUpdateAndRoles() + { + FormatRegistry registry = makeRegistry(); + HistoryModel model(registry); + + QSignalSpy countSpy(&model, &HistoryModel::countChanged); + model.addOrUpdateBook(QStringLiteral("/path/to/book.cbz"), 0.42, QStringLiteral("2026-01-01")); + + QCOMPARE(countSpy.count(), 1); + QCOMPARE(model.rowCount(), 1); + + const QModelIndex idx = model.index(0, 0); + QCOMPARE(model.data(idx, HistoryModel::FilePathRole).toString(), QStringLiteral("/path/to/book.cbz")); + QCOMPARE(model.data(idx, HistoryModel::ProgressRole).toDouble(), 0.42); + QCOMPARE(model.data(idx, HistoryModel::LastOpenedRole).toString(), QStringLiteral("2026-01-01")); + QCOMPARE(model.data(idx, HistoryModel::FormatRole).toString(), QStringLiteral("CBZ")); + } + + void loadMetadataPopulatesTitleAndCoverUrl() + { + const QString cbzPath = buildCbzWithCover(); + QVERIFY(!cbzPath.isEmpty()); + + FormatRegistry registry = makeRegistry(); + HistoryModel model(registry); + + QSignalSpy dataSpy(&model, &QAbstractListModel::dataChanged); + model.addOrUpdateBook(cbzPath, 0.0); + + QTRY_VERIFY_WITH_TIMEOUT(dataSpy.count() > 0, 5000); + + QFile::remove(cbzPath); + + const QModelIndex idx = model.index(0, 0); + QCOMPARE(model.data(idx, HistoryModel::TitleRole).toString(), QStringLiteral("Cover Test Book")); + QCOMPARE(model.data(idx, HistoryModel::AuthorRole).toString(), QStringLiteral("Test Author")); + + const QString coverUrl = model.data(idx, HistoryModel::CoverImageUrlRole).toString(); + QVERIFY(!coverUrl.isEmpty()); + QVERIFY(coverUrl.startsWith(QStringLiteral("image://cbz/001_cover.png?src="))); + } + + void removeBook() + { + FormatRegistry registry = makeRegistry(); + HistoryModel model(registry); + + model.addOrUpdateBook(QStringLiteral("/path/to/1.cbz"), 0.1); + model.addOrUpdateBook(QStringLiteral("/path/to/2.cbz"), 0.2); + QCOMPARE(model.rowCount(), 2); + + model.removeBook(QStringLiteral("/path/to/1.cbz")); + QCOMPARE(model.rowCount(), 1); + QCOMPARE(model.filePath(0), QStringLiteral("/path/to/2.cbz")); + } + + void loadAndSaveWithAppState() + { + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/hist-test-XXXXXX.ini")); + (void)f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState appState(s); + + FormatRegistry registry = makeRegistry(); + + { + HistoryModel model(registry); + model.addOrUpdateBook(QStringLiteral("/path/to/book.cbz"), 0.75, QStringLiteral("2026-10-25")); + model.save(appState); + } + + { + HistoryModel model2(registry); + model2.load(appState); + QCOMPARE(model2.rowCount(), 1); + QCOMPARE(model2.filePath(0), QStringLiteral("/path/to/book.cbz")); + QCOMPARE(model2.progress(0), 0.75); + QCOMPARE(model2.lastOpened(0), QStringLiteral("2026-10-25")); + } + } +}; + +QTEST_MAIN(HistoryModelTest) +#include "HistoryModelTest.moc" + diff --git a/tests/ReadingModelTest.cpp b/tests/ReadingModelTest.cpp index f8afbb1..28727ed 100644 --- a/tests/ReadingModelTest.cpp +++ b/tests/ReadingModelTest.cpp @@ -10,8 +10,9 @@ class FakeMangaReader : public FormatReader { public: + ReadingMode mode() const override { return ReadingMode::Comic; } bool open(const QString &) override { return true; } - QString lastError() override { return {}; } + QString lastError() const override { return {}; } QVector pages() const override { return { @@ -20,13 +21,37 @@ public: {QStringLiteral("image://cbz/2.jpg"), QSize(800, 1200)} }; } - 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"); } + QString title() const override { return QStringLiteral("Manga Title"); } + QString author() const override { return QStringLiteral("Manga Author"); } + QString filePath() const override { return QStringLiteral("/fake/manga.cbz"); } + QString coverImageUrl() const override { return QStringLiteral("image://cbz/0.jpg?src=/fake/manga.cbz"); } + QByteArray contentHash() const override { return QByteArray("mangahash"); } bool loadMetadata(const QString &) override { return true; } - QString fileType() const override { return QStringLiteral("cbz"); } +}; + +class FakeTextReader : public FormatReader { +public: + ReadingMode mode() const override { return ReadingMode::Text; } + bool open(const QString &) override { return true; } + QString lastError() const override { return {}; } + QString title() const override { return QStringLiteral("Text Book"); } + QString author() const override { return QStringLiteral("Text Author"); } + QString filePath() const override { return QStringLiteral("/fake/book.epub"); } + QString coverImageUrl() const override { return QStringLiteral("image://epub/cover.jpg?src=/fake/book.epub"); } + QByteArray contentHash() const override { return QByteArray("texthash"); } + bool loadMetadata(const QString &) override { return true; } + + int chapterCount() const override { return 2; } + Chapter loadChapter(int index) const override + { + if (index == 0) + return {0, QStringLiteral("Chapter 1"), {QStringLiteral("

Chunk 1

"), QStringLiteral("

Chunk 2

")}}; + return {1, QStringLiteral("Chapter 2"), {QStringLiteral("

Chunk 3

")}}; + } + QVector tableOfContents() const override + { + return {{QStringLiteral("Chapter 1"), 0, 0}, {QStringLiteral("Chapter 2"), 1, 0}}; + } }; class ReadingModelTest : public QObject { @@ -53,6 +78,7 @@ private slots: void initialState() { Ctx ctx; ReadingModel model(*ctx.store); + QVERIFY(!model.isTextMode()); QCOMPARE(model.progress(), 0.0); QCOMPARE(model.currentPage(), 0); QCOMPARE(model.totalPages(), 0); @@ -69,6 +95,7 @@ private slots: model.setReader(&reader); + QVERIFY(!model.isTextMode()); 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")); @@ -80,18 +107,24 @@ private slots: QCOMPARE(restoreSpy.first().at(0).toInt(), 0); } - void scrollInfoUpdatesCurrentPageAndProgress() + void scrollInfoUpdatesCurrentPageAndProgressAndSaves() { Ctx ctx; ReadingModel model(*ctx.store); FakeMangaReader reader; model.setReader(&reader); QSignalSpy pageSpy(&model, &ReadingModel::currentPageChanged); + QSignalSpy savedSpy(&model, &ReadingModel::positionSaved); model.setScrollInfo(1, 0.5); QCOMPARE(model.currentPage(), 2); QCOMPARE(model.progress(), 0.5); QCOMPARE(pageSpy.count(), 1); + QCOMPARE(savedSpy.count(), 1); + + const auto savedPos = ctx.store->load(reader.contentHash()); + QCOMPARE(savedPos.chunkIndex, 1); + QCOMPARE(savedPos.progress, 0.5); } void landscapeModeAndPageShift() @@ -134,6 +167,44 @@ private slots: QVERIFY(!model.mangaRTL()); } + void textModeChaptersAndChunks() + { + Ctx ctx; ReadingModel model(*ctx.store); + FakeTextReader reader; + QSignalSpy modeSpy(&model, &ReadingModel::modeChanged); + QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady); + + model.setReader(&reader); + + QCOMPARE(modeSpy.count(), 1); + QVERIFY(model.isTextMode()); + QCOMPARE(model.chapterCount(), 2); + QCOMPARE(model.currentChapter(), 0); + QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 1")); + QCOMPARE(model.rowCount(), 2); + QCOMPARE(model.data(model.index(0, 0), ReadingModel::ContentRole).toString(), + QStringLiteral("

Chunk 1

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

Chunk 2

")); + + QTRY_COMPARE(restoreSpy.count(), 1); + + // Next chapter navigation + QSignalSpy chapterSpy(&model, &ReadingModel::currentChapterChanged); + model.nextChapter(); + QCOMPARE(chapterSpy.count(), 1); + QCOMPARE(model.currentChapter(), 1); + QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 2")); + QCOMPARE(model.rowCount(), 1); + QCOMPARE(model.data(model.index(0, 0), ReadingModel::ContentRole).toString(), + QStringLiteral("

Chunk 3

")); + + // Previous chapter navigation + model.previousChapter(); + QCOMPARE(model.currentChapter(), 0); + QCOMPARE(model.rowCount(), 2); + } + void setReaderNullResetsState() { Ctx ctx; ReadingModel model(*ctx.store); @@ -145,6 +216,8 @@ private slots: QCOMPARE(model.totalPages(), 0); QCOMPARE(model.currentPage(), 0); QCOMPARE(model.progress(), 0.0); + QVERIFY(!model.isTextMode()); + QCOMPARE(model.rowCount(), 0); } }; diff --git a/tests/book/BookTest.cpp b/tests/book/BookTest.cpp index 8827612..6d9cacc 100644 --- a/tests/book/BookTest.cpp +++ b/tests/book/BookTest.cpp @@ -1,17 +1,13 @@ #include #include #include -#include #include #include #include -#include "backend/AppState.h" #include "backend/IFileDialogService.h" #include "backend/formats/FormatRegistry.h" -#include "backend/formats/comic/FolderReader.h" #include "backend/formats/sources/DirByteSource.h" -#include "backend/state/BookPositionStore.h" #include "backend/book/Book.h" // Minimal fake dialog service — never opens a dialog; used to satisfy the Book constructor. @@ -37,35 +33,22 @@ private: } struct Ctx { - QTemporaryFile f; - QSettings *s = nullptr; - AppState *appState = nullptr; - BookPositionStore *store = nullptr; FakeDialogService *dialog = nullptr; FormatRegistry *factory = nullptr; Book *book = nullptr; Ctx() { - f.setFileTemplate(QDir::tempPath() + QStringLiteral("/book-test-XXXXXX.ini")); - (void)f.open(); f.close(); - s = new QSettings(f.fileName(), QSettings::IniFormat); - appState = new AppState(*s); - store = new BookPositionStore(*appState); dialog = new FakeDialogService; factory = new FormatRegistry({ - {{}, /*matchesDirectory=*/true, QStringLiteral("dir"), - [] { return std::make_unique(); }, - [] { return std::make_unique(); }}, + FormatSpec::comic({}, /*matchesDirectory=*/true, QStringLiteral("dir"), + [] { return std::make_unique(); }), }); - book = new Book(*dialog, *store, *factory); + book = new Book(*dialog, *factory); } ~Ctx() { delete book; delete dialog; delete factory; - delete store; - delete appState; - delete s; } }; @@ -80,6 +63,7 @@ private slots: QCOMPARE(ctx.book->filePath(), QString()); QCOMPARE(ctx.book->coverImageUrl(),QString()); QCOMPARE(ctx.book->errorMessage(), QString()); + QVERIFY(ctx.book->tableOfContents().isEmpty()); } void openValidFile() @@ -101,6 +85,7 @@ private slots: QCOMPARE(ctx.book->filePath(), path); QVERIFY(!ctx.book->title().isEmpty()); QVERIFY(bookChanged.count() > 0); + QVERIFY(ctx.book->coverImageUrl().startsWith(QStringLiteral("image://dir/"))); } void openInvalidPath() @@ -181,26 +166,6 @@ private slots: ctx.dialog->triggerFile(path); QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); } - - void saveCurrentPositionUsesHash() - { - QTemporaryDir tmp; - const QString path = createSampleComic(tmp); - QVERIFY(!path.isEmpty()); - - Ctx ctx; - ctx.book->openFromPath(path); - QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); - - 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.mangaRTL, false); - QCOMPARE(pos.pageShift, true); - } }; QTEST_MAIN(BookTest) diff --git a/tests/formats/CbzReaderTest.cpp b/tests/formats/CbzReaderTest.cpp index bd8afb0..fbd56fc 100644 --- a/tests/formats/CbzReaderTest.cpp +++ b/tests/formats/CbzReaderTest.cpp @@ -7,7 +7,8 @@ #include -#include "backend/formats/comic/CbzReader.h" +#include "backend/formats/comic/ComicReader.h" +#include "backend/formats/sources/ZipByteSource.h" // --------------------------------------------------------------------------- // Fixture helpers @@ -67,6 +68,11 @@ static QString buildCbz(const QList> &entries) return path; } +static ComicReader makeCbzReader() +{ + return ComicReader([] { return std::make_unique(); }, QStringLiteral("cbz")); +} + // --------------------------------------------------------------------------- // Test class // --------------------------------------------------------------------------- @@ -95,7 +101,7 @@ private slots: void openNonexistentFile() { - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(!reader.open("/does/not/exist.cbz")); QVERIFY(!reader.lastError().isEmpty()); } @@ -109,7 +115,7 @@ private slots: tmp.close(); m_tempFiles.append(tmp.fileName()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(!reader.open(tmp.fileName())); QVERIFY(!reader.lastError().isEmpty()); } @@ -119,7 +125,7 @@ private slots: const QString path = makeCbz({{"readme.txt", "hello"}}); QVERIFY(!path.isEmpty()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(!reader.open(path)); QVERIFY(!reader.lastError().isEmpty()); } @@ -135,7 +141,7 @@ private slots: }); QVERIFY(!path.isEmpty()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.open(path)); QCOMPARE(reader.pages().size(), 3); } @@ -150,7 +156,7 @@ private slots: }); QVERIFY(!path.isEmpty()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.open(path)); const auto pages = reader.pages(); QCOMPARE(pages.size(), 3); @@ -167,19 +173,20 @@ private slots: }); QVERIFY(!path.isEmpty()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.open(path)); const auto pages = reader.pages(); QCOMPARE(pages.size(), 2); for (const PageInfo &page : pages) { QVERIFY(page.imageUrl.startsWith(QLatin1String("image://cbz/"))); + QVERIFY(page.imageUrl.contains(QLatin1String("?src="))); } } void emptyPagesBeforeOpen() { - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.pages().isEmpty()); } @@ -197,7 +204,7 @@ private slots: }); QVERIFY(!path.isEmpty()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.open(path)); QCOMPARE(reader.title(), QStringLiteral("My Comic")); QCOMPARE(reader.author(), QStringLiteral("Art Spiegelman")); @@ -215,7 +222,7 @@ private slots: }); QVERIFY(!path.isEmpty()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.open(path)); QCOMPARE(reader.title(), QStringLiteral("Batman #42")); } @@ -235,7 +242,7 @@ private slots: }); QVERIFY(!path.isEmpty()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.open(path)); QCOMPARE(reader.title(), QStringLiteral("Special Edition")); } @@ -247,7 +254,7 @@ private slots: const QString path = makeCbz({{"page001.png", makePng()}}); QVERIFY(!path.isEmpty()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.open(path)); QVERIFY(!reader.title().isEmpty()); // Title must equal the file's base name (no extension) @@ -266,9 +273,10 @@ private slots: }); QVERIFY(!path.isEmpty()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.open(path)); - QCOMPARE(reader.coverImagePath(), QStringLiteral("page001.jpg")); + QVERIFY(reader.coverImageUrl().contains(QStringLiteral("page001.jpg"))); + QVERIFY(reader.coverImageUrl().startsWith(QStringLiteral("image://cbz/"))); } void coverFromComicInfoFrontCover() @@ -291,9 +299,9 @@ private slots: }); QVERIFY(!path.isEmpty()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.open(path)); - QCOMPARE(reader.coverImagePath(), QStringLiteral("page002.jpg")); + QVERIFY(reader.coverImageUrl().contains(QStringLiteral("page002.jpg"))); } // --- content hash --- @@ -303,7 +311,8 @@ private slots: const QString path = makeCbz({{"page001.png", makePng()}}); QVERIFY(!path.isEmpty()); - CbzReader r1, r2; + auto r1 = makeCbzReader(); + auto r2 = makeCbzReader(); QVERIFY(r1.open(path)); QVERIFY(r2.open(path)); QVERIFY(!r1.contentHash().isEmpty()); @@ -312,7 +321,7 @@ private slots: void contentHashEmptyBeforeOpen() { - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.contentHash().isEmpty()); } @@ -330,7 +339,7 @@ private slots: }); QVERIFY(!path.isEmpty()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.loadMetadata(path)); QCOMPARE(reader.title(), QStringLiteral("Light Meta")); // contentHash must be empty (loadMetadata is lightweight) @@ -345,17 +354,17 @@ private slots: }); QVERIFY(!path.isEmpty()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.loadMetadata(path)); - QCOMPARE(reader.coverImagePath(), QStringLiteral("page001.jpg")); + QVERIFY(reader.coverImageUrl().contains(QStringLiteral("page001.jpg"))); } - // --- file type --- + // --- reading mode --- - void fileType() + void readingMode() { - CbzReader reader; - QCOMPARE(reader.fileType(), QStringLiteral("cbz")); + auto reader = makeCbzReader(); + QCOMPARE(reader.mode(), ReadingMode::Comic); } // --- skips __MACOSX entries --- @@ -368,7 +377,7 @@ private slots: }); QVERIFY(!path.isEmpty()); - CbzReader reader; + auto reader = makeCbzReader(); QVERIFY(reader.open(path)); QCOMPARE(reader.pages().size(), 1); } diff --git a/tests/formats/FolderReaderTest.cpp b/tests/formats/FolderReaderTest.cpp index a4f75ac..f878e3f 100644 --- a/tests/formats/FolderReaderTest.cpp +++ b/tests/formats/FolderReaderTest.cpp @@ -3,7 +3,8 @@ #include #include -#include "backend/formats/comic/FolderReader.h" +#include "backend/formats/comic/ComicReader.h" +#include "backend/formats/sources/DirByteSource.h" // --------------------------------------------------------------------------- // Helpers @@ -16,6 +17,11 @@ static bool writePng(const QString &path, int w = 8, int h = 8, QColor color = Q return img.save(path, "PNG"); } +static ComicReader makeFolderReader() +{ + return ComicReader([] { return std::make_unique(); }, QStringLiteral("dir")); +} + // --------------------------------------------------------------------------- // Tests // --------------------------------------------------------------------------- @@ -28,7 +34,7 @@ private slots: { QTemporaryDir tmp; QVERIFY(tmp.isValid()); - FolderReader reader; + auto reader = makeFolderReader(); QVERIFY(!reader.open(tmp.path())); // no images → error } @@ -40,7 +46,7 @@ private slots: QVERIFY(writePng(tmp.filePath(QStringLiteral("02.png")))); QVERIFY(writePng(tmp.filePath(QStringLiteral("03.png")))); - FolderReader reader; + auto reader = makeFolderReader(); QVERIFY(reader.open(tmp.path())); QCOMPARE(reader.pages().size(), 3); } @@ -53,7 +59,7 @@ private slots: QVERIFY(writePng(tmp.filePath(QStringLiteral("a.png")))); QVERIFY(writePng(tmp.filePath(QStringLiteral("b.png")))); - FolderReader reader; + auto reader = makeFolderReader(); QVERIFY(reader.open(tmp.path())); const auto pages = reader.pages(); QCOMPARE(pages.size(), 3); @@ -69,9 +75,10 @@ private slots: QVERIFY(writePng(tmp.filePath(QStringLiteral("01.png")))); QVERIFY(writePng(tmp.filePath(QStringLiteral("02.png")))); - FolderReader reader; + auto reader = makeFolderReader(); QVERIFY(reader.open(tmp.path())); - QCOMPARE(reader.coverImagePath(), QStringLiteral("01.png")); + QVERIFY(reader.coverImageUrl().contains(QStringLiteral("01.png"))); + QVERIFY(reader.coverImageUrl().startsWith(QStringLiteral("image://dir/"))); } void titleIsFolderBasename() @@ -80,7 +87,7 @@ private slots: QVERIFY(tmp.isValid()); QVERIFY(writePng(tmp.filePath(QStringLiteral("page.png")))); - FolderReader reader; + auto reader = makeFolderReader(); QVERIFY(reader.open(tmp.path())); QCOMPARE(reader.title(), QDir(tmp.path()).dirName()); } @@ -94,16 +101,17 @@ private slots: QVERIFY(writePng(tmpA.filePath(QStringLiteral("page.png")))); QVERIFY(writePng(tmpB.filePath(QStringLiteral("page.png")))); - FolderReader ra, rb; + auto ra = makeFolderReader(); + auto rb = makeFolderReader(); QVERIFY(ra.open(tmpA.path())); QVERIFY(rb.open(tmpB.path())); QCOMPARE(ra.contentHash(), rb.contentHash()); } - void fileType() + void readingMode() { - FolderReader reader; - QCOMPARE(reader.fileType(), QStringLiteral("folder")); + auto reader = makeFolderReader(); + QCOMPARE(reader.mode(), ReadingMode::Comic); } void nonImageFilesIgnored() @@ -117,7 +125,7 @@ private slots: txt.write("hello"); txt.close(); - FolderReader reader; + auto reader = makeFolderReader(); QVERIFY(reader.open(tmp.path())); QCOMPARE(reader.pages().size(), 1); } @@ -129,7 +137,7 @@ private slots: QVERIFY(writePng(tmp.filePath(QStringLiteral("page.png")))); QVERIFY(writePng(tmp.filePath(QStringLiteral(".hidden.png")))); - FolderReader reader; + auto reader = makeFolderReader(); QVERIFY(reader.open(tmp.path())); QCOMPARE(reader.pages().size(), 1); } diff --git a/tests/formats/ImageUrlTest.cpp b/tests/formats/ImageUrlTest.cpp index 9552a79..9283869 100644 --- a/tests/formats/ImageUrlTest.cpp +++ b/tests/formats/ImageUrlTest.cpp @@ -50,6 +50,34 @@ private slots: const auto parsed = ImageUrl::parseProviderId(QStringLiteral("page%2001.jpg")); QCOMPARE(parsed.entry, QStringLiteral("page 01.jpg")); } + + void resolveWebUrls() + { + const QString book = QStringLiteral("/books/test.epub"); + QCOMPARE(ImageUrl::resolve(QStringLiteral("epub"), QStringLiteral("http://example.com/pic.png"), book), + QStringLiteral("image://web/http://example.com/pic.png")); + QCOMPARE(ImageUrl::resolve(QStringLiteral("epub"), QStringLiteral("https://example.com/pic.png"), book), + QStringLiteral("image://web/https://example.com/pic.png")); + } + + void resolveRelativeUrlsWithBaseDir() + { + const QString book = QStringLiteral("/books/test.epub"); + const QString url = ImageUrl::resolve(QStringLiteral("epub"), + QStringLiteral("../images/pic.png"), + book, + QStringLiteral("OEBPS/text/")); + QVERIFY(url.startsWith(QStringLiteral("image://epub/OEBPS/images/pic.png?src="))); + } + + void resolveFb2Fragment() + { + const QString book = QStringLiteral("/books/test.fb2"); + const QString url = ImageUrl::resolve(QStringLiteral("fb2"), + QStringLiteral("#cover.png"), + book); + QVERIFY(url.startsWith(QStringLiteral("image://fb2/cover.png?src="))); + } }; QTEST_MAIN(ImageUrlTest) diff --git a/tests/state/BookPositionStoreTest.cpp b/tests/state/BookPositionStoreTest.cpp index 7b90535..5025d82 100644 --- a/tests/state/BookPositionStoreTest.cpp +++ b/tests/state/BookPositionStoreTest.cpp @@ -21,9 +21,11 @@ private slots: BookPositionStore store(appState); const BookPosition pos = store.load(QByteArray("nonexistent")); + QCOMPARE(pos.chapterIndex, 0); QCOMPARE(pos.chunkIndex, 0); - QCOMPARE(pos.pageShift, true); - QCOMPARE(pos.mangaRTL, true); + QCOMPARE(pos.progress, 0.0); + QCOMPARE(pos.pageShift, true); + QCOMPARE(pos.mangaRTL, true); } void saveAndLoad() @@ -36,11 +38,20 @@ private slots: BookPositionStore store(appState); const QByteArray hash = QByteArray("abc123deadbeef"); - store.save(hash, 7, false, false); + BookPosition toSave; + toSave.chapterIndex = 2; + toSave.chunkIndex = 7; + toSave.progress = 0.65; + toSave.mangaRTL = false; + toSave.pageShift = false; + store.save(hash, toSave); + const BookPosition pos = store.load(hash); + QCOMPARE(pos.chapterIndex, 2); QCOMPARE(pos.chunkIndex, 7); - QCOMPARE(pos.mangaRTL, false); - QCOMPARE(pos.pageShift, false); + QCOMPARE(pos.progress, 0.65); + QCOMPARE(pos.mangaRTL, false); + QCOMPARE(pos.pageShift, false); } void separateHashesStoredIndependently() @@ -52,8 +63,17 @@ private slots: AppState appState(s); BookPositionStore store(appState); - store.save(QByteArray("hash1"), 1, true, false); - store.save(QByteArray("hash2"), 2, false, true); + BookPosition p1; + p1.chunkIndex = 1; + p1.mangaRTL = true; + p1.pageShift = false; + store.save(QByteArray("hash1"), p1); + + BookPosition p2; + p2.chunkIndex = 2; + p2.mangaRTL = false; + p2.pageShift = true; + store.save(QByteArray("hash2"), p2); QCOMPARE(store.load(QByteArray("hash1")).chunkIndex, 1); QCOMPARE(store.load(QByteArray("hash2")).chunkIndex, 2); @@ -71,8 +91,15 @@ private slots: BookPositionStore store(appState); const QByteArray hash = QByteArray("overwrite-hash"); - store.save(hash, 3, true, true); - store.save(hash, 5, false, false); + BookPosition p1; + p1.chunkIndex = 3; + store.save(hash, p1); + + BookPosition p2; + p2.chunkIndex = 5; + p2.mangaRTL = false; + p2.pageShift = false; + store.save(hash, p2); const BookPosition pos = store.load(hash); QCOMPARE(pos.chunkIndex, 5); @@ -89,8 +116,9 @@ private slots: AppState appState(s); BookPositionStore store(appState); - // Neither save nor load should crash with an empty hash - store.save(QByteArray(), 1, true, true); + BookPosition p; + p.chunkIndex = 1; + store.save(QByteArray(), p); const BookPosition pos = store.load(QByteArray()); QCOMPARE(pos.chunkIndex, 0); }