old render cleanup part 3

This commit is contained in:
Agel committed 2026-10-25 15:43:51 +01:00
1 parent cef762c3ee
commit 3faedd4251
45 files changed
+1057 -1135

No files matched your search

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