Refactor using Fable
This commit is contained in:
90 files changed
+2080
-2267
No files matched your search
@@ -0,0 +1,143 @@
|
||||
#include "AppCoordinator.h"
|
||||
|
||||
#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,
|
||||
ReadingModel &readingModel,
|
||||
HistoryModel &historyModel,
|
||||
UiState &uiState,
|
||||
ReadingPreferences &readingPreferences,
|
||||
AppState &appState,
|
||||
QSettings &settings,
|
||||
FormatRegistry &formatRegistry,
|
||||
QQmlApplicationEngine &engine,
|
||||
QObject *parent)
|
||||
: QObject(parent)
|
||||
, m_book(book)
|
||||
, m_readingModel(readingModel)
|
||||
, m_historyModel(historyModel)
|
||||
, m_uiState(uiState)
|
||||
, m_readingPreferences(readingPreferences)
|
||||
, m_appState(appState)
|
||||
, m_settings(settings)
|
||||
, m_formatRegistry(formatRegistry)
|
||||
, m_engine(engine)
|
||||
{
|
||||
// Typography changes → re-push font params into ReadingModel
|
||||
connect(&m_readingPreferences, &ReadingPreferences::fontSizeChanged,
|
||||
this, &AppCoordinator::onFontPrefsChanged);
|
||||
connect(&m_readingPreferences, &ReadingPreferences::lineSpacingChanged,
|
||||
this, &AppCoordinator::onFontPrefsChanged);
|
||||
|
||||
connect(&m_book, &Book::willOpenNewBook, this, &AppCoordinator::onWillOpenNewBook);
|
||||
connect(&m_book, &Book::positionSaved, this, &AppCoordinator::onPositionSaved);
|
||||
connect(&m_book, &Book::bookChanged, this, &AppCoordinator::onBookChanged);
|
||||
connect(&m_book, &Book::contentWidthChanged, this, &AppCoordinator::onContentWidthChanged);
|
||||
|
||||
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit,
|
||||
this, &AppCoordinator::onAboutToQuit);
|
||||
}
|
||||
|
||||
void AppCoordinator::onFontPrefsChanged()
|
||||
{
|
||||
m_readingModel.setFontParams(m_readingPreferences.fontSize(),
|
||||
m_readingPreferences.lineSpacing());
|
||||
}
|
||||
|
||||
// Before a new book open: snapshot the outgoing book's progress into the library.
|
||||
// Scroll position is handled by PageView's scroll tracker via book.saveCurrentPosition().
|
||||
void AppCoordinator::onWillOpenNewBook()
|
||||
{
|
||||
if (m_book.hasBook())
|
||||
m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress());
|
||||
}
|
||||
|
||||
// Real-time history update: fired by PageView's scrollTrackTimer on every scroll.
|
||||
void AppCoordinator::onPositionSaved()
|
||||
{
|
||||
m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress());
|
||||
}
|
||||
|
||||
// After the new reader is installed: wire up image provider + ReadingModel
|
||||
void AppCoordinator::onBookChanged()
|
||||
{
|
||||
m_currentImageProvider = nullptr;
|
||||
|
||||
if (!m_book.hasBook()) {
|
||||
m_readingModel.setReader(nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
provider->setDisplayWidth(m_contentWidth);
|
||||
m_currentImageProvider = provider;
|
||||
|
||||
if (!reader->coverImagePath().isEmpty())
|
||||
m_book.setCoverImageUrl(provider->coverImageUrl(reader->coverImagePath()));
|
||||
}
|
||||
|
||||
m_readingModel.setFontParams(m_readingPreferences.fontSize(),
|
||||
m_readingPreferences.lineSpacing());
|
||||
m_readingModel.setImageLoader(m_formatRegistry.createImageLoader(filePath));
|
||||
m_readingModel.setCoverImageUrl(m_book.coverImageUrl());
|
||||
m_readingModel.setReader(reader);
|
||||
m_readingModel.measure(true);
|
||||
|
||||
m_uiState.setLastFilePath(filePath);
|
||||
m_historyModel.addOrUpdateBook(filePath, -1.0);
|
||||
}
|
||||
|
||||
// Propagate content-width changes to image provider + reading model.
|
||||
// Called from Book::setContentWidth which is triggered by QML's PageView.
|
||||
void AppCoordinator::onContentWidthChanged(int width)
|
||||
{
|
||||
m_contentWidth = width;
|
||||
if (m_currentImageProvider)
|
||||
m_currentImageProvider->setDisplayWidth(width);
|
||||
m_readingModel.setContentWidth(width);
|
||||
}
|
||||
|
||||
// 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()) {
|
||||
m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress());
|
||||
m_uiState.setLastFilePath(m_book.filePath());
|
||||
} else {
|
||||
m_uiState.setLastFilePath(QString());
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include <QObject>
|
||||
|
||||
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.
|
||||
class AppCoordinator : public QObject {
|
||||
Q_OBJECT
|
||||
public:
|
||||
AppCoordinator(Book &book,
|
||||
ReadingModel &readingModel,
|
||||
HistoryModel &historyModel,
|
||||
UiState &uiState,
|
||||
ReadingPreferences &readingPreferences,
|
||||
AppState &appState,
|
||||
QSettings &settings,
|
||||
FormatRegistry &formatRegistry,
|
||||
QQmlApplicationEngine &engine,
|
||||
QObject *parent = nullptr);
|
||||
|
||||
private slots:
|
||||
void onBookChanged();
|
||||
void onWillOpenNewBook();
|
||||
void onPositionSaved();
|
||||
void onContentWidthChanged(int width);
|
||||
void onFontPrefsChanged();
|
||||
void onAboutToQuit();
|
||||
|
||||
private:
|
||||
Book &m_book;
|
||||
ReadingModel &m_readingModel;
|
||||
HistoryModel &m_historyModel;
|
||||
UiState &m_uiState;
|
||||
ReadingPreferences &m_readingPreferences;
|
||||
AppState &m_appState;
|
||||
QSettings &m_settings;
|
||||
FormatRegistry &m_formatRegistry;
|
||||
QQmlApplicationEngine &m_engine;
|
||||
|
||||
IImageProvider *m_currentImageProvider = nullptr;
|
||||
int m_contentWidth = 0;
|
||||
};
|
||||
@@ -9,7 +9,7 @@ AppState::AppState(QSettings &settings)
|
||||
}
|
||||
}
|
||||
|
||||
QVariantMap AppState::loadSection(const QString §ion) const
|
||||
QVariantMap AppState::loadSection(const QString §ion)
|
||||
{
|
||||
QVariantMap result;
|
||||
m_settings.beginGroup(section);
|
||||
@@ -20,7 +20,7 @@ QVariantMap AppState::loadSection(const QString §ion) const
|
||||
return result;
|
||||
}
|
||||
|
||||
void AppState::saveSection(const QString §ion, const QVariantMap &data) const
|
||||
void AppState::saveSection(const QString §ion, const QVariantMap &data)
|
||||
{
|
||||
m_settings.beginGroup(section);
|
||||
m_settings.remove(QStringLiteral("")); // clear existing group
|
||||
@@ -29,23 +29,22 @@ void AppState::saveSection(const QString §ion, const QVariantMap &data) cons
|
||||
m_settings.endGroup();
|
||||
}
|
||||
|
||||
QList<QVariantMap> AppState::loadArray(const QString §ion) const
|
||||
QList<QVariantMap> AppState::loadArray(const QString §ion)
|
||||
{
|
||||
QList<QVariantMap> result;
|
||||
QSettings &s = const_cast<QSettings &>(m_settings);
|
||||
const int size = s.beginReadArray(section);
|
||||
const int size = m_settings.beginReadArray(section);
|
||||
for (int i = 0; i < size; ++i) {
|
||||
s.setArrayIndex(i);
|
||||
m_settings.setArrayIndex(i);
|
||||
QVariantMap entry;
|
||||
for (const QString &key : s.childKeys())
|
||||
entry[key] = s.value(key);
|
||||
for (const QString &key : m_settings.childKeys())
|
||||
entry[key] = m_settings.value(key);
|
||||
result.append(entry);
|
||||
}
|
||||
s.endArray();
|
||||
m_settings.endArray();
|
||||
return result;
|
||||
}
|
||||
|
||||
void AppState::saveArray(const QString §ion, const QList<QVariantMap> &items) const
|
||||
void AppState::saveArray(const QString §ion, const QList<QVariantMap> &items)
|
||||
{
|
||||
m_settings.beginWriteArray(section, items.size());
|
||||
for (int i = 0; i < items.size(); ++i) {
|
||||
|
||||
@@ -15,16 +15,16 @@ public:
|
||||
explicit AppState(QSettings &settings);
|
||||
|
||||
// Load all key/value pairs from the named QSettings group.
|
||||
QVariantMap loadSection(const QString §ion) const;
|
||||
QVariantMap loadSection(const QString §ion);
|
||||
|
||||
// Atomically replace the named QSettings group with the given data.
|
||||
void saveSection(const QString §ion, const QVariantMap &data) const;
|
||||
void saveSection(const QString §ion, const QVariantMap &data);
|
||||
|
||||
// Load an ordered array (e.g., library books) from the named QSettings array.
|
||||
QList<QVariantMap> loadArray(const QString §ion) const;
|
||||
QList<QVariantMap> loadArray(const QString §ion);
|
||||
|
||||
// Atomically replace the named QSettings array.
|
||||
void saveArray(const QString §ion, const QList<QVariantMap> &items) const;
|
||||
void saveArray(const QString §ion, const QList<QVariantMap> &items);
|
||||
|
||||
private:
|
||||
QSettings &m_settings;
|
||||
|
||||
@@ -1,27 +1,17 @@
|
||||
#include "HistoryBookModel.h"
|
||||
#include "FormatReader.h"
|
||||
#include "IImageProvider.h"
|
||||
#include "formats/ImageProviderFactory.h"
|
||||
#include "formats/ReaderFactory.h"
|
||||
#include <QtConcurrent/QtConcurrent>
|
||||
#include <QFileInfo>
|
||||
#include <QUrl>
|
||||
|
||||
HistoryBookModel::HistoryBookModel(ReaderFactory &factory, QObject *parent)
|
||||
: QObject(parent)
|
||||
, m_factory(factory)
|
||||
{
|
||||
connect(this, &HistoryBookModel::metadataLoaded, this, &HistoryBookModel::onMetadataLoaded);
|
||||
}
|
||||
|
||||
HistoryBookModel::HistoryBookModel(const QString &filePath, double progress, const QString &lastOpened, ReaderFactory &factory, QObject *parent)
|
||||
HistoryBookModel::HistoryBookModel(const QString &filePath, double progress, const QString &lastOpened, FormatRegistry ®istry, QObject *parent)
|
||||
: QObject(parent)
|
||||
, m_filePath(filePath)
|
||||
, m_progress(progress)
|
||||
, m_lastOpened(lastOpened)
|
||||
, m_factory(factory)
|
||||
, m_registry(registry)
|
||||
{
|
||||
connect(this, &HistoryBookModel::metadataLoaded, this, &HistoryBookModel::onMetadataLoaded);
|
||||
}
|
||||
|
||||
HistoryBookModel::~HistoryBookModel()
|
||||
@@ -91,9 +81,9 @@ void HistoryBookModel::loadMetadata()
|
||||
QPointer<HistoryBookModel> self = this;
|
||||
QString filePath = m_filePath;
|
||||
|
||||
ReaderFactory *factory = &m_factory;
|
||||
m_metadataFuture = QtConcurrent::run([self, filePath, factory]() {
|
||||
auto reader = factory->create(filePath);
|
||||
FormatRegistry *registry = &m_registry;
|
||||
m_metadataFuture = QtConcurrent::run([self, filePath, registry]() {
|
||||
auto reader = registry->createReader(filePath);
|
||||
QString title;
|
||||
QString author;
|
||||
bool success = false;
|
||||
@@ -108,7 +98,7 @@ void HistoryBookModel::loadMetadata()
|
||||
if (success) {
|
||||
QString coverPath = reader->coverImagePath();
|
||||
if (!coverPath.isEmpty()) {
|
||||
std::unique_ptr<IImageProvider> provider(ImageProviderFactory::create(filePath));
|
||||
std::unique_ptr<IImageProvider> provider(registry->createImageProvider(filePath));
|
||||
if (provider) {
|
||||
provider->setFilePath(filePath);
|
||||
coverImageUrl = provider->coverImageUrl(coverPath);
|
||||
@@ -123,11 +113,8 @@ void HistoryBookModel::loadMetadata()
|
||||
self->m_author = author;
|
||||
self->m_coverImageUrl = coverImageUrl;
|
||||
self->m_metadataLoaded = true;
|
||||
emit self->coverImageLoaded();
|
||||
emit self->metadataLoaded();
|
||||
}, Qt::QueuedConnection);
|
||||
});
|
||||
}
|
||||
|
||||
void HistoryBookModel::onMetadataLoaded()
|
||||
{
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
#include <QPointer>
|
||||
#include <QFuture>
|
||||
|
||||
#include "formats/ReaderFactory.h"
|
||||
#include "formats/FormatRegistry.h"
|
||||
|
||||
class FormatReader;
|
||||
|
||||
@@ -21,8 +21,7 @@ class HistoryBookModel : public QObject {
|
||||
Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY coverImageLoaded)
|
||||
|
||||
public:
|
||||
explicit HistoryBookModel(ReaderFactory &factory, QObject *parent = nullptr);
|
||||
explicit HistoryBookModel(const QString &filePath, double progress, const QString &lastOpened, ReaderFactory &factory, QObject *parent = nullptr);
|
||||
explicit HistoryBookModel(const QString &filePath, double progress, const QString &lastOpened, FormatRegistry ®istry, QObject *parent = nullptr);
|
||||
~HistoryBookModel() override;
|
||||
|
||||
QString filePath() const;
|
||||
@@ -39,9 +38,6 @@ public:
|
||||
|
||||
void loadMetadata();
|
||||
|
||||
public slots:
|
||||
void onMetadataLoaded();
|
||||
|
||||
signals:
|
||||
void progressChanged();
|
||||
void lastOpenedChanged();
|
||||
@@ -57,7 +53,7 @@ private:
|
||||
QString m_coverImageUrl;
|
||||
bool m_metadataLoaded = false;
|
||||
QFuture<void> m_metadataFuture;
|
||||
ReaderFactory &m_factory;
|
||||
FormatRegistry &m_registry;
|
||||
};
|
||||
|
||||
#endif // HISTORYBOOKMODEL_H
|
||||
@@ -2,9 +2,9 @@
|
||||
#include "HistoryBookModel.h"
|
||||
#include <QDateTime>
|
||||
|
||||
HistoryModel::HistoryModel(ReaderFactory &factory, QObject *parent)
|
||||
HistoryModel::HistoryModel(FormatRegistry ®istry, QObject *parent)
|
||||
: QAbstractListModel(parent)
|
||||
, m_factory(factory)
|
||||
, m_registry(registry)
|
||||
{
|
||||
// Initialize role names
|
||||
m_roleNames[FilePathRole] = "filePath";
|
||||
@@ -103,7 +103,7 @@ void HistoryModel::addOrUpdateBook(const QString &filePath, double progress, con
|
||||
}
|
||||
|
||||
// New book — HistoryModel takes ownership via parent
|
||||
auto* book = new HistoryBookModel(filePath, progress, lastOpened, m_factory, this);
|
||||
auto* book = new HistoryBookModel(filePath, progress, lastOpened, m_registry, this);
|
||||
connect(book, &HistoryBookModel::metadataLoaded, this, &HistoryModel::onBookMetadataLoaded);
|
||||
|
||||
beginInsertRows(QModelIndex(), 0, 0);
|
||||
@@ -119,14 +119,11 @@ 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];
|
||||
|
||||
// Disconnect signals
|
||||
disconnect(book, &HistoryBookModel::metadataLoaded, this, &HistoryModel::onBookMetadataLoaded);
|
||||
|
||||
|
||||
beginRemoveRows(QModelIndex(), i, i);
|
||||
m_books.removeAt(i);
|
||||
endRemoveRows();
|
||||
|
||||
|
||||
book->deleteLater();
|
||||
emit countChanged();
|
||||
return;
|
||||
@@ -150,13 +147,10 @@ void HistoryModel::clear()
|
||||
return;
|
||||
|
||||
beginRemoveRows(QModelIndex(), 0, m_books.size() - 1);
|
||||
|
||||
// Disconnect and delete all books
|
||||
for (HistoryBookModel* book : m_books) {
|
||||
disconnect(book, &HistoryBookModel::metadataLoaded, this, &HistoryModel::onBookMetadataLoaded);
|
||||
|
||||
for (HistoryBookModel* book : m_books)
|
||||
book->deleteLater();
|
||||
}
|
||||
|
||||
|
||||
m_books.clear();
|
||||
endRemoveRows();
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
#include <QList>
|
||||
#include <QHash>
|
||||
|
||||
#include "formats/ReaderFactory.h"
|
||||
#include "formats/FormatRegistry.h"
|
||||
|
||||
class HistoryBookModel;
|
||||
|
||||
@@ -26,7 +26,7 @@ public:
|
||||
};
|
||||
Q_ENUM(HistoryRoles)
|
||||
|
||||
explicit HistoryModel(ReaderFactory &factory, QObject *parent = nullptr);
|
||||
explicit HistoryModel(FormatRegistry ®istry, QObject *parent = nullptr);
|
||||
~HistoryModel() override;
|
||||
|
||||
// QAbstractItemModel interface
|
||||
@@ -62,7 +62,7 @@ private slots:
|
||||
private:
|
||||
QList<HistoryBookModel*> m_books;
|
||||
QHash<int, QByteArray> m_roleNames;
|
||||
ReaderFactory &m_factory;
|
||||
FormatRegistry &m_registry;
|
||||
};
|
||||
|
||||
#endif // HISTORYMODEL_H
|
||||
@@ -1 +0,0 @@
|
||||
#include "IFileDialogService.h"
|
||||
@@ -1,5 +1,4 @@
|
||||
#ifndef IFILEDIAL0GSERVICE_H
|
||||
#define IFILEDIAL0GSERVICE_H
|
||||
#pragma once
|
||||
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
@@ -16,5 +15,3 @@ public:
|
||||
signals:
|
||||
void fileSelected(const QString &path);
|
||||
};
|
||||
|
||||
#endif // IFILEDIAL0GSERVICE_H
|
||||
@@ -1,5 +1,4 @@
|
||||
#ifndef IIMAGELLOADER_H
|
||||
#define IIMAGELLOADER_H
|
||||
#pragma once
|
||||
#include <QImage>
|
||||
#include <QUrl>
|
||||
#include <memory>
|
||||
@@ -9,4 +8,3 @@ public:
|
||||
virtual QImage load(const QUrl &url, int maxWidth) const = 0;
|
||||
virtual std::unique_ptr<IImageLoader> clone() const = 0;
|
||||
};
|
||||
#endif
|
||||
+50
-116
@@ -1,26 +1,20 @@
|
||||
#include "ReadingModel.h"
|
||||
#include "FormatReader.h"
|
||||
#include "IChunkMeasurer.h"
|
||||
#include "IImageLoader.h"
|
||||
#include "ChunkMeasurer.h"
|
||||
#include <QRegularExpression>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <QtConcurrent>
|
||||
|
||||
ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent)
|
||||
: QAbstractListModel(parent)
|
||||
, m_positions(positions)
|
||||
{
|
||||
connect(&m_measurer, &MeasurementController::measuringChanged,
|
||||
this, &ReadingModel::measuringChanged);
|
||||
connect(&m_measurer, &MeasurementController::heightsReady,
|
||||
this, &ReadingModel::onHeightsReady);
|
||||
}
|
||||
|
||||
ReadingModel::~ReadingModel()
|
||||
{
|
||||
if (m_measureFuture.isRunning()) {
|
||||
m_measureFuture.cancel();
|
||||
m_measureFuture.waitForFinished();
|
||||
}
|
||||
}
|
||||
ReadingModel::~ReadingModel() = default;
|
||||
|
||||
int ReadingModel::rowCount(const QModelIndex &parent) const {
|
||||
if (parent.isValid()) return 0;
|
||||
@@ -59,9 +53,9 @@ QString ReadingModel::chapterTitle() const
|
||||
int ReadingModel::currentChapter() const { return m_currentChapter; }
|
||||
int ReadingModel::totalChapters() const { return m_totalChapters; }
|
||||
bool ReadingModel::hasChapters() const { return m_totalChapters > 1; }
|
||||
bool ReadingModel::measuring() const { return m_measuring; }
|
||||
bool ReadingModel::measuring() const { return m_measurer.measuring(); }
|
||||
qreal ReadingModel::totalPixelHeight() const { return m_totalPixelHeight; }
|
||||
int ReadingModel::totalPagePairs() const { return m_pagePairs.size(); }
|
||||
int ReadingModel::totalPagePairs() const { return m_pagination.count(); }
|
||||
bool ReadingModel::isMangaMode() const { return m_isMangaMode; }
|
||||
bool ReadingModel::pageShift() const { return m_pageShift; }
|
||||
bool ReadingModel::mangaRTL() const { return m_mangaRTL; }
|
||||
@@ -109,7 +103,8 @@ void ReadingModel::measure(const bool isNew)
|
||||
for (const auto &c : m_chunks)
|
||||
htmls.append(c.html);
|
||||
|
||||
runMeasurement(htmls, isNew);
|
||||
const int width = m_contentWidth > 0 ? m_contentWidth : 800;
|
||||
m_measurer.start(htmls, width, m_fontSize, m_lineSpacing, isNew);
|
||||
}
|
||||
|
||||
void ReadingModel::emitRestoreReady(const bool isNew)
|
||||
@@ -119,41 +114,19 @@ void ReadingModel::emitRestoreReady(const bool isNew)
|
||||
emit restoreReady(pos.chunkIndex, pos.intraOffset);
|
||||
}
|
||||
|
||||
void ReadingModel::runMeasurement(const QStringList &htmls, const bool isNew)
|
||||
void ReadingModel::onHeightsReady(const QVector<int> &heights, const bool isNew)
|
||||
{
|
||||
if (m_measureFuture.isRunning())
|
||||
m_measureFuture.cancel();
|
||||
for (int i = 0; i < qMin(heights.size(), static_cast<int>(m_chunks.size())); ++i) {
|
||||
m_chunks[i].pixelHeight = heights[i];
|
||||
m_totalPixelHeight += heights[i];
|
||||
}
|
||||
qInfo("Measured %lld chunks, total height: %f", heights.size(), m_totalPixelHeight);
|
||||
emit totalPixelHeightChanged();
|
||||
emit dataChanged(createIndex(0, 0),
|
||||
createIndex(m_chunks.size() - 1, 0),
|
||||
{PixelHeightRole});
|
||||
|
||||
m_measuring = true;
|
||||
emit measuringChanged();
|
||||
|
||||
const int width = m_contentWidth > 0 ? m_contentWidth : 800;
|
||||
const int fontSize = m_fontSize;
|
||||
const qreal lineSpacing = m_lineSpacing;
|
||||
|
||||
std::unique_ptr<IImageLoader> loaderClone = m_imageLoader ? m_imageLoader->clone() : nullptr;
|
||||
auto measurer = new ChunkMeasurer(std::move(loaderClone), fontSize, lineSpacing);
|
||||
|
||||
|
||||
m_measureFuture = QtConcurrent::run(
|
||||
[this, htmls, measurer, width, isNew]() {
|
||||
QVector<int> heights = measurer->measure(htmls, width);
|
||||
QMetaObject::invokeMethod(this, [this, heights, isNew] {
|
||||
for (int i = 0; i < qMin(heights.size(), static_cast<int>(m_chunks.size())); ++i) {
|
||||
m_chunks[i].pixelHeight = heights[i];
|
||||
m_totalPixelHeight += heights[i];
|
||||
}
|
||||
qInfo("Measured %lld chunks, total height: %f", heights.size(), m_totalPixelHeight);
|
||||
m_measuring = false;
|
||||
emit measuringChanged();
|
||||
emit totalPixelHeightChanged();
|
||||
emit dataChanged(createIndex(0, 0),
|
||||
createIndex(m_chunks.size() - 1, 0),
|
||||
{PixelHeightRole});
|
||||
|
||||
emitRestoreReady(isNew);
|
||||
}, Qt::QueuedConnection);
|
||||
});
|
||||
emitRestoreReady(isNew);
|
||||
}
|
||||
|
||||
void ReadingModel::setContentWidth(int width)
|
||||
@@ -173,7 +146,7 @@ void ReadingModel::setFontParams(int fontSize, qreal lineSpacing)
|
||||
|
||||
void ReadingModel::setImageLoader(std::unique_ptr<IImageLoader> loader)
|
||||
{
|
||||
m_imageLoader = std::move(loader);
|
||||
m_measurer.setImageLoader(std::move(loader));
|
||||
}
|
||||
|
||||
void ReadingModel::recalculateCurrentPage()
|
||||
@@ -193,59 +166,28 @@ void ReadingModel::recalculateCurrentPage()
|
||||
|
||||
void ReadingModel::rebuildPagePairs()
|
||||
{
|
||||
const int oldPairs = m_pagePairs.size();
|
||||
m_pagePairs.clear();
|
||||
const int oldPairs = m_pagination.count();
|
||||
|
||||
if (!m_isMangaMode || m_chunks.isEmpty()) {
|
||||
if (m_pagePairs.size() != oldPairs) emit totalPagePairsChanged();
|
||||
m_pagination.clear();
|
||||
if (m_pagination.count() != oldPairs) emit totalPagePairsChanged();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!m_mangaLandscape) {
|
||||
// Portrait: every chunk is its own solo pair.
|
||||
m_pagePairs.reserve(m_chunks.size());
|
||||
for (int i = 0; i < m_chunks.size(); ++i)
|
||||
m_pagePairs.append({i, -1});
|
||||
} else {
|
||||
// Landscape: cover alone, optional shift page alone, then portrait-pair the rest.
|
||||
m_pagePairs.append({0, -1}); // cover always solo
|
||||
int i = 1;
|
||||
if (m_pageShift && i < m_chunks.size()) {
|
||||
m_pagePairs.append({i, -1}); // page 1 solo when shift is ON
|
||||
++i;
|
||||
}
|
||||
while (i < m_chunks.size()) {
|
||||
const QSize sz = m_chunks[i].naturalSize;
|
||||
const bool isLandscape = sz.isValid() && sz.width() > sz.height();
|
||||
if (isLandscape) {
|
||||
m_pagePairs.append({i, -1});
|
||||
++i;
|
||||
} else {
|
||||
// Try to pair with next portrait page.
|
||||
const int next = i + 1;
|
||||
if (next < m_chunks.size()) {
|
||||
const QSize nextSz = m_chunks[next].naturalSize;
|
||||
const bool nextLandscape = nextSz.isValid() && nextSz.width() > nextSz.height();
|
||||
if (!nextLandscape) {
|
||||
m_pagePairs.append({i, next});
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
m_pagePairs.append({i, -1});
|
||||
++i;
|
||||
}
|
||||
}
|
||||
}
|
||||
QVector<QSize> sizes;
|
||||
sizes.reserve(m_chunks.size());
|
||||
for (const auto &c : m_chunks)
|
||||
sizes.append(c.naturalSize);
|
||||
m_pagination.rebuild(sizes, m_mangaLandscape, m_pageShift);
|
||||
|
||||
if (m_pagePairs.size() != oldPairs) emit totalPagePairsChanged();
|
||||
if (m_pagination.count() != oldPairs) emit totalPagePairsChanged();
|
||||
|
||||
// Sync totalPages/currentPage to pair count in manga mode.
|
||||
if (const int pairs = m_pagePairs.size(); m_totalPages != pairs) {
|
||||
if (const int pairs = m_pagination.count(); m_totalPages != pairs) {
|
||||
m_totalPages = pairs;
|
||||
emit totalPagesChanged();
|
||||
}
|
||||
if (m_currentPage == 0 && !m_pagePairs.isEmpty()) {
|
||||
if (m_currentPage == 0 && m_pagination.count() > 0) {
|
||||
m_currentPage = 1;
|
||||
emit currentPageChanged();
|
||||
}
|
||||
@@ -253,8 +195,8 @@ void ReadingModel::rebuildPagePairs()
|
||||
|
||||
QVariantList ReadingModel::pagePair(int pairIndex) const
|
||||
{
|
||||
if (pairIndex < 0 || pairIndex >= m_pagePairs.size()) return {};
|
||||
const auto &p = m_pagePairs.at(pairIndex);
|
||||
if (pairIndex < 0 || pairIndex >= m_pagination.count()) return {};
|
||||
const auto p = m_pagination.at(pairIndex);
|
||||
QVariantList list;
|
||||
list.append(p.first);
|
||||
if (p.second >= 0)
|
||||
@@ -264,23 +206,13 @@ QVariantList ReadingModel::pagePair(int pairIndex) const
|
||||
|
||||
int ReadingModel::pairIndexForChunk(int chunkIndex) const
|
||||
{
|
||||
for (int i = 0; i < m_pagePairs.size(); ++i) {
|
||||
if (m_pagePairs[i].first == chunkIndex || m_pagePairs[i].second == chunkIndex)
|
||||
return i;
|
||||
}
|
||||
return 0;
|
||||
return m_pagination.pairIndexForChunk(chunkIndex);
|
||||
}
|
||||
|
||||
QString ReadingModel::imageUrlForChunk(int chunkIndex) const
|
||||
{
|
||||
if (chunkIndex < 0 || chunkIndex >= m_chunks.size()) return {};
|
||||
const QString &html = m_chunks.at(chunkIndex).html;
|
||||
// Extract src="..." from the img tag.
|
||||
static const QRegularExpression re(QStringLiteral("<img\\s[^>]*src=\"([^\"]+)\""));
|
||||
const auto match = re.match(html);
|
||||
if (match.hasMatch())
|
||||
return match.captured(1);
|
||||
return {};
|
||||
return m_chunks.at(chunkIndex).imageUrl;
|
||||
}
|
||||
|
||||
void ReadingModel::setMangaLandscape(bool landscape)
|
||||
@@ -294,16 +226,9 @@ void ReadingModel::setPageShift(bool shift, int currentPairIndex)
|
||||
{
|
||||
if (m_pageShift == shift) return;
|
||||
|
||||
// Pick an anchor chunk that keeps an image on screen across the rebuild AND keeps
|
||||
// back-and-forth toggling stable (no cumulative drift):
|
||||
// - turning shift ON: anchor on the higher-index chunk (.second).
|
||||
// - turning shift OFF: anchor on the lower-index chunk (.first).
|
||||
// For solo pairs (cover, wide spread) fall back to .first.
|
||||
int currentChunk = 0;
|
||||
if (currentPairIndex >= 0 && currentPairIndex < m_pagePairs.size()) {
|
||||
const auto &pair = m_pagePairs.at(currentPairIndex);
|
||||
currentChunk = (shift && pair.second >= 0) ? pair.second : pair.first;
|
||||
}
|
||||
// Anchor on a chunk that keeps an image on screen across the rebuild and
|
||||
// keeps back-and-forth toggling stable (see MangaPagination for the rule).
|
||||
const int currentChunk = m_pagination.anchorChunkForShiftToggle(currentPairIndex, shift);
|
||||
|
||||
m_pageShift = shift;
|
||||
rebuildPagePairs();
|
||||
@@ -333,6 +258,14 @@ void ReadingModel::setMangaRTL(bool rtl)
|
||||
emit mangaRTLChanged();
|
||||
}
|
||||
|
||||
// Extract src="..." from a chunk's img tag, done once at load time.
|
||||
static QString extractImageUrl(const QString &html)
|
||||
{
|
||||
static const QRegularExpression re(QStringLiteral("<img\\s[^>]*src=\"([^\"]+)\""));
|
||||
const auto match = re.match(html);
|
||||
return match.hasMatch() ? match.captured(1) : QString();
|
||||
}
|
||||
|
||||
void ReadingModel::loadAllChapters()
|
||||
{
|
||||
beginResetModel();
|
||||
@@ -352,7 +285,8 @@ void ReadingModel::loadAllChapters()
|
||||
QString coverHtml = QStringLiteral("<div class=\"cover-image\" style=\"text-align: center; margin: 2em 0;\">")
|
||||
+ QStringLiteral("<img src=\"") + m_coverImageUrl
|
||||
+ QStringLiteral("\" style=\"max-width: 100%; max-height: 80vh;\" /></div>");
|
||||
m_chunks.push_back({coverHtml, 0, -1, -1, QSize()}); // chunkInChapter=-1 = cover sentinel
|
||||
m_chunks.push_back({coverHtml, 0, -1, -1, QSize(),
|
||||
extractImageUrl(coverHtml)}); // chunkInChapter=-1 = cover sentinel
|
||||
m_chapterStartIndices.append(1); // chapter 0 starts after cover
|
||||
} else {
|
||||
m_chapterStartIndices.append(0);
|
||||
@@ -366,7 +300,7 @@ void ReadingModel::loadAllChapters()
|
||||
int j = 0;
|
||||
for (const auto &html : chapter.contentChunks) {
|
||||
const QSize sz = (j < sizes.size()) ? sizes[j] : QSize();
|
||||
m_chunks.push_back({html, i, j, -1, sz});
|
||||
m_chunks.push_back({html, i, j, -1, sz, extractImageUrl(html)});
|
||||
++j;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
#define READINGMODEL_H
|
||||
|
||||
#include <QAbstractListModel>
|
||||
#include <QFuture>
|
||||
#include <QPair>
|
||||
#include <QSize>
|
||||
#include <QString>
|
||||
#include <QVector>
|
||||
#include <memory>
|
||||
#include "IImageLoader.h"
|
||||
#include "reading/MangaPagination.h"
|
||||
#include "reading/MeasurementController.h"
|
||||
#include "state/BookPositionStore.h"
|
||||
|
||||
class FormatReader;
|
||||
@@ -19,6 +19,7 @@ struct ContentChunk {
|
||||
int chunkInChapter = 0; // 0-based index within chapter (-1 for cover)
|
||||
int pixelHeight = -1; // -1 = not yet measured
|
||||
QSize naturalSize; // image pixel dimensions (null for text chunks)
|
||||
QString imageUrl; // src of the chunk's img tag (empty for text chunks)
|
||||
};
|
||||
|
||||
class ReadingModel : public QAbstractListModel {
|
||||
@@ -114,13 +115,15 @@ signals:
|
||||
|
||||
void restoreReady(int chunkIndex, int intraChunkOffset);
|
||||
|
||||
private slots:
|
||||
void onHeightsReady(const QVector<int> &heights, bool isNew);
|
||||
|
||||
private:
|
||||
static constexpr qreal page_ratio = 1.5;
|
||||
|
||||
void loadAllChapters();
|
||||
void recalculateCurrentPage();
|
||||
void rebuildPagePairs();
|
||||
void runMeasurement(const QStringList &htmls, bool isNew);
|
||||
void emitRestoreReady(bool isNew);
|
||||
|
||||
FormatReader *m_reader = nullptr;
|
||||
@@ -129,7 +132,6 @@ private:
|
||||
int m_totalChapters = 0;
|
||||
int m_currentPage = 0;
|
||||
int m_totalPages = 0;
|
||||
bool m_measuring = false;
|
||||
bool m_isMangaMode = false;
|
||||
bool m_mangaLandscape = false;
|
||||
bool m_pageShift = true;
|
||||
@@ -139,9 +141,8 @@ private:
|
||||
QVector<int> m_chapterStartIndices;
|
||||
QVector<QString> m_chapterTitles;
|
||||
|
||||
// Manga page pairs: each QPair holds (leftChunkIdx, rightChunkIdx) where rightChunkIdx
|
||||
// may be -1 for solo pages. In RTL mode the "left" slot is the later page visually.
|
||||
QVector<QPair<int,int>> m_pagePairs;
|
||||
// Manga page-pair layout. In RTL mode the "left" slot is the later page visually.
|
||||
MangaPagination m_pagination;
|
||||
|
||||
qreal m_totalPixelHeight = 0.0;
|
||||
qreal m_yOffset = 0.0;
|
||||
@@ -150,8 +151,7 @@ private:
|
||||
qreal m_lineSpacing = 0;
|
||||
|
||||
BookPositionStore &m_positions;
|
||||
std::unique_ptr<IImageLoader> m_imageLoader;
|
||||
QFuture<void> m_measureFuture;
|
||||
MeasurementController m_measurer;
|
||||
};
|
||||
|
||||
#endif // READINGMODEL_H
|
||||
+18
-37
@@ -1,16 +1,17 @@
|
||||
#include "Book.h"
|
||||
#include <QtConcurrent>
|
||||
#include <QFileInfo>
|
||||
#include <QSet>
|
||||
|
||||
#include "backend/formats/ImageExtensions.h"
|
||||
|
||||
Book::Book(IFileDialogService &dialog,
|
||||
BookPositionStore &positions,
|
||||
ReaderFactory &factory,
|
||||
FormatRegistry ®istry,
|
||||
QObject *parent)
|
||||
: QObject(parent)
|
||||
, m_dialog(dialog)
|
||||
, m_positions(positions)
|
||||
, m_factory(factory)
|
||||
, m_registry(registry)
|
||||
{
|
||||
connect(&m_dialog, &IFileDialogService::fileSelected,
|
||||
this, &Book::openFromPath);
|
||||
@@ -28,7 +29,6 @@ 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::renderingMode() const { return m_renderingMode; }
|
||||
|
||||
QString Book::title() const { return m_reader ? m_reader->title() : QString(); }
|
||||
QString Book::author() const { return m_reader ? m_reader->author() : QString(); }
|
||||
@@ -61,16 +61,10 @@ void Book::openFromPath(const QString &path)
|
||||
openImpl(path);
|
||||
}
|
||||
|
||||
static const QSet<QString> kImageExtensions = {
|
||||
QStringLiteral("jpg"), QStringLiteral("jpeg"),
|
||||
QStringLiteral("png"), QStringLiteral("gif"),
|
||||
QStringLiteral("webp")
|
||||
};
|
||||
|
||||
void Book::browseAndOpen()
|
||||
{
|
||||
QStringList exts = m_factory.supportedExtensions();
|
||||
for (const QString &e : kImageExtensions)
|
||||
QStringList exts = m_registry.supportedExtensions();
|
||||
for (const QString &e : imageFileExtensions())
|
||||
if (!exts.contains(e)) exts << e;
|
||||
m_dialog.open(exts);
|
||||
}
|
||||
@@ -79,7 +73,7 @@ void Book::openImpl(const QString &filePath)
|
||||
{
|
||||
// Opening a standalone image file triggers folder-comic mode for its parent directory.
|
||||
const QFileInfo fi(filePath);
|
||||
const QString effectivePath = (!fi.isDir() && kImageExtensions.contains(fi.suffix().toLower()))
|
||||
const QString effectivePath = (!fi.isDir() && imageFileExtensions().contains(fi.suffix().toLower()))
|
||||
? fi.absolutePath()
|
||||
: filePath;
|
||||
|
||||
@@ -97,21 +91,7 @@ void Book::openImpl(const QString &filePath)
|
||||
const int generation = ++m_openGeneration;
|
||||
|
||||
m_openFuture = QtConcurrent::run([this, effectivePath, generation]() {
|
||||
auto reader = m_factory.create(effectivePath);
|
||||
if (!reader) {
|
||||
QMetaObject::invokeMethod(this, [this, generation, effectivePath]() {
|
||||
if (generation != m_openGeneration) return;
|
||||
m_loading = false;
|
||||
emit loadingChanged();
|
||||
m_errorMessage = QStringLiteral("No format reader available for this file type");
|
||||
qWarning() << "Book load failed:" << effectivePath << "—" << m_errorMessage;
|
||||
emit errorMessageChanged();
|
||||
}, Qt::QueuedConnection);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!reader->open(effectivePath)) {
|
||||
const QString err = reader->lastError();
|
||||
const auto reportError = [this, generation, effectivePath](const QString &err) {
|
||||
QMetaObject::invokeMethod(this, [this, generation, effectivePath, err]() {
|
||||
if (generation != m_openGeneration) return;
|
||||
m_loading = false;
|
||||
@@ -120,6 +100,16 @@ void Book::openImpl(const QString &filePath)
|
||||
qWarning() << "Book load failed:" << effectivePath << "—" << m_errorMessage;
|
||||
emit errorMessageChanged();
|
||||
}, Qt::QueuedConnection);
|
||||
};
|
||||
|
||||
auto reader = m_registry.createReader(effectivePath);
|
||||
if (!reader) {
|
||||
reportError(QStringLiteral("No format reader available for this file type"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!reader->open(effectivePath)) {
|
||||
reportError(reader->lastError());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -132,14 +122,8 @@ void Book::openImpl(const QString &filePath)
|
||||
m_coverImageUrl.clear();
|
||||
m_loading = false;
|
||||
|
||||
const QString newMode = (m_reader->preferredRenderingMode() == FormatReader::RenderingMode::Manga)
|
||||
? QStringLiteral("manga") : QStringLiteral("scroll");
|
||||
const bool modeChanged = (newMode != m_renderingMode);
|
||||
m_renderingMode = newMode;
|
||||
|
||||
emit loadingChanged();
|
||||
emit bookChanged();
|
||||
if (modeChanged) emit renderingModeChanged();
|
||||
}, Qt::QueuedConnection);
|
||||
});
|
||||
}
|
||||
@@ -149,10 +133,7 @@ void Book::close()
|
||||
if (!m_reader) return;
|
||||
m_reader.reset();
|
||||
m_coverImageUrl.clear();
|
||||
const bool modeChanged = (m_renderingMode != QStringLiteral("scroll"));
|
||||
m_renderingMode = QStringLiteral("scroll");
|
||||
emit bookChanged();
|
||||
if (modeChanged) emit renderingModeChanged();
|
||||
}
|
||||
|
||||
void Book::clearError()
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
#include "backend/FormatReader.h"
|
||||
#include "backend/IFileDialogService.h"
|
||||
#include "backend/formats/ReaderFactory.h"
|
||||
#include "backend/formats/FormatRegistry.h"
|
||||
#include "backend/state/BookPositionStore.h"
|
||||
|
||||
class Book : public QObject {
|
||||
@@ -23,11 +23,10 @@ class Book : public QObject {
|
||||
Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY bookChanged)
|
||||
Q_PROPERTY(QList<TocEntry> toc READ toc NOTIFY bookChanged)
|
||||
Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorMessageChanged)
|
||||
Q_PROPERTY(QString renderingMode READ renderingMode NOTIFY renderingModeChanged)
|
||||
public:
|
||||
Book(IFileDialogService &dialog,
|
||||
BookPositionStore &positions,
|
||||
ReaderFactory &factory,
|
||||
FormatRegistry ®istry,
|
||||
QObject *parent = nullptr);
|
||||
~Book() override;
|
||||
|
||||
@@ -39,9 +38,8 @@ public:
|
||||
QString coverImageUrl() const;
|
||||
QList<TocEntry> toc() const;
|
||||
QString errorMessage() const;
|
||||
QString renderingMode() const;
|
||||
|
||||
// Called by main.cpp's bookChanged lambda after the image provider resolves the cover URL.
|
||||
// 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).
|
||||
@@ -69,7 +67,6 @@ signals:
|
||||
void bookChanged();
|
||||
void loadingChanged();
|
||||
void errorMessageChanged();
|
||||
void renderingModeChanged();
|
||||
void contentWidthChanged(int width);
|
||||
|
||||
private:
|
||||
@@ -77,11 +74,10 @@ private:
|
||||
|
||||
IFileDialogService &m_dialog;
|
||||
BookPositionStore &m_positions;
|
||||
ReaderFactory &m_factory;
|
||||
FormatRegistry &m_registry;
|
||||
std::unique_ptr<FormatReader> m_reader;
|
||||
QString m_coverImageUrl;
|
||||
QString m_errorMessage;
|
||||
QString m_renderingMode = QStringLiteral("scroll");
|
||||
bool m_loading = false;
|
||||
int m_openGeneration = 0;
|
||||
int m_contentWidth = 0;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#include "AsyncImageResponse.h"
|
||||
|
||||
#include <QQuickTextureFactory>
|
||||
|
||||
AsyncImageResponse::AsyncImageResponse(std::function<QImage()> job)
|
||||
: m_job(std::move(job))
|
||||
{
|
||||
setAutoDelete(false);
|
||||
}
|
||||
|
||||
QQuickTextureFactory *AsyncImageResponse::textureFactory() const
|
||||
{
|
||||
if (m_image.isNull())
|
||||
return nullptr;
|
||||
return QQuickTextureFactory::textureFactoryForImage(m_image);
|
||||
}
|
||||
|
||||
void AsyncImageResponse::cancel()
|
||||
{
|
||||
m_cancelled.storeRelaxed(1);
|
||||
}
|
||||
|
||||
void AsyncImageResponse::run()
|
||||
{
|
||||
if (m_cancelled.loadRelaxed())
|
||||
return;
|
||||
|
||||
m_image = m_job();
|
||||
|
||||
if (m_cancelled.loadRelaxed())
|
||||
return;
|
||||
|
||||
emit finished();
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <QAtomicInt>
|
||||
#include <QImage>
|
||||
#include <QQuickImageResponse>
|
||||
#include <QRunnable>
|
||||
|
||||
// Generic async image response: runs the given job on a thread pool and
|
||||
// publishes the resulting image. Shared by all image providers.
|
||||
class AsyncImageResponse : public QQuickImageResponse, public QRunnable {
|
||||
// NO Q_OBJECT — already inherited from QQuickImageResponse
|
||||
public:
|
||||
explicit AsyncImageResponse(std::function<QImage()> job);
|
||||
|
||||
QQuickTextureFactory *textureFactory() const override;
|
||||
void cancel() override;
|
||||
void run() override;
|
||||
|
||||
private:
|
||||
std::function<QImage()> m_job;
|
||||
QAtomicInt m_cancelled{0};
|
||||
QImage m_image;
|
||||
};
|
||||
@@ -0,0 +1,128 @@
|
||||
#include "EntryImageProvider.h"
|
||||
|
||||
#include <QImage>
|
||||
#include <QMutexLocker>
|
||||
#include <QThreadPool>
|
||||
#include <QUrl>
|
||||
|
||||
#include "AsyncImageResponse.h"
|
||||
#include "ImageScaling.h"
|
||||
#include "ImageUrl.h"
|
||||
|
||||
QImage EntryImageProvider::loadImageFromSource(IByteSource &source,
|
||||
const QString &entryName,
|
||||
int displayWidth,
|
||||
const QSize &requestedSize)
|
||||
{
|
||||
if (entryName.isEmpty())
|
||||
return {};
|
||||
|
||||
const QByteArray data = source.readEntry(entryName);
|
||||
if (data.isEmpty())
|
||||
return {};
|
||||
|
||||
QImage image;
|
||||
if (!image.loadFromData(data))
|
||||
return {};
|
||||
|
||||
return scaleToFit(image, displayWidth, requestedSize);
|
||||
}
|
||||
|
||||
EntryImageProvider::EntryImageProvider(SourceFactory sourceFactory, QString scheme)
|
||||
: m_sourceFactory(std::move(sourceFactory))
|
||||
, m_scheme(std::move(scheme))
|
||||
{
|
||||
}
|
||||
|
||||
QQuickImageResponse *EntryImageProvider::requestImageResponse(const QString &id,
|
||||
const QSize &requestedSize)
|
||||
{
|
||||
QString sourcePath;
|
||||
int displayWidth;
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
sourcePath = m_sourcePath;
|
||||
displayWidth = m_displayWidth;
|
||||
}
|
||||
|
||||
// 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;
|
||||
|
||||
auto *response = new AsyncImageResponse(
|
||||
[factory = m_sourceFactory, sourcePath, entryName, displayWidth, requestedSize]() -> QImage {
|
||||
auto source = factory();
|
||||
if (!source->open(sourcePath))
|
||||
return {};
|
||||
return loadImageFromSource(*source, entryName, displayWidth, requestedSize);
|
||||
});
|
||||
QThreadPool::globalInstance()->start(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
QImage EntryImageProvider::load(const QUrl &url, int maxWidth) const
|
||||
{
|
||||
if (url.scheme() != QLatin1String("image"))
|
||||
return {};
|
||||
|
||||
const ImageUrl::Parsed parsed = ImageUrl::parseImageUrl(url);
|
||||
const QString entryName = parsed.entry;
|
||||
if (entryName.isEmpty())
|
||||
return {};
|
||||
|
||||
QString sourcePath = parsed.sourcePath;
|
||||
if (sourcePath.isEmpty()) {
|
||||
QMutexLocker lock(&m_mutex);
|
||||
sourcePath = m_sourcePath;
|
||||
}
|
||||
|
||||
auto source = m_sourceFactory();
|
||||
if (!source->open(sourcePath))
|
||||
return {};
|
||||
return loadImageFromSource(*source, entryName, maxWidth, {});
|
||||
}
|
||||
|
||||
std::unique_ptr<IImageLoader> EntryImageProvider::clone() const
|
||||
{
|
||||
QString sourcePath;
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
sourcePath = m_sourcePath;
|
||||
}
|
||||
auto c = std::make_unique<EntryImageProvider>(m_sourceFactory, m_scheme);
|
||||
c->setFilePath(sourcePath);
|
||||
return c;
|
||||
}
|
||||
|
||||
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::setDisplayWidth(int width)
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
m_displayWidth = width;
|
||||
}
|
||||
|
||||
void EntryImageProvider::clear()
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
m_sourcePath.clear();
|
||||
m_displayWidth = 0;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include "IByteSource.h"
|
||||
#include "backend/IImageLoader.h"
|
||||
#include "backend/IImageProvider.h"
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <QMutex>
|
||||
#include <QString>
|
||||
|
||||
class EntryImageProvider : public IImageProvider, public IImageLoader {
|
||||
public:
|
||||
using SourceFactory = std::function<std::unique_ptr<IByteSource>()>;
|
||||
|
||||
EntryImageProvider(SourceFactory sourceFactory, QString scheme);
|
||||
|
||||
QQuickImageResponse *requestImageResponse(const QString &id,
|
||||
const QSize &requestedSize) override;
|
||||
|
||||
void setFilePath(const QString &filePath) override;
|
||||
void setDisplayWidth(int width) override;
|
||||
void clear() override;
|
||||
QString coverImageUrl(const QString &coverPath) const override;
|
||||
QString scheme() const override;
|
||||
|
||||
QImage load(const QUrl &url, int maxWidth) const override;
|
||||
std::unique_ptr<IImageLoader> clone() const override;
|
||||
|
||||
static QImage loadImageFromSource(IByteSource &source,
|
||||
const QString &entryName,
|
||||
int displayWidth,
|
||||
const QSize &requestedSize);
|
||||
|
||||
private:
|
||||
SourceFactory m_sourceFactory;
|
||||
QString m_scheme;
|
||||
mutable QMutex m_mutex;
|
||||
QString m_sourcePath;
|
||||
int m_displayWidth = 0;
|
||||
};
|
||||
@@ -1,202 +0,0 @@
|
||||
#include "EpubImageProvider.h"
|
||||
|
||||
#include <QImage>
|
||||
#include <QMutexLocker>
|
||||
#include <QQuickTextureFactory>
|
||||
#include <QThreadPool>
|
||||
#include <QUrl>
|
||||
|
||||
#include <minizip/unzip.h>
|
||||
|
||||
#include "backend/ZipUtils.h"
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// EpubImageResponse
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
EpubImageResponse::EpubImageResponse(const QString &epubPath, const QString &id,
|
||||
int displayWidth, const QSize &requestedSize)
|
||||
: m_epubPath(epubPath)
|
||||
, m_id(id)
|
||||
, m_displayWidth(displayWidth)
|
||||
, m_requestedSize(requestedSize)
|
||||
{
|
||||
setAutoDelete(false);
|
||||
}
|
||||
|
||||
QQuickTextureFactory *EpubImageResponse::textureFactory() const
|
||||
{
|
||||
if (m_image.isNull())
|
||||
return nullptr;
|
||||
return QQuickTextureFactory::textureFactoryForImage(m_image);
|
||||
}
|
||||
|
||||
void EpubImageResponse::cancel()
|
||||
{
|
||||
m_cancelled.storeRelaxed(1);
|
||||
}
|
||||
|
||||
void EpubImageResponse::run()
|
||||
{
|
||||
if (m_cancelled.loadRelaxed())
|
||||
return;
|
||||
|
||||
m_image = EpubImageProvider::loadImageFromEpub(
|
||||
m_epubPath, m_id, m_displayWidth, m_requestedSize);
|
||||
|
||||
if (m_cancelled.loadRelaxed())
|
||||
return;
|
||||
|
||||
emit finished();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// EpubImageProvider
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
QQuickImageResponse *EpubImageProvider::requestImageResponse(const QString &id,
|
||||
const QSize &requestedSize)
|
||||
{
|
||||
QString epubPath;
|
||||
int displayWidth;
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
epubPath = m_epubPath;
|
||||
displayWidth = m_displayWidth;
|
||||
}
|
||||
|
||||
// id may be "internal/path.jpg" (old format) or
|
||||
// "internal/path.jpg?epub=<percent-encoded-epub-path>" (new embedded format).
|
||||
QString internalPath = id;
|
||||
const int qmark = id.indexOf(QLatin1Char('?'));
|
||||
if (qmark >= 0) {
|
||||
internalPath = id.left(qmark);
|
||||
const QString query = id.mid(qmark + 1);
|
||||
// Parse epub=<value> from query string
|
||||
const QLatin1String key("epub=");
|
||||
if (query.startsWith(key))
|
||||
epubPath = QUrl::fromPercentEncoding(query.mid(key.size()).toUtf8());
|
||||
}
|
||||
|
||||
auto *response = new EpubImageResponse(epubPath, internalPath, displayWidth, requestedSize);
|
||||
QThreadPool::globalInstance()->start(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
QImage EpubImageProvider::loadImageFromEpub(const QString &epubPath, const QString &id,
|
||||
int displayWidth, const QSize &requestedSize)
|
||||
{
|
||||
if (epubPath.isEmpty())
|
||||
return {};
|
||||
|
||||
unzFile zf = unzOpen(epubPath.toUtf8().constData());
|
||||
if (!zf)
|
||||
return {};
|
||||
|
||||
const QByteArray data = ZipUtils::readZipEntry(zf, id.toUtf8().constData());
|
||||
unzClose(zf);
|
||||
|
||||
if (data.isEmpty())
|
||||
return {};
|
||||
|
||||
QImage image;
|
||||
if (!image.loadFromData(data))
|
||||
return {};
|
||||
|
||||
// Sizing logic: honor EPUB explicit dimensions, scale down to fit display width otherwise
|
||||
if (requestedSize.width() > 0 || requestedSize.height() > 0) {
|
||||
int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1;
|
||||
int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1;
|
||||
|
||||
// Clamp to display width
|
||||
if (displayWidth > 0 && targetW > 0 && targetW > displayWidth)
|
||||
targetW = displayWidth;
|
||||
|
||||
if (targetW > 0 && targetH > 0) {
|
||||
image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio,
|
||||
Qt::SmoothTransformation);
|
||||
} else if (targetW > 0) {
|
||||
image = image.scaledToWidth(targetW, Qt::SmoothTransformation);
|
||||
} else {
|
||||
image = image.scaledToHeight(targetH, Qt::SmoothTransformation);
|
||||
}
|
||||
} else {
|
||||
// No EPUB hints: scale down if wider than display, never enlarge
|
||||
if (displayWidth > 0 && image.width() > displayWidth)
|
||||
image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation);
|
||||
}
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
QImage EpubImageProvider::load(const QUrl &url, int maxWidth) const
|
||||
{
|
||||
if (url.scheme() != QLatin1String("image"))
|
||||
return {};
|
||||
|
||||
QString zipPath = url.path();
|
||||
if (zipPath.startsWith(QLatin1Char('/')))
|
||||
zipPath = zipPath.mid(1);
|
||||
if (zipPath.isEmpty())
|
||||
return {};
|
||||
|
||||
QString epubPath;
|
||||
if (url.hasQuery()) {
|
||||
// Embedded format: epub path is in the query string as epub=<encoded>
|
||||
const QString q = url.query();
|
||||
const QLatin1String key("epub=");
|
||||
if (q.startsWith(key))
|
||||
epubPath = QUrl::fromPercentEncoding(q.mid(key.size()).toUtf8());
|
||||
}
|
||||
if (epubPath.isEmpty()) {
|
||||
QMutexLocker lock(&m_mutex);
|
||||
epubPath = m_epubPath;
|
||||
}
|
||||
|
||||
return loadImageFromEpub(epubPath, zipPath, maxWidth, {});
|
||||
}
|
||||
|
||||
std::unique_ptr<IImageLoader> EpubImageProvider::clone() const
|
||||
{
|
||||
QString epubPath;
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
epubPath = m_epubPath;
|
||||
}
|
||||
auto c = std::make_unique<EpubImageProvider>();
|
||||
c->setFilePath(epubPath);
|
||||
return c;
|
||||
}
|
||||
|
||||
void EpubImageProvider::setFilePath(const QString &filePath)
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
m_epubPath = filePath;
|
||||
}
|
||||
|
||||
QString EpubImageProvider::coverImageUrl(const QString &coverPath) const
|
||||
{
|
||||
QString epubPath;
|
||||
{ QMutexLocker lock(&m_mutex); epubPath = m_epubPath; }
|
||||
return QStringLiteral("image://epub/") + coverPath
|
||||
+ QStringLiteral("?epub=")
|
||||
+ QString::fromUtf8(QUrl::toPercentEncoding(epubPath));
|
||||
}
|
||||
|
||||
QString EpubImageProvider::scheme() const
|
||||
{
|
||||
return QStringLiteral("epub");
|
||||
}
|
||||
|
||||
void EpubImageProvider::setDisplayWidth(int width)
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
m_displayWidth = width;
|
||||
}
|
||||
|
||||
void EpubImageProvider::clear()
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
m_epubPath.clear();
|
||||
m_displayWidth = 0;
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <QMutex>
|
||||
#include <QRunnable>
|
||||
#include <QString>
|
||||
|
||||
#include "backend/IImageLoader.h"
|
||||
#include "backend/IImageProvider.h"
|
||||
|
||||
class EpubImageResponse : public QQuickImageResponse, public QRunnable {
|
||||
// NO Q_OBJECT — already inherited from QQuickImageResponse
|
||||
public:
|
||||
EpubImageResponse(const QString &epubPath, const QString &id,
|
||||
int displayWidth, const QSize &requestedSize);
|
||||
|
||||
QQuickTextureFactory *textureFactory() const override;
|
||||
void cancel() override;
|
||||
void run() override;
|
||||
|
||||
private:
|
||||
const QString m_epubPath;
|
||||
const QString m_id;
|
||||
const int m_displayWidth;
|
||||
const QSize m_requestedSize;
|
||||
QAtomicInt m_cancelled{0};
|
||||
QImage m_image;
|
||||
};
|
||||
|
||||
class EpubImageProvider : public IImageProvider, public IImageLoader {
|
||||
public:
|
||||
QQuickImageResponse *requestImageResponse(const QString &id,
|
||||
const QSize &requestedSize) override;
|
||||
|
||||
void setFilePath(const QString &filePath) override;
|
||||
void setDisplayWidth(int width) override;
|
||||
void clear() override;
|
||||
QString coverImageUrl(const QString &coverPath) const override;
|
||||
QString scheme() const override;
|
||||
|
||||
QImage load(const QUrl &url, int maxWidth) const override;
|
||||
std::unique_ptr<IImageLoader> clone() const override;
|
||||
|
||||
static QImage loadImageFromEpub(const QString &epubPath, const QString &id,
|
||||
int displayWidth, const QSize &requestedSize);
|
||||
|
||||
private:
|
||||
mutable QMutex m_mutex;
|
||||
QString m_epubPath;
|
||||
int m_displayWidth = 0;
|
||||
};
|
||||
@@ -1,210 +0,0 @@
|
||||
#include "Fb2ImageProvider.h"
|
||||
#include "Fb2Reader.h"
|
||||
|
||||
#include <QFile>
|
||||
#include <QImage>
|
||||
#include <QMutexLocker>
|
||||
#include <QQuickTextureFactory>
|
||||
#include <QThreadPool>
|
||||
#include <QUrl>
|
||||
#include <QXmlStreamReader>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fb2ImageResponse
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
Fb2ImageResponse::Fb2ImageResponse(const QString &fb2Path, const QString &id,
|
||||
int displayWidth, const QSize &requestedSize)
|
||||
: m_fb2Path(fb2Path)
|
||||
, m_id(id)
|
||||
, m_displayWidth(displayWidth)
|
||||
, m_requestedSize(requestedSize)
|
||||
{
|
||||
setAutoDelete(false);
|
||||
}
|
||||
|
||||
QQuickTextureFactory *Fb2ImageResponse::textureFactory() const
|
||||
{
|
||||
if (m_image.isNull())
|
||||
return nullptr;
|
||||
return QQuickTextureFactory::textureFactoryForImage(m_image);
|
||||
}
|
||||
|
||||
void Fb2ImageResponse::cancel()
|
||||
{
|
||||
m_cancelled.storeRelaxed(1);
|
||||
}
|
||||
|
||||
void Fb2ImageResponse::run()
|
||||
{
|
||||
if (m_cancelled.loadRelaxed())
|
||||
return;
|
||||
|
||||
m_image = Fb2ImageProvider::loadImageFromFb2(m_fb2Path, m_id, m_displayWidth, m_requestedSize);
|
||||
|
||||
if (m_cancelled.loadRelaxed())
|
||||
return;
|
||||
|
||||
emit finished();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fb2ImageProvider
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
QImage Fb2ImageProvider::loadImageFromFb2(const QString &fb2Path, const QString &id,
|
||||
int displayWidth, const QSize &requestedSize)
|
||||
{
|
||||
if (fb2Path.isEmpty() || id.isEmpty())
|
||||
return {};
|
||||
|
||||
QFile f(fb2Path);
|
||||
if (!f.open(QIODevice::ReadOnly))
|
||||
return {};
|
||||
const QByteArray raw = f.readAll();
|
||||
f.close();
|
||||
|
||||
// Construct from decoded QString so the reader operates on pure Unicode,
|
||||
// bypassing QXmlStreamReader's own encoding detection which may fail for
|
||||
// Windows-1251 and other encodings not natively supported by Qt 6.
|
||||
QXmlStreamReader xml(Fb2Reader::decodeRawBytes(raw));
|
||||
while (!xml.atEnd()) {
|
||||
xml.readNext();
|
||||
if (!xml.isStartElement() || xml.name() != QLatin1String("binary"))
|
||||
continue;
|
||||
if (xml.attributes().value(QLatin1String("id")) != id)
|
||||
continue;
|
||||
|
||||
// Accumulate text (base64 data may span multiple character events)
|
||||
QString base64;
|
||||
while (!xml.atEnd()) {
|
||||
xml.readNext();
|
||||
if (xml.isCharacters())
|
||||
base64 += xml.text();
|
||||
else
|
||||
break;
|
||||
}
|
||||
|
||||
const QByteArray data = QByteArray::fromBase64(base64.toLatin1());
|
||||
QImage image;
|
||||
if (!image.loadFromData(data))
|
||||
return {};
|
||||
|
||||
if (requestedSize.width() > 0 || requestedSize.height() > 0) {
|
||||
int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1;
|
||||
int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1;
|
||||
if (displayWidth > 0 && targetW > 0 && targetW > displayWidth)
|
||||
targetW = displayWidth;
|
||||
if (targetW > 0 && targetH > 0)
|
||||
image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio, Qt::SmoothTransformation);
|
||||
else if (targetW > 0)
|
||||
image = image.scaledToWidth(targetW, Qt::SmoothTransformation);
|
||||
else
|
||||
image = image.scaledToHeight(targetH, Qt::SmoothTransformation);
|
||||
} else if (displayWidth > 0 && image.width() > displayWidth) {
|
||||
image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation);
|
||||
}
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
QQuickImageResponse *Fb2ImageProvider::requestImageResponse(const QString &id,
|
||||
const QSize &requestedSize)
|
||||
{
|
||||
QString fb2Path;
|
||||
int displayWidth;
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
fb2Path = m_fb2Path;
|
||||
displayWidth = m_displayWidth;
|
||||
}
|
||||
|
||||
// id may have "?fb2=<encoded-path>" appended
|
||||
QString binaryId = id;
|
||||
const int qmark = id.indexOf(QLatin1Char('?'));
|
||||
if (qmark >= 0) {
|
||||
binaryId = id.left(qmark);
|
||||
const QString query = id.mid(qmark + 1);
|
||||
const QLatin1String key("fb2=");
|
||||
if (query.startsWith(key))
|
||||
fb2Path = QUrl::fromPercentEncoding(query.mid(key.size()).toUtf8());
|
||||
}
|
||||
|
||||
auto *response = new Fb2ImageResponse(fb2Path, binaryId, displayWidth, requestedSize);
|
||||
QThreadPool::globalInstance()->start(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
QImage Fb2ImageProvider::load(const QUrl &url, int maxWidth) const
|
||||
{
|
||||
if (url.scheme() != QLatin1String("image"))
|
||||
return {};
|
||||
|
||||
QString binaryId = url.path();
|
||||
if (binaryId.startsWith(QLatin1Char('/')))
|
||||
binaryId = binaryId.mid(1);
|
||||
if (binaryId.isEmpty())
|
||||
return {};
|
||||
|
||||
QString fb2Path;
|
||||
if (url.hasQuery()) {
|
||||
const QString q = url.query();
|
||||
const QLatin1String key("fb2=");
|
||||
if (q.startsWith(key))
|
||||
fb2Path = QUrl::fromPercentEncoding(q.mid(key.size()).toUtf8());
|
||||
}
|
||||
if (fb2Path.isEmpty()) {
|
||||
QMutexLocker lock(&m_mutex);
|
||||
fb2Path = m_fb2Path;
|
||||
}
|
||||
|
||||
return loadImageFromFb2(fb2Path, binaryId, maxWidth, {});
|
||||
}
|
||||
|
||||
std::unique_ptr<IImageLoader> Fb2ImageProvider::clone() const
|
||||
{
|
||||
QString fb2Path;
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
fb2Path = m_fb2Path;
|
||||
}
|
||||
auto c = std::make_unique<Fb2ImageProvider>();
|
||||
c->setFilePath(fb2Path);
|
||||
return c;
|
||||
}
|
||||
|
||||
void Fb2ImageProvider::setFilePath(const QString &filePath)
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
m_fb2Path = filePath;
|
||||
}
|
||||
|
||||
QString Fb2ImageProvider::coverImageUrl(const QString &coverPath) const
|
||||
{
|
||||
QString fb2Path;
|
||||
{ QMutexLocker lock(&m_mutex); fb2Path = m_fb2Path; }
|
||||
return QStringLiteral("image://fb2/") + coverPath
|
||||
+ QStringLiteral("?fb2=")
|
||||
+ QString::fromUtf8(QUrl::toPercentEncoding(fb2Path));
|
||||
}
|
||||
|
||||
QString Fb2ImageProvider::scheme() const
|
||||
{
|
||||
return QStringLiteral("fb2");
|
||||
}
|
||||
|
||||
void Fb2ImageProvider::setDisplayWidth(int width)
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
m_displayWidth = width;
|
||||
}
|
||||
|
||||
void Fb2ImageProvider::clear()
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
m_fb2Path.clear();
|
||||
m_displayWidth = 0;
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <QMutex>
|
||||
#include <QRunnable>
|
||||
#include <QString>
|
||||
|
||||
#include "backend/IImageLoader.h"
|
||||
#include "backend/IImageProvider.h"
|
||||
|
||||
class Fb2ImageResponse : public QQuickImageResponse, public QRunnable {
|
||||
// NO Q_OBJECT — already inherited from QQuickImageResponse
|
||||
public:
|
||||
Fb2ImageResponse(const QString &fb2Path, const QString &id,
|
||||
int displayWidth, const QSize &requestedSize);
|
||||
|
||||
QQuickTextureFactory *textureFactory() const override;
|
||||
void cancel() override;
|
||||
void run() override;
|
||||
|
||||
private:
|
||||
const QString m_fb2Path;
|
||||
const QString m_id;
|
||||
const int m_displayWidth;
|
||||
const QSize m_requestedSize;
|
||||
QAtomicInt m_cancelled{0};
|
||||
QImage m_image;
|
||||
};
|
||||
|
||||
class Fb2ImageProvider : public IImageProvider, public IImageLoader {
|
||||
public:
|
||||
QQuickImageResponse *requestImageResponse(const QString &id,
|
||||
const QSize &requestedSize) override;
|
||||
|
||||
void setFilePath(const QString &filePath) override;
|
||||
void setDisplayWidth(int width) override;
|
||||
void clear() override;
|
||||
QString coverImageUrl(const QString &coverPath) const override;
|
||||
QString scheme() const override;
|
||||
|
||||
QImage load(const QUrl &url, int maxWidth) const override;
|
||||
std::unique_ptr<IImageLoader> clone() const override;
|
||||
|
||||
static QImage loadImageFromFb2(const QString &fb2Path, const QString &id,
|
||||
int displayWidth, const QSize &requestedSize);
|
||||
|
||||
private:
|
||||
mutable QMutex m_mutex;
|
||||
QString m_fb2Path;
|
||||
int m_displayWidth = 0;
|
||||
};
|
||||
@@ -1,5 +1,7 @@
|
||||
#include "Fb2Reader.h"
|
||||
|
||||
#include "ImageUrl.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QDomDocument>
|
||||
#include <QFileInfo>
|
||||
@@ -247,8 +249,7 @@ bool Fb2Reader::open(const QString &filePath)
|
||||
m_title = QFileInfo(filePath).completeBaseName();
|
||||
|
||||
// Pre-compute URL suffix so body image URLs embed the file path (self-contained, encoding-safe).
|
||||
const QString urlSuffix = QStringLiteral("?fb2=")
|
||||
+ QString::fromUtf8(QUrl::toPercentEncoding(filePath));
|
||||
const QString urlSuffix = ImageUrl::querySuffix(filePath);
|
||||
|
||||
// Body sections
|
||||
for (QDomNode bodyNode = root.firstChild(); !bodyNode.isNull(); bodyNode = bodyNode.nextSibling()) {
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
#include "FormatRegistry.h"
|
||||
|
||||
#include "EntryImageProvider.h"
|
||||
#include "WebImageProvider.h"
|
||||
#include "backend/FormatReader.h"
|
||||
|
||||
#include <QFileInfo>
|
||||
#include <QQmlEngine>
|
||||
|
||||
// Dispatches load() calls to the right child loader based on the image:// host (scheme name).
|
||||
class CompositeImageLoader : public IImageLoader {
|
||||
public:
|
||||
void add(const QString &host, std::unique_ptr<IImageLoader> loader)
|
||||
{
|
||||
m_loaders.emplace_back(host, std::move(loader));
|
||||
}
|
||||
|
||||
QImage load(const QUrl &url, int maxWidth) const override
|
||||
{
|
||||
const QString host = url.host();
|
||||
for (const auto &[h, loader] : m_loaders) {
|
||||
if (h == host)
|
||||
return loader->load(url, maxWidth);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::unique_ptr<IImageLoader> clone() const override
|
||||
{
|
||||
auto c = std::make_unique<CompositeImageLoader>();
|
||||
for (const auto &[host, loader] : m_loaders)
|
||||
c->add(host, loader->clone());
|
||||
return c;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<std::pair<QString, std::unique_ptr<IImageLoader>>> m_loaders;
|
||||
};
|
||||
|
||||
FormatRegistry::FormatRegistry(QVector<FormatSpec> specs)
|
||||
: m_specs(std::move(specs))
|
||||
{
|
||||
}
|
||||
|
||||
const FormatSpec *FormatRegistry::specFor(const QString &filePath) const
|
||||
{
|
||||
const QFileInfo fi(filePath);
|
||||
const bool isDir = fi.isDir();
|
||||
const QString ext = fi.suffix().toLower();
|
||||
|
||||
for (const FormatSpec &spec : m_specs) {
|
||||
if (isDir ? spec.matchesDirectory : (!spec.matchesDirectory && spec.extension == ext))
|
||||
return &spec;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::unique_ptr<FormatReader> FormatRegistry::createReader(const QString &filePath) const
|
||||
{
|
||||
const FormatSpec *spec = specFor(filePath);
|
||||
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);
|
||||
}
|
||||
|
||||
std::unique_ptr<IImageLoader> FormatRegistry::createImageLoader(const QString &filePath) const
|
||||
{
|
||||
const FormatSpec *spec = specFor(filePath);
|
||||
if (!spec || spec->scheme.isEmpty() || !spec->makeSource)
|
||||
return nullptr;
|
||||
|
||||
auto loader = std::make_unique<EntryImageProvider>(spec->makeSource, spec->scheme);
|
||||
loader->setFilePath(filePath);
|
||||
|
||||
if (!spec->loaderIncludesWeb)
|
||||
return loader;
|
||||
|
||||
auto composite = std::make_unique<CompositeImageLoader>();
|
||||
composite->add(spec->scheme, std::move(loader));
|
||||
composite->add(QStringLiteral("web"), std::make_unique<WebImageProvider>());
|
||||
return composite;
|
||||
}
|
||||
|
||||
QStringList FormatRegistry::supportedExtensions() const
|
||||
{
|
||||
QStringList out;
|
||||
for (const FormatSpec &spec : m_specs)
|
||||
if (!spec.matchesDirectory && !spec.extension.isEmpty())
|
||||
out << spec.extension;
|
||||
return out;
|
||||
}
|
||||
|
||||
void FormatRegistry::registerImageProviders(QQmlEngine &engine) const
|
||||
{
|
||||
for (const FormatSpec &spec : m_specs)
|
||||
if (!spec.scheme.isEmpty() && spec.makeSource)
|
||||
engine.addImageProvider(spec.scheme,
|
||||
new EntryImageProvider(spec.makeSource, spec.scheme));
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QVector>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
class FormatReader;
|
||||
class IByteSource;
|
||||
class IImageLoader;
|
||||
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 {
|
||||
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
|
||||
bool loaderIncludesWeb = false; // formats whose content may reference web images (epub)
|
||||
};
|
||||
|
||||
class FormatRegistry {
|
||||
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;
|
||||
|
||||
// Synchronous loader for measurement, or nullptr for formats without images.
|
||||
std::unique_ptr<IImageLoader> createImageLoader(const QString &filePath) const;
|
||||
|
||||
QStringList supportedExtensions() const;
|
||||
|
||||
// Register one provider per scheme with the QML engine (engine takes ownership).
|
||||
void registerImageProviders(QQmlEngine &engine) const;
|
||||
|
||||
private:
|
||||
const FormatSpec *specFor(const QString &filePath) const;
|
||||
|
||||
QVector<FormatSpec> m_specs;
|
||||
};
|
||||
@@ -5,10 +5,10 @@
|
||||
#include <QStringList>
|
||||
|
||||
// Abstracts how raw image bytes are obtained from a named entry.
|
||||
// Implementations: ZipComicSource (minizip), RarComicSource (libarchive), DirComicSource (QDir/QFile).
|
||||
class IComicSource {
|
||||
// Implementations: ZipByteSource (minizip), RarByteSource (libarchive), DirByteSource (QDir/QFile).
|
||||
class IByteSource {
|
||||
public:
|
||||
virtual ~IComicSource() = default;
|
||||
virtual ~IByteSource() = default;
|
||||
|
||||
// Opens the source. After returning true, listEntries/readEntry/contentHash are valid.
|
||||
virtual bool open(const QString &path) = 0;
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include <QSet>
|
||||
#include <QString>
|
||||
|
||||
// File extensions treated as standalone images (comic pages, folder comics).
|
||||
inline const QSet<QString> &imageFileExtensions()
|
||||
{
|
||||
static const QSet<QString> kExtensions = {
|
||||
QStringLiteral("jpg"), QStringLiteral("jpeg"),
|
||||
QStringLiteral("png"), QStringLiteral("gif"),
|
||||
QStringLiteral("webp")
|
||||
};
|
||||
return kExtensions;
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
#include "ImageLoaderFactory.h"
|
||||
#include "comic/Cbz.h"
|
||||
#include "comic/Cbr.h"
|
||||
#include "comic/Folder.h"
|
||||
#include "EpubImageProvider.h"
|
||||
#include "Fb2ImageProvider.h"
|
||||
#include "WebImageProvider.h"
|
||||
#include <QFileInfo>
|
||||
|
||||
// Dispatches load() calls to the right child loader based on the image:// host (scheme name).
|
||||
class CompositeImageLoader : public IImageLoader {
|
||||
public:
|
||||
void add(const QString &host, std::unique_ptr<IImageLoader> loader)
|
||||
{
|
||||
m_loaders.emplace_back(host, std::move(loader));
|
||||
}
|
||||
|
||||
QImage load(const QUrl &url, int maxWidth) const override
|
||||
{
|
||||
const QString host = url.host();
|
||||
for (const auto &[h, loader] : m_loaders) {
|
||||
if (h == host)
|
||||
return loader->load(url, maxWidth);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::unique_ptr<IImageLoader> clone() const override
|
||||
{
|
||||
auto c = std::make_unique<CompositeImageLoader>();
|
||||
for (const auto &[host, loader] : m_loaders)
|
||||
c->add(host, loader->clone());
|
||||
return c;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<std::pair<QString, std::unique_ptr<IImageLoader>>> m_loaders;
|
||||
};
|
||||
|
||||
std::unique_ptr<IImageLoader> ImageLoaderFactory::create(const QString &filePath)
|
||||
{
|
||||
const QFileInfo fi(filePath);
|
||||
|
||||
if (fi.isDir()) {
|
||||
auto loader = std::make_unique<FolderImageProvider>();
|
||||
loader->setFilePath(filePath);
|
||||
return loader;
|
||||
}
|
||||
|
||||
const QString ext = fi.suffix().toLower();
|
||||
if (ext == QLatin1String("epub")) {
|
||||
auto composite = std::make_unique<CompositeImageLoader>();
|
||||
|
||||
auto epubLoader = std::make_unique<EpubImageProvider>();
|
||||
epubLoader->setFilePath(filePath);
|
||||
composite->add(QStringLiteral("epub"), std::move(epubLoader));
|
||||
|
||||
composite->add(QStringLiteral("web"), std::make_unique<WebImageProvider>());
|
||||
|
||||
return composite;
|
||||
}
|
||||
if (ext == QLatin1String("fb2")) {
|
||||
auto loader = std::make_unique<Fb2ImageProvider>();
|
||||
loader->setFilePath(filePath);
|
||||
return loader;
|
||||
}
|
||||
if (ext == QLatin1String("cbz")) {
|
||||
auto loader = std::make_unique<CbzImageProvider>();
|
||||
loader->setFilePath(filePath);
|
||||
return loader;
|
||||
}
|
||||
if (ext == QLatin1String("cbr")) {
|
||||
auto loader = std::make_unique<CbrImageProvider>();
|
||||
loader->setFilePath(filePath);
|
||||
return loader;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
#include <memory>
|
||||
#include <QString>
|
||||
|
||||
class IImageLoader;
|
||||
|
||||
class ImageLoaderFactory {
|
||||
public:
|
||||
// Returns a new loader for the given file format, or nullptr for formats without images.
|
||||
static std::unique_ptr<IImageLoader> create(const QString &filePath);
|
||||
};
|
||||
@@ -1,24 +0,0 @@
|
||||
#include "ImageProviderFactory.h"
|
||||
#include "comic/Cbz.h"
|
||||
#include "comic/Cbr.h"
|
||||
#include "comic/Folder.h"
|
||||
#include "EpubImageProvider.h"
|
||||
#include "Fb2ImageProvider.h"
|
||||
#include <QFileInfo>
|
||||
|
||||
IImageProvider *ImageProviderFactory::create(const QString &filePath)
|
||||
{
|
||||
const QFileInfo fi(filePath);
|
||||
if (fi.isDir())
|
||||
return new FolderImageProvider();
|
||||
const QString ext = fi.suffix().toLower();
|
||||
if (ext == QLatin1String("epub"))
|
||||
return new EpubImageProvider();
|
||||
if (ext == QLatin1String("fb2"))
|
||||
return new Fb2ImageProvider();
|
||||
if (ext == QLatin1String("cbz"))
|
||||
return new CbzImageProvider();
|
||||
if (ext == QLatin1String("cbr"))
|
||||
return new CbrImageProvider();
|
||||
return nullptr;
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
#include <QString>
|
||||
|
||||
class IImageProvider;
|
||||
|
||||
class ImageProviderFactory {
|
||||
public:
|
||||
// Returns a new provider for the given file format, or nullptr for formats without images.
|
||||
// Caller is responsible for the returned pointer's lifetime.
|
||||
static IImageProvider *create(const QString &filePath);
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include <QImage>
|
||||
#include <QSize>
|
||||
|
||||
// Honor an explicit requested size (clamped to the display width), otherwise
|
||||
// scale down to fit the display width — never enlarge.
|
||||
inline QImage scaleToFit(QImage image, int displayWidth, const QSize &requestedSize)
|
||||
{
|
||||
if (requestedSize.width() > 0 || requestedSize.height() > 0) {
|
||||
int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1;
|
||||
int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1;
|
||||
|
||||
if (displayWidth > 0 && targetW > 0 && targetW > displayWidth)
|
||||
targetW = displayWidth;
|
||||
|
||||
if (targetW > 0 && targetH > 0) {
|
||||
image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio,
|
||||
Qt::SmoothTransformation);
|
||||
} else if (targetW > 0) {
|
||||
image = image.scaledToWidth(targetW, Qt::SmoothTransformation);
|
||||
} else {
|
||||
image = image.scaledToHeight(targetH, Qt::SmoothTransformation);
|
||||
}
|
||||
} else {
|
||||
if (displayWidth > 0 && image.width() > displayWidth)
|
||||
image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#include "ImageUrl.h"
|
||||
|
||||
#include <QLatin1Char>
|
||||
#include <QLatin1String>
|
||||
|
||||
namespace {
|
||||
const QLatin1String kSrcKey("src=");
|
||||
}
|
||||
|
||||
namespace ImageUrl {
|
||||
|
||||
QString build(const QString &scheme, const QString &entry)
|
||||
{
|
||||
return QStringLiteral("image://") + scheme + QLatin1Char('/') + entry;
|
||||
}
|
||||
|
||||
QString build(const QString &scheme, const QString &entry, const QString &sourcePath)
|
||||
{
|
||||
return build(scheme, entry) + querySuffix(sourcePath);
|
||||
}
|
||||
|
||||
QString querySuffix(const QString &sourcePath)
|
||||
{
|
||||
return QStringLiteral("?src=")
|
||||
+ QString::fromUtf8(QUrl::toPercentEncoding(sourcePath));
|
||||
}
|
||||
|
||||
Parsed parseProviderId(const QString &id)
|
||||
{
|
||||
Parsed result;
|
||||
result.entry = id;
|
||||
|
||||
const int qmark = id.indexOf(QLatin1Char('?'));
|
||||
if (qmark >= 0) {
|
||||
result.entry = id.left(qmark);
|
||||
const QString query = id.mid(qmark + 1);
|
||||
if (query.startsWith(kSrcKey))
|
||||
result.sourcePath = QUrl::fromPercentEncoding(query.mid(kSrcKey.size()).toUtf8());
|
||||
}
|
||||
result.entry = QUrl::fromPercentEncoding(result.entry.toUtf8());
|
||||
return result;
|
||||
}
|
||||
|
||||
Parsed parseImageUrl(const QUrl &url)
|
||||
{
|
||||
Parsed result;
|
||||
|
||||
result.entry = url.path();
|
||||
if (result.entry.startsWith(QLatin1Char('/')))
|
||||
result.entry = result.entry.mid(1);
|
||||
|
||||
if (url.hasQuery()) {
|
||||
const QString query = url.query();
|
||||
if (query.startsWith(kSrcKey))
|
||||
result.sourcePath = QUrl::fromPercentEncoding(query.mid(kSrcKey.size()).toUtf8());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace ImageUrl
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include <QString>
|
||||
#include <QUrl>
|
||||
|
||||
// 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.
|
||||
namespace ImageUrl {
|
||||
|
||||
QString build(const QString &scheme, const QString &entry);
|
||||
QString build(const QString &scheme, const QString &entry, const QString &sourcePath);
|
||||
|
||||
// "?src=<percent-encoded-source-path>" — for appending to an existing URL.
|
||||
QString querySuffix(const QString &sourcePath);
|
||||
|
||||
struct Parsed {
|
||||
QString entry;
|
||||
QString sourcePath; // empty = use the provider's current file
|
||||
};
|
||||
|
||||
// Parse the id handed to QQuickAsyncImageProvider (scheme already stripped,
|
||||
// entry arrives percent-encoded).
|
||||
Parsed parseProviderId(const QString &id);
|
||||
|
||||
// Parse a full image:// URL (IImageLoader::load path).
|
||||
Parsed parseImageUrl(const QUrl &url);
|
||||
|
||||
} // namespace ImageUrl
|
||||
@@ -1,31 +0,0 @@
|
||||
#include "ReaderFactory.h"
|
||||
#include "backend/FormatReader.h"
|
||||
|
||||
#include <QFileInfo>
|
||||
|
||||
ReaderFactory::ReaderFactory(QList<CreatorFn> creators)
|
||||
{
|
||||
for (const auto &creator : creators) {
|
||||
auto probe = creator();
|
||||
m_registry[probe->fileType()] = creator;
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_ptr<FormatReader> ReaderFactory::create(const QString &filePath) const
|
||||
{
|
||||
const QFileInfo fi(filePath);
|
||||
const QString key = fi.isDir() ? QStringLiteral("<dir>") : fi.suffix().toLower();
|
||||
auto it = m_registry.find(key);
|
||||
if (it == m_registry.end())
|
||||
return nullptr;
|
||||
return it.value()();
|
||||
}
|
||||
|
||||
QStringList ReaderFactory::supportedExtensions() const
|
||||
{
|
||||
QStringList out;
|
||||
for (auto it = m_registry.cbegin(); it != m_registry.cend(); ++it)
|
||||
if (!it.key().startsWith(QLatin1Char('<')))
|
||||
out << it.key();
|
||||
return out;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
#ifndef READERFACTORY_H
|
||||
#define READERFACTORY_H
|
||||
|
||||
#include <QMap>
|
||||
#include <QStringList>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
class FormatReader;
|
||||
|
||||
class ReaderFactory {
|
||||
public:
|
||||
using CreatorFn = std::function<std::unique_ptr<FormatReader>()>;
|
||||
|
||||
// Constructs the factory by probing each creator via fileType() to build the registry.
|
||||
explicit ReaderFactory(QList<CreatorFn> creators);
|
||||
|
||||
std::unique_ptr<FormatReader> create(const QString &filePath) const;
|
||||
QStringList supportedExtensions() const;
|
||||
|
||||
private:
|
||||
QMap<QString, CreatorFn> m_registry; // extension -> creator
|
||||
};
|
||||
|
||||
#endif // READERFACTORY_H
|
||||
@@ -10,10 +10,12 @@
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QQuickTextureFactory>
|
||||
#include <QStandardPaths>
|
||||
#include <QThreadPool>
|
||||
|
||||
#include "AsyncImageResponse.h"
|
||||
#include "ImageScaling.h"
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -33,30 +35,6 @@ QString WebImageProvider::cacheFilePath(const QString &urlString)
|
||||
+ (ext.isEmpty() ? QString() : QLatin1Char('.') + ext);
|
||||
}
|
||||
|
||||
static QImage scaleToFit(QImage image, int displayWidth, const QSize &requestedSize)
|
||||
{
|
||||
if (requestedSize.width() > 0 || requestedSize.height() > 0) {
|
||||
int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1;
|
||||
int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1;
|
||||
|
||||
if (displayWidth > 0 && targetW > 0 && targetW > displayWidth)
|
||||
targetW = displayWidth;
|
||||
|
||||
if (targetW > 0 && targetH > 0) {
|
||||
image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio,
|
||||
Qt::SmoothTransformation);
|
||||
} else if (targetW > 0) {
|
||||
image = image.scaledToWidth(targetW, Qt::SmoothTransformation);
|
||||
} else {
|
||||
image = image.scaledToHeight(targetH, Qt::SmoothTransformation);
|
||||
}
|
||||
} else {
|
||||
if (displayWidth > 0 && image.width() > displayWidth)
|
||||
image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// WebImageProvider
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -114,44 +92,6 @@ QImage WebImageProvider::loadWebImage(const QString &urlString, int displayWidth
|
||||
return scaleToFit(image, displayWidth, requestedSize);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// WebImageResponse
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
WebImageResponse::WebImageResponse(const QString &url, int displayWidth,
|
||||
const QSize &requestedSize)
|
||||
: m_url(url)
|
||||
, m_displayWidth(displayWidth)
|
||||
, m_requestedSize(requestedSize)
|
||||
{
|
||||
setAutoDelete(false);
|
||||
}
|
||||
|
||||
QQuickTextureFactory *WebImageResponse::textureFactory() const
|
||||
{
|
||||
if (m_image.isNull())
|
||||
return nullptr;
|
||||
return QQuickTextureFactory::textureFactoryForImage(m_image);
|
||||
}
|
||||
|
||||
void WebImageResponse::cancel()
|
||||
{
|
||||
m_cancelled.storeRelaxed(1);
|
||||
}
|
||||
|
||||
void WebImageResponse::run()
|
||||
{
|
||||
if (m_cancelled.loadRelaxed())
|
||||
return;
|
||||
|
||||
m_image = WebImageProvider::loadWebImage(m_url, m_displayWidth, m_requestedSize);
|
||||
|
||||
if (m_cancelled.loadRelaxed())
|
||||
return;
|
||||
|
||||
emit finished();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// WebImageProvider — IImageProvider
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -164,7 +104,7 @@ QQuickImageResponse *WebImageProvider::requestImageResponse(const QString &id,
|
||||
// a "Cannot create children for a parent in a different thread" warning).
|
||||
// Return an empty response immediately — no network request needed.
|
||||
if (id == QLatin1String("__warmup__")) {
|
||||
auto *response = new WebImageResponse(id, 0, requestedSize);
|
||||
auto *response = new AsyncImageResponse([] { return QImage(); });
|
||||
QMetaObject::invokeMethod(response, "finished", Qt::QueuedConnection);
|
||||
return response;
|
||||
}
|
||||
@@ -174,7 +114,9 @@ QQuickImageResponse *WebImageProvider::requestImageResponse(const QString &id,
|
||||
QMutexLocker lock(&m_mutex);
|
||||
displayWidth = m_displayWidth;
|
||||
}
|
||||
auto *response = new WebImageResponse(id, displayWidth, requestedSize);
|
||||
auto *response = new AsyncImageResponse([id, displayWidth, requestedSize] {
|
||||
return loadWebImage(id, displayWidth, requestedSize);
|
||||
});
|
||||
QThreadPool::globalInstance()->start(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -1,31 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include <QAtomicInt>
|
||||
#include <QMutex>
|
||||
#include <QRunnable>
|
||||
#include <QSize>
|
||||
#include <QString>
|
||||
|
||||
#include "backend/IImageLoader.h"
|
||||
#include "backend/IImageProvider.h"
|
||||
|
||||
class WebImageResponse : public QQuickImageResponse, public QRunnable {
|
||||
// NO Q_OBJECT — already inherited from QQuickImageResponse
|
||||
public:
|
||||
WebImageResponse(const QString &url, int displayWidth, const QSize &requestedSize);
|
||||
|
||||
QQuickTextureFactory *textureFactory() const override;
|
||||
void cancel() override;
|
||||
void run() override;
|
||||
|
||||
private:
|
||||
const QString m_url;
|
||||
const int m_displayWidth;
|
||||
const QSize m_requestedSize;
|
||||
QAtomicInt m_cancelled{0};
|
||||
QImage m_image;
|
||||
};
|
||||
|
||||
class WebImageProvider : public IImageProvider, public IImageLoader {
|
||||
public:
|
||||
QQuickImageResponse *requestImageResponse(const QString &id,
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
// Cbr shells are header-only (constructors inline in Cbr.h).
|
||||
@@ -1,7 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
// Convenience header — includes both reader and provider shells.
|
||||
// Use CbrReader.h if you only need the reader (avoids Qt::Quick dependency).
|
||||
|
||||
#include "CbrReader.h"
|
||||
#include "CbrProvider.h"
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "ComicImageProvider.h"
|
||||
#include "RarComicSource.h"
|
||||
|
||||
class CbrImageProvider : public ComicImageProvider {
|
||||
public:
|
||||
CbrImageProvider()
|
||||
: ComicImageProvider([] { return std::make_unique<RarComicSource>(); },
|
||||
QStringLiteral("cbr")) {}
|
||||
};
|
||||
@@ -1,12 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include "ComicReader.h"
|
||||
#include "RarComicSource.h"
|
||||
#include "backend/formats/sources/RarByteSource.h"
|
||||
|
||||
class CbrReader : public ComicReader {
|
||||
public:
|
||||
CbrReader()
|
||||
: ComicReader([] { return std::make_unique<RarComicSource>(); },
|
||||
: ComicReader([] { return std::make_unique<RarByteSource>(); },
|
||||
QStringLiteral("cbr"),
|
||||
QStringLiteral("cbr")) {}
|
||||
};
|
||||
@@ -1 +0,0 @@
|
||||
// Cbz shells are header-only (constructors inline in Cbz.h).
|
||||
@@ -1,7 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
// Convenience header — includes both reader and provider shells.
|
||||
// Use CbzReader.h if you only need the reader (avoids Qt::Quick dependency).
|
||||
|
||||
#include "CbzReader.h"
|
||||
#include "CbzProvider.h"
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "ComicImageProvider.h"
|
||||
#include "ZipComicSource.h"
|
||||
|
||||
class CbzImageProvider : public ComicImageProvider {
|
||||
public:
|
||||
CbzImageProvider()
|
||||
: ComicImageProvider([] { return std::make_unique<ZipComicSource>(); },
|
||||
QStringLiteral("cbz")) {}
|
||||
};
|
||||
@@ -1,12 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include "ComicReader.h"
|
||||
#include "ZipComicSource.h"
|
||||
#include "backend/formats/sources/ZipByteSource.h"
|
||||
|
||||
class CbzReader : public ComicReader {
|
||||
public:
|
||||
CbzReader()
|
||||
: ComicReader([] { return std::make_unique<ZipComicSource>(); },
|
||||
: ComicReader([] { return std::make_unique<ZipByteSource>(); },
|
||||
QStringLiteral("cbz"),
|
||||
QStringLiteral("cbz")) {}
|
||||
};
|
||||
@@ -1,202 +0,0 @@
|
||||
#include "ComicImageProvider.h"
|
||||
|
||||
#include <QImage>
|
||||
#include <QMutexLocker>
|
||||
#include <QQuickTextureFactory>
|
||||
#include <QThreadPool>
|
||||
#include <QUrl>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ComicImageResponse
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
ComicImageResponse::ComicImageResponse(SourceFactory sourceFactory,
|
||||
const QString &sourcePath,
|
||||
const QString &entryName,
|
||||
int displayWidth,
|
||||
const QSize &requestedSize)
|
||||
: m_sourceFactory(std::move(sourceFactory))
|
||||
, m_sourcePath(sourcePath)
|
||||
, m_entryName(entryName)
|
||||
, m_displayWidth(displayWidth)
|
||||
, m_requestedSize(requestedSize)
|
||||
{
|
||||
setAutoDelete(false);
|
||||
}
|
||||
|
||||
QQuickTextureFactory *ComicImageResponse::textureFactory() const
|
||||
{
|
||||
if (m_image.isNull())
|
||||
return nullptr;
|
||||
return QQuickTextureFactory::textureFactoryForImage(m_image);
|
||||
}
|
||||
|
||||
void ComicImageResponse::cancel()
|
||||
{
|
||||
m_cancelled.storeRelaxed(1);
|
||||
}
|
||||
|
||||
void ComicImageResponse::run()
|
||||
{
|
||||
if (m_cancelled.loadRelaxed())
|
||||
return;
|
||||
|
||||
auto source = m_sourceFactory();
|
||||
if (source->open(m_sourcePath))
|
||||
m_image = ComicImageProvider::loadImageFromSource(*source, m_sourcePath,
|
||||
m_entryName, m_displayWidth,
|
||||
m_requestedSize);
|
||||
|
||||
if (m_cancelled.loadRelaxed())
|
||||
return;
|
||||
|
||||
emit finished();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ComicImageProvider
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
QImage ComicImageProvider::loadImageFromSource(IComicSource &source,
|
||||
const QString &/*sourcePath*/,
|
||||
const QString &entryName,
|
||||
int displayWidth,
|
||||
const QSize &requestedSize)
|
||||
{
|
||||
if (entryName.isEmpty())
|
||||
return {};
|
||||
|
||||
const QByteArray data = source.readEntry(entryName);
|
||||
if (data.isEmpty())
|
||||
return {};
|
||||
|
||||
QImage image;
|
||||
if (!image.loadFromData(data))
|
||||
return {};
|
||||
|
||||
if (requestedSize.width() > 0 || requestedSize.height() > 0) {
|
||||
int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1;
|
||||
int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1;
|
||||
if (displayWidth > 0 && targetW > 0 && targetW > displayWidth)
|
||||
targetW = displayWidth;
|
||||
if (targetW > 0 && targetH > 0)
|
||||
image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio, Qt::SmoothTransformation);
|
||||
else if (targetW > 0)
|
||||
image = image.scaledToWidth(targetW, Qt::SmoothTransformation);
|
||||
else
|
||||
image = image.scaledToHeight(targetH, Qt::SmoothTransformation);
|
||||
} else if (displayWidth > 0 && image.width() > displayWidth) {
|
||||
image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation);
|
||||
}
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
ComicImageProvider::ComicImageProvider(SourceFactory sourceFactory, QString scheme)
|
||||
: m_sourceFactory(std::move(sourceFactory))
|
||||
, m_scheme(std::move(scheme))
|
||||
{
|
||||
}
|
||||
|
||||
QQuickImageResponse *ComicImageProvider::requestImageResponse(const QString &id,
|
||||
const QSize &requestedSize)
|
||||
{
|
||||
QString sourcePath;
|
||||
int displayWidth;
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
sourcePath = m_sourcePath;
|
||||
displayWidth = m_displayWidth;
|
||||
}
|
||||
|
||||
// id may be "entry/name.jpg?src=<encoded-path>"
|
||||
QString entryName = id;
|
||||
const int qmark = id.indexOf(QLatin1Char('?'));
|
||||
if (qmark >= 0) {
|
||||
entryName = id.left(qmark);
|
||||
const QString query = id.mid(qmark + 1);
|
||||
const QLatin1String key("src=");
|
||||
if (query.startsWith(key))
|
||||
sourcePath = QUrl::fromPercentEncoding(query.mid(key.size()).toUtf8());
|
||||
}
|
||||
entryName = QUrl::fromPercentEncoding(entryName.toUtf8());
|
||||
|
||||
auto *response = new ComicImageResponse(m_sourceFactory, sourcePath, entryName,
|
||||
displayWidth, requestedSize);
|
||||
QThreadPool::globalInstance()->start(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
QImage ComicImageProvider::load(const QUrl &url, int maxWidth) const
|
||||
{
|
||||
if (url.scheme() != QLatin1String("image"))
|
||||
return {};
|
||||
|
||||
QString entryName = url.path();
|
||||
if (entryName.startsWith(QLatin1Char('/')))
|
||||
entryName = entryName.mid(1);
|
||||
if (entryName.isEmpty())
|
||||
return {};
|
||||
|
||||
QString sourcePath;
|
||||
if (url.hasQuery()) {
|
||||
const QString q = url.query();
|
||||
const QLatin1String key("src=");
|
||||
if (q.startsWith(key))
|
||||
sourcePath = QUrl::fromPercentEncoding(q.mid(key.size()).toUtf8());
|
||||
}
|
||||
if (sourcePath.isEmpty()) {
|
||||
QMutexLocker lock(&m_mutex);
|
||||
sourcePath = m_sourcePath;
|
||||
}
|
||||
|
||||
auto source = m_sourceFactory();
|
||||
if (!source->open(sourcePath))
|
||||
return {};
|
||||
return loadImageFromSource(*source, sourcePath, entryName, maxWidth, {});
|
||||
}
|
||||
|
||||
std::unique_ptr<IImageLoader> ComicImageProvider::clone() const
|
||||
{
|
||||
QString sourcePath;
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
sourcePath = m_sourcePath;
|
||||
}
|
||||
auto c = std::make_unique<ComicImageProvider>(m_sourceFactory, m_scheme);
|
||||
c->setFilePath(sourcePath);
|
||||
return c;
|
||||
}
|
||||
|
||||
void ComicImageProvider::setFilePath(const QString &filePath)
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
m_sourcePath = filePath;
|
||||
}
|
||||
|
||||
QString ComicImageProvider::coverImageUrl(const QString &coverPath) const
|
||||
{
|
||||
QString sourcePath;
|
||||
{ QMutexLocker lock(&m_mutex); sourcePath = m_sourcePath; }
|
||||
return QStringLiteral("image://") + m_scheme + QLatin1Char('/') + coverPath
|
||||
+ QStringLiteral("?src=")
|
||||
+ QString::fromUtf8(QUrl::toPercentEncoding(sourcePath));
|
||||
}
|
||||
|
||||
QString ComicImageProvider::scheme() const
|
||||
{
|
||||
return m_scheme;
|
||||
}
|
||||
|
||||
void ComicImageProvider::setDisplayWidth(int width)
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
m_displayWidth = width;
|
||||
}
|
||||
|
||||
void ComicImageProvider::clear()
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
m_sourcePath.clear();
|
||||
m_displayWidth = 0;
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "IComicSource.h"
|
||||
|
||||
#include "backend/IImageLoader.h"
|
||||
#include "backend/IImageProvider.h"
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <QAtomicInt>
|
||||
#include <QMutex>
|
||||
#include <QRunnable>
|
||||
#include <QString>
|
||||
|
||||
class ComicImageResponse : public QQuickImageResponse, public QRunnable {
|
||||
// NO Q_OBJECT — already inherited from QQuickImageResponse
|
||||
public:
|
||||
using SourceFactory = std::function<std::unique_ptr<IComicSource>()>;
|
||||
|
||||
ComicImageResponse(SourceFactory sourceFactory,
|
||||
const QString &sourcePath,
|
||||
const QString &entryName,
|
||||
int displayWidth,
|
||||
const QSize &requestedSize);
|
||||
|
||||
QQuickTextureFactory *textureFactory() const override;
|
||||
void cancel() override;
|
||||
void run() override;
|
||||
|
||||
private:
|
||||
SourceFactory m_sourceFactory;
|
||||
const QString m_sourcePath;
|
||||
const QString m_entryName;
|
||||
const int m_displayWidth;
|
||||
const QSize m_requestedSize;
|
||||
QAtomicInt m_cancelled{0};
|
||||
QImage m_image;
|
||||
};
|
||||
|
||||
class ComicImageProvider : public IImageProvider, public IImageLoader {
|
||||
public:
|
||||
using SourceFactory = std::function<std::unique_ptr<IComicSource>()>;
|
||||
|
||||
ComicImageProvider(SourceFactory sourceFactory, QString scheme);
|
||||
|
||||
QQuickImageResponse *requestImageResponse(const QString &id,
|
||||
const QSize &requestedSize) override;
|
||||
|
||||
void setFilePath(const QString &filePath) override;
|
||||
void setDisplayWidth(int width) override;
|
||||
void clear() override;
|
||||
QString coverImageUrl(const QString &coverPath) const override;
|
||||
QString scheme() const override;
|
||||
|
||||
QImage load(const QUrl &url, int maxWidth) const override;
|
||||
std::unique_ptr<IImageLoader> clone() const override;
|
||||
|
||||
static QImage loadImageFromSource(IComicSource &source,
|
||||
const QString &sourcePath,
|
||||
const QString &entryName,
|
||||
int displayWidth,
|
||||
const QSize &requestedSize);
|
||||
|
||||
private:
|
||||
SourceFactory m_sourceFactory;
|
||||
QString m_scheme;
|
||||
mutable QMutex m_mutex;
|
||||
QString m_sourcePath;
|
||||
int m_displayWidth = 0;
|
||||
};
|
||||
@@ -3,9 +3,11 @@
|
||||
#include <QBuffer>
|
||||
#include <QFileInfo>
|
||||
#include <QImageReader>
|
||||
#include <QSet>
|
||||
#include <QXmlStreamReader>
|
||||
|
||||
#include "backend/formats/ImageExtensions.h"
|
||||
#include "backend/formats/ImageUrl.h"
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ComicInfo.xml parsing
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -55,12 +57,6 @@ static void parseComicInfo(const QByteArray &data,
|
||||
// ComicReader
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static const QSet<QString> kImageExtensions = {
|
||||
QStringLiteral("jpg"), QStringLiteral("jpeg"),
|
||||
QStringLiteral("png"), QStringLiteral("gif"),
|
||||
QStringLiteral("webp")
|
||||
};
|
||||
|
||||
ComicReader::ComicReader(SourceFactory sourceFactory, QString fileType, QString scheme)
|
||||
: m_sourceFactory(std::move(sourceFactory))
|
||||
, m_fileType(std::move(fileType))
|
||||
@@ -79,7 +75,7 @@ bool ComicReader::parseSource(const QString &filePath)
|
||||
return parseOpenSource(filePath, *source);
|
||||
}
|
||||
|
||||
bool ComicReader::parseOpenSource(const QString &filePath, IComicSource &source)
|
||||
bool ComicReader::parseOpenSource(const QString &filePath, IByteSource &source)
|
||||
{
|
||||
const QStringList allEntries = source.listEntries();
|
||||
|
||||
@@ -91,7 +87,7 @@ bool ComicReader::parseOpenSource(const QString &filePath, IComicSource &source)
|
||||
? entry.section(QLatin1Char('/'), -1) : entry;
|
||||
if (baseName.startsWith(QLatin1Char('.')))
|
||||
continue;
|
||||
if (kImageExtensions.contains(QFileInfo(entry).suffix().toLower()))
|
||||
if (imageFileExtensions().contains(QFileInfo(entry).suffix().toLower()))
|
||||
imageEntries.append(entry);
|
||||
}
|
||||
imageEntries.sort();
|
||||
@@ -177,8 +173,8 @@ Chapter ComicReader::loadChapter(int index)
|
||||
chunks.reserve(m_pageEntries.size());
|
||||
for (const PageEntry &page : m_pageEntries) {
|
||||
chunks.append(QStringLiteral("<p style=\"text-align:center;margin:0\">"
|
||||
"<img src=\"image://%1/%2\"/></p>")
|
||||
.arg(m_scheme, page.entry));
|
||||
"<img src=\"%1\"/></p>")
|
||||
.arg(ImageUrl::build(m_scheme, page.entry)));
|
||||
}
|
||||
return Chapter{0, m_title, chunks};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "backend/FormatReader.h"
|
||||
#include "IComicSource.h"
|
||||
#include "backend/formats/IByteSource.h"
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
class ComicReader : public FormatReader {
|
||||
public:
|
||||
using SourceFactory = std::function<std::unique_ptr<IComicSource>()>;
|
||||
using SourceFactory = std::function<std::unique_ptr<IByteSource>()>;
|
||||
|
||||
ComicReader(SourceFactory sourceFactory, QString fileType, QString scheme);
|
||||
|
||||
@@ -40,7 +40,7 @@ private:
|
||||
};
|
||||
|
||||
bool parseSource(const QString &filePath);
|
||||
bool parseOpenSource(const QString &filePath, IComicSource &source);
|
||||
bool parseOpenSource(const QString &filePath, IByteSource &source);
|
||||
|
||||
SourceFactory m_sourceFactory;
|
||||
QString m_fileType;
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
// Folder shells are header-only (constructors inline in Folder.h).
|
||||
@@ -1,7 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
// Convenience header — includes both reader and provider shells.
|
||||
// Use FolderReader.h if you only need the reader (avoids Qt::Quick dependency).
|
||||
|
||||
#include "FolderReader.h"
|
||||
#include "FolderProvider.h"
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "ComicImageProvider.h"
|
||||
#include "DirComicSource.h"
|
||||
|
||||
class FolderImageProvider : public ComicImageProvider {
|
||||
public:
|
||||
FolderImageProvider()
|
||||
: ComicImageProvider([] { return std::make_unique<DirComicSource>(); },
|
||||
QStringLiteral("dir")) {}
|
||||
};
|
||||
@@ -1,12 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include "ComicReader.h"
|
||||
#include "DirComicSource.h"
|
||||
#include "backend/formats/sources/DirByteSource.h"
|
||||
|
||||
class FolderReader : public ComicReader {
|
||||
public:
|
||||
FolderReader()
|
||||
: ComicReader([] { return std::make_unique<DirComicSource>(); },
|
||||
QStringLiteral("<dir>"),
|
||||
: ComicReader([] { return std::make_unique<DirByteSource>(); },
|
||||
QStringLiteral("folder"),
|
||||
QStringLiteral("dir")) {}
|
||||
};
|
||||
+5
-5
@@ -1,11 +1,11 @@
|
||||
#include "DirComicSource.h"
|
||||
#include "DirByteSource.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
|
||||
bool DirComicSource::open(const QString &path)
|
||||
bool DirByteSource::open(const QString &path)
|
||||
{
|
||||
m_dir.clear();
|
||||
m_hash.clear();
|
||||
@@ -32,12 +32,12 @@ bool DirComicSource::open(const QString &path)
|
||||
return true;
|
||||
}
|
||||
|
||||
QStringList DirComicSource::listEntries() const
|
||||
QStringList DirByteSource::listEntries() const
|
||||
{
|
||||
return m_entries;
|
||||
}
|
||||
|
||||
QByteArray DirComicSource::readEntry(const QString &entryName) const
|
||||
QByteArray DirByteSource::readEntry(const QString &entryName) const
|
||||
{
|
||||
if (m_dir.isEmpty() || entryName.isEmpty())
|
||||
return {};
|
||||
@@ -47,7 +47,7 @@ QByteArray DirComicSource::readEntry(const QString &entryName) const
|
||||
return f.readAll();
|
||||
}
|
||||
|
||||
QByteArray DirComicSource::contentHash() const
|
||||
QByteArray DirByteSource::contentHash() const
|
||||
{
|
||||
return m_hash;
|
||||
}
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "IComicSource.h"
|
||||
#include "backend/formats/IByteSource.h"
|
||||
|
||||
class DirComicSource : public IComicSource {
|
||||
class DirByteSource : public IByteSource {
|
||||
public:
|
||||
bool open(const QString &path) override;
|
||||
QStringList listEntries() const override;
|
||||
@@ -0,0 +1,88 @@
|
||||
#include "Fb2ByteSource.h"
|
||||
|
||||
#include "backend/formats/Fb2Reader.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QXmlStreamReader>
|
||||
|
||||
bool Fb2ByteSource::open(const QString &path)
|
||||
{
|
||||
m_path.clear();
|
||||
m_hash.clear();
|
||||
|
||||
if (!QFileInfo::exists(path))
|
||||
return false;
|
||||
|
||||
m_path = path;
|
||||
return true;
|
||||
}
|
||||
|
||||
QByteArray Fb2ByteSource::rawBytes() const
|
||||
{
|
||||
if (m_path.isEmpty())
|
||||
return {};
|
||||
QFile f(m_path);
|
||||
if (!f.open(QIODevice::ReadOnly))
|
||||
return {};
|
||||
return f.readAll();
|
||||
}
|
||||
|
||||
QStringList Fb2ByteSource::listEntries() const
|
||||
{
|
||||
const QByteArray raw = rawBytes();
|
||||
if (raw.isEmpty())
|
||||
return {};
|
||||
|
||||
QStringList ids;
|
||||
// Decode first so parsing works for encodings Qt 6 does not natively
|
||||
// detect (e.g. Windows-1251); see Fb2Reader::decodeRawBytes.
|
||||
QXmlStreamReader xml(Fb2Reader::decodeRawBytes(raw));
|
||||
while (!xml.atEnd()) {
|
||||
xml.readNext();
|
||||
if (xml.isStartElement() && xml.name() == QLatin1String("binary"))
|
||||
ids.append(xml.attributes().value(QLatin1String("id")).toString());
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
QByteArray Fb2ByteSource::readEntry(const QString &binaryId) const
|
||||
{
|
||||
if (binaryId.isEmpty())
|
||||
return {};
|
||||
const QByteArray raw = rawBytes();
|
||||
if (raw.isEmpty())
|
||||
return {};
|
||||
|
||||
QXmlStreamReader xml(Fb2Reader::decodeRawBytes(raw));
|
||||
while (!xml.atEnd()) {
|
||||
xml.readNext();
|
||||
if (!xml.isStartElement() || xml.name() != QLatin1String("binary"))
|
||||
continue;
|
||||
if (xml.attributes().value(QLatin1String("id")) != binaryId)
|
||||
continue;
|
||||
|
||||
// Accumulate text (base64 data may span multiple character events)
|
||||
QString base64;
|
||||
while (!xml.atEnd()) {
|
||||
xml.readNext();
|
||||
if (xml.isCharacters())
|
||||
base64 += xml.text();
|
||||
else
|
||||
break;
|
||||
}
|
||||
return QByteArray::fromBase64(base64.toLatin1());
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
QByteArray Fb2ByteSource::contentHash() const
|
||||
{
|
||||
if (m_hash.isEmpty() && !m_path.isEmpty()) {
|
||||
const QByteArray raw = rawBytes();
|
||||
if (!raw.isEmpty())
|
||||
m_hash = QCryptographicHash::hash(raw, QCryptographicHash::Md5);
|
||||
}
|
||||
return m_hash;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include "backend/formats/IByteSource.h"
|
||||
|
||||
// Byte source over an FB2 document: entries are the ids of its base64
|
||||
// <binary> elements. Parsing is deferred to the calls that need it so that
|
||||
// open() stays cheap for per-request provider use.
|
||||
class Fb2ByteSource : public IByteSource {
|
||||
public:
|
||||
bool open(const QString &path) override;
|
||||
QStringList listEntries() const override;
|
||||
QByteArray readEntry(const QString &binaryId) const override;
|
||||
QByteArray contentHash() const override;
|
||||
|
||||
private:
|
||||
QByteArray rawBytes() const;
|
||||
|
||||
QString m_path;
|
||||
mutable QByteArray m_hash;
|
||||
};
|
||||
+12
-11
@@ -1,4 +1,4 @@
|
||||
#include "RarComicSource.h"
|
||||
#include "RarByteSource.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QFile>
|
||||
@@ -6,7 +6,7 @@
|
||||
#include <archive.h>
|
||||
#include <archive_entry.h>
|
||||
|
||||
bool RarComicSource::open(const QString &path)
|
||||
bool RarByteSource::open(const QString &path)
|
||||
{
|
||||
m_path.clear();
|
||||
m_hash.clear();
|
||||
@@ -30,22 +30,16 @@ bool RarComicSource::open(const QString &path)
|
||||
if (!opened || m_entries.isEmpty())
|
||||
return false;
|
||||
|
||||
QFile f(path);
|
||||
if (f.open(QIODevice::ReadOnly)) {
|
||||
m_hash = QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5);
|
||||
f.close();
|
||||
}
|
||||
|
||||
m_path = path;
|
||||
return true;
|
||||
}
|
||||
|
||||
QStringList RarComicSource::listEntries() const
|
||||
QStringList RarByteSource::listEntries() const
|
||||
{
|
||||
return m_entries;
|
||||
}
|
||||
|
||||
QByteArray RarComicSource::readEntry(const QString &entryName) const
|
||||
QByteArray RarByteSource::readEntry(const QString &entryName) const
|
||||
{
|
||||
if (m_path.isEmpty() || entryName.isEmpty())
|
||||
return {};
|
||||
@@ -79,7 +73,14 @@ QByteArray RarComicSource::readEntry(const QString &entryName) const
|
||||
return result;
|
||||
}
|
||||
|
||||
QByteArray RarComicSource::contentHash() 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);
|
||||
}
|
||||
return m_hash;
|
||||
}
|
||||
+3
-3
@@ -1,8 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "IComicSource.h"
|
||||
#include "backend/formats/IByteSource.h"
|
||||
|
||||
class RarComicSource : public IComicSource {
|
||||
class RarByteSource : public IByteSource {
|
||||
public:
|
||||
bool open(const QString &path) override;
|
||||
QStringList listEntries() const override;
|
||||
@@ -11,6 +11,6 @@ public:
|
||||
|
||||
private:
|
||||
QString m_path;
|
||||
QByteArray m_hash;
|
||||
mutable QByteArray m_hash;
|
||||
QStringList m_entries;
|
||||
};
|
||||
+12
-11
@@ -1,4 +1,4 @@
|
||||
#include "ZipComicSource.h"
|
||||
#include "ZipByteSource.h"
|
||||
|
||||
#include "backend/ZipUtils.h"
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
#include <minizip/unzip.h>
|
||||
|
||||
bool ZipComicSource::open(const QString &path)
|
||||
bool ZipByteSource::open(const QString &path)
|
||||
{
|
||||
m_path.clear();
|
||||
m_hash.clear();
|
||||
@@ -19,22 +19,16 @@ bool ZipComicSource::open(const QString &path)
|
||||
m_entries = ZipUtils::listZipEntries(zf);
|
||||
unzClose(zf);
|
||||
|
||||
QFile f(path);
|
||||
if (f.open(QIODevice::ReadOnly)) {
|
||||
m_hash = QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5);
|
||||
f.close();
|
||||
}
|
||||
|
||||
m_path = path;
|
||||
return true;
|
||||
}
|
||||
|
||||
QStringList ZipComicSource::listEntries() const
|
||||
QStringList ZipByteSource::listEntries() const
|
||||
{
|
||||
return m_entries;
|
||||
}
|
||||
|
||||
QByteArray ZipComicSource::readEntry(const QString &entryName) const
|
||||
QByteArray ZipByteSource::readEntry(const QString &entryName) const
|
||||
{
|
||||
if (m_path.isEmpty() || entryName.isEmpty())
|
||||
return {};
|
||||
@@ -46,7 +40,14 @@ QByteArray ZipComicSource::readEntry(const QString &entryName) const
|
||||
return ZipUtils::readZipEntry(zf, entryName.toUtf8().constData());
|
||||
}
|
||||
|
||||
QByteArray ZipComicSource::contentHash() const
|
||||
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);
|
||||
}
|
||||
return m_hash;
|
||||
}
|
||||
+3
-3
@@ -1,8 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "IComicSource.h"
|
||||
#include "backend/formats/IByteSource.h"
|
||||
|
||||
class ZipComicSource : public IComicSource {
|
||||
class ZipByteSource : public IByteSource {
|
||||
public:
|
||||
bool open(const QString &path) override;
|
||||
QStringList listEntries() const override;
|
||||
@@ -11,6 +11,6 @@ public:
|
||||
|
||||
private:
|
||||
QString m_path;
|
||||
QByteArray m_hash;
|
||||
mutable QByteArray m_hash;
|
||||
QStringList m_entries;
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
#include "MangaPagination.h"
|
||||
|
||||
void MangaPagination::clear()
|
||||
{
|
||||
m_pairs.clear();
|
||||
}
|
||||
|
||||
void MangaPagination::rebuild(const QVector<QSize> &naturalSizes, bool landscape, bool pageShift)
|
||||
{
|
||||
m_pairs.clear();
|
||||
if (naturalSizes.isEmpty())
|
||||
return;
|
||||
|
||||
const int count = naturalSizes.size();
|
||||
const auto isLandscapePage = [&naturalSizes](int i) {
|
||||
const QSize sz = naturalSizes.at(i);
|
||||
return sz.isValid() && sz.width() > sz.height();
|
||||
};
|
||||
|
||||
if (!landscape) {
|
||||
// Portrait: every chunk is its own solo pair.
|
||||
m_pairs.reserve(count);
|
||||
for (int i = 0; i < count; ++i)
|
||||
m_pairs.append({i, -1});
|
||||
return;
|
||||
}
|
||||
|
||||
// Landscape: cover alone, optional shift page alone, then portrait-pair the rest.
|
||||
m_pairs.append({0, -1}); // cover always solo
|
||||
int i = 1;
|
||||
if (pageShift && i < count) {
|
||||
m_pairs.append({i, -1}); // page 1 solo when shift is ON
|
||||
++i;
|
||||
}
|
||||
while (i < count) {
|
||||
if (isLandscapePage(i)) {
|
||||
m_pairs.append({i, -1});
|
||||
++i;
|
||||
} else {
|
||||
// Try to pair with next portrait page.
|
||||
const int next = i + 1;
|
||||
if (next < count && !isLandscapePage(next)) {
|
||||
m_pairs.append({i, next});
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
m_pairs.append({i, -1});
|
||||
++i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int MangaPagination::count() const
|
||||
{
|
||||
return m_pairs.size();
|
||||
}
|
||||
|
||||
MangaPagination::Pair MangaPagination::at(int pairIndex) const
|
||||
{
|
||||
if (pairIndex < 0 || pairIndex >= m_pairs.size())
|
||||
return {};
|
||||
return m_pairs.at(pairIndex);
|
||||
}
|
||||
|
||||
int MangaPagination::pairIndexForChunk(int chunkIndex) const
|
||||
{
|
||||
for (int i = 0; i < m_pairs.size(); ++i) {
|
||||
if (m_pairs[i].first == chunkIndex || m_pairs[i].second == chunkIndex)
|
||||
return i;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int MangaPagination::anchorChunkForShiftToggle(int currentPairIndex, bool shiftTurningOn) const
|
||||
{
|
||||
if (currentPairIndex < 0 || currentPairIndex >= m_pairs.size())
|
||||
return 0;
|
||||
const Pair &pair = m_pairs.at(currentPairIndex);
|
||||
return (shiftTurningOn && pair.second >= 0) ? pair.second : pair.first;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include <QSize>
|
||||
#include <QVector>
|
||||
|
||||
// Pure page-pairing logic for manga mode. Given the natural sizes of the
|
||||
// page images, decides which pages display alone and which form two-page
|
||||
// spreads. Holds no Qt object state and emits nothing — the owning model
|
||||
// drives signals and persistence.
|
||||
class MangaPagination {
|
||||
public:
|
||||
struct Pair {
|
||||
int first = -1;
|
||||
int second = -1; // -1 = solo page
|
||||
};
|
||||
|
||||
void clear();
|
||||
|
||||
// Portrait viewport: every page solo. Landscape: cover solo, optional
|
||||
// shift page solo, consecutive portrait pages paired, wide pages solo.
|
||||
void rebuild(const QVector<QSize> &naturalSizes, bool landscape, bool pageShift);
|
||||
|
||||
int count() const;
|
||||
Pair at(int pairIndex) const;
|
||||
int pairIndexForChunk(int chunkIndex) const;
|
||||
|
||||
// Chunk to keep on screen across a shift toggle. Anchoring on the
|
||||
// higher-index chunk when shift turns on (and lower when it turns off)
|
||||
// keeps repeated back-and-forth toggling stable with no drift.
|
||||
int anchorChunkForShiftToggle(int currentPairIndex, bool shiftTurningOn) const;
|
||||
|
||||
private:
|
||||
QVector<Pair> m_pairs;
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
#include "MeasurementController.h"
|
||||
|
||||
#include "backend/ChunkMeasurer.h"
|
||||
|
||||
#include <QtConcurrent>
|
||||
|
||||
MeasurementController::MeasurementController(QObject *parent)
|
||||
: QObject(parent)
|
||||
{
|
||||
}
|
||||
|
||||
MeasurementController::~MeasurementController()
|
||||
{
|
||||
if (m_future.isRunning()) {
|
||||
m_future.cancel();
|
||||
m_future.waitForFinished();
|
||||
}
|
||||
}
|
||||
|
||||
void MeasurementController::setImageLoader(std::unique_ptr<IImageLoader> loader)
|
||||
{
|
||||
m_imageLoader = std::move(loader);
|
||||
}
|
||||
|
||||
bool MeasurementController::measuring() const
|
||||
{
|
||||
return m_measuring;
|
||||
}
|
||||
|
||||
void MeasurementController::start(const QStringList &htmls, int contentWidth,
|
||||
int fontSize, qreal lineSpacing, bool isNew)
|
||||
{
|
||||
if (m_future.isRunning())
|
||||
m_future.cancel();
|
||||
|
||||
m_measuring = true;
|
||||
emit measuringChanged();
|
||||
|
||||
std::unique_ptr<IImageLoader> loaderClone = m_imageLoader ? m_imageLoader->clone() : nullptr;
|
||||
auto measurer = std::make_shared<ChunkMeasurer>(std::move(loaderClone), fontSize, lineSpacing);
|
||||
|
||||
m_future = QtConcurrent::run([this, htmls, measurer, contentWidth, isNew]() {
|
||||
QVector<int> heights = measurer->measure(htmls, contentWidth);
|
||||
QMetaObject::invokeMethod(this, [this, heights, isNew] {
|
||||
m_measuring = false;
|
||||
emit measuringChanged();
|
||||
emit heightsReady(heights, isNew);
|
||||
}, Qt::QueuedConnection);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
#include <QFuture>
|
||||
#include <QObject>
|
||||
#include <QStringList>
|
||||
#include <QVector>
|
||||
#include <memory>
|
||||
|
||||
#include "backend/IImageLoader.h"
|
||||
|
||||
// Runs chunk height measurement off the GUI thread and reports the results
|
||||
// back on it. Owns the image loader used to resolve embedded images and the
|
||||
// lifetime of the in-flight measurement.
|
||||
class MeasurementController : public QObject {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit MeasurementController(QObject *parent = nullptr);
|
||||
~MeasurementController() override;
|
||||
|
||||
void setImageLoader(std::unique_ptr<IImageLoader> loader);
|
||||
|
||||
// isNew is passed through untouched to heightsReady so the owner knows
|
||||
// whether this measurement should trigger a position restore.
|
||||
void start(const QStringList &htmls, int contentWidth,
|
||||
int fontSize, qreal lineSpacing, bool isNew);
|
||||
|
||||
bool measuring() const;
|
||||
|
||||
signals:
|
||||
void measuringChanged();
|
||||
void heightsReady(QVector<int> heights, bool isNew);
|
||||
|
||||
private:
|
||||
std::unique_ptr<IImageLoader> m_imageLoader;
|
||||
bool m_measuring = false;
|
||||
QFuture<void> m_future;
|
||||
};
|
||||
Reference in new issue
Block a user