Refactor using Fable

This commit is contained in:
Agel committed 2026-07-31 17:31:02 +02:00
1 parent 1a60a6b93c
commit 83968646c6
90 files changed
+2080 -2267

No files matched your search

@@ -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();
}
+24
View File
@@ -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;
};
+128
View File
@@ -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;
}
+41
View File
@@ -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;
};
-202
View File
@@ -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;
}
-50
View File
@@ -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;
};
-210
View File
@@ -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;
}
-50
View File
@@ -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;
};
+3 -2
View File
@@ -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()) {
+105
View File
@@ -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));
}
+49
View File
@@ -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;
+15
View File
@@ -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;
}
-11
View File
@@ -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);
};
+30
View File
@@ -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;
}
+60
View File
@@ -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
+30
View File
@@ -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
-31
View File
@@ -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;
}
-25
View File
@@ -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
+7 -65
View File
@@ -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;
}
-19
View File
@@ -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
View File
@@ -1 +0,0 @@
// Cbr shells are header-only (constructors inline in Cbr.h).
-7
View File
@@ -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"
-11
View File
@@ -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")) {}
};
+2 -2
View File
@@ -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
View File
@@ -1 +0,0 @@
// Cbz shells are header-only (constructors inline in Cbz.h).
-7
View File
@@ -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"
-11
View File
@@ -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")) {}
};
+2 -2
View File
@@ -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;
};
+7 -11
View File
@@ -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};
}
+3 -3
View File
@@ -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
View File
@@ -1 +0,0 @@
// Folder shells are header-only (constructors inline in Folder.h).
-7
View File
@@ -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")) {}
};
+3 -3
View File
@@ -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")) {}
};
@@ -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;
}
@@ -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;
};
@@ -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;
}
@@ -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;
};
@@ -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;
}
@@ -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;
};