From 9280c838b2af4ec49ac87291d100d686b4e9fc42 Mon Sep 17 00:00:00 2001 From: Agel Date: Wed, 8 Apr 2026 14:01:03 +0200 Subject: [PATCH] Some refactor --- CLAUDE.md | 2 +- CMakeLists.txt | 53 ++- src/backend/AppState.cpp | 292 ++------------ src/backend/AppState.h | 115 +----- src/backend/FormatReader.h | 4 + src/backend/LibraryModel.cpp | 31 ++ src/backend/LibraryModel.h | 7 + src/backend/ReadingModel.cpp | 14 +- src/backend/ReadingModel.h | 4 +- src/backend/book/Book.cpp | 145 +++++++ src/backend/book/Book.h | 83 ++++ src/backend/formats/EpubReader.cpp | 15 + src/backend/formats/EpubReader.h | 2 + src/backend/formats/TxtReader.cpp | 8 + src/backend/formats/TxtReader.h | 2 + src/backend/state/BookPositionStore.cpp | 32 ++ src/backend/state/BookPositionStore.h | 28 ++ src/backend/state/ReadingPreferences.cpp | 55 +++ src/backend/state/ReadingPreferences.h | 42 ++ src/backend/state/UiState.cpp | 99 +++++ src/backend/state/UiState.h | 63 +++ src/main.cpp | 170 ++++++-- src/qml/Main.qml | 114 +++--- src/qml/ThemeManager.qml | 21 +- src/qml/components/ErrorPopup.qml | 6 +- src/qml/components/Footer.qml | 10 +- src/qml/components/Header.qml | 2 +- src/qml/components/PageView.qml | 45 +-- src/qml/components/SideBar.qml | 6 +- src/qml/pages/LibraryPage.qml | 10 +- src/qml/pages/SettingsPage.qml | 24 +- tests/AppStateTest.cpp | 489 ++++------------------- tests/ReadingModelTest.cpp | 78 ++-- tests/book/BookTest.cpp | 221 ++++++++++ tests/state/BookPositionStoreTest.cpp | 98 +++++ tests/state/ReadingPreferencesTest.cpp | 81 ++++ tests/state/UiStateTest.cpp | 109 +++++ 37 files changed, 1599 insertions(+), 981 deletions(-) create mode 100644 src/backend/book/Book.cpp create mode 100644 src/backend/book/Book.h create mode 100644 src/backend/state/BookPositionStore.cpp create mode 100644 src/backend/state/BookPositionStore.h create mode 100644 src/backend/state/ReadingPreferences.cpp create mode 100644 src/backend/state/ReadingPreferences.h create mode 100644 src/backend/state/UiState.cpp create mode 100644 src/backend/state/UiState.h create mode 100644 tests/book/BookTest.cpp create mode 100644 tests/state/BookPositionStoreTest.cpp create mode 100644 tests/state/ReadingPreferencesTest.cpp create mode 100644 tests/state/UiStateTest.cpp diff --git a/CLAUDE.md b/CLAUDE.md index 0c0b30c..dc344cc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -269,4 +269,4 @@ All colors are defined in `src/qml/Theme.qml` (a QML singleton registered via `q - `QSettings` for persistent state - Qt naming: `camelCase` properties/methods, `PascalCase` QML component names - `Q_INVOKABLE` for QML-callable methods; signals for C++→QML notifications -- **Never use timers to wait for state to settle** — always use signals (`onRunningChanged`, `onCompleted`, etc.) or direct synchronous calls. Timeouts are fragile and mask real sequencing problems. +- QT needs a moment to settle (otherwise there's a noticeable all-white window flash), so the main window MUST be opened with opacity 0 and then on timer ticked to 1 and continue initializing. \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index e51de8a..a70fdc4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,8 +42,14 @@ set(SOURCES src/backend/LibraryModel.cpp src/backend/ReadingModel.h src/backend/ReadingModel.cpp - src/backend/BookController.h - src/backend/BookController.cpp + src/backend/state/ReadingPreferences.h + src/backend/state/ReadingPreferences.cpp + src/backend/state/UiState.h + src/backend/state/UiState.cpp + src/backend/state/BookPositionStore.h + src/backend/state/BookPositionStore.cpp + src/backend/book/Book.h + src/backend/book/Book.cpp src/backend/IImageProvider.h src/backend/EpubImageProvider.h src/backend/EpubImageProvider.cpp @@ -214,6 +220,7 @@ add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp src/backend/ChunkMeasurer.cpp src/backend/EpubImageProvider.cpp src/backend/AppState.cpp + src/backend/state/BookPositionStore.cpp src/backend/LibraryBookModel.cpp src/backend/LibraryModel.cpp src/backend/ReaderFactory.cpp @@ -222,32 +229,34 @@ add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp target_link_libraries(ReadingModelTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP Qt6::Xml) set_tests_properties(ReadingModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") -add_asteria_test(BookControllerTest tests/BookControllerTest.cpp - src/backend/BookController.cpp +add_asteria_test(AppStateTest tests/AppStateTest.cpp + src/backend/AppState.cpp) + +add_asteria_test(ReadingPreferencesTest tests/state/ReadingPreferencesTest.cpp src/backend/AppState.cpp - src/backend/LibraryBookModel.cpp - src/backend/LibraryModel.cpp + src/backend/state/ReadingPreferences.cpp) +set_tests_properties(ReadingPreferencesTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + +add_asteria_test(UiStateTest tests/state/UiStateTest.cpp + src/backend/AppState.cpp + src/backend/state/UiState.cpp) +set_tests_properties(UiStateTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") + +add_asteria_test(BookPositionStoreTest tests/state/BookPositionStoreTest.cpp + src/backend/AppState.cpp + src/backend/state/BookPositionStore.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/ReaderFactory.cpp - src/backend/ReadingModel.cpp src/backend/IFileDialogService.cpp src/backend/NativeFileDialogService.cpp - src/backend/ImageProviderFactory.cpp - src/backend/ImageLoaderFactory.cpp - src/backend/EpubImageProvider.cpp - src/backend/ChunkMeasurer.cpp src/backend/formats/TxtReader.cpp src/backend/formats/EpubReader.cpp) -add_asteria_test(AppStateTest tests/AppStateTest.cpp - src/backend/AppState.cpp - src/backend/LibraryBookModel.cpp - src/backend/LibraryModel.cpp - src/backend/ReaderFactory.cpp - src/backend/formats/TxtReader.cpp - src/backend/formats/EpubReader.cpp) -target_link_libraries(AppStateTest PRIVATE PkgConfig::MINIZIP Qt6::Xml Qt6::Concurrent) - -target_link_libraries(BookControllerTest PRIVATE Qt6::Widgets Qt6::Quick Qt6::Gui PkgConfig::MINIZIP Qt6::Xml Qt6::Concurrent) -set_tests_properties(BookControllerTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") +target_link_libraries(BookTest PRIVATE Qt6::Concurrent Qt6::Widgets PkgConfig::MINIZIP Qt6::Xml) +set_tests_properties(BookTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") add_asteria_test(EpubImageProviderTest tests/EpubImageProviderTest.cpp src/backend/EpubImageProvider.cpp) diff --git a/src/backend/AppState.cpp b/src/backend/AppState.cpp index e6e63c4..c8fea44 100644 --- a/src/backend/AppState.cpp +++ b/src/backend/AppState.cpp @@ -1,279 +1,57 @@ #include "AppState.h" -#include "LibraryBookModel.h" -#include "LibraryModel.h" -#include -static constexpr int SETTINGS_VERSION = 3; - -static QString bookSettingsKey(const QString &filePath) +AppState::AppState(QSettings &settings) + : m_settings(settings) { - QByteArray hash = QCryptographicHash::hash(filePath.toUtf8(), QCryptographicHash::Md5).toHex(); - return QStringLiteral("bookmarks/") + QString::fromLatin1(hash); + if (m_settings.value(QStringLiteral("version"), 0).toInt() != SETTINGS_VERSION) { + m_settings.clear(); + m_settings.setValue(QStringLiteral("version"), SETTINGS_VERSION); + } } -AppState::AppState(QObject *parent) - : QObject(parent) +QVariantMap AppState::loadSection(const QString §ion) const { - m_libraryModel = new LibraryModel(this); -} - -QString AppState::lastFilePath() const { return m_lastFilePath; } - -void AppState::setLastFilePath(const QString &path) -{ - if (m_lastFilePath == path) - return; - m_lastFilePath = path; - emit lastFilePathChanged(); -} - -int AppState::horizontalMargin() const { return m_horizontalMargin; } - -void AppState::setHorizontalMargin(int margin) -{ - if (m_horizontalMargin == margin) - return; - m_horizontalMargin = margin; - emit horizontalMarginChanged(); -} - -int AppState::verticalMargin() const { return m_verticalMargin; } - -void AppState::setVerticalMargin(int margin) -{ - if (m_verticalMargin == margin) - return; - m_verticalMargin = margin; - emit verticalMarginChanged(); -} - -int AppState::fontSize() const { return m_fontSize; } - -void AppState::setFontSize(int size) -{ - if (m_fontSize == size) - return; - m_fontSize = size; - emit fontSizeChanged(); -} - -qreal AppState::lineSpacing() const { return m_lineSpacing; } - -void AppState::setLineSpacing(qreal spacing) -{ - if (qFuzzyCompare(m_lineSpacing, spacing)) - return; - m_lineSpacing = spacing; - emit lineSpacingChanged(); -} - -int AppState::windowWidth() const { return m_windowWidth; } - -void AppState::setWindowWidth(int width) -{ - if (m_windowWidth == width) - return; - m_windowWidth = width; - emit windowWidthChanged(); -} - -int AppState::windowHeight() const { return m_windowHeight; } - -void AppState::setWindowHeight(int height) -{ - if (m_windowHeight == height) - return; - m_windowHeight = height; - emit windowHeightChanged(); -} - -int AppState::windowX() const { return m_windowX; } - -void AppState::setWindowX(int x) -{ - if (m_windowX == x) - return; - m_windowX = x; - emit windowXChanged(); -} - -int AppState::windowY() const { return m_windowY; } - -void AppState::setWindowY(int y) -{ - if (m_windowY == y) - return; - m_windowY = y; - emit windowYChanged(); -} - -QUrl AppState::lastFileUrl() const -{ - return QUrl::fromLocalFile(m_lastFilePath); -} - -void AppState::saveBookPosition(const QString &filePath, int chunkIndex, int intraChunkOffset) -{ - qInfo() << "Saving book position: chunk" << chunkIndex << "offset" << intraChunkOffset; - QSettings s; - QString key = bookSettingsKey(filePath); - s.setValue(key + QStringLiteral("/chunkIndex"), chunkIndex); - s.setValue(key + QStringLiteral("/intraChunkOffset"), intraChunkOffset); -} - -QVariantMap AppState::loadBookPosition(const QString &filePath) -{ - QSettings s; - QString key = bookSettingsKey(filePath); QVariantMap result; - result[QStringLiteral("chunkIndex")] = s.value(key + QStringLiteral("/chunkIndex"), 0).toInt(); - result[QStringLiteral("intraChunkOffset")] = s.value(key + QStringLiteral("/intraChunkOffset"), 0.0).toInt(); + m_settings.beginGroup(section); + const QStringList keys = m_settings.childKeys(); + for (const QString &key : keys) + result[key] = m_settings.value(key); + m_settings.endGroup(); return result; } -QString AppState::lastPage() const { return m_lastPage; } - -void AppState::setLastPage(const QString &page) +void AppState::saveSection(const QString §ion, const QVariantMap &data) const { - if (m_lastPage == page) - return; - m_lastPage = page; - emit lastPageChanged(); + m_settings.beginGroup(section); + m_settings.remove(QStringLiteral("")); // clear existing group + for (auto it = data.cbegin(); it != data.cend(); ++it) + m_settings.setValue(it.key(), it.value()); + m_settings.endGroup(); } -bool AppState::sidebarOpen() const { return m_sidebarOpen; } - -void AppState::setSidebarOpen(bool open) +QList AppState::loadArray(const QString §ion) const { - if (m_sidebarOpen == open) - return; - m_sidebarOpen = open; - emit sidebarOpenChanged(); -} - -QString AppState::themeName() const { return m_themeName; } - -void AppState::setThemeName(const QString &themeName) -{ - if (m_themeName == themeName) - return; - m_themeName = themeName; - emit themeNameChanged(); -} - -void AppState::addOrUpdateLibraryBook(const QString &filePath, double progress) -{ - QString lastOpened = QDateTime::currentDateTime().toString(Qt::ISODate); - - // Sentinel: progress < 0 means "preserve existing progress" - double resolvedProgress = progress; - if (progress < 0.0) { - LibraryBookModel* existing = m_libraryModel->findBook(filePath); - resolvedProgress = existing ? existing->progress() : 0.0; - } - - m_libraryModel->addOrUpdateBook(filePath, resolvedProgress, lastOpened); - saveLibraryBooks(); -} - -void AppState::removeLibraryBook(const QString &filePath) -{ - m_libraryModel->removeBook(filePath); - saveLibraryBooks(); -} - -QObject* AppState::libraryModel() const -{ - // Add null check to prevent crashes during initialization - if (!m_libraryModel) { - qWarning() << "LibraryModel accessed before initialization"; - return nullptr; - } - return m_libraryModel; -} - -void AppState::loadLibraryBooks() -{ - QSettings s; - int size = s.beginReadArray(QStringLiteral("library")); - for (int i = 0; i < size; i++) { + QList result; + QSettings &s = const_cast(m_settings); + const int size = s.beginReadArray(section); + for (int i = 0; i < size; ++i) { s.setArrayIndex(i); - QString filePath = s.value(QStringLiteral("filePath")).toString(); - if (filePath.isEmpty()) - continue; - bool progressOk; - double progress = s.value(QStringLiteral("progress"), 0.0).toDouble(&progressOk); - if (!progressOk) - progress = 0.0; - progress = qBound(0.0, progress, 1.0); - QString lastOpened = s.value(QStringLiteral("lastOpened")).toString(); - m_libraryModel->addOrUpdateBook(filePath, progress, lastOpened); + QVariantMap entry; + for (const QString &key : s.childKeys()) + entry[key] = s.value(key); + result.append(entry); } s.endArray(); + return result; } -void AppState::saveLibraryBooks() +void AppState::saveArray(const QString §ion, const QList &items) const { - QSettings s; - QList books = m_libraryModel->books(); - s.beginWriteArray(QStringLiteral("library"), books.size()); - for (int i = 0; i < books.size(); i++) { - s.setArrayIndex(i); - LibraryBookModel* book = books[i]; - s.setValue(QStringLiteral("filePath"), book->filePath()); - s.setValue(QStringLiteral("progress"), book->progress()); - s.setValue(QStringLiteral("lastOpened"), book->lastOpened()); + m_settings.beginWriteArray(section, items.size()); + for (int i = 0; i < items.size(); ++i) { + m_settings.setArrayIndex(i); + for (auto it = items[i].cbegin(); it != items[i].cend(); ++it) + m_settings.setValue(it.key(), it.value()); } - s.endArray(); -} - -void AppState::save() -{ - QSettings s; - s.setValue(QStringLiteral("version"), SETTINGS_VERSION); - s.setValue(QStringLiteral("session/lastFilePath"), m_lastFilePath); - s.setValue(QStringLiteral("session/lastPage"), m_lastPage); - s.setValue(QStringLiteral("session/sidebarOpen"), m_sidebarOpen); - s.setValue(QStringLiteral("preferences/horizontalMargin"), m_horizontalMargin); - s.setValue(QStringLiteral("preferences/verticalMargin"), m_verticalMargin); - s.setValue(QStringLiteral("preferences/fontSize"), m_fontSize); - s.setValue(QStringLiteral("preferences/lineSpacing"), m_lineSpacing); - s.setValue(QStringLiteral("preferences/themeName"), m_themeName); - s.setValue(QStringLiteral("window/width"), m_windowWidth); - s.setValue(QStringLiteral("window/height"), m_windowHeight); - s.setValue(QStringLiteral("window/x"), m_windowX); - s.setValue(QStringLiteral("window/y"), m_windowY); - saveLibraryBooks(); - qInfo() << "filename:" << s.fileName(); -} - -void AppState::restore() -{ - QSettings s; - - // Wipe and start fresh if settings are from a different/incompatible format version - if (s.value(QStringLiteral("version"), 0).toInt() != SETTINGS_VERSION) { - s.clear(); - emit stateRestored(); - return; - } - - m_lastFilePath = s.value(QStringLiteral("session/lastFilePath"), QString()).toString(); - m_lastPage = s.value(QStringLiteral("session/lastPage"), QStringLiteral("starter")).toString(); - m_sidebarOpen = s.value(QStringLiteral("session/sidebarOpen"), false).toBool(); - - m_horizontalMargin = qMax(0, s.value(QStringLiteral("preferences/horizontalMargin"), 32).toInt()); - m_verticalMargin = qMax(0, s.value(QStringLiteral("preferences/verticalMargin"), 8).toInt()); - m_fontSize = qBound(8, s.value(QStringLiteral("preferences/fontSize"), 16).toInt(), 72); - m_lineSpacing = qMax(0.1, s.value(QStringLiteral("preferences/lineSpacing"), 1.6).toDouble()); - m_themeName = s.value(QStringLiteral("preferences/themeName"), QStringLiteral("dark")).toString(); - - m_windowWidth = s.value(QStringLiteral("window/width"), 1024).toInt(); - m_windowHeight = s.value(QStringLiteral("window/height"), 768).toInt(); - m_windowX = s.value(QStringLiteral("window/x"), -1).toInt(); - m_windowY = s.value(QStringLiteral("window/y"), -1).toInt(); - - loadLibraryBooks(); - - emit stateRestored(); + m_settings.endArray(); } diff --git a/src/backend/AppState.h b/src/backend/AppState.h index 6db087b..9d74457 100644 --- a/src/backend/AppState.h +++ b/src/backend/AppState.h @@ -1,114 +1,33 @@ #ifndef APPSTATE_H #define APPSTATE_H -#include -#include -#include +#include #include -class LibraryBookModel; -class LibraryModel; - -class AppState : public QObject { - Q_OBJECT - Q_PROPERTY(QString lastFilePath READ lastFilePath WRITE setLastFilePath NOTIFY lastFilePathChanged) - Q_PROPERTY(int horizontalMargin READ horizontalMargin WRITE setHorizontalMargin NOTIFY horizontalMarginChanged) - Q_PROPERTY(int verticalMargin READ verticalMargin WRITE setVerticalMargin NOTIFY verticalMarginChanged) - Q_PROPERTY(int fontSize READ fontSize WRITE setFontSize NOTIFY fontSizeChanged) - Q_PROPERTY(qreal lineSpacing READ lineSpacing WRITE setLineSpacing NOTIFY lineSpacingChanged) - Q_PROPERTY(int windowWidth READ windowWidth WRITE setWindowWidth NOTIFY windowWidthChanged) - Q_PROPERTY(int windowHeight READ windowHeight WRITE setWindowHeight NOTIFY windowHeightChanged) - Q_PROPERTY(int windowX READ windowX WRITE setWindowX NOTIFY windowXChanged) - Q_PROPERTY(int windowY READ windowY WRITE setWindowY NOTIFY windowYChanged) - - Q_PROPERTY(QString lastPage READ lastPage WRITE setLastPage NOTIFY lastPageChanged) - Q_PROPERTY(bool sidebarOpen READ sidebarOpen WRITE setSidebarOpen NOTIFY sidebarOpenChanged) - Q_PROPERTY(QString themeName READ themeName WRITE setThemeName NOTIFY themeNameChanged) - Q_PROPERTY(QObject* libraryModel READ libraryModel CONSTANT) - +// AppState is a pure persistence service. It wraps QSettings and provides an atomic +// section-based API. It holds no domain state of its own. QML never sees this object. +class AppState { public: - explicit AppState(QObject *parent = nullptr); + static constexpr int SETTINGS_VERSION = 4; - QString themeName() const; - void setThemeName(const QString &themeName); + // Constructs AppState. If the stored version does not match SETTINGS_VERSION, + // all settings are cleared (clean migration). + explicit AppState(QSettings &settings); - QString lastFilePath() const; - void setLastFilePath(const QString &path); + // Load all key/value pairs from the named QSettings group. + QVariantMap loadSection(const QString §ion) const; - int horizontalMargin() const; - void setHorizontalMargin(int margin); + // Atomically replace the named QSettings group with the given data. + void saveSection(const QString §ion, const QVariantMap &data) const; - int verticalMargin() const; - void setVerticalMargin(int margin); + // Load an ordered array (e.g., library books) from the named QSettings array. + QList loadArray(const QString §ion) const; - int fontSize() const; - void setFontSize(int size); - - qreal lineSpacing() const; - void setLineSpacing(qreal spacing); - - int windowWidth() const; - void setWindowWidth(int width); - - int windowHeight() const; - void setWindowHeight(int height); - - int windowX() const; - void setWindowX(int x); - - int windowY() const; - void setWindowY(int y); - - Q_INVOKABLE QUrl lastFileUrl() const; - - Q_INVOKABLE static void saveBookPosition(const QString &filePath, int chunkIndex, int intraChunkOffset); - Q_INVOKABLE static QVariantMap loadBookPosition(const QString &filePath); - - QString lastPage() const; - void setLastPage(const QString &page); - - bool sidebarOpen() const; - void setSidebarOpen(bool open); - - Q_INVOKABLE void addOrUpdateLibraryBook(const QString &filePath, double progress); - Q_INVOKABLE void removeLibraryBook(const QString &filePath); - QObject* libraryModel() const; - - Q_INVOKABLE void save(); - Q_INVOKABLE void restore(); - -signals: - void lastFilePathChanged(); - void horizontalMarginChanged(); - void verticalMarginChanged(); - void fontSizeChanged(); - void lineSpacingChanged(); - void stateRestored(); - void windowWidthChanged(); - void windowHeightChanged(); - void windowXChanged(); - void windowYChanged(); - - void lastPageChanged(); - void sidebarOpenChanged(); - void themeNameChanged(); + // Atomically replace the named QSettings array. + void saveArray(const QString §ion, const QList &items) const; private: - void loadLibraryBooks(); - void saveLibraryBooks(); - QString m_lastFilePath; - int m_horizontalMargin = 32; - int m_verticalMargin = 8; - int m_fontSize = 16; - qreal m_lineSpacing = 1.6; - int m_windowWidth = 1024; - int m_windowHeight = 768; - int m_windowX = -1; - int m_windowY = -1; - LibraryModel* m_libraryModel; - QString m_lastPage = QStringLiteral("starter"); - bool m_sidebarOpen = false; - QString m_themeName = QStringLiteral("dark"); + QSettings &m_settings; }; #endif // APPSTATE_H diff --git a/src/backend/FormatReader.h b/src/backend/FormatReader.h index ccb3bb1..9f0e0f0 100644 --- a/src/backend/FormatReader.h +++ b/src/backend/FormatReader.h @@ -1,6 +1,7 @@ #ifndef FORMATREADER_H #define FORMATREADER_H +#include #include #include @@ -30,6 +31,9 @@ public: 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; }; diff --git a/src/backend/LibraryModel.cpp b/src/backend/LibraryModel.cpp index d2d7bdf..1856832 100644 --- a/src/backend/LibraryModel.cpp +++ b/src/backend/LibraryModel.cpp @@ -1,5 +1,6 @@ #include "LibraryModel.h" #include "LibraryBookModel.h" +#include LibraryModel::LibraryModel(QObject *parent) : QAbstractListModel(parent) @@ -157,6 +158,36 @@ void LibraryModel::clear() emit countChanged(); } +void LibraryModel::addOrUpdateBook(const QString &filePath, double progress) +{ + // Sentinel: progress < 0 means "preserve the existing progress value" + double resolvedProgress = progress; + if (progress < 0.0) { + LibraryBookModel *existing = findBook(filePath); + resolvedProgress = existing ? existing->progress() : 0.0; + } + addOrUpdateBook(filePath, resolvedProgress, + QDateTime::currentDateTime().toString(Qt::ISODate)); +} + +QString LibraryModel::filePath(int index) const +{ + if (index < 0 || index >= m_books.size()) return {}; + return m_books.at(index)->filePath(); +} + +double LibraryModel::progress(int index) const +{ + if (index < 0 || index >= m_books.size()) return 0.0; + return m_books.at(index)->progress(); +} + +QString LibraryModel::lastOpened(int index) const +{ + if (index < 0 || index >= m_books.size()) return {}; + return m_books.at(index)->lastOpened(); +} + QList LibraryModel::books() const { return m_books; diff --git a/src/backend/LibraryModel.h b/src/backend/LibraryModel.h index c8248cc..db290a5 100644 --- a/src/backend/LibraryModel.h +++ b/src/backend/LibraryModel.h @@ -36,10 +36,17 @@ public: // Methods to manage books 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 LibraryBookModel* 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; diff --git a/src/backend/ReadingModel.cpp b/src/backend/ReadingModel.cpp index 1659b53..bbf3e7a 100644 --- a/src/backend/ReadingModel.cpp +++ b/src/backend/ReadingModel.cpp @@ -7,9 +7,11 @@ #include #include -#include "AppState.h" - -ReadingModel::ReadingModel(QObject *parent) : QAbstractListModel(parent) {} +ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent) + : QAbstractListModel(parent) + , m_positions(positions) +{ +} ReadingModel::~ReadingModel() { @@ -126,10 +128,8 @@ void ReadingModel::runMeasurement(const QStringList &htmls, const bool isNew) {PixelHeightRole}); if (isNew) { - QVariantMap map = AppState::loadBookPosition(m_reader->filePath()); - int savedChunk = map.value(QStringLiteral("chunkIndex"), 0).toInt(); - qreal savedIntra = map.value(QStringLiteral("intraChunkOffset"), 0).toInt(); - restoreReady(savedChunk, savedIntra); + const auto pos = m_positions.load(m_reader->contentHash()); + emit restoreReady(pos.chunkIndex, pos.intraOffset); } }, Qt::QueuedConnection); }); diff --git a/src/backend/ReadingModel.h b/src/backend/ReadingModel.h index 24322f0..1d9d934 100644 --- a/src/backend/ReadingModel.h +++ b/src/backend/ReadingModel.h @@ -6,6 +6,7 @@ #include #include #include "IImageLoader.h" +#include "state/BookPositionStore.h" class FormatReader; @@ -35,7 +36,7 @@ public: ChapterRole = Qt::UserRole + 3, }; - explicit ReadingModel(QObject *parent = nullptr); + explicit ReadingModel(BookPositionStore &positions, QObject *parent = nullptr); ~ReadingModel() override; int rowCount(const QModelIndex &parent) const override; @@ -106,6 +107,7 @@ private: int m_fontSize = 0; qreal m_lineSpacing = 0; + BookPositionStore &m_positions; std::unique_ptr m_imageLoader; QFuture m_measureFuture; }; diff --git a/src/backend/book/Book.cpp b/src/backend/book/Book.cpp new file mode 100644 index 0000000..8b9a10e --- /dev/null +++ b/src/backend/book/Book.cpp @@ -0,0 +1,145 @@ +#include "Book.h" +#include "backend/ReaderFactory.h" +#include + +Book::Book(IFileDialogService &dialog, + BookPositionStore &positions, + QObject *parent) + : QObject(parent) + , m_dialog(dialog) + , m_positions(positions) +{ + connect(&m_dialog, &IFileDialogService::fileSelected, + this, &Book::openFromPath); +} + +Book::~Book() +{ + if (m_openFuture.isRunning()) { + m_openFuture.cancel(); + m_openFuture.waitForFinished(); + } +} + +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(); } + +QList Book::toc() const +{ + return m_reader ? m_reader->tableOfContents() : QList{}; +} + +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()); +} + +void Book::openFromPath(const QString &path) +{ + openImpl(path); +} + +void Book::browseAndOpen() +{ + m_dialog.open(); +} + +void Book::openImpl(const QString &filePath) +{ + if (m_reader) + emit willOpenNewBook(); + + close(); + + m_loading = true; + emit loadingChanged(); + + m_errorMessage.clear(); + emit errorMessageChanged(); + + const int generation = ++m_openGeneration; + + m_openFuture = QtConcurrent::run([this, filePath, generation]() { + auto reader = ReaderFactory::create(filePath); + if (!reader) { + QMetaObject::invokeMethod(this, [this, generation]() { + if (generation != m_openGeneration) return; + m_loading = false; + emit loadingChanged(); + m_errorMessage = QStringLiteral("No format reader available for this file type"); + emit errorMessageChanged(); + }, Qt::QueuedConnection); + return; + } + + if (!reader->open(filePath)) { + const QString err = reader->lastError(); + QMetaObject::invokeMethod(this, [this, generation, err]() { + if (generation != m_openGeneration) return; + m_loading = false; + emit loadingChanged(); + m_errorMessage = err; + emit errorMessageChanged(); + }, Qt::QueuedConnection); + return; + } + + auto readerBox = std::make_shared>(std::move(reader)); + + QMetaObject::invokeMethod(this, [this, generation, readerBox]() { + if (generation != m_openGeneration) return; + + m_reader = std::move(*readerBox); + m_coverImageUrl.clear(); + m_loading = false; + emit loadingChanged(); + emit bookChanged(); + }, Qt::QueuedConnection); + }); +} + +void Book::close() +{ + if (!m_reader) return; + m_reader.reset(); + m_coverImageUrl.clear(); + emit bookChanged(); +} + +void Book::clearError() +{ + if (m_errorMessage.isEmpty()) return; + m_errorMessage.clear(); + emit errorMessageChanged(); +} + +void Book::saveCurrentPosition(int chunkIndex, int intraOffset) +{ + if (!m_reader) return; + m_positions.save(m_reader->contentHash(), chunkIndex, intraOffset); +} + +void Book::setContentWidth(int width) +{ + if (m_contentWidth == width) return; + m_contentWidth = width; + emit contentWidthChanged(width); +} diff --git a/src/backend/book/Book.h b/src/backend/book/Book.h new file mode 100644 index 0000000..6acae5a --- /dev/null +++ b/src/backend/book/Book.h @@ -0,0 +1,83 @@ +#ifndef BOOK_H +#define BOOK_H + +#include +#include +#include +#include +#include +#include + +#include "backend/FormatReader.h" +#include "backend/IFileDialogService.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(QList toc READ toc NOTIFY bookChanged) + Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorMessageChanged) +public: + Book(IFileDialogService &dialog, + BookPositionStore &positions, + QObject *parent = nullptr); + ~Book() override; + + bool hasBook() const; + bool loading() const; + QString title() const; + QString author() const; + QString filePath() const; + QString coverImageUrl() const; + QList toc() const; + QString errorMessage() const; + + // Called by main.cpp's bookChanged lambda 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). + FormatReader *reader() const; + + Q_INVOKABLE void openFromUrl(const QUrl &url); + Q_INVOKABLE void openFromPath(const QString &path); + Q_INVOKABLE void browseAndOpen(); + Q_INVOKABLE void close(); + Q_INVOKABLE void clearError(); + + // Save current scroll position. Called from QML's scroll tracker; forwards to BookPositionStore. + Q_INVOKABLE void saveCurrentPosition(int chunkIndex, int intraOffset); + + // Called from QML's PageView when its width changes. Propagates to image provider + ReadingModel + // via the contentWidthChanged signal (wired in main.cpp). + Q_INVOKABLE void setContentWidth(int width); + +signals: + // 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 bookChanged(); + void loadingChanged(); + void errorMessageChanged(); + void contentWidthChanged(int width); + +private: + void openImpl(const QString &filePath); + + IFileDialogService &m_dialog; + BookPositionStore &m_positions; + std::unique_ptr m_reader; + QString m_coverImageUrl; + QString m_errorMessage; + bool m_loading = false; + int m_openGeneration = 0; + int m_contentWidth = 0; + QFuture m_openFuture; +}; + +#endif // BOOK_H diff --git a/src/backend/formats/EpubReader.cpp b/src/backend/formats/EpubReader.cpp index c1f00f5..594979e 100644 --- a/src/backend/formats/EpubReader.cpp +++ b/src/backend/formats/EpubReader.cpp @@ -1,7 +1,9 @@ #include "EpubReader.h" +#include #include #include +#include #include #include #include @@ -35,6 +37,14 @@ bool EpubReader::open(const QString &filePath) m_spineHrefs.clear(); m_spineRawContent.clear(); m_toc.clear(); + m_contentHash.clear(); + + // Compute content hash from raw file bytes before ZIP parsing + { + QFile f(filePath); + if (f.open(QIODevice::ReadOnly)) + m_contentHash = QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5); + } unzFile zf = unzOpen(filePath.toUtf8().constData()); if (!zf) { @@ -390,6 +400,11 @@ QString EpubReader::filePath() return m_filePath; } +QByteArray EpubReader::contentHash() +{ + return m_contentHash; +} + Chapter EpubReader::loadChapter(int index) { if (index < 0 || index >= m_spineRawContent.size()) diff --git a/src/backend/formats/EpubReader.h b/src/backend/formats/EpubReader.h index afc316a..ea69017 100644 --- a/src/backend/formats/EpubReader.h +++ b/src/backend/formats/EpubReader.h @@ -18,9 +18,11 @@ public: QString title() override; QString author() override; QString coverImagePath() override; + QByteArray contentHash() override; private: QString m_filePath; + QByteArray m_contentHash; QString m_title; QString m_author; QString m_error; diff --git a/src/backend/formats/TxtReader.cpp b/src/backend/formats/TxtReader.cpp index 3993bb7..1c33611 100644 --- a/src/backend/formats/TxtReader.cpp +++ b/src/backend/formats/TxtReader.cpp @@ -1,5 +1,6 @@ #include "TxtReader.h" +#include #include #include #include @@ -110,6 +111,8 @@ bool TxtReader::open(const QString &filePath) QByteArray raw = file.readAll(); file.close(); + m_contentHash = QCryptographicHash::hash(raw, QCryptographicHash::Md5); + uchardet_t ud = uchardet_new(); if (uchardet_handle_data(ud, raw.constData(), raw.size()) == 0) { uchardet_data_end(ud); @@ -206,3 +209,8 @@ QString TxtReader::coverImagePath() { return {}; } + +QByteArray TxtReader::contentHash() +{ + return m_contentHash; +} diff --git a/src/backend/formats/TxtReader.h b/src/backend/formats/TxtReader.h index 689e2a7..8591774 100644 --- a/src/backend/formats/TxtReader.h +++ b/src/backend/formats/TxtReader.h @@ -15,6 +15,7 @@ public: QString title() override; QString author() override; QString coverImagePath() override; + QByteArray contentHash() override; private: QString m_content; @@ -22,6 +23,7 @@ private: QString m_title; QString m_author; QString m_error; + QByteArray m_contentHash; }; #endif // TXTREADER_H diff --git a/src/backend/state/BookPositionStore.cpp b/src/backend/state/BookPositionStore.cpp new file mode 100644 index 0000000..3964b07 --- /dev/null +++ b/src/backend/state/BookPositionStore.cpp @@ -0,0 +1,32 @@ +#include "BookPositionStore.h" + +BookPositionStore::BookPositionStore(AppState &state) + : m_state(state) +{ +} + +BookPosition BookPositionStore::load(const QByteArray &contentMd5) +{ + if (contentMd5.isEmpty()) + return {}; + const QVariantMap d = m_state.loadSection(sectionKey(contentMd5)); + BookPosition pos; + pos.chunkIndex = d.value(QStringLiteral("chunkIndex"), 0).toInt(); + pos.intraOffset = d.value(QStringLiteral("intraOffset"), 0).toInt(); + return pos; +} + +void BookPositionStore::save(const QByteArray &contentMd5, int chunkIndex, int intraOffset) +{ + if (contentMd5.isEmpty()) + return; + m_state.saveSection(sectionKey(contentMd5), { + {QStringLiteral("chunkIndex"), chunkIndex}, + {QStringLiteral("intraOffset"), intraOffset}, + }); +} + +QString BookPositionStore::sectionKey(const QByteArray &contentMd5) +{ + return QStringLiteral("saved-progress/") + QString::fromLatin1(contentMd5.toHex()); +} diff --git a/src/backend/state/BookPositionStore.h b/src/backend/state/BookPositionStore.h new file mode 100644 index 0000000..8750fc2 --- /dev/null +++ b/src/backend/state/BookPositionStore.h @@ -0,0 +1,28 @@ +#ifndef BOOKPOSITIONSTORE_H +#define BOOKPOSITIONSTORE_H + +#include +#include "backend/AppState.h" + +struct BookPosition { + int chunkIndex = 0; + int intraOffset = 0; +}; + +class BookPositionStore { +public: + explicit BookPositionStore(AppState &state); + + // Load the saved position for a book identified by MD5 of its contents. + BookPosition load(const QByteArray &contentMd5); + + // Save the current position for a book identified by MD5 of its contents. + void save(const QByteArray &contentMd5, int chunkIndex, int intraOffset); + +private: + AppState &m_state; + + static QString sectionKey(const QByteArray &contentMd5); +}; + +#endif // BOOKPOSITIONSTORE_H diff --git a/src/backend/state/ReadingPreferences.cpp b/src/backend/state/ReadingPreferences.cpp new file mode 100644 index 0000000..0f7e38a --- /dev/null +++ b/src/backend/state/ReadingPreferences.cpp @@ -0,0 +1,55 @@ +#include "ReadingPreferences.h" +#include + +ReadingPreferences::ReadingPreferences(AppState &state, QObject *parent) + : QObject(parent), m_state(state) +{ + const QVariantMap d = state.loadSection(QStringLiteral("reading")); + m_fontSize = qBound(8, d.value(QStringLiteral("fontSize"), 16).toInt(), 72); + m_lineSpacing = qMax(0.1, d.value(QStringLiteral("lineSpacing"), 1.6).toDouble()); + m_horizontalMargin = qMax(0, d.value(QStringLiteral("horizontalMargin"), 32).toInt()); + m_verticalMargin = qMax(0, d.value(QStringLiteral("verticalMargin"), 8).toInt()); +} + +int ReadingPreferences::fontSize() const { return m_fontSize; } +qreal ReadingPreferences::lineSpacing() const { return m_lineSpacing; } +int ReadingPreferences::horizontalMargin() const { return m_horizontalMargin; } +int ReadingPreferences::verticalMargin() const { return m_verticalMargin; } + +void ReadingPreferences::setFontSize(int size) +{ + if (m_fontSize == size) return; + m_fontSize = size; + emit fontSizeChanged(); +} + +void ReadingPreferences::setLineSpacing(qreal spacing) +{ + if (qFuzzyCompare(m_lineSpacing, spacing)) return; + m_lineSpacing = spacing; + emit lineSpacingChanged(); +} + +void ReadingPreferences::setHorizontalMargin(int margin) +{ + if (m_horizontalMargin == margin) return; + m_horizontalMargin = margin; + emit horizontalMarginChanged(); +} + +void ReadingPreferences::setVerticalMargin(int margin) +{ + if (m_verticalMargin == margin) return; + m_verticalMargin = margin; + emit verticalMarginChanged(); +} + +void ReadingPreferences::save() +{ + m_state.saveSection(QStringLiteral("reading"), { + {QStringLiteral("fontSize"), m_fontSize}, + {QStringLiteral("lineSpacing"), m_lineSpacing}, + {QStringLiteral("horizontalMargin"),m_horizontalMargin}, + {QStringLiteral("verticalMargin"), m_verticalMargin}, + }); +} diff --git a/src/backend/state/ReadingPreferences.h b/src/backend/state/ReadingPreferences.h new file mode 100644 index 0000000..8c0c93e --- /dev/null +++ b/src/backend/state/ReadingPreferences.h @@ -0,0 +1,42 @@ +#ifndef READINGPREFERENCES_H +#define READINGPREFERENCES_H + +#include +#include "backend/AppState.h" + +class ReadingPreferences : public QObject { + Q_OBJECT + Q_PROPERTY(int fontSize READ fontSize WRITE setFontSize NOTIFY fontSizeChanged) + Q_PROPERTY(qreal lineSpacing READ lineSpacing WRITE setLineSpacing NOTIFY lineSpacingChanged) + Q_PROPERTY(int horizontalMargin READ horizontalMargin WRITE setHorizontalMargin NOTIFY horizontalMarginChanged) + Q_PROPERTY(int verticalMargin READ verticalMargin WRITE setVerticalMargin NOTIFY verticalMarginChanged) +public: + explicit ReadingPreferences(AppState &state, QObject *parent = nullptr); + + int fontSize() const; + qreal lineSpacing() const; + int horizontalMargin() const; + int verticalMargin() const; + + void setFontSize(int size); + void setLineSpacing(qreal spacing); + void setHorizontalMargin(int margin); + void setVerticalMargin(int margin); + + void save(); + +signals: + void fontSizeChanged(); + void lineSpacingChanged(); + void horizontalMarginChanged(); + void verticalMarginChanged(); + +private: + AppState &m_state; + int m_fontSize = 16; + qreal m_lineSpacing = 1.6; + int m_horizontalMargin = 32; + int m_verticalMargin = 8; +}; + +#endif // READINGPREFERENCES_H diff --git a/src/backend/state/UiState.cpp b/src/backend/state/UiState.cpp new file mode 100644 index 0000000..fa1426b --- /dev/null +++ b/src/backend/state/UiState.cpp @@ -0,0 +1,99 @@ +#include "UiState.h" + +UiState::UiState(AppState &state, QObject *parent) + : QObject(parent), m_state(state) +{ + const QVariantMap d = state.loadSection(QStringLiteral("ui")); + m_themeName = d.value(QStringLiteral("themeName"), QStringLiteral("dark")).toString(); + m_lastPage = d.value(QStringLiteral("lastPage"), QStringLiteral("starter")).toString(); + m_sidebarOpen = d.value(QStringLiteral("sidebarOpen"), false).toBool(); + m_lastFilePath = d.value(QStringLiteral("lastFilePath"), QString()).toString(); + + const QVariantMap wg = state.loadSection(QStringLiteral("window")); + m_width = wg.value(QStringLiteral("width"), 1024).toInt(); + m_height = wg.value(QStringLiteral("height"), 768).toInt(); + m_x = wg.value(QStringLiteral("x"), -1).toInt(); + m_y = wg.value(QStringLiteral("y"), -1).toInt(); +} + +QString UiState::themeName() const { return m_themeName; } +QString UiState::lastPage() const { return m_lastPage; } +bool UiState::sidebarOpen() const { return m_sidebarOpen; } +QString UiState::lastFilePath() const { return m_lastFilePath; } +int UiState::windowWidth() const { return m_width; } +int UiState::windowHeight() const { return m_height; } +int UiState::windowX() const { return m_x; } +int UiState::windowY() const { return m_y; } + +void UiState::setThemeName(const QString &name) +{ + if (m_themeName == name) return; + m_themeName = name; + emit themeNameChanged(); +} + +void UiState::setLastPage(const QString &page) +{ + if (m_lastPage == page) return; + m_lastPage = page; + emit lastPageChanged(); +} + +void UiState::setSidebarOpen(bool open) +{ + if (m_sidebarOpen == open) return; + m_sidebarOpen = open; + emit sidebarOpenChanged(); +} + +void UiState::setLastFilePath(const QString &path) +{ + if (m_lastFilePath == path) return; + m_lastFilePath = path; + emit lastFilePathChanged(); +} + +void UiState::setWindowWidth(int w) +{ + if (m_width == w) return; + m_width = w; + emit windowWidthChanged(); +} + +void UiState::setWindowHeight(int h) +{ + if (m_height == h) return; + m_height = h; + emit windowHeightChanged(); +} + +void UiState::setWindowX(int x) +{ + if (m_x == x) return; + m_x = x; + emit windowXChanged(); +} + +void UiState::setWindowY(int y) +{ + if (m_y == y) return; + m_y = y; + emit windowYChanged(); +} + +void UiState::save() +{ + m_state.saveSection(QStringLiteral("ui"), { + {QStringLiteral("themeName"), m_themeName}, + {QStringLiteral("lastPage"), m_lastPage}, + {QStringLiteral("sidebarOpen"), m_sidebarOpen}, + {QStringLiteral("lastFilePath"), m_lastFilePath}, + }); + + m_state.saveSection(QStringLiteral("window"), { + {QStringLiteral("width"), m_width}, + {QStringLiteral("height"), m_height}, + {QStringLiteral("x"), m_x}, + {QStringLiteral("y"), m_y}, + }); +} diff --git a/src/backend/state/UiState.h b/src/backend/state/UiState.h new file mode 100644 index 0000000..8c0f692 --- /dev/null +++ b/src/backend/state/UiState.h @@ -0,0 +1,63 @@ +#ifndef UISTATE_H +#define UISTATE_H + +#include +#include +#include "backend/AppState.h" + +class UiState : public QObject { + Q_OBJECT + Q_PROPERTY(QString themeName READ themeName WRITE setThemeName NOTIFY themeNameChanged) + Q_PROPERTY(QString lastPage READ lastPage WRITE setLastPage NOTIFY lastPageChanged) + Q_PROPERTY(bool sidebarOpen READ sidebarOpen WRITE setSidebarOpen NOTIFY sidebarOpenChanged) + Q_PROPERTY(QString lastFilePath READ lastFilePath WRITE setLastFilePath NOTIFY lastFilePathChanged) + Q_PROPERTY(int windowWidth READ windowWidth WRITE setWindowWidth NOTIFY windowWidthChanged) + Q_PROPERTY(int windowHeight READ windowHeight WRITE setWindowHeight NOTIFY windowHeightChanged) + Q_PROPERTY(int windowX READ windowX WRITE setWindowX NOTIFY windowXChanged) + Q_PROPERTY(int windowY READ windowY WRITE setWindowY NOTIFY windowYChanged) +public: + explicit UiState(AppState &state, QObject *parent = nullptr); + + QString themeName() const; + QString lastPage() const; + bool sidebarOpen() const; + QString lastFilePath() const; + int windowWidth() const; + int windowHeight() const; + int windowX() const; + int windowY() const; + + void setThemeName(const QString &name); + void setLastPage(const QString &page); + void setSidebarOpen(bool open); + void setLastFilePath(const QString &path); + void setWindowWidth(int w); + void setWindowHeight(int h); + void setWindowX(int x); + void setWindowY(int y); + + void save(); + +signals: + void themeNameChanged(); + void lastPageChanged(); + void sidebarOpenChanged(); + void lastFilePathChanged(); + void windowWidthChanged(); + void windowHeightChanged(); + void windowXChanged(); + void windowYChanged(); + +private: + AppState &m_state; + QString m_themeName = QStringLiteral("dark"); + QString m_lastPage = QStringLiteral("starter"); + bool m_sidebarOpen = false; + QString m_lastFilePath; + int m_width = 1024; + int m_height = 768; + int m_x = -1; + int m_y = -1; +}; + +#endif // UISTATE_H diff --git a/src/main.cpp b/src/main.cpp index 20995ad..181947b 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -8,12 +9,17 @@ #include #include -#include "backend/BookController.h" -#include "backend/IImageProvider.h" -#include "backend/ReadingModel.h" #include "backend/AppState.h" +#include "backend/IImageProvider.h" +#include "backend/ImageLoaderFactory.h" +#include "backend/ImageProviderFactory.h" #include "backend/LibraryModel.h" +#include "backend/ReadingModel.h" #include "backend/NativeFileDialogService.h" +#include "backend/book/Book.h" +#include "backend/state/BookPositionStore.h" +#include "backend/state/ReadingPreferences.h" +#include "backend/state/UiState.h" #ifdef HAS_QT_DBUS #include @@ -80,50 +86,147 @@ int main(int argc, char *argv[]) QQuickStyle::setStyle(QStringLiteral("Basic")); - ReadingModel readingModel; + // --- Object graph (construction order = dependency order) --- + QSettings settings; + AppState appState(settings); - BookController bookController; - bookController.setReadingModel(&readingModel); + ReadingPreferences readingPreferences(appState); + UiState uiState(appState); + BookPositionStore bookPositions(appState); - AppState appState; - appState.restore(); - bookController.setAppState(&appState); + LibraryModel libraryModel; + for (const QVariantMap &entry : appState.loadArray(QStringLiteral("library"))) { + 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(); + libraryModel.addOrUpdateBook(fp, progress, lo); + } + + // Command-line override: treat first argument as the file to open on startup + if (const QStringList args = QCoreApplication::arguments(); args.size() > 1) { + const QString &argPath = args.at(1); + if (QFileInfo::exists(argPath)) + uiState.setLastFilePath(argPath); + } #if defined(HAS_QT_DBUS) && defined(Q_OS_LINUX) IFileDialogService *fileDialogService; if (QDBusConnection::sessionBus().isConnected()) { - fileDialogService = new PortalFileDialogService(&bookController); + fileDialogService = new PortalFileDialogService(nullptr); } else { - fileDialogService = new NativeFileDialogService(&bookController); + fileDialogService = new NativeFileDialogService(nullptr); } #else - IFileDialogService *fileDialogService = new NativeFileDialogService(&bookController); + IFileDialogService *fileDialogService = new NativeFileDialogService(nullptr); #endif - bookController.setFileDialogService(fileDialogService); - if (const QStringList args = QCoreApplication::arguments(); args.size() > 1) { - const QString& filePath = args.at(1); - if (QFileInfo::exists(filePath)) - appState.setLastFilePath(filePath); - } + Book book(*fileDialogService, bookPositions); + ReadingModel readingModel(bookPositions); + // --- QML engine --- QQmlApplicationEngine engine; - engine.rootContext()->setContextProperty("isDebugBuild", - #ifdef QT_DEBUG + engine.rootContext()->setContextProperty(QStringLiteral("isDebugBuild"), +#ifdef QT_DEBUG true - #else +#else false - #endif +#endif ); - bookController.setImageProviderRegistrar([&engine](const QString &scheme, IImageProvider *provider) { - engine.removeImageProvider(scheme); - engine.addImageProvider(scheme, provider); + engine.rootContext()->setContextProperty(QStringLiteral("book"), &book); + engine.rootContext()->setContextProperty(QStringLiteral("readingModel"), &readingModel); + engine.rootContext()->setContextProperty(QStringLiteral("readingPreferences"), &readingPreferences); + engine.rootContext()->setContextProperty(QStringLiteral("uiState"), &uiState); + engine.rootContext()->setContextProperty(QStringLiteral("libraryModel"), &libraryModel); + + // --- Cross-class signal wiring --- + + // Typography changes → re-push font params into ReadingModel + QObject::connect(&readingPreferences, &ReadingPreferences::fontSizeChanged, [&]{ + readingModel.setFontParams(readingPreferences.fontSize(), readingPreferences.lineSpacing()); + }); + QObject::connect(&readingPreferences, &ReadingPreferences::lineSpacingChanged, [&]{ + readingModel.setFontParams(readingPreferences.fontSize(), readingPreferences.lineSpacing()); }); - engine.rootContext()->setContextProperty(QStringLiteral("bookController"), &bookController); - engine.rootContext()->setContextProperty(QStringLiteral("readingModel"), &readingModel); - engine.rootContext()->setContextProperty(QStringLiteral("appState"), &appState); + // Track the current image provider so setContentWidth can reach it + IImageProvider *currentImageProvider = nullptr; + + // Before a new book open: snapshot the outgoing book's progress into the library. + // Scroll position is handled by PageView's scroll tracker via book.saveCurrentPosition(). + QObject::connect(&book, &Book::willOpenNewBook, [&]{ + if (book.hasBook()) + libraryModel.addOrUpdateBook(book.filePath(), readingModel.progress()); + }); + + // After the new reader is installed: wire up image provider + ReadingModel + QObject::connect(&book, &Book::bookChanged, [&]{ + currentImageProvider = nullptr; + + if (!book.hasBook()) { + readingModel.setReader(nullptr); + return; + } + + FormatReader *reader = book.reader(); + const QString filePath = reader->filePath(); + + IImageProvider *provider = ImageProviderFactory::create(filePath); + if (provider) { + engine.removeImageProvider(provider->scheme()); + engine.addImageProvider(provider->scheme(), provider); + provider->setFilePath(filePath); + currentImageProvider = provider; + + if (!reader->coverImagePath().isEmpty()) + book.setCoverImageUrl(provider->coverImageUrl(reader->coverImagePath())); + } + + readingModel.setFontParams(readingPreferences.fontSize(), readingPreferences.lineSpacing()); + readingModel.setImageLoader(ImageLoaderFactory::create(filePath)); + readingModel.setCoverImageUrl(book.coverImageUrl()); + readingModel.setReader(reader); + readingModel.measure(true); + + uiState.setLastFilePath(filePath); + libraryModel.addOrUpdateBook(filePath, -1.0); + }); + + // Propagate content-width changes to image provider + reading model. + // Called from Book::setContentWidth which is triggered by QML's PageView. + QObject::connect(&book, &Book::contentWidthChanged, [&](int width){ + if (currentImageProvider) + currentImageProvider->setDisplayWidth(width); + readingModel.setContentWidth(width); + }); + + // Quit: flush everything to persistent storage. + // Scroll position was last saved by PageView's scroll tracker; we save library progress here. + QObject::connect(&app, &QCoreApplication::aboutToQuit, [&]{ + if (book.hasBook()) { + libraryModel.addOrUpdateBook(book.filePath(), readingModel.progress()); + uiState.setLastFilePath(book.filePath()); + } else { + uiState.setLastFilePath(QString()); + } + + readingPreferences.save(); + uiState.save(); + + QList items; + for (int i = 0; i < libraryModel.rowCount(); ++i) { + items.append({ + {QStringLiteral("filePath"), libraryModel.filePath(i)}, + {QStringLiteral("progress"), libraryModel.progress(i)}, + {QStringLiteral("lastOpened"), libraryModel.lastOpened(i)}, + }); + } + appState.saveArray(QStringLiteral("library"), items); + + qInfo() << "Settings saved to:" << settings.fileName(); + }); const QUrl url(QStringLiteral("qrc:/Asteria/Main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed, @@ -148,16 +251,5 @@ int main(int argc, char *argv[]) qInfo("Rendering API: %s", apiName); } - QObject::connect(&app, &QCoreApplication::aboutToQuit, [&bookController, &appState, &readingModel]() { - if (bookController.hasBook()) { - appState.setLastFilePath(bookController.currentFilePath()); - appState.addOrUpdateLibraryBook(bookController.currentFilePath(), - readingModel.progress()); - } else { - appState.setLastFilePath(QString()); - } - appState.save(); - }); - return QApplication::exec(); } diff --git a/src/qml/Main.qml b/src/qml/Main.qml index 57219ba..c117ca5 100644 --- a/src/qml/Main.qml +++ b/src/qml/Main.qml @@ -17,49 +17,51 @@ ApplicationWindow { source: "qrc:/Asteria/src/assets/MaterialIconsOutlined-Regular.otf" } - property bool sidebarOpen: appState.sidebarOpen - onSidebarOpenChanged: appState.sidebarOpen = sidebarOpen + property bool sidebarOpen: uiState.sidebarOpen + onSidebarOpenChanged: uiState.sidebarOpen = sidebarOpen property string currentPage: "starter" property bool barsVisible: true + // Set to true on the first book open at startup so we restore the last page. + property bool _startupRestore: false - onCurrentPageChanged: appState.lastPage = currentPage + onCurrentPageChanged: uiState.lastPage = currentPage Component.onCompleted: { - width = appState.windowWidth - height = appState.windowHeight - if (appState.windowX >= 0 && appState.windowY >= 0) { - x = appState.windowX - y = appState.windowY - } - // Initialize theme from AppState - if (appState.themeName !== "") { - ThemeManager.currentThemeName = appState.themeName + width = uiState.windowWidth + height = uiState.windowHeight + if (uiState.windowX >= 0 && uiState.windowY >= 0) { + x = uiState.windowX + y = uiState.windowY } + if (uiState.themeName !== "") + ThemeManager.currentThemeName = uiState.themeName + + } Connections { - target: appState + target: uiState function onThemeNameChanged() { - ThemeManager.currentThemeName = appState.themeName + ThemeManager.currentThemeName = uiState.themeName } } Timer { id: geometrySaveTimer - interval: 500 + interval: 250 repeat: false onTriggered: { - appState.windowWidth = window.width - appState.windowHeight = window.height - appState.windowX = window.x - appState.windowY = window.y + uiState.windowWidth = window.width + uiState.windowHeight = window.height + uiState.windowX = window.x + uiState.windowY = window.y } } - onWidthChanged: geometrySaveTimer.restart() + onWidthChanged: geometrySaveTimer.restart() onHeightChanged: geometrySaveTimer.restart() - onXChanged: geometrySaveTimer.restart() - onYChanged: geometrySaveTimer.restart() + onXChanged: geometrySaveTimer.restart() + onYChanged: geometrySaveTimer.restart() Row { anchors.fill: parent @@ -73,10 +75,10 @@ ApplicationWindow { window.currentPage = page } onOpenFile: { - bookController.browseAndOpen() + book.browseAndOpen() } onCloseBook: { - bookController.closeBook() + book.close() } } @@ -121,7 +123,7 @@ ApplicationWindow { BusyIndicator { anchors.centerIn: parent - running: bookController.loading || readingModel.measuring + running: book.loading || readingModel.measuring visible: running z: 10 } @@ -141,6 +143,32 @@ ApplicationWindow { z: 3000 } + // Navigate once measurement (and position restoration) is done + Connections { + target: readingModel + function onRestoreReady(chunkIndex, intraOffset) { + if (!book.hasBook) return + if (window._startupRestore) { + window._startupRestore = false + var savedPage = uiState.lastPage + if (savedPage === "library" || savedPage === "settings") + window.currentPage = savedPage + else + window.currentPage = "reader" + } else { + window.currentPage = "reader" + } + } + } + + Connections { + target: book + function onBookChanged() { + if (!book.hasBook && window.currentPage === "reader") + window.currentPage = "starter" + } + } + // Global keyboard shortcuts - work regardless of focus Shortcut { sequence: "F" @@ -188,7 +216,6 @@ ApplicationWindow { } } } - // Fallback shortcuts using alternative key names Shortcut { sequence: "Prior" context: Qt.ApplicationShortcut @@ -217,31 +244,6 @@ ApplicationWindow { } } - Connections { - target: bookController - function onBookReady() { - if (bookController.startupRestore) { - var savedPage = appState.lastPage - if (savedPage === "library" || savedPage === "settings") - window.currentPage = savedPage - else - window.currentPage = "reader" - } else { - window.currentPage = "reader" - } - } - function onBookChanged() { - if (!bookController.hasBook && window.currentPage === "reader") - window.currentPage = "starter" - } - function onNoSavedBook() { - window.sidebarOpen = true - var savedPage = appState.lastPage - if (savedPage === "library" || savedPage === "settings") - window.currentPage = savedPage - } - } - Timer { running: true repeat: false @@ -250,7 +252,15 @@ ApplicationWindow { onTriggered: { window.opacity = 1 readerPage.pageView.updateContentWidth() - bookController.uiReady() + if (uiState.lastFilePath !== "") { + window._startupRestore = true + book.openFromPath(uiState.lastFilePath) + } else { + var savedPage = uiState.lastPage + if (savedPage === "library" || savedPage === "settings") + window.currentPage = savedPage + window.sidebarOpen = true + } } } } diff --git a/src/qml/ThemeManager.qml b/src/qml/ThemeManager.qml index 37b2af5..bbf3123 100644 --- a/src/qml/ThemeManager.qml +++ b/src/qml/ThemeManager.qml @@ -14,27 +14,16 @@ QtObject { function setDarkTheme() { currentThemeName = "dark" - if (appState) { - appState.themeName = "dark" - } + uiState.themeName = "dark" } - + function setLightTheme() { currentThemeName = "light" - if (appState) { - appState.themeName = "light" - } + uiState.themeName = "light" } - + function toggleTheme() { currentThemeName = currentThemeName === "dark" ? "light" : "dark" - if (appState) { - appState.themeName = currentThemeName - } - } - - onCurrentThemeNameChanged: { - // This ensures UI updates when theme changes - // The actual theme switching happens through the currentTheme property + uiState.themeName = currentThemeName } } \ No newline at end of file diff --git a/src/qml/components/ErrorPopup.qml b/src/qml/components/ErrorPopup.qml index 114cd9f..c273345 100644 --- a/src/qml/components/ErrorPopup.qml +++ b/src/qml/components/ErrorPopup.qml @@ -5,7 +5,7 @@ import Asteria Rectangle { id: overlay color: ThemeManager.currentTheme.overlayBg - visible: bookController.errorMessage !== "" + visible: book.errorMessage !== "" MouseArea { anchors.fill: parent @@ -33,7 +33,7 @@ Rectangle { Text { width: parent.width - text: bookController.errorMessage + text: book.errorMessage font.pixelSize: 15 color: ThemeManager.currentTheme.readingText horizontalAlignment: Text.AlignHCenter @@ -55,7 +55,7 @@ Rectangle { radius: 4 color: parent.hovered ? Qt.lighter(ThemeManager.currentTheme.primaryAccent, 1.15) : ThemeManager.currentTheme.primaryAccent } - onClicked: bookController.clearError() + onClicked: book.clearError() } } } diff --git a/src/qml/components/Footer.qml b/src/qml/components/Footer.qml index 1512239..83a1ac9 100644 --- a/src/qml/components/Footer.qml +++ b/src/qml/components/Footer.qml @@ -18,7 +18,7 @@ Rectangle { id: prevBtn anchors.verticalCenter: parent.verticalCenter x: parent.width * 0.5 - chapterText.implicitWidth / 2 - width - 4 - visible: bookController.hasBook && readingModel.hasChapters + visible: book.hasBook && readingModel.hasChapters enabled: readingModel.currentChapter > 0 flat: true padding: 0 @@ -40,7 +40,7 @@ Rectangle { id: chapterText anchors.verticalCenter: parent.verticalCenter anchors.horizontalCenter: parent.horizontalCenter - text: bookController.hasBook && readingModel.hasChapters + text: book.hasBook && readingModel.hasChapters ? "Chapter " + (readingModel.currentChapter + 1) + " / " + readingModel.totalChapters : "" font.pixelSize: 11 @@ -53,7 +53,7 @@ Rectangle { id: nextBtn anchors.verticalCenter: parent.verticalCenter x: parent.width * 0.5 + chapterText.implicitWidth / 2 + 4 - visible: bookController.hasBook && readingModel.hasChapters + visible: book.hasBook && readingModel.hasChapters enabled: readingModel.currentChapter < readingModel.totalChapters - 1 flat: true padding: 0 @@ -75,8 +75,8 @@ Rectangle { anchors.right: parent.right anchors.rightMargin: 16 anchors.verticalCenter: parent.verticalCenter - visible: bookController.hasBook - text: bookController.hasBook + visible: book.hasBook + text: book.hasBook ? readingModel.currentPage + "/" + readingModel.totalPages : "" font.pixelSize: 11 diff --git a/src/qml/components/Header.qml b/src/qml/components/Header.qml index fa2ba96..703a9c2 100644 --- a/src/qml/components/Header.qml +++ b/src/qml/components/Header.qml @@ -39,7 +39,7 @@ Rectangle { text: { switch (header.currentPage) { case "settings": return "Settings" - case "reader": return bookController.bookTitle || "" + case "reader": return book.title || "" default: return "" } } diff --git a/src/qml/components/PageView.qml b/src/qml/components/PageView.qml index d89a1b9..6582c31 100644 --- a/src/qml/components/PageView.qml +++ b/src/qml/components/PageView.qml @@ -34,25 +34,21 @@ Rectangle { } function handleScrollUp() { - // Scroll up by approximately 2-3 lines - var lineHeight = appState.fontSize * appState.lineSpacing; - var scrollAmount = lineHeight * 3; // ~2-3 lines + var lineHeight = readingPreferences.fontSize * readingPreferences.lineSpacing; + var scrollAmount = lineHeight * 3; var targetY = Math.max(0, chunkListView.contentY - scrollAmount); animateScrollTo(targetY); } function handleScrollDown() { - // Scroll down by approximately 2-3 lines - var lineHeight = appState.fontSize * appState.lineSpacing; - var scrollAmount = lineHeight * 3; // ~2-3 lines + var lineHeight = readingPreferences.fontSize * readingPreferences.lineSpacing; + var scrollAmount = lineHeight * 3; var maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height); var targetY = Math.min(maxY, chunkListView.contentY + scrollAmount); animateScrollTo(targetY); } - // Helper function to animate scrolling function animateScrollTo(targetY) { - // Stop any ongoing animation scrollAnimation.stop(); scrollAnimation.to = targetY; scrollAnimation.start(); @@ -64,7 +60,7 @@ Rectangle { } function updateContentWidth() { - bookController.setContentWidth(chunkListView.width - 18 - 2 * appState.horizontalMargin) + book.setContentWidth(chunkListView.width - 18 - 2 * readingPreferences.horizontalMargin) } Component.onCompleted: updateContentWidth() @@ -87,8 +83,8 @@ Rectangle { id: chunkListView anchors.fill: parent model: contentReady ? readingModel : null - header: Item { height: appState.verticalMargin } - footer: Item { height: appState.verticalMargin } + header: Item { height: readingPreferences.verticalMargin } + footer: Item { height: readingPreferences.verticalMargin } cacheBuffer: 20 clip: true @@ -108,16 +104,15 @@ Rectangle { Text { id: contentText width: parent.width - 18 // subtract scrollbar - leftPadding: appState.horizontalMargin - rightPadding: appState.horizontalMargin + leftPadding: readingPreferences.horizontalMargin + rightPadding: readingPreferences.horizontalMargin wrapMode: Text.WrapAtWordBoundaryOrAnywhere textFormat: Text.RichText - font.pixelSize: appState.fontSize - lineHeight: appState.lineSpacing + font.pixelSize: readingPreferences.fontSize + lineHeight: readingPreferences.lineSpacing color: ThemeManager.currentTheme.readingText text: model.content visible: model.content !== "" - // TODO: remove when we're good with measurer onImplicitHeightChanged: { if (model.pixelHeight > 0 && implicitHeight > 0) { var diff = model.pixelHeight - implicitHeight @@ -177,21 +172,21 @@ Rectangle { interval: 300 repeat: false onTriggered: { - if (bookController.hasBook && contentReady && restoreReady) { + if (book.hasBook && contentReady && restoreReady) { var topIdx = chunkListView.indexAt(0, chunkListView.contentY) if (topIdx < 0) topIdx = 0 var topItem = chunkListView.itemAtIndex(topIdx) var intraOffset = topItem ? (chunkListView.contentY - topItem.y) : 0 readingModel.setScrollInfo(topIdx, chunkListView.visibleArea.yPosition) - appState.saveBookPosition(bookController.currentFilePath, topIdx, intraOffset) + book.saveCurrentPosition(topIdx, intraOffset) } } } Connections { - target: bookController + target: book function onLoadingChanged() { - if (bookController.loading) + if (book.loading) contentReady = false } } @@ -209,16 +204,6 @@ Rectangle { } } - Connections { - target: appState - function onFontSizeChanged() { - readingModel.setFontParams(appState.fontSize, appState.lineSpacing) - } - function onLineSpacingChanged() { - readingModel.setFontParams(appState.fontSize, appState.lineSpacing) - } - } - Timer { id: restoreTimer interval: 1 diff --git a/src/qml/components/SideBar.qml b/src/qml/components/SideBar.qml index 690af00..a80d0c3 100644 --- a/src/qml/components/SideBar.qml +++ b/src/qml/components/SideBar.qml @@ -73,7 +73,7 @@ Rectangle { } SideBarButton { - visible: bookController.hasBook + visible: book.hasBook iconText: "\ue5cd" title: "Close Book" onClicked: sidebar.closeBook() @@ -114,7 +114,7 @@ Rectangle { // TOC section — shown when the current book has a table of contents Item { - visible: bookController.hasBook && bookController.toc.length > 0 + visible: book.hasBook && book.toc.length > 0 anchors.top: navColumn.bottom anchors.bottom: parent.bottom width: parent.width @@ -145,7 +145,7 @@ Rectangle { anchors.bottom: parent.bottom width: parent.width clip: true - model: bookController.toc + model: book.toc delegate: Rectangle { width: ListView.view.width diff --git a/src/qml/pages/LibraryPage.qml b/src/qml/pages/LibraryPage.qml index 32a8591..89296de 100644 --- a/src/qml/pages/LibraryPage.qml +++ b/src/qml/pages/LibraryPage.qml @@ -6,7 +6,7 @@ Rectangle { color: ThemeManager.currentTheme.backgroundDefault Text { - visible: appState.libraryModel.count === 0 + visible: libraryModel.count === 0 anchors.centerIn: parent text: "No books read yet.\nOpen a book to start your library." horizontalAlignment: Text.AlignHCenter @@ -16,12 +16,12 @@ Rectangle { } ListView { - visible: appState.libraryModel.count > 0 + visible: libraryModel.count > 0 anchors.fill: parent anchors.margins: 16 spacing: 8 clip: true - model: appState.libraryModel + model: libraryModel delegate: Rectangle { id: bookRow @@ -92,14 +92,14 @@ Rectangle { verticalAlignment: Text.AlignVCenter } background: Item {} - onClicked: appState.removeLibraryBook(filePath) + onClicked: libraryModel.removeBook(filePath) } } MouseArea { anchors.fill: parent z: -1 - onClicked: bookController.openBookFromPath(filePath) + onClicked: book.openFromPath(filePath) } } } diff --git a/src/qml/pages/SettingsPage.qml b/src/qml/pages/SettingsPage.qml index 14e1ebd..b8be07e 100644 --- a/src/qml/pages/SettingsPage.qml +++ b/src/qml/pages/SettingsPage.qml @@ -56,7 +56,7 @@ Rectangle { Timer { id: hmTimer interval: 250 - onTriggered: appState.horizontalMargin = hmSlider.value + onTriggered: readingPreferences.horizontalMargin = hmSlider.value } Slider { @@ -65,9 +65,9 @@ Rectangle { from: 0 to: 120 stepSize: 1 - value: appState.horizontalMargin + value: readingPreferences.horizontalMargin onValueChanged: { - if (value !== appState.horizontalMargin) + if (value !== readingPreferences.horizontalMargin) hmTimer.restart() } } @@ -103,7 +103,7 @@ Rectangle { Timer { id: vmTimer interval: 250 - onTriggered: appState.verticalMargin = vmSlider.value + onTriggered: readingPreferences.verticalMargin = vmSlider.value } Slider { @@ -112,9 +112,9 @@ Rectangle { from: 0 to: 80 stepSize: 1 - value: appState.verticalMargin + value: readingPreferences.verticalMargin onValueChanged: { - if (value !== appState.verticalMargin) + if (value !== readingPreferences.verticalMargin) vmTimer.restart() } } @@ -150,7 +150,7 @@ Rectangle { Timer { id: fsTimer interval: 250 - onTriggered: appState.fontSize = fsSlider.value + onTriggered: readingPreferences.fontSize = fsSlider.value } Slider { @@ -159,9 +159,9 @@ Rectangle { from: 10 to: 32 stepSize: 1 - value: appState.fontSize + value: readingPreferences.fontSize onValueChanged: { - if (value !== appState.fontSize) + if (value !== readingPreferences.fontSize) fsTimer.restart() } } @@ -197,7 +197,7 @@ Rectangle { Timer { id: lsTimer interval: 250 - onTriggered: appState.lineSpacing = lsSlider.value + onTriggered: readingPreferences.lineSpacing = lsSlider.value } Slider { @@ -206,9 +206,9 @@ Rectangle { from: 0.5 to: 3.0 stepSize: 0.1 - value: appState.lineSpacing + value: readingPreferences.lineSpacing onValueChanged: { - if (Math.abs(value - appState.lineSpacing) > 0.01) + if (Math.abs(value - readingPreferences.lineSpacing) > 0.01) lsTimer.restart() } } diff --git a/tests/AppStateTest.cpp b/tests/AppStateTest.cpp index ec6f878..dcce36a 100644 --- a/tests/AppStateTest.cpp +++ b/tests/AppStateTest.cpp @@ -1,437 +1,122 @@ #include -#include +#include #include +#include + #include "backend/AppState.h" -#include "backend/LibraryModel.h" class AppStateTest : public QObject { Q_OBJECT private slots: - void initTestCase() + void freshSettingsWriteVersion() { - QCoreApplication::setOrganizationName(QStringLiteral("AsteriaTest")); - QCoreApplication::setApplicationName(QStringLiteral("AppStateTest")); + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-test-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState state(s); + QCOMPARE(s.value(QStringLiteral("version")).toInt(), AppState::SETTINGS_VERSION); } - void cleanup() + void staleVersionClearsSettings() { - QSettings().clear(); - } + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-stale-XXXXXX.ini")); + f.open(); f.close(); - void saveAndRestoreLastFilePath() - { { - AppState state; - state.setLastFilePath(QStringLiteral("/books/test.epub")); - state.save(); + QSettings s(f.fileName(), QSettings::IniFormat); + s.setValue(QStringLiteral("version"), 0); + s.setValue(QStringLiteral("someOldKey"), QStringLiteral("data")); } - AppState state2; - state2.restore(); - QCOMPARE(state2.lastFilePath(), QStringLiteral("/books/test.epub")); + + QSettings s2(f.fileName(), QSettings::IniFormat); + AppState state(s2); + QVERIFY(!s2.contains(QStringLiteral("someOldKey"))); + QCOMPARE(s2.value(QStringLiteral("version")).toInt(), AppState::SETTINGS_VERSION); } - void saveAndRestoreMargins() + void saveAndLoadSection() { - { - AppState state; - state.setHorizontalMargin(64); - state.setVerticalMargin(24); - state.save(); - } - AppState state2; - state2.restore(); - QCOMPARE(state2.horizontalMargin(), 64); - QCOMPARE(state2.verticalMargin(), 24); + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-sec-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState state(s); + + QVariantMap data; + data[QStringLiteral("foo")] = 42; + data[QStringLiteral("bar")] = QStringLiteral("hello"); + state.saveSection(QStringLiteral("test"), data); + + const QVariantMap loaded = state.loadSection(QStringLiteral("test")); + QCOMPARE(loaded.value(QStringLiteral("foo")).toInt(), 42); + QCOMPARE(loaded.value(QStringLiteral("bar")).toString(), QStringLiteral("hello")); } - void saveAndRestoreFontSize() + void saveSectionOverwritesPrevious() { - { - AppState state; - state.setFontSize(22); - state.save(); - } - AppState state2; - state2.restore(); - QCOMPARE(state2.fontSize(), 22); + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-over-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState state(s); + + state.saveSection(QStringLiteral("g"), {{QStringLiteral("old"), 1}}); + state.saveSection(QStringLiteral("g"), {{QStringLiteral("new"), 2}}); + + const QVariantMap loaded = state.loadSection(QStringLiteral("g")); + QVERIFY(!loaded.contains(QStringLiteral("old"))); + QCOMPARE(loaded.value(QStringLiteral("new")).toInt(), 2); } - void saveAndRestoreLineSpacing() + void saveAndLoadArray() { - { - AppState state; - state.setLineSpacing(2.0); - state.save(); - } - AppState state2; - state2.restore(); - QCOMPARE(state2.lineSpacing(), 2.0); + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-arr-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState state(s); + + QList items; + items.append({{QStringLiteral("filePath"), QStringLiteral("/a/b.epub")}, + {QStringLiteral("progress"), 0.5}}); + items.append({{QStringLiteral("filePath"), QStringLiteral("/c/d.txt")}, + {QStringLiteral("progress"), 0.0}}); + state.saveArray(QStringLiteral("library"), items); + + const auto loaded = state.loadArray(QStringLiteral("library")); + QCOMPARE(loaded.size(), 2); + QCOMPARE(loaded[0].value(QStringLiteral("filePath")).toString(), QStringLiteral("/a/b.epub")); + QCOMPARE(loaded[0].value(QStringLiteral("progress")).toDouble(), 0.5); + QCOMPARE(loaded[1].value(QStringLiteral("filePath")).toString(), QStringLiteral("/c/d.txt")); } - void saveAndRestoreWindowGeometry() + void emptyArrayReturnsEmptyList() { - { - AppState state; - state.setWindowWidth(1280); - state.setWindowHeight(800); - state.setWindowX(100); - state.setWindowY(50); - state.save(); - } - AppState state2; - state2.restore(); - QCOMPARE(state2.windowWidth(), 1280); - QCOMPARE(state2.windowHeight(), 800); - QCOMPARE(state2.windowX(), 100); - QCOMPARE(state2.windowY(), 50); + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-earr-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState state(s); + + QCOMPARE(state.loadArray(QStringLiteral("nonexistent")).size(), 0); } - void restoreWithNoSavedData() + void nestedSectionKey() { - AppState state; - state.restore(); - QVERIFY(state.lastFilePath().isEmpty()); - QCOMPARE(state.horizontalMargin(), 32); - QCOMPARE(state.verticalMargin(), 8); - QCOMPARE(state.fontSize(), 16); - QCOMPARE(state.lineSpacing(), 1.6); - QCOMPARE(state.windowWidth(), 1024); - QCOMPARE(state.windowHeight(), 768); - QCOMPARE(state.windowX(), -1); - QCOMPARE(state.windowY(), -1); - } + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-nest-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState state(s); - void settersEmitSignals() - { - AppState state; - QSignalSpy spyFilePath(&state, &AppState::lastFilePathChanged); - QSignalSpy spyHMargin(&state, &AppState::horizontalMarginChanged); - QSignalSpy spyVMargin(&state, &AppState::verticalMarginChanged); - QSignalSpy spyFontSize(&state, &AppState::fontSizeChanged); - QSignalSpy spyLineSpacing(&state, &AppState::lineSpacingChanged); - QSignalSpy spyWidth(&state, &AppState::windowWidthChanged); - QSignalSpy spyHeight(&state, &AppState::windowHeightChanged); - QSignalSpy spyX(&state, &AppState::windowXChanged); - QSignalSpy spyY(&state, &AppState::windowYChanged); + const QString nestedSection = QStringLiteral("saved-progress/abc123"); + state.saveSection(nestedSection, {{QStringLiteral("chunkIndex"), 5}}); - state.setLastFilePath(QStringLiteral("/foo.txt")); - state.setHorizontalMargin(64); - state.setVerticalMargin(24); - state.setFontSize(20); - state.setLineSpacing(2.0); - state.setWindowWidth(800); - state.setWindowHeight(600); - state.setWindowX(200); - state.setWindowY(150); - - QCOMPARE(spyFilePath.count(), 1); - QCOMPARE(spyHMargin.count(), 1); - QCOMPARE(spyVMargin.count(), 1); - QCOMPARE(spyFontSize.count(), 1); - QCOMPARE(spyLineSpacing.count(), 1); - QCOMPARE(spyWidth.count(), 1); - QCOMPARE(spyHeight.count(), 1); - QCOMPARE(spyX.count(), 1); - QCOMPARE(spyY.count(), 1); - } - - void saveAndLoadBookPosition() - { - AppState state; - state.saveBookPosition(QStringLiteral("/books/a.epub"), 5, 120); - QVariantMap pos = state.loadBookPosition(QStringLiteral("/books/a.epub")); - QCOMPARE(pos[QStringLiteral("chunkIndex")].toInt(), 5); - QCOMPARE(pos[QStringLiteral("intraChunkOffset")].toInt(), 120); - } - - void loadBookPositionForUnknownBook() - { - AppState state; - QVariantMap pos = state.loadBookPosition(QStringLiteral("/books/unknown.epub")); - QCOMPARE(pos[QStringLiteral("chunkIndex")].toInt(), 0); - QCOMPARE(pos[QStringLiteral("intraChunkOffset")].toInt(), 0); - } - - void saveBookPositionForMultipleBooks() - { - AppState state; - state.saveBookPosition(QStringLiteral("/books/a.epub"), 10, 50); - state.saveBookPosition(QStringLiteral("/books/b.epub"), 20, 200); - QVariantMap posA = state.loadBookPosition(QStringLiteral("/books/a.epub")); - QVariantMap posB = state.loadBookPosition(QStringLiteral("/books/b.epub")); - QCOMPARE(posA[QStringLiteral("chunkIndex")].toInt(), 10); - QCOMPARE(posA[QStringLiteral("intraChunkOffset")].toInt(), 50); - QCOMPARE(posB[QStringLiteral("chunkIndex")].toInt(), 20); - QCOMPARE(posB[QStringLiteral("intraChunkOffset")].toInt(), 200); - } - - void saveBookPositionOverwritesPrevious() - { - AppState state; - state.saveBookPosition(QStringLiteral("/books/a.epub"), 10, 50); - state.saveBookPosition(QStringLiteral("/books/a.epub"), 15, 88); - QVariantMap pos = state.loadBookPosition(QStringLiteral("/books/a.epub")); - QCOMPARE(pos[QStringLiteral("chunkIndex")].toInt(), 15); - QCOMPARE(pos[QStringLiteral("intraChunkOffset")].toInt(), 88); - } - - void restoreEmitsSingleSignal() - { - AppState state; - - QSignalSpy spyRestored(&state, &AppState::stateRestored); - QSignalSpy spyFilePath(&state, &AppState::lastFilePathChanged); - QSignalSpy spyHMargin(&state, &AppState::horizontalMarginChanged); - QSignalSpy spyVMargin(&state, &AppState::verticalMarginChanged); - QSignalSpy spyFontSize(&state, &AppState::fontSizeChanged); - QSignalSpy spyLineSpacing(&state, &AppState::lineSpacingChanged); - QSignalSpy spyWidth(&state, &AppState::windowWidthChanged); - QSignalSpy spyHeight(&state, &AppState::windowHeightChanged); - QSignalSpy spyX(&state, &AppState::windowXChanged); - QSignalSpy spyY(&state, &AppState::windowYChanged); - QSignalSpy spyTheme(&state, &AppState::themeNameChanged); - - state.restore(); - - QCOMPARE(spyRestored.count(), 1); - QCOMPARE(spyFilePath.count(), 0); - QCOMPARE(spyHMargin.count(), 0); - QCOMPARE(spyVMargin.count(), 0); - QCOMPARE(spyFontSize.count(), 0); - QCOMPARE(spyLineSpacing.count(), 0); - QCOMPARE(spyWidth.count(), 0); - QCOMPARE(spyHeight.count(), 0); - QCOMPARE(spyX.count(), 0); - QCOMPARE(spyY.count(), 0); - QCOMPARE(spyTheme.count(), 0); - } - - void saveAndRestoreThemeName() - { - { - AppState state; - state.setThemeName(QStringLiteral("light")); - state.save(); - } - AppState state2; - state2.restore(); - QCOMPARE(state2.themeName(), QStringLiteral("light")); - } - - void themeNameDefaultsToDark() - { - AppState state; - QCOMPARE(state.themeName(), QStringLiteral("dark")); - } - - void themeNameSetterEmitsSignal() - { - AppState state; - QSignalSpy spy(&state, &AppState::themeNameChanged); - state.setThemeName(QStringLiteral("light")); - QCOMPARE(spy.count(), 1); - } - - void themeNameSetterDoesNotEmitForSameValue() - { - AppState state; - QSignalSpy spy(&state, &AppState::themeNameChanged); - state.setThemeName(QStringLiteral("dark")); // Same as default - QCOMPARE(spy.count(), 0); - } - - // Library tests - - void saveAndRestoreLastPage() - { - { - AppState state; - state.setLastPage(QStringLiteral("library")); - state.save(); - } - AppState state2; - state2.restore(); - QCOMPARE(state2.lastPage(), QStringLiteral("library")); - } - - void lastPageDefaultsToStarter() - { - AppState state; - QCOMPARE(state.lastPage(), QStringLiteral("starter")); - } - - void libraryBooksInitiallyEmpty() - { - AppState state; - auto* model = qobject_cast(state.libraryModel()); - QVERIFY(model->rowCount() == 0); - } - - void addLibraryBookAddsEntry() - { - AppState state; - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.0); - - auto* model = qobject_cast(state.libraryModel()); - QCOMPARE(model->rowCount(), 1); - - // Get data from the model - QModelIndex index = model->index(0); - QString filePath = model->data(index, LibraryModel::FilePathRole).toString(); - double progress = model->data(index, LibraryModel::ProgressRole).toDouble(); - - QCOMPARE(filePath, QStringLiteral("/books/a.epub")); - QCOMPARE(progress, 0.0); - // Title and author are now loaded asynchronously from file metadata - // QString title = model->data(index, 2).toString(); // TitleRole = 2 - // QString author = model->data(index, 3).toString(); // AuthorRole = 3 - // QCOMPARE(title, QStringLiteral("Title A")); - // QCOMPARE(author, QStringLiteral("Author A")); - } - - void addLibraryBookPersistsThroughSaveRestore() - { - { - AppState state; - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.5); - state.save(); - } - AppState state2; - state2.restore(); - auto* model = qobject_cast(state2.libraryModel()); - QCOMPARE(model->rowCount(), 1); - - QModelIndex index = model->index(0); - QString filePath = model->data(index, LibraryModel::FilePathRole).toString(); - double progress = model->data(index, LibraryModel::ProgressRole).toDouble(); - - QCOMPARE(filePath, QStringLiteral("/books/a.epub")); - // Title is now loaded asynchronously from file metadata - // QString title = model->data(index, 2).toString(); // TitleRole = 2 - // QCOMPARE(title, QStringLiteral("Title A")); - QCOMPARE(progress, 0.5); - } - - void addLibraryBookUpdatesMetadata() - { - AppState state; - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.3); - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.3); - - auto* model = qobject_cast(state.libraryModel()); - QCOMPARE(model->rowCount(), 1); - - QModelIndex index = model->index(0); - // Title and author are now loaded asynchronously from file metadata - // QString title = model->data(index, 2).toString(); // TitleRole = 2 - // QString author = model->data(index, 3).toString(); // AuthorRole = 3 - // QCOMPARE(title, QStringLiteral("New Title")); - // QCOMPARE(author, QStringLiteral("New Author")); - } - - void addLibraryBookOverwritesProgress() - { - AppState state; - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.6); - // Lower value should overwrite (always update, no max logic) - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.2); - - auto* model = qobject_cast(state.libraryModel()); - QCOMPARE(model->rowCount(), 1); - QModelIndex index = model->index(0); - double progress = model->data(index, LibraryModel::ProgressRole).toDouble(); - QCOMPARE(progress, 0.2); - } - - void addLibraryBookSentinelPreservesProgress() - { - AppState state; - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.5); - // -1.0 sentinel: update metadata but don't touch progress - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), -1.0); - - auto* model = qobject_cast(state.libraryModel()); - QCOMPARE(model->rowCount(), 1); - QModelIndex index = model->index(0); - double progress = model->data(index, LibraryModel::ProgressRole).toDouble(); - QCOMPARE(progress, 0.5); - // Title is now loaded asynchronously from file metadata - // QString title = model->data(index, 2).toString(); // TitleRole = 2 - // QCOMPARE(title, QStringLiteral("New Title")); - } - - void addNewLibraryBookWithSentinelStartsAtZero() - { - AppState state; - // New book added with sentinel should start at 0% - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), -1.0); - - auto* model = qobject_cast(state.libraryModel()); - QCOMPARE(model->rowCount(), 1); - QModelIndex index = model->index(0); - double progress = model->data(index, LibraryModel::ProgressRole).toDouble(); - QCOMPARE(progress, 0.0); - } - - void removeLibraryBookRemovesEntry() - { - AppState state; - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.5); - state.addOrUpdateLibraryBook(QStringLiteral("/books/b.epub"), 0.3); - state.removeLibraryBook(QStringLiteral("/books/a.epub")); - - auto* model = qobject_cast(state.libraryModel()); - QCOMPARE(model->rowCount(), 1); - QModelIndex index = model->index(0); - QString filePath = model->data(index, LibraryModel::FilePathRole).toString(); - QCOMPARE(filePath, QStringLiteral("/books/b.epub")); - } - - void removeNonexistentLibraryBookIsNoop() - { - AppState state; - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.5); - state.removeLibraryBook(QStringLiteral("/books/nonexistent.epub")); - - auto* model = qobject_cast(state.libraryModel()); - QCOMPARE(model->rowCount(), 1); - } - - void libraryBooksChangedSignalOnAdd() - { - AppState state; - auto* model = qobject_cast(state.libraryModel()); - QSignalSpy spy(model, &QAbstractListModel::rowsInserted); - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.0); - QCOMPARE(spy.count(), 1); - } - - void libraryBooksChangedSignalOnRemove() - { - AppState state; - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.0); - auto* model = qobject_cast(state.libraryModel()); - QSignalSpy spy(model, &QAbstractListModel::rowsRemoved); - state.removeLibraryBook(QStringLiteral("/books/a.epub")); - QCOMPARE(spy.count(), 1); - } - - void multipleLibraryBooksAreStoredInOrder() - { - AppState state; - state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.1); - state.addOrUpdateLibraryBook(QStringLiteral("/books/b.epub"), 0.2); - - auto* model = qobject_cast(state.libraryModel()); - QCOMPARE(model->rowCount(), 2); - // Most recently added/updated comes first - QModelIndex index0 = model->index(0); - QModelIndex index1 = model->index(1); - QString filePath0 = model->data(index0, LibraryModel::FilePathRole).toString(); - QString filePath1 = model->data(index1, LibraryModel::FilePathRole).toString(); - QCOMPARE(filePath0, QStringLiteral("/books/b.epub")); - QCOMPARE(filePath1, QStringLiteral("/books/a.epub")); + const QVariantMap loaded = state.loadSection(nestedSection); + QCOMPARE(loaded.value(QStringLiteral("chunkIndex")).toInt(), 5); } }; diff --git a/tests/ReadingModelTest.cpp b/tests/ReadingModelTest.cpp index 1a87f4b..4236831 100644 --- a/tests/ReadingModelTest.cpp +++ b/tests/ReadingModelTest.cpp @@ -1,7 +1,12 @@ #include +#include +#include #include +#include +#include "backend/AppState.h" #include "backend/ReadingModel.h" #include "backend/FormatReader.h" +#include "backend/state/BookPositionStore.h" // A fake reader that has 3 chapters, 2 chunks each → 6 total chunks class FakeReader : public FormatReader { @@ -25,6 +30,7 @@ public: QString author() override { return QStringLiteral("Fake Author"); } QString filePath() override { return QStringLiteral("/fake/path.txt"); } QString coverImagePath() override { return {}; } + QByteArray contentHash() override { return QByteArray("fakehash"); } bool loadMetadata(const QString &) override { return true; } }; @@ -39,16 +45,34 @@ public: QString author() override { return {}; } QString filePath() override { return QStringLiteral("/fake/single.txt"); } QString coverImagePath() override { return {}; } + QByteArray contentHash() override { return QByteArray("singlehash"); } bool loadMetadata(const QString &) override { return true; } }; class ReadingModelTest : public QObject { Q_OBJECT +private: + struct Ctx { + QTemporaryFile f; + QSettings *s = nullptr; + AppState *appState = nullptr; + BookPositionStore *store = nullptr; + + Ctx() { + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/rm-test-XXXXXX.ini")); + f.open(); f.close(); + s = new QSettings(f.fileName(), QSettings::IniFormat); + appState = new AppState(*s); + store = new BookPositionStore(*appState); + } + ~Ctx() { delete store; delete appState; delete s; } + }; + private slots: void initialState() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); QCOMPARE(model.totalChapters(), 0); QCOMPARE(model.progress(), 0.0); QVERIFY(model.chapterTitle().isEmpty()); @@ -57,7 +81,7 @@ private slots: void setReaderLoadsAllChapters() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); @@ -70,7 +94,7 @@ private slots: void chunkContentAcrossChapters() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); @@ -93,7 +117,7 @@ private slots: void dataInvalidForOutOfRange() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); @@ -103,7 +127,7 @@ private slots: void currentChapterDerivedFromScroll() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); @@ -126,7 +150,7 @@ private slots: void chapterChangedSignalOnScroll() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); @@ -147,7 +171,7 @@ private slots: void goToChapterEmitsScrollSignal() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); @@ -164,7 +188,7 @@ private slots: void goToChapterOutOfRangeNoSignal() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); @@ -176,7 +200,7 @@ private slots: void nextChapterEmitsScrollSignal() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); @@ -189,7 +213,7 @@ private slots: void nextChapterAtEndNoSignal() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); model.setScrollInfo(4, 0.0); // chapter 2 @@ -201,7 +225,7 @@ private slots: void previousChapterEmitsScrollSignal() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); model.setScrollInfo(4, 0.0); // chapter 2 @@ -214,7 +238,7 @@ private slots: void previousChapterAtStartNoSignal() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); @@ -225,7 +249,7 @@ private slots: void setReaderNull() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); model.setReader(nullptr); @@ -238,7 +262,7 @@ private slots: void roleNamesContainsContent() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); QHash roles = model.roleNames(); QVERIFY(roles.contains(ReadingModel::ContentRole)); QCOMPARE(roles.value(ReadingModel::ContentRole), QByteArray("content")); @@ -246,14 +270,14 @@ private slots: void initialPageState() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); QCOMPARE(model.currentPage(), 0); QCOMPARE(model.totalPages(), 0); } void setScrollInfoUpdatesCurrentPage() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); @@ -270,7 +294,7 @@ private slots: void hasChaptersFalseForSingleChapter() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); SingleChapterReader reader; model.setReader(&reader); @@ -279,7 +303,7 @@ private slots: void hasChaptersTrueForMultipleChapters() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; model.setReader(&reader); @@ -288,7 +312,7 @@ private slots: void hasChaptersFalseInitially() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); QVERIFY(!model.hasChapters()); } @@ -297,7 +321,7 @@ private slots: void coverImagePrependedToChunks() { FakeReader reader; - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); model.setCoverImageUrl("image://epub/OEBPS/cover.jpg"); model.setReader(&reader); @@ -313,7 +337,7 @@ private slots: void coverImageNotAddedWhenUrlEmpty() { FakeReader reader; - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); model.setReader(&reader); model.setCoverImageUrl(""); @@ -324,7 +348,7 @@ private slots: void chapterNavigationSkipsCoverImage() { FakeReader reader; - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); model.setCoverImageUrl("image://epub/OEBPS/cover.jpg"); model.setReader(&reader); @@ -343,7 +367,7 @@ private slots: void coverImageSetAfterReaderReloadsChunks() { FakeReader reader; - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); model.setReader(&reader); QCOMPARE(model.rowCount(QModelIndex()), 6); // no cover yet @@ -363,7 +387,7 @@ private slots: void clearCoverImageUrlRemovesCover() { FakeReader reader; - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); model.setCoverImageUrl(QStringLiteral("image://epub/OEBPS/cover.jpg")); model.setReader(&reader); QCOMPARE(model.rowCount(QModelIndex()), 7); // 1 cover + 6 @@ -378,7 +402,7 @@ private slots: void roleNamesHasNewRoles() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); auto roles = model.roleNames(); QVERIFY(roles.contains(ReadingModel::PixelHeightRole)); QVERIFY(roles.contains(ReadingModel::ChapterRole)); @@ -388,13 +412,13 @@ private slots: void totalPixelHeightInitiallyZero() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); QCOMPARE(model.totalPixelHeight(), 0.0); } void totalPixelHeightResetOnReaderSet() { - ReadingModel model; + Ctx ctx; ReadingModel model(*ctx.store); FakeReader reader; QSignalSpy spy(&model, &ReadingModel::totalPixelHeightChanged); diff --git a/tests/book/BookTest.cpp b/tests/book/BookTest.cpp new file mode 100644 index 0000000..2bb95f4 --- /dev/null +++ b/tests/book/BookTest.cpp @@ -0,0 +1,221 @@ +#include +#include +#include +#include +#include + +#include "backend/AppState.h" +#include "backend/IFileDialogService.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. +class FakeDialogService : public IFileDialogService { + Q_OBJECT +public: + explicit FakeDialogService(QObject *parent = nullptr) : IFileDialogService(parent) {} + void open() override { /* no-op */ } + void triggerFile(const QString &path) { emit fileSelected(path); } +}; + +class BookTest : public QObject { + Q_OBJECT + +private: + static QString epubFixture() + { +#ifdef FIXTURES_DIR + return QStringLiteral(FIXTURES_DIR) + QStringLiteral("/sample.epub"); +#else + return QString(); +#endif + } + + static QString txtFixture() + { +#ifdef FIXTURES_DIR + return QStringLiteral(FIXTURES_DIR) + QStringLiteral("/sample.txt"); +#else + return QString(); +#endif + } + + struct Ctx { + QTemporaryFile f; + QSettings *s = nullptr; + AppState *appState = nullptr; + BookPositionStore *store = nullptr; + FakeDialogService *dialog = nullptr; + Book *book = nullptr; + + Ctx() { + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/book-test-XXXXXX.ini")); + f.open(); f.close(); + s = new QSettings(f.fileName(), QSettings::IniFormat); + appState = new AppState(*s); + store = new BookPositionStore(*appState); + dialog = new FakeDialogService; + book = new Book(*dialog, *store); + } + ~Ctx() { + delete book; + delete dialog; + delete store; + delete appState; + delete s; + } + }; + +private slots: + void initialState() + { + Ctx ctx; + QVERIFY(!ctx.book->hasBook()); + QVERIFY(!ctx.book->loading()); + QCOMPARE(ctx.book->title(), QString()); + QCOMPARE(ctx.book->author(), QString()); + QCOMPARE(ctx.book->filePath(), QString()); + QCOMPARE(ctx.book->coverImageUrl(),QString()); + QCOMPARE(ctx.book->errorMessage(), QString()); + QVERIFY(ctx.book->toc().isEmpty()); + } + + void openValidTxtFile() + { + const QString path = txtFixture(); + if (path.isEmpty() || !QFileInfo::exists(path)) + QSKIP("No TXT fixture"); + + Ctx ctx; + QSignalSpy bookChanged(ctx.book, &Book::bookChanged); + QSignalSpy loading(ctx.book, &Book::loadingChanged); + + ctx.book->openFromPath(path); + + // loading should have become true + QVERIFY(loading.count() > 0 || ctx.book->loading()); + + // Wait for the async open to complete + QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); + + QVERIFY(!ctx.book->loading()); + QCOMPARE(ctx.book->filePath(), path); + QVERIFY(!ctx.book->title().isEmpty()); + QVERIFY(bookChanged.count() > 0); + } + + void openInvalidPath() + { + Ctx ctx; + QSignalSpy errorSpy(ctx.book, &Book::errorMessageChanged); + + ctx.book->openFromPath(QStringLiteral("/nonexistent/file.txt")); + + QTRY_VERIFY_WITH_TIMEOUT(!ctx.book->errorMessage().isEmpty(), 5000); + QVERIFY(!ctx.book->hasBook()); + QVERIFY(!ctx.book->loading()); + } + + void clearError() + { + Ctx ctx; + ctx.book->openFromPath(QStringLiteral("/nonexistent/file.txt")); + QTRY_VERIFY_WITH_TIMEOUT(!ctx.book->errorMessage().isEmpty(), 5000); + + QSignalSpy errorSpy(ctx.book, &Book::errorMessageChanged); + ctx.book->clearError(); + QCOMPARE(ctx.book->errorMessage(), QString()); + QCOMPARE(errorSpy.count(), 1); + } + + void closeBook() + { + const QString path = txtFixture(); + if (path.isEmpty() || !QFileInfo::exists(path)) + QSKIP("No TXT fixture"); + + Ctx ctx; + ctx.book->openFromPath(path); + QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); + + QSignalSpy bookChanged(ctx.book, &Book::bookChanged); + ctx.book->close(); + QVERIFY(!ctx.book->hasBook()); + QCOMPARE(bookChanged.count(), 1); + } + + void willOpenNewBookFiredBeforeSwap() + { + const QString path = txtFixture(); + if (path.isEmpty() || !QFileInfo::exists(path)) + QSKIP("No TXT fixture"); + + Ctx ctx; + ctx.book->openFromPath(path); + QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); + + QSignalSpy willOpen(ctx.book, &Book::willOpenNewBook); + ctx.book->openFromPath(path); // second open triggers willOpenNewBook + QCOMPARE(willOpen.count(), 1); + } + + void openFromUrl() + { + const QString path = txtFixture(); + if (path.isEmpty() || !QFileInfo::exists(path)) + QSKIP("No TXT fixture"); + + Ctx ctx; + ctx.book->openFromUrl(QUrl::fromLocalFile(path)); + QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); + QCOMPARE(ctx.book->filePath(), path); + } + + void browseAndOpenDelegatesToDialog() + { + Ctx ctx; + QSignalSpy loading(ctx.book, &Book::loadingChanged); + + const QString path = txtFixture(); + if (path.isEmpty() || !QFileInfo::exists(path)) + QSKIP("No TXT fixture"); + + // Simulate the dialog emitting fileSelected + ctx.book->browseAndOpen(); // calls dialog.open() which in FakeDialogService is a no-op + ctx.dialog->triggerFile(path); + QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); + } + + void saveCurrentPositionUsesHash() + { + const QString path = txtFixture(); + if (path.isEmpty() || !QFileInfo::exists(path)) + QSKIP("No TXT fixture"); + + Ctx ctx; + ctx.book->openFromPath(path); + QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000); + + ctx.book->saveCurrentPosition(3, 17); + + const QByteArray hash = ctx.book->reader()->contentHash(); + QVERIFY(!hash.isEmpty()); + const BookPosition pos = ctx.store->load(hash); + QCOMPARE(pos.chunkIndex, 3); + QCOMPARE(pos.intraOffset, 17); + } + + void contentWidthSignal() + { + Ctx ctx; + QSignalSpy spy(ctx.book, &Book::contentWidthChanged); + ctx.book->setContentWidth(800); + QCOMPARE(spy.count(), 1); + QCOMPARE(spy.first().first().toInt(), 800); + ctx.book->setContentWidth(800); // no-op + QCOMPARE(spy.count(), 1); + } +}; + +QTEST_MAIN(BookTest) +#include "BookTest.moc" diff --git a/tests/state/BookPositionStoreTest.cpp b/tests/state/BookPositionStoreTest.cpp new file mode 100644 index 0000000..3e74ac9 --- /dev/null +++ b/tests/state/BookPositionStoreTest.cpp @@ -0,0 +1,98 @@ +#include +#include +#include +#include +#include + +#include "backend/AppState.h" +#include "backend/state/BookPositionStore.h" + +class BookPositionStoreTest : public QObject { + Q_OBJECT + +private slots: + void defaultPositionForUnknownHash() + { + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/bps-def-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState appState(s); + BookPositionStore store(appState); + + const BookPosition pos = store.load(QByteArray("nonexistent")); + QCOMPARE(pos.chunkIndex, 0); + QCOMPARE(pos.intraOffset, 0); + } + + void saveAndLoad() + { + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/bps-sr-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState appState(s); + BookPositionStore store(appState); + + const QByteArray hash = QByteArray("abc123deadbeef"); + store.save(hash, 7, 42); + const BookPosition pos = store.load(hash); + QCOMPARE(pos.chunkIndex, 7); + QCOMPARE(pos.intraOffset, 42); + } + + void separateHashesStoredIndependently() + { + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/bps-sep-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState appState(s); + BookPositionStore store(appState); + + store.save(QByteArray("hash1"), 1, 10); + store.save(QByteArray("hash2"), 2, 20); + + QCOMPARE(store.load(QByteArray("hash1")).chunkIndex, 1); + QCOMPARE(store.load(QByteArray("hash2")).chunkIndex, 2); + QCOMPARE(store.load(QByteArray("hash1")).intraOffset, 10); + QCOMPARE(store.load(QByteArray("hash2")).intraOffset, 20); + } + + void overwriteExistingPosition() + { + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/bps-ow-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState appState(s); + BookPositionStore store(appState); + + const QByteArray hash = QByteArray("overwrite-hash"); + store.save(hash, 3, 30); + store.save(hash, 5, 55); + + const BookPosition pos = store.load(hash); + QCOMPARE(pos.chunkIndex, 5); + QCOMPARE(pos.intraOffset, 55); + } + + void emptyHashIgnored() + { + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/bps-empty-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState appState(s); + BookPositionStore store(appState); + + // Neither save nor load should crash with an empty hash + store.save(QByteArray(), 1, 1); + const BookPosition pos = store.load(QByteArray()); + QCOMPARE(pos.chunkIndex, 0); + QCOMPARE(pos.intraOffset, 0); + } +}; + +QTEST_MAIN(BookPositionStoreTest) +#include "BookPositionStoreTest.moc" diff --git a/tests/state/ReadingPreferencesTest.cpp b/tests/state/ReadingPreferencesTest.cpp new file mode 100644 index 0000000..035ff66 --- /dev/null +++ b/tests/state/ReadingPreferencesTest.cpp @@ -0,0 +1,81 @@ +#include +#include +#include +#include +#include + +#include "backend/AppState.h" +#include "backend/state/ReadingPreferences.h" + +class ReadingPreferencesTest : public QObject { + Q_OBJECT + +private slots: + void defaultsWhenEmpty() + { + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/rp-def-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState appState(s); + ReadingPreferences prefs(appState); + + QCOMPARE(prefs.fontSize(), 16); + QCOMPARE(prefs.lineSpacing(), 1.6); + QCOMPARE(prefs.horizontalMargin(), 32); + QCOMPARE(prefs.verticalMargin(), 8); + } + + void saveAndRestore() + { + QString fileName; + { + QTemporaryFile tmp; + tmp.setFileTemplate(QDir::tempPath() + QStringLiteral("/rp-sr-XXXXXX.ini")); + tmp.setAutoRemove(false); + QVERIFY(tmp.open()); + fileName = tmp.fileName(); + } + + { + QSettings s(fileName, QSettings::IniFormat); + AppState appState(s); + ReadingPreferences prefs(appState); + prefs.setFontSize(20); + prefs.setLineSpacing(2.0); + prefs.setHorizontalMargin(48); + prefs.setVerticalMargin(16); + prefs.save(); + } + + QSettings s2(fileName, QSettings::IniFormat); + AppState appState2(s2); + ReadingPreferences prefs2(appState2); + + QCOMPARE(prefs2.fontSize(), 20); + QCOMPARE(prefs2.lineSpacing(), 2.0); + QCOMPARE(prefs2.horizontalMargin(), 48); + QCOMPARE(prefs2.verticalMargin(), 16); + + QFile::remove(fileName); + } + + void fontSizeSignal() + { + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/rp-sig-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState appState(s); + ReadingPreferences prefs(appState); + + QSignalSpy spy(&prefs, &ReadingPreferences::fontSizeChanged); + prefs.setFontSize(18); + QCOMPARE(spy.count(), 1); + prefs.setFontSize(18); // no-op + QCOMPARE(spy.count(), 1); + } +}; + +QTEST_MAIN(ReadingPreferencesTest) +#include "ReadingPreferencesTest.moc" diff --git a/tests/state/UiStateTest.cpp b/tests/state/UiStateTest.cpp new file mode 100644 index 0000000..013fccf --- /dev/null +++ b/tests/state/UiStateTest.cpp @@ -0,0 +1,109 @@ +#include +#include +#include +#include +#include + +#include "backend/AppState.h" +#include "backend/state/UiState.h" + +class UiStateTest : public QObject { + Q_OBJECT + +private slots: + void defaultsWhenEmpty() + { + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/ui-def-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState appState(s); + UiState ui(appState); + + QCOMPARE(ui.themeName(), QStringLiteral("dark")); + QCOMPARE(ui.lastPage(), QStringLiteral("starter")); + QCOMPARE(ui.sidebarOpen(), false); + QCOMPARE(ui.lastFilePath(), QString()); + QCOMPARE(ui.windowWidth(), 1024); + QCOMPARE(ui.windowHeight(), 768); + QCOMPARE(ui.windowX(), -1); + QCOMPARE(ui.windowY(), -1); + } + + void saveAndRestore() + { + QString fileName; + { + QTemporaryFile tmp; + tmp.setFileTemplate(QDir::tempPath() + QStringLiteral("/ui-sr-XXXXXX.ini")); + tmp.setAutoRemove(false); + QVERIFY(tmp.open()); + fileName = tmp.fileName(); + } + + { + QSettings s(fileName, QSettings::IniFormat); + AppState appState(s); + UiState ui(appState); + ui.setThemeName(QStringLiteral("light")); + ui.setLastPage(QStringLiteral("settings")); + ui.setSidebarOpen(true); + ui.setLastFilePath(QStringLiteral("/some/file.epub")); + ui.setWindowWidth(1280); + ui.setWindowHeight(800); + ui.setWindowX(100); + ui.setWindowY(50); + ui.save(); + } + + QSettings s2(fileName, QSettings::IniFormat); + AppState appState2(s2); + UiState ui2(appState2); + + QCOMPARE(ui2.themeName(), QStringLiteral("light")); + QCOMPARE(ui2.lastPage(), QStringLiteral("settings")); + QCOMPARE(ui2.sidebarOpen(), true); + QCOMPARE(ui2.lastFilePath(), QStringLiteral("/some/file.epub")); + QCOMPARE(ui2.windowWidth(), 1280); + QCOMPARE(ui2.windowHeight(), 800); + QCOMPARE(ui2.windowX(), 100); + QCOMPARE(ui2.windowY(), 50); + + QFile::remove(fileName); + } + + void lastFilePathSignal() + { + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/ui-sig-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState appState(s); + UiState ui(appState); + + QSignalSpy spy(&ui, &UiState::lastFilePathChanged); + ui.setLastFilePath(QStringLiteral("/a/b")); + QCOMPARE(spy.count(), 1); + ui.setLastFilePath(QStringLiteral("/a/b")); // no-op + QCOMPARE(spy.count(), 1); + } + + void windowWidthSignal() + { + QTemporaryFile f; + f.setFileTemplate(QDir::tempPath() + QStringLiteral("/ui-sig-w-XXXXXX.ini")); + f.open(); f.close(); + QSettings s(f.fileName(), QSettings::IniFormat); + AppState appState(s); + UiState ui(appState); + + QSignalSpy spy(&ui, &UiState::windowWidthChanged); + ui.setWindowWidth(999); + QCOMPARE(spy.count(), 1); + ui.setWindowWidth(999); // no-op + QCOMPARE(spy.count(), 1); + } +}; + +QTEST_MAIN(UiStateTest) +#include "UiStateTest.moc"