some refactor
This commit is contained in:
20 files changed
+1195
-939
No files matched your search
@@ -30,9 +30,9 @@ Full target format list:
|
||||
|
||||
| Format | Active | Approach |
|
||||
|----------|---------|-----------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| EPUB | Yes | Unzip (`ZipByteSource`) + parse OPF spine + CSS parser + Knuth-Plass text layout |
|
||||
| FB2 | Yes | `Fb2ByteSource` (plain XML / ZIP) + encoding detection (BOM/XML/iconv) + semantic tag mapping + shared `DomChunkPipeline` + Knuth-Plass |
|
||||
| TXT | Queued | `QTextStream` + encoding detection + paginate for `ChunkLayoutEngine` |
|
||||
| EPUB | Yes | Unzip (`ZipByteSource`) + parse OPF spine + CSS parser + `HtmlBlockParser` to `DocumentChunkBuilder` + Knuth-Plass |
|
||||
| FB2 | Yes | `Fb2ByteSource` (plain XML / ZIP) + `TextEncoding` + direct `DocumentChunkBuilder` streaming + Knuth-Plass |
|
||||
| TXT | Queued | `TextEncoding` + direct streaming into `DocumentChunkBuilder` + Knuth-Plass |
|
||||
| PDF | Planned | `QtPdf` module (`QPdfDocument`, Qt 6.4+) |
|
||||
| DOC | Planned | `libwpd` or antiword subprocess |
|
||||
| RTF | Planned | `QTextDocumentReader` or RTF→HTML |
|
||||
@@ -159,8 +159,14 @@ public:
|
||||
|
||||
### 1. Text Mode (`ScrollPageView.qml`)
|
||||
- `ReadingModel` manages a list of `ContentChunk`s (`QVector<ContentChunk>`).
|
||||
- `EpubReader` cascades CSS onto the spine DOM and delegates directly to `HtmlBlockParser::parseChunks()`. This bypasses raw HTML string serialization and eliminates the double-parsing penalty, producing structured `ContentChunk` entities with pre-parsed `BlockItem`s, `wordCount`, `charCount`, and `unnestedContainers` for open containers spanning chunk boundaries.
|
||||
- `HtmlBlockParser` normalizes paragraph typography across EPUB (`<div class="paragraph">` and `<p>`) and FB2 (`<p>`): unstyled paragraphs default to zero vertical margins (`marginTop = 0`, `marginBottom = 0`) and `2.0em` first-line indent (`textIndent = 2.0 * baseFontSize`), eliminating `ContainerStart`/`ContainerEnd` box allocation overhead and preventing blank vertical gaps between prose/dialogue lines. Explicit CSS margins in publisher stylesheets override this default. Shorthand `margin` and `padding` (1 to 4 token syntax) are fully parsed.
|
||||
- **Format-Agnostic IR Pipeline (`DocumentIr.h`, `DocumentChunkBuilder.h`)**:
|
||||
- Readers build intermediate representation (`ContentChunk`, `BlockItem`, `InlineItem`, `BoxStyle`) directly via `DocumentChunkBuilder` without allocating intermediate HTML DOM trees or serializing HTML strings.
|
||||
- `DocumentChunkBuilder` streams and partitions content chunks (target ~512 chars), normalizes inter-word spacing, trims paragraph whitespace, and handles cross-chunk container splitting and reopening (`unnestedContainers`).
|
||||
- `HtmlBlockParser` serves as the unified XML/HTML-to-IR converter streaming directly into `DocumentChunkBuilder`. It handles both XHTML (EPUB) and FictionBook (FB2) elements with native semantic tag defaults, CSS cascade, container nesting, and inline styling.
|
||||
- `Fb2Reader` streams XML sections directly into `HtmlBlockParser::parseChunks()` without synthetic HTML DOM allocations.
|
||||
- `EpubReader` resolves spine XHTML DOM nodes against in-memory CSS stylesheets (`Css::StyleSheet`) via `HtmlBlockParser::parseChunks()`, streaming directly into `DocumentChunkBuilder` with on-the-fly image URL resolution and zero DOM string mutations.
|
||||
- `TextEncoding` provides unified BOM/XML/HTML/iconv encoding detection across `FB2` and queued formats (`TXT`, `MOBI`, `PDB`).
|
||||
- `HtmlBlockParser` and `Fb2Reader` normalize paragraph typography across EPUB (`<div class="paragraph">` and `<p>`) and FB2 (`<p>`): unstyled paragraphs default to zero vertical margins (`marginTop = 0`, `marginBottom = 0`) and `2.0em` first-line indent (`textIndent = 2.0 * baseFontSize`), eliminating `ContainerStart`/`ContainerEnd` box allocation overhead and preventing blank vertical gaps between prose/dialogue lines. Explicit CSS margins in publisher stylesheets override this default. Shorthand `margin` and `padding` (1 to 4 token syntax) are fully parsed.
|
||||
- Headings (`h1`..`h6`) default to left-aligned (`TextAlign::Left`) without first-line indentation (`textIndent = 0`). In `Fb2Reader`, `<title>` flattens child `<p>` lines separated by `<br/>` with `text-align: left; text-indent: 0;`, preventing nested paragraph indent on titles. Scene transitions via FB2 `<empty-line>` use explicit margins to provide intended section gaps.
|
||||
- When viewport geometry or font preferences change, `ReadingModel::updateLayoutMetrics()` runs `ChunkLayoutEngine` off-thread:
|
||||
- Pre-parsed `BlockItem`s in `ContentChunk` scale dynamically with user font preferences in `ChunkLayoutEngine::prepareBlocks()` with zero HTML/XML re-parsing.
|
||||
@@ -241,6 +247,7 @@ src/
|
||||
ImageExtensions.h
|
||||
ImageScaling.h
|
||||
ImageUrl.h/cpp
|
||||
TextEncoding.h/cpp
|
||||
WebImageProvider.h/cpp
|
||||
comic/
|
||||
ComicReader.h/cpp
|
||||
@@ -256,7 +263,8 @@ src/
|
||||
layout/
|
||||
ChunkLayoutEngine.h/cpp
|
||||
CssParser.h/cpp
|
||||
DomChunkPipeline.h/cpp
|
||||
DocumentChunkBuilder.h/cpp
|
||||
DocumentIr.h
|
||||
HtmlBlockParser.h/cpp
|
||||
KnuthPlass.h/cpp
|
||||
state/
|
||||
@@ -302,6 +310,7 @@ tests/
|
||||
Fb2ReaderTest.cpp
|
||||
FolderReaderTest.cpp
|
||||
ImageUrlTest.cpp
|
||||
TextEncodingTest.cpp
|
||||
WebImageProviderTest.cpp
|
||||
reading/
|
||||
KnuthPlassRenderingSpecTest.cpp
|
||||
|
||||
+12
-3
@@ -83,6 +83,8 @@ set(SOURCES
|
||||
src/backend/formats/FileIconProvider.cpp
|
||||
src/backend/formats/HtmlEntities.h
|
||||
src/backend/formats/HtmlEntities.cpp
|
||||
src/backend/formats/TextEncoding.h
|
||||
src/backend/formats/TextEncoding.cpp
|
||||
src/backend/formats/WebImageProvider.h
|
||||
src/backend/formats/WebImageProvider.cpp
|
||||
src/backend/formats/EpubReader.h
|
||||
@@ -100,10 +102,11 @@ set(SOURCES
|
||||
src/backend/reading/layout/KnuthPlass.cpp
|
||||
src/backend/reading/layout/CssParser.h
|
||||
src/backend/reading/layout/CssParser.cpp
|
||||
src/backend/reading/layout/DocumentIr.h
|
||||
src/backend/reading/layout/DocumentChunkBuilder.h
|
||||
src/backend/reading/layout/DocumentChunkBuilder.cpp
|
||||
src/backend/reading/layout/HtmlBlockParser.h
|
||||
src/backend/reading/layout/HtmlBlockParser.cpp
|
||||
src/backend/reading/layout/DomChunkPipeline.h
|
||||
src/backend/reading/layout/DomChunkPipeline.cpp
|
||||
src/backend/reading/layout/ChunkLayoutEngine.h
|
||||
src/backend/reading/layout/ChunkLayoutEngine.cpp
|
||||
)
|
||||
@@ -248,9 +251,9 @@ set(COMIC_SOURCES
|
||||
set(LAYOUT_SOURCES
|
||||
src/backend/reading/layout/KnuthPlass.cpp
|
||||
src/backend/reading/layout/CssParser.cpp
|
||||
src/backend/reading/layout/DocumentChunkBuilder.cpp
|
||||
src/backend/reading/layout/HtmlBlockParser.cpp
|
||||
src/backend/reading/layout/ChunkLayoutEngine.cpp
|
||||
src/backend/reading/layout/DomChunkPipeline.cpp
|
||||
)
|
||||
|
||||
set(EPUB_READER_SOURCES
|
||||
@@ -262,6 +265,7 @@ set(EPUB_READER_SOURCES
|
||||
)
|
||||
|
||||
set(FB2_READER_SOURCES
|
||||
src/backend/formats/TextEncoding.cpp
|
||||
src/backend/formats/HtmlEntities.cpp
|
||||
src/backend/formats/ImageUrl.cpp
|
||||
src/backend/formats/sources/ZipByteSource.cpp
|
||||
@@ -448,3 +452,8 @@ add_asteria_test(FileIconProviderTest tests/FileIconProviderTest.cpp
|
||||
src/backend/formats/FileIconProvider.cpp)
|
||||
target_link_libraries(FileIconProviderTest PRIVATE Qt6::Quick Qt6::Gui Qt6::Widgets)
|
||||
set_tests_properties(FileIconProviderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||
|
||||
add_asteria_test(TextEncodingTest tests/formats/TextEncodingTest.cpp
|
||||
src/backend/formats/TextEncoding.cpp)
|
||||
target_link_libraries(TextEncodingTest PRIVATE Iconv::Iconv)
|
||||
set_tests_properties(TextEncodingTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||
@@ -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);
|
||||
|
||||
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
|
||||
@@ -322,17 +322,6 @@ QVector<Declaration> cascade(const StyleSheet &sheet, const QDomElement &element
|
||||
return out;
|
||||
}
|
||||
|
||||
QString serialize(const QVector<Declaration> &declarations)
|
||||
{
|
||||
QString out;
|
||||
for (const Declaration &d : declarations) {
|
||||
if (!out.isEmpty())
|
||||
out += QLatin1Char(';');
|
||||
out += d.property + QLatin1Char(':') + d.value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::optional<qreal> parseLength(QStringView valueIn, const LengthContext &ctx)
|
||||
{
|
||||
const QString value = valueIn.trimmed().toString().toLower();
|
||||
|
||||
@@ -61,7 +61,6 @@ bool matches(const Selector &selector, const QDomElement &element);
|
||||
// Cascade result for one element, in application order (later wins):
|
||||
// stylesheet normal, inline normal, stylesheet !important, inline !important.
|
||||
QVector<Declaration> cascade(const StyleSheet &sheet, const QDomElement &element);
|
||||
QString serialize(const QVector<Declaration> &declarations);
|
||||
|
||||
// --- Values -----------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
#include "DocumentChunkBuilder.h"
|
||||
|
||||
#include <QRegularExpression>
|
||||
|
||||
namespace {
|
||||
|
||||
void countInlines(const QVector<InlineItem> &inlines, int &pChars, int &pWords)
|
||||
{
|
||||
pChars = 0;
|
||||
pWords = 0;
|
||||
for (const auto &inl : inlines) {
|
||||
if (inl.kind == InlineItem::Kind::Text) {
|
||||
pChars += inl.text.size();
|
||||
pWords += inl.text.split(QLatin1Char(' '), Qt::SkipEmptyParts).size();
|
||||
} else if (inl.kind == InlineItem::Kind::Image) {
|
||||
pChars += 1;
|
||||
pWords += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
DocumentChunkBuilder::DocumentChunkBuilder(QString sectionHref, int targetChars)
|
||||
: m_sectionHref(std::move(sectionHref))
|
||||
, m_targetChars(targetChars)
|
||||
{
|
||||
m_currentChunk.sectionHref = m_sectionHref;
|
||||
}
|
||||
|
||||
void DocumentChunkBuilder::checkPendingFlush()
|
||||
{
|
||||
if (m_pendingFlush) {
|
||||
m_pendingFlush = false;
|
||||
flushCurrentChunk();
|
||||
}
|
||||
}
|
||||
|
||||
void DocumentChunkBuilder::flushCurrentChunk()
|
||||
{
|
||||
if (m_currentChunk.isEmpty())
|
||||
return;
|
||||
|
||||
// Close outer open containers at chunk boundary
|
||||
for (int j = m_openContainers.size() - 1; j >= 0; --j) {
|
||||
BlockItem endItem;
|
||||
endItem.kind = BlockItem::Kind::ContainerEnd;
|
||||
endItem.box = m_openContainers[j];
|
||||
endItem.box.borderBottom = 0;
|
||||
endItem.box.paddingBottom = 0;
|
||||
endItem.box.marginBottom = 0;
|
||||
m_currentChunk.blocks.append(endItem);
|
||||
}
|
||||
|
||||
m_chunks.append(std::move(m_currentChunk));
|
||||
m_currentChunk = ContentChunk();
|
||||
m_currentChunk.sectionHref = m_sectionHref;
|
||||
m_currentChunk.unnestedContainers = m_openContainers.size();
|
||||
|
||||
// Reopen outer containers at start of next chunk
|
||||
for (int j = 0; j < m_openContainers.size(); ++j) {
|
||||
BlockItem startItem;
|
||||
startItem.kind = BlockItem::Kind::ContainerStart;
|
||||
startItem.box = m_openContainers[j];
|
||||
startItem.box.borderTop = 0;
|
||||
startItem.box.paddingTop = 0;
|
||||
startItem.box.marginTop = 0;
|
||||
m_currentChunk.blocks.append(startItem);
|
||||
}
|
||||
}
|
||||
|
||||
void DocumentChunkBuilder::startContainer(const BoxStyle &box)
|
||||
{
|
||||
finishParagraph();
|
||||
checkPendingFlush();
|
||||
|
||||
m_openContainers.append(box);
|
||||
BlockItem start;
|
||||
start.kind = BlockItem::Kind::ContainerStart;
|
||||
start.box = box;
|
||||
m_currentChunk.blocks.append(start);
|
||||
}
|
||||
|
||||
void DocumentChunkBuilder::endContainer(const BoxStyle &box)
|
||||
{
|
||||
finishParagraph();
|
||||
|
||||
BoxStyle effectiveBox = box;
|
||||
if (!m_openContainers.isEmpty()) {
|
||||
BoxStyle popped = m_openContainers.takeLast();
|
||||
if (effectiveBox.marginTop == 0 && effectiveBox.marginBottom == 0
|
||||
&& effectiveBox.marginLeft == 0 && effectiveBox.marginRight == 0
|
||||
&& effectiveBox.paddingTop == 0 && effectiveBox.paddingBottom == 0
|
||||
&& effectiveBox.borderLeft == 0 && !effectiveBox.background.isValid()) {
|
||||
effectiveBox = popped;
|
||||
}
|
||||
}
|
||||
|
||||
BlockItem end;
|
||||
end.kind = BlockItem::Kind::ContainerEnd;
|
||||
end.box = effectiveBox;
|
||||
m_currentChunk.blocks.append(end);
|
||||
|
||||
checkPendingFlush();
|
||||
}
|
||||
|
||||
void DocumentChunkBuilder::startParagraph(TextAlign align,
|
||||
qreal textIndent,
|
||||
qreal lineHeight,
|
||||
qreal fontSize,
|
||||
bool preformatted,
|
||||
const QString &marker,
|
||||
const TextStyle &markerStyle)
|
||||
{
|
||||
finishParagraph();
|
||||
checkPendingFlush();
|
||||
|
||||
m_hasActiveParagraph = true;
|
||||
m_currentParagraph = BlockItem();
|
||||
m_currentParagraph.kind = BlockItem::Kind::Paragraph;
|
||||
m_currentParagraph.align = align;
|
||||
m_currentParagraph.textIndent = textIndent;
|
||||
m_currentParagraph.lineHeight = lineHeight;
|
||||
m_currentParagraph.fontSize = fontSize;
|
||||
m_currentParagraph.preformatted = preformatted;
|
||||
m_currentParagraph.marker = marker;
|
||||
m_currentParagraph.markerStyle = markerStyle;
|
||||
}
|
||||
|
||||
void DocumentChunkBuilder::appendText(const QString &text, const TextStyle &style, bool preformatted)
|
||||
{
|
||||
if (text.isEmpty())
|
||||
return;
|
||||
|
||||
if (!m_hasActiveParagraph) {
|
||||
startParagraph(TextAlign::Justify, 0, 0, style.fontSize, preformatted);
|
||||
}
|
||||
|
||||
QString processed = text;
|
||||
if (!preformatted && !m_currentParagraph.preformatted) {
|
||||
static const QRegularExpression kSpaces(QStringLiteral("\\s+"));
|
||||
processed.replace(kSpaces, QStringLiteral(" "));
|
||||
if (m_currentParagraph.inlines.isEmpty() && processed == QLatin1String(" "))
|
||||
return;
|
||||
}
|
||||
|
||||
if (processed.isEmpty())
|
||||
return;
|
||||
|
||||
InlineItem item;
|
||||
item.kind = InlineItem::Kind::Text;
|
||||
item.text = processed;
|
||||
item.style = style;
|
||||
m_currentParagraph.inlines.append(item);
|
||||
}
|
||||
|
||||
void DocumentChunkBuilder::appendImage(const QString &imageUrl, qreal cssWidth, qreal cssHeight, qreal cssMaxWidth, const TextStyle &style)
|
||||
{
|
||||
if (imageUrl.isEmpty())
|
||||
return;
|
||||
|
||||
if (!m_hasActiveParagraph) {
|
||||
startParagraph(TextAlign::Justify, 0, 0, style.fontSize > 0 ? style.fontSize : 16);
|
||||
}
|
||||
|
||||
InlineItem item;
|
||||
item.kind = InlineItem::Kind::Image;
|
||||
item.imageUrl = imageUrl;
|
||||
item.cssWidth = cssWidth;
|
||||
item.cssHeight = cssHeight;
|
||||
item.cssMaxWidth = cssMaxWidth;
|
||||
item.style = style;
|
||||
m_currentParagraph.inlines.append(item);
|
||||
}
|
||||
|
||||
void DocumentChunkBuilder::appendLineBreak()
|
||||
{
|
||||
if (!m_hasActiveParagraph) {
|
||||
startParagraph();
|
||||
}
|
||||
|
||||
InlineItem br;
|
||||
br.kind = InlineItem::Kind::LineBreak;
|
||||
m_currentParagraph.inlines.append(br);
|
||||
}
|
||||
|
||||
void DocumentChunkBuilder::finishParagraph()
|
||||
{
|
||||
if (!m_hasActiveParagraph)
|
||||
return;
|
||||
|
||||
auto &inlines = m_currentParagraph.inlines;
|
||||
|
||||
if (!m_currentParagraph.preformatted) {
|
||||
// Drop trailing line breaks and whitespace
|
||||
while (!inlines.isEmpty()) {
|
||||
const auto &last = inlines.last();
|
||||
if (last.kind == InlineItem::Kind::LineBreak) {
|
||||
inlines.removeLast();
|
||||
} else if (last.kind == InlineItem::Kind::Text && last.text.trimmed().isEmpty()) {
|
||||
inlines.removeLast();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!inlines.isEmpty() && inlines.last().kind == InlineItem::Kind::Text) {
|
||||
while (inlines.last().text.endsWith(QLatin1Char(' '))) {
|
||||
inlines.last().text.chop(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Drop leading whitespace
|
||||
while (!inlines.isEmpty()) {
|
||||
const auto &first = inlines.first();
|
||||
if (first.kind == InlineItem::Kind::Text && first.text.trimmed().isEmpty()) {
|
||||
inlines.removeFirst();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!inlines.isEmpty() && inlines.first().kind == InlineItem::Kind::Text) {
|
||||
while (inlines.first().text.startsWith(QLatin1Char(' '))) {
|
||||
inlines.first().text.remove(0, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (inlines.isEmpty()) {
|
||||
m_hasActiveParagraph = false;
|
||||
m_currentParagraph = BlockItem();
|
||||
return;
|
||||
}
|
||||
|
||||
int pChars = 0;
|
||||
int pWords = 0;
|
||||
countInlines(inlines, pChars, pWords);
|
||||
|
||||
m_currentChunk.blocks.append(m_currentParagraph);
|
||||
m_currentChunk.charCount += pChars;
|
||||
m_currentChunk.wordCount += pWords;
|
||||
|
||||
m_hasActiveParagraph = false;
|
||||
m_currentParagraph = BlockItem();
|
||||
|
||||
if (m_currentChunk.charCount >= m_targetChars) {
|
||||
m_pendingFlush = true;
|
||||
}
|
||||
}
|
||||
|
||||
void DocumentChunkBuilder::appendRule(const QColor &ruleColor)
|
||||
{
|
||||
finishParagraph();
|
||||
checkPendingFlush();
|
||||
|
||||
BlockItem r;
|
||||
r.kind = BlockItem::Kind::Rule;
|
||||
r.ruleColor = ruleColor;
|
||||
m_currentChunk.blocks.append(r);
|
||||
m_currentChunk.charCount += 1;
|
||||
|
||||
if (m_currentChunk.charCount >= m_targetChars) {
|
||||
m_pendingFlush = true;
|
||||
}
|
||||
}
|
||||
|
||||
void DocumentChunkBuilder::appendBlock(const BlockItem &block)
|
||||
{
|
||||
finishParagraph();
|
||||
checkPendingFlush();
|
||||
|
||||
if (block.kind == BlockItem::Kind::ContainerStart) {
|
||||
startContainer(block.box);
|
||||
} else if (block.kind == BlockItem::Kind::ContainerEnd) {
|
||||
endContainer(block.box);
|
||||
} else if (block.kind == BlockItem::Kind::Rule) {
|
||||
appendRule(block.ruleColor);
|
||||
} else if (block.kind == BlockItem::Kind::Paragraph) {
|
||||
int pChars = 0;
|
||||
int pWords = 0;
|
||||
countInlines(block.inlines, pChars, pWords);
|
||||
m_currentChunk.blocks.append(block);
|
||||
m_currentChunk.charCount += pChars;
|
||||
m_currentChunk.wordCount += pWords;
|
||||
|
||||
if (m_currentChunk.charCount >= m_targetChars) {
|
||||
m_pendingFlush = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
QVector<ContentChunk> DocumentChunkBuilder::build()
|
||||
{
|
||||
finishParagraph();
|
||||
m_pendingFlush = false;
|
||||
|
||||
if (!m_currentChunk.isEmpty()) {
|
||||
m_chunks.append(std::move(m_currentChunk));
|
||||
m_currentChunk = ContentChunk();
|
||||
m_currentChunk.sectionHref = m_sectionHref;
|
||||
}
|
||||
|
||||
return std::move(m_chunks);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
|
||||
#include "DocumentIr.h"
|
||||
#include <QString>
|
||||
#include <QVector>
|
||||
|
||||
class DocumentChunkBuilder {
|
||||
public:
|
||||
explicit DocumentChunkBuilder(QString sectionHref = {}, int targetChars = 512);
|
||||
|
||||
void startContainer(const BoxStyle &box);
|
||||
void endContainer(const BoxStyle &box = {});
|
||||
|
||||
void startParagraph(TextAlign align = TextAlign::Justify,
|
||||
qreal textIndent = 0,
|
||||
qreal lineHeight = 0,
|
||||
qreal fontSize = 16,
|
||||
bool preformatted = false,
|
||||
const QString &marker = {},
|
||||
const TextStyle &markerStyle = {});
|
||||
|
||||
void appendText(const QString &text, const TextStyle &style, bool preformatted = false);
|
||||
void appendImage(const QString &imageUrl, qreal cssWidth = -1, qreal cssHeight = -1, qreal cssMaxWidth = -1, const TextStyle &style = {});
|
||||
void appendLineBreak();
|
||||
void finishParagraph();
|
||||
|
||||
void appendRule(const QColor &ruleColor = {});
|
||||
void appendBlock(const BlockItem &block);
|
||||
|
||||
QVector<ContentChunk> build();
|
||||
|
||||
private:
|
||||
void checkPendingFlush();
|
||||
void flushCurrentChunk();
|
||||
|
||||
QString m_sectionHref;
|
||||
int m_targetChars = 512;
|
||||
|
||||
QVector<ContentChunk> m_chunks;
|
||||
ContentChunk m_currentChunk;
|
||||
QVector<BoxStyle> m_openContainers;
|
||||
|
||||
bool m_hasActiveParagraph = false;
|
||||
BlockItem m_currentParagraph;
|
||||
bool m_pendingFlush = false;
|
||||
};
|
||||
@@ -0,0 +1,161 @@
|
||||
#pragma once
|
||||
|
||||
#include <QColor>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QVector>
|
||||
|
||||
// Core format-neutral Document Intermediate Representation (IR).
|
||||
// Produced by format readers (EPUB, FB2, TXT, MOBI, PDB) and consumed by ChunkLayoutEngine.
|
||||
|
||||
enum class TextAlign { Justify, Left, Center, Right };
|
||||
enum class TextTransform { None, Uppercase, Lowercase, Capitalize };
|
||||
|
||||
struct TextStyle {
|
||||
QStringList fontFamilies; // preferred families in order (may contain generic names); empty = default
|
||||
qreal fontSize = 16; // px
|
||||
int weight = 400; // CSS weight 100..900
|
||||
bool italic = false;
|
||||
bool smallCaps = false;
|
||||
TextTransform transform = TextTransform::None;
|
||||
qreal letterSpacing = 0; // px
|
||||
bool underline = false;
|
||||
bool strikeOut = false;
|
||||
bool overline = false;
|
||||
bool link = false;
|
||||
QColor color; // invalid = theme default
|
||||
QColor background; // invalid = none
|
||||
qreal baselineShift = 0; // px, positive = raised (superscript)
|
||||
|
||||
bool operator==(const TextStyle &o) const {
|
||||
return fontFamilies == o.fontFamilies
|
||||
&& qFuzzyCompare(fontSize, o.fontSize)
|
||||
&& weight == o.weight
|
||||
&& italic == o.italic
|
||||
&& smallCaps == o.smallCaps
|
||||
&& transform == o.transform
|
||||
&& qFuzzyCompare(letterSpacing, o.letterSpacing)
|
||||
&& underline == o.underline
|
||||
&& strikeOut == o.strikeOut
|
||||
&& overline == o.overline
|
||||
&& link == o.link
|
||||
&& color == o.color
|
||||
&& background == o.background
|
||||
&& qFuzzyCompare(baselineShift, o.baselineShift);
|
||||
}
|
||||
};
|
||||
|
||||
struct InlineItem {
|
||||
enum class Kind { Text, Image, LineBreak };
|
||||
Kind kind = Kind::Text;
|
||||
QString text; // whitespace already collapsed unless preformatted
|
||||
TextStyle style;
|
||||
QString imageUrl;
|
||||
qreal cssWidth = -1; // px, -1 = auto
|
||||
qreal cssHeight = -1;
|
||||
qreal cssMaxWidth = -1;
|
||||
|
||||
bool operator==(const InlineItem &o) const
|
||||
{
|
||||
return kind == o.kind
|
||||
&& text == o.text
|
||||
&& style == o.style
|
||||
&& imageUrl == o.imageUrl
|
||||
&& qFuzzyCompare(cssWidth, o.cssWidth)
|
||||
&& qFuzzyCompare(cssHeight, o.cssHeight)
|
||||
&& qFuzzyCompare(cssMaxWidth, o.cssMaxWidth);
|
||||
}
|
||||
};
|
||||
|
||||
struct BoxStyle {
|
||||
qreal marginTop = 0, marginBottom = 0, marginLeft = 0, marginRight = 0;
|
||||
qreal paddingTop = 0, paddingBottom = 0, paddingLeft = 0, paddingRight = 0;
|
||||
qreal borderTop = 0, borderBottom = 0, borderLeft = 0, borderRight = 0;
|
||||
QColor borderColor; // invalid = theme dim colour
|
||||
QColor background; // invalid = none
|
||||
|
||||
// Boxes with a visible top edge stop margins collapsing through them.
|
||||
bool blocksTopCollapse() const
|
||||
{
|
||||
return paddingTop > 0 || borderTop > 0 || borderLeft > 0 || borderRight > 0 || background.isValid();
|
||||
}
|
||||
bool blocksBottomCollapse() const
|
||||
{
|
||||
return paddingBottom > 0 || borderBottom > 0 || borderLeft > 0 || borderRight > 0 || background.isValid();
|
||||
}
|
||||
|
||||
bool operator==(const BoxStyle &o) const
|
||||
{
|
||||
return qFuzzyCompare(marginTop, o.marginTop)
|
||||
&& qFuzzyCompare(marginBottom, o.marginBottom)
|
||||
&& qFuzzyCompare(marginLeft, o.marginLeft)
|
||||
&& qFuzzyCompare(marginRight, o.marginRight)
|
||||
&& qFuzzyCompare(paddingTop, o.paddingTop)
|
||||
&& qFuzzyCompare(paddingBottom, o.paddingBottom)
|
||||
&& qFuzzyCompare(paddingLeft, o.paddingLeft)
|
||||
&& qFuzzyCompare(paddingRight, o.paddingRight)
|
||||
&& qFuzzyCompare(borderTop, o.borderTop)
|
||||
&& qFuzzyCompare(borderBottom, o.borderBottom)
|
||||
&& qFuzzyCompare(borderLeft, o.borderLeft)
|
||||
&& qFuzzyCompare(borderRight, o.borderRight)
|
||||
&& borderColor == o.borderColor
|
||||
&& background == o.background;
|
||||
}
|
||||
};
|
||||
|
||||
struct BlockItem {
|
||||
enum class Kind { ContainerStart, ContainerEnd, Paragraph, Rule };
|
||||
Kind kind = Kind::Paragraph;
|
||||
BoxStyle box; // ContainerStart / ContainerEnd (same values on both)
|
||||
|
||||
// Paragraph properties
|
||||
TextAlign align = TextAlign::Justify;
|
||||
qreal textIndent = 0; // px, first line only
|
||||
qreal lineHeight = 0; // multiplier of fontSize; 0 = LayoutParams default
|
||||
qreal fontSize = 16; // block font size (minimum line height basis)
|
||||
bool preformatted = false;
|
||||
QString marker; // list marker drawn left of the first line
|
||||
TextStyle markerStyle;
|
||||
QVector<InlineItem> inlines;
|
||||
|
||||
QColor ruleColor; // Rule only; invalid = theme dim colour
|
||||
|
||||
bool operator==(const BlockItem &o) const
|
||||
{
|
||||
return kind == o.kind
|
||||
&& box == o.box
|
||||
&& align == o.align
|
||||
&& qFuzzyCompare(textIndent, o.textIndent)
|
||||
&& qFuzzyCompare(lineHeight, o.lineHeight)
|
||||
&& qFuzzyCompare(fontSize, o.fontSize)
|
||||
&& preformatted == o.preformatted
|
||||
&& marker == o.marker
|
||||
&& markerStyle == o.markerStyle
|
||||
&& inlines == o.inlines
|
||||
&& ruleColor == o.ruleColor;
|
||||
}
|
||||
};
|
||||
|
||||
struct ParseParams {
|
||||
qreal baseFontSize = 16; // user preference, px
|
||||
qreal contentWidth = 600; // px, resolves percentage lengths
|
||||
};
|
||||
|
||||
struct ContentChunk {
|
||||
QString sectionHref;
|
||||
QVector<BlockItem> blocks;
|
||||
int wordCount = 0;
|
||||
int charCount = 0;
|
||||
int unnestedContainers = 0;
|
||||
|
||||
bool isEmpty() const { return blocks.isEmpty(); }
|
||||
|
||||
bool operator==(const ContentChunk &o) const
|
||||
{
|
||||
return sectionHref == o.sectionHref
|
||||
&& blocks == o.blocks
|
||||
&& wordCount == o.wordCount
|
||||
&& charCount == o.charCount
|
||||
&& unnestedContainers == o.unnestedContainers;
|
||||
}
|
||||
};
|
||||
@@ -1,68 +0,0 @@
|
||||
#include "DomChunkPipeline.h"
|
||||
|
||||
#include <functional>
|
||||
#include "backend/formats/ImageUrl.h"
|
||||
|
||||
namespace DomChunkPipeline {
|
||||
|
||||
QVector<ContentChunk> cascadeAndChunk(QDomElement &root,
|
||||
const Css::StyleSheet &sheet,
|
||||
const QString &scheme,
|
||||
const QString &sourcePath,
|
||||
const QString §ionHref,
|
||||
const QString &baseDir,
|
||||
int targetChars)
|
||||
{
|
||||
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;
|
||||
if (el.hasAttribute(QStringLiteral("src"))) {
|
||||
srcAttr = QStringLiteral("src");
|
||||
} else if (el.hasAttribute(QStringLiteral("xlink:href"))) {
|
||||
srcAttr = QStringLiteral("xlink:href");
|
||||
} else if (el.hasAttribute(QStringLiteral("l:href"))) {
|
||||
srcAttr = QStringLiteral("l:href");
|
||||
} else if (el.hasAttribute(QStringLiteral("href"))) {
|
||||
srcAttr = QStringLiteral("href");
|
||||
}
|
||||
if (!srcAttr.isEmpty()) {
|
||||
const QString src = el.attribute(srcAttr);
|
||||
const QString resolved = ImageUrl::resolve(scheme, src, sourcePath, baseDir);
|
||||
el.setAttribute(srcAttr, resolved);
|
||||
}
|
||||
}
|
||||
|
||||
for (QDomNode child = el.firstChild(); !child.isNull(); child = child.nextSibling()) {
|
||||
if (child.isElement()) {
|
||||
QDomElement childEl = child.toElement();
|
||||
processElement(childEl);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
processElement(root);
|
||||
return HtmlBlockParser::parseChunks(root, sectionHref, targetChars);
|
||||
}
|
||||
|
||||
QVector<ContentChunk> cascadeAndChunk(QDomElement &root,
|
||||
const QStringList &stylesheetTexts,
|
||||
const QString &scheme,
|
||||
const QString &sourcePath,
|
||||
const QString §ionHref,
|
||||
const QString &baseDir,
|
||||
int targetChars)
|
||||
{
|
||||
Css::StyleSheet combinedSheet;
|
||||
for (const QString &text : stylesheetTexts) {
|
||||
combinedSheet.append(Css::StyleSheet::parse(text));
|
||||
}
|
||||
return cascadeAndChunk(root, combinedSheet, scheme, sourcePath, sectionHref, baseDir, targetChars);
|
||||
}
|
||||
|
||||
} // namespace DomChunkPipeline
|
||||
@@ -1,29 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <QDomElement>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QVector>
|
||||
|
||||
#include "backend/reading/layout/HtmlBlockParser.h"
|
||||
#include "backend/reading/layout/CssParser.h"
|
||||
|
||||
namespace DomChunkPipeline {
|
||||
|
||||
QVector<ContentChunk> cascadeAndChunk(QDomElement &root,
|
||||
const QStringList &stylesheetTexts,
|
||||
const QString &scheme,
|
||||
const QString &sourcePath,
|
||||
const QString §ionHref,
|
||||
const QString &baseDir = {},
|
||||
int targetChars = 512);
|
||||
|
||||
QVector<ContentChunk> cascadeAndChunk(QDomElement &root,
|
||||
const Css::StyleSheet &sheet,
|
||||
const QString &scheme,
|
||||
const QString &sourcePath,
|
||||
const QString §ionHref,
|
||||
const QString &baseDir = {},
|
||||
int targetChars = 512);
|
||||
|
||||
} // namespace DomChunkPipeline
|
||||
@@ -1,11 +1,12 @@
|
||||
#include "HtmlBlockParser.h"
|
||||
|
||||
#include <QDomDocument>
|
||||
#include <QRegularExpression>
|
||||
#include <QSet>
|
||||
#include <algorithm>
|
||||
|
||||
#include "CssParser.h"
|
||||
#include "DocumentChunkBuilder.h"
|
||||
#include "backend/formats/HtmlEntities.h"
|
||||
#include "backend/formats/ImageUrl.h"
|
||||
|
||||
namespace HtmlBlockParser {
|
||||
|
||||
@@ -31,7 +32,7 @@ QString localName(const QDomElement &e)
|
||||
|
||||
bool isBlockTag(const QString &tag)
|
||||
{
|
||||
static const QStringList kBlocks = {
|
||||
static const QSet<QString> kBlocks = {
|
||||
QStringLiteral("p"), QStringLiteral("div"),
|
||||
QStringLiteral("h1"), QStringLiteral("h2"),
|
||||
QStringLiteral("h3"), QStringLiteral("h4"),
|
||||
@@ -44,12 +45,71 @@ bool isBlockTag(const QString &tag)
|
||||
QStringLiteral("svg"), QStringLiteral("figcaption"),
|
||||
QStringLiteral("section"), QStringLiteral("article"),
|
||||
QStringLiteral("header"), QStringLiteral("footer"), QStringLiteral("aside"),
|
||||
QStringLiteral("body")
|
||||
QStringLiteral("body"),
|
||||
// FB2 semantic block tags
|
||||
QStringLiteral("title"), QStringLiteral("subtitle"),
|
||||
QStringLiteral("epigraph"), QStringLiteral("poem"),
|
||||
QStringLiteral("stanza"), QStringLiteral("v"),
|
||||
QStringLiteral("text-author"),QStringLiteral("date"),
|
||||
QStringLiteral("empty-line")
|
||||
};
|
||||
return kBlocks.contains(tag);
|
||||
}
|
||||
|
||||
void applyCssDeclarations(const QVector<Css::Declaration> &decls,
|
||||
void applyFourSides(qreal &top, qreal &right, qreal &bottom, qreal &left,
|
||||
const QString &val, const Css::LengthContext &lenCtx)
|
||||
{
|
||||
const QStringList tokens = Css::splitValue(val);
|
||||
QVector<qreal> v;
|
||||
v.reserve(tokens.size());
|
||||
for (const QString &tok : tokens) {
|
||||
if (auto len = Css::parseLength(tok, lenCtx))
|
||||
v.append(*len);
|
||||
}
|
||||
if (v.size() == 1) {
|
||||
top = right = bottom = left = v[0];
|
||||
} else if (v.size() == 2) {
|
||||
top = bottom = v[0];
|
||||
right = left = v[1];
|
||||
} else if (v.size() == 3) {
|
||||
top = v[0];
|
||||
right = left = v[1];
|
||||
bottom = v[2];
|
||||
} else if (v.size() >= 4) {
|
||||
top = v[0];
|
||||
right = v[1];
|
||||
bottom = v[2];
|
||||
left = v[3];
|
||||
}
|
||||
}
|
||||
|
||||
void applyBorderWidths(BoxStyle &box, const QString &val, const Css::LengthContext &lenCtx)
|
||||
{
|
||||
const QStringList tokens = Css::splitValue(val);
|
||||
QVector<qreal> widths;
|
||||
widths.reserve(tokens.size());
|
||||
for (const QString &tok : tokens) {
|
||||
if (auto w = Css::parseBorderSide(tok, lenCtx).width)
|
||||
widths.append(*w);
|
||||
}
|
||||
if (widths.size() == 1) {
|
||||
box.borderTop = box.borderRight = box.borderBottom = box.borderLeft = widths[0];
|
||||
} else if (widths.size() == 2) {
|
||||
box.borderTop = box.borderBottom = widths[0];
|
||||
box.borderRight = box.borderLeft = widths[1];
|
||||
} else if (widths.size() == 3) {
|
||||
box.borderTop = widths[0];
|
||||
box.borderRight = box.borderLeft = widths[1];
|
||||
box.borderBottom = widths[2];
|
||||
} else if (widths.size() >= 4) {
|
||||
box.borderTop = widths[0];
|
||||
box.borderRight = widths[1];
|
||||
box.borderBottom = widths[2];
|
||||
box.borderLeft = widths[3];
|
||||
}
|
||||
}
|
||||
|
||||
void applyDeclarations(const QVector<Css::Declaration> &decls,
|
||||
StyleContext &ctx,
|
||||
BoxStyle &box,
|
||||
const ParseParams ¶ms,
|
||||
@@ -61,6 +121,12 @@ void applyCssDeclarations(const QVector<Css::Declaration> &decls,
|
||||
lenCtx.percentBase = params.contentWidth;
|
||||
lenCtx.absoluteScale = params.baseFontSize / 16.0;
|
||||
|
||||
auto applySide = [&](qreal &w, const QString &v) {
|
||||
auto b = Css::parseBorderSide(v, lenCtx);
|
||||
if (b.width) w = *b.width;
|
||||
if (b.color.isValid()) box.borderColor = b.color;
|
||||
};
|
||||
|
||||
for (const auto &d : decls) {
|
||||
const QString &prop = d.property;
|
||||
const QString &val = d.value;
|
||||
@@ -154,27 +220,7 @@ void applyCssDeclarations(const QVector<Css::Declaration> &decls,
|
||||
} else if (prop == QLatin1String("margin-right")) {
|
||||
auto m = Css::parseLength(val, lenCtx); if (m) box.marginRight = *m;
|
||||
} else if (prop == QLatin1String("margin")) {
|
||||
const QStringList tokens = Css::splitValue(val);
|
||||
QVector<qreal> vals;
|
||||
for (const QString &tok : tokens) {
|
||||
auto m = Css::parseLength(tok, lenCtx);
|
||||
if (m) vals.append(*m);
|
||||
}
|
||||
if (vals.size() == 1) {
|
||||
box.marginTop = box.marginRight = box.marginBottom = box.marginLeft = vals[0];
|
||||
} else if (vals.size() == 2) {
|
||||
box.marginTop = box.marginBottom = vals[0];
|
||||
box.marginRight = box.marginLeft = vals[1];
|
||||
} else if (vals.size() == 3) {
|
||||
box.marginTop = vals[0];
|
||||
box.marginRight = box.marginLeft = vals[1];
|
||||
box.marginBottom = vals[2];
|
||||
} else if (vals.size() >= 4) {
|
||||
box.marginTop = vals[0];
|
||||
box.marginRight = vals[1];
|
||||
box.marginBottom = vals[2];
|
||||
box.marginLeft = vals[3];
|
||||
}
|
||||
applyFourSides(box.marginTop, box.marginRight, box.marginBottom, box.marginLeft, val, lenCtx);
|
||||
} else if (prop == QLatin1String("padding-top")) {
|
||||
auto p = Css::parseLength(val, lenCtx); if (p) box.paddingTop = *p;
|
||||
} else if (prop == QLatin1String("padding-bottom")) {
|
||||
@@ -184,52 +230,19 @@ void applyCssDeclarations(const QVector<Css::Declaration> &decls,
|
||||
} else if (prop == QLatin1String("padding-right")) {
|
||||
auto p = Css::parseLength(val, lenCtx); if (p) box.paddingRight = *p;
|
||||
} else if (prop == QLatin1String("padding")) {
|
||||
const QStringList tokens = Css::splitValue(val);
|
||||
QVector<qreal> vals;
|
||||
for (const QString &tok : tokens) {
|
||||
auto p = Css::parseLength(tok, lenCtx);
|
||||
if (p) vals.append(*p);
|
||||
}
|
||||
if (vals.size() == 1) {
|
||||
box.paddingTop = box.paddingRight = box.paddingBottom = box.paddingLeft = vals[0];
|
||||
} else if (vals.size() == 2) {
|
||||
box.paddingTop = box.paddingBottom = vals[0];
|
||||
box.paddingRight = box.paddingLeft = vals[1];
|
||||
} else if (vals.size() == 3) {
|
||||
box.paddingTop = vals[0];
|
||||
box.paddingRight = box.paddingLeft = vals[1];
|
||||
box.paddingBottom = vals[2];
|
||||
} else if (vals.size() >= 4) {
|
||||
box.paddingTop = vals[0];
|
||||
box.paddingRight = vals[1];
|
||||
box.paddingBottom = vals[2];
|
||||
box.paddingLeft = vals[3];
|
||||
}
|
||||
applyFourSides(box.paddingTop, box.paddingRight, box.paddingBottom, box.paddingLeft, val, lenCtx);
|
||||
} else if (prop == QLatin1String("border")) {
|
||||
auto b = Css::parseBorderSide(val, lenCtx);
|
||||
if (b.width) {
|
||||
box.borderTop = *b.width;
|
||||
box.borderRight = *b.width;
|
||||
box.borderBottom = *b.width;
|
||||
box.borderLeft = *b.width;
|
||||
}
|
||||
if (b.width) box.borderTop = box.borderRight = box.borderBottom = box.borderLeft = *b.width;
|
||||
if (b.color.isValid()) box.borderColor = b.color;
|
||||
} else if (prop == QLatin1String("border-top")) {
|
||||
auto b = Css::parseBorderSide(val, lenCtx);
|
||||
if (b.width) box.borderTop = *b.width;
|
||||
if (b.color.isValid()) box.borderColor = b.color;
|
||||
applySide(box.borderTop, val);
|
||||
} else if (prop == QLatin1String("border-right")) {
|
||||
auto b = Css::parseBorderSide(val, lenCtx);
|
||||
if (b.width) box.borderRight = *b.width;
|
||||
if (b.color.isValid()) box.borderColor = b.color;
|
||||
applySide(box.borderRight, val);
|
||||
} else if (prop == QLatin1String("border-bottom")) {
|
||||
auto b = Css::parseBorderSide(val, lenCtx);
|
||||
if (b.width) box.borderBottom = *b.width;
|
||||
if (b.color.isValid()) box.borderColor = b.color;
|
||||
applySide(box.borderBottom, val);
|
||||
} else if (prop == QLatin1String("border-left")) {
|
||||
auto b = Css::parseBorderSide(val, lenCtx);
|
||||
if (b.width) box.borderLeft = *b.width;
|
||||
if (b.color.isValid()) box.borderColor = b.color;
|
||||
applySide(box.borderLeft, val);
|
||||
} else if (prop == QLatin1String("border-top-width")) {
|
||||
auto w = Css::parseBorderSide(val, lenCtx).width; if (w) box.borderTop = *w;
|
||||
} else if (prop == QLatin1String("border-right-width")) {
|
||||
@@ -239,27 +252,7 @@ void applyCssDeclarations(const QVector<Css::Declaration> &decls,
|
||||
} else if (prop == QLatin1String("border-left-width")) {
|
||||
auto w = Css::parseBorderSide(val, lenCtx).width; if (w) box.borderLeft = *w;
|
||||
} else if (prop == QLatin1String("border-width")) {
|
||||
const QStringList tokens = Css::splitValue(val);
|
||||
QVector<qreal> widths;
|
||||
for (const QString &tok : tokens) {
|
||||
auto w = Css::parseBorderSide(tok, lenCtx).width;
|
||||
if (w) widths.append(*w);
|
||||
}
|
||||
if (widths.size() == 1) {
|
||||
box.borderTop = box.borderRight = box.borderBottom = box.borderLeft = widths[0];
|
||||
} else if (widths.size() == 2) {
|
||||
box.borderTop = box.borderBottom = widths[0];
|
||||
box.borderRight = box.borderLeft = widths[1];
|
||||
} else if (widths.size() == 3) {
|
||||
box.borderTop = widths[0];
|
||||
box.borderRight = box.borderLeft = widths[1];
|
||||
box.borderBottom = widths[2];
|
||||
} else if (widths.size() >= 4) {
|
||||
box.borderTop = widths[0];
|
||||
box.borderRight = widths[1];
|
||||
box.borderBottom = widths[2];
|
||||
box.borderLeft = widths[3];
|
||||
}
|
||||
applyBorderWidths(box, val, lenCtx);
|
||||
} else if (prop == QLatin1String("border-color") || prop.endsWith(QLatin1String("-color"))) {
|
||||
QColor c = Css::parseColor(val);
|
||||
if (c.isValid()) box.borderColor = c;
|
||||
@@ -269,7 +262,7 @@ void applyCssDeclarations(const QVector<Css::Declaration> &decls,
|
||||
else if (prop == QLatin1String("border-right-style")) box.borderRight = 0;
|
||||
else if (prop == QLatin1String("border-bottom-style")) box.borderBottom = 0;
|
||||
else if (prop == QLatin1String("border-left-style")) box.borderLeft = 0;
|
||||
else { box.borderTop = box.borderRight = box.borderBottom = box.borderLeft = 0; }
|
||||
else box.borderTop = box.borderRight = box.borderBottom = box.borderLeft = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -277,128 +270,40 @@ void applyCssDeclarations(const QVector<Css::Declaration> &decls,
|
||||
|
||||
class Builder {
|
||||
public:
|
||||
Builder(const ParseParams ¶ms) : m_params(params)
|
||||
Builder(DocumentChunkBuilder &chunkBuilder,
|
||||
const ParseParams ¶ms,
|
||||
const Css::StyleSheet *sheet = nullptr,
|
||||
const QString &scheme = {},
|
||||
const QString &sourcePath = {},
|
||||
const QString &baseDir = {},
|
||||
int headingDepth = 1,
|
||||
const QDomNode &root = QDomNode())
|
||||
: m_chunkBuilder(chunkBuilder)
|
||||
, m_params(params)
|
||||
, m_sheet(sheet)
|
||||
, m_scheme(scheme)
|
||||
, m_sourcePath(sourcePath)
|
||||
, m_baseDir(baseDir)
|
||||
, m_headingDepth(headingDepth)
|
||||
, m_root(root)
|
||||
{
|
||||
StyleContext root;
|
||||
root.text.fontSize = params.baseFontSize;
|
||||
m_stack.append(root);
|
||||
StyleContext rootCtx;
|
||||
rootCtx.text.fontSize = params.baseFontSize;
|
||||
m_stack.append(rootCtx);
|
||||
}
|
||||
|
||||
QVector<BlockItem> build(const QDomElement &root)
|
||||
void build(const QDomElement &root)
|
||||
{
|
||||
walk(root);
|
||||
finishCurrentParagraph();
|
||||
return m_blocks;
|
||||
m_chunkBuilder.finishParagraph();
|
||||
}
|
||||
|
||||
private:
|
||||
void finishCurrentParagraph()
|
||||
{
|
||||
if (m_currentInlines.isEmpty())
|
||||
return;
|
||||
|
||||
if (!m_currentPreformatted) {
|
||||
// Drop trailing line breaks and whitespace
|
||||
while (!m_currentInlines.isEmpty()) {
|
||||
const auto &last = m_currentInlines.last();
|
||||
if (last.kind == InlineItem::Kind::LineBreak) {
|
||||
m_currentInlines.removeLast();
|
||||
} else if (last.kind == InlineItem::Kind::Text && last.text.trimmed().isEmpty()) {
|
||||
m_currentInlines.removeLast();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!m_currentInlines.isEmpty() && m_currentInlines.last().kind == InlineItem::Kind::Text) {
|
||||
while (m_currentInlines.last().text.endsWith(QLatin1Char(' '))) {
|
||||
m_currentInlines.last().text.chop(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Drop leading whitespace
|
||||
while (!m_currentInlines.isEmpty()) {
|
||||
const auto &first = m_currentInlines.first();
|
||||
if (first.kind == InlineItem::Kind::Text && first.text.trimmed().isEmpty()) {
|
||||
m_currentInlines.removeFirst();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!m_currentInlines.isEmpty() && m_currentInlines.first().kind == InlineItem::Kind::Text) {
|
||||
while (m_currentInlines.first().text.startsWith(QLatin1Char(' '))) {
|
||||
m_currentInlines.first().text.remove(0, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (m_currentInlines.isEmpty())
|
||||
return;
|
||||
|
||||
BlockItem p;
|
||||
p.kind = BlockItem::Kind::Paragraph;
|
||||
p.align = m_currentAlign;
|
||||
p.textIndent = m_currentIndent;
|
||||
p.lineHeight = m_currentLineHeight;
|
||||
p.fontSize = m_currentBlockFontSize;
|
||||
p.preformatted = m_currentPreformatted;
|
||||
p.marker = m_currentMarker;
|
||||
p.markerStyle = m_currentMarkerStyle;
|
||||
p.inlines = std::move(m_currentInlines);
|
||||
|
||||
m_blocks.append(p);
|
||||
|
||||
m_currentInlines.clear();
|
||||
m_currentMarker.clear();
|
||||
m_currentIndent = 0;
|
||||
}
|
||||
|
||||
void startParagraph(const StyleContext &ctx, const QString &marker = {}, const TextStyle &markerStyle = {})
|
||||
{
|
||||
finishCurrentParagraph();
|
||||
m_currentAlign = ctx.align;
|
||||
m_currentIndent = ctx.textIndent;
|
||||
m_currentLineHeight = ctx.lineHeight;
|
||||
m_currentBlockFontSize = ctx.text.fontSize;
|
||||
m_currentPreformatted = ctx.preformatted;
|
||||
m_currentMarker = marker;
|
||||
m_currentMarkerStyle = markerStyle;
|
||||
}
|
||||
|
||||
void appendText(const QString &text, const TextStyle &style, bool pre)
|
||||
{
|
||||
if (text.isEmpty())
|
||||
return;
|
||||
|
||||
if (m_currentInlines.isEmpty()) {
|
||||
startParagraph(m_stack.last());
|
||||
}
|
||||
|
||||
QString processed = text;
|
||||
if (!pre) {
|
||||
// Collapse whitespaces
|
||||
static const QRegularExpression kSpaces(QStringLiteral("\\s+"));
|
||||
processed.replace(kSpaces, QStringLiteral(" "));
|
||||
if (m_currentInlines.isEmpty() && processed == QLatin1String(" "))
|
||||
return;
|
||||
}
|
||||
|
||||
if (processed.isEmpty())
|
||||
return;
|
||||
|
||||
InlineItem item;
|
||||
item.kind = InlineItem::Kind::Text;
|
||||
item.text = processed;
|
||||
item.style = style;
|
||||
m_currentInlines.append(item);
|
||||
}
|
||||
|
||||
void walk(const QDomNode &node)
|
||||
{
|
||||
if (node.isText()) {
|
||||
const StyleContext &ctx = m_stack.last();
|
||||
appendText(node.nodeValue(), ctx.text, ctx.preformatted);
|
||||
m_chunkBuilder.appendText(node.nodeValue(), ctx.text, ctx.preformatted);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -411,10 +316,28 @@ private:
|
||||
if (tag == QLatin1String("head") || tag == QLatin1String("style") || tag == QLatin1String("script"))
|
||||
return;
|
||||
|
||||
// Skip nested sections in FB2 so they can be processed independently
|
||||
if (node != m_root && tag == QLatin1String("section") && m_scheme == QLatin1String("fb2"))
|
||||
return;
|
||||
|
||||
// Child handling within heading/title
|
||||
if (m_stack.last().isHeading) {
|
||||
if (tag == QLatin1String("p") || tag == QLatin1String("empty-line")) {
|
||||
if (!m_firstTitleLine) {
|
||||
m_chunkBuilder.appendLineBreak();
|
||||
}
|
||||
m_firstTitleLine = false;
|
||||
for (QDomNode child = el.firstChild(); !child.isNull(); child = child.nextSibling()) {
|
||||
walk(child);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
StyleContext ctx = m_stack.last();
|
||||
BoxStyle box;
|
||||
|
||||
// Default HTML semantics
|
||||
// Default HTML & FB2 semantics
|
||||
if (tag == QLatin1String("h1")) {
|
||||
ctx.text.fontSize = m_params.baseFontSize * 1.8;
|
||||
ctx.text.weight = 700;
|
||||
@@ -447,15 +370,30 @@ private:
|
||||
ctx.isHeading = true;
|
||||
box.marginTop = m_params.baseFontSize * 0.5;
|
||||
box.marginBottom = m_params.baseFontSize * 0.25;
|
||||
} else if (tag == QLatin1String("title")) {
|
||||
const int hLevel = qBound(1, m_headingDepth, 6);
|
||||
const qreal hScale = (hLevel == 1) ? 1.8 : (hLevel == 2 ? 1.5 : (hLevel == 3 ? 1.3 : 1.1));
|
||||
const qreal hMarginTop = (hLevel == 1) ? 1.0 : (hLevel == 2 ? 0.8 : (hLevel == 3 ? 0.6 : 0.5));
|
||||
ctx.text.fontSize = m_params.baseFontSize * hScale;
|
||||
ctx.text.weight = 700;
|
||||
ctx.textIndent = 0;
|
||||
ctx.align = TextAlign::Left;
|
||||
ctx.isHeading = true;
|
||||
box.marginTop = m_params.baseFontSize * hMarginTop;
|
||||
box.marginBottom = m_params.baseFontSize * (hMarginTop * 0.5);
|
||||
m_firstTitleLine = true;
|
||||
} else if (tag == QLatin1String("subtitle")) {
|
||||
ctx.align = TextAlign::Center;
|
||||
ctx.text.weight = 700;
|
||||
ctx.textIndent = 0;
|
||||
box.marginTop = 0;
|
||||
box.marginBottom = 0;
|
||||
} else if (tag == QLatin1String("p")) {
|
||||
box.marginTop = 0;
|
||||
box.marginBottom = 0;
|
||||
if (!ctx.isHeading) {
|
||||
ctx.textIndent = m_params.baseFontSize * 2.0;
|
||||
} else {
|
||||
ctx.textIndent = 0;
|
||||
}
|
||||
} else if (tag == QLatin1String("blockquote")) {
|
||||
ctx.textIndent = ctx.isHeading ? 0 : (m_params.baseFontSize * 2.0);
|
||||
} else if (tag == QLatin1String("blockquote") || tag == QLatin1String("epigraph")
|
||||
|| (tag == QLatin1String("cite") && m_scheme == QLatin1String("fb2"))) {
|
||||
box.marginLeft = m_params.baseFontSize * 1.5;
|
||||
box.marginRight = m_params.baseFontSize * 1.0;
|
||||
box.marginTop = m_params.baseFontSize * 0.5;
|
||||
@@ -463,6 +401,33 @@ private:
|
||||
box.borderLeft = 3;
|
||||
box.paddingLeft = m_params.baseFontSize * 0.75;
|
||||
ctx.text.italic = true;
|
||||
} else if (tag == QLatin1String("poem")) {
|
||||
box.marginLeft = m_params.baseFontSize * 2.0;
|
||||
box.marginRight = m_params.baseFontSize * 2.0;
|
||||
} else if (tag == QLatin1String("stanza")) {
|
||||
box.marginTop = m_params.baseFontSize * 1.0;
|
||||
box.marginBottom = m_params.baseFontSize * 1.0;
|
||||
} else if (tag == QLatin1String("v")) {
|
||||
ctx.textIndent = 0;
|
||||
box.marginTop = 0;
|
||||
box.marginBottom = 0;
|
||||
} else if (tag == QLatin1String("text-author") || tag == QLatin1String("date")) {
|
||||
ctx.align = TextAlign::Right;
|
||||
ctx.text.italic = true;
|
||||
ctx.textIndent = 0;
|
||||
box.marginTop = 0;
|
||||
box.marginBottom = 0;
|
||||
} else if (tag == QLatin1String("empty-line")) {
|
||||
m_chunkBuilder.finishParagraph();
|
||||
BoxStyle emptyBox;
|
||||
emptyBox.marginTop = m_params.baseFontSize * 0.5;
|
||||
emptyBox.marginBottom = m_params.baseFontSize * 0.5;
|
||||
m_chunkBuilder.startContainer(emptyBox);
|
||||
m_chunkBuilder.startParagraph(TextAlign::Left, 0, 0, m_params.baseFontSize);
|
||||
m_chunkBuilder.appendLineBreak();
|
||||
m_chunkBuilder.finishParagraph();
|
||||
m_chunkBuilder.endContainer(emptyBox);
|
||||
return;
|
||||
} else if (tag == QLatin1String("pre")) {
|
||||
ctx.text.fontFamilies = {QStringLiteral("monospace")};
|
||||
ctx.preformatted = true;
|
||||
@@ -470,11 +435,12 @@ private:
|
||||
box.marginBottom = m_params.baseFontSize * 0.5;
|
||||
} else if (tag == QLatin1String("b") || tag == QLatin1String("strong")) {
|
||||
ctx.text.weight = 700;
|
||||
} else if (tag == QLatin1String("i") || tag == QLatin1String("em") || tag == QLatin1String("cite")) {
|
||||
} else if (tag == QLatin1String("i") || tag == QLatin1String("em") || tag == QLatin1String("emphasis")
|
||||
|| (tag == QLatin1String("cite") && m_scheme != QLatin1String("fb2"))) {
|
||||
ctx.text.italic = true;
|
||||
} else if (tag == QLatin1String("u") || tag == QLatin1String("ins")) {
|
||||
ctx.text.underline = true;
|
||||
} else if (tag == QLatin1String("s") || tag == QLatin1String("strike") || tag == QLatin1String("del")) {
|
||||
} else if (tag == QLatin1String("s") || tag == QLatin1String("strike") || tag == QLatin1String("del") || tag == QLatin1String("strikethrough")) {
|
||||
ctx.text.strikeOut = true;
|
||||
} else if (tag == QLatin1String("sub")) {
|
||||
ctx.text.fontSize *= 0.75;
|
||||
@@ -491,15 +457,10 @@ private:
|
||||
ctx.text.underline = true;
|
||||
ctx.text.link = true;
|
||||
} else if (tag == QLatin1String("hr")) {
|
||||
finishCurrentParagraph();
|
||||
BlockItem r;
|
||||
r.kind = BlockItem::Kind::Rule;
|
||||
m_blocks.append(r);
|
||||
m_chunkBuilder.appendRule();
|
||||
return;
|
||||
} else if (tag == QLatin1String("br")) {
|
||||
InlineItem br;
|
||||
br.kind = InlineItem::Kind::LineBreak;
|
||||
m_currentInlines.append(br);
|
||||
m_chunkBuilder.appendLineBreak();
|
||||
return;
|
||||
} else if (tag == QLatin1String("img") || tag == QLatin1String("image")) {
|
||||
handleImage(el, ctx);
|
||||
@@ -517,10 +478,14 @@ private:
|
||||
|
||||
const bool isBlock = isBlockTag(tag);
|
||||
|
||||
// Apply CSS declarations from cascaded style attribute
|
||||
if (el.hasAttribute(QStringLiteral("style"))) {
|
||||
const auto decls = Css::parseDeclarations(el.attribute(QStringLiteral("style")));
|
||||
applyCssDeclarations(decls, ctx, box, m_params, isBlock);
|
||||
QVector<Css::Declaration> decls;
|
||||
if (m_sheet && !m_sheet->rules.isEmpty()) {
|
||||
decls = Css::cascade(*m_sheet, el);
|
||||
} else if (el.hasAttribute(QStringLiteral("style"))) {
|
||||
decls = Css::parseDeclarations(el.attribute(QStringLiteral("style")));
|
||||
}
|
||||
if (!decls.isEmpty()) {
|
||||
applyDeclarations(decls, ctx, box, m_params, isBlock);
|
||||
}
|
||||
|
||||
const bool hasBox = (box.marginTop > 0 || box.marginBottom > 0 || box.marginLeft > 0 || box.marginRight > 0
|
||||
@@ -529,12 +494,9 @@ private:
|
||||
|| box.background.isValid());
|
||||
|
||||
if (isBlock) {
|
||||
finishCurrentParagraph();
|
||||
m_chunkBuilder.finishParagraph();
|
||||
if (hasBox) {
|
||||
BlockItem start;
|
||||
start.kind = BlockItem::Kind::ContainerStart;
|
||||
start.box = box;
|
||||
m_blocks.append(start);
|
||||
m_chunkBuilder.startContainer(box);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -552,7 +514,7 @@ private:
|
||||
}
|
||||
|
||||
if (isBlock) {
|
||||
startParagraph(ctx, marker, markerStyle);
|
||||
m_chunkBuilder.startParagraph(ctx.align, ctx.textIndent, ctx.lineHeight, ctx.text.fontSize, ctx.preformatted, marker, markerStyle);
|
||||
}
|
||||
|
||||
m_stack.append(ctx);
|
||||
@@ -562,12 +524,9 @@ private:
|
||||
m_stack.removeLast();
|
||||
|
||||
if (isBlock) {
|
||||
finishCurrentParagraph();
|
||||
m_chunkBuilder.finishParagraph();
|
||||
if (hasBox) {
|
||||
BlockItem end;
|
||||
end.kind = BlockItem::Kind::ContainerEnd;
|
||||
end.box = box;
|
||||
m_blocks.append(end);
|
||||
m_chunkBuilder.endContainer(box);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -579,12 +538,15 @@ private:
|
||||
src = el.attribute(QStringLiteral("xlink:href"));
|
||||
if (src.isEmpty())
|
||||
src = el.attribute(QStringLiteral("href"));
|
||||
if (src.isEmpty())
|
||||
src = el.attribute(QStringLiteral("l:href"));
|
||||
if (src.isEmpty())
|
||||
return;
|
||||
|
||||
InlineItem item;
|
||||
item.kind = InlineItem::Kind::Image;
|
||||
item.imageUrl = src;
|
||||
QString resolved = src;
|
||||
if (!m_scheme.isEmpty()) {
|
||||
resolved = ImageUrl::resolve(m_scheme, src, m_sourcePath, m_baseDir);
|
||||
}
|
||||
|
||||
Css::LengthContext lenCtx;
|
||||
lenCtx.em = ctx.text.fontSize;
|
||||
@@ -592,64 +554,53 @@ private:
|
||||
lenCtx.percentBase = m_params.contentWidth;
|
||||
lenCtx.absoluteScale = m_params.baseFontSize / 16.0;
|
||||
|
||||
qreal cssW = -1;
|
||||
qreal cssH = -1;
|
||||
qreal cssMaxW = -1;
|
||||
|
||||
if (el.hasAttribute(QStringLiteral("width"))) {
|
||||
auto w = Css::parseLength(el.attribute(QStringLiteral("width")), lenCtx);
|
||||
if (w) item.cssWidth = *w;
|
||||
if (w) cssW = *w;
|
||||
}
|
||||
if (el.hasAttribute(QStringLiteral("height"))) {
|
||||
auto h = Css::parseLength(el.attribute(QStringLiteral("height")), lenCtx);
|
||||
if (h) item.cssHeight = *h;
|
||||
if (h) cssH = *h;
|
||||
}
|
||||
|
||||
QVector<Css::Declaration> decls;
|
||||
if (m_sheet && !m_sheet->rules.isEmpty()) {
|
||||
decls = Css::cascade(*m_sheet, el);
|
||||
} else if (el.hasAttribute(QStringLiteral("style"))) {
|
||||
decls = Css::parseDeclarations(el.attribute(QStringLiteral("style")));
|
||||
}
|
||||
|
||||
if (el.hasAttribute(QStringLiteral("style"))) {
|
||||
const auto decls = Css::parseDeclarations(el.attribute(QStringLiteral("style")));
|
||||
for (const auto &d : decls) {
|
||||
if (d.property == QLatin1String("width")) {
|
||||
auto w = Css::parseLength(d.value, lenCtx); if (w) item.cssWidth = *w;
|
||||
auto w = Css::parseLength(d.value, lenCtx); if (w) cssW = *w;
|
||||
} else if (d.property == QLatin1String("height")) {
|
||||
auto h = Css::parseLength(d.value, lenCtx); if (h) item.cssHeight = *h;
|
||||
auto h = Css::parseLength(d.value, lenCtx); if (h) cssH = *h;
|
||||
} else if (d.property == QLatin1String("max-width")) {
|
||||
auto mw = Css::parseLength(d.value, lenCtx); if (mw) item.cssMaxWidth = *mw;
|
||||
}
|
||||
auto mw = Css::parseLength(d.value, lenCtx); if (mw) cssMaxW = *mw;
|
||||
}
|
||||
}
|
||||
|
||||
if (m_currentInlines.isEmpty()) {
|
||||
startParagraph(ctx);
|
||||
}
|
||||
m_currentInlines.append(item);
|
||||
m_chunkBuilder.appendImage(resolved, cssW, cssH, cssMaxW, ctx.text);
|
||||
}
|
||||
|
||||
DocumentChunkBuilder &m_chunkBuilder;
|
||||
const ParseParams &m_params;
|
||||
const Css::StyleSheet *m_sheet = nullptr;
|
||||
QString m_scheme;
|
||||
QString m_sourcePath;
|
||||
QString m_baseDir;
|
||||
int m_headingDepth = 1;
|
||||
QDomNode m_root;
|
||||
QVector<StyleContext> m_stack;
|
||||
QVector<BlockItem> m_blocks;
|
||||
|
||||
QVector<InlineItem> m_currentInlines;
|
||||
TextAlign m_currentAlign = TextAlign::Justify;
|
||||
qreal m_currentIndent = 0;
|
||||
qreal m_currentLineHeight = 0;
|
||||
qreal m_currentBlockFontSize = 16;
|
||||
bool m_currentPreformatted = false;
|
||||
QString m_currentMarker;
|
||||
TextStyle m_currentMarkerStyle;
|
||||
bool m_firstTitleLine = false;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
QVector<BlockItem> parse(const QDomElement &root, const ParseParams ¶ms)
|
||||
QDomDocument parseHtmlToDoc(const QString &html)
|
||||
{
|
||||
if (root.isNull())
|
||||
return {};
|
||||
|
||||
Builder builder(params);
|
||||
return builder.build(root);
|
||||
}
|
||||
|
||||
QVector<BlockItem> parse(const QString &html, const ParseParams ¶ms)
|
||||
{
|
||||
if (html.trimmed().isEmpty())
|
||||
return {};
|
||||
|
||||
QString wrapped = html.trimmed();
|
||||
if (!wrapped.startsWith(QLatin1String("<")))
|
||||
wrapped = QStringLiteral("<p>") + wrapped + QStringLiteral("</p>");
|
||||
@@ -657,12 +608,40 @@ QVector<BlockItem> parse(const QString &html, const ParseParams ¶ms)
|
||||
wrapped = QStringLiteral("<body>") + wrapped + QStringLiteral("</body>");
|
||||
|
||||
const QString safeXml = HtmlEntities::toXmlSafe(wrapped);
|
||||
|
||||
QDomDocument doc;
|
||||
QString errorMsg;
|
||||
int errorLine = 0, errorColumn = 0;
|
||||
if (!doc.setContent(safeXml, false, &errorMsg, &errorLine, &errorColumn)) {
|
||||
// Fallback: return as a simple paragraph
|
||||
doc.setContent(safeXml);
|
||||
return doc;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
QVector<BlockItem> parse(const QDomElement &root,
|
||||
const ParseParams ¶ms,
|
||||
const Css::StyleSheet *sheet,
|
||||
const QString &scheme,
|
||||
const QString &sourcePath,
|
||||
const QString &baseDir,
|
||||
int headingDepth)
|
||||
{
|
||||
if (root.isNull())
|
||||
return {};
|
||||
|
||||
DocumentChunkBuilder chunkBuilder({}, 1000000000);
|
||||
Builder builder(chunkBuilder, params, sheet, scheme, sourcePath, baseDir, headingDepth, root);
|
||||
builder.build(root);
|
||||
auto chunks = chunkBuilder.build();
|
||||
if (chunks.isEmpty())
|
||||
return {};
|
||||
return chunks.first().blocks;
|
||||
}
|
||||
|
||||
QVector<BlockItem> parse(const QString &html, const ParseParams ¶ms)
|
||||
{
|
||||
if (html.trimmed().isEmpty())
|
||||
return {};
|
||||
|
||||
QDomDocument doc = parseHtmlToDoc(html);
|
||||
if (doc.documentElement().isNull()) {
|
||||
BlockItem b;
|
||||
b.kind = BlockItem::Kind::Paragraph;
|
||||
InlineItem textItem;
|
||||
@@ -682,105 +661,30 @@ QVector<ContentChunk> partitionBlocks(const QVector<BlockItem> &blocks,
|
||||
if (blocks.isEmpty())
|
||||
return {};
|
||||
|
||||
QVector<ContentChunk> chunks;
|
||||
ContentChunk current;
|
||||
current.sectionHref = sectionHref;
|
||||
|
||||
QVector<BoxStyle> openContainers;
|
||||
|
||||
auto flushCurrent = [&]() {
|
||||
if (current.isEmpty())
|
||||
return;
|
||||
|
||||
// Close outer containers at chunk boundary
|
||||
for (int j = openContainers.size() - 1; j >= 0; --j) {
|
||||
BlockItem endItem;
|
||||
endItem.kind = BlockItem::Kind::ContainerEnd;
|
||||
endItem.box = openContainers[j];
|
||||
endItem.box.borderBottom = 0;
|
||||
endItem.box.paddingBottom = 0;
|
||||
endItem.box.marginBottom = 0;
|
||||
current.blocks.append(endItem);
|
||||
DocumentChunkBuilder builder(sectionHref, targetChars);
|
||||
for (const auto &b : blocks) {
|
||||
builder.appendBlock(b);
|
||||
}
|
||||
|
||||
chunks.append(std::move(current));
|
||||
current = ContentChunk();
|
||||
current.sectionHref = sectionHref;
|
||||
current.unnestedContainers = openContainers.size();
|
||||
|
||||
// Reopen outer containers at start of next chunk
|
||||
for (int j = 0; j < openContainers.size(); ++j) {
|
||||
BlockItem startItem;
|
||||
startItem.kind = BlockItem::Kind::ContainerStart;
|
||||
startItem.box = openContainers[j];
|
||||
startItem.box.borderTop = 0;
|
||||
startItem.box.paddingTop = 0;
|
||||
startItem.box.marginTop = 0;
|
||||
current.blocks.append(startItem);
|
||||
}
|
||||
};
|
||||
|
||||
for (int i = 0; i < blocks.size(); ++i) {
|
||||
const auto &b = blocks[i];
|
||||
if (b.kind == BlockItem::Kind::ContainerStart) {
|
||||
openContainers.append(b.box);
|
||||
current.blocks.append(b);
|
||||
} else if (b.kind == BlockItem::Kind::ContainerEnd) {
|
||||
if (!openContainers.isEmpty())
|
||||
openContainers.removeLast();
|
||||
current.blocks.append(b);
|
||||
} else if (b.kind == BlockItem::Kind::Rule) {
|
||||
current.blocks.append(b);
|
||||
current.charCount += 1;
|
||||
if (current.charCount >= targetChars && i + 1 < blocks.size()) {
|
||||
flushCurrent();
|
||||
}
|
||||
} else if (b.kind == BlockItem::Kind::Paragraph) {
|
||||
int pChars = 0;
|
||||
int pWords = 0;
|
||||
for (const auto &inl : b.inlines) {
|
||||
if (inl.kind == InlineItem::Kind::Text) {
|
||||
pChars += inl.text.size();
|
||||
const QStringList words = inl.text.split(QLatin1Char(' '), Qt::SkipEmptyParts);
|
||||
pWords += words.size();
|
||||
} else if (inl.kind == InlineItem::Kind::Image) {
|
||||
pChars += 1;
|
||||
pWords += 1;
|
||||
}
|
||||
}
|
||||
|
||||
current.blocks.append(b);
|
||||
current.charCount += pChars;
|
||||
current.wordCount += pWords;
|
||||
|
||||
// Consume immediately following ContainerEnd that closes this paragraph's leaf box
|
||||
if (i + 1 < blocks.size() && blocks[i + 1].kind == BlockItem::Kind::ContainerEnd) {
|
||||
if (!openContainers.isEmpty())
|
||||
openContainers.removeLast();
|
||||
current.blocks.append(blocks[i + 1]);
|
||||
++i;
|
||||
}
|
||||
|
||||
if (current.charCount >= targetChars && i + 1 < blocks.size()) {
|
||||
flushCurrent();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!current.isEmpty()) {
|
||||
chunks.append(std::move(current));
|
||||
}
|
||||
|
||||
return chunks;
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
QVector<ContentChunk> parseChunks(const QDomElement &root,
|
||||
const QString §ionHref,
|
||||
int targetChars,
|
||||
const ParseParams ¶ms)
|
||||
const ParseParams ¶ms,
|
||||
const Css::StyleSheet *sheet,
|
||||
const QString &scheme,
|
||||
const QString &sourcePath,
|
||||
const QString &baseDir,
|
||||
int headingDepth)
|
||||
{
|
||||
const auto blocks = parse(root, params);
|
||||
return partitionBlocks(blocks, sectionHref, targetChars);
|
||||
if (root.isNull())
|
||||
return {};
|
||||
|
||||
DocumentChunkBuilder chunkBuilder(sectionHref, targetChars);
|
||||
Builder builder(chunkBuilder, params, sheet, scheme, sourcePath, baseDir, headingDepth, root);
|
||||
builder.build(root);
|
||||
return chunkBuilder.build();
|
||||
}
|
||||
|
||||
QVector<ContentChunk> parseChunks(const QString &html,
|
||||
@@ -788,9 +692,26 @@ QVector<ContentChunk> parseChunks(const QString &html,
|
||||
int targetChars,
|
||||
const ParseParams ¶ms)
|
||||
{
|
||||
const auto blocks = parse(html, params);
|
||||
return partitionBlocks(blocks, sectionHref, targetChars);
|
||||
if (html.trimmed().isEmpty())
|
||||
return {};
|
||||
|
||||
QDomDocument doc = parseHtmlToDoc(html);
|
||||
if (doc.documentElement().isNull()) {
|
||||
ContentChunk chunk;
|
||||
chunk.sectionHref = sectionHref;
|
||||
BlockItem b;
|
||||
b.kind = BlockItem::Kind::Paragraph;
|
||||
InlineItem textItem;
|
||||
textItem.kind = InlineItem::Kind::Text;
|
||||
textItem.text = html;
|
||||
b.inlines.append(textItem);
|
||||
chunk.blocks.append(b);
|
||||
chunk.charCount = html.size();
|
||||
chunk.wordCount = html.split(QLatin1Char(' '), Qt::SkipEmptyParts).size();
|
||||
return {chunk};
|
||||
}
|
||||
|
||||
return parseChunks(doc.documentElement(), sectionHref, targetChars, params);
|
||||
}
|
||||
|
||||
} // namespace HtmlBlockParser
|
||||
|
||||
@@ -1,173 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include <QColor>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QVector>
|
||||
|
||||
// Intermediate representation between HTML chunks and the Knuth-Plass layout.
|
||||
// All lengths are resolved to pixels for the LayoutParams used at parse time.
|
||||
|
||||
enum class TextAlign { Justify, Left, Center, Right };
|
||||
enum class TextTransform { None, Uppercase, Lowercase, Capitalize };
|
||||
|
||||
struct TextStyle {
|
||||
QStringList fontFamilies; // preferred families in order (may contain generic names); empty = default
|
||||
qreal fontSize = 16; // px
|
||||
int weight = 400; // CSS weight 100..900
|
||||
bool italic = false;
|
||||
bool smallCaps = false;
|
||||
TextTransform transform = TextTransform::None;
|
||||
qreal letterSpacing = 0; // px
|
||||
bool underline = false;
|
||||
bool strikeOut = false;
|
||||
bool overline = false;
|
||||
bool link = false;
|
||||
QColor color; // invalid = theme default
|
||||
QColor background; // invalid = none
|
||||
qreal baselineShift = 0; // px, positive = raised (superscript)
|
||||
|
||||
bool operator==(const TextStyle &o) const {
|
||||
return fontFamilies == o.fontFamilies
|
||||
&& qFuzzyCompare(fontSize, o.fontSize)
|
||||
&& weight == o.weight
|
||||
&& italic == o.italic
|
||||
&& smallCaps == o.smallCaps
|
||||
&& transform == o.transform
|
||||
&& qFuzzyCompare(letterSpacing, o.letterSpacing)
|
||||
&& underline == o.underline
|
||||
&& strikeOut == o.strikeOut
|
||||
&& overline == o.overline
|
||||
&& link == o.link
|
||||
&& color == o.color
|
||||
&& background == o.background
|
||||
&& qFuzzyCompare(baselineShift, o.baselineShift);
|
||||
}
|
||||
};
|
||||
|
||||
struct InlineItem {
|
||||
enum class Kind { Text, Image, LineBreak };
|
||||
Kind kind = Kind::Text;
|
||||
QString text; // whitespace already collapsed unless preformatted
|
||||
TextStyle style;
|
||||
QString imageUrl;
|
||||
qreal cssWidth = -1; // px, -1 = auto
|
||||
qreal cssHeight = -1;
|
||||
qreal cssMaxWidth = -1;
|
||||
|
||||
bool operator==(const InlineItem &o) const
|
||||
{
|
||||
return kind == o.kind
|
||||
&& text == o.text
|
||||
&& style == o.style
|
||||
&& imageUrl == o.imageUrl
|
||||
&& qFuzzyCompare(cssWidth, o.cssWidth)
|
||||
&& qFuzzyCompare(cssHeight, o.cssHeight)
|
||||
&& qFuzzyCompare(cssMaxWidth, o.cssMaxWidth);
|
||||
}
|
||||
};
|
||||
|
||||
struct BoxStyle {
|
||||
qreal marginTop = 0, marginBottom = 0, marginLeft = 0, marginRight = 0;
|
||||
qreal paddingTop = 0, paddingBottom = 0, paddingLeft = 0, paddingRight = 0;
|
||||
qreal borderTop = 0, borderBottom = 0, borderLeft = 0, borderRight = 0;
|
||||
QColor borderColor; // invalid = theme dim colour
|
||||
QColor background; // invalid = none
|
||||
|
||||
// Boxes with a visible top edge stop margins collapsing through them.
|
||||
bool blocksTopCollapse() const
|
||||
{
|
||||
return paddingTop > 0 || borderTop > 0 || borderLeft > 0 || borderRight > 0 || background.isValid();
|
||||
}
|
||||
bool blocksBottomCollapse() const
|
||||
{
|
||||
return paddingBottom > 0 || borderBottom > 0 || borderLeft > 0 || borderRight > 0 || background.isValid();
|
||||
}
|
||||
|
||||
bool operator==(const BoxStyle &o) const
|
||||
{
|
||||
return qFuzzyCompare(marginTop, o.marginTop)
|
||||
&& qFuzzyCompare(marginBottom, o.marginBottom)
|
||||
&& qFuzzyCompare(marginLeft, o.marginLeft)
|
||||
&& qFuzzyCompare(marginRight, o.marginRight)
|
||||
&& qFuzzyCompare(paddingTop, o.paddingTop)
|
||||
&& qFuzzyCompare(paddingBottom, o.paddingBottom)
|
||||
&& qFuzzyCompare(paddingLeft, o.paddingLeft)
|
||||
&& qFuzzyCompare(paddingRight, o.paddingRight)
|
||||
&& qFuzzyCompare(borderTop, o.borderTop)
|
||||
&& qFuzzyCompare(borderBottom, o.borderBottom)
|
||||
&& qFuzzyCompare(borderLeft, o.borderLeft)
|
||||
&& qFuzzyCompare(borderRight, o.borderRight)
|
||||
&& borderColor == o.borderColor
|
||||
&& background == o.background;
|
||||
}
|
||||
};
|
||||
|
||||
struct BlockItem {
|
||||
enum class Kind { ContainerStart, ContainerEnd, Paragraph, Rule };
|
||||
Kind kind = Kind::Paragraph;
|
||||
BoxStyle box; // ContainerStart / ContainerEnd (same values on both)
|
||||
|
||||
// Paragraph properties
|
||||
TextAlign align = TextAlign::Justify;
|
||||
qreal textIndent = 0; // px, first line only
|
||||
qreal lineHeight = 0; // multiplier of fontSize; 0 = LayoutParams default
|
||||
qreal fontSize = 16; // block font size (minimum line height basis)
|
||||
bool preformatted = false;
|
||||
QString marker; // list marker drawn left of the first line
|
||||
TextStyle markerStyle;
|
||||
QVector<InlineItem> inlines;
|
||||
|
||||
QColor ruleColor; // Rule only; invalid = theme dim colour
|
||||
|
||||
bool operator==(const BlockItem &o) const
|
||||
{
|
||||
return kind == o.kind
|
||||
&& box == o.box
|
||||
&& align == o.align
|
||||
&& qFuzzyCompare(textIndent, o.textIndent)
|
||||
&& qFuzzyCompare(lineHeight, o.lineHeight)
|
||||
&& qFuzzyCompare(fontSize, o.fontSize)
|
||||
&& preformatted == o.preformatted
|
||||
&& marker == o.marker
|
||||
&& markerStyle == o.markerStyle
|
||||
&& inlines == o.inlines
|
||||
&& ruleColor == o.ruleColor;
|
||||
}
|
||||
};
|
||||
|
||||
struct ParseParams {
|
||||
qreal baseFontSize = 16; // user preference, px
|
||||
qreal contentWidth = 600; // px, resolves percentage lengths
|
||||
};
|
||||
|
||||
struct ContentChunk {
|
||||
QString sectionHref;
|
||||
QVector<BlockItem> blocks;
|
||||
int wordCount = 0;
|
||||
int charCount = 0;
|
||||
int unnestedContainers = 0;
|
||||
|
||||
bool isEmpty() const { return blocks.isEmpty(); }
|
||||
|
||||
bool operator==(const ContentChunk &o) const
|
||||
{
|
||||
return sectionHref == o.sectionHref
|
||||
&& blocks == o.blocks
|
||||
&& wordCount == o.wordCount
|
||||
&& charCount == o.charCount
|
||||
&& unnestedContainers == o.unnestedContainers;
|
||||
}
|
||||
};
|
||||
#include "DocumentIr.h"
|
||||
#include "CssParser.h"
|
||||
|
||||
class QDomElement;
|
||||
|
||||
namespace HtmlBlockParser {
|
||||
|
||||
// Parses HTML or DOM element (whose elements carry cascaded CSS in `style` attributes)
|
||||
// into a flat block list.
|
||||
// Parses HTML or DOM element into a flat block list.
|
||||
QVector<BlockItem> parse(const QString &html, const ParseParams ¶ms = {});
|
||||
QVector<BlockItem> parse(const QDomElement &root, const ParseParams ¶ms = {});
|
||||
QVector<BlockItem> parse(const QDomElement &root,
|
||||
const ParseParams ¶ms = {},
|
||||
const Css::StyleSheet *sheet = nullptr,
|
||||
const QString &scheme = {},
|
||||
const QString &sourcePath = {},
|
||||
const QString &baseDir = {},
|
||||
int headingDepth = 1);
|
||||
|
||||
// Partitions a block list into granular ContentChunks (~targetChars per chunk).
|
||||
QVector<ContentChunk> partitionBlocks(const QVector<BlockItem> &blocks,
|
||||
@@ -178,7 +26,12 @@ QVector<ContentChunk> partitionBlocks(const QVector<BlockItem> &blocks,
|
||||
QVector<ContentChunk> parseChunks(const QDomElement &root,
|
||||
const QString §ionHref = {},
|
||||
int targetChars = 512,
|
||||
const ParseParams ¶ms = {});
|
||||
const ParseParams ¶ms = {},
|
||||
const Css::StyleSheet *sheet = nullptr,
|
||||
const QString &scheme = {},
|
||||
const QString &sourcePath = {},
|
||||
const QString &baseDir = {},
|
||||
int headingDepth = 1);
|
||||
|
||||
QVector<ContentChunk> parseChunks(const QString &html,
|
||||
const QString §ionHref = {},
|
||||
@@ -186,4 +39,3 @@ QVector<ContentChunk> parseChunks(const QString &html,
|
||||
const ParseParams ¶ms = {});
|
||||
|
||||
} // namespace HtmlBlockParser
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
#include "backend/formats/Fb2Types.h"
|
||||
#include "backend/formats/sources/Fb2ByteSource.h"
|
||||
#include "backend/formats/ImageUrl.h"
|
||||
#include "backend/reading/layout/DomChunkPipeline.h"
|
||||
#include "backend/reading/layout/CssParser.h"
|
||||
#include "backend/reading/layout/HtmlBlockParser.h"
|
||||
#include "backend/reading/layout/ChunkLayoutEngine.h"
|
||||
|
||||
@@ -367,7 +367,7 @@ private slots:
|
||||
// Obligation 7: contract-signature.SharedDomChunkPipeline.cascade_and_chunk
|
||||
void testContractSignatureSharedDomChunkPipeline()
|
||||
{
|
||||
// Verify cascade_and_chunk signature and invariant DeterministicChunking
|
||||
// Verify parseChunks deterministic chunking invariant
|
||||
QDomDocument doc1;
|
||||
doc1.setContent(QStringLiteral("<div><p class=\"lead\">Paragraph in EPUB spine</p></div>"));
|
||||
QDomElement root1 = doc1.documentElement();
|
||||
@@ -382,10 +382,11 @@ private slots:
|
||||
const QString sectionHref = QStringLiteral("sec1");
|
||||
const int targetChars = 512;
|
||||
|
||||
QVector<ContentChunk> chunks1 = DomChunkPipeline::cascadeAndChunk(
|
||||
root1, stylesheets, scheme, sourcePath, sectionHref, QString(), targetChars);
|
||||
QVector<ContentChunk> chunks2 = DomChunkPipeline::cascadeAndChunk(
|
||||
root2, stylesheets, scheme, sourcePath, sectionHref, QString(), targetChars);
|
||||
Css::StyleSheet sheet = Css::StyleSheet::parse(stylesheets.first());
|
||||
QVector<ContentChunk> chunks1 = HtmlBlockParser::parseChunks(
|
||||
root1, sectionHref, targetChars, {}, &sheet, scheme, sourcePath);
|
||||
QVector<ContentChunk> chunks2 = HtmlBlockParser::parseChunks(
|
||||
root2, sectionHref, targetChars, {}, &sheet, scheme, sourcePath);
|
||||
|
||||
QCOMPARE(chunks1.size(), chunks2.size());
|
||||
QVERIFY(!chunks1.isEmpty());
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
#include <QtTest>
|
||||
#include "backend/formats/TextEncoding.h"
|
||||
|
||||
class TextEncodingTest : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void testEmpty();
|
||||
void testUtf8NoBom();
|
||||
void testUtf8WithBom();
|
||||
void testUtf16LeWithBom();
|
||||
void testUtf16BeWithBom();
|
||||
void testDetectXmlEncoding();
|
||||
void testDetectHtml5Charset();
|
||||
void testDetectHtml4Charset();
|
||||
void testDecodeWindows1251();
|
||||
void testDecodeWithHint();
|
||||
void testDecodeWithExplicitEncoding();
|
||||
};
|
||||
|
||||
void TextEncodingTest::testEmpty()
|
||||
{
|
||||
QCOMPARE(TextEncoding::detectEncoding(QByteArray()), QString());
|
||||
QCOMPARE(TextEncoding::decode(QByteArray()), QString());
|
||||
QCOMPARE(TextEncoding::decodeWithEncoding(QByteArray(), QStringLiteral("utf-8")), QString());
|
||||
}
|
||||
|
||||
void TextEncodingTest::testUtf8NoBom()
|
||||
{
|
||||
const QByteArray bytes = "Hello, world! \xF0\x9F\x93\x96"; // book emoji
|
||||
const QString result = TextEncoding::decode(bytes);
|
||||
QCOMPARE(result, QString::fromUtf8(bytes));
|
||||
}
|
||||
|
||||
void TextEncodingTest::testUtf8WithBom()
|
||||
{
|
||||
const QByteArray bytes = "\xEF\xBB\xBFHello, BOM!";
|
||||
QCOMPARE(TextEncoding::detectEncoding(bytes), QStringLiteral("UTF-8"));
|
||||
const QString result = TextEncoding::decode(bytes);
|
||||
QCOMPARE(result, QStringLiteral("Hello, BOM!"));
|
||||
}
|
||||
|
||||
void TextEncodingTest::testUtf16LeWithBom()
|
||||
{
|
||||
// UTF-16 LE BOM + "AB" (0x0041, 0x0042)
|
||||
const QByteArray bytes = QByteArray("\xFF\xFE\x41\x00\x42\x00", 6);
|
||||
QCOMPARE(TextEncoding::detectEncoding(bytes), QStringLiteral("UTF-16LE"));
|
||||
const QString result = TextEncoding::decode(bytes);
|
||||
QCOMPARE(result, QStringLiteral("AB"));
|
||||
}
|
||||
|
||||
void TextEncodingTest::testUtf16BeWithBom()
|
||||
{
|
||||
// UTF-16 BE BOM + "AB" (0x0041, 0x0042)
|
||||
const QByteArray bytes = QByteArray("\xFE\xFF\x00\x41\x00\x42", 6);
|
||||
QCOMPARE(TextEncoding::detectEncoding(bytes), QStringLiteral("UTF-16BE"));
|
||||
const QString result = TextEncoding::decode(bytes);
|
||||
QCOMPARE(result, QStringLiteral("AB"));
|
||||
}
|
||||
|
||||
void TextEncodingTest::testDetectXmlEncoding()
|
||||
{
|
||||
const QByteArray xml1 = "<?xml version=\"1.0\" encoding=\"windows-1251\"?>\n<FictionBook>";
|
||||
QCOMPARE(TextEncoding::detectEncoding(xml1), QStringLiteral("windows-1251"));
|
||||
|
||||
const QByteArray xml2 = "<?xml version='1.0' encoding='KOI8-R'?>\n<FictionBook>";
|
||||
QCOMPARE(TextEncoding::detectEncoding(xml2), QStringLiteral("KOI8-R"));
|
||||
}
|
||||
|
||||
void TextEncodingTest::testDetectHtml5Charset()
|
||||
{
|
||||
const QByteArray html = "<html><head><meta charset=\"shift_jis\"></head></html>";
|
||||
QCOMPARE(TextEncoding::detectEncoding(html), QStringLiteral("shift_jis"));
|
||||
}
|
||||
|
||||
void TextEncodingTest::testDetectHtml4Charset()
|
||||
{
|
||||
const QByteArray html = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=gbk\"></head></html>";
|
||||
QCOMPARE(TextEncoding::detectEncoding(html), QStringLiteral("gbk"));
|
||||
}
|
||||
|
||||
void TextEncodingTest::testDecodeWindows1251()
|
||||
{
|
||||
// "Привет" in windows-1251: CF F0 E8 E2 E5 F2
|
||||
const QByteArray win1251Text("\xCF\xF0\xE8\xE2\xE5\xF2");
|
||||
const QByteArray xml = "<?xml version=\"1.0\" encoding=\"windows-1251\"?>\n<title>" + win1251Text + "</title>";
|
||||
|
||||
const QString result = TextEncoding::decode(xml);
|
||||
QVERIFY(result.contains(QString::fromUtf8("Привет")));
|
||||
}
|
||||
|
||||
void TextEncodingTest::testDecodeWithHint()
|
||||
{
|
||||
// "Привет" in windows-1251 without header
|
||||
const QByteArray win1251Text("\xCF\xF0\xE8\xE2\xE5\xF2");
|
||||
const QString result = TextEncoding::decode(win1251Text, QStringLiteral("windows-1251"));
|
||||
QCOMPARE(result, QString::fromUtf8("Привет"));
|
||||
}
|
||||
|
||||
void TextEncodingTest::testDecodeWithExplicitEncoding()
|
||||
{
|
||||
const QByteArray win1251Text("\xCF\xF0\xE8\xE2\xE5\xF2");
|
||||
const QString result = TextEncoding::decodeWithEncoding(win1251Text, QStringLiteral("windows-1251"));
|
||||
QCOMPARE(result, QString::fromUtf8("Привет"));
|
||||
|
||||
// Invalid encoding returns empty
|
||||
const QString invalid = TextEncoding::decodeWithEncoding(win1251Text, QStringLiteral("invalid_encoding_xyz"));
|
||||
QVERIFY(invalid.isEmpty());
|
||||
}
|
||||
|
||||
QTEST_MAIN(TextEncodingTest)
|
||||
#include "TextEncodingTest.moc"
|
||||
@@ -111,12 +111,19 @@ private slots:
|
||||
QDomElement p = doc.elementsByTagName(QStringLiteral("p")).at(0).toElement();
|
||||
|
||||
auto decls = Css::cascade(sheet, p);
|
||||
QString serialized = Css::serialize(decls);
|
||||
bool hasBold = false;
|
||||
bool hasRed = false;
|
||||
for (const auto &d : decls) {
|
||||
if (d.property == QLatin1String("font-weight") && d.value == QLatin1String("bold"))
|
||||
hasBold = true;
|
||||
if (d.property == QLatin1String("color") && d.value == QLatin1String("red"))
|
||||
hasRed = true;
|
||||
}
|
||||
|
||||
// font-weight: bold should match div > p.highlight
|
||||
QVERIFY(serialized.contains(QStringLiteral("font-weight:bold")));
|
||||
QVERIFY(hasBold);
|
||||
// color: red should win because it is !important in #special, beating inline style="color: green"
|
||||
QVERIFY(serialized.contains(QStringLiteral("color:red")));
|
||||
QVERIFY(hasRed);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user