reintroduced epub support

This commit is contained in:
Agel committed 2026-10-25 19:59:23 +01:00
1 parent 49a959a89d
commit d14170a68f
49 files changed
+5048 -205

No files matched your search

+340
View File
@@ -0,0 +1,340 @@
#include "EpubReader.h"
#include <QDir>
#include <QDomDocument>
#include <QFontDatabase>
#include <QFileInfo>
#include <QSet>
#include <QTextStream>
#include <QUrl>
#include <QXmlStreamReader>
#include "backend/formats/HtmlEntities.h"
#include "backend/formats/ImageUrl.h"
#include "backend/reading/layout/CssParser.h"
EpubReader::EpubReader(SourceFactory sourceFactory, QString scheme)
: m_sourceFactory(std::move(sourceFactory))
, m_scheme(std::move(scheme))
{
}
QString EpubReader::coverImageUrl() const
{
if (m_coverEntry.isEmpty())
return {};
return ImageUrl::build(m_scheme, m_coverEntry, m_filePath);
}
bool EpubReader::parseContainer(const QByteArray &data, QString &outOpfPath)
{
QXmlStreamReader xml(data);
while (!xml.atEnd()) {
xml.readNext();
if (xml.isStartElement() && xml.name() == QLatin1String("rootfile")) {
outOpfPath = xml.attributes().value(QLatin1String("full-path")).toString();
if (!outOpfPath.isEmpty())
return true;
}
}
return false;
}
bool EpubReader::parseOpf(const QByteArray &data, IByteSource &source, bool metadataOnly)
{
QXmlStreamReader xml(data);
QString coverId;
static const QLatin1String kDcNs("http://purl.org/dc/elements/1.1/");
while (!xml.atEnd()) {
xml.readNext();
if (!xml.isStartElement())
continue;
const QStringView name = xml.name();
const QStringView ns = xml.namespaceUri();
if (name == QLatin1String("title") && (ns == kDcNs || ns.isEmpty())) {
if (m_title.isEmpty())
m_title = xml.readElementText().trimmed();
} else if (name == QLatin1String("creator") && (ns == kDcNs || ns.isEmpty())) {
if (m_author.isEmpty())
m_author = xml.readElementText().trimmed();
} else if (name == QLatin1String("meta")) {
const auto attrs = xml.attributes();
if (attrs.value(QLatin1String("name")) == QLatin1String("cover"))
coverId = attrs.value(QLatin1String("content")).toString();
else if (attrs.value(QLatin1String("content")) == QLatin1String("cover"))
coverId = attrs.value(QLatin1String("name")).toString();
} else if (name == QLatin1String("item")) {
const auto attrs = xml.attributes();
const QString id = attrs.value(QLatin1String("id")).toString();
const QString rawHref = attrs.value(QLatin1String("href")).toString();
const QString href = QUrl::fromPercentEncoding(rawHref.toUtf8());
const QString mediaType = attrs.value(QLatin1String("media-type")).toString().toLower();
const QString props = attrs.value(QLatin1String("properties")).toString();
if (!id.isEmpty() && !href.isEmpty()) {
m_manifest.insert(id, {href, mediaType, props});
if (props.contains(QLatin1String("cover-image")))
coverId = id;
// Load embedded fonts
if (!metadataOnly && (mediaType.startsWith(QLatin1String("font/"))
|| mediaType.startsWith(QLatin1String("application/font"))
|| mediaType.startsWith(QLatin1String("application/x-font"))
|| mediaType == QLatin1String("application/vnd.ms-opentype"))) {
const QString fontPath = QDir::cleanPath(m_opfDir + href);
const QByteArray fontData = source.readEntry(fontPath);
if (!fontData.isEmpty()) {
QFontDatabase::addApplicationFontFromData(fontData);
}
}
}
} else if (name == QLatin1String("itemref")) {
const auto attrs = xml.attributes();
const QString idref = attrs.value(QLatin1String("idref")).toString();
if (m_manifest.contains(idref)) {
const QString resolved = QDir::cleanPath(m_opfDir + m_manifest[idref].href);
m_spineHrefs.append(resolved);
}
}
}
if (!coverId.isEmpty() && m_manifest.contains(coverId)) {
m_coverEntry = QDir::cleanPath(m_opfDir + m_manifest[coverId].href);
} else {
// Fallback: look for item with id cover/cover-image and image media type
for (auto it = m_manifest.begin(); it != m_manifest.end(); ++it) {
if (it.key().contains(QLatin1String("cover"), Qt::CaseInsensitive)
&& it.value().mediaType.startsWith(QLatin1String("image/"))) {
m_coverEntry = QDir::cleanPath(m_opfDir + it.value().href);
break;
}
}
}
return true;
}
void EpubReader::appendSpineChunks(const QString &xhtml,
const QString &xhtmlHref,
IByteSource &source,
QHash<QString, Css::StyleSheet> &cssCache,
QSet<QString> &loadedFonts)
{
const QString safeXml = HtmlEntities::toXmlSafe(xhtml);
QDomDocument doc;
if (!doc.setContent(safeXml)) {
m_chunks.append(xhtml);
return;
}
const int lastSlash = xhtmlHref.lastIndexOf(QLatin1Char('/'));
const QString xhtmlDir = (lastSlash >= 0) ? xhtmlHref.left(lastSlash + 1) : QString();
Css::StyleSheet sheet;
// 1. External stylesheets <link rel="stylesheet" href="..."/>
QDomNodeList links = doc.elementsByTagName(QStringLiteral("link"));
for (int i = 0; i < links.size(); ++i) {
QDomElement linkEl = links.at(i).toElement();
if (linkEl.attribute(QStringLiteral("rel")).toLower() == QLatin1String("stylesheet")) {
QString href = linkEl.attribute(QStringLiteral("href"));
href = QUrl::fromPercentEncoding(href.toUtf8());
const QString cssPath = QDir::cleanPath(xhtmlDir + href);
auto it = cssCache.constFind(cssPath);
if (it != cssCache.constEnd()) {
sheet.append(it.value());
} else {
const QByteArray cssData = source.readEntry(cssPath);
if (!cssData.isEmpty()) {
Css::StyleSheet parsedSheet = Css::StyleSheet::parse(QString::fromUtf8(cssData));
sheet.append(parsedSheet);
cssCache.insert(cssPath, parsedSheet);
}
}
}
}
// 2. Embedded <style> blocks
QDomNodeList styles = doc.elementsByTagName(QStringLiteral("style"));
for (int i = 0; i < styles.size(); ++i) {
sheet.append(Css::StyleSheet::parse(styles.at(i).toElement().text()));
}
// 3. Resolve CSS fonts if any
for (const auto &ff : sheet.fontFaces) {
if (!ff.src.isEmpty()) {
const QString fontPath = QDir::cleanPath(xhtmlDir + ff.src);
if (!loadedFonts.contains(fontPath)) {
loadedFonts.insert(fontPath);
const QByteArray fData = source.readEntry(fontPath);
if (!fData.isEmpty()) {
QFontDatabase::addApplicationFontFromData(fData);
}
}
}
}
// 4. Cascade onto each element & rewrite image URLs
std::function<void(QDomElement &)> processElement = [&](QDomElement &el) {
const auto decls = Css::cascade(sheet, el);
if (!decls.isEmpty()) {
el.setAttribute(QStringLiteral("style"), Css::serialize(decls));
}
const QString tag = el.tagName().toLower();
if (tag == QLatin1String("img") || tag == QLatin1String("image")) {
QString srcAttr = el.hasAttribute(QStringLiteral("src")) ? QStringLiteral("src")
: (el.hasAttribute(QStringLiteral("xlink:href")) ? QStringLiteral("xlink:href")
: (el.hasAttribute(QStringLiteral("href")) ? QStringLiteral("href") : QString()));
if (!srcAttr.isEmpty()) {
const QString src = el.attribute(srcAttr);
const QString resolved = ImageUrl::resolve(m_scheme, src, m_filePath, xhtmlDir);
el.setAttribute(srcAttr, resolved);
}
}
for (QDomNode child = el.firstChild(); !child.isNull(); child = child.nextSibling()) {
if (child.isElement()) {
QDomElement childEl = child.toElement();
processElement(childEl);
}
}
};
QDomElement root = doc.documentElement();
processElement(root);
// 5. Chunk <body> directly from modified DOM
QDomNodeList bodies = doc.elementsByTagName(QStringLiteral("body"));
if (bodies.isEmpty()) {
QString serialized;
QTextStream ts(&serialized);
doc.save(ts, 0);
m_chunks.append(serialized);
return;
}
QDomElement body = bodies.at(0).toElement();
QString currentChunk;
static constexpr int kChunkTargetSize = 4096;
for (QDomNode node = body.firstChild(); !node.isNull(); node = node.nextSibling()) {
QString serialized;
QTextStream ts(&serialized);
node.save(ts, 0);
if (!currentChunk.isEmpty() && (currentChunk.size() + serialized.size() > kChunkTargetSize)) {
m_chunks.append(currentChunk);
currentChunk.clear();
}
currentChunk += serialized;
}
if (!currentChunk.isEmpty())
m_chunks.append(currentChunk);
}
bool EpubReader::parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly)
{
m_filePath = filePath;
// 1. container.xml
const QByteArray containerData = source.readEntry(QStringLiteral("META-INF/container.xml"));
if (containerData.isEmpty()) {
m_error = QStringLiteral("Missing or invalid META-INF/container.xml");
return false;
}
QString opfPath;
if (!parseContainer(containerData, opfPath)) {
m_error = QStringLiteral("Could not find OPF rootfile path in container.xml");
return false;
}
const int lastSlash = opfPath.lastIndexOf(QLatin1Char('/'));
m_opfDir = (lastSlash >= 0) ? opfPath.left(lastSlash + 1) : QString();
// 2. OPF
const QByteArray opfData = source.readEntry(opfPath);
if (opfData.isEmpty()) {
m_error = QStringLiteral("Cannot read OPF file: ") + opfPath;
return false;
}
if (!parseOpf(opfData, source, metadataOnly)) {
m_error = QStringLiteral("Error parsing OPF package");
return false;
}
if (m_title.isEmpty())
m_title = QFileInfo(filePath).completeBaseName();
if (!metadataOnly) {
QHash<QString, Css::StyleSheet> cssCache;
QSet<QString> loadedFonts;
m_chunks.clear();
for (const QString &href : m_spineHrefs) {
const QByteArray xhtmlData = source.readEntry(href);
if (!xhtmlData.isEmpty()) {
appendSpineChunks(QString::fromUtf8(xhtmlData), href, source, cssCache, loadedFonts);
}
}
if (m_chunks.isEmpty()) {
m_chunks.append(QStringLiteral("<p></p>"));
}
}
m_filePath = filePath;
return true;
}
bool EpubReader::open(const QString &filePath)
{
m_title.clear();
m_author.clear();
m_error.clear();
m_opfDir.clear();
m_coverEntry.clear();
m_manifest.clear();
m_spineHrefs.clear();
m_chunks.clear();
m_contentHash.clear();
m_filePath.clear();
auto source = m_sourceFactory();
if (!source || !source->open(filePath)) {
m_error = QStringLiteral("Cannot open EPUB file: ") + filePath;
return false;
}
m_contentHash = source->contentHash();
return parseOpen(filePath, *source, false);
}
bool EpubReader::loadMetadata(const QString &filePath)
{
m_title.clear();
m_author.clear();
m_error.clear();
m_opfDir.clear();
m_coverEntry.clear();
m_manifest.clear();
m_spineHrefs.clear();
m_chunks.clear();
m_contentHash.clear();
m_filePath.clear();
auto source = m_sourceFactory();
if (!source || !source->open(filePath)) {
m_error = QStringLiteral("Cannot open EPUB file: ") + filePath;
return false;
}
return parseOpen(filePath, *source, true);
}
+66
View File
@@ -0,0 +1,66 @@
#pragma once
#include <functional>
#include <memory>
#include <QByteArray>
#include <QHash>
#include <QSet>
#include <QString>
#include <QStringList>
#include <QVector>
#include "backend/FormatReader.h"
#include "backend/formats/IByteSource.h"
#include "backend/reading/layout/CssParser.h"
class EpubReader : public FormatReader {
public:
using SourceFactory = std::function<std::unique_ptr<IByteSource>()>;
EpubReader(SourceFactory sourceFactory, QString scheme);
ReadingMode mode() const override { return ReadingMode::Text; }
bool open(const QString &filePath) override;
bool loadMetadata(const QString &filePath) override;
QString lastError() const override { return m_error; }
QString filePath() const override { return m_filePath; }
QString title() const override { return m_title; }
QString author() const override { return m_author; }
QString coverImageUrl() const override;
QByteArray contentHash() const override { return m_contentHash; }
QStringList chunks() const override { return m_chunks; }
private:
struct ManifestItem {
QString href;
QString mediaType;
QString properties;
};
bool parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly);
bool parseContainer(const QByteArray &data, QString &outOpfPath);
bool parseOpf(const QByteArray &data, IByteSource &source, bool metadataOnly);
void appendSpineChunks(const QString &xhtml,
const QString &xhtmlHref,
IByteSource &source,
QHash<QString, Css::StyleSheet> &cssCache,
QSet<QString> &loadedFonts);
SourceFactory m_sourceFactory;
QString m_scheme;
QString m_filePath;
QByteArray m_contentHash;
QString m_title;
QString m_author;
QString m_error;
QString m_opfDir;
QString m_coverEntry;
QHash<QString, ManifestItem> m_manifest; // id -> item
QStringList m_spineHrefs; // ordered spine relative hrefs
QStringList m_chunks;
};
+21
View File
@@ -3,6 +3,7 @@
#include "EntryImageProvider.h"
#include "backend/FormatReader.h"
#include "backend/formats/comic/ComicReader.h"
#include "backend/formats/EpubReader.h"
#include <QFileInfo>
#include <QQmlEngine>
@@ -19,6 +20,17 @@ FormatSpec FormatSpec::comic(const QString &ext, bool matchesDirectory, const QS
};
}
FormatSpec FormatSpec::epub(SourceFactory makeSource)
{
return FormatSpec{
QStringLiteral("epub"),
false,
QStringLiteral("epub"),
[makeSource] { return std::make_unique<EpubReader>(makeSource, QStringLiteral("epub")); },
makeSource
};
}
FormatRegistry::FormatRegistry(QVector<FormatSpec> specs)
: m_specs(std::move(specs))
{
@@ -43,6 +55,15 @@ std::unique_ptr<FormatReader> FormatRegistry::createReader(const QString &filePa
return spec ? spec->makeReader() : nullptr;
}
std::unique_ptr<IByteSource> FormatRegistry::createByteSourceForScheme(const QString &scheme) const
{
for (const FormatSpec &spec : m_specs) {
if (spec.scheme == scheme && spec.makeSource)
return spec.makeSource();
}
return nullptr;
}
QStringList FormatRegistry::supportedExtensions() const
{
QStringList out;
+2
View File
@@ -25,6 +25,7 @@ struct FormatSpec {
static FormatSpec comic(const QString &ext, bool matchesDirectory, const QString &scheme,
SourceFactory makeSource);
static FormatSpec epub(SourceFactory makeSource);
};
class FormatRegistry {
@@ -32,6 +33,7 @@ public:
explicit FormatRegistry(QVector<FormatSpec> specs);
std::unique_ptr<FormatReader> createReader(const QString &filePath) const;
std::unique_ptr<IByteSource> createByteSourceForScheme(const QString &scheme) const;
QStringList supportedExtensions() const;
// Register one provider per scheme with the QML engine (engine takes ownership).
+101
View File
@@ -0,0 +1,101 @@
#include "HtmlEntities.h"
#include <QHash>
namespace HtmlEntities {
namespace {
const QHash<QString, int> &entityTable()
{
static const QHash<QString, int> table = [] {
QHash<QString, int> t;
static const char *const latin1[] = {
"nbsp", "iexcl", "cent", "pound", "curren", "yen", "brvbar", "sect", "uml", "copy",
"ordf", "laquo", "not", "shy", "reg", "macr", "deg", "plusmn", "sup2", "sup3",
"acute", "micro", "para", "middot", "cedil", "sup1", "ordm", "raquo", "frac14", "frac12",
"frac34", "iquest", "Agrave", "Aacute", "Acirc", "Atilde", "Auml", "Aring", "AElig", "Ccedil",
"Egrave", "Eacute", "Ecirc", "Euml", "Igrave", "Iacute", "Icirc", "Iuml", "ETH", "Ntilde",
"Ograve", "Oacute", "Ocirc", "Otilde", "Ouml", "times", "Oslash", "Ugrave", "Uacute", "Ucirc",
"Uuml", "Yacute", "THORN", "szlig", "agrave", "aacute", "acirc", "atilde", "auml", "aring",
"aelig", "ccedil", "egrave", "eacute", "ecirc", "euml", "igrave", "iacute", "icirc", "iuml",
"eth", "ntilde", "ograve", "oacute", "ocirc", "otilde", "ouml", "divide", "oslash", "ugrave",
"uacute", "ucirc", "uuml", "yacute", "thorn", "yuml",
};
for (int i = 0; i < int(sizeof(latin1) / sizeof(latin1[0])); ++i)
t.insert(QString::fromLatin1(latin1[i]), 160 + i);
static const struct { const char *name; int code; } others[] = {
{"OElig", 338}, {"oelig", 339}, {"Scaron", 352}, {"scaron", 353}, {"Yuml", 376},
{"fnof", 402}, {"circ", 710}, {"tilde", 732}, {"ensp", 8194}, {"emsp", 8195},
{"thinsp", 8201}, {"zwnj", 8204}, {"zwj", 8205}, {"lrm", 8206}, {"rlm", 8207},
{"ndash", 8211}, {"mdash", 8212}, {"lsquo", 8216}, {"rsquo", 8217}, {"sbquo", 8218},
{"ldquo", 8220}, {"rdquo", 8221}, {"bdquo", 8222}, {"dagger", 8224}, {"Dagger", 8225},
{"bull", 8226}, {"hellip", 8230}, {"permil", 8240}, {"prime", 8242}, {"Prime", 8243},
{"lsaquo", 8249}, {"rsaquo", 8250}, {"oline", 8254}, {"euro", 8364}, {"trade", 8482},
{"larr", 8592}, {"uarr", 8593}, {"rarr", 8594}, {"darr", 8595}, {"harr", 8596},
{"minus", 8722}, {"infin", 8734}, {"asymp", 8776}, {"ne", 8800}, {"le", 8804},
{"ge", 8805}, {"alpha", 945}, {"beta", 946}, {"gamma", 947}, {"delta", 948},
{"epsilon", 949}, {"theta", 952}, {"lambda", 955}, {"mu", 956}, {"pi", 960},
{"sigma", 963}, {"tau", 964}, {"phi", 966}, {"omega", 969}, {"Omega", 937},
};
for (const auto &e : others)
t.insert(QString::fromLatin1(e.name), e.code);
return t;
}();
return table;
}
bool isXmlEntity(QStringView name)
{
return name == QLatin1String("amp") || name == QLatin1String("lt") || name == QLatin1String("gt")
|| name == QLatin1String("quot") || name == QLatin1String("apos");
}
} // namespace
QString toXmlSafe(const QString &html)
{
if (!html.contains(QLatin1Char('&')))
return html;
QString out;
out.reserve(html.size() + 16);
const int n = html.size();
int i = 0;
while (i < n) {
const QChar c = html[i];
if (c != QLatin1Char('&')) {
out += c;
++i;
continue;
}
// Numeric references pass through unchanged.
if (i + 1 < n && html[i + 1] == QLatin1Char('#')) {
out += c;
++i;
continue;
}
int j = i + 1;
while (j < n && j - i <= 32 && html[j].isLetterOrNumber())
++j;
const QStringView name = QStringView(html).mid(i + 1, j - i - 1);
if (j < n && html[j] == QLatin1Char(';') && !name.isEmpty()) {
if (isXmlEntity(name)) {
out += QStringView(html).mid(i, j - i + 1);
} else if (const auto it = entityTable().constFind(name.toString()); it != entityTable().cend()) {
out += QStringLiteral("&#") + QString::number(it.value()) + QLatin1Char(';');
} else {
out += QStringLiteral("&amp;") + name + QLatin1Char(';');
}
i = j + 1;
} else {
out += QStringLiteral("&amp;"); // bare ampersand
++i;
}
}
return out;
}
} // namespace HtmlEntities
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include <QString>
namespace HtmlEntities {
// Rewrites HTML named character references (e.g. "&nbsp;", "&mdash;") to
// numeric references so the text parses as plain XML. The five XML entities
// are kept; unknown names are escaped ("&foo;" -> "&amp;foo;") so the parse
// does not fail on them.
QString toXmlSafe(const QString &html);
} // namespace HtmlEntities
+217
View File
@@ -0,0 +1,217 @@
#include "WebImageProvider.h"
#include <QCryptographicHash>
#include <QDir>
#include <QEventLoop>
#include <QFile>
#include <QFileInfo>
#include <QMutexLocker>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSaveFile>
#include <QStandardPaths>
#include <QThreadPool>
#include <QUrl>
#include "AsyncImageResponse.h"
#include "ImageScaling.h"
// ---------------------------------------------------------------------------
// DiskWebImageStorage
// ---------------------------------------------------------------------------
DiskWebImageStorage::DiskWebImageStorage()
: DiskWebImageStorage(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/web-images"))
{
}
DiskWebImageStorage::DiskWebImageStorage(QString baseDir)
: m_baseDir(std::move(baseDir))
{
if (!m_baseDir.isEmpty()) {
QDir().mkpath(m_baseDir);
}
}
QString DiskWebImageStorage::filePathForKey(const QString &key) const
{
return m_baseDir + QLatin1Char('/') + key;
}
bool DiskWebImageStorage::contains(const QString &key) const
{
QMutexLocker lock(&m_mutex);
return QFile::exists(filePathForKey(key));
}
QByteArray DiskWebImageStorage::read(const QString &key) const
{
QMutexLocker lock(&m_mutex);
QFile f(filePathForKey(key));
if (f.open(QIODevice::ReadOnly))
return f.readAll();
return {};
}
bool DiskWebImageStorage::write(const QString &key, const QByteArray &data)
{
QMutexLocker lock(&m_mutex);
if (m_baseDir.isEmpty() || data.isEmpty())
return false;
QDir().mkpath(m_baseDir);
QSaveFile f(filePathForKey(key));
if (!f.open(QIODevice::WriteOnly))
return false;
f.write(data);
return f.commit();
}
// ---------------------------------------------------------------------------
// Default Network Fetcher
// ---------------------------------------------------------------------------
static QByteArray defaultHttpFetch(const QString &urlString)
{
QUrl url(urlString);
if (!url.isValid() || (url.scheme() != QLatin1String("http") && url.scheme() != QLatin1String("https")))
return {};
QNetworkAccessManager nam;
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::UserAgentHeader, QStringLiteral("Asteria/1.0"));
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
request.setTransferTimeout(5000);
QNetworkReply *reply = nam.get(request);
QEventLoop loop;
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (reply->error() != QNetworkReply::NoError) {
reply->deleteLater();
return {};
}
const QByteArray data = reply->readAll();
reply->deleteLater();
return data;
}
// ---------------------------------------------------------------------------
// WebImageProvider
// ---------------------------------------------------------------------------
WebImageProvider::WebImageProvider()
: WebImageProvider(std::make_shared<DiskWebImageStorage>(), defaultHttpFetch)
{
}
WebImageProvider::WebImageProvider(std::shared_ptr<IWebImageStorage> storage,
HttpFetcher fetcher)
: m_storage(std::move(storage))
, m_fetcher(fetcher ? std::move(fetcher) : defaultHttpFetch)
{
}
WebImageProvider *WebImageProvider::defaultInstance()
{
static WebImageProvider s_instance;
return &s_instance;
}
void WebImageProvider::setStorage(std::shared_ptr<IWebImageStorage> storage)
{
QMutexLocker lock(&m_imageMutex);
m_storage = std::move(storage);
m_memoryCache.clear();
}
void WebImageProvider::setFetcher(HttpFetcher fetcher)
{
QMutexLocker lock(&m_imageMutex);
m_fetcher = fetcher ? std::move(fetcher) : defaultHttpFetch;
}
QString WebImageProvider::cacheKey(const QString &url)
{
const QByteArray hash = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Sha256).toHex();
const QString ext = QFileInfo(QUrl(url).path()).suffix().toLower();
if (!ext.isEmpty() && (ext == QLatin1String("png") || ext == QLatin1String("jpg")
|| ext == QLatin1String("jpeg") || ext == QLatin1String("gif")
|| ext == QLatin1String("webp") || ext == QLatin1String("svg"))) {
return QString::fromLatin1(hash) + QLatin1Char('.') + ext;
}
return QString::fromLatin1(hash);
}
QImage WebImageProvider::fetchImage(const QString &urlString, const QSize &requestedSize)
{
if (urlString.isEmpty())
return {};
// 1. In-memory cache
{
QMutexLocker lock(&m_imageMutex);
auto it = m_memoryCache.find(urlString);
if (it != m_memoryCache.end())
return scaleToFit(*it, requestedSize);
}
const QString key = cacheKey(urlString);
// 2. Persistent storage (disk or mock)
if (m_storage && m_storage->contains(key)) {
const QByteArray data = m_storage->read(key);
if (!data.isEmpty()) {
QImage img;
if (img.loadFromData(data)) {
QMutexLocker lock(&m_imageMutex);
m_memoryCache.insert(urlString, img);
return scaleToFit(img, requestedSize);
}
}
}
// 3. Network fetch
if (!m_fetcher)
return {};
const QByteArray fetched = m_fetcher(urlString);
if (fetched.isEmpty())
return {};
QImage img;
if (!img.loadFromData(fetched))
return {};
// Store
if (m_storage) {
m_storage->write(key, fetched);
}
{
QMutexLocker lock(&m_imageMutex);
m_memoryCache.insert(urlString, img);
}
return scaleToFit(img, requestedSize);
}
QQuickImageResponse *WebImageProvider::requestImageResponse(const QString &id,
const QSize &requestedSize)
{
if (id == QLatin1String("__warmup__")) {
auto *response = new AsyncImageResponse([] { return QImage(); });
QMetaObject::invokeMethod(response, "finished", Qt::QueuedConnection);
return response;
}
auto *response = new AsyncImageResponse([this, id, requestedSize]() -> QImage {
return fetchImage(id, requestedSize);
});
QThreadPool::globalInstance()->start(response);
return response;
}
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include <QByteArray>
#include <QImage>
#include <QMutex>
#include <QQuickAsyncImageProvider>
#include <QString>
#include <functional>
#include <memory>
class IWebImageStorage {
public:
virtual ~IWebImageStorage() = default;
virtual bool contains(const QString &key) const = 0;
virtual QByteArray read(const QString &key) const = 0;
virtual bool write(const QString &key, const QByteArray &data) = 0;
};
class DiskWebImageStorage : public IWebImageStorage {
public:
DiskWebImageStorage();
explicit DiskWebImageStorage(QString baseDir);
bool contains(const QString &key) const override;
QByteArray read(const QString &key) const override;
bool write(const QString &key, const QByteArray &data) override;
QString cacheDir() const { return m_baseDir; }
private:
QString filePathForKey(const QString &key) const;
QString m_baseDir;
mutable QMutex m_mutex;
};
class WebImageProvider : public QQuickAsyncImageProvider {
public:
using HttpFetcher = std::function<QByteArray(const QString &url)>;
WebImageProvider();
explicit WebImageProvider(std::shared_ptr<IWebImageStorage> storage,
HttpFetcher fetcher = nullptr);
QQuickImageResponse *requestImageResponse(const QString &id,
const QSize &requestedSize) override;
QString scheme() const { return QStringLiteral("web"); }
static QString cacheKey(const QString &url);
// Synchronous download or cache lookup (safe across threads)
QImage fetchImage(const QString &url, const QSize &requestedSize = {});
// Set custom storage & fetcher (e.g. for unit tests)
void setStorage(std::shared_ptr<IWebImageStorage> storage);
void setFetcher(HttpFetcher fetcher);
// Global default instance for non-QML direct resolution
static WebImageProvider *defaultInstance();
private:
std::shared_ptr<IWebImageStorage> m_storage;
HttpFetcher m_fetcher;
mutable QMutex m_imageMutex;
QHash<QString, QImage> m_memoryCache;
};
+57 -7
View File
@@ -2,7 +2,6 @@
#include <algorithm>
#include <QBuffer>
#include <QCollator>
#include <QFileInfo>
#include <QImageReader>
#include <QXmlStreamReader>
@@ -55,17 +54,68 @@ static void parseComicInfo(const QByteArray &data,
outAuthor = writer;
}
static int naturalCompare(QStringView a, QStringView b)
{
int i = 0, j = 0;
const int lenA = a.size();
const int lenB = b.size();
while (i < lenA && j < lenB) {
const QChar ca = a[i];
const QChar cb = b[j];
if (ca.isDigit() && cb.isDigit()) {
const int startA = i;
while (i < lenA && a[i] == QLatin1Char('0'))
++i;
const int startB = j;
while (j < lenB && b[j] == QLatin1Char('0'))
++j;
const int numStartA = i;
while (i < lenA && a[i].isDigit())
++i;
const int numStartB = j;
while (j < lenB && b[j].isDigit())
++j;
const int numLenA = i - numStartA;
const int numLenB = j - numStartB;
if (numLenA != numLenB)
return (numLenA < numLenB) ? -1 : 1;
for (int kA = numStartA, kB = numStartB; kA < i; ++kA, ++kB) {
if (a[kA] != b[kB])
return (a[kA] < b[kB]) ? -1 : 1;
}
const int zerosA = numStartA - startA;
const int zerosB = numStartB - startB;
if (zerosA != zerosB)
return (zerosA < zerosB) ? -1 : 1;
} else {
const QChar la = ca.toLower();
const QChar lb = cb.toLower();
if (la != lb)
return (la < lb) ? -1 : 1;
++i;
++j;
}
}
if (i < lenA) return 1;
if (j < lenB) return -1;
return 0;
}
static void naturalSortEntries(QStringList &entries)
{
if (entries.size() <= 1)
return;
QCollator collator{QLocale(QLocale::English)};
collator.setNumericMode(true);
collator.setCaseSensitivity(Qt::CaseInsensitive);
std::sort(entries.begin(), entries.end(), [&collator](const QString &a, const QString &b) {
const int cmp = collator.compare(a, b);
std::sort(entries.begin(), entries.end(), [](const QString &a, const QString &b) {
const int cmp = naturalCompare(a, b);
if (cmp != 0)
return cmp < 0;
return a < b;
+80 -29
View File
@@ -1,20 +1,19 @@
#include "ZipByteSource.h"
#include <minizip/unzip.h>
#include <QMutexLocker>
#include <memory>
namespace {
QByteArray readZipEntry(unzFile zf, const char *entryName)
QByteArray readCurrentZipEntry(unzFile zf)
{
if (unzLocateFile(zf, entryName, 0) != UNZ_OK)
return {};
if (unzOpenCurrentFile(zf) != UNZ_OK)
return {};
QByteArray result;
char buf[4096];
int bytesRead;
char buf[16384];
int bytesRead = 0;
while ((bytesRead = unzReadCurrentFile(zf, buf, sizeof(buf))) > 0)
result.append(buf, bytesRead);
@@ -22,27 +21,56 @@ QByteArray readZipEntry(unzFile zf, const char *entryName)
return (bytesRead == 0) ? result : QByteArray{};
}
QStringList listZipEntries(unzFile zf)
} // namespace
ZipByteSource::ZipByteSource() = default;
ZipByteSource::~ZipByteSource()
{
QStringList entries;
if (unzGoToFirstFile(zf) != UNZ_OK)
return entries;
do {
char name[4096];
unz_file_info64 info{};
if (unzGetCurrentFileInfo64(zf, &info, name, static_cast<uLong>(sizeof(name) - 1),
nullptr, 0, nullptr, 0) == UNZ_OK) {
name[sizeof(name) - 1] = '\0';
entries.append(QString::fromUtf8(name));
}
} while (unzGoToNextFile(zf) == UNZ_OK);
return entries;
closeArchive();
}
} // namespace
ZipByteSource::ZipByteSource(ZipByteSource &&other) noexcept
{
QMutexLocker locker(&other.m_mutex);
m_path = std::move(other.m_path);
m_hash = std::move(other.m_hash);
m_entries = std::move(other.m_entries);
m_entryPositions = std::move(other.m_entryPositions);
m_zf = other.m_zf;
other.m_zf = nullptr;
}
ZipByteSource &ZipByteSource::operator=(ZipByteSource &&other) noexcept
{
if (this != &other) {
closeArchive();
QMutexLocker locker(&other.m_mutex);
m_path = std::move(other.m_path);
m_hash = std::move(other.m_hash);
m_entries = std::move(other.m_entries);
m_entryPositions = std::move(other.m_entryPositions);
m_zf = other.m_zf;
other.m_zf = nullptr;
}
return *this;
}
void ZipByteSource::closeArchive()
{
QMutexLocker locker(&m_mutex);
if (m_zf) {
unzClose(static_cast<unzFile>(m_zf));
m_zf = nullptr;
}
m_entryPositions.clear();
}
bool ZipByteSource::open(const QString &path)
{
closeArchive();
QMutexLocker locker(&m_mutex);
m_path.clear();
m_hash.clear();
m_entries.clear();
@@ -50,9 +78,24 @@ bool ZipByteSource::open(const QString &path)
unzFile zf = unzOpen(path.toUtf8().constData());
if (!zf)
return false;
m_entries = listZipEntries(zf);
unzClose(zf);
if (unzGoToFirstFile(zf) == UNZ_OK) {
do {
char name[4096];
unz_file_info64 info{};
unz64_file_pos pos{};
unzGetFilePos64(zf, &pos);
if (unzGetCurrentFileInfo64(zf, &info, name, static_cast<uLong>(sizeof(name) - 1),
nullptr, 0, nullptr, 0) == UNZ_OK) {
name[sizeof(name) - 1] = '\0';
const QString entryName = QString::fromUtf8(name);
m_entries.append(entryName);
m_entryPositions.insert(entryName, pos);
}
} while (unzGoToNextFile(zf) == UNZ_OK);
}
m_zf = zf;
m_path = path;
return true;
}
@@ -64,14 +107,22 @@ QStringList ZipByteSource::listEntries() const
QByteArray ZipByteSource::readEntry(const QString &entryName) const
{
if (m_path.isEmpty() || entryName.isEmpty())
QMutexLocker locker(&m_mutex);
if (!m_zf || 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 readZipEntry(zf, entryName.toUtf8().constData());
unzFile zf = static_cast<unzFile>(m_zf);
auto it = m_entryPositions.constFind(entryName);
if (it != m_entryPositions.constEnd()) {
unz64_file_pos pos = it.value();
if (unzGoToFilePos64(zf, &pos) != UNZ_OK)
return {};
} else {
if (unzLocateFile(zf, entryName.toUtf8().constData(), 0) != UNZ_OK)
return {};
}
return readCurrentZipEntry(zf);
}
QByteArray ZipByteSource::contentHash() const
@@ -1,16 +1,32 @@
#pragma once
#include <QHash>
#include <QMutex>
#include <minizip/unzip.h>
#include "backend/formats/IByteSource.h"
class ZipByteSource : public IByteSource {
public:
ZipByteSource();
~ZipByteSource() override;
ZipByteSource(const ZipByteSource &) = delete;
ZipByteSource &operator=(const ZipByteSource &) = delete;
ZipByteSource(ZipByteSource &&other) noexcept;
ZipByteSource &operator=(ZipByteSource &&other) noexcept;
bool open(const QString &path) override;
QStringList listEntries() const override;
QByteArray readEntry(const QString &entryName) const override;
QByteArray contentHash() const override;
private:
void closeArchive();
QString m_path;
mutable QByteArray m_hash;
QStringList m_entries;
QHash<QString, unz64_file_pos> m_entryPositions;
void *m_zf = nullptr;
mutable QMutex m_mutex;
};