hopefully true virtual list layout

This commit is contained in:
Agel committed 2026-10-28 23:44:54 +01:00
1 parent 905c61da52
commit 6c821c6a3c
10 files changed
+522 -37

No files matched your search

+87 -12
View File
@@ -38,13 +38,41 @@ QVariant ReadingModel::data(const QModelIndex &index, int role) const
return {};
if (role == ContentRole)
return m_chunks.at(index.row());
if (role == LayoutRole && index.row() < m_chunkLayouts.size())
if (role == LayoutRole && index.row() < m_chunks.size()) {
ensureChunkLayout(index.row());
return QVariant::fromValue(m_chunkLayouts.at(index.row()));
if (role == PixelHeightRole && index.row() < m_chunkLayouts.size())
}
if (role == PixelHeightRole && index.row() < m_chunks.size()) {
if (index.row() < m_chunkLayouts.size() && m_chunkLayouts.at(index.row()).totalHeight > 0 && !m_chunkLayouts.at(index.row()).lines.isEmpty())
return m_chunkLayouts.at(index.row()).totalHeight;
ensureChunkLayout(index.row());
return m_chunkLayouts.at(index.row()).totalHeight;
}
return {};
}
void ReadingModel::ensureChunkLayout(int row) const
{
if (row < 0 || row >= m_chunks.size())
return;
if (row < m_chunkLayouts.size() && m_chunkLayouts[row].totalHeight > 0 && !m_chunkLayouts[row].lines.isEmpty())
return;
if (row >= m_preparedChunks.size())
m_preparedChunks.resize(m_chunks.size());
if (row >= m_chunkLayouts.size())
m_chunkLayouts.resize(m_chunks.size());
LayoutParams params;
params.contentWidth = m_layoutContentWidth;
params.fontSize = m_layoutFontSize;
params.lineSpacing = m_layoutLineSpacing;
if (m_preparedChunks[row].blocks.isEmpty() && !m_chunks[row].isEmpty()) {
m_preparedChunks[row] = ChunkLayoutEngine::prepareChunk(m_chunks[row], params.fontSize, m_imageResolver);
}
m_chunkLayouts[row] = ChunkLayoutEngine::layoutPreparedChunk(m_preparedChunks[row], params);
}
QHash<int, QByteArray> ReadingModel::roleNames() const
{
return {
@@ -107,8 +135,11 @@ void ReadingModel::updateLayoutMetrics(int contentWidth, int fontSize, qreal lin
params.fontSize = m_layoutFontSize;
params.lineSpacing = m_layoutLineSpacing;
const int startIdx = std::max(0, targetChunk - 2);
const int endIdx = std::min(int(m_preparedChunks.size() - 1), targetChunk + 4);
const int startIdx = std::max(0, targetChunk - 5);
const int endIdx = std::min(int(m_preparedChunks.size() - 1), targetChunk + 25);
m_lastSyncStart = startIdx;
m_lastSyncEnd = endIdx;
if (m_chunkLayouts.size() != m_preparedChunks.size()) {
m_chunkLayouts.resize(m_preparedChunks.size());
@@ -141,9 +172,11 @@ void ReadingModel::runRemainingLayout()
params.contentWidth = m_layoutContentWidth;
params.fontSize = m_layoutFontSize;
params.lineSpacing = m_layoutLineSpacing;
const int syncStart = m_lastSyncStart;
const int syncEnd = m_lastSyncEnd;
QPointer<ReadingModel> self(this);
m_layoutFuture = QtConcurrent::run([self, generation, prepared, params]() {
m_layoutFuture = QtConcurrent::run([self, generation, prepared, params, syncStart, syncEnd]() {
QVector<ChunkLayout> newLayouts = QtConcurrent::blockingMapped(
prepared,
[params](const ChunkLayoutEngine::PreparedChunk &prep) {
@@ -153,12 +186,20 @@ void ReadingModel::runRemainingLayout()
if (!self || self->m_layoutGeneration != generation)
return;
QMetaObject::invokeMethod(self.data(), [self, generation, newLayouts = std::move(newLayouts)]() mutable {
QMetaObject::invokeMethod(self.data(), [self, generation, newLayouts = std::move(newLayouts), syncStart, syncEnd]() mutable {
if (!self || generation != self->m_layoutGeneration)
return;
self->m_chunkLayouts = std::move(newLayouts);
if (!self->m_chunkLayouts.isEmpty()) {
emit self->dataChanged(self->index(0, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole});
if (syncStart > 0) {
emit self->dataChanged(self->index(0, 0), self->index(syncStart - 1, 0), {LayoutRole, PixelHeightRole});
}
if (syncEnd >= 0 && syncEnd + 1 < self->m_chunkLayouts.size()) {
emit self->dataChanged(self->index(syncEnd + 1, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole});
}
if (syncStart < 0 && syncEnd < 0) {
emit self->dataChanged(self->index(0, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole});
}
}
}, Qt::QueuedConnection);
});
@@ -235,8 +276,40 @@ void ReadingModel::startLayoutMeasurement(int restoreChunk, qreal restoreIntraOf
params.lineSpacing = m_layoutLineSpacing;
auto *resolver = m_imageResolver;
// Phase 1: Immediately prepare and layout the visible window synchronously (<1ms)
const int startIdx = std::max(0, restoreChunk - 5);
const int endIdx = std::min(int(chunks.size() - 1), restoreChunk + 25);
m_preparedChunks.resize(chunks.size());
m_chunkLayouts.resize(chunks.size());
for (int i = startIdx; i <= endIdx; ++i) {
m_preparedChunks[i] = ChunkLayoutEngine::prepareChunk(chunks[i], params.fontSize, resolver);
m_chunkLayouts[i] = ChunkLayoutEngine::layoutPreparedChunk(m_preparedChunks[i], params);
}
for (int i = 0; i < chunks.size(); ++i) {
if (i < startIdx || i > endIdx) {
m_chunkLayouts[i].totalHeight = 60.0;
}
}
m_lastSyncStart = startIdx;
m_lastSyncEnd = endIdx;
if (startIdx <= endIdx) {
emit dataChanged(index(startIdx, 0), index(endIdx, 0), {LayoutRole, PixelHeightRole});
}
emit restoreReady(restoreChunk, restoreIntraOffset);
if (startIdx == 0 && endIdx == chunks.size() - 1) {
m_measuring = false;
emit measuringChanged();
return;
}
// Phase 2: Compute remaining chunks in the background
QPointer<ReadingModel> self(this);
m_layoutFuture = QtConcurrent::run([self, generation, chunks, params, resolver, restoreChunk, restoreIntraOffset]() {
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);
});
@@ -251,17 +324,19 @@ void ReadingModel::startLayoutMeasurement(int restoreChunk, qreal restoreIntraOf
if (!self || self->m_layoutGeneration != generation)
return;
QMetaObject::invokeMethod(self.data(), [self, generation, prepared = std::move(prepared), layouts = std::move(layouts), restoreChunk, restoreIntraOffset]() mutable {
QMetaObject::invokeMethod(self.data(), [self, generation, prepared = std::move(prepared), layouts = std::move(layouts), startIdx, endIdx]() mutable {
if (!self || generation != self->m_layoutGeneration)
return;
self->m_preparedChunks = std::move(prepared);
self->m_chunkLayouts = std::move(layouts);
self->m_measuring = false;
emit self->measuringChanged();
if (!self->m_chunkLayouts.isEmpty()) {
emit self->dataChanged(self->index(0, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole});
if (startIdx > 0) {
emit self->dataChanged(self->index(0, 0), self->index(startIdx - 1, 0), {LayoutRole, PixelHeightRole});
}
if (endIdx + 1 < self->m_chunkLayouts.size()) {
emit self->dataChanged(self->index(endIdx + 1, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole});
}
emit self->restoreReady(restoreChunk, restoreIntraOffset);
}, Qt::QueuedConnection);
});
}
+5 -2
View File
@@ -98,6 +98,7 @@ private:
void startLayoutMeasurement(int restoreChunk = 0, qreal restoreIntraOffset = 0.0);
void runRemainingLayout();
void saveCurrentPosition(int chunkIndex, qreal intraOffset = 0.0);
void ensureChunkLayout(int row) const;
FormatReader *m_reader = nullptr;
IBookImageResolver *m_imageResolver = nullptr;
@@ -106,8 +107,10 @@ private:
int m_currentPage = 0;
int m_totalPages = 0;
QStringList m_chunks;
QVector<ChunkLayoutEngine::PreparedChunk> m_preparedChunks;
QVector<ChunkLayout> m_chunkLayouts;
mutable QVector<ChunkLayoutEngine::PreparedChunk> m_preparedChunks;
mutable QVector<ChunkLayout> m_chunkLayouts;
int m_lastSyncStart = -1;
int m_lastSyncEnd = -1;
int m_layoutContentWidth = 600;
int m_layoutFontSize = 16;
+148 -3
View File
@@ -220,10 +220,155 @@ void EpubReader::appendSpineChunks(const QString &xhtml,
}
QDomElement body = bodies.at(0).toElement();
QString currentChunk;
static constexpr int kChunkTargetSize = 4096;
for (QDomNode node = body.firstChild(); !node.isNull(); node = node.nextSibling()) {
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);
+27 -3
View File
@@ -4,7 +4,7 @@
#include "BookImageResolver.h"
BookImageResolver *KnuthPlassItem::s_imageResolver = nullptr;
IBookImageResolver *KnuthPlassItem::s_imageResolver = nullptr;
KnuthPlassItem::KnuthPlassItem(QQuickItem *parent)
: QQuickPaintedItem(parent)
@@ -13,7 +13,7 @@ KnuthPlassItem::KnuthPlassItem(QQuickItem *parent)
setRenderTarget(QQuickPaintedItem::Image);
}
void KnuthPlassItem::setImageResolver(BookImageResolver *resolver)
void KnuthPlassItem::setImageResolver(IBookImageResolver *resolver)
{
s_imageResolver = resolver;
}
@@ -124,11 +124,19 @@ void KnuthPlassItem::paint(QPainter *painter)
const qreal offX = m_horizontalMargin;
QRectF clip = painter->clipBoundingRect();
if (clip.isEmpty()) {
clip = QRectF(0, 0, width(), height());
}
// 1. Draw block decorations (backgrounds & borders)
for (const auto &dec : m_layout.decorations) {
QRectF r = dec.rect;
r.translate(offX, 0);
if (r.bottom() < clip.top() || r.top() > clip.bottom())
continue;
if (m_useBookColours) {
if (dec.background.isValid() && dec.background.alpha() > 0) {
painter->fillRect(r, dec.background);
@@ -160,6 +168,10 @@ void KnuthPlassItem::paint(QPainter *painter)
for (const auto &rule : m_layout.rules) {
QRectF r = rule.rect;
r.translate(offX, 0);
if (r.bottom() < clip.top() || r.top() > clip.bottom())
continue;
QColor rc = (m_useBookColours && rule.color.isValid()) ? rule.color : m_dimColor;
painter->fillRect(r, rc);
}
@@ -172,7 +184,16 @@ void KnuthPlassItem::paint(QPainter *painter)
const QColor baseSurface = m_surfaceColor.isValid() ? m_surfaceColor : QColor(25, 29, 53);
for (const auto &line : m_layout.lines) {
auto it = std::lower_bound(m_layout.lines.begin(), m_layout.lines.end(), clip.top(),
[](const PositionedLine &line, qreal clipTop) {
return line.rect.bottom() < clipTop;
});
for (; it != m_layout.lines.end(); ++it) {
const auto &line = *it;
if (line.rect.top() > clip.bottom())
break;
for (const auto &run : line.runs) {
QRectF r = run.rect;
r.translate(offX, 0);
@@ -236,6 +257,9 @@ void KnuthPlassItem::paint(QPainter *painter)
QRectF r = imgItem.targetRect;
r.translate(offX, 0);
if (r.bottom() < clip.top() || r.top() > clip.bottom())
continue;
QImage img;
if (s_imageResolver) {
img = s_imageResolver->resolveImage(imgItem.url);
+3 -3
View File
@@ -7,7 +7,7 @@
#include "layout/ChunkLayoutEngine.h"
class BookImageResolver;
class IBookImageResolver;
class KnuthPlassItem : public QQuickPaintedItem {
Q_OBJECT
@@ -48,7 +48,7 @@ public:
void paint(QPainter *painter) override;
static void setImageResolver(BookImageResolver *resolver);
static void setImageResolver(IBookImageResolver *resolver);
protected:
void geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry) override;
@@ -70,6 +70,6 @@ private:
bool m_useBookColours = false;
qreal m_horizontalMargin = 0;
static BookImageResolver *s_imageResolver;
static IBookImageResolver *s_imageResolver;
};