hopefully true virtual list layout
This commit is contained in:
10 files changed
+516
-31
No files matched your search
@@ -159,6 +159,7 @@ public:
|
|||||||
|
|
||||||
### 1. Text Mode (`ScrollPageView.qml`)
|
### 1. Text Mode (`ScrollPageView.qml`)
|
||||||
- `ReadingModel` manages a list of HTML chunks.
|
- `ReadingModel` manages a list of HTML chunks.
|
||||||
|
- `EpubReader` unwraps unstyled structural containers (`<div>`, `<section>`, `<article>`, etc.) that contain block-level children and partitions documents into fine-grained block/paragraph chunks (~512 chars max), propagating inherited CSS declarations. Paragraph `<div>`s containing inline markup (`<em>`, `<span>`, `<a>`, etc.) are preserved intact as atomic blocks without fragmenting text or punctuation.
|
||||||
- When viewport geometry or font preferences change, `ReadingModel::updateLayoutMetrics()` runs `ChunkLayoutEngine` off-thread:
|
- When viewport geometry or font preferences change, `ReadingModel::updateLayoutMetrics()` runs `ChunkLayoutEngine` off-thread:
|
||||||
- `HtmlBlockParser` extracts structured blocks (`Paragraph`, `ImageBlock`, `Rule`, `Container`).
|
- `HtmlBlockParser` extracts structured blocks (`Paragraph`, `ImageBlock`, `Rule`, `Container`).
|
||||||
- Block-level `background` sets `BoxStyle::background` (emitted as `PositionedDecoration`), while inline spans apply to `TextStyle::background` (individual word runs).
|
- Block-level `background` sets `BoxStyle::background` (emitted as `PositionedDecoration`), while inline spans apply to `TextStyle::background` (individual word runs).
|
||||||
@@ -167,7 +168,10 @@ public:
|
|||||||
- `KnuthPlass` computes optimal justified/aligned line breaks.
|
- `KnuthPlass` computes optimal justified/aligned line breaks.
|
||||||
- `BookImageResolver` resolves embedded image dimensions and URLs.
|
- `BookImageResolver` resolves embedded image dimensions and URLs.
|
||||||
- Off-thread calculation stores `ChunkLayout` and pixel heights.
|
- Off-thread calculation stores `ChunkLayout` and pixel heights.
|
||||||
- Rendered in a virtualized `ListView` (`cacheBuffer: 600`, high flick velocity) using `KnuthPlassItem`.
|
- **Two-Phase Visible-First Layout**: On book open and font changes, `ReadingModel::startLayoutMeasurement()` computes layout for the visible window around the anchor chunk synchronously (<1ms) and emits `restoreReady(chunkIndex, intraOffset)` immediately so the visible screen renders on the first frame, while the background thread computes remaining off-screen chunks and updates only non-visible model ranges. On-demand layout guards ensure any chunk scrolled to before background completion is measured instantly.
|
||||||
|
- Rendered in a strictly virtualized `ListView` (`cacheBuffer: 0`, `reuseItems: true`, high flick velocity) using `KnuthPlassItem` as the direct delegate, preserving smooth scrolling without allocating off-screen delegate textures.
|
||||||
|
- **Debug Chunk Index**: In debug builds (`isDebugBuild`), displays the chunk index at the top-left of each list item (`x: 4, y: 2`), ignoring `horizontalMargin`.
|
||||||
|
- **Clip-Rect Culling in `KnuthPlassItem`**: `paint()` inspects `painter->clipBoundingRect()`, skips decorations/rules outside the clip, uses $O(\log N)$ binary search (`std::lower_bound`) to draw only lines intersecting the clip, and skips off-screen image decoding/resolution completely.
|
||||||
- **Publisher Colours vs Theme**: Controlled by per-book `useBookColours` setting (default `false`).
|
- **Publisher Colours vs Theme**: Controlled by per-book `useBookColours` setting (default `false`).
|
||||||
- When off: paints with theme palette (`readingText`, `dimText`, `buttonAccent`), omitting publisher backgrounds and border boxes (semantic blockquote bars with only `borderLeft` and no explicit border colour are drawn in `dimText`).
|
- When off: paints with theme palette (`readingText`, `dimText`, `buttonAccent`), omitting publisher backgrounds and border boxes (semantic blockquote bars with only `borderLeft` and no explicit border colour are drawn in `dimText`).
|
||||||
- When on: paints publisher backgrounds and border colours, using WCAG contrast calculation (`contrastRatio < 3.0`) to automatically select high-contrast black or white text when publisher or theme text colours would be unreadable on the effective background.
|
- When on: paints publisher backgrounds and border colours, using WCAG contrast calculation (`contrastRatio < 3.0`) to automatically select high-contrast black or white text when publisher or theme text colours would be unreadable on the effective background.
|
||||||
|
|||||||
@@ -38,13 +38,41 @@ QVariant ReadingModel::data(const QModelIndex &index, int role) const
|
|||||||
return {};
|
return {};
|
||||||
if (role == ContentRole)
|
if (role == ContentRole)
|
||||||
return m_chunks.at(index.row());
|
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()));
|
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;
|
return m_chunkLayouts.at(index.row()).totalHeight;
|
||||||
|
ensureChunkLayout(index.row());
|
||||||
|
return m_chunkLayouts.at(index.row()).totalHeight;
|
||||||
|
}
|
||||||
return {};
|
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
|
QHash<int, QByteArray> ReadingModel::roleNames() const
|
||||||
{
|
{
|
||||||
return {
|
return {
|
||||||
@@ -107,8 +135,11 @@ void ReadingModel::updateLayoutMetrics(int contentWidth, int fontSize, qreal lin
|
|||||||
params.fontSize = m_layoutFontSize;
|
params.fontSize = m_layoutFontSize;
|
||||||
params.lineSpacing = m_layoutLineSpacing;
|
params.lineSpacing = m_layoutLineSpacing;
|
||||||
|
|
||||||
const int startIdx = std::max(0, targetChunk - 2);
|
const int startIdx = std::max(0, targetChunk - 5);
|
||||||
const int endIdx = std::min(int(m_preparedChunks.size() - 1), targetChunk + 4);
|
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()) {
|
if (m_chunkLayouts.size() != m_preparedChunks.size()) {
|
||||||
m_chunkLayouts.resize(m_preparedChunks.size());
|
m_chunkLayouts.resize(m_preparedChunks.size());
|
||||||
@@ -141,9 +172,11 @@ void ReadingModel::runRemainingLayout()
|
|||||||
params.contentWidth = m_layoutContentWidth;
|
params.contentWidth = m_layoutContentWidth;
|
||||||
params.fontSize = m_layoutFontSize;
|
params.fontSize = m_layoutFontSize;
|
||||||
params.lineSpacing = m_layoutLineSpacing;
|
params.lineSpacing = m_layoutLineSpacing;
|
||||||
|
const int syncStart = m_lastSyncStart;
|
||||||
|
const int syncEnd = m_lastSyncEnd;
|
||||||
|
|
||||||
QPointer<ReadingModel> self(this);
|
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(
|
QVector<ChunkLayout> newLayouts = QtConcurrent::blockingMapped(
|
||||||
prepared,
|
prepared,
|
||||||
[params](const ChunkLayoutEngine::PreparedChunk &prep) {
|
[params](const ChunkLayoutEngine::PreparedChunk &prep) {
|
||||||
@@ -153,13 +186,21 @@ void ReadingModel::runRemainingLayout()
|
|||||||
if (!self || self->m_layoutGeneration != generation)
|
if (!self || self->m_layoutGeneration != generation)
|
||||||
return;
|
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)
|
if (!self || generation != self->m_layoutGeneration)
|
||||||
return;
|
return;
|
||||||
self->m_chunkLayouts = std::move(newLayouts);
|
self->m_chunkLayouts = std::move(newLayouts);
|
||||||
if (!self->m_chunkLayouts.isEmpty()) {
|
if (!self->m_chunkLayouts.isEmpty()) {
|
||||||
|
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});
|
emit self->dataChanged(self->index(0, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}, Qt::QueuedConnection);
|
}, Qt::QueuedConnection);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -235,8 +276,40 @@ void ReadingModel::startLayoutMeasurement(int restoreChunk, qreal restoreIntraOf
|
|||||||
params.lineSpacing = m_layoutLineSpacing;
|
params.lineSpacing = m_layoutLineSpacing;
|
||||||
auto *resolver = m_imageResolver;
|
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);
|
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) {
|
auto prepared = QtConcurrent::blockingMapped(chunks, [params, resolver](const QString &chunkHtml) {
|
||||||
return ChunkLayoutEngine::prepareChunk(chunkHtml, params.fontSize, resolver);
|
return ChunkLayoutEngine::prepareChunk(chunkHtml, params.fontSize, resolver);
|
||||||
});
|
});
|
||||||
@@ -251,17 +324,19 @@ void ReadingModel::startLayoutMeasurement(int restoreChunk, qreal restoreIntraOf
|
|||||||
if (!self || self->m_layoutGeneration != generation)
|
if (!self || self->m_layoutGeneration != generation)
|
||||||
return;
|
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)
|
if (!self || generation != self->m_layoutGeneration)
|
||||||
return;
|
return;
|
||||||
self->m_preparedChunks = std::move(prepared);
|
self->m_preparedChunks = std::move(prepared);
|
||||||
self->m_chunkLayouts = std::move(layouts);
|
self->m_chunkLayouts = std::move(layouts);
|
||||||
self->m_measuring = false;
|
self->m_measuring = false;
|
||||||
emit self->measuringChanged();
|
emit self->measuringChanged();
|
||||||
if (!self->m_chunkLayouts.isEmpty()) {
|
if (startIdx > 0) {
|
||||||
emit self->dataChanged(self->index(0, 0), self->index(self->m_chunkLayouts.size() - 1, 0), {LayoutRole, PixelHeightRole});
|
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);
|
}, Qt::QueuedConnection);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -98,6 +98,7 @@ private:
|
|||||||
void startLayoutMeasurement(int restoreChunk = 0, qreal restoreIntraOffset = 0.0);
|
void startLayoutMeasurement(int restoreChunk = 0, qreal restoreIntraOffset = 0.0);
|
||||||
void runRemainingLayout();
|
void runRemainingLayout();
|
||||||
void saveCurrentPosition(int chunkIndex, qreal intraOffset = 0.0);
|
void saveCurrentPosition(int chunkIndex, qreal intraOffset = 0.0);
|
||||||
|
void ensureChunkLayout(int row) const;
|
||||||
|
|
||||||
FormatReader *m_reader = nullptr;
|
FormatReader *m_reader = nullptr;
|
||||||
IBookImageResolver *m_imageResolver = nullptr;
|
IBookImageResolver *m_imageResolver = nullptr;
|
||||||
@@ -106,8 +107,10 @@ private:
|
|||||||
int m_currentPage = 0;
|
int m_currentPage = 0;
|
||||||
int m_totalPages = 0;
|
int m_totalPages = 0;
|
||||||
QStringList m_chunks;
|
QStringList m_chunks;
|
||||||
QVector<ChunkLayoutEngine::PreparedChunk> m_preparedChunks;
|
mutable QVector<ChunkLayoutEngine::PreparedChunk> m_preparedChunks;
|
||||||
QVector<ChunkLayout> m_chunkLayouts;
|
mutable QVector<ChunkLayout> m_chunkLayouts;
|
||||||
|
int m_lastSyncStart = -1;
|
||||||
|
int m_lastSyncEnd = -1;
|
||||||
|
|
||||||
int m_layoutContentWidth = 600;
|
int m_layoutContentWidth = 600;
|
||||||
int m_layoutFontSize = 16;
|
int m_layoutFontSize = 16;
|
||||||
|
|||||||
@@ -220,10 +220,155 @@ void EpubReader::appendSpineChunks(const QString &xhtml,
|
|||||||
}
|
}
|
||||||
|
|
||||||
QDomElement body = bodies.at(0).toElement();
|
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;
|
QString serialized;
|
||||||
QTextStream ts(&serialized);
|
QTextStream ts(&serialized);
|
||||||
node.save(ts, 0);
|
node.save(ts, 0);
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
#include "BookImageResolver.h"
|
#include "BookImageResolver.h"
|
||||||
|
|
||||||
BookImageResolver *KnuthPlassItem::s_imageResolver = nullptr;
|
IBookImageResolver *KnuthPlassItem::s_imageResolver = nullptr;
|
||||||
|
|
||||||
KnuthPlassItem::KnuthPlassItem(QQuickItem *parent)
|
KnuthPlassItem::KnuthPlassItem(QQuickItem *parent)
|
||||||
: QQuickPaintedItem(parent)
|
: QQuickPaintedItem(parent)
|
||||||
@@ -13,7 +13,7 @@ KnuthPlassItem::KnuthPlassItem(QQuickItem *parent)
|
|||||||
setRenderTarget(QQuickPaintedItem::Image);
|
setRenderTarget(QQuickPaintedItem::Image);
|
||||||
}
|
}
|
||||||
|
|
||||||
void KnuthPlassItem::setImageResolver(BookImageResolver *resolver)
|
void KnuthPlassItem::setImageResolver(IBookImageResolver *resolver)
|
||||||
{
|
{
|
||||||
s_imageResolver = resolver;
|
s_imageResolver = resolver;
|
||||||
}
|
}
|
||||||
@@ -124,11 +124,19 @@ void KnuthPlassItem::paint(QPainter *painter)
|
|||||||
|
|
||||||
const qreal offX = m_horizontalMargin;
|
const qreal offX = m_horizontalMargin;
|
||||||
|
|
||||||
|
QRectF clip = painter->clipBoundingRect();
|
||||||
|
if (clip.isEmpty()) {
|
||||||
|
clip = QRectF(0, 0, width(), height());
|
||||||
|
}
|
||||||
|
|
||||||
// 1. Draw block decorations (backgrounds & borders)
|
// 1. Draw block decorations (backgrounds & borders)
|
||||||
for (const auto &dec : m_layout.decorations) {
|
for (const auto &dec : m_layout.decorations) {
|
||||||
QRectF r = dec.rect;
|
QRectF r = dec.rect;
|
||||||
r.translate(offX, 0);
|
r.translate(offX, 0);
|
||||||
|
|
||||||
|
if (r.bottom() < clip.top() || r.top() > clip.bottom())
|
||||||
|
continue;
|
||||||
|
|
||||||
if (m_useBookColours) {
|
if (m_useBookColours) {
|
||||||
if (dec.background.isValid() && dec.background.alpha() > 0) {
|
if (dec.background.isValid() && dec.background.alpha() > 0) {
|
||||||
painter->fillRect(r, dec.background);
|
painter->fillRect(r, dec.background);
|
||||||
@@ -160,6 +168,10 @@ void KnuthPlassItem::paint(QPainter *painter)
|
|||||||
for (const auto &rule : m_layout.rules) {
|
for (const auto &rule : m_layout.rules) {
|
||||||
QRectF r = rule.rect;
|
QRectF r = rule.rect;
|
||||||
r.translate(offX, 0);
|
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;
|
QColor rc = (m_useBookColours && rule.color.isValid()) ? rule.color : m_dimColor;
|
||||||
painter->fillRect(r, rc);
|
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);
|
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) {
|
for (const auto &run : line.runs) {
|
||||||
QRectF r = run.rect;
|
QRectF r = run.rect;
|
||||||
r.translate(offX, 0);
|
r.translate(offX, 0);
|
||||||
@@ -236,6 +257,9 @@ void KnuthPlassItem::paint(QPainter *painter)
|
|||||||
QRectF r = imgItem.targetRect;
|
QRectF r = imgItem.targetRect;
|
||||||
r.translate(offX, 0);
|
r.translate(offX, 0);
|
||||||
|
|
||||||
|
if (r.bottom() < clip.top() || r.top() > clip.bottom())
|
||||||
|
continue;
|
||||||
|
|
||||||
QImage img;
|
QImage img;
|
||||||
if (s_imageResolver) {
|
if (s_imageResolver) {
|
||||||
img = s_imageResolver->resolveImage(imgItem.url);
|
img = s_imageResolver->resolveImage(imgItem.url);
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
#include "layout/ChunkLayoutEngine.h"
|
#include "layout/ChunkLayoutEngine.h"
|
||||||
|
|
||||||
class BookImageResolver;
|
class IBookImageResolver;
|
||||||
|
|
||||||
class KnuthPlassItem : public QQuickPaintedItem {
|
class KnuthPlassItem : public QQuickPaintedItem {
|
||||||
Q_OBJECT
|
Q_OBJECT
|
||||||
@@ -48,7 +48,7 @@ public:
|
|||||||
|
|
||||||
void paint(QPainter *painter) override;
|
void paint(QPainter *painter) override;
|
||||||
|
|
||||||
static void setImageResolver(BookImageResolver *resolver);
|
static void setImageResolver(IBookImageResolver *resolver);
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
void geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry) override;
|
void geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry) override;
|
||||||
@@ -70,6 +70,6 @@ private:
|
|||||||
bool m_useBookColours = false;
|
bool m_useBookColours = false;
|
||||||
qreal m_horizontalMargin = 0;
|
qreal m_horizontalMargin = 0;
|
||||||
|
|
||||||
static BookImageResolver *s_imageResolver;
|
static IBookImageResolver *s_imageResolver;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -107,25 +107,37 @@ Rectangle {
|
|||||||
anchors.topMargin: readingPreferences.verticalMargin
|
anchors.topMargin: readingPreferences.verticalMargin
|
||||||
anchors.bottomMargin: readingPreferences.verticalMargin
|
anchors.bottomMargin: readingPreferences.verticalMargin
|
||||||
model: contentReady ? readingModel : null
|
model: contentReady ? readingModel : null
|
||||||
cacheBuffer: 600
|
cacheBuffer: 0
|
||||||
|
reuseItems: true
|
||||||
clip: true
|
clip: true
|
||||||
maximumFlickVelocity: 99999
|
maximumFlickVelocity: 99999
|
||||||
|
|
||||||
delegate: Item {
|
delegate: KnuthPlassItem {
|
||||||
id: chunkDelegate
|
id: chunkDelegate
|
||||||
width: chunkListView.width
|
width: chunkListView.width
|
||||||
height: model.pixelHeight > 0 ? model.pixelHeight : 30
|
height: (model && model.pixelHeight > 0) ? model.pixelHeight : 30
|
||||||
|
layout: model ? model.layout : null
|
||||||
KnuthPlassItem {
|
|
||||||
width: parent.width
|
|
||||||
height: parent.height
|
|
||||||
layout: model.layout
|
|
||||||
textColor: ThemeManager.currentTheme.readingText
|
textColor: ThemeManager.currentTheme.readingText
|
||||||
linkColor: ThemeManager.currentTheme.buttonAccent
|
linkColor: ThemeManager.currentTheme.buttonAccent
|
||||||
dimColor: ThemeManager.currentTheme.dimText
|
dimColor: ThemeManager.currentTheme.dimText
|
||||||
surfaceColor: ThemeManager.currentTheme.surface
|
surfaceColor: ThemeManager.currentTheme.surface
|
||||||
useBookColours: readingModel.useBookColours
|
useBookColours: readingModel.useBookColours
|
||||||
horizontalMargin: readingPreferences.horizontalMargin
|
horizontalMargin: readingPreferences.horizontalMargin
|
||||||
|
|
||||||
|
Loader {
|
||||||
|
active: isDebugBuild
|
||||||
|
visible: isDebugBuild
|
||||||
|
sourceComponent: Text {
|
||||||
|
text: index !== undefined ? index.toString() : ""
|
||||||
|
font.pixelSize: 10
|
||||||
|
font.family: "monospace"
|
||||||
|
font.bold: true
|
||||||
|
color: ThemeManager.currentTheme.buttonAccent
|
||||||
|
opacity: 0.85
|
||||||
|
x: 4
|
||||||
|
y: 2
|
||||||
|
z: 10
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -51,6 +51,29 @@ public:
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
class ManyChunksTextReader : public FormatReader {
|
||||||
|
public:
|
||||||
|
ReadingMode mode() const override { return ReadingMode::Text; }
|
||||||
|
bool open(const QString &) override { return true; }
|
||||||
|
QString lastError() const override { return {}; }
|
||||||
|
QString title() const override { return QStringLiteral("Many Chunks"); }
|
||||||
|
QString author() const override { return QStringLiteral("Author"); }
|
||||||
|
QString filePath() const override { return QStringLiteral("/fake/many.epub"); }
|
||||||
|
QString coverImageUrl() const override { return {}; }
|
||||||
|
QByteArray contentHash() const override { return QByteArray("manychunks"); }
|
||||||
|
bool loadMetadata(const QString &) override { return true; }
|
||||||
|
|
||||||
|
QStringList chunks() const override
|
||||||
|
{
|
||||||
|
QStringList list;
|
||||||
|
list.reserve(60);
|
||||||
|
for (int i = 0; i < 60; ++i) {
|
||||||
|
list.append(QStringLiteral("<p>Paragraph chunk number %1 with some text content.</p>").arg(i));
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
class ReadingModelTest : public QObject {
|
class ReadingModelTest : public QObject {
|
||||||
Q_OBJECT
|
Q_OBJECT
|
||||||
|
|
||||||
@@ -243,6 +266,29 @@ private slots:
|
|||||||
model.setReader(nullptr);
|
model.setReader(nullptr);
|
||||||
QCOMPARE(model.useBookColours(), false);
|
QCOMPARE(model.useBookColours(), false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void visibleFirstLayoutAndOnDemandLayout()
|
||||||
|
{
|
||||||
|
Ctx ctx;
|
||||||
|
ReadingModel model(*ctx.store);
|
||||||
|
ManyChunksTextReader reader;
|
||||||
|
QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady);
|
||||||
|
|
||||||
|
model.setReader(&reader);
|
||||||
|
|
||||||
|
// restoreReady must be emitted immediately from Phase 1 (<1ms)
|
||||||
|
QCOMPARE(restoreSpy.count(), 1);
|
||||||
|
QCOMPARE(restoreSpy.first().at(0).toInt(), 0);
|
||||||
|
|
||||||
|
// Row 0..25 are laid out immediately
|
||||||
|
QVERIFY(model.data(model.index(0, 0), ReadingModel::PixelHeightRole).toReal() > 0);
|
||||||
|
QVERIFY(!model.data(model.index(0, 0), ReadingModel::LayoutRole).value<ChunkLayout>().lines.isEmpty());
|
||||||
|
|
||||||
|
// Far-away row (e.g. 55) layout should be computed on-demand if queried
|
||||||
|
QVERIFY(model.data(model.index(55, 0), ReadingModel::PixelHeightRole).toReal() > 0);
|
||||||
|
const auto layout55 = model.data(model.index(55, 0), ReadingModel::LayoutRole).value<ChunkLayout>();
|
||||||
|
QVERIFY(!layout55.lines.isEmpty());
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
QTEST_MAIN(ReadingModelTest)
|
QTEST_MAIN(ReadingModelTest)
|
||||||
|
|||||||
@@ -189,6 +189,124 @@ private slots:
|
|||||||
QVERIFY(!reader.chunks().isEmpty());
|
QVERIFY(!reader.chunks().isEmpty());
|
||||||
QVERIFY(reader.chunks().first().contains(QStringLiteral("Hello EPUB 3")));
|
QVERIFY(reader.chunks().first().contains(QStringLiteral("Hello EPUB 3")));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void chapterWrapperUnwrappedIntoGranularChunks()
|
||||||
|
{
|
||||||
|
auto src = std::make_unique<InMemoryByteSource>();
|
||||||
|
|
||||||
|
src->m_entries.insert(QStringLiteral("META-INF/container.xml"),
|
||||||
|
"<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n"
|
||||||
|
" <rootfiles>\n"
|
||||||
|
" <rootfile full-path=\"EPUB/package.opf\" media-type=\"application/oebps-package+xml\"/>\n"
|
||||||
|
" </rootfiles>\n"
|
||||||
|
"</container>");
|
||||||
|
|
||||||
|
src->m_entries.insert(QStringLiteral("EPUB/package.opf"),
|
||||||
|
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\">\n"
|
||||||
|
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"
|
||||||
|
" <dc:title>Unwrap Test</dc:title>\n"
|
||||||
|
" </metadata>\n"
|
||||||
|
" <manifest>\n"
|
||||||
|
" <item id=\"c1\" href=\"ch1.xhtml\" media-type=\"application/xhtml+xml\"/>\n"
|
||||||
|
" </manifest>\n"
|
||||||
|
" <spine>\n"
|
||||||
|
" <itemref idref=\"c1\"/>\n"
|
||||||
|
" </spine>\n"
|
||||||
|
"</package>");
|
||||||
|
|
||||||
|
// Generates several long paragraphs inside a single wrapper div
|
||||||
|
QString xhtml = QStringLiteral(
|
||||||
|
"<html xmlns=\"http://www.w3.org/1999/xhtml\"><body>\n"
|
||||||
|
"<div class=\"calibre1\" style=\"text-align: justify;\">\n"
|
||||||
|
);
|
||||||
|
for (int i = 0; i < 10; ++i) {
|
||||||
|
xhtml += QStringLiteral("<p>This is paragraph %1 with sufficient text to exceed the target chunk size when combined together with other paragraphs in the chapter.</p>\n").arg(i);
|
||||||
|
}
|
||||||
|
xhtml += QStringLiteral("</div></body></html>");
|
||||||
|
|
||||||
|
src->m_entries.insert(QStringLiteral("EPUB/ch1.xhtml"), xhtml.toUtf8());
|
||||||
|
|
||||||
|
auto sharedEntries = std::make_shared<QHash<QString, QByteArray>>(src->m_entries);
|
||||||
|
auto factory = [sharedEntries]() {
|
||||||
|
auto s = std::make_unique<InMemoryByteSource>();
|
||||||
|
s->m_entries = *sharedEntries;
|
||||||
|
return s;
|
||||||
|
};
|
||||||
|
|
||||||
|
EpubReader reader(factory, QStringLiteral("epub"));
|
||||||
|
QVERIFY(reader.open(QStringLiteral("/virtual/unwrap.epub")));
|
||||||
|
|
||||||
|
// Must be split into multiple granular chunks instead of one single monolithic chunk
|
||||||
|
QVERIFY(reader.chunks().size() >= 3);
|
||||||
|
// Children must inherit text-align: justify
|
||||||
|
for (const QString &c : reader.chunks()) {
|
||||||
|
QVERIFY(c.contains(QStringLiteral("text-align:justify")) || c.contains(QStringLiteral("text-align: justify")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void divParagraphWithInlineElementsNotBroken()
|
||||||
|
{
|
||||||
|
auto src = std::make_unique<InMemoryByteSource>();
|
||||||
|
|
||||||
|
src->m_entries.insert(QStringLiteral("META-INF/container.xml"),
|
||||||
|
"<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n"
|
||||||
|
" <rootfiles>\n"
|
||||||
|
" <rootfile full-path=\"EPUB/package.opf\" media-type=\"application/oebps-package+xml\"/>\n"
|
||||||
|
" </rootfiles>\n"
|
||||||
|
"</container>");
|
||||||
|
|
||||||
|
src->m_entries.insert(QStringLiteral("EPUB/package.opf"),
|
||||||
|
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\">\n"
|
||||||
|
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"
|
||||||
|
" <dc:title>Inline Div Test</dc:title>\n"
|
||||||
|
" </metadata>\n"
|
||||||
|
" <manifest>\n"
|
||||||
|
" <item id=\"c1\" href=\"ch1.xhtml\" media-type=\"application/xhtml+xml\"/>\n"
|
||||||
|
" </manifest>\n"
|
||||||
|
" <spine>\n"
|
||||||
|
" <itemref idref=\"c1\"/>\n"
|
||||||
|
" </spine>\n"
|
||||||
|
"</package>");
|
||||||
|
|
||||||
|
QString xhtml = QStringLiteral(
|
||||||
|
"<html xmlns=\"http://www.w3.org/1999/xhtml\"><body>\n"
|
||||||
|
"<div class=\"calibre1\">\n"
|
||||||
|
" <div class=\"p\">«<em>Одноглазый</em>».</div>\n"
|
||||||
|
" <div class=\"p\"><em>«Когда я умру, они съедят меня и оставят только кости»</em>, — эта мысль странным образом утешала.</div>\n"
|
||||||
|
"</div></body></html>"
|
||||||
|
);
|
||||||
|
src->m_entries.insert(QStringLiteral("EPUB/ch1.xhtml"), xhtml.toUtf8());
|
||||||
|
|
||||||
|
auto sharedEntries = std::make_shared<QHash<QString, QByteArray>>(src->m_entries);
|
||||||
|
auto factory = [sharedEntries]() {
|
||||||
|
auto s = std::make_unique<InMemoryByteSource>();
|
||||||
|
s->m_entries = *sharedEntries;
|
||||||
|
return s;
|
||||||
|
};
|
||||||
|
|
||||||
|
EpubReader reader(factory, QStringLiteral("epub"));
|
||||||
|
QVERIFY(reader.open(QStringLiteral("/virtual/inline_div.epub")));
|
||||||
|
|
||||||
|
bool foundOdnoglazyiTogether = false;
|
||||||
|
bool foundThoughtTogether = false;
|
||||||
|
|
||||||
|
for (const QString &chunk : reader.chunks()) {
|
||||||
|
if (chunk.contains(QStringLiteral("Одноглазый"))) {
|
||||||
|
// Must have both opening and closing quotes together in the same chunk
|
||||||
|
QVERIFY(chunk.contains(QStringLiteral("«")));
|
||||||
|
QVERIFY(chunk.contains(QStringLiteral("»")));
|
||||||
|
foundOdnoglazyiTogether = true;
|
||||||
|
}
|
||||||
|
if (chunk.contains(QStringLiteral("Когда я умру"))) {
|
||||||
|
// Must have the attribution text in the same chunk
|
||||||
|
QVERIFY(chunk.contains(QStringLiteral("эта мысль странным образом утешала")));
|
||||||
|
foundThoughtTogether = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
QVERIFY(foundOdnoglazyiTogether);
|
||||||
|
QVERIFY(foundThoughtTogether);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
QTEST_MAIN(EpubReaderTest)
|
QTEST_MAIN(EpubReaderTest)
|
||||||
|
|||||||
@@ -311,6 +311,64 @@ private slots:
|
|||||||
// With useBookColours = true, (testX, testY) is drawn with border or background
|
// With useBookColours = true, (testX, testY) is drawn with border or background
|
||||||
QVERIFY(imgTrue.pixelColor(testX, testY).alpha() > 0);
|
QVERIFY(imgTrue.pixelColor(testX, testY).alpha() > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void clipRectCullingSkipsOffscreenImage()
|
||||||
|
{
|
||||||
|
class TrackingResolver : public IBookImageResolver {
|
||||||
|
public:
|
||||||
|
int resolveCount = 0;
|
||||||
|
QImage resolveImage(const QString &) override {
|
||||||
|
++resolveCount;
|
||||||
|
QImage img(100, 100, QImage::Format_RGB32);
|
||||||
|
img.fill(Qt::blue);
|
||||||
|
return img;
|
||||||
|
}
|
||||||
|
QSizeF imageSize(const QString &) override {
|
||||||
|
return QSizeF(100, 100);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
TrackingResolver resolver;
|
||||||
|
KnuthPlassItem::setImageResolver(&resolver);
|
||||||
|
|
||||||
|
const QString html = QStringLiteral(
|
||||||
|
"<p>First paragraph taking vertical space</p>"
|
||||||
|
"<p><img src=\"image://epub/fig1.png\" width=\"100\" height=\"100\"/></p>"
|
||||||
|
);
|
||||||
|
LayoutParams params;
|
||||||
|
params.contentWidth = 400;
|
||||||
|
params.fontSize = 16;
|
||||||
|
params.lineSpacing = 1.0;
|
||||||
|
|
||||||
|
auto layout = ChunkLayoutEngine::layoutChunk(html, params, &resolver);
|
||||||
|
QVERIFY(!layout.images.isEmpty());
|
||||||
|
const qreal imageTop = layout.images[0].targetRect.top();
|
||||||
|
QVERIFY(imageTop > 20.0);
|
||||||
|
|
||||||
|
KnuthPlassItem item;
|
||||||
|
item.setSize(QSizeF(400, layout.totalHeight));
|
||||||
|
item.setLayout(QVariant::fromValue(layout));
|
||||||
|
|
||||||
|
// 1. Paint with clip above the image: image resolver must NOT be called
|
||||||
|
QImage img(400, int(layout.totalHeight), QImage::Format_ARGB32_Premultiplied);
|
||||||
|
img.fill(Qt::transparent);
|
||||||
|
{
|
||||||
|
QPainter p(&img);
|
||||||
|
p.setClipRect(QRectF(0, 0, 400, imageTop - 5.0));
|
||||||
|
item.paint(&p);
|
||||||
|
}
|
||||||
|
QCOMPARE(resolver.resolveCount, 0);
|
||||||
|
|
||||||
|
// 2. Paint with clip covering the image: image resolver must be called
|
||||||
|
{
|
||||||
|
QPainter p(&img);
|
||||||
|
p.setClipRect(QRectF(0, 0, 400, imageTop + 50.0));
|
||||||
|
item.paint(&p);
|
||||||
|
}
|
||||||
|
QVERIFY(resolver.resolveCount >= 1);
|
||||||
|
|
||||||
|
KnuthPlassItem::setImageResolver(nullptr);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
QTEST_MAIN(ChunkLayoutEngineTest)
|
QTEST_MAIN(ChunkLayoutEngineTest)
|
||||||
|
|||||||
Reference in new issue
Block a user