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
+1599 -981

No files matched your search

+35 -257
View File
@@ -1,279 +1,57 @@
#include "AppState.h"
#include "LibraryBookModel.h"
#include "LibraryModel.h"
#include <QtConcurrent/QtConcurrent>
static constexpr int SETTINGS_VERSION = 3;
static QString bookSettingsKey(const QString &filePath)
AppState::AppState(QSettings &settings)
: m_settings(settings)
{
QByteArray hash = QCryptographicHash::hash(filePath.toUtf8(), QCryptographicHash::Md5).toHex();
return QStringLiteral("bookmarks/") + QString::fromLatin1(hash);
if (m_settings.value(QStringLiteral("version"), 0).toInt() != SETTINGS_VERSION) {
m_settings.clear();
m_settings.setValue(QStringLiteral("version"), SETTINGS_VERSION);
}
}
AppState::AppState(QObject *parent)
: QObject(parent)
QVariantMap AppState::loadSection(const QString &section) const
{
m_libraryModel = new LibraryModel(this);
}
QString AppState::lastFilePath() const { return m_lastFilePath; }
void AppState::setLastFilePath(const QString &path)
{
if (m_lastFilePath == path)
return;
m_lastFilePath = path;
emit lastFilePathChanged();
}
int AppState::horizontalMargin() const { return m_horizontalMargin; }
void AppState::setHorizontalMargin(int margin)
{
if (m_horizontalMargin == margin)
return;
m_horizontalMargin = margin;
emit horizontalMarginChanged();
}
int AppState::verticalMargin() const { return m_verticalMargin; }
void AppState::setVerticalMargin(int margin)
{
if (m_verticalMargin == margin)
return;
m_verticalMargin = margin;
emit verticalMarginChanged();
}
int AppState::fontSize() const { return m_fontSize; }
void AppState::setFontSize(int size)
{
if (m_fontSize == size)
return;
m_fontSize = size;
emit fontSizeChanged();
}
qreal AppState::lineSpacing() const { return m_lineSpacing; }
void AppState::setLineSpacing(qreal spacing)
{
if (qFuzzyCompare(m_lineSpacing, spacing))
return;
m_lineSpacing = spacing;
emit lineSpacingChanged();
}
int AppState::windowWidth() const { return m_windowWidth; }
void AppState::setWindowWidth(int width)
{
if (m_windowWidth == width)
return;
m_windowWidth = width;
emit windowWidthChanged();
}
int AppState::windowHeight() const { return m_windowHeight; }
void AppState::setWindowHeight(int height)
{
if (m_windowHeight == height)
return;
m_windowHeight = height;
emit windowHeightChanged();
}
int AppState::windowX() const { return m_windowX; }
void AppState::setWindowX(int x)
{
if (m_windowX == x)
return;
m_windowX = x;
emit windowXChanged();
}
int AppState::windowY() const { return m_windowY; }
void AppState::setWindowY(int y)
{
if (m_windowY == y)
return;
m_windowY = y;
emit windowYChanged();
}
QUrl AppState::lastFileUrl() const
{
return QUrl::fromLocalFile(m_lastFilePath);
}
void AppState::saveBookPosition(const QString &filePath, int chunkIndex, int intraChunkOffset)
{
qInfo() << "Saving book position: chunk" << chunkIndex << "offset" << intraChunkOffset;
QSettings s;
QString key = bookSettingsKey(filePath);
s.setValue(key + QStringLiteral("/chunkIndex"), chunkIndex);
s.setValue(key + QStringLiteral("/intraChunkOffset"), intraChunkOffset);
}
QVariantMap AppState::loadBookPosition(const QString &filePath)
{
QSettings s;
QString key = bookSettingsKey(filePath);
QVariantMap result;
result[QStringLiteral("chunkIndex")] = s.value(key + QStringLiteral("/chunkIndex"), 0).toInt();
result[QStringLiteral("intraChunkOffset")] = s.value(key + QStringLiteral("/intraChunkOffset"), 0.0).toInt();
m_settings.beginGroup(section);
const QStringList keys = m_settings.childKeys();
for (const QString &key : keys)
result[key] = m_settings.value(key);
m_settings.endGroup();
return result;
}
QString AppState::lastPage() const { return m_lastPage; }
void AppState::setLastPage(const QString &page)
void AppState::saveSection(const QString &section, const QVariantMap &data) const
{
if (m_lastPage == page)
return;
m_lastPage = page;
emit lastPageChanged();
m_settings.beginGroup(section);
m_settings.remove(QStringLiteral("")); // clear existing group
for (auto it = data.cbegin(); it != data.cend(); ++it)
m_settings.setValue(it.key(), it.value());
m_settings.endGroup();
}
bool AppState::sidebarOpen() const { return m_sidebarOpen; }
void AppState::setSidebarOpen(bool open)
QList<QVariantMap> AppState::loadArray(const QString &section) const
{
if (m_sidebarOpen == open)
return;
m_sidebarOpen = open;
emit sidebarOpenChanged();
}
QString AppState::themeName() const { return m_themeName; }
void AppState::setThemeName(const QString &themeName)
{
if (m_themeName == themeName)
return;
m_themeName = themeName;
emit themeNameChanged();
}
void AppState::addOrUpdateLibraryBook(const QString &filePath, double progress)
{
QString lastOpened = QDateTime::currentDateTime().toString(Qt::ISODate);
// Sentinel: progress < 0 means "preserve existing progress"
double resolvedProgress = progress;
if (progress < 0.0) {
LibraryBookModel* existing = m_libraryModel->findBook(filePath);
resolvedProgress = existing ? existing->progress() : 0.0;
}
m_libraryModel->addOrUpdateBook(filePath, resolvedProgress, lastOpened);
saveLibraryBooks();
}
void AppState::removeLibraryBook(const QString &filePath)
{
m_libraryModel->removeBook(filePath);
saveLibraryBooks();
}
QObject* AppState::libraryModel() const
{
// Add null check to prevent crashes during initialization
if (!m_libraryModel) {
qWarning() << "LibraryModel accessed before initialization";
return nullptr;
}
return m_libraryModel;
}
void AppState::loadLibraryBooks()
{
QSettings s;
int size = s.beginReadArray(QStringLiteral("library"));
for (int i = 0; i < size; i++) {
QList<QVariantMap> result;
QSettings &s = const_cast<QSettings &>(m_settings);
const int size = s.beginReadArray(section);
for (int i = 0; i < size; ++i) {
s.setArrayIndex(i);
QString filePath = s.value(QStringLiteral("filePath")).toString();
if (filePath.isEmpty())
continue;
bool progressOk;
double progress = s.value(QStringLiteral("progress"), 0.0).toDouble(&progressOk);
if (!progressOk)
progress = 0.0;
progress = qBound(0.0, progress, 1.0);
QString lastOpened = s.value(QStringLiteral("lastOpened")).toString();
m_libraryModel->addOrUpdateBook(filePath, progress, lastOpened);
QVariantMap entry;
for (const QString &key : s.childKeys())
entry[key] = s.value(key);
result.append(entry);
}
s.endArray();
return result;
}
void AppState::saveLibraryBooks()
void AppState::saveArray(const QString &section, const QList<QVariantMap> &items) const
{
QSettings s;
QList<LibraryBookModel*> books = m_libraryModel->books();
s.beginWriteArray(QStringLiteral("library"), books.size());
for (int i = 0; i < books.size(); i++) {
s.setArrayIndex(i);
LibraryBookModel* book = books[i];
s.setValue(QStringLiteral("filePath"), book->filePath());
s.setValue(QStringLiteral("progress"), book->progress());
s.setValue(QStringLiteral("lastOpened"), book->lastOpened());
m_settings.beginWriteArray(section, items.size());
for (int i = 0; i < items.size(); ++i) {
m_settings.setArrayIndex(i);
for (auto it = items[i].cbegin(); it != items[i].cend(); ++it)
m_settings.setValue(it.key(), it.value());
}
s.endArray();
}
void AppState::save()
{
QSettings s;
s.setValue(QStringLiteral("version"), SETTINGS_VERSION);
s.setValue(QStringLiteral("session/lastFilePath"), m_lastFilePath);
s.setValue(QStringLiteral("session/lastPage"), m_lastPage);
s.setValue(QStringLiteral("session/sidebarOpen"), m_sidebarOpen);
s.setValue(QStringLiteral("preferences/horizontalMargin"), m_horizontalMargin);
s.setValue(QStringLiteral("preferences/verticalMargin"), m_verticalMargin);
s.setValue(QStringLiteral("preferences/fontSize"), m_fontSize);
s.setValue(QStringLiteral("preferences/lineSpacing"), m_lineSpacing);
s.setValue(QStringLiteral("preferences/themeName"), m_themeName);
s.setValue(QStringLiteral("window/width"), m_windowWidth);
s.setValue(QStringLiteral("window/height"), m_windowHeight);
s.setValue(QStringLiteral("window/x"), m_windowX);
s.setValue(QStringLiteral("window/y"), m_windowY);
saveLibraryBooks();
qInfo() << "filename:" << s.fileName();
}
void AppState::restore()
{
QSettings s;
// Wipe and start fresh if settings are from a different/incompatible format version
if (s.value(QStringLiteral("version"), 0).toInt() != SETTINGS_VERSION) {
s.clear();
emit stateRestored();
return;
}
m_lastFilePath = s.value(QStringLiteral("session/lastFilePath"), QString()).toString();
m_lastPage = s.value(QStringLiteral("session/lastPage"), QStringLiteral("starter")).toString();
m_sidebarOpen = s.value(QStringLiteral("session/sidebarOpen"), false).toBool();
m_horizontalMargin = qMax(0, s.value(QStringLiteral("preferences/horizontalMargin"), 32).toInt());
m_verticalMargin = qMax(0, s.value(QStringLiteral("preferences/verticalMargin"), 8).toInt());
m_fontSize = qBound(8, s.value(QStringLiteral("preferences/fontSize"), 16).toInt(), 72);
m_lineSpacing = qMax(0.1, s.value(QStringLiteral("preferences/lineSpacing"), 1.6).toDouble());
m_themeName = s.value(QStringLiteral("preferences/themeName"), QStringLiteral("dark")).toString();
m_windowWidth = s.value(QStringLiteral("window/width"), 1024).toInt();
m_windowHeight = s.value(QStringLiteral("window/height"), 768).toInt();
m_windowX = s.value(QStringLiteral("window/x"), -1).toInt();
m_windowY = s.value(QStringLiteral("window/y"), -1).toInt();
loadLibraryBooks();
emit stateRestored();
m_settings.endArray();
}
+17 -98
View File
@@ -1,114 +1,33 @@
#ifndef APPSTATE_H
#define APPSTATE_H
#include <QObject>
#include <QString>
#include <QUrl>
#include <QSettings>
#include <QVariantMap>
class LibraryBookModel;
class LibraryModel;
class AppState : public QObject {
Q_OBJECT
Q_PROPERTY(QString lastFilePath READ lastFilePath WRITE setLastFilePath NOTIFY lastFilePathChanged)
Q_PROPERTY(int horizontalMargin READ horizontalMargin WRITE setHorizontalMargin NOTIFY horizontalMarginChanged)
Q_PROPERTY(int verticalMargin READ verticalMargin WRITE setVerticalMargin NOTIFY verticalMarginChanged)
Q_PROPERTY(int fontSize READ fontSize WRITE setFontSize NOTIFY fontSizeChanged)
Q_PROPERTY(qreal lineSpacing READ lineSpacing WRITE setLineSpacing NOTIFY lineSpacingChanged)
Q_PROPERTY(int windowWidth READ windowWidth WRITE setWindowWidth NOTIFY windowWidthChanged)
Q_PROPERTY(int windowHeight READ windowHeight WRITE setWindowHeight NOTIFY windowHeightChanged)
Q_PROPERTY(int windowX READ windowX WRITE setWindowX NOTIFY windowXChanged)
Q_PROPERTY(int windowY READ windowY WRITE setWindowY NOTIFY windowYChanged)
Q_PROPERTY(QString lastPage READ lastPage WRITE setLastPage NOTIFY lastPageChanged)
Q_PROPERTY(bool sidebarOpen READ sidebarOpen WRITE setSidebarOpen NOTIFY sidebarOpenChanged)
Q_PROPERTY(QString themeName READ themeName WRITE setThemeName NOTIFY themeNameChanged)
Q_PROPERTY(QObject* libraryModel READ libraryModel CONSTANT)
// AppState is a pure persistence service. It wraps QSettings and provides an atomic
// section-based API. It holds no domain state of its own. QML never sees this object.
class AppState {
public:
explicit AppState(QObject *parent = nullptr);
static constexpr int SETTINGS_VERSION = 4;
QString themeName() const;
void setThemeName(const QString &themeName);
// Constructs AppState. If the stored version does not match SETTINGS_VERSION,
// all settings are cleared (clean migration).
explicit AppState(QSettings &settings);
QString lastFilePath() const;
void setLastFilePath(const QString &path);
// Load all key/value pairs from the named QSettings group.
QVariantMap loadSection(const QString &section) const;
int horizontalMargin() const;
void setHorizontalMargin(int margin);
// Atomically replace the named QSettings group with the given data.
void saveSection(const QString &section, const QVariantMap &data) const;
int verticalMargin() const;
void setVerticalMargin(int margin);
// Load an ordered array (e.g., library books) from the named QSettings array.
QList<QVariantMap> loadArray(const QString &section) const;
int fontSize() const;
void setFontSize(int size);
qreal lineSpacing() const;
void setLineSpacing(qreal spacing);
int windowWidth() const;
void setWindowWidth(int width);
int windowHeight() const;
void setWindowHeight(int height);
int windowX() const;
void setWindowX(int x);
int windowY() const;
void setWindowY(int y);
Q_INVOKABLE QUrl lastFileUrl() const;
Q_INVOKABLE static void saveBookPosition(const QString &filePath, int chunkIndex, int intraChunkOffset);
Q_INVOKABLE static QVariantMap loadBookPosition(const QString &filePath);
QString lastPage() const;
void setLastPage(const QString &page);
bool sidebarOpen() const;
void setSidebarOpen(bool open);
Q_INVOKABLE void addOrUpdateLibraryBook(const QString &filePath, double progress);
Q_INVOKABLE void removeLibraryBook(const QString &filePath);
QObject* libraryModel() const;
Q_INVOKABLE void save();
Q_INVOKABLE void restore();
signals:
void lastFilePathChanged();
void horizontalMarginChanged();
void verticalMarginChanged();
void fontSizeChanged();
void lineSpacingChanged();
void stateRestored();
void windowWidthChanged();
void windowHeightChanged();
void windowXChanged();
void windowYChanged();
void lastPageChanged();
void sidebarOpenChanged();
void themeNameChanged();
// Atomically replace the named QSettings array.
void saveArray(const QString &section, const QList<QVariantMap> &items) const;
private:
void loadLibraryBooks();
void saveLibraryBooks();
QString m_lastFilePath;
int m_horizontalMargin = 32;
int m_verticalMargin = 8;
int m_fontSize = 16;
qreal m_lineSpacing = 1.6;
int m_windowWidth = 1024;
int m_windowHeight = 768;
int m_windowX = -1;
int m_windowY = -1;
LibraryModel* m_libraryModel;
QString m_lastPage = QStringLiteral("starter");
bool m_sidebarOpen = false;
QString m_themeName = QStringLiteral("dark");
QSettings &m_settings;
};
#endif // APPSTATE_H
+4
View File
@@ -1,6 +1,7 @@
#ifndef FORMATREADER_H
#define FORMATREADER_H
#include <QByteArray>
#include <QString>
#include <QList>
@@ -30,6 +31,9 @@ public:
virtual QString title() = 0;
virtual QString author() = 0;
virtual QString coverImagePath() = 0;
// MD5 of file contents, computed once during open(). Used as a stable key for
// per-book state (bookmarks, etc.) that survives file renames.
virtual QByteArray contentHash() = 0;
};
+31
View File
@@ -1,5 +1,6 @@
#include "LibraryModel.h"
#include "LibraryBookModel.h"
#include <QDateTime>
LibraryModel::LibraryModel(QObject *parent)
: QAbstractListModel(parent)
@@ -157,6 +158,36 @@ void LibraryModel::clear()
emit countChanged();
}
void LibraryModel::addOrUpdateBook(const QString &filePath, double progress)
{
// Sentinel: progress < 0 means "preserve the existing progress value"
double resolvedProgress = progress;
if (progress < 0.0) {
LibraryBookModel *existing = findBook(filePath);
resolvedProgress = existing ? existing->progress() : 0.0;
}
addOrUpdateBook(filePath, resolvedProgress,
QDateTime::currentDateTime().toString(Qt::ISODate));
}
QString LibraryModel::filePath(int index) const
{
if (index < 0 || index >= m_books.size()) return {};
return m_books.at(index)->filePath();
}
double LibraryModel::progress(int index) const
{
if (index < 0 || index >= m_books.size()) return 0.0;
return m_books.at(index)->progress();
}
QString LibraryModel::lastOpened(int index) const
{
if (index < 0 || index >= m_books.size()) return {};
return m_books.at(index)->lastOpened();
}
QList<LibraryBookModel*> LibraryModel::books() const
{
return m_books;
+7
View File
@@ -36,10 +36,17 @@ public:
// Methods to manage books
Q_INVOKABLE void addOrUpdateBook(const QString &filePath, double progress, const QString &lastOpened);
// Convenience overload: sentinel progress < 0 preserves the existing progress value.
Q_INVOKABLE void addOrUpdateBook(const QString &filePath, double progress);
Q_INVOKABLE void removeBook(const QString &filePath);
Q_INVOKABLE LibraryBookModel* findBook(const QString &filePath) const;
Q_INVOKABLE void clear();
// Indexed accessors for persistence (e.g., main.cpp's aboutToQuit loop).
QString filePath(int index) const;
double progress(int index) const;
QString lastOpened(int index) const;
// Access to books for saving/loading
QList<LibraryBookModel*> books() const;
+7 -7
View File
@@ -7,9 +7,11 @@
#include <cmath>
#include <QtConcurrent>
#include "AppState.h"
ReadingModel::ReadingModel(QObject *parent) : QAbstractListModel(parent) {}
ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent)
: QAbstractListModel(parent)
, m_positions(positions)
{
}
ReadingModel::~ReadingModel()
{
@@ -126,10 +128,8 @@ void ReadingModel::runMeasurement(const QStringList &htmls, const bool isNew)
{PixelHeightRole});
if (isNew) {
QVariantMap map = AppState::loadBookPosition(m_reader->filePath());
int savedChunk = map.value(QStringLiteral("chunkIndex"), 0).toInt();
qreal savedIntra = map.value(QStringLiteral("intraChunkOffset"), 0).toInt();
restoreReady(savedChunk, savedIntra);
const auto pos = m_positions.load(m_reader->contentHash());
emit restoreReady(pos.chunkIndex, pos.intraOffset);
}
}, Qt::QueuedConnection);
});
+3 -1
View File
@@ -6,6 +6,7 @@
#include <QString>
#include <memory>
#include "IImageLoader.h"
#include "state/BookPositionStore.h"
class FormatReader;
@@ -35,7 +36,7 @@ public:
ChapterRole = Qt::UserRole + 3,
};
explicit ReadingModel(QObject *parent = nullptr);
explicit ReadingModel(BookPositionStore &positions, QObject *parent = nullptr);
~ReadingModel() override;
int rowCount(const QModelIndex &parent) const override;
@@ -106,6 +107,7 @@ private:
int m_fontSize = 0;
qreal m_lineSpacing = 0;
BookPositionStore &m_positions;
std::unique_ptr<IImageLoader> m_imageLoader;
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 <QCryptographicHash>
#include <QDir>
#include <QDomDocument>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include <QUrl>
@@ -35,6 +37,14 @@ bool EpubReader::open(const QString &filePath)
m_spineHrefs.clear();
m_spineRawContent.clear();
m_toc.clear();
m_contentHash.clear();
// Compute content hash from raw file bytes before ZIP parsing
{
QFile f(filePath);
if (f.open(QIODevice::ReadOnly))
m_contentHash = QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5);
}
unzFile zf = unzOpen(filePath.toUtf8().constData());
if (!zf) {
@@ -390,6 +400,11 @@ QString EpubReader::filePath()
return m_filePath;
}
QByteArray EpubReader::contentHash()
{
return m_contentHash;
}
Chapter EpubReader::loadChapter(int index)
{
if (index < 0 || index >= m_spineRawContent.size())
+2
View File
@@ -18,9 +18,11 @@ public:
QString title() override;
QString author() override;
QString coverImagePath() override;
QByteArray contentHash() override;
private:
QString m_filePath;
QByteArray m_contentHash;
QString m_title;
QString m_author;
QString m_error;
+8
View File
@@ -1,5 +1,6 @@
#include "TxtReader.h"
#include <QCryptographicHash>
#include <QFileInfo>
#include <QRegularExpression>
#include <QTextStream>
@@ -110,6 +111,8 @@ bool TxtReader::open(const QString &filePath)
QByteArray raw = file.readAll();
file.close();
m_contentHash = QCryptographicHash::hash(raw, QCryptographicHash::Md5);
uchardet_t ud = uchardet_new();
if (uchardet_handle_data(ud, raw.constData(), raw.size()) == 0) {
uchardet_data_end(ud);
@@ -206,3 +209,8 @@ QString TxtReader::coverImagePath()
{
return {};
}
QByteArray TxtReader::contentHash()
{
return m_contentHash;
}
+2
View File
@@ -15,6 +15,7 @@ public:
QString title() override;
QString author() override;
QString coverImagePath() override;
QByteArray contentHash() override;
private:
QString m_content;
@@ -22,6 +23,7 @@ private:
QString m_title;
QString m_author;
QString m_error;
QByteArray m_contentHash;
};
#endif // TXTREADER_H
+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 <QDateTime>
#include <QFileInfo>
#include <QSize>
#include <QQmlApplicationEngine>
@@ -8,12 +9,17 @@
#include <QSettings>
#include <QSGRendererInterface>
#include "backend/BookController.h"
#include "backend/IImageProvider.h"
#include "backend/ReadingModel.h"
#include "backend/AppState.h"
#include "backend/IImageProvider.h"
#include "backend/ImageLoaderFactory.h"
#include "backend/ImageProviderFactory.h"
#include "backend/LibraryModel.h"
#include "backend/ReadingModel.h"
#include "backend/NativeFileDialogService.h"
#include "backend/book/Book.h"
#include "backend/state/BookPositionStore.h"
#include "backend/state/ReadingPreferences.h"
#include "backend/state/UiState.h"
#ifdef HAS_QT_DBUS
#include <QDBusConnection>
@@ -80,50 +86,147 @@ int main(int argc, char *argv[])
QQuickStyle::setStyle(QStringLiteral("Basic"));
ReadingModel readingModel;
// --- Object graph (construction order = dependency order) ---
QSettings settings;
AppState appState(settings);
BookController bookController;
bookController.setReadingModel(&readingModel);
ReadingPreferences readingPreferences(appState);
UiState uiState(appState);
BookPositionStore bookPositions(appState);
AppState appState;
appState.restore();
bookController.setAppState(&appState);
LibraryModel libraryModel;
for (const QVariantMap &entry : appState.loadArray(QStringLiteral("library"))) {
const QString fp = entry.value(QStringLiteral("filePath")).toString();
if (fp.isEmpty()) continue;
double progress = entry.value(QStringLiteral("progress"), 0.0).toDouble();
progress = qBound(0.0, progress, 1.0);
const QString lo = entry.value(QStringLiteral("lastOpened")).toString();
libraryModel.addOrUpdateBook(fp, progress, lo);
}
// Command-line override: treat first argument as the file to open on startup
if (const QStringList args = QCoreApplication::arguments(); args.size() > 1) {
const QString &argPath = args.at(1);
if (QFileInfo::exists(argPath))
uiState.setLastFilePath(argPath);
}
#if defined(HAS_QT_DBUS) && defined(Q_OS_LINUX)
IFileDialogService *fileDialogService;
if (QDBusConnection::sessionBus().isConnected()) {
fileDialogService = new PortalFileDialogService(&bookController);
fileDialogService = new PortalFileDialogService(nullptr);
} else {
fileDialogService = new NativeFileDialogService(&bookController);
fileDialogService = new NativeFileDialogService(nullptr);
}
#else
IFileDialogService *fileDialogService = new NativeFileDialogService(&bookController);
IFileDialogService *fileDialogService = new NativeFileDialogService(nullptr);
#endif
bookController.setFileDialogService(fileDialogService);
if (const QStringList args = QCoreApplication::arguments(); args.size() > 1) {
const QString& filePath = args.at(1);
if (QFileInfo::exists(filePath))
appState.setLastFilePath(filePath);
}
Book book(*fileDialogService, bookPositions);
ReadingModel readingModel(bookPositions);
// --- QML engine ---
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("isDebugBuild",
#ifdef QT_DEBUG
engine.rootContext()->setContextProperty(QStringLiteral("isDebugBuild"),
#ifdef QT_DEBUG
true
#else
#else
false
#endif
#endif
);
bookController.setImageProviderRegistrar([&engine](const QString &scheme, IImageProvider *provider) {
engine.removeImageProvider(scheme);
engine.addImageProvider(scheme, provider);
engine.rootContext()->setContextProperty(QStringLiteral("book"), &book);
engine.rootContext()->setContextProperty(QStringLiteral("readingModel"), &readingModel);
engine.rootContext()->setContextProperty(QStringLiteral("readingPreferences"), &readingPreferences);
engine.rootContext()->setContextProperty(QStringLiteral("uiState"), &uiState);
engine.rootContext()->setContextProperty(QStringLiteral("libraryModel"), &libraryModel);
// --- Cross-class signal wiring ---
// Typography changes → re-push font params into ReadingModel
QObject::connect(&readingPreferences, &ReadingPreferences::fontSizeChanged, [&]{
readingModel.setFontParams(readingPreferences.fontSize(), readingPreferences.lineSpacing());
});
QObject::connect(&readingPreferences, &ReadingPreferences::lineSpacingChanged, [&]{
readingModel.setFontParams(readingPreferences.fontSize(), readingPreferences.lineSpacing());
});
engine.rootContext()->setContextProperty(QStringLiteral("bookController"), &bookController);
engine.rootContext()->setContextProperty(QStringLiteral("readingModel"), &readingModel);
engine.rootContext()->setContextProperty(QStringLiteral("appState"), &appState);
// Track the current image provider so setContentWidth can reach it
IImageProvider *currentImageProvider = nullptr;
// Before a new book open: snapshot the outgoing book's progress into the library.
// Scroll position is handled by PageView's scroll tracker via book.saveCurrentPosition().
QObject::connect(&book, &Book::willOpenNewBook, [&]{
if (book.hasBook())
libraryModel.addOrUpdateBook(book.filePath(), readingModel.progress());
});
// After the new reader is installed: wire up image provider + ReadingModel
QObject::connect(&book, &Book::bookChanged, [&]{
currentImageProvider = nullptr;
if (!book.hasBook()) {
readingModel.setReader(nullptr);
return;
}
FormatReader *reader = book.reader();
const QString filePath = reader->filePath();
IImageProvider *provider = ImageProviderFactory::create(filePath);
if (provider) {
engine.removeImageProvider(provider->scheme());
engine.addImageProvider(provider->scheme(), provider);
provider->setFilePath(filePath);
currentImageProvider = provider;
if (!reader->coverImagePath().isEmpty())
book.setCoverImageUrl(provider->coverImageUrl(reader->coverImagePath()));
}
readingModel.setFontParams(readingPreferences.fontSize(), readingPreferences.lineSpacing());
readingModel.setImageLoader(ImageLoaderFactory::create(filePath));
readingModel.setCoverImageUrl(book.coverImageUrl());
readingModel.setReader(reader);
readingModel.measure(true);
uiState.setLastFilePath(filePath);
libraryModel.addOrUpdateBook(filePath, -1.0);
});
// Propagate content-width changes to image provider + reading model.
// Called from Book::setContentWidth which is triggered by QML's PageView.
QObject::connect(&book, &Book::contentWidthChanged, [&](int width){
if (currentImageProvider)
currentImageProvider->setDisplayWidth(width);
readingModel.setContentWidth(width);
});
// Quit: flush everything to persistent storage.
// Scroll position was last saved by PageView's scroll tracker; we save library progress here.
QObject::connect(&app, &QCoreApplication::aboutToQuit, [&]{
if (book.hasBook()) {
libraryModel.addOrUpdateBook(book.filePath(), readingModel.progress());
uiState.setLastFilePath(book.filePath());
} else {
uiState.setLastFilePath(QString());
}
readingPreferences.save();
uiState.save();
QList<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"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed,
@@ -148,16 +251,5 @@ int main(int argc, char *argv[])
qInfo("Rendering API: %s", apiName);
}
QObject::connect(&app, &QCoreApplication::aboutToQuit, [&bookController, &appState, &readingModel]() {
if (bookController.hasBook()) {
appState.setLastFilePath(bookController.currentFilePath());
appState.addOrUpdateLibraryBook(bookController.currentFilePath(),
readingModel.progress());
} else {
appState.setLastFilePath(QString());
}
appState.save();
});
return QApplication::exec();
}
+62 -52
View File
@@ -17,49 +17,51 @@ ApplicationWindow {
source: "qrc:/Asteria/src/assets/MaterialIconsOutlined-Regular.otf"
}
property bool sidebarOpen: appState.sidebarOpen
onSidebarOpenChanged: appState.sidebarOpen = sidebarOpen
property bool sidebarOpen: uiState.sidebarOpen
onSidebarOpenChanged: uiState.sidebarOpen = sidebarOpen
property string currentPage: "starter"
property bool barsVisible: true
// Set to true on the first book open at startup so we restore the last page.
property bool _startupRestore: false
onCurrentPageChanged: appState.lastPage = currentPage
onCurrentPageChanged: uiState.lastPage = currentPage
Component.onCompleted: {
width = appState.windowWidth
height = appState.windowHeight
if (appState.windowX >= 0 && appState.windowY >= 0) {
x = appState.windowX
y = appState.windowY
}
// Initialize theme from AppState
if (appState.themeName !== "") {
ThemeManager.currentThemeName = appState.themeName
width = uiState.windowWidth
height = uiState.windowHeight
if (uiState.windowX >= 0 && uiState.windowY >= 0) {
x = uiState.windowX
y = uiState.windowY
}
if (uiState.themeName !== "")
ThemeManager.currentThemeName = uiState.themeName
}
Connections {
target: appState
target: uiState
function onThemeNameChanged() {
ThemeManager.currentThemeName = appState.themeName
ThemeManager.currentThemeName = uiState.themeName
}
}
Timer {
id: geometrySaveTimer
interval: 500
interval: 250
repeat: false
onTriggered: {
appState.windowWidth = window.width
appState.windowHeight = window.height
appState.windowX = window.x
appState.windowY = window.y
uiState.windowWidth = window.width
uiState.windowHeight = window.height
uiState.windowX = window.x
uiState.windowY = window.y
}
}
onWidthChanged: geometrySaveTimer.restart()
onWidthChanged: geometrySaveTimer.restart()
onHeightChanged: geometrySaveTimer.restart()
onXChanged: geometrySaveTimer.restart()
onYChanged: geometrySaveTimer.restart()
onXChanged: geometrySaveTimer.restart()
onYChanged: geometrySaveTimer.restart()
Row {
anchors.fill: parent
@@ -73,10 +75,10 @@ ApplicationWindow {
window.currentPage = page
}
onOpenFile: {
bookController.browseAndOpen()
book.browseAndOpen()
}
onCloseBook: {
bookController.closeBook()
book.close()
}
}
@@ -121,7 +123,7 @@ ApplicationWindow {
BusyIndicator {
anchors.centerIn: parent
running: bookController.loading || readingModel.measuring
running: book.loading || readingModel.measuring
visible: running
z: 10
}
@@ -141,6 +143,32 @@ ApplicationWindow {
z: 3000
}
// Navigate once measurement (and position restoration) is done
Connections {
target: readingModel
function onRestoreReady(chunkIndex, intraOffset) {
if (!book.hasBook) return
if (window._startupRestore) {
window._startupRestore = false
var savedPage = uiState.lastPage
if (savedPage === "library" || savedPage === "settings")
window.currentPage = savedPage
else
window.currentPage = "reader"
} else {
window.currentPage = "reader"
}
}
}
Connections {
target: book
function onBookChanged() {
if (!book.hasBook && window.currentPage === "reader")
window.currentPage = "starter"
}
}
// Global keyboard shortcuts - work regardless of focus
Shortcut {
sequence: "F"
@@ -188,7 +216,6 @@ ApplicationWindow {
}
}
}
// Fallback shortcuts using alternative key names
Shortcut {
sequence: "Prior"
context: Qt.ApplicationShortcut
@@ -217,31 +244,6 @@ ApplicationWindow {
}
}
Connections {
target: bookController
function onBookReady() {
if (bookController.startupRestore) {
var savedPage = appState.lastPage
if (savedPage === "library" || savedPage === "settings")
window.currentPage = savedPage
else
window.currentPage = "reader"
} else {
window.currentPage = "reader"
}
}
function onBookChanged() {
if (!bookController.hasBook && window.currentPage === "reader")
window.currentPage = "starter"
}
function onNoSavedBook() {
window.sidebarOpen = true
var savedPage = appState.lastPage
if (savedPage === "library" || savedPage === "settings")
window.currentPage = savedPage
}
}
Timer {
running: true
repeat: false
@@ -250,7 +252,15 @@ ApplicationWindow {
onTriggered: {
window.opacity = 1
readerPage.pageView.updateContentWidth()
bookController.uiReady()
if (uiState.lastFilePath !== "") {
window._startupRestore = true
book.openFromPath(uiState.lastFilePath)
} else {
var savedPage = uiState.lastPage
if (savedPage === "library" || savedPage === "settings")
window.currentPage = savedPage
window.sidebarOpen = true
}
}
}
}
+5 -16
View File
@@ -14,27 +14,16 @@ QtObject {
function setDarkTheme() {
currentThemeName = "dark"
if (appState) {
appState.themeName = "dark"
}
uiState.themeName = "dark"
}
function setLightTheme() {
currentThemeName = "light"
if (appState) {
appState.themeName = "light"
}
uiState.themeName = "light"
}
function toggleTheme() {
currentThemeName = currentThemeName === "dark" ? "light" : "dark"
if (appState) {
appState.themeName = currentThemeName
}
}
onCurrentThemeNameChanged: {
// This ensures UI updates when theme changes
// The actual theme switching happens through the currentTheme property
uiState.themeName = currentThemeName
}
}
+3 -3
View File
@@ -5,7 +5,7 @@ import Asteria
Rectangle {
id: overlay
color: ThemeManager.currentTheme.overlayBg
visible: bookController.errorMessage !== ""
visible: book.errorMessage !== ""
MouseArea {
anchors.fill: parent
@@ -33,7 +33,7 @@ Rectangle {
Text {
width: parent.width
text: bookController.errorMessage
text: book.errorMessage
font.pixelSize: 15
color: ThemeManager.currentTheme.readingText
horizontalAlignment: Text.AlignHCenter
@@ -55,7 +55,7 @@ Rectangle {
radius: 4
color: parent.hovered ? Qt.lighter(ThemeManager.currentTheme.primaryAccent, 1.15) : ThemeManager.currentTheme.primaryAccent
}
onClicked: bookController.clearError()
onClicked: book.clearError()
}
}
}
+5 -5
View File
@@ -18,7 +18,7 @@ Rectangle {
id: prevBtn
anchors.verticalCenter: parent.verticalCenter
x: parent.width * 0.5 - chapterText.implicitWidth / 2 - width - 4
visible: bookController.hasBook && readingModel.hasChapters
visible: book.hasBook && readingModel.hasChapters
enabled: readingModel.currentChapter > 0
flat: true
padding: 0
@@ -40,7 +40,7 @@ Rectangle {
id: chapterText
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
text: bookController.hasBook && readingModel.hasChapters
text: book.hasBook && readingModel.hasChapters
? "Chapter " + (readingModel.currentChapter + 1) + " / " + readingModel.totalChapters
: ""
font.pixelSize: 11
@@ -53,7 +53,7 @@ Rectangle {
id: nextBtn
anchors.verticalCenter: parent.verticalCenter
x: parent.width * 0.5 + chapterText.implicitWidth / 2 + 4
visible: bookController.hasBook && readingModel.hasChapters
visible: book.hasBook && readingModel.hasChapters
enabled: readingModel.currentChapter < readingModel.totalChapters - 1
flat: true
padding: 0
@@ -75,8 +75,8 @@ Rectangle {
anchors.right: parent.right
anchors.rightMargin: 16
anchors.verticalCenter: parent.verticalCenter
visible: bookController.hasBook
text: bookController.hasBook
visible: book.hasBook
text: book.hasBook
? readingModel.currentPage + "/" + readingModel.totalPages
: ""
font.pixelSize: 11
+1 -1
View File
@@ -39,7 +39,7 @@ Rectangle {
text: {
switch (header.currentPage) {
case "settings": return "Settings"
case "reader": return bookController.bookTitle || ""
case "reader": return book.title || ""
default: return ""
}
}
+15 -30
View File
@@ -34,25 +34,21 @@ Rectangle {
}
function handleScrollUp() {
// Scroll up by approximately 2-3 lines
var lineHeight = appState.fontSize * appState.lineSpacing;
var scrollAmount = lineHeight * 3; // ~2-3 lines
var lineHeight = readingPreferences.fontSize * readingPreferences.lineSpacing;
var scrollAmount = lineHeight * 3;
var targetY = Math.max(0, chunkListView.contentY - scrollAmount);
animateScrollTo(targetY);
}
function handleScrollDown() {
// Scroll down by approximately 2-3 lines
var lineHeight = appState.fontSize * appState.lineSpacing;
var scrollAmount = lineHeight * 3; // ~2-3 lines
var lineHeight = readingPreferences.fontSize * readingPreferences.lineSpacing;
var scrollAmount = lineHeight * 3;
var maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height);
var targetY = Math.min(maxY, chunkListView.contentY + scrollAmount);
animateScrollTo(targetY);
}
// Helper function to animate scrolling
function animateScrollTo(targetY) {
// Stop any ongoing animation
scrollAnimation.stop();
scrollAnimation.to = targetY;
scrollAnimation.start();
@@ -64,7 +60,7 @@ Rectangle {
}
function updateContentWidth() {
bookController.setContentWidth(chunkListView.width - 18 - 2 * appState.horizontalMargin)
book.setContentWidth(chunkListView.width - 18 - 2 * readingPreferences.horizontalMargin)
}
Component.onCompleted: updateContentWidth()
@@ -87,8 +83,8 @@ Rectangle {
id: chunkListView
anchors.fill: parent
model: contentReady ? readingModel : null
header: Item { height: appState.verticalMargin }
footer: Item { height: appState.verticalMargin }
header: Item { height: readingPreferences.verticalMargin }
footer: Item { height: readingPreferences.verticalMargin }
cacheBuffer: 20
clip: true
@@ -108,16 +104,15 @@ Rectangle {
Text {
id: contentText
width: parent.width - 18 // subtract scrollbar
leftPadding: appState.horizontalMargin
rightPadding: appState.horizontalMargin
leftPadding: readingPreferences.horizontalMargin
rightPadding: readingPreferences.horizontalMargin
wrapMode: Text.WrapAtWordBoundaryOrAnywhere
textFormat: Text.RichText
font.pixelSize: appState.fontSize
lineHeight: appState.lineSpacing
font.pixelSize: readingPreferences.fontSize
lineHeight: readingPreferences.lineSpacing
color: ThemeManager.currentTheme.readingText
text: model.content
visible: model.content !== ""
// TODO: remove when we're good with measurer
onImplicitHeightChanged: {
if (model.pixelHeight > 0 && implicitHeight > 0) {
var diff = model.pixelHeight - implicitHeight
@@ -177,21 +172,21 @@ Rectangle {
interval: 300
repeat: false
onTriggered: {
if (bookController.hasBook && contentReady && restoreReady) {
if (book.hasBook && contentReady && restoreReady) {
var topIdx = chunkListView.indexAt(0, chunkListView.contentY)
if (topIdx < 0) topIdx = 0
var topItem = chunkListView.itemAtIndex(topIdx)
var intraOffset = topItem ? (chunkListView.contentY - topItem.y) : 0
readingModel.setScrollInfo(topIdx, chunkListView.visibleArea.yPosition)
appState.saveBookPosition(bookController.currentFilePath, topIdx, intraOffset)
book.saveCurrentPosition(topIdx, intraOffset)
}
}
}
Connections {
target: bookController
target: book
function onLoadingChanged() {
if (bookController.loading)
if (book.loading)
contentReady = false
}
}
@@ -209,16 +204,6 @@ Rectangle {
}
}
Connections {
target: appState
function onFontSizeChanged() {
readingModel.setFontParams(appState.fontSize, appState.lineSpacing)
}
function onLineSpacingChanged() {
readingModel.setFontParams(appState.fontSize, appState.lineSpacing)
}
}
Timer {
id: restoreTimer
interval: 1
+3 -3
View File
@@ -73,7 +73,7 @@ Rectangle {
}
SideBarButton {
visible: bookController.hasBook
visible: book.hasBook
iconText: "\ue5cd"
title: "Close Book"
onClicked: sidebar.closeBook()
@@ -114,7 +114,7 @@ Rectangle {
// TOC section — shown when the current book has a table of contents
Item {
visible: bookController.hasBook && bookController.toc.length > 0
visible: book.hasBook && book.toc.length > 0
anchors.top: navColumn.bottom
anchors.bottom: parent.bottom
width: parent.width
@@ -145,7 +145,7 @@ Rectangle {
anchors.bottom: parent.bottom
width: parent.width
clip: true
model: bookController.toc
model: book.toc
delegate: Rectangle {
width: ListView.view.width
+5 -5
View File
@@ -6,7 +6,7 @@ Rectangle {
color: ThemeManager.currentTheme.backgroundDefault
Text {
visible: appState.libraryModel.count === 0
visible: libraryModel.count === 0
anchors.centerIn: parent
text: "No books read yet.\nOpen a book to start your library."
horizontalAlignment: Text.AlignHCenter
@@ -16,12 +16,12 @@ Rectangle {
}
ListView {
visible: appState.libraryModel.count > 0
visible: libraryModel.count > 0
anchors.fill: parent
anchors.margins: 16
spacing: 8
clip: true
model: appState.libraryModel
model: libraryModel
delegate: Rectangle {
id: bookRow
@@ -92,14 +92,14 @@ Rectangle {
verticalAlignment: Text.AlignVCenter
}
background: Item {}
onClicked: appState.removeLibraryBook(filePath)
onClicked: libraryModel.removeBook(filePath)
}
}
MouseArea {
anchors.fill: parent
z: -1
onClicked: bookController.openBookFromPath(filePath)
onClicked: book.openFromPath(filePath)
}
}
}
+12 -12
View File
@@ -56,7 +56,7 @@ Rectangle {
Timer {
id: hmTimer
interval: 250
onTriggered: appState.horizontalMargin = hmSlider.value
onTriggered: readingPreferences.horizontalMargin = hmSlider.value
}
Slider {
@@ -65,9 +65,9 @@ Rectangle {
from: 0
to: 120
stepSize: 1
value: appState.horizontalMargin
value: readingPreferences.horizontalMargin
onValueChanged: {
if (value !== appState.horizontalMargin)
if (value !== readingPreferences.horizontalMargin)
hmTimer.restart()
}
}
@@ -103,7 +103,7 @@ Rectangle {
Timer {
id: vmTimer
interval: 250
onTriggered: appState.verticalMargin = vmSlider.value
onTriggered: readingPreferences.verticalMargin = vmSlider.value
}
Slider {
@@ -112,9 +112,9 @@ Rectangle {
from: 0
to: 80
stepSize: 1
value: appState.verticalMargin
value: readingPreferences.verticalMargin
onValueChanged: {
if (value !== appState.verticalMargin)
if (value !== readingPreferences.verticalMargin)
vmTimer.restart()
}
}
@@ -150,7 +150,7 @@ Rectangle {
Timer {
id: fsTimer
interval: 250
onTriggered: appState.fontSize = fsSlider.value
onTriggered: readingPreferences.fontSize = fsSlider.value
}
Slider {
@@ -159,9 +159,9 @@ Rectangle {
from: 10
to: 32
stepSize: 1
value: appState.fontSize
value: readingPreferences.fontSize
onValueChanged: {
if (value !== appState.fontSize)
if (value !== readingPreferences.fontSize)
fsTimer.restart()
}
}
@@ -197,7 +197,7 @@ Rectangle {
Timer {
id: lsTimer
interval: 250
onTriggered: appState.lineSpacing = lsSlider.value
onTriggered: readingPreferences.lineSpacing = lsSlider.value
}
Slider {
@@ -206,9 +206,9 @@ Rectangle {
from: 0.5
to: 3.0
stepSize: 0.1
value: appState.lineSpacing
value: readingPreferences.lineSpacing
onValueChanged: {
if (Math.abs(value - appState.lineSpacing) > 0.01)
if (Math.abs(value - readingPreferences.lineSpacing) > 0.01)
lsTimer.restart()
}
}