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

-31
View File
@@ -1,31 +0,0 @@
{
"permissions": {
"allow": [
"Bash(find:*)",
"Bash(grep:*)",
"Bash(cmake:*)",
"Bash(ninja:*)",
"Bash(ctest:*)",
"Bash(*cmake.exe*)",
"Bash(*ninja.exe*)",
"Bash(*ctest.exe*)",
"Bash(qmake6 --version)",
"Bash(pkg-config --modversion*)",
"Bash(dpkg -l)",
"WebSearch",
"Bash(bash scripts/test-ci-windows.sh 2>&1)",
"Bash(bash scripts/test-ci-linux.sh 2>&1)",
"Bash(pkg-config --modversion Qt6Core)",
"Bash(dpkg -l)",
"Bash(pkg-config:*)",
"Bash(git checkout:*)",
"Bash(git:*)",
"Bash(ls -lh /opt/qt/6.10.3/gcc_64/lib/libQt6WebView*.so* /opt/qt/6.10.3/gcc_64/lib/libQt6WebEngine*.so*)",
"Bash(xargs ls:*)",
"Bash(ls -lh /opt/qt/6.10.3/gcc_64/lib/*WebChannel*)",
"Bash(ls -1 /opt/qt/6.10.3/gcc_64/lib/libQt6*.so.6.10.3)",
"Bash(ls -lh /opt/qt/6.10.3/gcc_64/lib/libQt6*.so.6.10.3)",
"Bash(du:*)"
]
}
}
+5 -8
View File
@@ -148,8 +148,8 @@ public:
virtual QString author() const;
virtual QString coverImageUrl() const;
virtual QByteArray contentHash() const = 0; // MD5 hash for stable persistent state
virtual QVector<PageInfo> pages() const; // Comic mode
virtual QStringList chunks() const; // Text mode: HTML fragments
virtual QVector<PageInfo> pages() const; // Comic mode
virtual QVector<ContentChunk> chunks() const; // Text mode: structured content chunks
};
```
@@ -158,13 +158,10 @@ public:
## Rendering Architecture
### 1. Text Mode (`ScrollPageView.qml`)
- `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.
- `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.
- When viewport geometry or font preferences change, `ReadingModel::updateLayoutMetrics()` runs `ChunkLayoutEngine` off-thread:
- `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).
- Cleans up trailing `<br/>` and trailing/leading whitespace in blocks.
- `CssParser` evaluates stylesheets and styles inline tags. Parses full `border` shorthand, individual borders (`border-top/right/bottom/left`), widths (1-4 values), keywords, styles, and colours.
- Pre-parsed `BlockItem`s in `ContentChunk` scale dynamically with user font preferences in `ChunkLayoutEngine::prepareBlocks()` with zero HTML/XML re-parsing.
- `KnuthPlass` computes optimal justified/aligned line breaks.
- `BookImageResolver` resolves embedded image dimensions and URLs.
- Off-thread calculation stores `ChunkLayout` and pixel heights.
-192
View File
@@ -1,192 +0,0 @@
---
name: run-workflow
description: 'How to write and run a dynamic workflow script with the `run_workflow` tool: a Python script that orchestrates many agents with `agent`, `parallel`, `pipeline`, and `phase`. Use when a task splits into many independent or staged pieces of agent work (fan out over files, modules, bugs, or review angles, then aggregate), or when the user asks for a workflow. Don''t use for a single delegated task (use a subagent) or for legacy workflow files (see migrate-workflows).'
metadata:
namespace: system
---
# Dynamic workflows with `run_workflow`
A workflow is a short Python script that the `run_workflow` tool executes. The
script decides which agents to start, in what order, and what to do with their
results. Use it instead of many manual subagent calls when the orchestration
itself is code: loops over a list, fan-out then aggregate, or staged pipelines.
## Steps
1. Pass the script inline as `Script`, or write it to a file (for example in
the conversation scratch directory) and pass its absolute path as
`ScriptPath`. Set exactly one of them; a file is easier to fix and rerun.
2. Call `run_workflow(Script="...", Description="...")` or
`run_workflow(ScriptPath="/abs/path/workflow.py", Description="...")`.
`Description` is a one-line goal shown in the UI.
The workflow runs in the background, and you are notified when it ends.
For a quick script, such as a `call_tool` fan-out, set
`WaitMsBeforeAsync` (up to 10000) to get the result in the same turn if it
finishes in time.
To pass inputs, set `Args` to a JSON object; the script reads it as the
`args` dict. When `ScriptPath` is a saved workflow's entry script, `Args`
is validated against the args schema in its `workflow.json`.
3. Read the tool result: it contains the `log()` output (`Logs:`) and what the
script printed (`Output:`). Each agent is also linked from the workflow
step, so the user can open its conversation.
4. If the tool returns an error, fix the script at the reported line and run
it again.
## Script rules
The script runs in its own `python3` process, which needs Python 3.8 or later
on `PATH`:
- `await` works at the top level, and you can define `async def` helpers.
- Installed library workflows are importable by name (`import <library>` or
`from <library> import <name>`); library modules see the same primitives as
the script.
- What the script prints (`print()`, `stderr`, child-process output, and the
`repr` of a trailing expression) is returned in the tool result's `Output:`
section (and appended to the error when the workflow fails).
- An uncaught exception stops the workflow and reports the script line.
- `CONVERSATION_ID` and `STEP_INDEX` identify the `run_workflow` step.
`WORKSPACES` is a tuple of the workspace directories, primary first (empty
if there are none).
- The working directory is `Cwd` if given, else `WORKSPACES[0]`, so relative
paths resolve against it. Local modules are not importable.
## Primitives
| Primitive | Behavior |
| --- | --- |
| `log(*args)` | Adds a line to the workflow output and the UI. |
| `phase(name)` | Starts a named phase; later logs and agents group under it. |
| `agent(prompt=None, schema=None, role=None, type_name="self", workspace="inherit", model=None)` | Defines an agent; nothing runs yet. `await agent(prompt, schema)` runs it once and returns its result. `a = agent(...)` then `await a(prompt, schema)` runs one turn in a conversation kept across calls. |
| `parallel(items, fn)` | Promise that calls `fn(item)` for each item and awaits all results concurrently; results are in item order. If one fails, the rest are cancelled. |
| `pipeline(items, fn)` | Promise that calls and awaits `fn(item)` one item at a time; results are in item order. |
| `trajectory(last=None, types=None, tools=None, min_index=None, max_index=None)` | `await trajectory()` returns steps before this `run_workflow` call started, oldest first. `min_index` and `max_index` bound `step.index` (inclusive); `types` and `tools` filter by step type or tool name; `last` keeps the last N matching steps. |
Arguments:
- `type_name`: the agent type to run. `"self"` uses the current agent's
configuration; any available custom agent name also works.
- `workspace`: `"inherit"` (the current workspace), `"branch"` (a new isolated
clone, for agents that edit code in parallel), or `"share"` (a new workspace
that shares the underlying repository). Other values are errors.
- `schema` (required): a JSON schema (dict or string) for the agent's result.
The agent returns the result by calling its `finish` tool, which checks it
against the schema, and `await agent(...)` returns the parsed value. An
agent that ends without calling `finish` fails the workflow. Use
`{"type": "string"}` for a free-form answer.
- `role`: an optional short title for the agent's card, such as
`"Security reviewer"`.
- `model`: the agent's model tier: `"inherit"` (default, your model),
`"flash_lite"`, `"flash"`, or `"pro"`. Use a lighter tier for simple,
high-fan-out work.
- `fn`: usually a `lambda` that returns `agent(...)`, or an `async def`
helper that awaits several agents. It must return something awaitable:
an `agent()` or a call on one, a nested `parallel()` / `pipeline()`, or
an `async def` call. Build per-item prompts and roles with f-strings.
Awaiting the same agent twice runs it once and returns the same result. An
`agent()` that is never awaited or called never runs, so always `await` it, or
pass it to `parallel` / `pipeline` and await that.
The workflow step shows one card per agent, in the order agents start, titled
with its `role`, or else the first line of its prompt, so set a role or start
each prompt with a short line that names the job.
## Agents that keep their context
When one agent should do several related turns, such as a reviewer that checks
the fixes for the bugs it found, call it instead of awaiting it. Each
`a(prompt, schema)` is lazy like an awaited `agent()` and returns that turn's
`finish` result; the agent's own `prompt`, if any, is its standing instructions
and leads the first turn. `schema` on a call defaults to the agent's. Turns on
one agent run one at a time, in the order they were started. A failed turn
raises, but the agent stays usable. An agent is either awaited or called, not
both. `del a` ends the agent, unless something else, such as a lambda, still
references it; every agent ends when the workflow ends.
```python
reviewer = agent("You review Go code for correctness.", role="Reviewer")
bugs = await reviewer("List the bugs in foo.go.", {"type": "array", "items": {"type": "string"}})
fixes = await parallel(bugs, lambda b: agent(f"Fix: {b}", {"type": "string"}))
ok = await reviewer(f"Fixes made: {fixes}. Are all your bugs fixed?", {"type": "boolean"})
del reviewer
```
## Calling tools from the script
Where the `run_workflow` tool description lists tools for `call_tool`, the
script can call them directly:
- `call_tool(name, **args)` returns a promise like `agent()` does. Awaiting it
runs the tool with the arguments you would pass to it directly and returns
the tool's output as a `str`.
- It raises `ToolError` (with `.tool` and `.message`) if the tool fails or
the call is denied. `.denied` is `True` when a pre-tool hook or the
permission check rejected the call before the tool ran, so a script can
skip denied calls and still fail on real errors.
- The user cannot be asked anything from a workflow: a call that needs user
approval that has not already been granted is denied.
- Tool outputs are not shown to you unless the script logs or prints them.
## Reading earlier conversation steps
Pass inputs you already have in `Args` (or inline in the script). Use
`await trajectory(...)` when the script needs to inspect steps from earlier in
this conversation—such as mining a failed `run_command` output without
rerunning it—and pass only the relevant slice into child `agent()` prompts.
Each returned `Step` is a `dict` that also supports attribute access (missing
fields return `None` as attributes):
- `index` (`int`): 0-based step index.
- `type` (`str`): step type, e.g. `"USER_INPUT"`, `"PLANNER_RESPONSE"`,
`"SYSTEM_MESSAGE"`, or `"GENERIC"` (tool calls).
- `status` (`str`): e.g. `"DONE"`, `"ERROR"`, or `"CLEARED"`.
- Message steps set `text` (`str`); tool steps set `tool` (`str`), `args`
(parsed `dict`), and `output` (`str`, truncated at 200k characters).
```python
steps = await trajectory(tools=["run_command"], last=20)
errors = [s.output for s in steps if s.status == "ERROR" and s.output]
log(f"Found {len(errors)} failed command(s)")
```
`trajectory()` only returns steps before the `run_workflow` call started (steps
added while the workflow runs in the background are not included). Older tool
steps evicted from memory have `status == "CLEARED"` and `output == None`; read
the conversation's `transcript.jsonl` / `transcript_full.jsonl` when you need
cleared tool outputs or steps added after the workflow started.
## Behavior to know
- Workflow agents are main agents, not subagents. They are hidden from the
conversation list and reachable from the workflow step. An awaited agent
is single-use; a called agent lasts until deleted or the workflow ends.
- `await agent(...)` returns when the agent's run ends, with the result it
passed to `finish`.
- If one agent in `parallel` fails, the whole call fails and the other agents
in it are cancelled. Stopping the parent conversation stops all running
workflow agents.
- Agents do not see the script or each other. Put all the context an agent
needs in its prompt, and ask for a short, well-defined output.
## Example
Fan out over a list that an agent produces:
```python
phase("Discover")
files = await agent(
"List the Go files under pkg/foo that call Bar(). Paths only.",
schema={"type": "array", "items": {"type": "string"}},
)
phase("Review")
reviews = await parallel(files, lambda f: agent(
f"Review {f} for misuse of Bar(). Reply in 3 bullets or 'OK'.",
schema={"type": "string"},
role=f"Review {f}",
))
for r in reviews:
log(r)
```
+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
+16 -12
View File
@@ -41,13 +41,13 @@ public:
QByteArray contentHash() const override { return QByteArray("texthash"); }
bool loadMetadata(const QString &) override { return true; }
QStringList chunks() const override
QVector<ContentChunk> chunks() const override
{
return {
QStringLiteral("<p>Chunk 1</p>"),
QStringLiteral("<p>Chunk 2</p>"),
QStringLiteral("<p>Chunk 3</p>")
};
return HtmlBlockParser::parseChunks(
QStringLiteral("<p>Chunk 1</p><p>Chunk 2</p><p>Chunk 3</p>"),
QStringLiteral("text/ch1.xhtml"),
1 // targetChars = 1 forces each paragraph into its own chunk
);
}
};
@@ -63,12 +63,16 @@ public:
QByteArray contentHash() const override { return QByteArray("manychunks"); }
bool loadMetadata(const QString &) override { return true; }
QStringList chunks() const override
QVector<ContentChunk> chunks() const override
{
QStringList list;
QVector<ContentChunk> 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));
auto parsed = HtmlBlockParser::parseChunks(
QStringLiteral("<p>Paragraph chunk number %1 with some text content.</p>").arg(i),
QStringLiteral("text/ch1.xhtml")
);
list.append(parsed);
}
return list;
}
@@ -200,11 +204,11 @@ private slots:
QVERIFY(model.isTextMode());
QCOMPARE(model.rowCount(), 3);
QCOMPARE(model.data(model.index(0, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk 1</p>"));
QStringLiteral("text/ch1.xhtml"));
QCOMPARE(model.data(model.index(1, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk 2</p>"));
QStringLiteral("text/ch1.xhtml"));
QCOMPARE(model.data(model.index(2, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk 3</p>"));
QStringLiteral("text/ch1.xhtml"));
QTRY_COMPARE(restoreSpy.count(), 1);
+66 -22
View File
@@ -123,14 +123,33 @@ private slots:
QVERIFY(!reader.chunks().isEmpty());
QString fullHtml = reader.chunks().join(QString());
// Verify CSS styling inlined
QVERIFY(fullHtml.contains(QStringLiteral("color:red")) || fullHtml.contains(QStringLiteral("italic")));
// Verify embedded image resolved to image://epub/ with source path
QVERIFY(fullHtml.contains(QStringLiteral("image://epub/OEBPS/images/fig1.png")));
QVERIFY(fullHtml.contains(QStringLiteral("src=%2Fvirtual%2Fbook.epub")) || fullHtml.contains(QStringLiteral("src=/virtual/book.epub")));
// Verify web image resolved to image://web/
QVERIFY(fullHtml.contains(QStringLiteral("image://web/https://example.com/pic.jpg")));
bool foundColorOrItalic = false;
bool foundEpubImage = false;
bool foundWebImage = false;
for (const auto &chunk : reader.chunks()) {
QCOMPARE(chunk.sectionHref, QStringLiteral("OEBPS/text/ch1.xhtml"));
for (const auto &b : chunk.blocks) {
for (const auto &inl : b.inlines) {
if (inl.style.color == QColor(Qt::red) || inl.style.italic) {
foundColorOrItalic = true;
}
if (inl.kind == InlineItem::Kind::Image) {
if (inl.imageUrl.contains(QStringLiteral("image://epub/OEBPS/images/fig1.png"))
&& (inl.imageUrl.contains(QStringLiteral("src=%2Fvirtual%2Fbook.epub")) || inl.imageUrl.contains(QStringLiteral("src=/virtual/book.epub")))) {
foundEpubImage = true;
}
if (inl.imageUrl.contains(QStringLiteral("image://web/https://example.com/pic.jpg"))) {
foundWebImage = true;
}
}
}
}
}
QVERIFY(foundColorOrItalic);
QVERIFY(foundEpubImage);
QVERIFY(foundWebImage);
}
void openEpub3WithNavDocument()
@@ -187,7 +206,17 @@ private slots:
QStringLiteral("EPUB/cover.png"),
QStringLiteral("/virtual/epub3.epub")));
QVERIFY(!reader.chunks().isEmpty());
QVERIFY(reader.chunks().first().contains(QStringLiteral("Hello EPUB 3")));
bool foundHello = false;
for (const auto &chunk : reader.chunks()) {
QCOMPARE(chunk.sectionHref, QStringLiteral("EPUB/ch1.xhtml"));
for (const auto &b : chunk.blocks) {
for (const auto &inl : b.inlines) {
if (inl.text.contains(QStringLiteral("Hello EPUB 3")))
foundHello = true;
}
}
}
QVERIFY(foundHello);
}
void chapterWrapperUnwrappedIntoGranularChunks()
@@ -239,8 +268,13 @@ private slots:
// 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")));
for (const auto &chunk : reader.chunks()) {
QCOMPARE(chunk.sectionHref, QStringLiteral("EPUB/ch1.xhtml"));
for (const auto &b : chunk.blocks) {
if (b.kind == BlockItem::Kind::Paragraph) {
QCOMPARE(b.align, TextAlign::Justify);
}
}
}
}
@@ -290,17 +324,27 @@ private slots:
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;
for (const auto &chunk : reader.chunks()) {
for (const auto &b : chunk.blocks) {
if (b.kind != BlockItem::Kind::Paragraph)
continue;
QString paraText;
for (const auto &inl : b.inlines) {
paraText += inl.text;
}
if (paraText.contains(QStringLiteral("Одноглазый"))) {
// Must have both opening and closing quotes together in the same paragraph
QVERIFY(paraText.contains(QStringLiteral("«")));
QVERIFY(paraText.contains(QStringLiteral("»")));
foundOdnoglazyiTogether = true;
}
if (paraText.contains(QStringLiteral("Когда я умру"))) {
// Must have the attribution text in the same paragraph
QVERIFY(paraText.contains(QStringLiteral("эта мысль странным образом утешала")));
foundThoughtTogether = true;
}
}
}
+65
View File
@@ -369,6 +369,71 @@ private slots:
KnuthPlassItem::setImageResolver(nullptr);
}
void contentChunkFontSizeScaling()
{
const QString html = QStringLiteral("<p>Testing dynamic font scaling directly on structured ContentChunk without re-parsing XML.</p>");
auto chunks = HtmlBlockParser::parseChunks(html, QStringLiteral("section.xhtml"));
QCOMPARE(chunks.size(), 1);
const auto &chunk = chunks.first();
QVERIFY(chunk.wordCount > 5);
QVERIFY(chunk.charCount > 20);
LayoutParams p16;
p16.contentWidth = 400;
p16.fontSize = 16;
p16.lineSpacing = 1.0;
auto prep16 = ChunkLayoutEngine::prepareChunk(chunk, 16);
auto l16 = ChunkLayoutEngine::layoutPreparedChunk(prep16, p16);
LayoutParams p24;
p24.contentWidth = 400;
p24.fontSize = 24;
p24.lineSpacing = 1.0;
auto prep24 = ChunkLayoutEngine::prepareChunk(chunk, 24);
auto l24 = ChunkLayoutEngine::layoutPreparedChunk(prep24, p24);
QVERIFY(l24.totalHeight > l16.totalHeight);
QVERIFY(!l24.lines.isEmpty());
QVERIFY(l24.lines[0].runs[0].font.pixelSize() > l16.lines[0].runs[0].font.pixelSize());
}
void contentChunkPartitionAndUnnestedContainers()
{
const QString html = QStringLiteral(
"<blockquote>"
"<p>First paragraph inside a blockquote designed to be split across chunk boundaries cleanly.</p>"
"<p>Second paragraph inside the same blockquote continuing the quote.</p>"
"</blockquote>"
);
auto chunks = HtmlBlockParser::parseChunks(html, QStringLiteral("section1.xhtml"), 60);
QVERIFY(chunks.size() >= 2);
QCOMPARE(chunks[0].sectionHref, QStringLiteral("section1.xhtml"));
QCOMPARE(chunks[0].unnestedContainers, 0);
QVERIFY(chunks[0].wordCount > 0);
QVERIFY(chunks[0].charCount > 0);
QCOMPARE(chunks[1].sectionHref, QStringLiteral("section1.xhtml"));
QCOMPARE(chunks[1].unnestedContainers, 1); // Carries the open blockquote container
QVERIFY(chunks[1].wordCount > 0);
QVERIFY(chunks[1].charCount > 0);
// Layout both chunks and verify decorations
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto l1 = ChunkLayoutEngine::layoutPreparedChunk(ChunkLayoutEngine::prepareChunk(chunks[0], 16), params);
auto l2 = ChunkLayoutEngine::layoutPreparedChunk(ChunkLayoutEngine::prepareChunk(chunks[1], 16), params);
QVERIFY(!l1.decorations.isEmpty());
QVERIFY(l1.decorations[0].borderLeft > 0);
QVERIFY(!l2.decorations.isEmpty());
QVERIFY(l2.decorations[0].borderLeft > 0);
}
};
QTEST_MAIN(ChunkLayoutEngineTest)