Some refactor

This commit is contained in:
Agel committed 2026-04-08 14:01:03 +02:00
1 parent 7ecb7f4f4f
commit 9280c838b2
37 files changed
+1595 -977

No files matched your search

+1 -1
View File
@@ -269,4 +269,4 @@ All colors are defined in `src/qml/Theme.qml` (a QML singleton registered via `q
- `QSettings` for persistent state - `QSettings` for persistent state
- Qt naming: `camelCase` properties/methods, `PascalCase` QML component names - Qt naming: `camelCase` properties/methods, `PascalCase` QML component names
- `Q_INVOKABLE` for QML-callable methods; signals for C++→QML notifications - `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.
+31 -22
View File
@@ -42,8 +42,14 @@ set(SOURCES
src/backend/LibraryModel.cpp src/backend/LibraryModel.cpp
src/backend/ReadingModel.h src/backend/ReadingModel.h
src/backend/ReadingModel.cpp src/backend/ReadingModel.cpp
src/backend/BookController.h src/backend/state/ReadingPreferences.h
src/backend/BookController.cpp 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/IImageProvider.h
src/backend/EpubImageProvider.h src/backend/EpubImageProvider.h
src/backend/EpubImageProvider.cpp src/backend/EpubImageProvider.cpp
@@ -214,6 +220,7 @@ add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp
src/backend/ChunkMeasurer.cpp src/backend/ChunkMeasurer.cpp
src/backend/EpubImageProvider.cpp src/backend/EpubImageProvider.cpp
src/backend/AppState.cpp src/backend/AppState.cpp
src/backend/state/BookPositionStore.cpp
src/backend/LibraryBookModel.cpp src/backend/LibraryBookModel.cpp
src/backend/LibraryModel.cpp src/backend/LibraryModel.cpp
src/backend/ReaderFactory.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) 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") set_tests_properties(ReadingModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(BookControllerTest tests/BookControllerTest.cpp add_asteria_test(AppStateTest tests/AppStateTest.cpp
src/backend/BookController.cpp src/backend/AppState.cpp)
add_asteria_test(ReadingPreferencesTest tests/state/ReadingPreferencesTest.cpp
src/backend/AppState.cpp src/backend/AppState.cpp
src/backend/LibraryBookModel.cpp src/backend/state/ReadingPreferences.cpp)
src/backend/LibraryModel.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/ReaderFactory.cpp
src/backend/ReadingModel.cpp
src/backend/IFileDialogService.cpp src/backend/IFileDialogService.cpp
src/backend/NativeFileDialogService.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/TxtReader.cpp
src/backend/formats/EpubReader.cpp) src/backend/formats/EpubReader.cpp)
add_asteria_test(AppStateTest tests/AppStateTest.cpp target_link_libraries(BookTest PRIVATE Qt6::Concurrent Qt6::Widgets PkgConfig::MINIZIP Qt6::Xml)
src/backend/AppState.cpp set_tests_properties(BookTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
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")
add_asteria_test(EpubImageProviderTest tests/EpubImageProviderTest.cpp add_asteria_test(EpubImageProviderTest tests/EpubImageProviderTest.cpp
src/backend/EpubImageProvider.cpp) src/backend/EpubImageProvider.cpp)
+35 -257
View File
@@ -1,279 +1,57 @@
#include "AppState.h" #include "AppState.h"
#include "LibraryBookModel.h"
#include "LibraryModel.h"
#include <QtConcurrent/QtConcurrent>
static constexpr int SETTINGS_VERSION = 3; AppState::AppState(QSettings &settings)
: m_settings(settings)
static QString bookSettingsKey(const QString &filePath)
{ {
QByteArray hash = QCryptographicHash::hash(filePath.toUtf8(), QCryptographicHash::Md5).toHex(); if (m_settings.value(QStringLiteral("version"), 0).toInt() != SETTINGS_VERSION) {
return QStringLiteral("bookmarks/") + QString::fromLatin1(hash); m_settings.clear();
m_settings.setValue(QStringLiteral("version"), SETTINGS_VERSION);
}
} }
AppState::AppState(QObject *parent) QVariantMap AppState::loadSection(const QString &section) const
: QObject(parent)
{ {
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; QVariantMap result;
result[QStringLiteral("chunkIndex")] = s.value(key + QStringLiteral("/chunkIndex"), 0).toInt(); m_settings.beginGroup(section);
result[QStringLiteral("intraChunkOffset")] = s.value(key + QStringLiteral("/intraChunkOffset"), 0.0).toInt(); const QStringList keys = m_settings.childKeys();
for (const QString &key : keys)
result[key] = m_settings.value(key);
m_settings.endGroup();
return result; return result;
} }
QString AppState::lastPage() const { return m_lastPage; } void AppState::saveSection(const QString &section, const QVariantMap &data) const
void AppState::setLastPage(const QString &page)
{ {
if (m_lastPage == page) m_settings.beginGroup(section);
return; m_settings.remove(QStringLiteral("")); // clear existing group
m_lastPage = page; for (auto it = data.cbegin(); it != data.cend(); ++it)
emit lastPageChanged(); m_settings.setValue(it.key(), it.value());
m_settings.endGroup();
} }
bool AppState::sidebarOpen() const { return m_sidebarOpen; } QList<QVariantMap> AppState::loadArray(const QString &section) const
void AppState::setSidebarOpen(bool open)
{ {
if (m_sidebarOpen == open) QList<QVariantMap> result;
return; QSettings &s = const_cast<QSettings &>(m_settings);
m_sidebarOpen = open; const int size = s.beginReadArray(section);
emit sidebarOpenChanged(); for (int i = 0; i < size; ++i) {
}
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++) {
s.setArrayIndex(i); s.setArrayIndex(i);
QString filePath = s.value(QStringLiteral("filePath")).toString(); QVariantMap entry;
if (filePath.isEmpty()) for (const QString &key : s.childKeys())
continue; entry[key] = s.value(key);
bool progressOk; result.append(entry);
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);
} }
s.endArray(); s.endArray();
return result;
} }
void AppState::saveLibraryBooks() void AppState::saveArray(const QString &section, const QList<QVariantMap> &items) const
{ {
QSettings s; m_settings.beginWriteArray(section, items.size());
QList<LibraryBookModel*> books = m_libraryModel->books(); for (int i = 0; i < items.size(); ++i) {
s.beginWriteArray(QStringLiteral("library"), books.size()); m_settings.setArrayIndex(i);
for (int i = 0; i < books.size(); i++) { for (auto it = items[i].cbegin(); it != items[i].cend(); ++it)
s.setArrayIndex(i); m_settings.setValue(it.key(), it.value());
LibraryBookModel* book = books[i];
s.setValue(QStringLiteral("filePath"), book->filePath());
s.setValue(QStringLiteral("progress"), book->progress());
s.setValue(QStringLiteral("lastOpened"), book->lastOpened());
} }
s.endArray(); m_settings.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();
} }
+17 -98
View File
@@ -1,114 +1,33 @@
#ifndef APPSTATE_H #ifndef APPSTATE_H
#define APPSTATE_H #define APPSTATE_H
#include <QObject> #include <QSettings>
#include <QString>
#include <QUrl>
#include <QVariantMap> #include <QVariantMap>
class LibraryBookModel; // AppState is a pure persistence service. It wraps QSettings and provides an atomic
class LibraryModel; // section-based API. It holds no domain state of its own. QML never sees this object.
class AppState {
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)
public: public:
explicit AppState(QObject *parent = nullptr); static constexpr int SETTINGS_VERSION = 4;
QString themeName() const; // Constructs AppState. If the stored version does not match SETTINGS_VERSION,
void setThemeName(const QString &themeName); // all settings are cleared (clean migration).
explicit AppState(QSettings &settings);
QString lastFilePath() const; // Load all key/value pairs from the named QSettings group.
void setLastFilePath(const QString &path); QVariantMap loadSection(const QString &section) const;
int horizontalMargin() const; // Atomically replace the named QSettings group with the given data.
void setHorizontalMargin(int margin); void saveSection(const QString &section, const QVariantMap &data) const;
int verticalMargin() const; // Load an ordered array (e.g., library books) from the named QSettings array.
void setVerticalMargin(int margin); QList<QVariantMap> loadArray(const QString &section) const;
int fontSize() const; // Atomically replace the named QSettings array.
void setFontSize(int size); void saveArray(const QString &section, const QList<QVariantMap> &items) const;
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();
private: private:
void loadLibraryBooks(); QSettings &m_settings;
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");
}; };
#endif // APPSTATE_H #endif // APPSTATE_H
+4
View File
@@ -1,6 +1,7 @@
#ifndef FORMATREADER_H #ifndef FORMATREADER_H
#define FORMATREADER_H #define FORMATREADER_H
#include <QByteArray>
#include <QString> #include <QString>
#include <QList> #include <QList>
@@ -30,6 +31,9 @@ public:
virtual QString title() = 0; virtual QString title() = 0;
virtual QString author() = 0; virtual QString author() = 0;
virtual QString coverImagePath() = 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;
}; };
+31
View File
@@ -1,5 +1,6 @@
#include "LibraryModel.h" #include "LibraryModel.h"
#include "LibraryBookModel.h" #include "LibraryBookModel.h"
#include <QDateTime>
LibraryModel::LibraryModel(QObject *parent) LibraryModel::LibraryModel(QObject *parent)
: QAbstractListModel(parent) : QAbstractListModel(parent)
@@ -157,6 +158,36 @@ void LibraryModel::clear()
emit countChanged(); 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<LibraryBookModel*> LibraryModel::books() const QList<LibraryBookModel*> LibraryModel::books() const
{ {
return m_books; return m_books;
+7
View File
@@ -36,10 +36,17 @@ public:
// Methods to manage books // Methods to manage books
Q_INVOKABLE void addOrUpdateBook(const QString &filePath, double progress, const QString &lastOpened); 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 void removeBook(const QString &filePath);
Q_INVOKABLE LibraryBookModel* findBook(const QString &filePath) const; Q_INVOKABLE LibraryBookModel* findBook(const QString &filePath) const;
Q_INVOKABLE void clear(); 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 // Access to books for saving/loading
QList<LibraryBookModel*> books() const; QList<LibraryBookModel*> books() const;
+7 -7
View File
@@ -7,9 +7,11 @@
#include <cmath> #include <cmath>
#include <QtConcurrent> #include <QtConcurrent>
#include "AppState.h" ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent)
: QAbstractListModel(parent)
ReadingModel::ReadingModel(QObject *parent) : QAbstractListModel(parent) {} , m_positions(positions)
{
}
ReadingModel::~ReadingModel() ReadingModel::~ReadingModel()
{ {
@@ -126,10 +128,8 @@ void ReadingModel::runMeasurement(const QStringList &htmls, const bool isNew)
{PixelHeightRole}); {PixelHeightRole});
if (isNew) { if (isNew) {
QVariantMap map = AppState::loadBookPosition(m_reader->filePath()); const auto pos = m_positions.load(m_reader->contentHash());
int savedChunk = map.value(QStringLiteral("chunkIndex"), 0).toInt(); emit restoreReady(pos.chunkIndex, pos.intraOffset);
qreal savedIntra = map.value(QStringLiteral("intraChunkOffset"), 0).toInt();
restoreReady(savedChunk, savedIntra);
} }
}, Qt::QueuedConnection); }, Qt::QueuedConnection);
}); });
+3 -1
View File
@@ -6,6 +6,7 @@
#include <QString> #include <QString>
#include <memory> #include <memory>
#include "IImageLoader.h" #include "IImageLoader.h"
#include "state/BookPositionStore.h"
class FormatReader; class FormatReader;
@@ -35,7 +36,7 @@ public:
ChapterRole = Qt::UserRole + 3, ChapterRole = Qt::UserRole + 3,
}; };
explicit ReadingModel(QObject *parent = nullptr); explicit ReadingModel(BookPositionStore &positions, QObject *parent = nullptr);
~ReadingModel() override; ~ReadingModel() override;
int rowCount(const QModelIndex &parent) const override; int rowCount(const QModelIndex &parent) const override;
@@ -106,6 +107,7 @@ private:
int m_fontSize = 0; int m_fontSize = 0;
qreal m_lineSpacing = 0; qreal m_lineSpacing = 0;
BookPositionStore &m_positions;
std::unique_ptr<IImageLoader> m_imageLoader; std::unique_ptr<IImageLoader> m_imageLoader;
QFuture<void> m_measureFuture; QFuture<void> m_measureFuture;
}; };
+145
View File
@@ -0,0 +1,145 @@
#include "Book.h"
#include "backend/ReaderFactory.h"
#include <QtConcurrent>
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<TocEntry> Book::toc() const
{
return m_reader ? m_reader->tableOfContents() : QList<TocEntry>{};
}
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::unique_ptr<FormatReader>>(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);
}
+83
View File
@@ -0,0 +1,83 @@
#ifndef BOOK_H
#define BOOK_H
#include <QFuture>
#include <QList>
#include <QObject>
#include <QString>
#include <QUrl>
#include <memory>
#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<TocEntry> 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<TocEntry> 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<FormatReader> m_reader;
QString m_coverImageUrl;
QString m_errorMessage;
bool m_loading = false;
int m_openGeneration = 0;
int m_contentWidth = 0;
QFuture<void> m_openFuture;
};
#endif // BOOK_H
+15
View File
@@ -1,7 +1,9 @@
#include "EpubReader.h" #include "EpubReader.h"
#include <QCryptographicHash>
#include <QDir> #include <QDir>
#include <QDomDocument> #include <QDomDocument>
#include <QFile>
#include <QFileInfo> #include <QFileInfo>
#include <QTextStream> #include <QTextStream>
#include <QUrl> #include <QUrl>
@@ -35,6 +37,14 @@ bool EpubReader::open(const QString &filePath)
m_spineHrefs.clear(); m_spineHrefs.clear();
m_spineRawContent.clear(); m_spineRawContent.clear();
m_toc.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()); unzFile zf = unzOpen(filePath.toUtf8().constData());
if (!zf) { if (!zf) {
@@ -390,6 +400,11 @@ QString EpubReader::filePath()
return m_filePath; return m_filePath;
} }
QByteArray EpubReader::contentHash()
{
return m_contentHash;
}
Chapter EpubReader::loadChapter(int index) Chapter EpubReader::loadChapter(int index)
{ {
if (index < 0 || index >= m_spineRawContent.size()) if (index < 0 || index >= m_spineRawContent.size())
+2
View File
@@ -18,9 +18,11 @@ public:
QString title() override; QString title() override;
QString author() override; QString author() override;
QString coverImagePath() override; QString coverImagePath() override;
QByteArray contentHash() override;
private: private:
QString m_filePath; QString m_filePath;
QByteArray m_contentHash;
QString m_title; QString m_title;
QString m_author; QString m_author;
QString m_error; QString m_error;
+8
View File
@@ -1,5 +1,6 @@
#include "TxtReader.h" #include "TxtReader.h"
#include <QCryptographicHash>
#include <QFileInfo> #include <QFileInfo>
#include <QRegularExpression> #include <QRegularExpression>
#include <QTextStream> #include <QTextStream>
@@ -110,6 +111,8 @@ bool TxtReader::open(const QString &filePath)
QByteArray raw = file.readAll(); QByteArray raw = file.readAll();
file.close(); file.close();
m_contentHash = QCryptographicHash::hash(raw, QCryptographicHash::Md5);
uchardet_t ud = uchardet_new(); uchardet_t ud = uchardet_new();
if (uchardet_handle_data(ud, raw.constData(), raw.size()) == 0) { if (uchardet_handle_data(ud, raw.constData(), raw.size()) == 0) {
uchardet_data_end(ud); uchardet_data_end(ud);
@@ -206,3 +209,8 @@ QString TxtReader::coverImagePath()
{ {
return {}; return {};
} }
QByteArray TxtReader::contentHash()
{
return m_contentHash;
}
+2
View File
@@ -15,6 +15,7 @@ public:
QString title() override; QString title() override;
QString author() override; QString author() override;
QString coverImagePath() override; QString coverImagePath() override;
QByteArray contentHash() override;
private: private:
QString m_content; QString m_content;
@@ -22,6 +23,7 @@ private:
QString m_title; QString m_title;
QString m_author; QString m_author;
QString m_error; QString m_error;
QByteArray m_contentHash;
}; };
#endif // TXTREADER_H #endif // TXTREADER_H
+32
View File
@@ -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());
}
+28
View File
@@ -0,0 +1,28 @@
#ifndef BOOKPOSITIONSTORE_H
#define BOOKPOSITIONSTORE_H
#include <QByteArray>
#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
+55
View File
@@ -0,0 +1,55 @@
#include "ReadingPreferences.h"
#include <QtGlobal>
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},
});
}
+42
View File
@@ -0,0 +1,42 @@
#ifndef READINGPREFERENCES_H
#define READINGPREFERENCES_H
#include <QObject>
#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
+99
View File
@@ -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},
});
}
+63
View File
@@ -0,0 +1,63 @@
#ifndef UISTATE_H
#define UISTATE_H
#include <QObject>
#include <QString>
#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
+131 -39
View File
@@ -1,4 +1,5 @@
#include <QApplication> #include <QApplication>
#include <QDateTime>
#include <QFileInfo> #include <QFileInfo>
#include <QSize> #include <QSize>
#include <QQmlApplicationEngine> #include <QQmlApplicationEngine>
@@ -8,12 +9,17 @@
#include <QSettings> #include <QSettings>
#include <QSGRendererInterface> #include <QSGRendererInterface>
#include "backend/BookController.h"
#include "backend/IImageProvider.h"
#include "backend/ReadingModel.h"
#include "backend/AppState.h" #include "backend/AppState.h"
#include "backend/IImageProvider.h"
#include "backend/ImageLoaderFactory.h"
#include "backend/ImageProviderFactory.h"
#include "backend/LibraryModel.h" #include "backend/LibraryModel.h"
#include "backend/ReadingModel.h"
#include "backend/NativeFileDialogService.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 #ifdef HAS_QT_DBUS
#include <QDBusConnection> #include <QDBusConnection>
@@ -80,50 +86,147 @@ int main(int argc, char *argv[])
QQuickStyle::setStyle(QStringLiteral("Basic")); QQuickStyle::setStyle(QStringLiteral("Basic"));
ReadingModel readingModel; // --- Object graph (construction order = dependency order) ---
QSettings settings;
AppState appState(settings);
BookController bookController; ReadingPreferences readingPreferences(appState);
bookController.setReadingModel(&readingModel); UiState uiState(appState);
BookPositionStore bookPositions(appState);
AppState appState; LibraryModel libraryModel;
appState.restore(); for (const QVariantMap &entry : appState.loadArray(QStringLiteral("library"))) {
bookController.setAppState(&appState); 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) #if defined(HAS_QT_DBUS) && defined(Q_OS_LINUX)
IFileDialogService *fileDialogService; IFileDialogService *fileDialogService;
if (QDBusConnection::sessionBus().isConnected()) { if (QDBusConnection::sessionBus().isConnected()) {
fileDialogService = new PortalFileDialogService(&bookController); fileDialogService = new PortalFileDialogService(nullptr);
} else { } else {
fileDialogService = new NativeFileDialogService(&bookController); fileDialogService = new NativeFileDialogService(nullptr);
} }
#else #else
IFileDialogService *fileDialogService = new NativeFileDialogService(&bookController); IFileDialogService *fileDialogService = new NativeFileDialogService(nullptr);
#endif #endif
bookController.setFileDialogService(fileDialogService);
if (const QStringList args = QCoreApplication::arguments(); args.size() > 1) { Book book(*fileDialogService, bookPositions);
const QString& filePath = args.at(1); ReadingModel readingModel(bookPositions);
if (QFileInfo::exists(filePath))
appState.setLastFilePath(filePath);
}
// --- QML engine ---
QQmlApplicationEngine engine; QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("isDebugBuild", engine.rootContext()->setContextProperty(QStringLiteral("isDebugBuild"),
#ifdef QT_DEBUG #ifdef QT_DEBUG
true true
#else #else
false false
#endif #endif
); );
bookController.setImageProviderRegistrar([&engine](const QString &scheme, IImageProvider *provider) { engine.rootContext()->setContextProperty(QStringLiteral("book"), &book);
engine.removeImageProvider(scheme); engine.rootContext()->setContextProperty(QStringLiteral("readingModel"), &readingModel);
engine.addImageProvider(scheme, provider); 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); // Track the current image provider so setContentWidth can reach it
engine.rootContext()->setContextProperty(QStringLiteral("readingModel"), &readingModel); IImageProvider *currentImageProvider = nullptr;
engine.rootContext()->setContextProperty(QStringLiteral("appState"), &appState);
// 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<QVariantMap> 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")); const QUrl url(QStringLiteral("qrc:/Asteria/Main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed, QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed,
@@ -148,16 +251,5 @@ int main(int argc, char *argv[])
qInfo("Rendering API: %s", apiName); 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(); return QApplication::exec();
} }
+59 -49
View File
@@ -17,42 +17,44 @@ ApplicationWindow {
source: "qrc:/Asteria/src/assets/MaterialIconsOutlined-Regular.otf" source: "qrc:/Asteria/src/assets/MaterialIconsOutlined-Regular.otf"
} }
property bool sidebarOpen: appState.sidebarOpen property bool sidebarOpen: uiState.sidebarOpen
onSidebarOpenChanged: appState.sidebarOpen = sidebarOpen onSidebarOpenChanged: uiState.sidebarOpen = sidebarOpen
property string currentPage: "starter" property string currentPage: "starter"
property bool barsVisible: true 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: { Component.onCompleted: {
width = appState.windowWidth width = uiState.windowWidth
height = appState.windowHeight height = uiState.windowHeight
if (appState.windowX >= 0 && appState.windowY >= 0) { if (uiState.windowX >= 0 && uiState.windowY >= 0) {
x = appState.windowX x = uiState.windowX
y = appState.windowY y = uiState.windowY
}
// Initialize theme from AppState
if (appState.themeName !== "") {
ThemeManager.currentThemeName = appState.themeName
} }
if (uiState.themeName !== "")
ThemeManager.currentThemeName = uiState.themeName
} }
Connections { Connections {
target: appState target: uiState
function onThemeNameChanged() { function onThemeNameChanged() {
ThemeManager.currentThemeName = appState.themeName ThemeManager.currentThemeName = uiState.themeName
} }
} }
Timer { Timer {
id: geometrySaveTimer id: geometrySaveTimer
interval: 500 interval: 250
repeat: false repeat: false
onTriggered: { onTriggered: {
appState.windowWidth = window.width uiState.windowWidth = window.width
appState.windowHeight = window.height uiState.windowHeight = window.height
appState.windowX = window.x uiState.windowX = window.x
appState.windowY = window.y uiState.windowY = window.y
} }
} }
@@ -73,10 +75,10 @@ ApplicationWindow {
window.currentPage = page window.currentPage = page
} }
onOpenFile: { onOpenFile: {
bookController.browseAndOpen() book.browseAndOpen()
} }
onCloseBook: { onCloseBook: {
bookController.closeBook() book.close()
} }
} }
@@ -121,7 +123,7 @@ ApplicationWindow {
BusyIndicator { BusyIndicator {
anchors.centerIn: parent anchors.centerIn: parent
running: bookController.loading || readingModel.measuring running: book.loading || readingModel.measuring
visible: running visible: running
z: 10 z: 10
} }
@@ -141,6 +143,32 @@ ApplicationWindow {
z: 3000 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 // Global keyboard shortcuts - work regardless of focus
Shortcut { Shortcut {
sequence: "F" sequence: "F"
@@ -188,7 +216,6 @@ ApplicationWindow {
} }
} }
} }
// Fallback shortcuts using alternative key names
Shortcut { Shortcut {
sequence: "Prior" sequence: "Prior"
context: Qt.ApplicationShortcut 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 { Timer {
running: true running: true
repeat: false repeat: false
@@ -250,7 +252,15 @@ ApplicationWindow {
onTriggered: { onTriggered: {
window.opacity = 1 window.opacity = 1
readerPage.pageView.updateContentWidth() 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
}
} }
} }
} }
+3 -14
View File
@@ -14,27 +14,16 @@ QtObject {
function setDarkTheme() { function setDarkTheme() {
currentThemeName = "dark" currentThemeName = "dark"
if (appState) { uiState.themeName = "dark"
appState.themeName = "dark"
}
} }
function setLightTheme() { function setLightTheme() {
currentThemeName = "light" currentThemeName = "light"
if (appState) { uiState.themeName = "light"
appState.themeName = "light"
}
} }
function toggleTheme() { function toggleTheme() {
currentThemeName = currentThemeName === "dark" ? "light" : "dark" currentThemeName = currentThemeName === "dark" ? "light" : "dark"
if (appState) { uiState.themeName = currentThemeName
appState.themeName = currentThemeName
}
}
onCurrentThemeNameChanged: {
// This ensures UI updates when theme changes
// The actual theme switching happens through the currentTheme property
} }
} }
+3 -3
View File
@@ -5,7 +5,7 @@ import Asteria
Rectangle { Rectangle {
id: overlay id: overlay
color: ThemeManager.currentTheme.overlayBg color: ThemeManager.currentTheme.overlayBg
visible: bookController.errorMessage !== "" visible: book.errorMessage !== ""
MouseArea { MouseArea {
anchors.fill: parent anchors.fill: parent
@@ -33,7 +33,7 @@ Rectangle {
Text { Text {
width: parent.width width: parent.width
text: bookController.errorMessage text: book.errorMessage
font.pixelSize: 15 font.pixelSize: 15
color: ThemeManager.currentTheme.readingText color: ThemeManager.currentTheme.readingText
horizontalAlignment: Text.AlignHCenter horizontalAlignment: Text.AlignHCenter
@@ -55,7 +55,7 @@ Rectangle {
radius: 4 radius: 4
color: parent.hovered ? Qt.lighter(ThemeManager.currentTheme.primaryAccent, 1.15) : ThemeManager.currentTheme.primaryAccent color: parent.hovered ? Qt.lighter(ThemeManager.currentTheme.primaryAccent, 1.15) : ThemeManager.currentTheme.primaryAccent
} }
onClicked: bookController.clearError() onClicked: book.clearError()
} }
} }
} }
+5 -5
View File
@@ -18,7 +18,7 @@ Rectangle {
id: prevBtn id: prevBtn
anchors.verticalCenter: parent.verticalCenter anchors.verticalCenter: parent.verticalCenter
x: parent.width * 0.5 - chapterText.implicitWidth / 2 - width - 4 x: parent.width * 0.5 - chapterText.implicitWidth / 2 - width - 4
visible: bookController.hasBook && readingModel.hasChapters visible: book.hasBook && readingModel.hasChapters
enabled: readingModel.currentChapter > 0 enabled: readingModel.currentChapter > 0
flat: true flat: true
padding: 0 padding: 0
@@ -40,7 +40,7 @@ Rectangle {
id: chapterText id: chapterText
anchors.verticalCenter: parent.verticalCenter anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter anchors.horizontalCenter: parent.horizontalCenter
text: bookController.hasBook && readingModel.hasChapters text: book.hasBook && readingModel.hasChapters
? "Chapter " + (readingModel.currentChapter + 1) + " / " + readingModel.totalChapters ? "Chapter " + (readingModel.currentChapter + 1) + " / " + readingModel.totalChapters
: "" : ""
font.pixelSize: 11 font.pixelSize: 11
@@ -53,7 +53,7 @@ Rectangle {
id: nextBtn id: nextBtn
anchors.verticalCenter: parent.verticalCenter anchors.verticalCenter: parent.verticalCenter
x: parent.width * 0.5 + chapterText.implicitWidth / 2 + 4 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 enabled: readingModel.currentChapter < readingModel.totalChapters - 1
flat: true flat: true
padding: 0 padding: 0
@@ -75,8 +75,8 @@ Rectangle {
anchors.right: parent.right anchors.right: parent.right
anchors.rightMargin: 16 anchors.rightMargin: 16
anchors.verticalCenter: parent.verticalCenter anchors.verticalCenter: parent.verticalCenter
visible: bookController.hasBook visible: book.hasBook
text: bookController.hasBook text: book.hasBook
? readingModel.currentPage + "/" + readingModel.totalPages ? readingModel.currentPage + "/" + readingModel.totalPages
: "" : ""
font.pixelSize: 11 font.pixelSize: 11
+1 -1
View File
@@ -39,7 +39,7 @@ Rectangle {
text: { text: {
switch (header.currentPage) { switch (header.currentPage) {
case "settings": return "Settings" case "settings": return "Settings"
case "reader": return bookController.bookTitle || "" case "reader": return book.title || ""
default: return "" default: return ""
} }
} }
+15 -30
View File
@@ -34,25 +34,21 @@ Rectangle {
} }
function handleScrollUp() { function handleScrollUp() {
// Scroll up by approximately 2-3 lines var lineHeight = readingPreferences.fontSize * readingPreferences.lineSpacing;
var lineHeight = appState.fontSize * appState.lineSpacing; var scrollAmount = lineHeight * 3;
var scrollAmount = lineHeight * 3; // ~2-3 lines
var targetY = Math.max(0, chunkListView.contentY - scrollAmount); var targetY = Math.max(0, chunkListView.contentY - scrollAmount);
animateScrollTo(targetY); animateScrollTo(targetY);
} }
function handleScrollDown() { function handleScrollDown() {
// Scroll down by approximately 2-3 lines var lineHeight = readingPreferences.fontSize * readingPreferences.lineSpacing;
var lineHeight = appState.fontSize * appState.lineSpacing; var scrollAmount = lineHeight * 3;
var scrollAmount = lineHeight * 3; // ~2-3 lines
var maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height); var maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height);
var targetY = Math.min(maxY, chunkListView.contentY + scrollAmount); var targetY = Math.min(maxY, chunkListView.contentY + scrollAmount);
animateScrollTo(targetY); animateScrollTo(targetY);
} }
// Helper function to animate scrolling
function animateScrollTo(targetY) { function animateScrollTo(targetY) {
// Stop any ongoing animation
scrollAnimation.stop(); scrollAnimation.stop();
scrollAnimation.to = targetY; scrollAnimation.to = targetY;
scrollAnimation.start(); scrollAnimation.start();
@@ -64,7 +60,7 @@ Rectangle {
} }
function updateContentWidth() { function updateContentWidth() {
bookController.setContentWidth(chunkListView.width - 18 - 2 * appState.horizontalMargin) book.setContentWidth(chunkListView.width - 18 - 2 * readingPreferences.horizontalMargin)
} }
Component.onCompleted: updateContentWidth() Component.onCompleted: updateContentWidth()
@@ -87,8 +83,8 @@ Rectangle {
id: chunkListView id: chunkListView
anchors.fill: parent anchors.fill: parent
model: contentReady ? readingModel : null model: contentReady ? readingModel : null
header: Item { height: appState.verticalMargin } header: Item { height: readingPreferences.verticalMargin }
footer: Item { height: appState.verticalMargin } footer: Item { height: readingPreferences.verticalMargin }
cacheBuffer: 20 cacheBuffer: 20
clip: true clip: true
@@ -108,16 +104,15 @@ Rectangle {
Text { Text {
id: contentText id: contentText
width: parent.width - 18 // subtract scrollbar width: parent.width - 18 // subtract scrollbar
leftPadding: appState.horizontalMargin leftPadding: readingPreferences.horizontalMargin
rightPadding: appState.horizontalMargin rightPadding: readingPreferences.horizontalMargin
wrapMode: Text.WrapAtWordBoundaryOrAnywhere wrapMode: Text.WrapAtWordBoundaryOrAnywhere
textFormat: Text.RichText textFormat: Text.RichText
font.pixelSize: appState.fontSize font.pixelSize: readingPreferences.fontSize
lineHeight: appState.lineSpacing lineHeight: readingPreferences.lineSpacing
color: ThemeManager.currentTheme.readingText color: ThemeManager.currentTheme.readingText
text: model.content text: model.content
visible: model.content !== "" visible: model.content !== ""
// TODO: remove when we're good with measurer
onImplicitHeightChanged: { onImplicitHeightChanged: {
if (model.pixelHeight > 0 && implicitHeight > 0) { if (model.pixelHeight > 0 && implicitHeight > 0) {
var diff = model.pixelHeight - implicitHeight var diff = model.pixelHeight - implicitHeight
@@ -177,21 +172,21 @@ Rectangle {
interval: 300 interval: 300
repeat: false repeat: false
onTriggered: { onTriggered: {
if (bookController.hasBook && contentReady && restoreReady) { if (book.hasBook && contentReady && restoreReady) {
var topIdx = chunkListView.indexAt(0, chunkListView.contentY) var topIdx = chunkListView.indexAt(0, chunkListView.contentY)
if (topIdx < 0) topIdx = 0 if (topIdx < 0) topIdx = 0
var topItem = chunkListView.itemAtIndex(topIdx) var topItem = chunkListView.itemAtIndex(topIdx)
var intraOffset = topItem ? (chunkListView.contentY - topItem.y) : 0 var intraOffset = topItem ? (chunkListView.contentY - topItem.y) : 0
readingModel.setScrollInfo(topIdx, chunkListView.visibleArea.yPosition) readingModel.setScrollInfo(topIdx, chunkListView.visibleArea.yPosition)
appState.saveBookPosition(bookController.currentFilePath, topIdx, intraOffset) book.saveCurrentPosition(topIdx, intraOffset)
} }
} }
} }
Connections { Connections {
target: bookController target: book
function onLoadingChanged() { function onLoadingChanged() {
if (bookController.loading) if (book.loading)
contentReady = false 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 { Timer {
id: restoreTimer id: restoreTimer
interval: 1 interval: 1
+3 -3
View File
@@ -73,7 +73,7 @@ Rectangle {
} }
SideBarButton { SideBarButton {
visible: bookController.hasBook visible: book.hasBook
iconText: "\ue5cd" iconText: "\ue5cd"
title: "Close Book" title: "Close Book"
onClicked: sidebar.closeBook() onClicked: sidebar.closeBook()
@@ -114,7 +114,7 @@ Rectangle {
// TOC section — shown when the current book has a table of contents // TOC section — shown when the current book has a table of contents
Item { Item {
visible: bookController.hasBook && bookController.toc.length > 0 visible: book.hasBook && book.toc.length > 0
anchors.top: navColumn.bottom anchors.top: navColumn.bottom
anchors.bottom: parent.bottom anchors.bottom: parent.bottom
width: parent.width width: parent.width
@@ -145,7 +145,7 @@ Rectangle {
anchors.bottom: parent.bottom anchors.bottom: parent.bottom
width: parent.width width: parent.width
clip: true clip: true
model: bookController.toc model: book.toc
delegate: Rectangle { delegate: Rectangle {
width: ListView.view.width width: ListView.view.width
+5 -5
View File
@@ -6,7 +6,7 @@ Rectangle {
color: ThemeManager.currentTheme.backgroundDefault color: ThemeManager.currentTheme.backgroundDefault
Text { Text {
visible: appState.libraryModel.count === 0 visible: libraryModel.count === 0
anchors.centerIn: parent anchors.centerIn: parent
text: "No books read yet.\nOpen a book to start your library." text: "No books read yet.\nOpen a book to start your library."
horizontalAlignment: Text.AlignHCenter horizontalAlignment: Text.AlignHCenter
@@ -16,12 +16,12 @@ Rectangle {
} }
ListView { ListView {
visible: appState.libraryModel.count > 0 visible: libraryModel.count > 0
anchors.fill: parent anchors.fill: parent
anchors.margins: 16 anchors.margins: 16
spacing: 8 spacing: 8
clip: true clip: true
model: appState.libraryModel model: libraryModel
delegate: Rectangle { delegate: Rectangle {
id: bookRow id: bookRow
@@ -92,14 +92,14 @@ Rectangle {
verticalAlignment: Text.AlignVCenter verticalAlignment: Text.AlignVCenter
} }
background: Item {} background: Item {}
onClicked: appState.removeLibraryBook(filePath) onClicked: libraryModel.removeBook(filePath)
} }
} }
MouseArea { MouseArea {
anchors.fill: parent anchors.fill: parent
z: -1 z: -1
onClicked: bookController.openBookFromPath(filePath) onClicked: book.openFromPath(filePath)
} }
} }
} }
+12 -12
View File
@@ -56,7 +56,7 @@ Rectangle {
Timer { Timer {
id: hmTimer id: hmTimer
interval: 250 interval: 250
onTriggered: appState.horizontalMargin = hmSlider.value onTriggered: readingPreferences.horizontalMargin = hmSlider.value
} }
Slider { Slider {
@@ -65,9 +65,9 @@ Rectangle {
from: 0 from: 0
to: 120 to: 120
stepSize: 1 stepSize: 1
value: appState.horizontalMargin value: readingPreferences.horizontalMargin
onValueChanged: { onValueChanged: {
if (value !== appState.horizontalMargin) if (value !== readingPreferences.horizontalMargin)
hmTimer.restart() hmTimer.restart()
} }
} }
@@ -103,7 +103,7 @@ Rectangle {
Timer { Timer {
id: vmTimer id: vmTimer
interval: 250 interval: 250
onTriggered: appState.verticalMargin = vmSlider.value onTriggered: readingPreferences.verticalMargin = vmSlider.value
} }
Slider { Slider {
@@ -112,9 +112,9 @@ Rectangle {
from: 0 from: 0
to: 80 to: 80
stepSize: 1 stepSize: 1
value: appState.verticalMargin value: readingPreferences.verticalMargin
onValueChanged: { onValueChanged: {
if (value !== appState.verticalMargin) if (value !== readingPreferences.verticalMargin)
vmTimer.restart() vmTimer.restart()
} }
} }
@@ -150,7 +150,7 @@ Rectangle {
Timer { Timer {
id: fsTimer id: fsTimer
interval: 250 interval: 250
onTriggered: appState.fontSize = fsSlider.value onTriggered: readingPreferences.fontSize = fsSlider.value
} }
Slider { Slider {
@@ -159,9 +159,9 @@ Rectangle {
from: 10 from: 10
to: 32 to: 32
stepSize: 1 stepSize: 1
value: appState.fontSize value: readingPreferences.fontSize
onValueChanged: { onValueChanged: {
if (value !== appState.fontSize) if (value !== readingPreferences.fontSize)
fsTimer.restart() fsTimer.restart()
} }
} }
@@ -197,7 +197,7 @@ Rectangle {
Timer { Timer {
id: lsTimer id: lsTimer
interval: 250 interval: 250
onTriggered: appState.lineSpacing = lsSlider.value onTriggered: readingPreferences.lineSpacing = lsSlider.value
} }
Slider { Slider {
@@ -206,9 +206,9 @@ Rectangle {
from: 0.5 from: 0.5
to: 3.0 to: 3.0
stepSize: 0.1 stepSize: 0.1
value: appState.lineSpacing value: readingPreferences.lineSpacing
onValueChanged: { onValueChanged: {
if (Math.abs(value - appState.lineSpacing) > 0.01) if (Math.abs(value - readingPreferences.lineSpacing) > 0.01)
lsTimer.restart() lsTimer.restart()
} }
} }
+88 -403
View File
@@ -1,437 +1,122 @@
#include <QtTest> #include <QtTest>
#include <QSignalSpy> #include <QDir>
#include <QSettings> #include <QSettings>
#include <QTemporaryFile>
#include "backend/AppState.h" #include "backend/AppState.h"
#include "backend/LibraryModel.h"
class AppStateTest : public QObject { class AppStateTest : public QObject {
Q_OBJECT Q_OBJECT
private slots: private slots:
void initTestCase() void freshSettingsWriteVersion()
{ {
QCoreApplication::setOrganizationName(QStringLiteral("AsteriaTest")); QTemporaryFile f;
QCoreApplication::setApplicationName(QStringLiteral("AppStateTest")); 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();
{
QSettings s(f.fileName(), QSettings::IniFormat);
s.setValue(QStringLiteral("version"), 0);
s.setValue(QStringLiteral("someOldKey"), QStringLiteral("data"));
} }
void saveAndRestoreLastFilePath() QSettings s2(f.fileName(), QSettings::IniFormat);
{ AppState state(s2);
{ QVERIFY(!s2.contains(QStringLiteral("someOldKey")));
AppState state; QCOMPARE(s2.value(QStringLiteral("version")).toInt(), AppState::SETTINGS_VERSION);
state.setLastFilePath(QStringLiteral("/books/test.epub"));
state.save();
}
AppState state2;
state2.restore();
QCOMPARE(state2.lastFilePath(), QStringLiteral("/books/test.epub"));
} }
void saveAndRestoreMargins() void saveAndLoadSection()
{ {
{ QTemporaryFile f;
AppState state; f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-sec-XXXXXX.ini"));
state.setHorizontalMargin(64); f.open(); f.close();
state.setVerticalMargin(24); QSettings s(f.fileName(), QSettings::IniFormat);
state.save(); AppState state(s);
}
AppState state2; QVariantMap data;
state2.restore(); data[QStringLiteral("foo")] = 42;
QCOMPARE(state2.horizontalMargin(), 64); data[QStringLiteral("bar")] = QStringLiteral("hello");
QCOMPARE(state2.verticalMargin(), 24); 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()
{ {
{ QTemporaryFile f;
AppState state; f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-over-XXXXXX.ini"));
state.setFontSize(22); f.open(); f.close();
state.save(); QSettings s(f.fileName(), QSettings::IniFormat);
} AppState state(s);
AppState state2;
state2.restore(); state.saveSection(QStringLiteral("g"), {{QStringLiteral("old"), 1}});
QCOMPARE(state2.fontSize(), 22); 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()
{ {
{ QTemporaryFile f;
AppState state; f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-arr-XXXXXX.ini"));
state.setLineSpacing(2.0); f.open(); f.close();
state.save(); QSettings s(f.fileName(), QSettings::IniFormat);
} AppState state(s);
AppState state2;
state2.restore(); QList<QVariantMap> items;
QCOMPARE(state2.lineSpacing(), 2.0); 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()
{ {
{ QTemporaryFile f;
AppState state; f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-earr-XXXXXX.ini"));
state.setWindowWidth(1280); f.open(); f.close();
state.setWindowHeight(800); QSettings s(f.fileName(), QSettings::IniFormat);
state.setWindowX(100); AppState state(s);
state.setWindowY(50);
state.save(); QCOMPARE(state.loadArray(QStringLiteral("nonexistent")).size(), 0);
}
AppState state2;
state2.restore();
QCOMPARE(state2.windowWidth(), 1280);
QCOMPARE(state2.windowHeight(), 800);
QCOMPARE(state2.windowX(), 100);
QCOMPARE(state2.windowY(), 50);
} }
void restoreWithNoSavedData() void nestedSectionKey()
{ {
AppState state; QTemporaryFile f;
state.restore(); f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-nest-XXXXXX.ini"));
QVERIFY(state.lastFilePath().isEmpty()); f.open(); f.close();
QCOMPARE(state.horizontalMargin(), 32); QSettings s(f.fileName(), QSettings::IniFormat);
QCOMPARE(state.verticalMargin(), 8); AppState state(s);
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);
}
void settersEmitSignals() const QString nestedSection = QStringLiteral("saved-progress/abc123");
{ state.saveSection(nestedSection, {{QStringLiteral("chunkIndex"), 5}});
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);
state.setLastFilePath(QStringLiteral("/foo.txt")); const QVariantMap loaded = state.loadSection(nestedSection);
state.setHorizontalMargin(64); QCOMPARE(loaded.value(QStringLiteral("chunkIndex")).toInt(), 5);
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<QAbstractListModel*>(state.libraryModel());
QVERIFY(model->rowCount() == 0);
}
void addLibraryBookAddsEntry()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.0);
auto* model = qobject_cast<QAbstractListModel*>(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<QAbstractListModel*>(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<QAbstractListModel*>(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<QAbstractListModel*>(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<QAbstractListModel*>(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<QAbstractListModel*>(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<QAbstractListModel*>(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<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
}
void libraryBooksChangedSignalOnAdd()
{
AppState state;
auto* model = qobject_cast<QAbstractListModel*>(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<QAbstractListModel*>(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<QAbstractListModel*>(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"));
} }
}; };
+51 -27
View File
@@ -1,7 +1,12 @@
#include <QtTest> #include <QtTest>
#include <QDir>
#include <QSettings>
#include <QSignalSpy> #include <QSignalSpy>
#include <QTemporaryFile>
#include "backend/AppState.h"
#include "backend/ReadingModel.h" #include "backend/ReadingModel.h"
#include "backend/FormatReader.h" #include "backend/FormatReader.h"
#include "backend/state/BookPositionStore.h"
// A fake reader that has 3 chapters, 2 chunks each → 6 total chunks // A fake reader that has 3 chapters, 2 chunks each → 6 total chunks
class FakeReader : public FormatReader { class FakeReader : public FormatReader {
@@ -25,6 +30,7 @@ public:
QString author() override { return QStringLiteral("Fake Author"); } QString author() override { return QStringLiteral("Fake Author"); }
QString filePath() override { return QStringLiteral("/fake/path.txt"); } QString filePath() override { return QStringLiteral("/fake/path.txt"); }
QString coverImagePath() override { return {}; } QString coverImagePath() override { return {}; }
QByteArray contentHash() override { return QByteArray("fakehash"); }
bool loadMetadata(const QString &) override { return true; } bool loadMetadata(const QString &) override { return true; }
}; };
@@ -39,16 +45,34 @@ public:
QString author() override { return {}; } QString author() override { return {}; }
QString filePath() override { return QStringLiteral("/fake/single.txt"); } QString filePath() override { return QStringLiteral("/fake/single.txt"); }
QString coverImagePath() override { return {}; } QString coverImagePath() override { return {}; }
QByteArray contentHash() override { return QByteArray("singlehash"); }
bool loadMetadata(const QString &) override { return true; } bool loadMetadata(const QString &) override { return true; }
}; };
class ReadingModelTest : public QObject { class ReadingModelTest : public QObject {
Q_OBJECT 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: private slots:
void initialState() void initialState()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
QCOMPARE(model.totalChapters(), 0); QCOMPARE(model.totalChapters(), 0);
QCOMPARE(model.progress(), 0.0); QCOMPARE(model.progress(), 0.0);
QVERIFY(model.chapterTitle().isEmpty()); QVERIFY(model.chapterTitle().isEmpty());
@@ -57,7 +81,7 @@ private slots:
void setReaderLoadsAllChapters() void setReaderLoadsAllChapters()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
@@ -70,7 +94,7 @@ private slots:
void chunkContentAcrossChapters() void chunkContentAcrossChapters()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
@@ -93,7 +117,7 @@ private slots:
void dataInvalidForOutOfRange() void dataInvalidForOutOfRange()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
@@ -103,7 +127,7 @@ private slots:
void currentChapterDerivedFromScroll() void currentChapterDerivedFromScroll()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
@@ -126,7 +150,7 @@ private slots:
void chapterChangedSignalOnScroll() void chapterChangedSignalOnScroll()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
@@ -147,7 +171,7 @@ private slots:
void goToChapterEmitsScrollSignal() void goToChapterEmitsScrollSignal()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
@@ -164,7 +188,7 @@ private slots:
void goToChapterOutOfRangeNoSignal() void goToChapterOutOfRangeNoSignal()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
@@ -176,7 +200,7 @@ private slots:
void nextChapterEmitsScrollSignal() void nextChapterEmitsScrollSignal()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
@@ -189,7 +213,7 @@ private slots:
void nextChapterAtEndNoSignal() void nextChapterAtEndNoSignal()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
model.setScrollInfo(4, 0.0); // chapter 2 model.setScrollInfo(4, 0.0); // chapter 2
@@ -201,7 +225,7 @@ private slots:
void previousChapterEmitsScrollSignal() void previousChapterEmitsScrollSignal()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
model.setScrollInfo(4, 0.0); // chapter 2 model.setScrollInfo(4, 0.0); // chapter 2
@@ -214,7 +238,7 @@ private slots:
void previousChapterAtStartNoSignal() void previousChapterAtStartNoSignal()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
@@ -225,7 +249,7 @@ private slots:
void setReaderNull() void setReaderNull()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
model.setReader(nullptr); model.setReader(nullptr);
@@ -238,7 +262,7 @@ private slots:
void roleNamesContainsContent() void roleNamesContainsContent()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
QHash<int, QByteArray> roles = model.roleNames(); QHash<int, QByteArray> roles = model.roleNames();
QVERIFY(roles.contains(ReadingModel::ContentRole)); QVERIFY(roles.contains(ReadingModel::ContentRole));
QCOMPARE(roles.value(ReadingModel::ContentRole), QByteArray("content")); QCOMPARE(roles.value(ReadingModel::ContentRole), QByteArray("content"));
@@ -246,14 +270,14 @@ private slots:
void initialPageState() void initialPageState()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
QCOMPARE(model.currentPage(), 0); QCOMPARE(model.currentPage(), 0);
QCOMPARE(model.totalPages(), 0); QCOMPARE(model.totalPages(), 0);
} }
void setScrollInfoUpdatesCurrentPage() void setScrollInfoUpdatesCurrentPage()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
@@ -270,7 +294,7 @@ private slots:
void hasChaptersFalseForSingleChapter() void hasChaptersFalseForSingleChapter()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
SingleChapterReader reader; SingleChapterReader reader;
model.setReader(&reader); model.setReader(&reader);
@@ -279,7 +303,7 @@ private slots:
void hasChaptersTrueForMultipleChapters() void hasChaptersTrueForMultipleChapters()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
model.setReader(&reader); model.setReader(&reader);
@@ -288,7 +312,7 @@ private slots:
void hasChaptersFalseInitially() void hasChaptersFalseInitially()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
QVERIFY(!model.hasChapters()); QVERIFY(!model.hasChapters());
} }
@@ -297,7 +321,7 @@ private slots:
void coverImagePrependedToChunks() void coverImagePrependedToChunks()
{ {
FakeReader reader; FakeReader reader;
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
model.setCoverImageUrl("image://epub/OEBPS/cover.jpg"); model.setCoverImageUrl("image://epub/OEBPS/cover.jpg");
model.setReader(&reader); model.setReader(&reader);
@@ -313,7 +337,7 @@ private slots:
void coverImageNotAddedWhenUrlEmpty() void coverImageNotAddedWhenUrlEmpty()
{ {
FakeReader reader; FakeReader reader;
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
model.setReader(&reader); model.setReader(&reader);
model.setCoverImageUrl(""); model.setCoverImageUrl("");
@@ -324,7 +348,7 @@ private slots:
void chapterNavigationSkipsCoverImage() void chapterNavigationSkipsCoverImage()
{ {
FakeReader reader; FakeReader reader;
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
model.setCoverImageUrl("image://epub/OEBPS/cover.jpg"); model.setCoverImageUrl("image://epub/OEBPS/cover.jpg");
model.setReader(&reader); model.setReader(&reader);
@@ -343,7 +367,7 @@ private slots:
void coverImageSetAfterReaderReloadsChunks() void coverImageSetAfterReaderReloadsChunks()
{ {
FakeReader reader; FakeReader reader;
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
model.setReader(&reader); model.setReader(&reader);
QCOMPARE(model.rowCount(QModelIndex()), 6); // no cover yet QCOMPARE(model.rowCount(QModelIndex()), 6); // no cover yet
@@ -363,7 +387,7 @@ private slots:
void clearCoverImageUrlRemovesCover() void clearCoverImageUrlRemovesCover()
{ {
FakeReader reader; FakeReader reader;
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
model.setCoverImageUrl(QStringLiteral("image://epub/OEBPS/cover.jpg")); model.setCoverImageUrl(QStringLiteral("image://epub/OEBPS/cover.jpg"));
model.setReader(&reader); model.setReader(&reader);
QCOMPARE(model.rowCount(QModelIndex()), 7); // 1 cover + 6 QCOMPARE(model.rowCount(QModelIndex()), 7); // 1 cover + 6
@@ -378,7 +402,7 @@ private slots:
void roleNamesHasNewRoles() void roleNamesHasNewRoles()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
auto roles = model.roleNames(); auto roles = model.roleNames();
QVERIFY(roles.contains(ReadingModel::PixelHeightRole)); QVERIFY(roles.contains(ReadingModel::PixelHeightRole));
QVERIFY(roles.contains(ReadingModel::ChapterRole)); QVERIFY(roles.contains(ReadingModel::ChapterRole));
@@ -388,13 +412,13 @@ private slots:
void totalPixelHeightInitiallyZero() void totalPixelHeightInitiallyZero()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
QCOMPARE(model.totalPixelHeight(), 0.0); QCOMPARE(model.totalPixelHeight(), 0.0);
} }
void totalPixelHeightResetOnReaderSet() void totalPixelHeightResetOnReaderSet()
{ {
ReadingModel model; Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader; FakeReader reader;
QSignalSpy spy(&model, &ReadingModel::totalPixelHeightChanged); QSignalSpy spy(&model, &ReadingModel::totalPixelHeightChanged);
+221
View File
@@ -0,0 +1,221 @@
#include <QtTest>
#include <QDir>
#include <QSettings>
#include <QSignalSpy>
#include <QTemporaryFile>
#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"
+98
View File
@@ -0,0 +1,98 @@
#include <QtTest>
#include <QByteArray>
#include <QDir>
#include <QSettings>
#include <QTemporaryFile>
#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"
+81
View File
@@ -0,0 +1,81 @@
#include <QtTest>
#include <QDir>
#include <QFile>
#include <QSettings>
#include <QTemporaryFile>
#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"
+109
View File
@@ -0,0 +1,109 @@
#include <QtTest>
#include <QDir>
#include <QFile>
#include <QSettings>
#include <QTemporaryFile>
#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"