fb2 support

This commit is contained in:
Agel committed 2026-10-29 17:31:37 +01:00
1 parent 6fb7798476
commit c5439099f6
18 files changed
+2352 -54

No files matched your search

+3 -31
View File
@@ -12,6 +12,7 @@
#include "backend/formats/HtmlEntities.h"
#include "backend/formats/ImageUrl.h"
#include "backend/reading/layout/CssParser.h"
#include "backend/reading/layout/DomChunkPipeline.h"
EpubReader::EpubReader(SourceFactory sourceFactory, QString scheme)
: m_sourceFactory(std::move(sourceFactory))
@@ -179,38 +180,9 @@ void EpubReader::appendSpineChunks(const QString &xhtml,
}
}
// 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);
}
}
};
// 4. Cascade onto each element, rewrite image URLs & build ContentChunks directly from cascaded DOM
QDomElement root = doc.documentElement();
processElement(root);
// 5. Build ContentChunks directly from cascaded DOM
m_chunks.append(HtmlBlockParser::parseChunks(root, xhtmlHref));
m_chunks.append(DomChunkPipeline::cascadeAndChunk(root, sheet, m_scheme, m_filePath, xhtmlHref, xhtmlDir));
}
bool EpubReader::parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly)
+471
View File
@@ -0,0 +1,471 @@
#include "Fb2Reader.h"
#include <QDomDocument>
#include <QFileInfo>
#include <QRegularExpression>
#include <QStringDecoder>
#include <iconv.h>
#include "backend/formats/AuthorAttribution.h"
#include "backend/formats/ImageUrl.h"
#include "backend/formats/sources/Fb2ByteSource.h"
#include "backend/reading/layout/DomChunkPipeline.h"
namespace {
QString decodeFb2Xml(const QByteArray &bytes)
{
if (bytes.startsWith("\xEF\xBB\xBF"))
return QString::fromUtf8(bytes.constData() + 3, bytes.size() - 3);
if (bytes.startsWith("\xFF\xFE"))
return QString::fromUtf16(reinterpret_cast<const char16_t*>(bytes.constData() + 2), (bytes.size() - 2) / 2);
const int checkLen = qMin(512, bytes.size());
const QByteArray header = bytes.left(checkLen);
static const QRegularExpression encRe(QStringLiteral("encoding\\s*=\\s*[\"']([^\"']+)[\"']"),
QRegularExpression::CaseInsensitiveOption);
const QString headerStr = QString::fromLatin1(header);
const auto match = encRe.match(headerStr);
if (match.hasMatch()) {
const QString enc = match.captured(1).trimmed();
if (enc.compare(QLatin1String("utf-8"), Qt::CaseInsensitive) == 0) {
return QString::fromUtf8(bytes);
}
QStringDecoder decoder(enc.toUtf8().constData());
if (decoder.isValid()) {
QString res = decoder(bytes);
if (!decoder.hasError())
return res;
}
iconv_t cd = iconv_open("UTF-8", enc.toUtf8().constData());
if (cd != (iconv_t)-1) {
size_t inBytesLeft = bytes.size();
char *inBuf = const_cast<char*>(bytes.constData());
size_t outBytesLeft = bytes.size() * 4 + 4;
QByteArray out;
out.resize(outBytesLeft);
char *outBuf = out.data();
if (iconv(cd, &inBuf, &inBytesLeft, &outBuf, &outBytesLeft) != (size_t)-1) {
iconv_close(cd);
return QString::fromUtf8(out.constData(), out.size() - outBytesLeft);
}
iconv_close(cd);
}
}
return QString::fromUtf8(bytes);
}
void mapFb2Children(const QDomElement &srcEl,
QDomElement &dstParent,
QDomDocument &dstDoc,
int depth)
{
for (QDomNode child = srcEl.firstChild(); !child.isNull(); child = child.nextSibling()) {
if (child.isText()) {
dstParent.appendChild(dstDoc.createTextNode(child.toText().data()));
continue;
}
if (!child.isElement())
continue;
const QDomElement el = child.toElement();
const QString tag = el.tagName().toLower();
if (tag == QLatin1String("section")) {
// Child sections are processed separately as independent chunk boundaries
continue;
}
if (tag == QLatin1String("title")) {
const int hLevel = qBound(1, depth, 6);
QDomElement h = dstDoc.createElement(QStringLiteral("h%1").arg(hLevel));
h.setAttribute(QStringLiteral("style"), QStringLiteral("text-align: left; text-indent: 0;"));
bool firstLine = true;
for (QDomNode child = el.firstChild(); !child.isNull(); child = child.nextSibling()) {
if (child.isText()) {
h.appendChild(dstDoc.createTextNode(child.toText().data()));
} else if (child.isElement()) {
const QDomElement childEl = child.toElement();
const QString childTag = childEl.tagName().toLower();
if (childTag == QLatin1String("p") || childTag == QLatin1String("empty-line")) {
if (!firstLine) {
h.appendChild(dstDoc.createElement(QStringLiteral("br")));
}
firstLine = false;
mapFb2Children(childEl, h, dstDoc, depth);
} else {
mapFb2Children(childEl, h, dstDoc, depth);
}
}
}
dstParent.appendChild(h);
} else if (tag == QLatin1String("subtitle")) {
QDomElement p = dstDoc.createElement(QStringLiteral("p"));
p.setAttribute(QStringLiteral("style"), QStringLiteral("text-align: center; font-weight: bold; text-indent: 0;"));
mapFb2Children(el, p, dstDoc, depth);
dstParent.appendChild(p);
} else if (tag == QLatin1String("epigraph") || tag == QLatin1String("cite")) {
QDomElement bq = dstDoc.createElement(QStringLiteral("blockquote"));
mapFb2Children(el, bq, dstDoc, depth);
dstParent.appendChild(bq);
} else if (tag == QLatin1String("poem")) {
QDomElement div = dstDoc.createElement(QStringLiteral("div"));
div.setAttribute(QStringLiteral("style"), QStringLiteral("margin-left: 2em; margin-right: 2em;"));
mapFb2Children(el, div, dstDoc, depth);
dstParent.appendChild(div);
} else if (tag == QLatin1String("stanza")) {
QDomElement div = dstDoc.createElement(QStringLiteral("div"));
div.setAttribute(QStringLiteral("style"), QStringLiteral("margin-top: 1em; margin-bottom: 1em;"));
mapFb2Children(el, div, dstDoc, depth);
dstParent.appendChild(div);
} else if (tag == QLatin1String("v")) {
QDomElement p = dstDoc.createElement(QStringLiteral("p"));
p.setAttribute(QStringLiteral("style"), QStringLiteral("margin: 0; text-indent: 0;"));
mapFb2Children(el, p, dstDoc, depth);
dstParent.appendChild(p);
} else if (tag == QLatin1String("text-author") || tag == QLatin1String("date")) {
QDomElement p = dstDoc.createElement(QStringLiteral("p"));
p.setAttribute(QStringLiteral("style"), QStringLiteral("text-align: right; font-style: italic; text-indent: 0;"));
mapFb2Children(el, p, dstDoc, depth);
dstParent.appendChild(p);
} else if (tag == QLatin1String("empty-line")) {
QDomElement p = dstDoc.createElement(QStringLiteral("p"));
p.setAttribute(QStringLiteral("style"), QStringLiteral("margin: 0.5em 0;"));
p.appendChild(dstDoc.createElement(QStringLiteral("br")));
dstParent.appendChild(p);
} else if (tag == QLatin1String("emphasis")) {
QDomElement em = dstDoc.createElement(QStringLiteral("i"));
mapFb2Children(el, em, dstDoc, depth);
dstParent.appendChild(em);
} else if (tag == QLatin1String("strikethrough")) {
QDomElement s = dstDoc.createElement(QStringLiteral("s"));
mapFb2Children(el, s, dstDoc, depth);
dstParent.appendChild(s);
} else if (tag == QLatin1String("strong")) {
QDomElement b = dstDoc.createElement(QStringLiteral("b"));
mapFb2Children(el, b, dstDoc, depth);
dstParent.appendChild(b);
} else if (tag == QLatin1String("p")) {
QDomElement p = dstDoc.createElement(QStringLiteral("p"));
mapFb2Children(el, p, dstDoc, depth);
dstParent.appendChild(p);
} else if (tag == QLatin1String("a")) {
QDomElement a = dstDoc.createElement(QStringLiteral("a"));
QString href = el.attribute(QStringLiteral("href"));
if (href.isEmpty()) href = el.attribute(QStringLiteral("l:href"));
if (href.isEmpty()) href = el.attribute(QStringLiteral("xlink:href"));
if (!href.isEmpty()) a.setAttribute(QStringLiteral("href"), href);
mapFb2Children(el, a, dstDoc, depth);
dstParent.appendChild(a);
} else if (tag == QLatin1String("image")) {
QDomElement img = dstDoc.createElement(QStringLiteral("img"));
QString href = el.attribute(QStringLiteral("l:href"));
if (href.isEmpty()) href = el.attribute(QStringLiteral("xlink:href"));
if (href.isEmpty()) href = el.attribute(QStringLiteral("href"));
if (!href.isEmpty()) img.setAttribute(QStringLiteral("src"), href);
dstParent.appendChild(img);
} else {
// General element pass-through
QDomElement generic = dstDoc.createElement(el.tagName());
mapFb2Children(el, generic, dstDoc, depth);
dstParent.appendChild(generic);
}
}
}
} // namespace
Fb2Reader::Fb2Reader(SourceFactory sourceFactory, QString scheme)
: m_sourceFactory(std::move(sourceFactory))
, m_scheme(std::move(scheme))
{
}
HistoryFormatLabel Fb2Reader::formatLabelEnum() const
{
if (m_filePath.endsWith(QLatin1String(".fbz"), Qt::CaseInsensitive))
return HistoryFormatLabel::FBZ;
return HistoryFormatLabel::FB2;
}
QString Fb2Reader::formatLabel() const
{
return formatLabelEnum() == HistoryFormatLabel::FBZ ? QStringLiteral("FBZ") : QStringLiteral("FB2");
}
bool Fb2Reader::open(const QString &filePath)
{
m_filePath = filePath;
m_status = Fb2LoadStatus::loading_full;
m_title.clear();
m_author.clear();
m_error.clear();
m_coverImageUrl.clear();
m_authors.clear();
m_binaries.clear();
m_chunks.clear();
m_contentHash.clear();
auto source = m_sourceFactory();
if (!source || !source->open(filePath)) {
m_status = Fb2LoadStatus::failed;
if (auto *fb2Src = dynamic_cast<Fb2ByteSource*>(source.get())) {
m_error = fb2Src->lastError();
}
if (m_error.isEmpty())
m_error = QStringLiteral("Cannot open FB2 file: ") + filePath;
return false;
}
return parseOpen(filePath, *source, false);
}
bool Fb2Reader::loadMetadata(const QString &filePath)
{
m_filePath = filePath;
m_status = Fb2LoadStatus::loading_metadata;
m_title.clear();
m_author.clear();
m_error.clear();
m_coverImageUrl.clear();
m_authors.clear();
m_binaries.clear();
m_chunks.clear();
m_contentHash.clear();
auto source = m_sourceFactory();
if (!source || !source->open(filePath)) {
m_status = Fb2LoadStatus::failed;
if (auto *fb2Src = dynamic_cast<Fb2ByteSource*>(source.get())) {
m_error = fb2Src->lastError();
}
if (m_error.isEmpty())
m_error = QStringLiteral("Cannot open FB2 file: ") + filePath;
return false;
}
return parseOpen(filePath, *source, true);
}
bool Fb2Reader::parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly)
{
m_filePath = filePath;
m_contentHash = source.contentHash();
QByteArray rawXml;
if (auto *fb2Source = dynamic_cast<Fb2ByteSource*>(&source)) {
m_containerKind = fb2Source->containerKind();
rawXml = fb2Source->rawXmlData();
} else {
m_containerKind = (filePath.endsWith(QLatin1String(".fbz"), Qt::CaseInsensitive)
|| filePath.endsWith(QLatin1String(".fb2.zip"), Qt::CaseInsensitive))
? Fb2ContainerKind::zip_archive : Fb2ContainerKind::plain_xml;
rawXml = source.readEntry(QString());
}
const QString decodedXml = decodeFb2Xml(rawXml);
QDomDocument doc;
QString errorMsg;
int errorLine = 0;
int errorColumn = 0;
if (!doc.setContent(decodedXml, &errorMsg, &errorLine, &errorColumn)) {
m_status = Fb2LoadStatus::failed;
m_error = QStringLiteral("Invalid or malformed FictionBook XML");
return false;
}
QDomElement root = doc.documentElement();
if (root.tagName() != QLatin1String("FictionBook")) {
m_status = Fb2LoadStatus::failed;
m_error = QStringLiteral("Invalid or malformed FictionBook XML");
return false;
}
// Binaries
if (auto *fb2Source = dynamic_cast<Fb2ByteSource*>(&source)) {
m_binaries = fb2Source->binaries().values().toVector();
} else {
// Fallback: extract <binary> tags from DOM
QDomNodeList binaryNodes = root.elementsByTagName(QStringLiteral("binary"));
for (int i = 0; i < binaryNodes.size(); ++i) {
QDomElement bEl = binaryNodes.at(i).toElement();
const QString id = bEl.attribute(QStringLiteral("id"));
const QString ct = bEl.attribute(QStringLiteral("content-type"));
const QByteArray decoded = QByteArray::fromBase64(bEl.text().trimmed().toUtf8());
BinaryResource res;
res.id = id;
if (!ct.isEmpty())
res.content_type = ct;
res.decoded_bytes = decoded;
m_binaries.append(res);
}
}
// Metadata extraction
QDomElement desc = root.firstChildElement(QLatin1String("description"));
QDomElement titleInfo = desc.firstChildElement(QLatin1String("title-info"));
// Title
m_title = titleInfo.firstChildElement(QLatin1String("book-title")).text().trimmed();
if (m_title.isEmpty()) {
m_title = QFileInfo(filePath).completeBaseName();
}
// Authors
QStringList formattedAuthors;
for (QDomElement child = titleInfo.firstChildElement(); !child.isNull(); child = child.nextSiblingElement()) {
if (child.tagName() == QLatin1String("author")) {
AuthorName an;
QDomElement fn = child.firstChildElement(QLatin1String("first-name"));
if (!fn.isNull()) an.first_name = fn.text().trimmed();
QDomElement mn = child.firstChildElement(QLatin1String("middle-name"));
if (!mn.isNull()) an.middle_name = mn.text().trimmed();
QDomElement ln = child.firstChildElement(QLatin1String("last-name"));
if (!ln.isNull()) an.last_name = ln.text().trimmed();
QDomElement nn = child.firstChildElement(QLatin1String("nickname"));
if (!nn.isNull()) an.nickname = nn.text().trimmed();
m_authors.append(an);
const QString fmt = an.format();
if (!fmt.isEmpty())
formattedAuthors << fmt;
}
}
m_author = formattedAuthors.join(QStringLiteral(", "));
// Cover image
QString coverId;
QDomElement coverpage = titleInfo.firstChildElement(QLatin1String("coverpage"));
if (!coverpage.isNull()) {
QDomElement img = coverpage.firstChildElement(QLatin1String("image"));
if (!img.isNull()) {
QString href = img.attribute(QStringLiteral("l:href"));
if (href.isEmpty()) href = img.attribute(QStringLiteral("xlink:href"));
if (href.isEmpty()) href = img.attribute(QStringLiteral("href"));
if (href.startsWith(QLatin1Char('#')))
href.remove(0, 1);
coverId = href;
}
}
if (coverId.isEmpty()) {
for (const auto &b : m_binaries) {
if (b.id.contains(QLatin1String("cover"), Qt::CaseInsensitive)
&& (!b.content_type.has_value() || b.content_type->isEmpty() || b.content_type->startsWith(QLatin1String("image/"), Qt::CaseInsensitive))) {
coverId = b.id;
break;
}
}
}
if (!coverId.isEmpty()) {
m_coverImageUrl = ImageUrl::build(m_scheme, coverId, m_filePath);
} else {
m_coverImageUrl.clear();
}
if (metadataOnly) {
m_chunks.clear();
m_status = Fb2LoadStatus::loaded;
return true;
}
// Stylesheets
QStringList stylesheetTexts;
for (QDomElement child = root.firstChildElement(); !child.isNull(); child = child.nextSiblingElement()) {
if (child.tagName() == QLatin1String("stylesheet") &&
(child.attribute(QStringLiteral("type")).isEmpty() || child.attribute(QStringLiteral("type")) == QLatin1String("text/css"))) {
stylesheetTexts << child.text();
}
}
// Process sections helper
std::function<void(const QDomElement &, const QString &, int)> processSection =
[&](const QDomElement &secEl, const QString &secHref, int depth) {
QDomDocument secDoc;
QDomElement secRoot = secDoc.createElement(QStringLiteral("div"));
secDoc.appendChild(secRoot);
mapFb2Children(secEl, secRoot, secDoc, depth);
if (secRoot.hasChildNodes()) {
m_chunks.append(DomChunkPipeline::cascadeAndChunk(secRoot, stylesheetTexts, m_scheme, m_filePath, secHref, QString(), 512));
}
int childSecIndex = 0;
for (QDomElement child = secEl.firstChildElement(); !child.isNull(); child = child.nextSiblingElement()) {
if (child.tagName().toLower() == QLatin1String("section")) {
QString childHref = child.attribute(QStringLiteral("id"));
if (childHref.isEmpty()) {
childHref = QStringLiteral("%1/section-%2").arg(secHref).arg(childSecIndex++);
}
processSection(child, childHref, depth + 1);
}
}
};
// 1. Prepend <description><title-info><annotation> if present
QDomElement annotationEl = titleInfo.firstChildElement(QLatin1String("annotation"));
if (!annotationEl.isNull()) {
QString annotHref = annotationEl.attribute(QStringLiteral("id"));
if (annotHref.isEmpty())
annotHref = QStringLiteral("annotation");
processSection(annotationEl, annotHref, 1);
}
// 2. All <body> elements in document order
int bodyIndex = 0;
for (QDomElement child = root.firstChildElement(); !child.isNull(); child = child.nextSiblingElement()) {
if (child.tagName().toLower() == QLatin1String("body")) {
const QString bodyPrefix = QStringLiteral("body-%1").arg(bodyIndex++);
QDomElement firstSec = child.firstChildElement(QLatin1String("section"));
if (firstSec.isNull()) {
// Whole body without sections
QString bodyHref = child.attribute(QStringLiteral("id"));
if (bodyHref.isEmpty()) bodyHref = child.attribute(QLatin1String("name"));
if (bodyHref.isEmpty()) bodyHref = bodyPrefix;
processSection(child, bodyHref, 1);
} else {
// Direct elements before sections (e.g. body title, epigraph)
QDomDocument secDoc;
QDomElement secRoot = secDoc.createElement(QStringLiteral("div"));
secDoc.appendChild(secRoot);
mapFb2Children(child, secRoot, secDoc, 1);
if (secRoot.hasChildNodes()) {
QString headerHref = child.attribute(QStringLiteral("id"));
if (headerHref.isEmpty()) headerHref = bodyPrefix;
m_chunks.append(DomChunkPipeline::cascadeAndChunk(secRoot, stylesheetTexts, m_scheme, m_filePath, headerHref, QString(), 512));
}
int secIdx = 0;
for (QDomElement sec = child.firstChildElement(); !sec.isNull(); sec = sec.nextSiblingElement()) {
if (sec.tagName().toLower() == QLatin1String("section")) {
QString secHref = sec.attribute(QStringLiteral("id"));
if (secHref.isEmpty())
secHref = QStringLiteral("%1/section-%2").arg(bodyPrefix).arg(secIdx++);
processSection(sec, secHref, 1);
}
}
}
}
}
// Fallback if no chunks were extracted
if (m_chunks.isEmpty()) {
ContentChunk fallbackChunk;
fallbackChunk.sectionHref = m_filePath;
BlockItem p;
p.kind = BlockItem::Kind::Paragraph;
fallbackChunk.blocks.append(p);
m_chunks.append(fallbackChunk);
}
m_status = Fb2LoadStatus::loaded;
return true;
}
+62
View File
@@ -0,0 +1,62 @@
#pragma once
#include <functional>
#include <memory>
#include <QByteArray>
#include <QHash>
#include <QString>
#include <QStringList>
#include <QVector>
#include "backend/FormatReader.h"
#include "backend/formats/IByteSource.h"
#include "backend/formats/Fb2Types.h"
class Fb2Reader : public FormatReader {
public:
using SourceFactory = std::function<std::unique_ptr<IByteSource>()>;
Fb2Reader(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 { return m_coverImageUrl; }
QByteArray contentHash() const override { return m_contentHash; }
QVector<ContentChunk> chunks() const override { return m_chunks; }
// Spec properties
Fb2LoadStatus status() const { return m_status; }
Fb2ContainerKind containerKind() const { return m_containerKind; }
HistoryFormatLabel formatLabelEnum() const;
QString formatLabel() const;
const QVector<AuthorName> &authors() const { return m_authors; }
const QVector<BinaryResource> &binaries() const { return m_binaries; }
private:
bool parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly);
SourceFactory m_sourceFactory;
QString m_scheme;
QString m_filePath;
QByteArray m_contentHash;
QString m_title;
QString m_author;
QString m_error;
QString m_coverImageUrl;
Fb2LoadStatus m_status = Fb2LoadStatus::idle;
Fb2ContainerKind m_containerKind = Fb2ContainerKind::plain_xml;
QVector<AuthorName> m_authors;
QVector<BinaryResource> m_binaries;
QVector<ContentChunk> m_chunks;
};
+119
View File
@@ -0,0 +1,119 @@
#pragma once
#include <optional>
#include <QByteArray>
#include <QString>
#include <QStringList>
#include "backend/reading/layout/HtmlBlockParser.h"
struct AuthorName {
std::optional<QString> first_name;
std::optional<QString> middle_name;
std::optional<QString> last_name;
std::optional<QString> nickname;
bool has_structured_name() const
{
return first_name.has_value() || middle_name.has_value() || last_name.has_value();
}
QString format() const
{
QStringList parts;
if (first_name.has_value() && !first_name->trimmed().isEmpty())
parts << first_name->trimmed();
if (middle_name.has_value() && !middle_name->trimmed().isEmpty())
parts << middle_name->trimmed();
if (last_name.has_value() && !last_name->trimmed().isEmpty())
parts << last_name->trimmed();
if (!parts.isEmpty())
return parts.join(QLatin1Char(' '));
if (nickname.has_value() && !nickname->trimmed().isEmpty())
return nickname->trimmed();
return {};
}
bool operator==(const AuthorName &o) const
{
return first_name == o.first_name &&
middle_name == o.middle_name &&
last_name == o.last_name &&
nickname == o.nickname;
}
bool operator!=(const AuthorName &o) const
{
return !(*this == o);
}
};
struct BinaryResource {
QString id;
std::optional<QString> content_type;
QByteArray decoded_bytes;
bool operator==(const BinaryResource &o) const
{
return id == o.id &&
content_type == o.content_type &&
decoded_bytes == o.decoded_bytes;
}
bool operator!=(const BinaryResource &o) const
{
return !(*this == o);
}
};
struct ContentChunkValue {
QString section_href;
int blocks_count = 0;
int word_count = 0;
int char_count = 0;
int unnested_containers = 0;
static ContentChunkValue fromChunk(const ContentChunk &c)
{
return ContentChunkValue{
c.sectionHref,
static_cast<int>(c.blocks.size()),
c.wordCount,
c.charCount,
c.unnestedContainers
};
}
bool operator==(const ContentChunkValue &o) const
{
return section_href == o.section_href &&
blocks_count == o.blocks_count &&
word_count == o.word_count &&
char_count == o.char_count &&
unnested_containers == o.unnested_containers;
}
bool operator!=(const ContentChunkValue &o) const
{
return !(*this == o);
}
};
enum class Fb2ContainerKind {
plain_xml,
zip_archive
};
enum class Fb2LoadStatus {
idle,
loading_metadata,
loading_full,
loaded,
failed
};
enum class HistoryFormatLabel {
FB2,
FBZ
};
+25 -4
View File
@@ -4,9 +4,11 @@
#include "backend/FormatReader.h"
#include "backend/formats/comic/ComicReader.h"
#include "backend/formats/EpubReader.h"
#include "backend/formats/Fb2Reader.h"
#include <QFileInfo>
#include <QQmlEngine>
#include <QSet>
FormatSpec FormatSpec::comic(const QString &ext, bool matchesDirectory, const QString &scheme,
SourceFactory makeSource)
@@ -31,6 +33,17 @@ FormatSpec FormatSpec::epub(SourceFactory makeSource)
};
}
FormatSpec FormatSpec::fb2(const QString &ext, SourceFactory makeSource)
{
return FormatSpec{
ext,
false,
QStringLiteral("fb2"),
[makeSource] { return std::make_unique<Fb2Reader>(makeSource, QStringLiteral("fb2")); },
makeSource
};
}
FormatRegistry::FormatRegistry(QVector<FormatSpec> specs)
: m_specs(std::move(specs))
{
@@ -40,11 +53,16 @@ const FormatSpec *FormatRegistry::specFor(const QString &filePath) const
{
const QFileInfo fi(filePath);
const bool isDir = fi.isDir();
const QString ext = fi.suffix().toLower();
const QString lowerPath = filePath.toLower();
for (const FormatSpec &spec : m_specs) {
if (isDir ? spec.matchesDirectory : (!spec.matchesDirectory && spec.extension == ext))
return &spec;
if (isDir) {
if (spec.matchesDirectory)
return &spec;
} else if (!spec.matchesDirectory) {
if (lowerPath.endsWith(QLatin1Char('.') + spec.extension.toLower()))
return &spec;
}
}
return nullptr;
}
@@ -75,9 +93,12 @@ QStringList FormatRegistry::supportedExtensions() const
void FormatRegistry::registerImageProviders(QQmlEngine &engine) const
{
QSet<QString> registeredSchemes;
for (const FormatSpec &spec : m_specs) {
if (!spec.scheme.isEmpty() && spec.makeSource)
if (!spec.scheme.isEmpty() && spec.makeSource && !registeredSchemes.contains(spec.scheme)) {
registeredSchemes.insert(spec.scheme);
engine.addImageProvider(spec.scheme,
new EntryImageProvider(spec.makeSource, spec.scheme));
}
}
}
+1
View File
@@ -26,6 +26,7 @@ struct FormatSpec {
static FormatSpec comic(const QString &ext, bool matchesDirectory, const QString &scheme,
SourceFactory makeSource);
static FormatSpec epub(SourceFactory makeSource);
static FormatSpec fb2(const QString &ext, SourceFactory makeSource);
};
class FormatRegistry {
@@ -0,0 +1,192 @@
#include "Fb2ByteSource.h"
#include <QFile>
#include <QFileInfo>
#include <QRegularExpression>
#include <QXmlStreamReader>
#include "backend/formats/sources/ZipByteSource.h"
namespace {
bool isZipFile(const QString &path)
{
if (path.endsWith(QLatin1String(".fbz"), Qt::CaseInsensitive)
|| path.endsWith(QLatin1String(".fb2.zip"), Qt::CaseInsensitive)
|| path.endsWith(QLatin1String(".zip"), Qt::CaseInsensitive)) {
return true;
}
QFile f(path);
if (f.open(QIODevice::ReadOnly)) {
const QByteArray magic = f.read(4);
if (magic.size() >= 4 && magic[0] == 'P' && magic[1] == 'K' && (magic[2] == 3 || magic[2] == 5 || magic[2] == 7))
return true;
}
return false;
}
qsizetype findCaseInsensitive(const QByteArray &haystack, const QByteArray &needle, qsizetype from = 0)
{
const qsizetype nLen = needle.size();
const qsizetype hLen = haystack.size();
if (nLen == 0 || from >= hLen)
return -1;
for (qsizetype i = qMax(qsizetype(0), from); i <= hLen - nLen; ++i) {
bool match = true;
for (qsizetype j = 0; j < nLen; ++j) {
char c1 = haystack[i + j];
char c2 = needle[j];
if (c1 >= 'A' && c1 <= 'Z') c1 += 32;
if (c2 >= 'A' && c2 <= 'Z') c2 += 32;
if (c1 != c2) {
match = false;
break;
}
}
if (match)
return i;
}
return -1;
}
} // namespace
Fb2ByteSource::Fb2ByteSource() = default;
Fb2ByteSource::~Fb2ByteSource() = default;
bool Fb2ByteSource::open(const QString &path)
{
m_path = path;
m_error.clear();
m_binaries.clear();
m_archiveEntries.clear();
m_rawXmlData.clear();
m_hash.clear();
if (isZipFile(path)) {
m_containerKind = Fb2ContainerKind::zip_archive;
ZipByteSource zip;
if (!zip.open(path)) {
m_error = QStringLiteral("Cannot open zip archive: ") + path;
return false;
}
m_archiveEntries = zip.listEntries();
if (m_archiveEntries.isEmpty()) {
m_error = QStringLiteral("Archive contains no readable FB2 entry");
return false;
}
QString fb2Entry;
for (const QString &entry : m_archiveEntries) {
if (entry.endsWith(QLatin1String(".fb2"), Qt::CaseInsensitive)) {
fb2Entry = entry;
break;
}
}
if (fb2Entry.isEmpty()) {
fb2Entry = m_archiveEntries.first();
}
m_rawXmlData = zip.readEntry(fb2Entry);
if (m_rawXmlData.isEmpty()) {
m_error = QStringLiteral("Archive contains no readable FB2 entry");
return false;
}
m_hash = zip.contentHash();
} else {
m_containerKind = Fb2ContainerKind::plain_xml;
QFile file(path);
if (!file.open(QIODevice::ReadOnly)) {
m_error = QStringLiteral("Cannot open FB2 file: ") + path;
return false;
}
m_rawXmlData = file.readAll();
m_hash = IByteSource::hashFileMd5(path);
}
extractBinaries(m_rawXmlData);
return true;
}
QStringList Fb2ByteSource::listEntries() const
{
return m_binaries.keys();
}
QByteArray Fb2ByteSource::readEntry(const QString &entryName) const
{
QString key = entryName;
if (key.startsWith(QLatin1Char('#')))
key.remove(0, 1);
auto it = m_binaries.constFind(key);
if (it != m_binaries.constEnd())
return it.value().decoded_bytes;
return {};
}
QByteArray Fb2ByteSource::contentHash() const
{
return m_hash;
}
void Fb2ByteSource::extractBinaries(const QByteArray &xmlData)
{
static const QByteArray kBinaryStart("<binary");
static const QByteArray kBinaryEnd("</binary>");
qsizetype pos = 0;
while ((pos = findCaseInsensitive(xmlData, kBinaryStart, pos)) >= 0) {
qsizetype tagEnd = xmlData.indexOf('>', pos + kBinaryStart.size());
if (tagEnd < 0)
break;
qsizetype closePos = findCaseInsensitive(xmlData, kBinaryEnd, tagEnd + 1);
if (closePos < 0)
break;
// Parse attributes from <binary ...>
const QByteArray tagHeader = xmlData.mid(pos, tagEnd - pos + 1);
QXmlStreamReader tagXml(tagHeader + "</binary>");
QString id;
QString contentType;
if (tagXml.readNextStartElement() && tagXml.name().compare(QLatin1String("binary"), Qt::CaseInsensitive) == 0) {
const auto attrs = tagXml.attributes();
id = attrs.value(QLatin1String("id")).toString();
contentType = attrs.value(QLatin1String("content-type")).toString();
}
if (id.isEmpty()) {
static const QRegularExpression idRe(QStringLiteral("id\\s*=\\s*[\"']([^\"']+)[\"']"),
QRegularExpression::CaseInsensitiveOption);
static const QRegularExpression ctRe(QStringLiteral("content-type\\s*=\\s*[\"']([^\"']+)[\"']"),
QRegularExpression::CaseInsensitiveOption);
const QString headerStr = QString::fromLatin1(tagHeader);
auto idMatch = idRe.match(headerStr);
if (idMatch.hasMatch())
id = idMatch.captured(1);
auto ctMatch = ctRe.match(headerStr);
if (ctMatch.hasMatch())
contentType = ctMatch.captured(1);
}
if (id.startsWith(QLatin1Char('#')))
id.remove(0, 1);
if (!id.isEmpty()) {
const QByteArray base64Bytes = xmlData.mid(tagEnd + 1, closePos - (tagEnd + 1)).trimmed();
const QByteArray decoded = QByteArray::fromBase64(base64Bytes);
BinaryResource res;
res.id = id;
if (!contentType.isEmpty())
res.content_type = contentType;
res.decoded_bytes = decoded;
m_binaries.insert(id, res);
}
pos = closePos + kBinaryEnd.size();
}
}
@@ -0,0 +1,37 @@
#pragma once
#include <QByteArray>
#include <QHash>
#include <QString>
#include <QStringList>
#include "backend/formats/IByteSource.h"
#include "backend/formats/Fb2Types.h"
class Fb2ByteSource : public IByteSource {
public:
Fb2ByteSource();
~Fb2ByteSource() override;
bool open(const QString &path) override;
QStringList listEntries() const override;
QByteArray readEntry(const QString &entryName) const override;
QByteArray contentHash() const override;
const QByteArray &rawXmlData() const { return m_rawXmlData; }
Fb2ContainerKind containerKind() const { return m_containerKind; }
const QStringList &archiveEntries() const { return m_archiveEntries; }
const QHash<QString, BinaryResource> &binaries() const { return m_binaries; }
QString lastError() const { return m_error; }
private:
void extractBinaries(const QByteArray &xmlData);
QString m_path;
QByteArray m_hash;
QByteArray m_rawXmlData;
Fb2ContainerKind m_containerKind = Fb2ContainerKind::plain_xml;
QStringList m_archiveEntries;
QHash<QString, BinaryResource> m_binaries;
QString m_error;
};