CBR and folder formats

This commit is contained in:
Agel committed 2026-05-23 00:15:35 +02:00
1 parent e043ded6b1
commit bfc50a67b8
40 files changed
+1028 -349

No files matched your search

+3
View File
@@ -4,6 +4,7 @@
#include "formats/ImageProviderFactory.h"
#include "formats/ReaderFactory.h"
#include <QtConcurrent/QtConcurrent>
#include <QFileInfo>
#include <QUrl>
HistoryBookModel::HistoryBookModel(ReaderFactory &factory, QObject *parent)
@@ -72,6 +73,8 @@ QString HistoryBookModel::author() const
QString HistoryBookModel::format() const
{
if (QFileInfo(m_filePath).isDir())
return QStringLiteral("Folder");
return m_filePath.section('.', -1).toUpper();
}
+25 -8
View File
@@ -1,5 +1,7 @@
#include "Book.h"
#include <QtConcurrent>
#include <QFileInfo>
#include <QSet>
Book::Book(IFileDialogService &dialog,
BookPositionStore &positions,
@@ -59,13 +61,28 @@ 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()
{
m_dialog.open(m_factory.supportedExtensions());
QStringList exts = m_factory.supportedExtensions();
for (const QString &e : kImageExtensions)
if (!exts.contains(e)) exts << e;
m_dialog.open(exts);
}
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()))
? fi.absolutePath()
: filePath;
if (m_reader)
emit willOpenNewBook();
@@ -79,28 +96,28 @@ void Book::openImpl(const QString &filePath)
const int generation = ++m_openGeneration;
m_openFuture = QtConcurrent::run([this, filePath, generation]() {
auto reader = m_factory.create(filePath);
m_openFuture = QtConcurrent::run([this, effectivePath, generation]() {
auto reader = m_factory.create(effectivePath);
if (!reader) {
QMetaObject::invokeMethod(this, [this, generation, filePath]() {
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:" << filePath << "—" << m_errorMessage;
qWarning() << "Book load failed:" << effectivePath << "—" << m_errorMessage;
emit errorMessageChanged();
}, Qt::QueuedConnection);
return;
}
if (!reader->open(filePath)) {
if (!reader->open(effectivePath)) {
const QString err = reader->lastError();
QMetaObject::invokeMethod(this, [this, generation, filePath, err]() {
QMetaObject::invokeMethod(this, [this, generation, effectivePath, err]() {
if (generation != m_openGeneration) return;
m_loading = false;
emit loadingChanged();
m_errorMessage = err;
qWarning() << "Book load failed:" << filePath << "—" << m_errorMessage;
qWarning() << "Book load failed:" << effectivePath << "—" << m_errorMessage;
emit errorMessageChanged();
}, Qt::QueuedConnection);
return;
-194
View File
@@ -1,194 +0,0 @@
#include "CbzImageProvider.h"
#include "backend/ZipUtils.h"
#include <QImage>
#include <QMutexLocker>
#include <QQuickTextureFactory>
#include <QThreadPool>
#include <QUrl>
#include <minizip/unzip.h>
// ---------------------------------------------------------------------------
// CbzImageResponse
// ---------------------------------------------------------------------------
CbzImageResponse::CbzImageResponse(const QString &cbzPath, const QString &entryName,
int displayWidth, const QSize &requestedSize)
: m_cbzPath(cbzPath)
, m_entryName(entryName)
, m_displayWidth(displayWidth)
, m_requestedSize(requestedSize)
{
setAutoDelete(false);
}
QQuickTextureFactory *CbzImageResponse::textureFactory() const
{
if (m_image.isNull())
return nullptr;
return QQuickTextureFactory::textureFactoryForImage(m_image);
}
void CbzImageResponse::cancel()
{
m_cancelled.storeRelaxed(1);
}
void CbzImageResponse::run()
{
if (m_cancelled.loadRelaxed())
return;
m_image = CbzImageProvider::loadImageFromCbz(m_cbzPath, m_entryName,
m_displayWidth, m_requestedSize);
if (m_cancelled.loadRelaxed())
return;
emit finished();
}
// ---------------------------------------------------------------------------
// CbzImageProvider
// ---------------------------------------------------------------------------
QImage CbzImageProvider::loadImageFromCbz(const QString &cbzPath, const QString &entryName,
int displayWidth, const QSize &requestedSize)
{
if (cbzPath.isEmpty() || entryName.isEmpty())
return {};
unzFile zf = unzOpen(cbzPath.toUtf8().constData());
if (!zf)
return {};
auto closeGuard = [](void *p) { unzClose(static_cast<unzFile>(p)); };
std::unique_ptr<void, decltype(closeGuard)> guard(zf, closeGuard);
const QByteArray data = ZipUtils::readZipEntry(zf, entryName.toUtf8().constData());
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;
}
QQuickImageResponse *CbzImageProvider::requestImageResponse(const QString &id,
const QSize &requestedSize)
{
QString cbzPath;
int displayWidth;
{
QMutexLocker lock(&m_mutex);
cbzPath = m_cbzPath;
displayWidth = m_displayWidth;
}
// id may be "entry/name.jpg?cbz=<encoded-path>"
// Qt Quick passes the path portion of the URL in percent-encoded form
// (e.g. "{HQ}" becomes "%7BHQ%7D"), so decode it back to get the real entry name.
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("cbz=");
if (query.startsWith(key))
cbzPath = QUrl::fromPercentEncoding(query.mid(key.size()).toUtf8());
}
entryName = QUrl::fromPercentEncoding(entryName.toUtf8());
auto *response = new CbzImageResponse(cbzPath, entryName, displayWidth, requestedSize);
QThreadPool::globalInstance()->start(response);
return response;
}
QImage CbzImageProvider::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 cbzPath;
if (url.hasQuery()) {
const QString q = url.query();
const QLatin1String key("cbz=");
if (q.startsWith(key))
cbzPath = QUrl::fromPercentEncoding(q.mid(key.size()).toUtf8());
}
if (cbzPath.isEmpty()) {
QMutexLocker lock(&m_mutex);
cbzPath = m_cbzPath;
}
return loadImageFromCbz(cbzPath, entryName, maxWidth, {});
}
std::unique_ptr<IImageLoader> CbzImageProvider::clone() const
{
QString cbzPath;
{
QMutexLocker lock(&m_mutex);
cbzPath = m_cbzPath;
}
auto c = std::make_unique<CbzImageProvider>();
c->setFilePath(cbzPath);
return c;
}
void CbzImageProvider::setFilePath(const QString &filePath)
{
QMutexLocker lock(&m_mutex);
m_cbzPath = filePath;
}
QString CbzImageProvider::coverImageUrl(const QString &coverPath) const
{
QString cbzPath;
{ QMutexLocker lock(&m_mutex); cbzPath = m_cbzPath; }
return QStringLiteral("image://cbz/") + coverPath
+ QStringLiteral("?cbz=")
+ QString::fromUtf8(QUrl::toPercentEncoding(cbzPath));
}
QString CbzImageProvider::scheme() const
{
return QStringLiteral("cbz");
}
void CbzImageProvider::setDisplayWidth(int width)
{
QMutexLocker lock(&m_mutex);
m_displayWidth = width;
}
void CbzImageProvider::clear()
{
QMutexLocker lock(&m_mutex);
m_cbzPath.clear();
m_displayWidth = 0;
}
-53
View File
@@ -1,53 +0,0 @@
#ifndef CBZIMAGEPROVIDER_H
#define CBZIMAGEPROVIDER_H
#include <QMutex>
#include <QRunnable>
#include <QString>
#include "backend/IImageLoader.h"
#include "backend/IImageProvider.h"
class CbzImageResponse : public QQuickImageResponse, public QRunnable {
// NO Q_OBJECT — already inherited from QQuickImageResponse
public:
CbzImageResponse(const QString &cbzPath, const QString &entryName,
int displayWidth, const QSize &requestedSize);
QQuickTextureFactory *textureFactory() const override;
void cancel() override;
void run() override;
private:
const QString m_cbzPath;
const QString m_entryName;
const int m_displayWidth;
const QSize m_requestedSize;
QAtomicInt m_cancelled{0};
QImage m_image;
};
class CbzImageProvider : 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 loadImageFromCbz(const QString &cbzPath, const QString &entryName,
int displayWidth, const QSize &requestedSize);
private:
mutable QMutex m_mutex;
QString m_cbzPath;
int m_displayWidth = 0;
};
#endif // CBZIMAGEPROVIDER_H
+17 -2
View File
@@ -1,5 +1,7 @@
#include "ImageLoaderFactory.h"
#include "CbzImageProvider.h"
#include "comic/Cbz.h"
#include "comic/Cbr.h"
#include "comic/Folder.h"
#include "EpubImageProvider.h"
#include "Fb2ImageProvider.h"
#include "WebImageProvider.h"
@@ -37,7 +39,15 @@ private:
std::unique_ptr<IImageLoader> ImageLoaderFactory::create(const QString &filePath)
{
const QString ext = QFileInfo(filePath).suffix().toLower();
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>();
@@ -59,5 +69,10 @@ std::unique_ptr<IImageLoader> ImageLoaderFactory::create(const QString &filePath
loader->setFilePath(filePath);
return loader;
}
if (ext == QLatin1String("cbr")) {
auto loader = std::make_unique<CbrImageProvider>();
loader->setFilePath(filePath);
return loader;
}
return nullptr;
}
+9 -2
View File
@@ -1,17 +1,24 @@
#include "ImageProviderFactory.h"
#include "CbzImageProvider.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 QString ext = QFileInfo(filePath).suffix().toLower();
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;
}
+8 -3
View File
@@ -13,8 +13,9 @@ ReaderFactory::ReaderFactory(QList<CreatorFn> creators)
std::unique_ptr<FormatReader> ReaderFactory::create(const QString &filePath) const
{
const QString ext = QFileInfo(filePath).suffix().toLower();
auto it = m_registry.find(ext);
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()();
@@ -22,5 +23,9 @@ std::unique_ptr<FormatReader> ReaderFactory::create(const QString &filePath) con
QStringList ReaderFactory::supportedExtensions() const
{
return m_registry.keys();
QStringList out;
for (auto it = m_registry.cbegin(); it != m_registry.cend(); ++it)
if (!it.key().startsWith(QLatin1Char('<')))
out << it.key();
return out;
}
+1
View File
@@ -0,0 +1 @@
// Cbr shells are header-only (constructors inline in Cbr.h).
+7
View File
@@ -0,0 +1,7 @@
#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
@@ -0,0 +1,11 @@
#pragma once
#include "ComicImageProvider.h"
#include "RarComicSource.h"
class CbrImageProvider : public ComicImageProvider {
public:
CbrImageProvider()
: ComicImageProvider([] { return std::make_unique<RarComicSource>(); },
QStringLiteral("cbr")) {}
};
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include "ComicReader.h"
#include "RarComicSource.h"
class CbrReader : public ComicReader {
public:
CbrReader()
: ComicReader([] { return std::make_unique<RarComicSource>(); },
QStringLiteral("cbr"),
QStringLiteral("cbr")) {}
};
+1
View File
@@ -0,0 +1 @@
// Cbz shells are header-only (constructors inline in Cbz.h).
+7
View File
@@ -0,0 +1,7 @@
#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
@@ -0,0 +1,11 @@
#pragma once
#include "ComicImageProvider.h"
#include "ZipComicSource.h"
class CbzImageProvider : public ComicImageProvider {
public:
CbzImageProvider()
: ComicImageProvider([] { return std::make_unique<ZipComicSource>(); },
QStringLiteral("cbz")) {}
};
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include "ComicReader.h"
#include "ZipComicSource.h"
class CbzReader : public ComicReader {
public:
CbzReader()
: ComicReader([] { return std::make_unique<ZipComicSource>(); },
QStringLiteral("cbz"),
QStringLiteral("cbz")) {}
};
@@ -0,0 +1,202 @@
#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;
}
@@ -0,0 +1,70 @@
#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;
};
@@ -1,17 +1,11 @@
#include "CbzReader.h"
#include "backend/ZipUtils.h"
#include "ComicReader.h"
#include <QBuffer>
#include <QCryptographicHash>
#include <QFile>
#include <QFileInfo>
#include <QImageReader>
#include <QSet>
#include <QXmlStreamReader>
#include <minizip/unzip.h>
// ---------------------------------------------------------------------------
// ComicInfo.xml parsing
// ---------------------------------------------------------------------------
@@ -58,7 +52,7 @@ static void parseComicInfo(const QByteArray &data,
}
// ---------------------------------------------------------------------------
// CbzReader
// ComicReader
// ---------------------------------------------------------------------------
static const QSet<QString> kImageExtensions = {
@@ -67,17 +61,27 @@ static const QSet<QString> kImageExtensions = {
QStringLiteral("webp")
};
bool CbzReader::parseArchive(const QString &filePath)
ComicReader::ComicReader(SourceFactory sourceFactory, QString fileType, QString scheme)
: m_sourceFactory(std::move(sourceFactory))
, m_fileType(std::move(fileType))
, m_scheme(std::move(scheme))
{
unzFile zf = unzOpen(filePath.toUtf8().constData());
if (!zf) {
m_error = QStringLiteral("Cannot open as ZIP archive: ") + filePath;
}
// Shared parsing logic given an already-opened source.
bool ComicReader::parseSource(const QString &filePath)
{
auto source = m_sourceFactory();
if (!source->open(filePath)) {
m_error = QStringLiteral("Cannot open comic source: ") + filePath;
return false;
}
auto closeGuard = [](void *p) { unzClose(static_cast<unzFile>(p)); };
std::unique_ptr<void, decltype(closeGuard)> guard(zf, closeGuard);
return parseOpenSource(filePath, *source);
}
const QStringList allEntries = ZipUtils::listZipEntries(zf);
bool ComicReader::parseOpenSource(const QString &filePath, IComicSource &source)
{
const QStringList allEntries = source.listEntries();
QStringList imageEntries;
for (const QString &entry : allEntries) {
@@ -92,11 +96,10 @@ bool CbzReader::parseArchive(const QString &filePath)
}
imageEntries.sort();
// Read image header for each page to get natural dimensions (header-only, no pixel decode).
m_pageEntries.reserve(imageEntries.size());
for (const QString &entry : imageEntries) {
QSize naturalSize;
const QByteArray data = ZipUtils::readZipEntry(zf, entry.toUtf8().constData());
const QByteArray data = source.readEntry(entry);
if (!data.isEmpty()) {
QBuffer buf;
buf.setData(data);
@@ -108,19 +111,19 @@ bool CbzReader::parseArchive(const QString &filePath)
}
if (m_pageEntries.isEmpty()) {
m_error = QStringLiteral("No images found in archive: ") + filePath;
m_error = QStringLiteral("No images found: ") + filePath;
return false;
}
m_coverEntry = m_pageEntries.first().entry;
// Look for ComicInfo.xml (case-insensitive, archive-root only)
// ComicInfo.xml: archive root only, case-insensitive
for (const QString &entry : allEntries) {
if (entry.compare(QLatin1String("ComicInfo.xml"), Qt::CaseInsensitive) == 0) {
const QByteArray comicInfoData = ZipUtils::readZipEntry(zf, entry.toUtf8().constData());
if (!comicInfoData.isEmpty()) {
const QByteArray data = source.readEntry(entry);
if (!data.isEmpty()) {
int coverIndex = -1;
parseComicInfo(comicInfoData, m_title, m_author, coverIndex);
parseComicInfo(data, m_title, m_author, coverIndex);
if (coverIndex >= 0 && coverIndex < m_pageEntries.size())
m_coverEntry = m_pageEntries[coverIndex].entry;
}
@@ -135,7 +138,7 @@ bool CbzReader::parseArchive(const QString &filePath)
return true;
}
bool CbzReader::open(const QString &filePath)
bool ComicReader::open(const QString &filePath)
{
m_title.clear();
m_author.clear();
@@ -145,16 +148,16 @@ bool CbzReader::open(const QString &filePath)
m_contentHash.clear();
m_filePath.clear();
QFile f(filePath);
if (f.open(QIODevice::ReadOnly)) {
m_contentHash = QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5);
f.close();
auto source = m_sourceFactory();
if (!source->open(filePath)) {
m_error = QStringLiteral("Cannot open comic source: ") + filePath;
return false;
}
return parseArchive(filePath);
m_contentHash = source->contentHash();
return parseOpenSource(filePath, *source);
}
bool CbzReader::loadMetadata(const QString &filePath)
bool ComicReader::loadMetadata(const QString &filePath)
{
m_title.clear();
m_author.clear();
@@ -162,11 +165,10 @@ bool CbzReader::loadMetadata(const QString &filePath)
m_pageEntries.clear();
m_coverEntry.clear();
m_filePath.clear();
return parseArchive(filePath);
return parseSource(filePath);
}
Chapter CbzReader::loadChapter(int index)
Chapter ComicReader::loadChapter(int index)
{
if (index != 0 || m_pageEntries.isEmpty())
return Chapter{index, {}, {}};
@@ -175,12 +177,13 @@ Chapter CbzReader::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://cbz/%1\"/></p>").arg(page.entry));
"<img src=\"image://%1/%2\"/></p>")
.arg(m_scheme, page.entry));
}
return Chapter{0, m_title, chunks};
}
QVector<QSize> CbzReader::chapterPageSizes(int chapterIndex) const
QVector<QSize> ComicReader::chapterPageSizes(int chapterIndex) const
{
if (chapterIndex != 0 || m_pageEntries.isEmpty())
return {};
@@ -191,13 +194,13 @@ QVector<QSize> CbzReader::chapterPageSizes(int chapterIndex) const
return sizes;
}
QString CbzReader::lastError() { return m_error; }
QString CbzReader::title() { return m_title; }
QString CbzReader::author() { return m_author; }
QString CbzReader::coverImagePath() { return m_coverEntry; }
int CbzReader::chapterCount() { return m_pageEntries.isEmpty() ? 0 : 1; }
QString CbzReader::filePath() { return m_filePath; }
QByteArray CbzReader::contentHash() { return m_contentHash; }
QString CbzReader::fileType() const { return QStringLiteral("cbz"); }
QString ComicReader::lastError() { return m_error; }
QString ComicReader::title() { return m_title; }
QString ComicReader::author() { return m_author; }
QString ComicReader::coverImagePath() { return m_coverEntry; }
int ComicReader::chapterCount() { return m_pageEntries.isEmpty() ? 0 : 1; }
QString ComicReader::filePath() { return m_filePath; }
QByteArray ComicReader::contentHash() { return m_contentHash; }
QString ComicReader::fileType() const { return m_fileType; }
QList<TocEntry> CbzReader::tableOfContents() { return {}; }
QList<TocEntry> ComicReader::tableOfContents() { return {}; }
@@ -1,15 +1,22 @@
#ifndef CBZREADER_H
#define CBZREADER_H
#pragma once
#include "backend/FormatReader.h"
#include "IComicSource.h"
#include <functional>
#include <memory>
#include <QByteArray>
#include <QList>
#include <QSize>
#include <QStringList>
#include <QVector>
class CbzReader : public FormatReader {
class ComicReader : public FormatReader {
public:
using SourceFactory = std::function<std::unique_ptr<IComicSource>()>;
ComicReader(SourceFactory sourceFactory, QString fileType, QString scheme);
bool open(const QString &filePath) override;
bool loadMetadata(const QString &filePath) override;
QString lastError() override;
@@ -32,7 +39,12 @@ private:
QSize naturalSize;
};
bool parseArchive(const QString &filePath);
bool parseSource(const QString &filePath);
bool parseOpenSource(const QString &filePath, IComicSource &source);
SourceFactory m_sourceFactory;
QString m_fileType;
QString m_scheme;
QString m_filePath;
QByteArray m_contentHash;
@@ -42,5 +54,3 @@ private:
QVector<PageEntry> m_pageEntries;
QString m_coverEntry;
};
#endif // CBZREADER_H
@@ -0,0 +1,53 @@
#include "DirComicSource.h"
#include <QCryptographicHash>
#include <QDir>
#include <QFile>
#include <QFileInfo>
bool DirComicSource::open(const QString &path)
{
m_dir.clear();
m_hash.clear();
m_entries.clear();
const QDir d(path);
if (!d.exists())
return false;
const auto infos = d.entryInfoList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name);
if (infos.isEmpty())
return false;
QByteArray hashInput;
for (const QFileInfo &fi : infos) {
m_entries.append(fi.fileName());
hashInput += fi.fileName().toUtf8()
+ QByteArrayLiteral(":")
+ QByteArray::number(fi.size())
+ QByteArrayLiteral("\n");
}
m_hash = QCryptographicHash::hash(hashInput, QCryptographicHash::Md5);
m_dir = path;
return true;
}
QStringList DirComicSource::listEntries() const
{
return m_entries;
}
QByteArray DirComicSource::readEntry(const QString &entryName) const
{
if (m_dir.isEmpty() || entryName.isEmpty())
return {};
QFile f(m_dir + QLatin1Char('/') + entryName);
if (!f.open(QIODevice::ReadOnly))
return {};
return f.readAll();
}
QByteArray DirComicSource::contentHash() const
{
return m_hash;
}
@@ -0,0 +1,16 @@
#pragma once
#include "IComicSource.h"
class DirComicSource : public IComicSource {
public:
bool open(const QString &path) override;
QStringList listEntries() const override;
QByteArray readEntry(const QString &entryName) const override;
QByteArray contentHash() const override;
private:
QString m_dir;
QByteArray m_hash;
QStringList m_entries;
};
+1
View File
@@ -0,0 +1 @@
// Folder shells are header-only (constructors inline in Folder.h).
+7
View File
@@ -0,0 +1,7 @@
#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"
@@ -0,0 +1,11 @@
#pragma once
#include "ComicImageProvider.h"
#include "DirComicSource.h"
class FolderImageProvider : public ComicImageProvider {
public:
FolderImageProvider()
: ComicImageProvider([] { return std::make_unique<DirComicSource>(); },
QStringLiteral("dir")) {}
};
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include "ComicReader.h"
#include "DirComicSource.h"
class FolderReader : public ComicReader {
public:
FolderReader()
: ComicReader([] { return std::make_unique<DirComicSource>(); },
QStringLiteral("<dir>"),
QStringLiteral("dir")) {}
};
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include <QByteArray>
#include <QString>
#include <QStringList>
// Abstracts how raw image bytes are obtained from a named entry.
// Implementations: ZipComicSource (minizip), RarComicSource (libarchive), DirComicSource (QDir/QFile).
class IComicSource {
public:
virtual ~IComicSource() = default;
// Opens the source. After returning true, listEntries/readEntry/contentHash are valid.
virtual bool open(const QString &path) = 0;
// All entry names in the source's natural order. Caller filters and sorts.
virtual QStringList listEntries() const = 0;
// Full bytes of one named entry. Returns empty on miss.
virtual QByteArray readEntry(const QString &entryName) const = 0;
// MD5 of the source. For archives: MD5 of file bytes.
// For directories: MD5 of sorted "name:size\n" lines.
virtual QByteArray contentHash() const = 0;
};
@@ -0,0 +1,85 @@
#include "RarComicSource.h"
#include <QCryptographicHash>
#include <QFile>
#include <archive.h>
#include <archive_entry.h>
bool RarComicSource::open(const QString &path)
{
m_path.clear();
m_hash.clear();
m_entries.clear();
// Walk headers only to build the entry list (no payload decompression here).
struct archive *a = archive_read_new();
archive_read_support_format_rar(a);
archive_read_support_format_rar5(a);
const bool opened = archive_read_open_filename(a, path.toUtf8().constData(), 16384) == ARCHIVE_OK;
if (opened) {
struct archive_entry *e;
while (archive_read_next_header(a, &e) == ARCHIVE_OK) {
if (archive_entry_filetype(e) == AE_IFREG)
m_entries.append(QString::fromUtf8(archive_entry_pathname(e)));
archive_read_data_skip(a);
}
}
archive_read_free(a);
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
{
return m_entries;
}
QByteArray RarComicSource::readEntry(const QString &entryName) const
{
if (m_path.isEmpty() || entryName.isEmpty())
return {};
const QByteArray nameBytes = entryName.toUtf8();
struct archive *a = archive_read_new();
archive_read_support_format_rar(a);
archive_read_support_format_rar5(a);
if (archive_read_open_filename(a, m_path.toUtf8().constData(), 16384) != ARCHIVE_OK) {
archive_read_free(a);
return {};
}
QByteArray result;
struct archive_entry *e;
while (archive_read_next_header(a, &e) == ARCHIVE_OK) {
if (qstrcmp(archive_entry_pathname(e), nameBytes.constData()) == 0) {
const la_int64_t sz = archive_entry_size(e);
if (sz > 0) result.reserve(static_cast<int>(sz));
char chunk[65536];
la_ssize_t n;
while ((n = archive_read_data(a, chunk, sizeof(chunk))) > 0)
result.append(chunk, static_cast<int>(n));
break;
}
archive_read_data_skip(a);
}
archive_read_free(a);
return result;
}
QByteArray RarComicSource::contentHash() const
{
return m_hash;
}
@@ -0,0 +1,16 @@
#pragma once
#include "IComicSource.h"
class RarComicSource : public IComicSource {
public:
bool open(const QString &path) override;
QStringList listEntries() const override;
QByteArray readEntry(const QString &entryName) const override;
QByteArray contentHash() const override;
private:
QString m_path;
QByteArray m_hash;
QStringList m_entries;
};
@@ -0,0 +1,52 @@
#include "ZipComicSource.h"
#include "backend/ZipUtils.h"
#include <QCryptographicHash>
#include <QFile>
#include <minizip/unzip.h>
bool ZipComicSource::open(const QString &path)
{
m_path.clear();
m_hash.clear();
m_entries.clear();
unzFile zf = unzOpen(path.toUtf8().constData());
if (!zf)
return false;
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
{
return m_entries;
}
QByteArray ZipComicSource::readEntry(const QString &entryName) const
{
if (m_path.isEmpty() || entryName.isEmpty())
return {};
unzFile zf = unzOpen(m_path.toUtf8().constData());
if (!zf)
return {};
auto closeGuard = [](void *p) { unzClose(static_cast<unzFile>(p)); };
std::unique_ptr<void, decltype(closeGuard)> guard(zf, closeGuard);
return ZipUtils::readZipEntry(zf, entryName.toUtf8().constData());
}
QByteArray ZipComicSource::contentHash() const
{
return m_hash;
}
@@ -0,0 +1,16 @@
#pragma once
#include "IComicSource.h"
class ZipComicSource : public IComicSource {
public:
bool open(const QString &path) override;
QStringList listEntries() const override;
QByteArray readEntry(const QString &entryName) const override;
QByteArray contentHash() const override;
private:
QString m_path;
QByteArray m_hash;
QStringList m_entries;
};
+7 -2
View File
@@ -25,8 +25,9 @@
#include "backend/formats/EpubReader.h"
#include "backend/formats/Fb2Reader.h"
#include "backend/formats/Fb2ImageProvider.h"
#include "backend/formats/CbzReader.h"
#include "backend/formats/CbzImageProvider.h"
#include "backend/formats/comic/Cbz.h"
#include "backend/formats/comic/Cbr.h"
#include "backend/formats/comic/Folder.h"
#include "backend/state/BookPositionStore.h"
#include "backend/state/ReadingPreferences.h"
#include "backend/state/UiState.h"
@@ -109,6 +110,8 @@ int main(int argc, char *argv[])
[] { return std::make_unique<EpubReader>(); },
[] { return std::make_unique<Fb2Reader>(); },
[] { return std::make_unique<CbzReader>(); },
[] { return std::make_unique<CbrReader>(); },
[] { return std::make_unique<FolderReader>(); },
});
HistoryModel historyModel(readerFactory);
@@ -148,6 +151,8 @@ int main(int argc, char *argv[])
engine.addImageProvider(QStringLiteral("epub"), new EpubImageProvider());
engine.addImageProvider(QStringLiteral("fb2"), new Fb2ImageProvider());
engine.addImageProvider(QStringLiteral("cbz"), new CbzImageProvider());
engine.addImageProvider(QStringLiteral("cbr"), new CbrImageProvider());
engine.addImageProvider(QStringLiteral("dir"), new FolderImageProvider());
engine.addImageProvider(QStringLiteral("fileicon"), new FileIconProvider());
engine.rootContext()->setContextProperty(QStringLiteral("isDebugBuild"),
#ifdef QT_DEBUG