Files
asteria-qt/tests/reading/ChunkLayoutEngineTest.cpp
T
2026-11-01 12:19:45 +01:00

538 lines
20 KiB
C++

#include <QtTest>
#include "backend/reading/BookImageResolver.h"
#include "backend/reading/KnuthPlassItem.h"
#include "backend/reading/layout/ChunkLayoutEngine.h"
class MockImageResolver : public IBookImageResolver {
public:
QImage resolveImage(const QString &url) override
{
if (url == QLatin1String("image://epub/fig1.png") || url == QLatin1String("image://web/https://example.com/pic.jpg")) {
QImage img(200, 100, QImage::Format_RGB32);
img.fill(Qt::blue);
return img;
}
return {};
}
QSizeF imageSize(const QString &url) override
{
if (url == QLatin1String("image://epub/fig1.png") || url == QLatin1String("image://web/https://example.com/pic.jpg")) {
return QSizeF(200, 100);
}
return {};
}
};
class ChunkLayoutEngineTest : public QObject {
Q_OBJECT
private slots:
void paragraphLayout()
{
const QString html = QStringLiteral("<p>This is a test paragraph with several words that will fit nicely.</p>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.2;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QVERIFY(!layout.lines.isEmpty());
QVERIFY(layout.totalHeight > 0);
QVERIFY(layout.lines[0].runs.size() >= 1);
}
void headingsAndRules()
{
const QString html = QStringLiteral("<h1>Title</h1><hr/><p>Body text</p>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QVERIFY(layout.lines.size() >= 2);
QCOMPARE(layout.rules.size(), 1);
QVERIFY(layout.totalHeight > 30);
}
void textAlignment()
{
const QString html = QStringLiteral("<p style=\"text-align: center\">Centered line</p>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QVERIFY(!layout.lines.isEmpty());
const auto &run = layout.lines[0].runs.first();
// Since it's centered in 400px width, start x should be > 0
QVERIFY(run.rect.left() > 10.0);
}
void blockquoteDecoration()
{
const QString html = QStringLiteral("<blockquote><p>Quote text</p></blockquote>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QVERIFY(!layout.decorations.isEmpty());
QVERIFY(layout.decorations[0].borderLeft > 0);
}
void imageBlockLayout()
{
MockImageResolver resolver;
const QString html = QStringLiteral("<p><img src=\"image://epub/fig1.png\" width=\"150\"/></p>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params, &resolver);
QCOMPARE(layout.images.size(), 1);
QCOMPARE(layout.images[0].url, QStringLiteral("image://epub/fig1.png"));
QCOMPARE(layout.images[0].targetRect.width(), 150.0);
QCOMPARE(layout.images[0].targetRect.height(), 75.0); // 200x100 aspect ratio -> 150x75
}
void imageWithWhitespaceAroundIt()
{
MockImageResolver resolver;
const QString html = QStringLiteral("<p>\n <img src=\"image://epub/fig1.png\" width=\"150\"/>\n</p>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params, &resolver);
QCOMPARE(layout.images.size(), 1);
QCOMPARE(layout.images[0].url, QStringLiteral("image://epub/fig1.png"));
QCOMPARE(layout.images[0].targetRect.width(), 150.0);
}
void svgImageElement()
{
MockImageResolver resolver;
const QString html = QStringLiteral("<svg width=\"200\" height=\"100\"><image xlink:href=\"image://epub/fig1.png\" width=\"150\"/></svg>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params, &resolver);
QCOMPARE(layout.images.size(), 1);
QCOMPARE(layout.images[0].url, QStringLiteral("image://epub/fig1.png"));
}
void inlineImageInParagraph()
{
MockImageResolver resolver;
const QString html = QStringLiteral("<p>Before <img src=\"image://epub/fig1.png\" width=\"40\" height=\"20\"/> after</p>");
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params, &resolver);
QCOMPARE(layout.images.size(), 1);
QCOMPARE(layout.images[0].url, QStringLiteral("image://epub/fig1.png"));
QVERIFY(!layout.lines.isEmpty());
}
void preparedChunkFastResize()
{
const QString html = QStringLiteral("<p>This is a long paragraph designed to be laid out at different widths to test rapid reflow.</p>");
auto prepared = ChunkLayoutEngine::prepareChunk(html, 16);
QVERIFY(!prepared.blocks.isEmpty());
LayoutParams p1;
p1.contentWidth = 300;
p1.fontSize = 16;
p1.lineSpacing = 1.0;
auto l1 = ChunkLayoutEngine::layoutPreparedChunk(prepared, p1);
LayoutParams p2;
p2.contentWidth = 600;
p2.fontSize = 16;
p2.lineSpacing = 1.0;
auto l2 = ChunkLayoutEngine::layoutPreparedChunk(prepared, p2);
QVERIFY(l1.lines.size() >= l2.lines.size());
QCOMPARE(l1.contentWidth, 300.0);
QCOMPARE(l2.contentWidth, 600.0);
}
void calibreHeaderLayout()
{
const QString html = QStringLiteral(
"<h1 style=\"background-color: #e7e7e7; border: 1px solid black; font-size: 1.375em; text-align: left;\">"
"<a id=\"TOC_1\"></a>СЛУГА КУПЦА <br class=\"calibre9\"/></h1>"
);
LayoutParams params;
params.contentWidth = 600;
params.fontSize = 16;
params.lineSpacing = 1.2;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
// Should have exactly 1 block decoration for the h1 box
QCOMPARE(layout.decorations.size(), 1);
const auto &dec = layout.decorations[0];
QCOMPARE(dec.background, QColor(0xe7, 0xe7, 0xe7));
QCOMPARE(dec.borderColor, QColor(Qt::black));
QCOMPARE(dec.borderLeft, 1.0);
QCOMPARE(dec.borderRight, 1.0);
QCOMPARE(dec.borderTop, 1.0);
QCOMPARE(dec.borderBottom, 1.0);
// Trailing <br/> must be stripped and not produce a spurious empty second line
QCOMPARE(layout.lines.size(), 1);
QVERIFY(!layout.lines[0].runs.isEmpty());
// Words must NOT have individual highlight backgrounds
for (const auto &run : layout.lines[0].runs) {
QVERIFY(!run.background.isValid());
// But they should know the enclosing box background
QCOMPARE(run.surfaceBackground, QColor(0xe7, 0xe7, 0xe7));
}
}
void inlineBackgrounds()
{
const QString html = QStringLiteral("<p>Normal <span style=\"background-color: yellow;\">highlighted</span> text</p>");
LayoutParams params;
params.contentWidth = 600;
params.fontSize = 16;
params.lineSpacing = 1.2;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
// No container box decorations for an inline span
QCOMPARE(layout.decorations.size(), 0);
QVERIFY(!layout.lines.isEmpty());
bool foundYellow = false;
bool foundNormal = false;
for (const auto &run : layout.lines[0].runs) {
if (run.text.contains(QLatin1String("highlighted"))) {
QCOMPARE(run.background, QColor(Qt::yellow));
foundYellow = true;
} else if (run.text.contains(QLatin1String("Normal"))) {
QVERIFY(!run.background.isValid());
foundNormal = true;
}
}
QVERIFY(foundYellow);
QVERIFY(foundNormal);
}
void nestedBackgroundContainer()
{
const QString html = QStringLiteral("<div style=\"background-color: #ff0000;\"><p>Inner text</p></div>");
LayoutParams params;
params.contentWidth = 600;
params.fontSize = 16;
params.lineSpacing = 1.2;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QCOMPARE(layout.decorations.size(), 1);
QCOMPARE(layout.decorations[0].background, QColor(0xff, 0, 0));
QVERIFY(!layout.lines.isEmpty());
QVERIFY(!layout.lines[0].runs.isEmpty());
// Enclosing background is inherited as surfaceBackground
QCOMPARE(layout.lines[0].runs[0].surfaceBackground, QColor(0xff, 0, 0));
// But not as run.background
QVERIFY(!layout.lines[0].runs[0].background.isValid());
}
void contrastRatioHelper()
{
QColor lightBg(0xe7, 0xe7, 0xe7);
QColor darkBg(0x19, 0x1d, 0x35);
qreal crLightBlack = KnuthPlassItem::contrastRatio(Qt::black, lightBg);
qreal crLightWhite = KnuthPlassItem::contrastRatio(Qt::white, lightBg);
QVERIFY(crLightBlack > 10.0);
QVERIFY(crLightWhite < 2.0);
qreal crDarkBlack = KnuthPlassItem::contrastRatio(Qt::black, darkBg);
qreal crDarkWhite = KnuthPlassItem::contrastRatio(Qt::white, darkBg);
QVERIFY(crDarkWhite > 10.0);
QVERIFY(crDarkBlack < 2.0);
}
void knuthPlassItemPaintBoxSuppression()
{
const QString html = QStringLiteral(
"<h1 style=\"background-color: #e7e7e7; border: 2px solid black;\">Header Title</h1>"
);
LayoutParams params;
params.contentWidth = 400;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QCOMPARE(layout.decorations.size(), 1);
KnuthPlassItem item;
item.setSize(QSizeF(400, 200));
item.setLayout(QVariant::fromValue(layout));
// When useBookColours is false:
item.setUseBookColours(false);
QImage imgFalse(400, 200, QImage::Format_ARGB32_Premultiplied);
imgFalse.fill(Qt::transparent);
{
QPainter p(&imgFalse);
item.paint(&p);
}
// When useBookColours is true:
item.setUseBookColours(true);
QImage imgTrue(400, 200, QImage::Format_ARGB32_Premultiplied);
imgTrue.fill(Qt::transparent);
{
QPainter p(&imgTrue);
item.paint(&p);
}
const auto &dec = layout.decorations[0];
int testX = int(dec.rect.left());
int testY = int(dec.rect.top());
// With useBookColours = false, (testX, testY) should be transparent (no background, no border box)
QCOMPARE(imgFalse.pixelColor(testX, testY).alpha(), 0);
// With useBookColours = true, (testX, testY) is drawn with border or background
QVERIFY(imgTrue.pixelColor(testX, testY).alpha() > 0);
}
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.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 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);
}
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].charCount > 0);
QCOMPARE(chunks[1].sectionHref, QStringLiteral("section1.xhtml"));
QCOMPARE(chunks[1].unnestedContainers, 1); // Carries the open blockquote container
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);
}
void paragraphDefaultsAndCssOverrides()
{
// 1. Unstyled <p> must produce zero ContainerStart/End boxes and have 2.0em indent
const QString plainHtml = QStringLiteral("<div><p>Paragraph one</p><p>Paragraph two</p></div>");
auto plainChunks = HtmlBlockParser::parseChunks(plainHtml, QStringLiteral("plain.xhtml"));
QCOMPARE(plainChunks.size(), 1);
const auto &plainBlocks = plainChunks.first().blocks;
// Exactly 2 blocks (both paragraphs), zero containers
QCOMPARE(plainBlocks.size(), 2);
QCOMPARE(plainBlocks[0].kind, BlockItem::Kind::Paragraph);
QCOMPARE(plainBlocks[1].kind, BlockItem::Kind::Paragraph);
QCOMPARE(plainBlocks[0].textIndent, 32.0); // 16 * 2.0
QCOMPARE(plainBlocks[1].textIndent, 32.0);
// 2. Styled <p> with explicit margin must preserve box margins via ContainerStart/End
const QString styledHtml = QStringLiteral("<div><p style=\"margin-top: 10px; margin-bottom: 12px; text-indent: 0;\">Styled paragraph</p></div>");
auto styledChunks = HtmlBlockParser::parseChunks(styledHtml, QStringLiteral("styled.xhtml"));
QCOMPARE(styledChunks.size(), 1);
const auto &styledBlocks = styledChunks.first().blocks;
// ContainerStart, Paragraph, ContainerEnd
QCOMPARE(styledBlocks.size(), 3);
QCOMPARE(styledBlocks[0].kind, BlockItem::Kind::ContainerStart);
QCOMPARE(styledBlocks[0].box.marginTop, 10.0);
QCOMPARE(styledBlocks[0].box.marginBottom, 12.0);
QCOMPARE(styledBlocks[1].kind, BlockItem::Kind::Paragraph);
QCOMPARE(styledBlocks[1].textIndent, 0.0);
QCOMPARE(styledBlocks[2].kind, BlockItem::Kind::ContainerEnd);
}
void lineBreakBeforeParagraphEndDoesNotStretch()
{
// Simulating the Protector.epub Summary block:
// A paragraph with short lines separated by <br/>, with text-align: justify
const QString html = QStringLiteral(
"<p style=\"text-align: justify;\">"
"This does not contain non-con or Loki treating Tony like a slave.<br/>"
"It's a hurt/comfort-story."
"</p>"
);
LayoutParams params;
params.contentWidth = 800; // Wide viewport where each line easily fits on one line
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutChunk(html, params);
QCOMPARE(layout.lines.size(), 2);
// Neither line should stretch to fill the 800px width.
// The first line has text ending at its natural width, not reaching anywhere near 800.
const auto &line1 = layout.lines[0];
QVERIFY(!line1.runs.isEmpty());
const qreal line1Right = line1.runs.last().rect.right();
QVERIFY(line1Right < 700.0);
const auto &line2 = layout.lines[1];
QVERIFY(!line2.runs.isEmpty());
const qreal line2Right = line2.runs.last().rect.right();
QVERIFY(line2Right < 400.0);
}
void overstretchedJustifiedLineFallsBackToNaturalSpacing()
{
// When a line in a justified paragraph has an extreme ratio (> 2.0),
// e.g. because the next word is too wide to fit on the line,
// it must not stretch spaces across the line to fill the container.
// We choose words that each individually fit in availWidth (250px) to avoid
// emergency letter-splitting, but whose sum exceeds 250px.
BlockItem p;
p.kind = BlockItem::Kind::Paragraph;
p.align = TextAlign::Justify;
p.fontSize = 16.0;
InlineItem t1;
t1.kind = InlineItem::Kind::Text;
// "Alpha Beta Gamma" (~120px) followed by "Characterization" (~120px).
// Total width ~240px > 200px, so it must break onto 2 lines.
// Each word is well under 200px, so no emergency letter-split occurs.
// Line 0 has "Alpha Beta Gamma" with shortfall ~80px in 200px width (ratio ~20.0 >> 2.0).
t1.text = QStringLiteral("Alpha Beta Gamma Characterization");
p.inlines.append(t1);
LayoutParams params;
params.contentWidth = 200;
params.fontSize = 16;
params.lineSpacing = 1.0;
auto layout = ChunkLayoutEngine::layoutBlocks({p}, params);
QVERIFY(layout.lines.size() >= 2);
// First line has "Alpha Beta Gamma" (natural width ~120-135px).
// If it were stretched to fill 200px, its right would be 200.0.
// Because line.ratio > 2.0, it falls back to natural spacing (right < 165.0).
const auto &line0 = layout.lines[0];
QVERIFY(!line0.runs.isEmpty());
QVERIFY(line0.runs.last().rect.right() < 165.0);
}
};
QTEST_MAIN(ChunkLayoutEngineTest)
#include "ChunkLayoutEngineTest.moc"