some refactor
This commit is contained in:
20 files changed
+1204
-948
No files matched your search
@@ -12,7 +12,7 @@
|
||||
#include "backend/formats/HtmlEntities.h"
|
||||
#include "backend/formats/ImageUrl.h"
|
||||
#include "backend/reading/layout/CssParser.h"
|
||||
#include "backend/reading/layout/DomChunkPipeline.h"
|
||||
#include "backend/reading/layout/HtmlBlockParser.h"
|
||||
|
||||
EpubReader::EpubReader(SourceFactory sourceFactory, QString scheme)
|
||||
: m_sourceFactory(std::move(sourceFactory))
|
||||
@@ -180,17 +180,36 @@ void EpubReader::appendSpineChunks(const QString &xhtml,
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Cascade onto each element, rewrite image URLs & build ContentChunks directly from cascaded DOM
|
||||
// 4. Cascade onto each element, resolve image URLs & build ContentChunks directly
|
||||
QDomElement root = doc.documentElement();
|
||||
m_chunks.append(DomChunkPipeline::cascadeAndChunk(root, sheet, m_scheme, m_filePath, xhtmlHref, xhtmlDir));
|
||||
m_chunks.append(HtmlBlockParser::parseChunks(root, xhtmlHref, 512, {}, &sheet, m_scheme, m_filePath, xhtmlDir));
|
||||
}
|
||||
|
||||
bool EpubReader::parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly)
|
||||
bool EpubReader::parseOpen(const QString &filePath, bool metadataOnly)
|
||||
{
|
||||
m_filePath = filePath;
|
||||
m_filePath.clear();
|
||||
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();
|
||||
|
||||
auto source = m_sourceFactory();
|
||||
if (!source || !source->open(filePath)) {
|
||||
m_error = QStringLiteral("Cannot open EPUB file: ") + filePath;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!metadataOnly) {
|
||||
m_contentHash = source->contentHash();
|
||||
}
|
||||
|
||||
// 1. container.xml
|
||||
const QByteArray containerData = source.readEntry(QStringLiteral("META-INF/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;
|
||||
@@ -206,13 +225,13 @@ bool EpubReader::parseOpen(const QString &filePath, IByteSource &source, bool me
|
||||
m_opfDir = (lastSlash >= 0) ? opfPath.left(lastSlash + 1) : QString();
|
||||
|
||||
// 2. OPF
|
||||
const QByteArray opfData = source.readEntry(opfPath);
|
||||
const QByteArray opfData = source->readEntry(opfPath);
|
||||
if (opfData.isEmpty()) {
|
||||
m_error = QStringLiteral("Cannot read OPF file: ") + opfPath;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!parseOpf(opfData, source, metadataOnly)) {
|
||||
if (!parseOpf(opfData, *source, metadataOnly)) {
|
||||
m_error = QStringLiteral("Error parsing OPF package");
|
||||
return false;
|
||||
}
|
||||
@@ -220,14 +239,16 @@ bool EpubReader::parseOpen(const QString &filePath, IByteSource &source, bool me
|
||||
if (m_title.isEmpty())
|
||||
m_title = QFileInfo(filePath).completeBaseName();
|
||||
|
||||
m_filePath = filePath;
|
||||
|
||||
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);
|
||||
const QByteArray xhtmlData = source->readEntry(href);
|
||||
if (!xhtmlData.isEmpty()) {
|
||||
appendSpineChunks(QString::fromUtf8(xhtmlData), href, source, cssCache, loadedFonts);
|
||||
appendSpineChunks(QString::fromUtf8(xhtmlData), href, *source, cssCache, loadedFonts);
|
||||
}
|
||||
}
|
||||
if (m_chunks.isEmpty()) {
|
||||
@@ -240,52 +261,16 @@ bool EpubReader::parseOpen(const QString &filePath, IByteSource &source, bool me
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
return parseOpen(filePath, 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);
|
||||
return parseOpen(filePath, true);
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ private:
|
||||
QString properties;
|
||||
};
|
||||
|
||||
bool parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly);
|
||||
bool parseOpen(const QString &filePath, bool metadataOnly);
|
||||
bool parseContainer(const QByteArray &data, QString &outOpfPath);
|
||||
bool parseOpf(const QByteArray &data, IByteSource &source, bool metadataOnly);
|
||||
void appendSpineChunks(const QString &xhtml,
|
||||
|
||||
@@ -1,182 +1,13 @@
|
||||
#include "Fb2Reader.h"
|
||||
|
||||
#include <functional>
|
||||
#include <QDomDocument>
|
||||
#include <QFileInfo>
|
||||
#include <QRegularExpression>
|
||||
#include <QStringDecoder>
|
||||
#include <iconv.h>
|
||||
|
||||
#include "backend/formats/AuthorAttribution.h"
|
||||
#include "backend/formats/ImageUrl.h"
|
||||
#include "backend/formats/TextEncoding.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
|
||||
#include "backend/reading/layout/HtmlBlockParser.h"
|
||||
|
||||
Fb2Reader::Fb2Reader(SourceFactory sourceFactory, QString scheme)
|
||||
: m_sourceFactory(std::move(sourceFactory))
|
||||
@@ -198,35 +29,18 @@ QString Fb2Reader::formatLabel() const
|
||||
|
||||
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);
|
||||
return parseOpen(filePath, false);
|
||||
}
|
||||
|
||||
bool Fb2Reader::loadMetadata(const QString &filePath)
|
||||
{
|
||||
return parseOpen(filePath, true);
|
||||
}
|
||||
|
||||
bool Fb2Reader::parseOpen(const QString &filePath, bool metadataOnly)
|
||||
{
|
||||
m_filePath = filePath;
|
||||
m_status = Fb2LoadStatus::loading_metadata;
|
||||
m_status = metadataOnly ? Fb2LoadStatus::loading_metadata : Fb2LoadStatus::loading_full;
|
||||
m_title.clear();
|
||||
m_author.clear();
|
||||
m_error.clear();
|
||||
@@ -247,32 +61,24 @@ bool Fb2Reader::loadMetadata(const QString &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();
|
||||
m_contentHash = source->contentHash();
|
||||
|
||||
QByteArray rawXml;
|
||||
if (auto *fb2Source = dynamic_cast<Fb2ByteSource*>(&source)) {
|
||||
if (auto *fb2Source = dynamic_cast<Fb2ByteSource*>(source.get())) {
|
||||
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());
|
||||
rawXml = source->readEntry(QString());
|
||||
}
|
||||
|
||||
const QString decodedXml = decodeFb2Xml(rawXml);
|
||||
const QString decodedXml = TextEncoding::decode(rawXml);
|
||||
|
||||
QDomDocument doc;
|
||||
QString errorMsg;
|
||||
int errorLine = 0;
|
||||
int errorColumn = 0;
|
||||
if (!doc.setContent(decodedXml, &errorMsg, &errorLine, &errorColumn)) {
|
||||
const auto parseResult = doc.setContent(decodedXml);
|
||||
if (!parseResult) {
|
||||
m_status = Fb2LoadStatus::failed;
|
||||
m_error = QStringLiteral("Invalid or malformed FictionBook XML");
|
||||
return false;
|
||||
@@ -286,10 +92,9 @@ bool Fb2Reader::parseOpen(const QString &filePath, IByteSource &source, bool met
|
||||
}
|
||||
|
||||
// Binaries
|
||||
if (auto *fb2Source = dynamic_cast<Fb2ByteSource*>(&source)) {
|
||||
if (auto *fb2Source = dynamic_cast<Fb2ByteSource*>(source.get())) {
|
||||
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();
|
||||
@@ -375,25 +180,19 @@ bool Fb2Reader::parseOpen(const QString &filePath, IByteSource &source, bool met
|
||||
}
|
||||
|
||||
// Stylesheets
|
||||
QStringList stylesheetTexts;
|
||||
Css::StyleSheet fb2Sheet;
|
||||
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();
|
||||
fb2Sheet.append(Css::StyleSheet::parse(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));
|
||||
auto chunks = HtmlBlockParser::parseChunks(secEl, secHref, 512, {}, &fb2Sheet, m_scheme, m_filePath, {}, depth);
|
||||
if (!chunks.isEmpty()) {
|
||||
m_chunks.append(std::move(chunks));
|
||||
}
|
||||
|
||||
int childSecIndex = 0;
|
||||
@@ -432,15 +231,12 @@ bool Fb2Reader::parseOpen(const QString &filePath, IByteSource &source, bool met
|
||||
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);
|
||||
QString headerHref = child.attribute(QStringLiteral("id"));
|
||||
if (headerHref.isEmpty()) headerHref = bodyPrefix;
|
||||
|
||||
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));
|
||||
auto headerChunks = HtmlBlockParser::parseChunks(child, headerHref, 512, {}, &fb2Sheet, m_scheme, m_filePath, {}, 1);
|
||||
if (!headerChunks.isEmpty()) {
|
||||
m_chunks.append(std::move(headerChunks));
|
||||
}
|
||||
|
||||
int secIdx = 0;
|
||||
|
||||
@@ -41,7 +41,7 @@ public:
|
||||
const QVector<BinaryResource> &binaries() const { return m_binaries; }
|
||||
|
||||
private:
|
||||
bool parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly);
|
||||
bool parseOpen(const QString &filePath, bool metadataOnly);
|
||||
|
||||
SourceFactory m_sourceFactory;
|
||||
QString m_scheme;
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
#include "TextEncoding.h"
|
||||
|
||||
#include <QRegularExpression>
|
||||
#include <QStringDecoder>
|
||||
#include <QtGlobal>
|
||||
#include <iconv.h>
|
||||
|
||||
namespace TextEncoding {
|
||||
|
||||
QString detectEncoding(const QByteArray &bytes)
|
||||
{
|
||||
if (bytes.startsWith("\xEF\xBB\xBF"))
|
||||
return QStringLiteral("UTF-8");
|
||||
if (bytes.startsWith("\xFF\xFE"))
|
||||
return QStringLiteral("UTF-16LE");
|
||||
if (bytes.startsWith("\xFE\xFF"))
|
||||
return QStringLiteral("UTF-16BE");
|
||||
|
||||
const int checkLen = qMin(1024, bytes.size());
|
||||
const QString headerStr = QString::fromLatin1(bytes.constData(), checkLen);
|
||||
|
||||
// 1. XML declaration: <?xml version="1.0" encoding="..."?>
|
||||
static const QRegularExpression xmlEncRe(
|
||||
QStringLiteral("encoding\\s*=\\s*[\"']([^\"']+)[\"']"),
|
||||
QRegularExpression::CaseInsensitiveOption);
|
||||
auto match = xmlEncRe.match(headerStr);
|
||||
if (match.hasMatch())
|
||||
return match.captured(1).trimmed();
|
||||
|
||||
// 2. HTML5 meta charset: <meta charset="...">
|
||||
static const QRegularExpression html5CharsetRe(
|
||||
QStringLiteral("<meta\\s+[^>]*charset\\s*=\\s*[\"']?([^\"'>/\\s]+)"),
|
||||
QRegularExpression::CaseInsensitiveOption);
|
||||
match = html5CharsetRe.match(headerStr);
|
||||
if (match.hasMatch())
|
||||
return match.captured(1).trimmed();
|
||||
|
||||
// 3. HTML4 meta http-equiv: <meta http-equiv="Content-Type" content="text/html; charset=...">
|
||||
static const QRegularExpression html4CharsetRe(
|
||||
QStringLiteral("content\\s*=\\s*[\"'][^\"']*charset=([^\"';\\s]+)"),
|
||||
QRegularExpression::CaseInsensitiveOption);
|
||||
match = html4CharsetRe.match(headerStr);
|
||||
if (match.hasMatch())
|
||||
return match.captured(1).trimmed();
|
||||
|
||||
return QString();
|
||||
}
|
||||
|
||||
QString decodeWithEncoding(const QByteArray &bytes, const QString &encodingName)
|
||||
{
|
||||
if (bytes.isEmpty())
|
||||
return QString();
|
||||
|
||||
const QString enc = encodingName.trimmed();
|
||||
if (enc.isEmpty())
|
||||
return QString();
|
||||
|
||||
if (enc.compare(QLatin1String("utf-8"), Qt::CaseInsensitive) == 0 ||
|
||||
enc.compare(QLatin1String("utf8"), Qt::CaseInsensitive) == 0) {
|
||||
return QString::fromUtf8(bytes);
|
||||
}
|
||||
if (enc.compare(QLatin1String("utf-16le"), Qt::CaseInsensitive) == 0 ||
|
||||
enc.compare(QLatin1String("utf16le"), Qt::CaseInsensitive) == 0) {
|
||||
return QString::fromUtf16(reinterpret_cast<const char16_t*>(bytes.constData()), bytes.size() / 2);
|
||||
}
|
||||
if (enc.compare(QLatin1String("utf-16be"), Qt::CaseInsensitive) == 0 ||
|
||||
enc.compare(QLatin1String("utf16be"), Qt::CaseInsensitive) == 0) {
|
||||
QStringDecoder decoder(QStringDecoder::Utf16BE);
|
||||
if (decoder.isValid()) {
|
||||
QString res = decoder(bytes);
|
||||
if (!decoder.hasError())
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
QString decode(const QByteArray &bytes, const QString &hintEncoding)
|
||||
{
|
||||
if (bytes.isEmpty())
|
||||
return QString();
|
||||
|
||||
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);
|
||||
if (bytes.startsWith("\xFE\xFF")) {
|
||||
QStringDecoder decoder(QStringDecoder::Utf16BE);
|
||||
if (decoder.isValid())
|
||||
return decoder(bytes.mid(2));
|
||||
}
|
||||
|
||||
QString enc = detectEncoding(bytes);
|
||||
if (enc.isEmpty())
|
||||
enc = hintEncoding;
|
||||
|
||||
if (!enc.isEmpty()) {
|
||||
const QString decoded = decodeWithEncoding(bytes, enc);
|
||||
if (!decoded.isEmpty())
|
||||
return decoded;
|
||||
}
|
||||
|
||||
return QString::fromUtf8(bytes);
|
||||
}
|
||||
|
||||
} // namespace TextEncoding
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
|
||||
namespace TextEncoding {
|
||||
|
||||
/**
|
||||
* Sniffs character encoding from BOM or XML / HTML meta headers.
|
||||
* Returns the detected encoding name (e.g. "UTF-8", "windows-1251", "UTF-16LE"),
|
||||
* or an empty QString if no explicit encoding is detected.
|
||||
*/
|
||||
QString detectEncoding(const QByteArray &bytes);
|
||||
|
||||
/**
|
||||
* Decodes raw bytes using a specific encoding name.
|
||||
* Attempts QStringDecoder first, followed by iconv.
|
||||
* Returns empty QString if conversion fails or encoding is unrecognized.
|
||||
*/
|
||||
QString decodeWithEncoding(const QByteArray &bytes, const QString &encodingName);
|
||||
|
||||
/**
|
||||
* Decodes raw byte array into QString.
|
||||
* - Inspects BOM (UTF-8, UTF-16LE, UTF-16BE).
|
||||
* - Detects encoding header if present (XML declaration, HTML meta charset).
|
||||
* - Uses hintEncoding if provided and no header was detected.
|
||||
* - Decodes using QStringDecoder or iconv fallback.
|
||||
* - Defaults to UTF-8 if all else fails.
|
||||
*/
|
||||
QString decode(const QByteArray &bytes, const QString &hintEncoding = QString());
|
||||
|
||||
} // namespace TextEncoding
|
||||
Reference in new issue
Block a user