Upgrade to Qt 6.10.3, refactor AppState for LibraryModel integration, add ChunkMeasurer tests, and update CI/docker configurations.

This commit is contained in:
Agel committed 2026-04-03 13:55:28 +02:00
1 parent 0303107fa2
commit a31b20534a
53 files changed
+2095 -880

No files matched your search

+65 -113
View File
@@ -1,7 +1,9 @@
#include "AppState.h"
#include <QSettings>
#include <QCryptographicHash>
#include <QDateTime>
#include "LibraryBookModel.h"
#include "LibraryModel.h"
#include <QtConcurrent/QtConcurrent>
static constexpr int SETTINGS_VERSION = 3;
static QString bookSettingsKey(const QString &filePath)
{
@@ -12,6 +14,7 @@ static QString bookSettingsKey(const QString &filePath)
AppState::AppState(QObject *parent)
: QObject(parent)
{
m_libraryModel = new LibraryModel(this);
}
QString AppState::lastFilePath() const { return m_lastFilePath; }
@@ -24,46 +27,6 @@ void AppState::setLastFilePath(const QString &path)
emit lastFilePathChanged();
}
int AppState::lastChapter() const { return m_lastChapter; }
void AppState::setLastChapter(int chapter)
{
if (m_lastChapter == chapter)
return;
m_lastChapter = chapter;
emit lastChapterChanged();
}
qreal AppState::lastScrollPosition() const { return m_lastScrollPosition; }
void AppState::setLastScrollPosition(qreal position)
{
if (qFuzzyCompare(m_lastScrollPosition, position))
return;
m_lastScrollPosition = position;
emit lastScrollPositionChanged();
}
int AppState::lastScrollIndex() const { return m_lastScrollIndex; }
void AppState::setLastScrollIndex(int index)
{
if (m_lastScrollIndex == index)
return;
m_lastScrollIndex = index;
emit lastScrollIndexChanged();
}
qreal AppState::lastScrollOffset() const { return m_lastScrollOffset; }
void AppState::setLastScrollOffset(qreal offset)
{
if (qFuzzyCompare(m_lastScrollOffset, offset))
return;
m_lastScrollOffset = offset;
emit lastScrollOffsetChanged();
}
int AppState::horizontalMargin() const { return m_horizontalMargin; }
void AppState::setHorizontalMargin(int margin)
@@ -149,23 +112,22 @@ QUrl AppState::lastFileUrl() const
return QUrl::fromLocalFile(m_lastFilePath);
}
void AppState::saveBookPosition(const QString &filePath, int chapter, int scrollIndex, qreal scrollOffset)
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("/chapter"), chapter);
s.setValue(key + QStringLiteral("/scrollIndex"), scrollIndex);
s.setValue(key + QStringLiteral("/scrollOffset"), scrollOffset);
s.setValue(key + QStringLiteral("/chunkIndex"), chunkIndex);
s.setValue(key + QStringLiteral("/intraChunkOffset"), intraChunkOffset);
}
QVariantMap AppState::loadBookPosition(const QString &filePath) const
QVariantMap AppState::loadBookPosition(const QString &filePath)
{
QSettings s;
QString key = bookSettingsKey(filePath);
QVariantMap result;
result[QStringLiteral("chapter")] = s.value(key + QStringLiteral("/chapter"), 0).toInt();
result[QStringLiteral("scrollIndex")] = s.value(key + QStringLiteral("/scrollIndex"), 0).toInt();
result[QStringLiteral("scrollOffset")] = s.value(key + QStringLiteral("/scrollOffset"), 0.0).toDouble();
result[QStringLiteral("chunkIndex")] = s.value(key + QStringLiteral("/chunkIndex"), 0).toInt();
result[QStringLiteral("intraChunkOffset")] = s.value(key + QStringLiteral("/intraChunkOffset"), 0.0).toInt();
return result;
}
@@ -199,67 +161,53 @@ void AppState::setThemeName(const QString &themeName)
emit themeNameChanged();
}
void AppState::addOrUpdateLibraryBook(const QString &filePath, const QString &title, const QString &author, double progress)
void AppState::addOrUpdateLibraryBook(const QString &filePath, double progress)
{
QString lastOpened = QDateTime::currentDateTime().toString(Qt::ISODate);
for (int i = 0; i < m_libraryBooks.size(); i++) {
QVariantMap book = m_libraryBooks[i].toMap();
if (book[QStringLiteral("filePath")].toString() == filePath) {
book[QStringLiteral("title")] = title;
book[QStringLiteral("author")] = author;
book[QStringLiteral("lastOpened")] = lastOpened;
if (progress >= 0.0)
book[QStringLiteral("progress")] = progress;
m_libraryBooks[i] = book;
// Move to front (most recently opened)
m_libraryBooks.move(i, 0);
saveLibraryBooks();
emit libraryBooksChanged();
return;
}
// 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;
}
QVariantMap newBook;
newBook[QStringLiteral("filePath")] = filePath;
newBook[QStringLiteral("title")] = title;
newBook[QStringLiteral("author")] = author;
newBook[QStringLiteral("progress")] = qMax(progress, 0.0);
newBook[QStringLiteral("lastOpened")] = lastOpened;
m_libraryBooks.prepend(newBook);
m_libraryModel->addOrUpdateBook(filePath, resolvedProgress, lastOpened);
saveLibraryBooks();
emit libraryBooksChanged();
}
void AppState::removeLibraryBook(const QString &filePath)
{
for (int i = 0; i < m_libraryBooks.size(); i++) {
if (m_libraryBooks[i].toMap()[QStringLiteral("filePath")].toString() == filePath) {
m_libraryBooks.removeAt(i);
saveLibraryBooks();
emit libraryBooksChanged();
return;
}
}
m_libraryModel->removeBook(filePath);
saveLibraryBooks();
}
QVariantList AppState::libraryBooks() const
QObject* AppState::libraryModel() const
{
return m_libraryBooks;
// 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"));
m_libraryBooks.clear();
for (int i = 0; i < size; i++) {
s.setArrayIndex(i);
QVariantMap book;
book[QStringLiteral("filePath")] = s.value(QStringLiteral("filePath")).toString();
book[QStringLiteral("title")] = s.value(QStringLiteral("title")).toString();
book[QStringLiteral("author")] = s.value(QStringLiteral("author")).toString();
book[QStringLiteral("progress")] = s.value(QStringLiteral("progress"), 0.0).toDouble();
book[QStringLiteral("lastOpened")] = s.value(QStringLiteral("lastOpened")).toString();
m_libraryBooks.append(book);
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);
}
s.endArray();
}
@@ -267,15 +215,14 @@ void AppState::loadLibraryBooks()
void AppState::saveLibraryBooks()
{
QSettings s;
s.beginWriteArray(QStringLiteral("library"), m_libraryBooks.size());
for (int i = 0; i < m_libraryBooks.size(); i++) {
QList<LibraryBookModel*> books = m_libraryModel->books();
s.beginWriteArray(QStringLiteral("library"), books.size());
for (int i = 0; i < books.size(); i++) {
s.setArrayIndex(i);
QVariantMap book = m_libraryBooks[i].toMap();
s.setValue(QStringLiteral("filePath"), book[QStringLiteral("filePath")]);
s.setValue(QStringLiteral("title"), book[QStringLiteral("title")]);
s.setValue(QStringLiteral("author"), book[QStringLiteral("author")]);
s.setValue(QStringLiteral("progress"), book[QStringLiteral("progress")]);
s.setValue(QStringLiteral("lastOpened"), book[QStringLiteral("lastOpened")]);
LibraryBookModel* book = books[i];
s.setValue(QStringLiteral("filePath"), book->filePath());
s.setValue(QStringLiteral("progress"), book->progress());
s.setValue(QStringLiteral("lastOpened"), book->lastOpened());
}
s.endArray();
}
@@ -283,11 +230,8 @@ void AppState::saveLibraryBooks()
void AppState::save()
{
QSettings s;
s.setValue(QStringLiteral("version"), SETTINGS_VERSION);
s.setValue(QStringLiteral("session/lastFilePath"), m_lastFilePath);
s.setValue(QStringLiteral("session/lastChapter"), m_lastChapter);
s.setValue(QStringLiteral("session/lastScrollPosition"), m_lastScrollPosition);
s.setValue(QStringLiteral("session/lastScrollIndex"), m_lastScrollIndex);
s.setValue(QStringLiteral("session/lastScrollOffset"), m_lastScrollOffset);
s.setValue(QStringLiteral("session/lastPage"), m_lastPage);
s.setValue(QStringLiteral("session/sidebarOpen"), m_sidebarOpen);
s.setValue(QStringLiteral("preferences/horizontalMargin"), m_horizontalMargin);
@@ -300,27 +244,35 @@ void AppState::save()
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_lastChapter = s.value(QStringLiteral("session/lastChapter"), 0).toInt();
m_lastScrollPosition = s.value(QStringLiteral("session/lastScrollPosition"), 0.0).toDouble();
m_lastScrollIndex = s.value(QStringLiteral("session/lastScrollIndex"), 0).toInt();
m_lastScrollOffset = s.value(QStringLiteral("session/lastScrollOffset"), 0.0).toDouble();
m_lastPage = s.value(QStringLiteral("session/lastPage"), QStringLiteral("starter")).toString();
m_sidebarOpen = s.value(QStringLiteral("session/sidebarOpen"), false).toBool();
m_horizontalMargin = s.value(QStringLiteral("preferences/horizontalMargin"), 32).toInt();
m_verticalMargin = s.value(QStringLiteral("preferences/verticalMargin"), 8).toInt();
m_fontSize = s.value(QStringLiteral("preferences/fontSize"), 16).toInt();
m_lineSpacing = s.value(QStringLiteral("preferences/lineSpacing"), 1.6).toDouble();
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();
+11 -32
View File
@@ -5,15 +5,13 @@
#include <QString>
#include <QUrl>
#include <QVariantMap>
#include <QVariantList>
class LibraryBookModel;
class LibraryModel;
class AppState : public QObject {
Q_OBJECT
Q_PROPERTY(QString lastFilePath READ lastFilePath WRITE setLastFilePath NOTIFY lastFilePathChanged)
Q_PROPERTY(int lastChapter READ lastChapter WRITE setLastChapter NOTIFY lastChapterChanged)
Q_PROPERTY(qreal lastScrollPosition READ lastScrollPosition WRITE setLastScrollPosition NOTIFY lastScrollPositionChanged)
Q_PROPERTY(int lastScrollIndex READ lastScrollIndex WRITE setLastScrollIndex NOTIFY lastScrollIndexChanged)
Q_PROPERTY(qreal lastScrollOffset READ lastScrollOffset WRITE setLastScrollOffset NOTIFY lastScrollOffsetChanged)
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)
@@ -22,10 +20,11 @@ class AppState : public QObject {
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(QVariantList libraryBooks READ libraryBooks NOTIFY libraryBooksChanged)
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:
explicit AppState(QObject *parent = nullptr);
@@ -36,18 +35,6 @@ public:
QString lastFilePath() const;
void setLastFilePath(const QString &path);
int lastChapter() const;
void setLastChapter(int chapter);
qreal lastScrollPosition() const;
void setLastScrollPosition(qreal position);
int lastScrollIndex() const;
void setLastScrollIndex(int index);
qreal lastScrollOffset() const;
void setLastScrollOffset(qreal offset);
int horizontalMargin() const;
void setHorizontalMargin(int margin);
@@ -74,8 +61,8 @@ public:
Q_INVOKABLE QUrl lastFileUrl() const;
Q_INVOKABLE void saveBookPosition(const QString &filePath, int chapter, int scrollIndex, qreal scrollOffset);
Q_INVOKABLE QVariantMap loadBookPosition(const QString &filePath) 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);
@@ -83,19 +70,15 @@ public:
bool sidebarOpen() const;
void setSidebarOpen(bool open);
Q_INVOKABLE void addOrUpdateLibraryBook(const QString &filePath, const QString &title, const QString &author, double progress);
Q_INVOKABLE void addOrUpdateLibraryBook(const QString &filePath, double progress);
Q_INVOKABLE void removeLibraryBook(const QString &filePath);
Q_INVOKABLE QVariantList libraryBooks() const;
QObject* libraryModel() const;
Q_INVOKABLE void save();
Q_INVOKABLE void restore();
signals:
void lastFilePathChanged();
void lastChapterChanged();
void lastScrollPositionChanged();
void lastScrollIndexChanged();
void lastScrollOffsetChanged();
void horizontalMarginChanged();
void verticalMarginChanged();
void fontSizeChanged();
@@ -105,7 +88,7 @@ signals:
void windowHeightChanged();
void windowXChanged();
void windowYChanged();
void libraryBooksChanged();
void lastPageChanged();
void sidebarOpenChanged();
void themeNameChanged();
@@ -114,10 +97,6 @@ private:
void loadLibraryBooks();
void saveLibraryBooks();
QString m_lastFilePath;
int m_lastChapter = 0;
qreal m_lastScrollPosition = 0.0;
int m_lastScrollIndex = 0;
qreal m_lastScrollOffset = 0.0;
int m_horizontalMargin = 32;
int m_verticalMargin = 8;
int m_fontSize = 16;
@@ -126,7 +105,7 @@ private:
int m_windowHeight = 768;
int m_windowX = -1;
int m_windowY = -1;
QVariantList m_libraryBooks;
LibraryModel* m_libraryModel;
QString m_lastPage = QStringLiteral("starter");
bool m_sidebarOpen = false;
QString m_themeName = QStringLiteral("dark");
+139 -49
View File
@@ -1,13 +1,24 @@
#include "BookController.h"
#include "AppState.h"
#include "ImageLoaderFactory.h"
#include "ImageProviderFactory.h"
#include "ReaderFactory.h"
#include "ReadingModel.h"
#include <QtConcurrent>
BookController::BookController(QObject *parent)
: QObject(parent)
{
}
BookController::~BookController()
{
if (m_openFuture.isRunning()) {
m_openFuture.cancel();
m_openFuture.waitForFinished();
}
}
QString BookController::bookTitle() const
{
return m_bookTitle;
@@ -38,6 +49,11 @@ QString BookController::currentFilePath() const
return m_currentFilePath;
}
bool BookController::startupRestore() const
{
return m_startupRestore;
}
QList<TocEntry> BookController::toc() const
{
if (m_reader)
@@ -45,9 +61,25 @@ QList<TocEntry> BookController::toc() const
return {};
}
QString BookController::coverImageUrl() const
{
return m_coverImageUrl;
}
void BookController::setReadingModel(ReadingModel *model)
{
m_readingModel = model;
if (m_readingModel) {
connect(m_readingModel, &ReadingModel::restoreReady,
this, [this]() {
if (!m_loading)
return;
m_loading = false;
emit loadingChanged();
emit bookReady();
m_startupRestore = false;
});
}
}
void BookController::setAppState(AppState *state)
@@ -63,6 +95,16 @@ void BookController::setFileDialogService(IFileDialogService *service)
this, &BookController::openBookFromPath);
}
void BookController::uiReady()
{
if (!m_appState || m_appState->lastFilePath().isEmpty()) {
emit noSavedBook();
return;
}
m_startupRestore = true;
openBook(m_appState->lastFileUrl());
}
void BookController::openBookFromPath(const QString &filePath)
{
openBook(QUrl::fromLocalFile(filePath));
@@ -70,15 +112,10 @@ void BookController::openBookFromPath(const QString &filePath)
void BookController::openBook(const QUrl &fileUrl)
{
QString filePath = fileUrl.toLocalFile();
const QString filePath = fileUrl.toLocalFile();
if (m_reader && m_appState && m_readingModel) {
m_appState->saveBookPosition(m_currentFilePath,
m_readingModel->currentChapter(),
m_appState->lastScrollIndex(),
m_appState->lastScrollOffset());
m_appState->addOrUpdateLibraryBook(m_currentFilePath, m_bookTitle, m_bookAuthor,
m_readingModel->progress());
m_appState->addOrUpdateLibraryBook(m_currentFilePath, m_readingModel->progress());
}
if (m_reader)
closeBook();
@@ -89,42 +126,94 @@ void BookController::openBook(const QUrl &fileUrl)
m_errorMessage.clear();
emit errorMessageChanged();
auto reader = ReaderFactory::create(filePath);
if (!reader) {
m_loading = false;
emit loadingChanged();
m_errorMessage = QStringLiteral("No format readers available");
emit errorMessageChanged();
emit bookError(m_errorMessage);
return;
}
const int generation = ++m_openGeneration;
if (!reader->open(filePath)) {
m_loading = false;
emit loadingChanged();
m_errorMessage = reader->lastError();
emit errorMessageChanged();
emit bookError(m_errorMessage);
return;
}
m_openFuture = QtConcurrent::run([this, filePath, generation]() {
// --- background thread: all file I/O ---
m_reader = std::move(reader);
m_currentFilePath = filePath;
if (m_imageProvider)
m_imageProvider->setEpubPath(filePath);
m_bookTitle = m_reader->title();
m_bookAuthor = m_reader->author();
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 readers available");
emit errorMessageChanged();
emit bookError(m_errorMessage);
}, Qt::QueuedConnection);
return;
}
if (m_readingModel)
m_readingModel->setReader(m_reader.get());
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();
emit bookError(m_errorMessage);
}, Qt::QueuedConnection);
return;
}
if (m_appState)
m_appState->addOrUpdateLibraryBook(m_currentFilePath, m_bookTitle, m_bookAuthor, -1.0);
// Cheap metadata reads while still on background thread
const QString title = reader->title();
const QString author = reader->author();
const QString coverPath = reader->coverImagePath();
m_loading = false;
emit loadingChanged();
emit bookChanged();
emit bookReady();
// Box the unique_ptr in a shared_ptr so the lambda capturing it is copyable
// (QMetaObject::invokeMethod requires a copyable functor for queued delivery).
auto readerBox = std::make_shared<std::unique_ptr<FormatReader>>(std::move(reader));
// --- main thread: model / provider setup ---
QMetaObject::invokeMethod(this, [this, generation, filePath,
readerBox, title, author, coverPath]() {
if (generation != m_openGeneration) return;
m_reader = std::move(*readerBox);
m_currentFilePath = filePath;
m_bookTitle = title;
m_bookAuthor = author;
IImageProvider *rawProvider = ImageProviderFactory::create(filePath);
m_ownedProvider.reset();
if (rawProvider && m_providerRegistrar) {
m_providerRegistrar(rawProvider->scheme(), rawProvider);
} else {
m_ownedProvider.reset(rawProvider);
}
m_imageProvider = rawProvider;
if (m_imageProvider) {
m_imageProvider->setFilePath(filePath);
m_imageProvider->setDisplayWidth(m_contentWidth);
}
if (!coverPath.isEmpty() && m_imageProvider)
m_coverImageUrl = m_imageProvider->coverImageUrl(coverPath);
else
m_coverImageUrl.clear();
if (m_readingModel) {
if (m_appState)
m_readingModel->setFontParams(m_appState->fontSize(), m_appState->lineSpacing());
m_readingModel->setImageLoader(ImageLoaderFactory::create(filePath));
m_readingModel->setCoverImageUrl(m_coverImageUrl);
m_readingModel->setReader(m_reader.get());
}
if (m_readingModel && m_appState) {
m_readingModel->measure(true);
emit bookChanged();
} else {
m_loading = false;
emit loadingChanged();
emit bookChanged();
emit bookReady();
m_startupRestore = false;
}
}, Qt::QueuedConnection);
});
}
void BookController::browseAndOpen()
@@ -136,22 +225,19 @@ void BookController::browseAndOpen()
void BookController::closeBook()
{
if (m_reader && m_appState && m_readingModel && !m_currentFilePath.isEmpty()) {
m_appState->saveBookPosition(m_currentFilePath,
m_readingModel->currentChapter(),
m_appState->lastScrollIndex(),
m_appState->lastScrollOffset());
m_appState->addOrUpdateLibraryBook(m_currentFilePath, m_bookTitle, m_bookAuthor,
m_readingModel->progress());
m_appState->addOrUpdateLibraryBook(m_currentFilePath, m_readingModel->progress());
}
if (m_imageProvider)
m_imageProvider->clear();
m_imageProvider = nullptr;
m_ownedProvider.reset();
if (m_readingModel)
m_readingModel->setReader(nullptr);
m_reader.reset();
m_bookTitle.clear();
m_bookAuthor.clear();
m_currentFilePath.clear();
if (m_readingModel)
m_readingModel->setReader(nullptr);
m_coverImageUrl.clear();
emit bookChanged();
}
@@ -164,13 +250,17 @@ void BookController::clearError()
emit errorMessageChanged();
}
void BookController::setImageProvider(EpubImageProvider *provider)
void BookController::setImageProviderRegistrar(
std::function<void(const QString &scheme, IImageProvider *)> fn)
{
m_imageProvider = provider;
m_providerRegistrar = std::move(fn);
}
void BookController::setContentWidth(int width)
{
m_contentWidth = width;
if (m_imageProvider)
m_imageProvider->setDisplayWidth(width);
if (m_readingModel)
m_readingModel->setContentWidth(width);
}
+25 -5
View File
@@ -1,15 +1,16 @@
#ifndef BOOKCONTROLLER_H
#define BOOKCONTROLLER_H
#include <QObject>
#include <QFuture>
#include <QString>
#include <QUrl>
#include <QList>
#include <functional>
#include <memory>
#include "EpubImageProvider.h"
#include "FormatReader.h"
#include "IFileDialogService.h"
#include "IImageLoader.h"
#include "IImageProvider.h"
class AppState;
class ReadingModel;
@@ -23,9 +24,12 @@ class BookController : public QObject {
Q_PROPERTY(bool hasBook READ hasBook NOTIFY bookChanged)
Q_PROPERTY(QList<TocEntry> toc READ toc NOTIFY bookChanged)
Q_PROPERTY(QString currentFilePath READ currentFilePath NOTIFY bookChanged)
Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY bookChanged)
Q_PROPERTY(bool startupRestore READ startupRestore NOTIFY bookReady)
public:
explicit BookController(QObject *parent = nullptr);
~BookController();
QString bookTitle() const;
QString bookAuthor() const;
@@ -34,12 +38,19 @@ public:
bool hasBook() const;
QList<TocEntry> toc() const;
QString currentFilePath() const;
QString coverImageUrl() const;
bool startupRestore() const;
void setReadingModel(ReadingModel *model);
void setAppState(AppState *state);
void setFileDialogService(IFileDialogService *service);
void setImageProvider(EpubImageProvider *provider);
// Called each time a new image provider is created for a book.
// The callback must register the provider with the QML engine (which takes ownership).
void setImageProviderRegistrar(std::function<void(const QString &scheme, IImageProvider *)> fn);
// Called by QML once the window is fully laid out. Reads AppState to decide
// whether to open the last book or emit noSavedBook().
Q_INVOKABLE void uiReady();
Q_INVOKABLE void openBook(const QUrl &fileUrl);
Q_INVOKABLE void openBookFromPath(const QString &filePath);
Q_INVOKABLE void browseAndOpen();
@@ -53,18 +64,27 @@ signals:
void bookChanged();
void loadingChanged();
void errorMessageChanged();
void noSavedBook(); // emitted by uiReady() when there is no last file to open
private:
std::unique_ptr<FormatReader> m_reader;
ReadingModel *m_readingModel = nullptr;
AppState *m_appState = nullptr;
IFileDialogService *m_fileDialogService = nullptr;
EpubImageProvider *m_imageProvider = nullptr;
std::function<void(const QString &, IImageProvider *)> m_providerRegistrar;
// Non-owning when the QML engine owns the provider; owning otherwise (e.g., in tests).
std::unique_ptr<IImageProvider> m_ownedProvider;
IImageProvider *m_imageProvider = nullptr;
QString m_bookTitle;
QString m_bookAuthor;
QString m_currentFilePath;
QString m_coverImageUrl;
bool m_loading = false;
QString m_errorMessage;
bool m_startupRestore = false;
int m_contentWidth = 0;
int m_openGeneration = 0; // incremented per openBook call; callbacks check for staleness
QFuture<void> m_openFuture;
};
#endif // BOOKCONTROLLER_H
+91
View File
@@ -0,0 +1,91 @@
#include "ChunkMeasurer.h"
#include <QFont>
#include <QImage>
#include <QTextBlockFormat>
#include <QTextCursor>
#include <QTextDocument>
#include <QTextOption>
#include <QThread>
#include <QtConcurrent>
#include <QAtomicInt>
// Private: one instance per worker thread — owns its IImageLoader clone
class ImageLoadingDocument : public QTextDocument {
IImageLoader *m_loader = nullptr;
int m_maxWidth = 0;
public:
void setLoader(IImageLoader *loader, int maxWidth) {
m_loader = loader;
m_maxWidth = maxWidth;
}
protected:
QVariant loadResource(int type, const QUrl &url) override {
if (type == QTextDocument::ImageResource && m_loader) {
QImage img = m_loader->load(url, m_maxWidth);
if (!img.isNull()) return img;
}
return QTextDocument::loadResource(type, url);
}
};
ChunkMeasurer::ChunkMeasurer(std::unique_ptr<IImageLoader> imageLoader,
int fontSize, qreal lineSpacing)
: m_imageLoader(std::move(imageLoader))
, m_fontSize(fontSize)
, m_lineSpacing(lineSpacing)
{}
QVector<int> ChunkMeasurer::measure(const QStringList &chunks, qreal textWidth)
{
const int n = chunks.size();
if (n == 0) return {};
if (textWidth <= 0) textWidth = 1.0;
QVector<int> heights(n, 0);
QAtomicInt nextIdx(0);
const int threadCount = QThread::idealThreadCount();
// Capture by value what each worker needs (no shared mutable state)
auto worker = [&]() {
std::unique_ptr<IImageLoader> loader =
m_imageLoader ? m_imageLoader->clone() : nullptr;
ImageLoadingDocument doc;
doc.setLoader(loader.get(), qRound(textWidth));
doc.setDocumentMargin(0);
doc.setUndoRedoEnabled(false);
QTextOption textOption = doc.defaultTextOption();
textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
doc.setDefaultTextOption(textOption);
QFont font;
font.setPixelSize(m_fontSize);
doc.setDefaultFont(font);
for (;;) {
const int i = nextIdx.fetchAndAddRelaxed(1);
if (i >= n) break;
doc.setHtml(chunks[i]);
doc.setTextWidth(textWidth);
QTextBlockFormat fmt;
fmt.setLineHeight(m_lineSpacing * 100.0, QTextBlockFormat::ProportionalHeight);
QTextCursor cursor(&doc);
cursor.select(QTextCursor::Document);
cursor.mergeBlockFormat(fmt);
heights[i] = qRound(doc.size().height());
}
};
QList<QFuture<void>> futures;
futures.reserve(threadCount);
for (int t = 0; t < threadCount; ++t)
futures.append(QtConcurrent::run(worker));
for (auto &f : futures)
f.waitForFinished();
return heights;
}
+16
View File
@@ -0,0 +1,16 @@
#ifndef CHUNKMEASURER_H
#define CHUNKMEASURER_H
#include "IChunkMeasurer.h"
#include "IImageLoader.h"
#include <memory>
class ChunkMeasurer : public IChunkMeasurer {
public:
explicit ChunkMeasurer(std::unique_ptr<IImageLoader> imageLoader = nullptr,
int fontSize = 16, qreal lineSpacing = 1.6);
QVector<int> measure(const QStringList &chunks, qreal textWidth) override;
private:
std::unique_ptr<IImageLoader> m_imageLoader;
int m_fontSize;
qreal m_lineSpacing;
};
#endif
+40 -1
View File
@@ -115,12 +115,51 @@ QImage EpubImageProvider::loadImageFromEpub(const QString &epubPath, const QStri
return image;
}
void EpubImageProvider::setEpubPath(const QString &filePath)
QImage EpubImageProvider::load(const QUrl &url, int maxWidth) const
{
if (url.scheme() != QLatin1String("image"))
return {};
QString zipPath = url.path();
if (zipPath.startsWith(QLatin1Char('/')))
zipPath = zipPath.mid(1);
if (zipPath.isEmpty())
return {};
QString epubPath;
{
QMutexLocker lock(&m_mutex);
epubPath = m_epubPath;
}
return loadImageFromEpub(epubPath, zipPath, maxWidth, {});
}
std::unique_ptr<IImageLoader> EpubImageProvider::clone() const
{
QString epubPath;
{
QMutexLocker lock(&m_mutex);
epubPath = m_epubPath;
}
auto c = std::make_unique<EpubImageProvider>();
c->setFilePath(epubPath);
return c;
}
void EpubImageProvider::setFilePath(const QString &filePath)
{
QMutexLocker lock(&m_mutex);
m_epubPath = filePath;
}
QString EpubImageProvider::coverImageUrl(const QString &coverPath) const
{
return QStringLiteral("image://epub/") + coverPath;
}
QString EpubImageProvider::scheme() const
{
return QStringLiteral("epub");
}
void EpubImageProvider::setDisplayWidth(int width)
{
QMutexLocker lock(&m_mutex);
+13 -8
View File
@@ -1,12 +1,12 @@
#pragma once
#include <QAtomicInt>
#include <QImage>
#include <QMutex>
#include <QQuickAsyncImageProvider>
#include <QRunnable>
#include <QString>
#include "IImageLoader.h"
#include "IImageProvider.h"
class EpubImageResponse : public QQuickImageResponse, public QRunnable {
// NO Q_OBJECT — already inherited from QQuickImageResponse
public:
@@ -26,20 +26,25 @@ private:
QImage m_image;
};
class EpubImageProvider : public QQuickAsyncImageProvider {
class EpubImageProvider : public IImageProvider, public IImageLoader {
public:
QQuickImageResponse *requestImageResponse(const QString &id,
const QSize &requestedSize) override;
void setEpubPath(const QString &filePath);
void setDisplayWidth(int width);
void clear();
void setFilePath(const QString &filePath) override;
void setDisplayWidth(int width) override;
void clear() override;
QString coverImageUrl(const QString &coverPath) const override;
QString scheme() const override;
QImage load(const QUrl &url, int maxWidth) const override;
std::unique_ptr<IImageLoader> clone() const override;
static QImage loadImageFromEpub(const QString &epubPath, const QString &id,
int displayWidth, const QSize &requestedSize);
private:
QMutex m_mutex;
mutable QMutex m_mutex;
QString m_epubPath;
int m_displayWidth = 0;
};
+4 -1
View File
@@ -2,7 +2,6 @@
#define FORMATREADER_H
#include <QString>
#include <QStringList>
#include <QList>
struct TocEntry {
@@ -22,12 +21,16 @@ public:
virtual ~FormatReader() = default;
virtual bool open(const QString &filePath) = 0;
virtual bool loadMetadata(const QString &filePath) = 0;
virtual QString lastError() = 0;
virtual int chapterCount() = 0;
virtual Chapter loadChapter(int index) = 0;
virtual QList<TocEntry> tableOfContents() = 0;
virtual QString filePath() = 0;
virtual QString title() = 0;
virtual QString author() = 0;
virtual QString coverImagePath() = 0;
};
#endif // FORMATREADER_H
+2 -5
View File
@@ -1,14 +1,11 @@
#ifndef ICHUNKMEASURER_H
#define ICHUNKMEASURER_H
#include <QStringList>
#include <QVector>
#include <QtGlobal>
class IChunkMeasurer {
public:
virtual ~IChunkMeasurer() = default;
virtual QVector<qreal> measure(const QStringList &chunks, qreal textWidth) const = 0;
virtual QVector<int> measure(const QStringList &chunks, qreal textWidth) = 0;
};
#endif // ICHUNKMEASURER_H
#endif
+12
View File
@@ -0,0 +1,12 @@
#ifndef IIMAGELLOADER_H
#define IIMAGELLOADER_H
#include <QImage>
#include <QUrl>
#include <memory>
class IImageLoader {
public:
virtual ~IImageLoader() = default;
virtual QImage load(const QUrl &url, int maxWidth) const = 0;
virtual std::unique_ptr<IImageLoader> clone() const = 0;
};
#endif
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include <QQuickAsyncImageProvider>
#include <QString>
class IImageProvider : public QQuickAsyncImageProvider {
public:
virtual ~IImageProvider() = default;
virtual void setFilePath(const QString &filePath) = 0;
virtual void setDisplayWidth(int width) = 0;
virtual void clear() = 0;
// Returns the full QML image URL for a given internal path (e.g., "image://epub/OEBPS/cover.jpg")
virtual QString coverImageUrl(const QString &coverPath) const = 0;
// The scheme this provider is registered under with the QML engine (e.g., "epub")
virtual QString scheme() const = 0;
};
+14
View File
@@ -0,0 +1,14 @@
#include "ImageLoaderFactory.h"
#include "EpubImageProvider.h"
#include <QFileInfo>
std::unique_ptr<IImageLoader> ImageLoaderFactory::create(const QString &filePath)
{
const QString ext = QFileInfo(filePath).suffix().toLower();
if (ext == QLatin1String("epub")) {
auto provider = std::make_unique<EpubImageProvider>();
provider->setFilePath(filePath);
return provider;
}
return nullptr;
}
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#include <memory>
#include <QString>
class IImageLoader;
class ImageLoaderFactory {
public:
// Returns a new loader for the given file format, or nullptr for formats without images.
static std::unique_ptr<IImageLoader> create(const QString &filePath);
};
+11
View File
@@ -0,0 +1,11 @@
#include "ImageProviderFactory.h"
#include "EpubImageProvider.h"
#include <QFileInfo>
IImageProvider *ImageProviderFactory::create(const QString &filePath)
{
const QString ext = QFileInfo(filePath).suffix().toLower();
if (ext == QLatin1String("epub"))
return new EpubImageProvider();
return nullptr;
}
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#include <QString>
class IImageProvider;
class ImageProviderFactory {
public:
// Returns a new provider for the given file format, or nullptr for formats without images.
// Caller is responsible for the returned pointer's lifetime.
static IImageProvider *create(const QString &filePath);
};
+119
View File
@@ -0,0 +1,119 @@
#include "LibraryBookModel.h"
#include "FormatReader.h"
#include "ReaderFactory.h"
#include <QtConcurrent/QtConcurrent>
LibraryBookModel::LibraryBookModel(QObject *parent)
: QObject(parent)
{
connect(this, &LibraryBookModel::metadataLoaded, this, &LibraryBookModel::onMetadataLoaded);
}
LibraryBookModel::LibraryBookModel(const QString &filePath, double progress, const QString &lastOpened, QObject *parent)
: QObject(parent), m_filePath(filePath), m_progress(progress), m_lastOpened(lastOpened)
{
connect(this, &LibraryBookModel::metadataLoaded, this, &LibraryBookModel::onMetadataLoaded);
}
LibraryBookModel::~LibraryBookModel()
{
if (m_metadataFuture.isRunning())
m_metadataFuture.waitForFinished();
}
QString LibraryBookModel::filePath() const
{
return m_filePath;
}
double LibraryBookModel::progress() const
{
return m_progress;
}
void LibraryBookModel::setProgress(double progress)
{
if (qFuzzyCompare(m_progress, progress))
return;
m_progress = progress;
emit progressChanged();
}
QString LibraryBookModel::lastOpened() const
{
return m_lastOpened;
}
void LibraryBookModel::setLastOpened(const QString &lastOpened)
{
if (m_lastOpened == lastOpened)
return;
m_lastOpened = lastOpened;
emit lastOpenedChanged();
}
QString LibraryBookModel::title() const
{
return m_title;
}
QString LibraryBookModel::author() const
{
return m_author;
}
QString LibraryBookModel::coverImageUrl() const
{
return m_coverImageUrl;
}
void LibraryBookModel::loadMetadata()
{
if (m_metadataLoaded || m_filePath.isEmpty() || m_metadataFuture.isRunning())
return;
QPointer<LibraryBookModel> self = this;
QString filePath = m_filePath;
m_metadataFuture = QtConcurrent::run([self, filePath]() {
auto reader = ReaderFactory::create(filePath);
QString title;
QString author;
bool success = false;
if (reader && reader->loadMetadata(filePath)) {
title = reader->title();
author = reader->author();
success = true;
}
QMetaObject::invokeMethod(self.data(), [self, title, author, success]() {
if (!self || !success)
return;
self->m_title = title;
self->m_author = author;
self->m_metadataLoaded = true;
emit self->metadataLoaded();
}, Qt::QueuedConnection);
});
}
void LibraryBookModel::onMetadataLoaded()
{
// This slot can be used for any post-processing after metadata is loaded
}
void LibraryBookModel::loadCoverImage(const QString &epubBasePath)
{
if (!m_coverImageUrl.isEmpty() || m_filePath.isEmpty())
return;
auto reader = ReaderFactory::create(m_filePath);
if (reader && reader->loadMetadata(m_filePath)) {
QString coverPath = reader->coverImagePath();
if (!coverPath.isEmpty()) {
m_coverImageUrl = QStringLiteral("image://epub/") + coverPath;
emit coverImageLoaded();
}
}
}
+59
View File
@@ -0,0 +1,59 @@
#ifndef LIBRARYBOOKMODEL_H
#define LIBRARYBOOKMODEL_H
#include <QString>
#include <QObject>
#include <QPointer>
#include <QFuture>
class FormatReader;
class LibraryBookModel : public QObject {
Q_OBJECT
Q_PROPERTY(QString filePath READ filePath CONSTANT)
Q_PROPERTY(double progress READ progress WRITE setProgress NOTIFY progressChanged)
Q_PROPERTY(QString lastOpened READ lastOpened WRITE setLastOpened NOTIFY lastOpenedChanged)
Q_PROPERTY(QString title READ title NOTIFY metadataLoaded)
Q_PROPERTY(QString author READ author NOTIFY metadataLoaded)
Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY coverImageLoaded)
public:
explicit LibraryBookModel(QObject *parent = nullptr);
explicit LibraryBookModel(const QString &filePath, double progress = 0.0, const QString &lastOpened = QString(), QObject *parent = nullptr);
~LibraryBookModel() override;
QString filePath() const;
double progress() const;
void setProgress(double progress);
QString lastOpened() const;
void setLastOpened(const QString &lastOpened);
QString title() const;
QString author() const;
QString coverImageUrl() const;
void loadMetadata();
void loadCoverImage(const QString &epubBasePath);
public slots:
void onMetadataLoaded();
signals:
void progressChanged();
void lastOpenedChanged();
void metadataLoaded();
void coverImageLoaded();
private:
QString m_filePath;
double m_progress = 0.0;
QString m_lastOpened;
QString m_title;
QString m_author;
QString m_coverImageUrl;
bool m_metadataLoaded = false;
QFuture<void> m_metadataFuture;
};
#endif // LIBRARYBOOKMODEL_H
+177
View File
@@ -0,0 +1,177 @@
#include "LibraryModel.h"
#include "LibraryBookModel.h"
LibraryModel::LibraryModel(QObject *parent)
: QAbstractListModel(parent)
{
// Initialize role names
m_roleNames[FilePathRole] = "filePath";
m_roleNames[TitleRole] = "title";
m_roleNames[AuthorRole] = "author";
m_roleNames[ProgressRole] = "progress";
m_roleNames[LastOpenedRole] = "lastOpened";
m_roleNames[CoverImageUrlRole] = "coverImageUrl";
}
LibraryModel::~LibraryModel()
{
clear();
}
int LibraryModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return m_books.count();
}
QVariant LibraryModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() < 0 || index.row() >= m_books.count())
return QVariant();
LibraryBookModel* book = m_books.at(index.row());
if (!book)
return QVariant();
switch (role) {
case FilePathRole:
return book->filePath();
case TitleRole:
return book->title();
case AuthorRole:
return book->author();
case ProgressRole:
return book->progress();
case LastOpenedRole:
return book->lastOpened();
case CoverImageUrlRole:
return book->coverImageUrl();
default:
return QVariant();
}
}
bool LibraryModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid() || index.row() < 0 || index.row() >= m_books.count())
return false;
LibraryBookModel* book = m_books.at(index.row());
switch (role) {
case ProgressRole:
book->setProgress(value.toDouble());
emit dataChanged(index, index, {ProgressRole});
return true;
case LastOpenedRole:
book->setLastOpened(value.toString());
emit dataChanged(index, index, {LastOpenedRole});
return true;
default:
return false;
}
}
QHash<int, QByteArray> LibraryModel::roleNames() const
{
return m_roleNames;
}
void LibraryModel::addOrUpdateBook(const QString &filePath, double progress, const QString &lastOpened)
{
// Check if book already exists
for (int i = 0; i < m_books.size(); i++) {
if (m_books[i]->filePath() == filePath) {
LibraryBookModel* existingBook = m_books[i];
existingBook->setProgress(progress);
existingBook->setLastOpened(lastOpened);
if (i != 0) {
beginMoveRows(QModelIndex(), i, i, QModelIndex(), 0);
m_books.move(i, 0);
endMoveRows();
}
return;
}
}
// New book — LibraryModel takes ownership via parent
auto* book = new LibraryBookModel(filePath, progress, lastOpened, this);
connect(book, &LibraryBookModel::metadataLoaded, this, &LibraryModel::onBookMetadataLoaded);
beginInsertRows(QModelIndex(), 0, 0);
m_books.prepend(book);
endInsertRows();
emit countChanged();
book->loadMetadata();
}
void LibraryModel::removeBook(const QString &filePath)
{
for (int i = 0; i < m_books.size(); i++) {
if (m_books[i]->filePath() == filePath) {
LibraryBookModel* book = m_books[i];
// Disconnect signals
disconnect(book, &LibraryBookModel::metadataLoaded, this, &LibraryModel::onBookMetadataLoaded);
beginRemoveRows(QModelIndex(), i, i);
m_books.removeAt(i);
endRemoveRows();
book->deleteLater();
emit countChanged();
return;
}
}
}
LibraryBookModel* LibraryModel::findBook(const QString &filePath) const
{
for (LibraryBookModel* book : m_books) {
if (book->filePath() == filePath) {
return book;
}
}
return nullptr;
}
void LibraryModel::clear()
{
if (m_books.isEmpty())
return;
beginRemoveRows(QModelIndex(), 0, m_books.size() - 1);
// Disconnect and delete all books
for (LibraryBookModel* book : m_books) {
disconnect(book, &LibraryBookModel::metadataLoaded, this, &LibraryModel::onBookMetadataLoaded);
book->deleteLater();
}
m_books.clear();
endRemoveRows();
emit countChanged();
}
QList<LibraryBookModel*> LibraryModel::books() const
{
return m_books;
}
void LibraryModel::onBookMetadataLoaded()
{
LibraryBookModel* book = qobject_cast<LibraryBookModel*>(sender());
if (!book)
return;
int row = m_books.indexOf(book);
if (row >= 0) {
QModelIndex index = this->index(row);
// Update all metadata-related roles when metadata is loaded
emit dataChanged(index, index, {TitleRole, AuthorRole, CoverImageUrlRole});
}
}
+57
View File
@@ -0,0 +1,57 @@
#ifndef LIBRARYMODEL_H
#define LIBRARYMODEL_H
#include <QAbstractListModel>
#include <QList>
#include <QHash>
class LibraryBookModel;
class LibraryModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(int count READ rowCount NOTIFY countChanged)
public:
enum LibraryRoles {
FilePathRole = Qt::UserRole + 1,
TitleRole,
AuthorRole,
ProgressRole,
LastOpenedRole,
CoverImageUrlRole
};
Q_ENUM(LibraryRoles)
explicit LibraryModel(QObject *parent = nullptr);
~LibraryModel() override;
// QAbstractItemModel interface
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::DisplayRole) override;
// Add QHash<int, QByteArray> for role names
QHash<int, QByteArray> roleNames() const override;
// Methods to manage books
Q_INVOKABLE void addOrUpdateBook(const QString &filePath, double progress, const QString &lastOpened);
Q_INVOKABLE void removeBook(const QString &filePath);
Q_INVOKABLE LibraryBookModel* findBook(const QString &filePath) const;
Q_INVOKABLE void clear();
// Access to books for saving/loading
QList<LibraryBookModel*> books() const;
signals:
void countChanged();
private slots:
void onBookMetadataLoaded();
private:
QList<LibraryBookModel*> m_books;
QHash<int, QByteArray> m_roleNames;
};
#endif // LIBRARYMODEL_H
-1
View File
@@ -3,7 +3,6 @@
#include "PortalFileDialogService.h"
#include <QDBusConnection>
#include <QDBusMessage>
#include <QDBusArgument>
#include <QDBusMetaType>
#include <QRandomGenerator>
#include <QUrl>
-41
View File
@@ -1,41 +0,0 @@
#include "QDocumentChunkMeasurer.h"
#include <QFont>
#include <QTextBlockFormat>
#include <QTextCursor>
#include <QTextDocument>
QDocumentChunkMeasurer::QDocumentChunkMeasurer(int pixelSize, qreal lineHeightPercent)
: m_pixelSize(pixelSize)
, m_lineHeightPercent(lineHeightPercent)
{
}
QVector<qreal> QDocumentChunkMeasurer::measure(const QStringList &chunks, qreal textWidth) const
{
if (textWidth <= 0)
textWidth = 1;
QFont font;
font.setPixelSize(m_pixelSize);
QTextDocument doc;
doc.setDefaultFont(font);
QVector<qreal> heights;
heights.reserve(chunks.size());
for (const QString &chunk : chunks) {
doc.setHtml(chunk);
doc.setTextWidth(textWidth);
QTextBlockFormat fmt;
fmt.setLineHeight(m_lineHeightPercent, QTextBlockFormat::ProportionalHeight);
QTextCursor cursor(&doc);
cursor.select(QTextCursor::Document);
cursor.mergeBlockFormat(fmt);
heights.append(doc.size().height());
}
return heights;
}
-16
View File
@@ -1,16 +0,0 @@
#ifndef QDOCUMENTCHUNKMEASURER_H
#define QDOCUMENTCHUNKMEASURER_H
#include "IChunkMeasurer.h"
class QDocumentChunkMeasurer : public IChunkMeasurer {
public:
explicit QDocumentChunkMeasurer(int pixelSize = 16, qreal lineHeightPercent = 160.0);
QVector<qreal> measure(const QStringList &chunks, qreal textWidth) const override;
private:
int m_pixelSize;
qreal m_lineHeightPercent;
};
#endif // QDOCUMENTCHUNKMEASURER_H
+149 -84
View File
@@ -1,34 +1,47 @@
#include "ReadingModel.h"
#include "FormatReader.h"
#include "IChunkMeasurer.h"
#include "IImageLoader.h"
#include "ChunkMeasurer.h"
#include <algorithm>
#include <cmath>
#include <QtConcurrent>
ReadingModel::ReadingModel(QObject *parent)
: QAbstractListModel(parent)
#include "AppState.h"
ReadingModel::ReadingModel(QObject *parent) : QAbstractListModel(parent) {}
ReadingModel::~ReadingModel()
{
if (m_measureFuture.isRunning()) {
m_measureFuture.cancel();
m_measureFuture.waitForFinished();
}
}
int ReadingModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
int ReadingModel::rowCount(const QModelIndex &parent) const {
if (parent.isValid()) return 0;
return m_chunks.size();
}
QVariant ReadingModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() < 0 || index.row() >= m_chunks.size())
QVariant ReadingModel::data(const QModelIndex &index, int role) const {
if (!index.isValid() || index.row() < 0 || index.row() >= (int)m_chunks.size())
return {};
if (role == ContentRole)
return m_chunks.at(index.row());
return {};
const auto &c = m_chunks.at(index.row());
switch (role) {
case ContentRole: return c.html;
case PixelHeightRole: return c.pixelHeight;
case ChapterRole: return c.chapterIndex;
default: return {};
}
}
QHash<int, QByteArray> ReadingModel::roleNames() const
{
return {{ContentRole, "content"}};
QHash<int, QByteArray> ReadingModel::roleNames() const {
return {
{ContentRole, "content"},
{PixelHeightRole, "pixelHeight"},
{ChapterRole, "chapter"},
};
}
QString ReadingModel::chapterTitle() const
@@ -38,52 +51,27 @@ QString ReadingModel::chapterTitle() const
return m_chapterTitles.at(m_currentChapter);
}
int ReadingModel::currentChapter() const
{
return m_currentChapter;
}
int ReadingModel::totalChapters() const
{
return m_totalChapters;
}
bool ReadingModel::hasChapters() const
{
return m_totalChapters > 1;
}
int ReadingModel::currentChapter() const { return m_currentChapter; }
int ReadingModel::totalChapters() const { return m_totalChapters; }
bool ReadingModel::hasChapters() const { return m_totalChapters > 1; }
bool ReadingModel::measuring() const { return m_measuring; }
qreal ReadingModel::totalPixelHeight() const { return m_totalPixelHeight; }
double ReadingModel::progress() const
{
if (m_totalBookBytes == 0)
return 0.0;
return qBound(0.0,
static_cast<double>(m_chunkByteOffsets.value(m_topChunkIndex)) / m_totalBookBytes,
1.0);
return qBound(0, static_cast<int>(m_yOffset * 100), 100);
}
int ReadingModel::currentPage() const
int ReadingModel::currentPage() const { return m_currentPage; }
int ReadingModel::totalPages() const { return m_totalPages; }
void ReadingModel::setScrollInfo(const int topChunkIndex, const qreal proportion)
{
return m_currentPage;
}
m_yOffset = proportion;
int ReadingModel::totalPages() const
{
return m_totalPages;
}
void ReadingModel::setScrollInfo(int topChunkIndex, qreal /*offsetInChunk*/, bool atYEnd)
{
if (topChunkIndex < 0 || topChunkIndex >= m_chunks.size())
return;
m_topChunkIndex = topChunkIndex;
m_atYEnd = atYEnd;
// Derive current chapter from global chunk index
auto it = std::upper_bound(m_chapterStartIndices.begin(), m_chapterStartIndices.end(), topChunkIndex);
int chapter = std::max(0, static_cast<int>(std::distance(m_chapterStartIndices.begin(), it)) - 1);
if (chapter != m_currentChapter) {
// Derive current chapter
const auto it = std::upper_bound(m_chapterStartIndices.begin(), m_chapterStartIndices.end(), topChunkIndex);
if (const int chapter = std::max(0, static_cast<int>(std::distance(m_chapterStartIndices.begin(), it)) - 1); chapter != m_currentChapter) {
m_currentChapter = chapter;
emit chapterChanged();
}
@@ -91,26 +79,87 @@ void ReadingModel::setScrollInfo(int topChunkIndex, qreal /*offsetInChunk*/, boo
recalculateCurrentPage();
}
void ReadingModel::computeChunkBytes()
void ReadingModel::measure(const bool isNew)
{
m_chunkBytes.resize(m_chunks.size());
m_chunkByteOffsets.resize(m_chunks.size());
qsizetype offset = 0;
for (int i = 0; i < m_chunks.size(); ++i) {
m_chunkByteOffsets[i] = offset;
qsizetype sz = m_chunks.at(i).toUtf8().size();
m_chunkBytes[i] = sz;
offset += sz;
}
m_totalBookBytes = offset;
if (!m_reader) return;
m_totalPixelHeight = 0;
QStringList htmls;
htmls.reserve(m_chunks.size());
for (const auto &c : m_chunks)
htmls.append(c.html);
runMeasurement(htmls, isNew);
}
void ReadingModel::runMeasurement(const QStringList &htmls, const bool isNew)
{
if (m_measureFuture.isRunning())
m_measureFuture.cancel();
m_measuring = true;
emit measuringChanged();
const int width = m_contentWidth > 0 ? m_contentWidth : 800;
const int fontSize = m_fontSize;
const qreal lineSpacing = m_lineSpacing;
std::unique_ptr<IImageLoader> loaderClone = m_imageLoader ? m_imageLoader->clone() : nullptr;
auto measurer = new ChunkMeasurer(std::move(loaderClone), fontSize, lineSpacing);
m_measureFuture = QtConcurrent::run(
[this, htmls, measurer, width, isNew]() {
QVector<int> heights = measurer->measure(htmls, width);
QMetaObject::invokeMethod(this, [this, heights, isNew] {
for (int i = 0; i < qMin(heights.size(), static_cast<int>(m_chunks.size())); ++i) {
m_chunks[i].pixelHeight = heights[i];
m_totalPixelHeight += heights[i];
}
qInfo("Measured %lld chunks, total height: %f", heights.size(), m_totalPixelHeight);
m_measuring = false;
emit measuringChanged();
emit totalPixelHeightChanged();
emit dataChanged(createIndex(0, 0),
createIndex(m_chunks.size() - 1, 0),
{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);
}
}, Qt::QueuedConnection);
});
}
void ReadingModel::setContentWidth(int width)
{
if (width == m_contentWidth) return;
m_contentWidth = width;
if (m_reader) measure(false);
}
void ReadingModel::setFontParams(int fontSize, qreal lineSpacing)
{
if (fontSize == m_fontSize && qFuzzyCompare(lineSpacing, m_lineSpacing)) return;
m_fontSize = fontSize;
m_lineSpacing = lineSpacing;
if (m_reader) measure(false);
}
void ReadingModel::setImageLoader(std::unique_ptr<IImageLoader> loader)
{
m_imageLoader = std::move(loader);
}
void ReadingModel::recalculateCurrentPage()
{
int page = 0;
if (!m_chunks.isEmpty()) {
page = m_atYEnd ? m_totalPages : m_topChunkIndex + 1;
page = std::max(1, std::min(page, m_totalPages));
page = qBound(0.0, m_yOffset / m_totalPixelHeight, 1.0) * m_chunks.size() * page_ratio;
}
if (m_currentPage == page)
return;
@@ -121,37 +170,46 @@ void ReadingModel::recalculateCurrentPage()
void ReadingModel::loadAllChapters()
{
beginResetModel();
m_chunks.clear();
m_chapterStartIndices.clear();
m_chapterTitles.clear();
m_chunkBytes.clear();
m_chunkByteOffsets.clear();
m_totalBookBytes = 0;
m_topChunkIndex = 0;
m_atYEnd = false;
m_totalPixelHeight = 0.0;
emit totalPixelHeightChanged();
m_currentChapter = 0;
if (m_currentPage != 0) { m_currentPage = 0; emit currentPageChanged(); }
if (m_totalPages != 0) { m_totalPages = 0; emit totalPagesChanged(); }
if (m_reader) {
if (!m_coverImageUrl.isEmpty()) {
QString coverHtml = QStringLiteral("<div class=\"cover-image\" style=\"text-align: center; margin: 2em 0;\">")
+ QStringLiteral("<img src=\"") + m_coverImageUrl
+ QStringLiteral("\" style=\"max-width: 100%; max-height: 80vh;\" /></div>");
m_chunks.push_back({coverHtml, 0, -1, -1}); // chunkInChapter=-1 = cover sentinel
m_chapterStartIndices.append(1); // chapter 0 starts after cover
} else {
m_chapterStartIndices.append(0);
}
for (int i = 0; i < m_totalChapters; ++i) {
auto chapter = m_reader->loadChapter(i);
m_chapterStartIndices.append(m_chunks.size());
if (i > 0)
m_chapterStartIndices.append(m_chunks.size());
m_chapterTitles.append(chapter.title);
m_chunks.append(chapter.contentChunks);
int j = 0;
for (const auto &html : chapter.contentChunks)
m_chunks.push_back({html, i, j++, -1});
}
}
endResetModel();
computeChunkBytes();
int pages = m_chunks.size();
if (m_totalPages != pages) { m_totalPages = pages; emit totalPagesChanged(); }
int page = m_chunks.isEmpty() ? 0 : 1;
if (m_currentPage != page) { m_currentPage = page; emit currentPageChanged(); }
if (const int pages = m_chunks.size() * page_ratio; m_totalPages != pages) {
m_totalPages = pages;
emit totalPagesChanged();
}
if (const int page = m_chunks.isEmpty() ? 0 : 1; m_currentPage != page) {
m_currentPage = page;
emit currentPageChanged();
}
}
void ReadingModel::setReader(FormatReader *reader)
@@ -166,6 +224,13 @@ void ReadingModel::setReader(FormatReader *reader)
emit chapterChanged();
}
void ReadingModel::setCoverImageUrl(const QString &coverImageUrl)
{
if (m_coverImageUrl != coverImageUrl) {
m_coverImageUrl = coverImageUrl;
}
}
void ReadingModel::nextChapter()
{
if (!m_reader || m_currentChapter >= m_totalChapters - 1)
+51 -16
View File
@@ -2,12 +2,20 @@
#define READINGMODEL_H
#include <QAbstractListModel>
#include <QFuture>
#include <QString>
#include <QStringList>
#include <QVector>
#include <memory>
#include "IImageLoader.h"
class FormatReader;
struct ContentChunk {
QString html; // empty when unloaded (lazy streaming)
int chapterIndex = 0; // which chapter owns this chunk
int chunkInChapter = 0; // 0-based index within chapter (-1 for cover)
int pixelHeight = -1; // -1 = not yet measured
};
class ReadingModel : public QAbstractListModel {
Q_OBJECT
Q_PROPERTY(QString chapterTitle READ chapterTitle NOTIFY chapterChanged)
@@ -17,17 +25,21 @@ class ReadingModel : public QAbstractListModel {
Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged)
Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged)
Q_PROPERTY(bool hasChapters READ hasChapters NOTIFY totalChaptersChanged)
Q_PROPERTY(bool measuring READ measuring NOTIFY measuringChanged)
Q_PROPERTY(qreal totalPixelHeight READ totalPixelHeight NOTIFY totalPixelHeightChanged)
public:
enum Roles {
ContentRole = Qt::UserRole + 1
ContentRole = Qt::UserRole + 1,
PixelHeightRole = Qt::UserRole + 2,
ChapterRole = Qt::UserRole + 3,
};
explicit ReadingModel(QObject *parent = nullptr);
~ReadingModel() override;
// QAbstractListModel overrides
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
int rowCount(const QModelIndex &parent) const override;
QVariant data(const QModelIndex &index, int role) const override;
QHash<int, QByteArray> roleNames() const override;
QString chapterTitle() const;
@@ -37,42 +49,65 @@ public:
int currentPage() const;
int totalPages() const;
bool hasChapters() const;
bool measuring() const;
qreal totalPixelHeight() const;
void setReader(FormatReader *reader);
void setCoverImageUrl(const QString &coverImageUrl);
// Called from QML on every scroll (real-time)
Q_INVOKABLE void setScrollInfo(int topChunkIndex, qreal offsetInChunk, bool atYEnd = false);
Q_INVOKABLE void setScrollInfo(int topChunkIndex, qreal proportion);
Q_INVOKABLE void nextChapter();
Q_INVOKABLE void previousChapter();
Q_INVOKABLE void goToChapter(int index);
// Measurement
Q_INVOKABLE void measure(bool isNew);
// Preferences & state
void setContentWidth(int width);
Q_INVOKABLE void setFontParams(int fontSize, qreal lineSpacing);
void setImageLoader(std::unique_ptr<IImageLoader> loader);
signals:
void chapterChanged();
void totalChaptersChanged();
void measuringChanged();
void totalPixelHeightChanged();
void currentPageChanged();
void totalPagesChanged();
void scrollToChunkRequested(int chunkIndex);
void restoreReady(int chunkIndex, int intraChunkOffset);
private:
static constexpr qreal page_ratio = 1.5;
void loadAllChapters();
void computeChunkBytes();
void recalculateCurrentPage();
void runMeasurement(const QStringList &htmls, bool isNew);
FormatReader *m_reader = nullptr;
QString m_coverImageUrl;
int m_currentChapter = 0;
int m_totalChapters = 0;
int m_currentPage = 0;
int m_totalPages = 0;
int m_topChunkIndex = 0;
bool m_atYEnd = false;
bool m_measuring = false;
QStringList m_chunks;
QVector<int> m_chapterStartIndices; // m_chapterStartIndices[i] = first global chunk index of chapter i
QVector<QString> m_chapterTitles; // title of each chapter
QVector<ContentChunk> m_chunks;
QVector<int> m_chapterStartIndices;
QVector<QString> m_chapterTitles;
QVector<qsizetype> m_chunkBytes; // UTF-8 byte size of each chunk (all chapters)
QVector<qsizetype> m_chunkByteOffsets; // prefix sums: offset[i] = sum of bytes[0..i-1]
qsizetype m_totalBookBytes = 0;
qreal m_totalPixelHeight = 0.0;
qreal m_yOffset = 0.0;
int m_contentWidth = 0;
int m_fontSize = 0;
qreal m_lineSpacing = 0;
std::unique_ptr<IImageLoader> m_imageLoader;
QFuture<void> m_measureFuture;
};
#endif // READINGMODEL_H
+82 -3
View File
@@ -31,6 +31,7 @@ bool EpubReader::open(const QString &filePath)
m_author.clear();
m_error.clear();
m_opfDir.clear();
m_coverImagePath.clear();
m_spineHrefs.clear();
m_spineRawContent.clear();
m_toc.clear();
@@ -40,7 +41,6 @@ bool EpubReader::open(const QString &filePath)
m_error = QStringLiteral("Cannot open as ZIP archive: ") + filePath;
return false;
}
// Ensure the handle is closed on all exit paths
auto guard = [&](void *) { unzClose(zf); };
std::unique_ptr<void, decltype(guard)> closeGuard(zf, guard);
@@ -85,7 +85,7 @@ bool EpubReader::open(const QString &filePath)
if (!ncxData.isEmpty())
parseNcx(ncxData);
}
m_filePath = filePath;
return true;
}
@@ -116,6 +116,7 @@ bool EpubReader::parseOpf(const QByteArray &data, QString &ncxHref)
QXmlStreamReader xml(data);
QHash<QString, QString> manifest; // id -> relative href
QString ncxId;
QString coverId; // ID of the cover image item
static const QLatin1String kDcNs("http://purl.org/dc/elements/1.1/");
@@ -133,11 +134,25 @@ bool EpubReader::parseOpf(const QByteArray &data, QString &ncxHref)
} else if (name == QLatin1String("creator") && ns == kDcNs) {
if (m_author.isEmpty())
m_author = xml.readElementText().trimmed();
} else if (name == QLatin1String("meta")) {
// Check for cover image metadata
const QString metaName = xml.attributes().value(QLatin1String("name")).toString();
const QString metaContent = xml.attributes().value(QLatin1String("content")).toString();
if (metaName == QLatin1String("cover") && !metaContent.isEmpty()) {
coverId = metaContent;
}
} else if (name == QLatin1String("item")) {
const QString id = xml.attributes().value(QLatin1String("id")).toString();
const QString href = xml.attributes().value(QLatin1String("href")).toString();
const QString properties = xml.attributes().value(QLatin1String("properties")).toString();
if (!id.isEmpty() && !href.isEmpty())
manifest.insert(id, href);
// Check if this item is the cover image
if (properties.contains(QLatin1String("cover-image"))) {
coverId = id;
}
} else if (name == QLatin1String("spine")) {
ncxId = xml.attributes().value(QLatin1String("toc")).toString();
} else if (name == QLatin1String("itemref")) {
@@ -147,6 +162,11 @@ bool EpubReader::parseOpf(const QByteArray &data, QString &ncxHref)
}
}
// Resolve cover image path if we found a cover ID
if (!coverId.isEmpty() && manifest.contains(coverId)) {
m_coverImagePath = m_opfDir + manifest.value(coverId);
}
if (!ncxId.isEmpty() && manifest.contains(ncxId))
ncxHref = m_opfDir + manifest.value(ncxId);
@@ -256,7 +276,8 @@ QStringList EpubReader::chunkXhtml(const QByteArray &data, const QString &xhtmlH
continue;
src = QUrl::fromPercentEncoding(src.toUtf8());
const QString resolved = QDir::cleanPath(xhtmlDir + src);
img.setAttribute(QStringLiteral("src"), QStringLiteral("image://epub/") + resolved);
img.setAttribute(QStringLiteral("src"),
QStringLiteral("image://epub/") + resolved);
}
// Find <body> element (may have namespace prefix in some EPUBs)
@@ -304,13 +325,71 @@ QStringList EpubReader::chunkXhtml(const QByteArray &data, const QString &xhtmlH
// FormatReader interface
// ---------------------------------------------------------------------------
bool EpubReader::loadMetadata(const QString &filePath)
{
// Reset state
m_title.clear();
m_author.clear();
m_error.clear();
m_opfDir.clear();
m_coverImagePath.clear();
m_spineHrefs.clear();
unzFile zf = unzOpen(filePath.toUtf8().constData());
if (!zf) {
m_error = QStringLiteral("Cannot open as ZIP archive: ") + filePath;
return false;
}
// Ensure the handle is closed on all exit paths
auto guard = [&](void *) { unzClose(zf); };
std::unique_ptr<void, decltype(guard)> closeGuard(zf, guard);
// 1. Parse META-INF/container.xml
QByteArray containerData = readZipEntry(zf, "META-INF/container.xml");
if (containerData.isEmpty()) {
m_error = QStringLiteral("Invalid EPUB: missing META-INF/container.xml");
return false;
}
QString opfPath;
if (!parseContainer(containerData, opfPath)) {
m_error = QStringLiteral("Invalid EPUB: cannot parse container.xml");
return false;
}
// 2. Determine OPF base directory
const int lastSlash = opfPath.lastIndexOf(QLatin1Char('/'));
m_opfDir = (lastSlash >= 0) ? opfPath.left(lastSlash + 1) : QString();
// 3. Parse OPF (only metadata and manifest for cover image)
QByteArray opfData = readZipEntry(zf, opfPath.toUtf8().constData());
if (opfData.isEmpty()) {
m_error = QStringLiteral("Invalid EPUB: cannot read OPF file: ") + opfPath;
return false;
}
QString ncxHref;
if (!parseOpf(opfData, ncxHref)) {
m_error = QStringLiteral("Invalid EPUB: cannot parse OPF file");
return false;
}
return true;
}
QString EpubReader::lastError() { return m_error; }
QString EpubReader::title() { return m_title; }
QString EpubReader::author() { return m_author; }
QString EpubReader::coverImagePath() { return m_coverImagePath; }
int EpubReader::chapterCount() { return m_spineHrefs.size(); }
QList<TocEntry> EpubReader::tableOfContents() { return m_toc; }
QString EpubReader::filePath()
{
return m_filePath;
}
Chapter EpubReader::loadChapter(int index)
{
if (index < 0 || index >= m_spineRawContent.size())
+5 -1
View File
@@ -5,23 +5,27 @@
#include <QByteArray>
#include <QHash>
#include <QList>
#include <QStringList>
class EpubReader : public FormatReader {
public:
bool open(const QString &filePath) override;
bool loadMetadata(const QString &filePath) override;
QString lastError() override;
int chapterCount() override;
Chapter loadChapter(int index) override;
QList<TocEntry> tableOfContents() override;
QString filePath() override;
QString title() override;
QString author() override;
QString coverImagePath() override;
private:
QString m_filePath;
QString m_title;
QString m_author;
QString m_error;
QString m_opfDir;
QString m_coverImagePath;
QStringList m_spineHrefs;
QList<QByteArray> m_spineRawContent;
QList<TocEntry> m_toc;
+26 -1
View File
@@ -1,6 +1,5 @@
#include "TxtReader.h"
#include <QFile>
#include <QFileInfo>
#include <QRegularExpression>
#include <QTextStream>
@@ -127,6 +126,7 @@ bool TxtReader::open(const QString &filePath)
uchardet_delete(ud);
if (!m_content.isEmpty()) {
m_title = QFileInfo(filePath).completeBaseName();
m_filePath = filePath;
return true;
}
}
@@ -136,6 +136,21 @@ bool TxtReader::open(const QString &filePath)
// Default: UTF-8
m_content = QString::fromUtf8(raw);
m_title = QFileInfo(filePath).completeBaseName();
m_filePath = filePath;
return true;
}
bool TxtReader::loadMetadata(const QString &filePath)
{
QFile file(filePath);
if (!file.exists()) {
m_error = QStringLiteral("File not found: ") + filePath;
return false;
}
// For TXT files, we only need the filename for title
m_title = QFileInfo(filePath).completeBaseName();
m_author.clear(); // No author info in plain text files
return true;
}
@@ -172,6 +187,11 @@ QList<TocEntry> TxtReader::tableOfContents()
return {};
}
QString TxtReader::filePath()
{
return m_filePath;
}
QString TxtReader::title()
{
return m_title;
@@ -181,3 +201,8 @@ QString TxtReader::author()
{
return {};
}
QString TxtReader::coverImagePath()
{
return {};
}
+5
View File
@@ -6,16 +6,21 @@
class TxtReader : public FormatReader {
public:
bool open(const QString &filePath) override;
bool loadMetadata(const QString &filePath) override;
QString lastError() override;
int chapterCount() override;
Chapter loadChapter(int index) override;
QList<TocEntry> tableOfContents() override;
QString filePath() override;
QString title() override;
QString author() override;
QString coverImagePath() override;
private:
QString m_content;
QString m_filePath;
QString m_title;
QString m_author;
QString m_error;
};
+16 -13
View File
@@ -1,17 +1,18 @@
#include <QApplication>
#include <QDateTime>
#include <QFileInfo>
#include <QSize>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQuickStyle>
#include <QQuickWindow>
#include <QSettings>
#include <QSGRendererInterface>
#include "backend/BookController.h"
#include "backend/EpubImageProvider.h"
#include "backend/IImageProvider.h"
#include "backend/ReadingModel.h"
#include "backend/AppState.h"
#include "backend/LibraryModel.h"
#include "backend/NativeFileDialogService.h"
#ifdef HAS_QT_DBUS
@@ -57,6 +58,7 @@ void myMessageHandler(const QtMsgType type, const QMessageLogContext &context, c
int main(int argc, char *argv[])
{
qInstallMessageHandler(myMessageHandler);
QSettings::setDefaultFormat(QSettings::IniFormat);
// Select graphics API per platform
#if defined(Q_OS_MACOS)
@@ -87,7 +89,7 @@ int main(int argc, char *argv[])
appState.restore();
bookController.setAppState(&appState);
#ifdef HAS_QT_DBUS
#if defined(HAS_QT_DBUS) && defined(Q_OS_LINUX)
IFileDialogService *fileDialogService;
if (QDBusConnection::sessionBus().isConnected()) {
fileDialogService = new PortalFileDialogService(&bookController);
@@ -106,10 +108,18 @@ int main(int argc, char *argv[])
}
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("isDebugBuild",
#ifdef QT_DEBUG
true
#else
false
#endif
);
auto *epubImageProvider = new EpubImageProvider;
engine.addImageProvider(QStringLiteral("epub"), epubImageProvider);
bookController.setImageProvider(epubImageProvider);
bookController.setImageProviderRegistrar([&engine](const QString &scheme, IImageProvider *provider) {
engine.removeImageProvider(scheme);
engine.addImageProvider(scheme, provider);
});
engine.rootContext()->setContextProperty(QStringLiteral("bookController"), &bookController);
engine.rootContext()->setContextProperty(QStringLiteral("readingModel"), &readingModel);
@@ -141,14 +151,7 @@ int main(int argc, char *argv[])
QObject::connect(&app, &QCoreApplication::aboutToQuit, [&bookController, &appState, &readingModel]() {
if (bookController.hasBook()) {
appState.setLastFilePath(bookController.currentFilePath());
appState.setLastChapter(readingModel.currentChapter());
appState.saveBookPosition(bookController.currentFilePath(),
readingModel.currentChapter(),
appState.lastScrollIndex(),
appState.lastScrollOffset());
appState.addOrUpdateLibraryBook(bookController.currentFilePath(),
bookController.bookTitle(),
bookController.bookAuthor(),
readingModel.progress());
} else {
appState.setLastFilePath(QString());
+28 -15
View File
@@ -7,6 +7,7 @@ ApplicationWindow {
id: window
width: 1024
height: 768
opacity: 0
visible: true
title: "Asteria"
color: ThemeManager.currentTheme.backgroundDeepest
@@ -19,7 +20,6 @@ ApplicationWindow {
property bool sidebarOpen: appState.sidebarOpen
onSidebarOpenChanged: appState.sidebarOpen = sidebarOpen
property string currentPage: "starter"
property bool _restoringState: false
property bool barsVisible: true
onCurrentPageChanged: appState.lastPage = currentPage
@@ -31,23 +31,12 @@ ApplicationWindow {
x = appState.windowX
y = appState.windowY
}
// Initialize theme from AppState
if (appState.themeName !== "") {
ThemeManager.currentThemeName = appState.themeName
}
if (appState.lastFilePath !== "") {
window._restoringState = true
bookController.openBook(appState.lastFileUrl())
} else {
window.sidebarOpen = true
var savedPage = appState.lastPage
if (savedPage === "library" || savedPage === "settings")
window.currentPage = savedPage
}
}
Connections {
target: appState
function onThemeNameChanged() {
@@ -129,6 +118,13 @@ ApplicationWindow {
anchors.fill: parent
visible: window.currentPage === "library"
}
BusyIndicator {
anchors.centerIn: parent
running: bookController.loading || readingModel.measuring
visible: running
z: 10
}
}
Loader {
@@ -224,8 +220,7 @@ ApplicationWindow {
Connections {
target: bookController
function onBookReady() {
if (window._restoringState) {
window._restoringState = false
if (bookController.startupRestore) {
var savedPage = appState.lastPage
if (savedPage === "library" || savedPage === "settings")
window.currentPage = savedPage
@@ -239,5 +234,23 @@ ApplicationWindow {
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
interval: 1
triggeredOnStart: false
onTriggered: {
window.opacity = 1
readerPage.pageView.updateContentWidth()
bookController.uiReady()
}
}
}
+104 -54
View File
@@ -5,6 +5,12 @@ import Asteria
Rectangle {
focus: true
property bool contentReady: false
property bool resizing: false
property bool restoreReady: false
property int initialIndex: -1
property int initialOffset: -1
// Animation for smooth scrolling
property Animation scrollAnimation: PropertyAnimation {
target: chunkListView
@@ -19,14 +25,14 @@ Rectangle {
var targetY = Math.max(0, chunkListView.contentY - scrollAmount);
animateScrollTo(targetY);
}
function handlePageDown() {
var scrollAmount = chunkListView.height * 0.95;
var maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height);
var targetY = Math.min(maxY, chunkListView.contentY + scrollAmount);
animateScrollTo(targetY);
}
function handleScrollUp() {
// Scroll up by approximately 2-3 lines
var lineHeight = appState.fontSize * appState.lineSpacing;
@@ -34,7 +40,7 @@ Rectangle {
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;
@@ -62,37 +68,72 @@ Rectangle {
}
Component.onCompleted: updateContentWidth()
onWidthChanged: updateContentWidth()
onWidthChanged: {
resizing = true;
remeasureTimer.restart()
}
Timer {
id: remeasureTimer
interval: 150
repeat: false
onTriggered: {
updateContentWidth()
resizing = false;
}
}
ListView {
id: chunkListView
anchors.fill: parent
model: bookController.hasBook ? readingModel : null
model: contentReady ? readingModel : null
header: Item { height: appState.verticalMargin }
footer: Item { height: appState.verticalMargin }
cacheBuffer: 2000
cacheBuffer: 20
clip: true
delegate: Text {
width: ListView.view.width - 18
leftPadding: appState.horizontalMargin
rightPadding: appState.horizontalMargin
wrapMode: Text.WrapAtWordBoundaryOrAnywhere
textFormat: Text.RichText
font.pixelSize: appState.fontSize
lineHeight: appState.lineSpacing
color: ThemeManager.currentTheme.readingText
text: model.content
delegate: Item {
id: chunkDelegate
readonly property int chunkIdx: model.index
width: chunkListView.width
height: resizing || readingModel.measuring ? contentText.implicitHeight : model.pixelHeight
Text {
visible: isDebugBuild
leftPadding: 0
text: model.index
color: "#FFFFFF"
height: 0
}
Text {
id: contentText
width: parent.width - 18 // subtract scrollbar
leftPadding: appState.horizontalMargin
rightPadding: appState.horizontalMargin
wrapMode: Text.WrapAtWordBoundaryOrAnywhere
textFormat: Text.RichText
font.pixelSize: appState.fontSize
lineHeight: appState.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
if (Math.abs(diff) > 1) {
console.warn("Chunk", model.index,
"height mismatch: measured=" + model.pixelHeight,
"actual=" + Math.round(implicitHeight),
"diff=" + Math.round(diff))
}
}
}
}
}
onContentYChanged: {
scrollTrackTimer.restart()
var idx = chunkListView.indexAt(0, chunkListView.contentY)
if (idx >= 0) {
var item = chunkListView.itemAtIndex(idx)
var offset = item ? chunkListView.contentY - item.y : 0
readingModel.setScrollInfo(idx, offset, chunkListView.atYEnd)
}
}
ScrollBar.vertical: ScrollBar {
@@ -125,60 +166,69 @@ Rectangle {
interval: 150
onTriggered: {
window.barsVisible = !window.barsVisible
window.sidebarOpen = false
window.sidebarOpen = !window.sidebarOpen
}
}
}
Timer {
id: scrollTrackTimer
interval: 300
repeat: false
onTriggered: {
var idx = chunkListView.indexAt(0, chunkListView.contentY)
appState.lastScrollIndex = idx
var item = chunkListView.itemAtIndex(idx)
var offset = item ? chunkListView.contentY - item.y : 0
appState.lastScrollOffset = offset
appState.lastScrollPosition = chunkListView.contentY
if (bookController.hasBook)
appState.saveBookPosition(bookController.currentFilePath,
readingModel.currentChapter, idx, offset)
if (bookController.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)
}
}
}
property bool _restoring: false
Connections {
target: bookController
function onBookReady() {
_restoring = true
var pos = appState.loadBookPosition(bookController.currentFilePath)
var savedScrollIndex = pos["scrollIndex"]
var savedScrollOffset = pos["scrollOffset"]
Qt.callLater(function() {
if (savedScrollIndex > 0) {
chunkListView.positionViewAtIndex(savedScrollIndex, ListView.Beginning)
chunkListView.contentY += savedScrollOffset
var idx = chunkListView.indexAt(0, chunkListView.contentY)
if (idx >= 0) {
var item = chunkListView.itemAtIndex(idx)
var offset = item ? chunkListView.contentY - item.y : 0
readingModel.setScrollInfo(idx, offset, chunkListView.atYEnd)
}
}
_restoring = false
})
function onLoadingChanged() {
if (bookController.loading)
contentReady = false
}
}
Connections {
target: readingModel
function onRestoreReady(chunkIndex, intraOffset) {
contentReady = true
initialIndex = chunkIndex
initialOffset = intraOffset
restoreTimer.start()
}
function onScrollToChunkRequested(chunkIndex) {
chunkListView.positionViewAtIndex(chunkIndex, ListView.Beginning)
}
}
Connections {
target: appState
function onFontSizeChanged() {
readingModel.setFontParams(appState.fontSize, appState.lineSpacing)
}
function onLineSpacingChanged() {
readingModel.setFontParams(appState.fontSize, appState.lineSpacing)
}
}
Timer {
id: restoreTimer
interval: 1
repeat: false
onTriggered: {
console.info("Restoring contentHeight:", chunkListView.contentHeight, "originY:", chunkListView.originY, "chunkIndex:", initialIndex, "intraOffset:", initialOffset)
chunkListView.positionViewAtIndex(initialIndex, ListView.Beginning)
chunkListView.contentY += initialOffset
restoreReady = true
}
}
}
+20 -10
View File
@@ -6,7 +6,7 @@ Rectangle {
color: ThemeManager.currentTheme.backgroundDefault
Text {
visible: appState.libraryBooks.length === 0
visible: appState.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.libraryBooks.length > 0
visible: appState.libraryModel.count > 0
anchors.fill: parent
anchors.margins: 16
spacing: 8
clip: true
model: appState.libraryBooks
model: appState.libraryModel
delegate: Rectangle {
id: bookRow
@@ -38,15 +38,25 @@ Rectangle {
anchors.bottomMargin: 12
spacing: 8
Image {
id: coverImage
visible: filePath !== ""
width: 60
height: 80
source: coverImageUrl
fillMode: Image.PreserveAspectFit
anchors.verticalCenter: parent.verticalCenter
}
Column {
id: bookInfoCol
width: parent.width - removeBtn.width - parent.spacing
width: parent.width - removeBtn.width - parent.spacing - (coverImage.visible ? coverImage.width + 8 : 0)
anchors.verticalCenter: parent.verticalCenter
spacing: 3
Text {
width: parent.width
text: modelData.title || "Unknown Title"
text: title || "Unknown Title"
color: ThemeManager.currentTheme.uiText
font.pixelSize: 14
font.bold: true
@@ -54,16 +64,16 @@ Rectangle {
}
Text {
visible: modelData.author !== ""
visible: author !== ""
width: parent.width
text: modelData.author
text: author
color: ThemeManager.currentTheme.dimText
font.pixelSize: 12
elide: Text.ElideRight
}
Text {
text: Math.round(modelData.progress * 100) + "%"
text: Math.round(progress * 100) + "%"
color: ThemeManager.currentTheme.buttonAccent
font.pixelSize: 12
}
@@ -82,14 +92,14 @@ Rectangle {
verticalAlignment: Text.AlignVCenter
}
background: Item {}
onClicked: appState.removeLibraryBook(modelData.filePath)
onClicked: appState.removeLibraryBook(filePath)
}
}
MouseArea {
anchors.fill: parent
z: -1
onClicked: bookController.openBookFromPath(modelData.filePath)
onClicked: bookController.openBookFromPath(filePath)
}
}
}
+49 -9
View File
@@ -44,7 +44,7 @@ Rectangle {
}
Text {
id: valueH
text: appState.horizontalMargin + " px"
text: hmSlider.value + " px"
font.pixelSize: 13
color: ThemeManager.currentTheme.dimText
anchors.right: parent.right
@@ -53,13 +53,23 @@ Rectangle {
}
}
Timer {
id: hmTimer
interval: 250
onTriggered: appState.horizontalMargin = hmSlider.value
}
Slider {
id: hmSlider
width: parent.width
from: 0
to: 120
stepSize: 1
value: appState.horizontalMargin
onValueChanged: appState.horizontalMargin = value
onValueChanged: {
if (value !== appState.horizontalMargin)
hmTimer.restart()
}
}
}
@@ -81,7 +91,7 @@ Rectangle {
}
Text {
id: valueV
text: appState.verticalMargin + " px"
text: vmSlider.value + " px"
font.pixelSize: 13
color: ThemeManager.currentTheme.dimText
anchors.right: parent.right
@@ -90,13 +100,23 @@ Rectangle {
}
}
Timer {
id: vmTimer
interval: 250
onTriggered: appState.verticalMargin = vmSlider.value
}
Slider {
id: vmSlider
width: parent.width
from: 0
to: 80
stepSize: 1
value: appState.verticalMargin
onValueChanged: appState.verticalMargin = value
onValueChanged: {
if (value !== appState.verticalMargin)
vmTimer.restart()
}
}
}
@@ -118,7 +138,7 @@ Rectangle {
}
Text {
id: valueF
text: appState.fontSize + " px"
text: fsSlider.value + " px"
font.pixelSize: 13
color: ThemeManager.currentTheme.dimText
anchors.right: parent.right
@@ -127,13 +147,23 @@ Rectangle {
}
}
Timer {
id: fsTimer
interval: 250
onTriggered: appState.fontSize = fsSlider.value
}
Slider {
id: fsSlider
width: parent.width
from: 10
to: 32
stepSize: 1
value: appState.fontSize
onValueChanged: appState.fontSize = value
onValueChanged: {
if (value !== appState.fontSize)
fsTimer.restart()
}
}
}
@@ -155,7 +185,7 @@ Rectangle {
}
Text {
id: valueL
text: appState.lineSpacing.toFixed(1) + "×"
text: lsSlider.value.toFixed(1) + "×"
font.pixelSize: 13
color: ThemeManager.currentTheme.dimText
anchors.right: parent.right
@@ -164,15 +194,25 @@ Rectangle {
}
}
Timer {
id: lsTimer
interval: 250
onTriggered: appState.lineSpacing = lsSlider.value
}
Slider {
id: lsSlider
width: parent.width
from: 0.5
to: 3.0
stepSize: 0.1
value: appState.lineSpacing
onValueChanged: appState.lineSpacing = value
onValueChanged: {
if (Math.abs(value - appState.lineSpacing) > 0.01)
lsTimer.restart()
}
}
}
}
}
}
}