more performance optimizations + cleanup

This commit is contained in:
Agel committed 2026-10-29 12:12:02 +01:00
1 parent b23713bea6
commit d9a0991f9b
15 files changed
+396 -469

No files matched your search

+4 -2
View File
@@ -7,6 +7,8 @@
#include <QStringList>
#include <QVector>
#include "backend/reading/layout/HtmlBlockParser.h"
enum class ReadingMode {
Comic, // Paged / paired image mode (CBZ, CBR, Folder)
Text // Continuous / chaptered text mode (EPUB, FB2, TXT)
@@ -38,8 +40,8 @@ public:
virtual QVector<PageInfo> pages() const { return {}; }
// Text mode (default empty for comic readers)
// Returns standalone HTML fragments representing the entire book for continuous scrolling.
virtual QStringList chunks() const { return {}; }
// Returns pre-parsed content chunks representing the entire book for continuous scrolling.
virtual QVector<ContentChunk> chunks() const { return {}; }
};
#endif // FORMATREADER_H
+3 -3
View File
@@ -37,7 +37,7 @@ QVariant ReadingModel::data(const QModelIndex &index, int role) const
if (!index.isValid() || !m_isTextMode || index.row() < 0 || index.row() >= m_chunks.size())
return {};
if (role == ContentRole)
return m_chunks.at(index.row());
return m_chunks.at(index.row()).sectionHref;
if (role == LayoutRole && index.row() < m_chunks.size()) {
ensureChunkLayout(index.row());
return QVariant::fromValue(m_chunkLayouts.at(index.row()));
@@ -310,8 +310,8 @@ void ReadingModel::startLayoutMeasurement(int restoreChunk, qreal restoreIntraOf
// Phase 2: Compute remaining chunks in the background
QPointer<ReadingModel> self(this);
m_layoutFuture = QtConcurrent::run([self, generation, chunks, params, resolver, startIdx, endIdx]() {
auto prepared = QtConcurrent::blockingMapped(chunks, [params, resolver](const QString &chunkHtml) {
return ChunkLayoutEngine::prepareChunk(chunkHtml, params.fontSize, resolver);
auto prepared = QtConcurrent::blockingMapped(chunks, [params, resolver](const ContentChunk &chunk) {
return ChunkLayoutEngine::prepareChunk(chunk, params.fontSize, resolver);
});
if (!self || self->m_layoutGeneration != generation)
+1 -1
View File
@@ -106,7 +106,7 @@ private:
bool m_measuring = false;
int m_currentPage = 0;
int m_totalPages = 0;
QStringList m_chunks;
QVector<ContentChunk> m_chunks;
mutable QVector<ChunkLayoutEngine::PreparedChunk> m_preparedChunks;
mutable QVector<ChunkLayout> m_chunkLayouts;
int m_lastSyncStart = -1;
+9 -175
View File
@@ -128,7 +128,7 @@ void EpubReader::appendSpineChunks(const QString &xhtml,
const QString safeXml = HtmlEntities::toXmlSafe(xhtml);
QDomDocument doc;
if (!doc.setContent(safeXml)) {
m_chunks.append(xhtml);
m_chunks.append(HtmlBlockParser::parseChunks(xhtml, xhtmlHref));
return;
}
@@ -209,179 +209,8 @@ void EpubReader::appendSpineChunks(const QString &xhtml,
QDomElement root = doc.documentElement();
processElement(root);
// 5. Chunk <body> directly from modified DOM
QDomNodeList bodies = doc.elementsByTagName(QStringLiteral("body"));
if (bodies.isEmpty()) {
QString serialized;
QTextStream ts(&serialized);
doc.save(ts, 0);
m_chunks.append(serialized);
return;
}
QDomElement body = bodies.at(0).toElement();
auto hasBoxDecoration = [](const QDomElement &el) -> bool {
const QString style = el.attribute(QStringLiteral("style")).toLower();
if (style.isEmpty())
return false;
const auto decls = Css::parseDeclarations(style);
for (const auto &d : decls) {
const QString p = d.property.toLower();
if (p.contains(QLatin1String("background")) && d.value != QLatin1String("none") && d.value != QLatin1String("transparent"))
return true;
if (p.contains(QLatin1String("border")) && !d.value.startsWith(QLatin1String("none")) && !d.value.startsWith(QLatin1String("0")))
return true;
}
return false;
};
static const QStringList kInheritableProperties = {
QStringLiteral("color"),
QStringLiteral("font-family"),
QStringLiteral("font-size"),
QStringLiteral("font-style"),
QStringLiteral("font-weight"),
QStringLiteral("line-height"),
QStringLiteral("text-align"),
QStringLiteral("letter-spacing"),
QStringLiteral("text-transform")
};
auto propagateInheritedStyles = [](const QDomElement &parentEl, QDomElement &childEl) {
const auto parentDecls = Css::parseDeclarations(parentEl.attribute(QStringLiteral("style")));
if (parentDecls.isEmpty())
return;
auto childDecls = Css::parseDeclarations(childEl.attribute(QStringLiteral("style")));
QSet<QString> childProps;
for (const auto &cd : childDecls) {
childProps.insert(cd.property.toLower());
}
bool modified = false;
for (const auto &pd : parentDecls) {
const QString prop = pd.property.toLower();
if (kInheritableProperties.contains(prop) && !childProps.contains(prop)) {
childDecls.append(pd);
childProps.insert(prop);
modified = true;
}
}
if (modified) {
childEl.setAttribute(QStringLiteral("style"), Css::serialize(childDecls));
}
};
static const QSet<QString> kBlockTags = {
QStringLiteral("p"), QStringLiteral("div"),
QStringLiteral("h1"), QStringLiteral("h2"),
QStringLiteral("h3"), QStringLiteral("h4"),
QStringLiteral("h5"), QStringLiteral("h6"),
QStringLiteral("blockquote"), QStringLiteral("pre"),
QStringLiteral("ul"), QStringLiteral("ol"),
QStringLiteral("li"), QStringLiteral("table"),
QStringLiteral("hr"), QStringLiteral("figure"),
QStringLiteral("section"), QStringLiteral("article"),
QStringLiteral("header"), QStringLiteral("footer"),
QStringLiteral("aside")
};
static const QSet<QString> kStructuralTags = {
QStringLiteral("div"),
QStringLiteral("section"),
QStringLiteral("article"),
QStringLiteral("main"),
QStringLiteral("header"),
QStringLiteral("footer"),
QStringLiteral("aside")
};
std::function<bool(const QDomElement &)> hasBlockChild = [&](const QDomElement &el) {
for (QDomNode n = el.firstChild(); !n.isNull(); n = n.nextSibling()) {
if (n.isElement()) {
const QString childTag = n.toElement().tagName().toLower();
if (kBlockTags.contains(childTag)) {
return true;
}
}
}
return false;
};
QVector<QDomNode> blockNodes;
std::function<void(const QDomElement &)> collectBlocks = [&](const QDomElement &parent) {
QDomDocument parentDoc = parent.ownerDocument();
QDomElement pendingInlinePara;
auto flushPendingInline = [&]() {
if (!pendingInlinePara.isNull()) {
if (!pendingInlinePara.text().trimmed().isEmpty() || pendingInlinePara.elementsByTagName(QStringLiteral("img")).size() > 0) {
blockNodes.append(pendingInlinePara);
}
pendingInlinePara = QDomElement();
}
};
for (QDomNode child = parent.firstChild(); !child.isNull(); child = child.nextSibling()) {
if (!child.isElement()) {
if (child.isText() && !child.toText().data().trimmed().isEmpty()) {
if (pendingInlinePara.isNull()) {
pendingInlinePara = parentDoc.createElement(QStringLiteral("p"));
}
pendingInlinePara.appendChild(child.cloneNode(true));
}
continue;
}
QDomElement childEl = child.toElement();
const QString tag = childEl.tagName().toLower();
if (!kBlockTags.contains(tag)) {
// Inline element (e.g. <span>, <em>, <a>, <img>) directly in container
if (pendingInlinePara.isNull()) {
pendingInlinePara = parentDoc.createElement(QStringLiteral("p"));
}
pendingInlinePara.appendChild(childEl.cloneNode(true));
continue;
}
// Child is a block element: flush any preceding inline nodes into their own block
flushPendingInline();
// Unwrap only structural containers that have block-level children and no box decoration
if (kStructuralTags.contains(tag) && !hasBoxDecoration(childEl) && hasBlockChild(childEl)) {
for (QDomNode n = childEl.firstChild(); !n.isNull(); n = n.nextSibling()) {
if (n.isElement()) {
QDomElement subEl = n.toElement();
propagateInheritedStyles(childEl, subEl);
}
}
collectBlocks(childEl);
} else {
blockNodes.append(childEl);
}
}
flushPendingInline();
};
collectBlocks(body);
QString currentChunk;
static constexpr int kChunkTargetSize = 512;
for (const QDomNode &node : blockNodes) {
QString serialized;
QTextStream ts(&serialized);
node.save(ts, 0);
if (!currentChunk.isEmpty() && (currentChunk.size() + serialized.size() > kChunkTargetSize)) {
m_chunks.append(currentChunk);
currentChunk.clear();
}
currentChunk += serialized;
}
if (!currentChunk.isEmpty())
m_chunks.append(currentChunk);
// 5. Build ContentChunks directly from cascaded DOM
m_chunks.append(HtmlBlockParser::parseChunks(root, xhtmlHref));
}
bool EpubReader::parseOpen(const QString &filePath, IByteSource &source, bool metadataOnly)
@@ -430,7 +259,12 @@ bool EpubReader::parseOpen(const QString &filePath, IByteSource &source, bool me
}
}
if (m_chunks.isEmpty()) {
m_chunks.append(QStringLiteral("<p></p>"));
ContentChunk emptyChunk;
emptyChunk.sectionHref = m_filePath;
BlockItem p;
p.kind = BlockItem::Kind::Paragraph;
emptyChunk.blocks.append(p);
m_chunks.append(emptyChunk);
}
}
+2 -2
View File
@@ -30,7 +30,7 @@ public:
QString coverImageUrl() const override;
QByteArray contentHash() const override { return m_contentHash; }
QStringList chunks() const override { return m_chunks; }
QVector<ContentChunk> chunks() const override { return m_chunks; }
private:
struct ManifestItem {
@@ -61,6 +61,6 @@ private:
QHash<QString, ManifestItem> m_manifest; // id -> item
QStringList m_spineHrefs; // ordered spine relative hrefs
QStringList m_chunks;
QVector<ContentChunk> m_chunks;
};
@@ -157,7 +157,7 @@ private:
dec.background = box.background;
dec.borderColor = box.borderColor;
dec.borderLeft = box.borderLeft;
dec.borderTop = box.borderTop;
dec.borderTop = ab.box.borderTop;
dec.borderBottom = box.borderBottom;
dec.borderRight = box.borderRight;
@@ -466,6 +466,8 @@ PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
PreparedChunk prepared;
prepared.blocks.reserve(blocks.size());
const qreal fontScale = (baseFontSize > 0) ? (baseFontSize / 16.0) : 1.0;
// Word metrics cache across the chunk
QHash<QString, WordMetrics> metricsCache;
@@ -475,11 +477,39 @@ PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
case BlockItem::Kind::ContainerStart:
pb.kind = PreparedBlock::Kind::ContainerStart;
pb.box = b.box;
if (!qFuzzyCompare(fontScale, 1.0)) {
pb.box.marginTop *= fontScale;
pb.box.marginBottom *= fontScale;
pb.box.marginLeft *= fontScale;
pb.box.marginRight *= fontScale;
pb.box.paddingTop *= fontScale;
pb.box.paddingBottom *= fontScale;
pb.box.paddingLeft *= fontScale;
pb.box.paddingRight *= fontScale;
pb.box.borderTop *= fontScale;
pb.box.borderBottom *= fontScale;
pb.box.borderLeft *= fontScale;
pb.box.borderRight *= fontScale;
}
prepared.blocks.append(pb);
break;
case BlockItem::Kind::ContainerEnd:
pb.kind = PreparedBlock::Kind::ContainerEnd;
pb.box = b.box;
if (!qFuzzyCompare(fontScale, 1.0)) {
pb.box.marginTop *= fontScale;
pb.box.marginBottom *= fontScale;
pb.box.marginLeft *= fontScale;
pb.box.marginRight *= fontScale;
pb.box.paddingTop *= fontScale;
pb.box.paddingBottom *= fontScale;
pb.box.paddingLeft *= fontScale;
pb.box.paddingRight *= fontScale;
pb.box.borderTop *= fontScale;
pb.box.borderBottom *= fontScale;
pb.box.borderLeft *= fontScale;
pb.box.borderRight *= fontScale;
}
prepared.blocks.append(pb);
break;
case BlockItem::Kind::Rule:
@@ -493,9 +523,9 @@ PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
const auto &imgInline = b.inlines[pureImageIdx];
pb.kind = PreparedBlock::Kind::ImageBlock;
pb.imageBlock.imageUrl = imgInline.imageUrl;
pb.imageBlock.cssWidth = imgInline.cssWidth;
pb.imageBlock.cssHeight = imgInline.cssHeight;
pb.imageBlock.cssMaxWidth = imgInline.cssMaxWidth;
pb.imageBlock.cssWidth = (imgInline.cssWidth > 0) ? (imgInline.cssWidth * fontScale) : imgInline.cssWidth;
pb.imageBlock.cssHeight = (imgInline.cssHeight > 0) ? (imgInline.cssHeight * fontScale) : imgInline.cssHeight;
pb.imageBlock.cssMaxWidth = (imgInline.cssMaxWidth > 0) ? (imgInline.cssMaxWidth * fontScale) : imgInline.cssMaxWidth;
if (imageResolver) {
QSizeF sz = imageResolver->imageSize(pb.imageBlock.imageUrl);
if (sz.isValid() && sz.width() > 0 && sz.height() > 0) {
@@ -506,14 +536,15 @@ PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
} else {
pb.kind = PreparedBlock::Kind::Paragraph;
pb.paragraph.align = b.align;
pb.paragraph.textIndent = b.textIndent;
pb.paragraph.textIndent = b.textIndent * fontScale;
pb.paragraph.lineHeight = b.lineHeight;
pb.paragraph.fontSize = b.fontSize;
pb.paragraph.fontSize = b.fontSize * fontScale;
pb.paragraph.marker = b.marker;
pb.paragraph.markerStyle = b.markerStyle;
pb.paragraph.markerStyle.fontSize *= fontScale;
if (b.textIndent > 0) {
pb.paragraph.kpItems.append(KnuthPlass::Item::box(b.textIndent, -1));
if (pb.paragraph.textIndent > 0) {
pb.paragraph.kpItems.append(KnuthPlass::Item::box(pb.paragraph.textIndent, -1));
}
for (const auto &item : b.inlines) {
@@ -523,7 +554,7 @@ PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
}
if (item.kind == InlineItem::Kind::Image) {
qreal w = 24.0, h = 24.0;
qreal w = 24.0 * fontScale, h = 24.0 * fontScale;
if (imageResolver) {
QSizeF sz = imageResolver->imageSize(item.imageUrl);
if (sz.isValid() && sz.width() > 0 && sz.height() > 0) {
@@ -533,13 +564,14 @@ PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
}
if (item.cssWidth > 0) {
qreal aspect = w > 0 ? (h / w) : 1.0;
w = item.cssWidth;
h = item.cssHeight > 0 ? item.cssHeight : (w * aspect);
w = item.cssWidth * fontScale;
h = item.cssHeight > 0 ? (item.cssHeight * fontScale) : (w * aspect);
}
PreparedWord tok;
tok.imageUrl = item.imageUrl;
tok.style = item.style;
tok.style.fontSize *= fontScale;
tok.width = w;
tok.ascent = h;
tok.descent = 0;
@@ -549,12 +581,19 @@ PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
continue;
}
QFont font = resolveFont(item.style, baseFontSize, QString());
TextStyle itemStyle = item.style;
if (!qFuzzyCompare(fontScale, 1.0)) {
itemStyle.fontSize *= fontScale;
itemStyle.letterSpacing *= fontScale;
itemStyle.baselineShift *= fontScale;
}
QFont font = resolveFont(itemStyle, baseFontSize, QString());
QFontMetricsF fm(font);
qreal spaceW = fm.horizontalAdvance(QLatin1Char(' '));
qreal hyphenW = fm.horizontalAdvance(QLatin1Char('-'));
QString rawText = transformText(item.text, item.style.transform);
QString rawText = transformText(item.text, itemStyle.transform);
const QStringList words = rawText.split(QLatin1Char(' '), Qt::SkipEmptyParts);
for (int wIdx = 0; wIdx < words.size(); ++wIdx) {
@@ -565,7 +604,7 @@ PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
for (int pIdx = 0; pIdx < parts.size(); ++pIdx) {
PreparedWord tok;
tok.text = parts[pIdx];
tok.style = item.style;
tok.style = itemStyle;
tok.font = font;
QString cacheKey = font.key() + QLatin1Char('|') + tok.text;
@@ -592,7 +631,7 @@ PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
} else {
PreparedWord tok;
tok.text = wStr;
tok.style = item.style;
tok.style = itemStyle;
tok.font = font;
QString cacheKey = font.key() + QLatin1Char('|') + tok.text;
@@ -632,12 +671,19 @@ PreparedChunk prepareBlocks(const QVector<BlockItem> &blocks,
return prepared;
}
PreparedChunk prepareChunk(const ContentChunk &chunk,
qreal baseFontSize,
IBookImageResolver *imageResolver)
{
return prepareBlocks(chunk.blocks, baseFontSize, imageResolver);
}
PreparedChunk prepareChunk(const QString &html,
qreal baseFontSize,
IBookImageResolver *imageResolver)
{
ParseParams pp;
pp.baseFontSize = baseFontSize;
pp.baseFontSize = 16.0;
pp.contentWidth = 600;
const auto blocks = HtmlBlockParser::parse(html, pp);
return prepareBlocks(blocks, baseFontSize, imageResolver);
@@ -112,6 +112,10 @@ struct PreparedChunk {
QVector<PreparedBlock> blocks;
};
PreparedChunk prepareChunk(const ContentChunk &chunk,
qreal baseFontSize,
IBookImageResolver *imageResolver = nullptr);
PreparedChunk prepareChunk(const QString &html,
qreal baseFontSize,
IBookImageResolver *imageResolver = nullptr);
+127 -2
View File
@@ -579,6 +579,15 @@ private:
} // namespace
QVector<BlockItem> parse(const QDomElement &root, const ParseParams &params)
{
if (root.isNull())
return {};
Builder builder(params);
return builder.build(root);
}
QVector<BlockItem> parse(const QString &html, const ParseParams &params)
{
if (html.trimmed().isEmpty())
@@ -606,8 +615,124 @@ QVector<BlockItem> parse(const QString &html, const ParseParams &params)
return {b};
}
Builder builder(params);
return builder.build(doc.documentElement());
return parse(doc.documentElement(), params);
}
QVector<ContentChunk> partitionBlocks(const QVector<BlockItem> &blocks,
const QString &sectionHref,
int targetChars)
{
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);
}
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;
}
QVector<ContentChunk> parseChunks(const QDomElement &root,
const QString &sectionHref,
int targetChars,
const ParseParams &params)
{
const auto blocks = parse(root, params);
return partitionBlocks(blocks, sectionHref, targetChars);
}
QVector<ContentChunk> parseChunks(const QString &html,
const QString &sectionHref,
int targetChars,
const ParseParams &params)
{
const auto blocks = parse(html, params);
return partitionBlocks(blocks, sectionHref, targetChars);
}
} // namespace HtmlBlockParser
+32 -3
View File
@@ -97,11 +97,40 @@ struct ParseParams {
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(); }
};
class QDomElement;
namespace HtmlBlockParser {
// Parses one standalone HTML chunk (an XHTML fragment whose elements carry
// their cascaded CSS in `style` attributes) into a flat block list.
QVector<BlockItem> parse(const QString &html, const ParseParams &params);
// Parses HTML or DOM element (whose elements carry cascaded CSS in `style` attributes)
// into a flat block list.
QVector<BlockItem> parse(const QString &html, const ParseParams &params = {});
QVector<BlockItem> parse(const QDomElement &root, const ParseParams &params = {});
// Partitions a block list into granular ContentChunks (~targetChars per chunk).
QVector<ContentChunk> partitionBlocks(const QVector<BlockItem> &blocks,
const QString &sectionHref = {},
int targetChars = 512);
// Parses and partitions into granular ContentChunks in a single pass.
QVector<ContentChunk> parseChunks(const QDomElement &root,
const QString &sectionHref = {},
int targetChars = 512,
const ParseParams &params = {});
QVector<ContentChunk> parseChunks(const QString &html,
const QString &sectionHref = {},
int targetChars = 512,
const ParseParams &params = {});
} // namespace HtmlBlockParser