test: propagate text layout engine specification test suite

Formalize the Asteria Qt text layout engine behavior and establish
comprehensive test coverage across all 94 Allium specification
obligations for two-phase layout, Knuth-Plass line breaking, and
reading session state management.

- Add `specs/text-layout-engine.allium` detailing layout lifecycle,
  generation monotonicity, viewport metrics, and contrast safety.
- Implement structural equality operators (`operator==`) across layout
  domain value types (`BoxStyle`, `InlineItem`, `BlockItem`,
  `ContentChunk`, `KnuthPlass::Item`, positioned line/run elements,
  and `BookPosition`) to enable deterministic assertion testing.
- Introduce `TextLayoutEngineSpecTest` verifying entity fields, value
  equality, enum comparability, contract signatures, config defaults,
  lifecycle state transitions, rules, and invariants.
- Register `TextLayoutEngineSpecTest` in `CMakeLists.txt` and update
  test inventory in `AGENTS.md`.
This commit is contained in:
Agel committed 2026-10-29 15:21:28 +01:00
1 parent 306d4cac5c
commit e64bf33f65
8 files changed
+1681

No files matched your search

+25
View File
@@ -276,6 +276,31 @@ src/
HistoryPage.qml
ReaderPage.qml
StarterPage.qml
tests/
AppStateTest.cpp
EntryImageProviderTest.cpp
FileIconProviderTest.cpp
FormatRegistryTest.cpp
HistoryModelTest.cpp
ReadingModelTest.cpp
book/
BookTest.cpp
formats/
CbzReaderTest.cpp
EpubReaderTest.cpp
FolderReaderTest.cpp
ImageUrlTest.cpp
WebImageProviderTest.cpp
reading/
ChunkLayoutEngineTest.cpp
CssParserTest.cpp
KnuthPlassTest.cpp
MangaPaginationTest.cpp
TextLayoutEngineSpecTest.cpp
state/
BookPositionStoreTest.cpp
ReadingPreferencesTest.cpp
UiStateTest.cpp
```
---
+14
View File
@@ -332,6 +332,20 @@ add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp
target_link_libraries(ReadingModelTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Network)
set_tests_properties(ReadingModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(TextLayoutEngineSpecTest tests/reading/TextLayoutEngineSpecTest.cpp
src/backend/ReadingModel.cpp
src/backend/reading/KnuthPlassItem.cpp
src/backend/reading/MangaPagination.cpp
src/backend/formats/AsyncImageResponse.cpp
src/backend/formats/FormatRegistry.cpp
src/backend/AppState.cpp
src/backend/state/BookPositionStore.cpp
src/backend/HistoryModel.cpp
${COMIC_SOURCES}
${EPUB_READER_SOURCES})
target_link_libraries(TextLayoutEngineSpecTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Network)
set_tests_properties(TextLayoutEngineSpecTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(AppStateTest tests/AppStateTest.cpp
src/backend/AppState.cpp)
+551
View File
@@ -0,0 +1,551 @@
-- allium: 3
-- text-layout-engine.allium
-- Scope: Asteria Qt Text Layout Engine
-- Includes:
-- - Layout lifecycle & state: Two-phase visible-first layout (synchronous layout of visible anchor window + off-thread background layout of remaining chunks)
-- - Layout metrics & preference changes: Viewport geometry changes, font size/line spacing/margins updating layout metrics, dynamic scaling without reparsing
-- - Off-thread Knuth-Plass line breaking (word measurement, box-glue-penalty model, multi-pass solver, optimal break computation)
-- - Two-phase layout synchronization: restoreReady(chunkIndex, intraOffset) emission, on-demand layout guards for chunks scrolled into view before background completion
-- - Position restoration & tracking: Anchor chunk + intra-chunk pixel offset tracking
-- - Image dimension resolution: BookImageResolver resolving embedded images
-- - Publisher colours vs theme styling: useBookColours, WCAG contrast safety fallback (contrastRatio < 3.0)
-- Excludes:
-- - ZIP archive byte extraction mechanics (ZipByteSource / IByteSource implementations)
-- - QML rendering (UI presentation, ScrollPageView.qml, KnuthPlassItem QPainter drawing)
-- Deferred:
-- - Detailed CSS selector specificity and property value parsing (deferred to CssCascade)
-- - Detailed HTML DOM to BlockItem and ContentChunk partitioning algorithms (deferred to HtmlBlockParser)
entity User {
id: String
}
------------------------------------------------------------
-- Value Types
------------------------------------------------------------
value Size {
width: Decimal
height: Decimal
}
value Rect {
x: Decimal
y: Decimal
width: Decimal
height: Decimal
}
value Color {
r: Decimal
g: Decimal
b: Decimal
alpha: Decimal
is_valid: Boolean
}
value TextStyle {
font_families: List<String>
font_size: Decimal
weight: Integer
italic: Boolean
small_caps: Boolean
transform: TextTransform
letter_spacing: Decimal
underline: Boolean
strike_out: Boolean
overline: Boolean
link: Boolean
color: Color
background: Color
baseline_shift: Decimal
}
value BoxStyle {
margin_top: Decimal
margin_bottom: Decimal
margin_left: Decimal
margin_right: Decimal
padding_top: Decimal
padding_bottom: Decimal
padding_left: Decimal
padding_right: Decimal
border_top: Decimal
border_bottom: Decimal
border_left: Decimal
border_right: Decimal
border_color: Color
background: Color
blocks_top_collapse: padding_top > 0 or border_top > 0 or border_left > 0 or border_right > 0 or background.is_valid
blocks_bottom_collapse: padding_bottom > 0 or border_bottom > 0 or border_left > 0 or border_right > 0 or background.is_valid
}
value InlineItem {
kind: InlineKind
text: String
style: TextStyle
image_url: String
natural_size: Size?
css_width: Decimal
css_height: Decimal
css_max_width: Decimal
}
value KpItem {
item_type: KpItemType
width: Decimal
stretch: Decimal
shrink: Decimal
penalty: Decimal
flagged: Boolean
tag: Integer
}
value BlockItem {
kind: BlockKind
box: BoxStyle
align: TextAlign
text_indent: Decimal
line_height: Decimal
font_size: Decimal
preformatted: Boolean
marker: String
marker_style: TextStyle
inlines: List<InlineItem>
kp_items: List<KpItem>
rule_color: Color
}
value PositionedWordRun {
text: String
rect: Rect
baseline_y: Decimal
font_size: Decimal
color: Color
background: Color
surface_background: Color
link: Boolean
}
value PositionedLine {
rect: Rect
baseline_y: Decimal
runs: List<PositionedWordRun>
}
value PositionedImage {
url: String
target_rect: Rect
}
value PositionedRule {
rect: Rect
color: Color
}
value PositionedDecoration {
rect: Rect
background: Color
border_color: Color
border_left: Decimal
border_top: Decimal
border_bottom: Decimal
border_right: Decimal
}
value ChunkLayout {
lines: List<PositionedLine>
images: List<PositionedImage>
rules: List<PositionedRule>
decorations: List<PositionedDecoration>
total_height: Decimal
content_width: Decimal
}
value LayoutParams {
content_width: Decimal
font_size: Decimal
line_spacing: Decimal
base_font_family: String
}
------------------------------------------------------------
-- Contracts
------------------------------------------------------------
contract BookImageResolver {
image_size: (url: String) -> Size
resolve_image: (url: String) -> String
}
------------------------------------------------------------
-- Enumerations
------------------------------------------------------------
enum TextAlign {
justify
left
center
right
}
enum TextTransform {
none
uppercase
lowercase
capitalize
}
enum InlineKind {
text
image
line_break
}
enum BlockKind {
container_start
container_end
paragraph
rule
}
enum KpItemType {
box
glue
penalty
}
------------------------------------------------------------
-- Entities and Variants
------------------------------------------------------------
entity Book {
file_path: String
content_hash: String
title: String
author: String
chunks: List<ContentChunk>
total_chunks: chunks.count
}
entity ContentChunk {
section_href: String
blocks: List<BlockItem>
word_count: Integer
char_count: Integer
unnested_containers: Integer
is_empty: blocks.is_empty
}
entity PreparedBlock {
kind: ContainerStart | ContainerEnd | Paragraph | ImageBlock | Rule
}
variant ContainerStart : PreparedBlock {
box: BoxStyle
}
variant ContainerEnd : PreparedBlock {
box: BoxStyle
}
variant Paragraph : PreparedBlock {
align: TextAlign
text_indent: Decimal
line_height: Decimal
font_size: Decimal
marker: String
marker_style: TextStyle
kp_items: List<KpItem>
}
variant ImageBlock : PreparedBlock {
image_url: String
natural_size: Size
css_width: Decimal
css_height: Decimal
css_max_width: Decimal
}
variant Rule : PreparedBlock {
rule_color: Color
}
entity PreparedChunk {
chunk_index: Integer
blocks: List<PreparedBlock>
}
entity ReadingSession {
book: Book
params: LayoutParams
anchor_chunk: Integer
current_chunk: Integer
intra_offset: Decimal
progress: Decimal
use_book_colours: Boolean
status: visible_ready | fully_measured
layout_generation: Integer
visible_start: Integer
visible_end: Integer
layouts: List<ChunkLayout>
prepared_chunks: List<PreparedChunk>
transitions status {
visible_ready -> fully_measured
visible_ready -> visible_ready
fully_measured -> visible_ready
terminal: fully_measured
}
}
entity SavedPosition {
content_hash: String
chunk_index: Integer
intra_offset: Decimal
progress: Decimal
use_book_colours: Boolean
}
------------------------------------------------------------
-- Config
------------------------------------------------------------
config {
default_font_size: Decimal = 16.0
default_line_spacing: Decimal = 1.0
default_content_width: Decimal = 600.0
kp_tolerance: Decimal = 2.0
kp_loose_tolerance: Decimal = 10.0
kp_line_penalty: Decimal = 10.0
kp_flagged_demerits: Decimal = 100.0
kp_fitness_demerits: Decimal = 100.0
visible_window_lead: Integer = 5
visible_window_trail: Integer = 25
wcag_minimum_contrast: Decimal = 3.0
}
------------------------------------------------------------
-- Rules
------------------------------------------------------------
rule OpenBook {
when: OpenBookRequested(reader, book, saved_position?)
let restore_chunk = if saved_position != null: saved_position.chunk_index else: 0
let restore_offset = if saved_position != null: saved_position.intra_offset else: 0.0
let restore_progress = if saved_position != null: saved_position.progress else: 0.0
let book_colours = if saved_position != null: saved_position.use_book_colours else: false
let start_idx = if restore_chunk - config.visible_window_lead > 0: restore_chunk - config.visible_window_lead else: 0
let end_idx = if restore_chunk + config.visible_window_trail < book.total_chunks - 1: restore_chunk + config.visible_window_trail else: book.total_chunks - 1
ensures: ReadingSession.created(
book: book,
params: LayoutParams{
content_width: config.default_content_width,
font_size: config.default_font_size,
line_spacing: config.default_line_spacing,
base_font_family: ""
},
anchor_chunk: restore_chunk,
current_chunk: restore_chunk,
intra_offset: restore_offset,
progress: restore_progress,
use_book_colours: book_colours,
status: visible_ready,
layout_generation: 1,
visible_start: start_idx,
visible_end: end_idx,
layouts: [],
prepared_chunks: []
)
ensures: RestoreReady(chunk_index: restore_chunk, intra_offset: restore_offset)
}
rule CompleteBackgroundLayout {
when: BackgroundLayoutComputed(worker, session, generation, new_prepared, new_layouts)
requires: session.status = visible_ready
requires: session.layout_generation = generation
ensures: session.status = fully_measured
ensures: session.prepared_chunks = new_prepared
ensures: session.layouts = new_layouts
}
rule UpdateFontMetrics {
when: FontSizeChanged(reader, session, new_font_size, anchor_chunk)
requires: new_font_size > 0.0
requires: new_font_size != session.params.font_size
let next_gen = session.layout_generation + 1
let target_chunk = if anchor_chunk >= 0: anchor_chunk else: session.current_chunk
let start_idx = if target_chunk - config.visible_window_lead > 0: target_chunk - config.visible_window_lead else: 0
let end_idx = if target_chunk + config.visible_window_trail < session.book.total_chunks - 1: target_chunk + config.visible_window_trail else: session.book.total_chunks - 1
ensures: session.status = visible_ready
ensures: session.params = LayoutParams{
content_width: session.params.content_width,
font_size: new_font_size,
line_spacing: session.params.line_spacing,
base_font_family: session.params.base_font_family
}
ensures: session.anchor_chunk = target_chunk
ensures: session.layout_generation = next_gen
ensures: session.visible_start = start_idx
ensures: session.visible_end = end_idx
ensures: RestoreReady(chunk_index: target_chunk, intra_offset: session.intra_offset)
}
rule UpdateGeometryMetrics {
when: ViewportGeometryChanged(reader, session, new_content_width, new_line_spacing)
requires: new_content_width > 0.0 and new_line_spacing > 0.0
requires: new_content_width != session.params.content_width or new_line_spacing != session.params.line_spacing
ensures: session.params = LayoutParams{
content_width: new_content_width,
font_size: session.params.font_size,
line_spacing: new_line_spacing,
base_font_family: session.params.base_font_family
}
ensures: session.layout_generation = session.layout_generation + 1
}
rule EnsureChunkLayoutOnScroll {
when: ChunkScrolledIntoView(reader, session, chunk_index)
requires: session.status = visible_ready
requires: chunk_index >= 0 and chunk_index < session.book.total_chunks
@guidance
-- Synchronously resolves layout for any chunk accessed before
-- background calculation finishes to avoid flickering or blank space.
}
rule RecordReadingPosition {
when: ScrollPositionChanged(reader, session, chunk_index, intra_offset, proportion)
ensures: session.current_chunk = chunk_index
ensures: session.intra_offset = intra_offset
ensures: session.progress = proportion
ensures: SavedPosition.created(
content_hash: session.book.content_hash,
chunk_index: chunk_index,
intra_offset: intra_offset,
progress: proportion,
use_book_colours: session.use_book_colours
)
}
rule TogglePublisherColours {
when: PublisherColoursToggled(reader, session, enabled)
ensures: session.use_book_colours = enabled
ensures: SavedPosition.created(
content_hash: session.book.content_hash,
chunk_index: session.current_chunk,
intra_offset: session.intra_offset,
progress: session.progress,
use_book_colours: enabled
)
@guidance
-- Toggling publisher colours operates strictly at paint time;
-- zero re-layout, zero position shift, and instant frame update.
}
------------------------------------------------------------
-- Invariants
------------------------------------------------------------
invariant VisibleWindowReadyBeforeRender {
-- The visible window around the anchor chunk must be prepared and measured
-- before restoreReady is emitted, ensuring first-frame rendering <1ms.
}
invariant GenerationMonotonicity {
-- Background layout results are applied only if their generation token matches
-- the active session layout generation, preventing stale background jobs from overwriting newer metrics.
}
invariant ZeroReparseOnMetricsChange {
-- Changes in viewport content width or line spacing reflow prepared blocks
-- without reparsing HTML or re-extracting CSS rules.
}
invariant ContrastSafetyFallback {
-- When use_book_colours is enabled, publisher colours that do not satisfy
-- minimum WCAG contrast against the surface are overridden with high-contrast text.
}
------------------------------------------------------------
-- Actor Declarations
------------------------------------------------------------
actor Reader {
identified_by: User
}
------------------------------------------------------------
-- Surfaces
------------------------------------------------------------
surface LibrarySurface {
facing reader: Reader
provides:
OpenBookRequested(reader, book, saved_position?)
}
surface ReadingSurface {
facing reader: Reader
context session: ReadingSession
exposes:
session.book.title
session.book.author
session.status
session.current_chunk
session.progress
session.use_book_colours
provides:
FontSizeChanged(reader, session, new_font_size, anchor_chunk)
ViewportGeometryChanged(reader, session, new_content_width, new_line_spacing)
ChunkScrolledIntoView(reader, session, chunk_index)
ScrollPositionChanged(reader, session, chunk_index, intra_offset, proportion)
PublisherColoursToggled(reader, session, enabled)
}
surface LayoutEngineIntegration {
facing worker: User
contracts:
demands BookImageResolver
provides:
BackgroundLayoutComputed(worker, session, generation, new_prepared, new_layouts)
@guarantee ThreadSafety
-- Knuth-Plass line breaking and block preparation operate off-thread
-- without accessing GUI state or main thread objects.
}
------------------------------------------------------------
-- Deferred Specifications
------------------------------------------------------------
deferred CssCascade.cascade -- see: css-cascade.allium
deferred HtmlBlockParser.parse_chunks -- see: html-block-parser.allium
------------------------------------------------------------
-- Open Questions
------------------------------------------------------------
open question "Pagination spread alignment - should two-page spread simulation be supported in text mode or stay restricted to manga mode?"
@@ -24,22 +24,54 @@ struct PositionedWordRun {
bool underline = false;
bool strikeOut = false;
bool overline = false;
bool operator==(const PositionedWordRun &o) const
{
return text == o.text
&& rect == o.rect
&& qFuzzyCompare(baselineY, o.baselineY)
&& font == o.font
&& color == o.color
&& background == o.background
&& surfaceBackground == o.surfaceBackground
&& link == o.link
&& underline == o.underline
&& strikeOut == o.strikeOut
&& overline == o.overline;
}
};
struct PositionedLine {
QRectF rect;
qreal baselineY = 0;
QVector<PositionedWordRun> runs;
bool operator==(const PositionedLine &o) const
{
return rect == o.rect
&& qFuzzyCompare(baselineY, o.baselineY)
&& runs == o.runs;
}
};
struct PositionedImage {
QString url;
QRectF targetRect;
bool operator==(const PositionedImage &o) const
{
return url == o.url && targetRect == o.targetRect;
}
};
struct PositionedRule {
QRectF rect;
QColor color;
bool operator==(const PositionedRule &o) const
{
return rect == o.rect && color == o.color;
}
};
struct PositionedDecoration {
@@ -50,6 +82,17 @@ struct PositionedDecoration {
qreal borderTop = 0;
qreal borderBottom = 0;
qreal borderRight = 0;
bool operator==(const PositionedDecoration &o) const
{
return rect == o.rect
&& background == o.background
&& borderColor == o.borderColor
&& qFuzzyCompare(borderLeft, o.borderLeft)
&& qFuzzyCompare(borderTop, o.borderTop)
&& qFuzzyCompare(borderBottom, o.borderBottom)
&& qFuzzyCompare(borderRight, o.borderRight);
}
};
struct ChunkLayout {
@@ -59,6 +102,16 @@ struct ChunkLayout {
QVector<PositionedDecoration> decorations;
qreal totalHeight = 0;
qreal contentWidth = 0;
bool operator==(const ChunkLayout &o) const
{
return lines == o.lines
&& images == o.images
&& rules == o.rules
&& decorations == o.decorations
&& qFuzzyCompare(totalHeight, o.totalHeight)
&& qFuzzyCompare(contentWidth, o.contentWidth);
}
};
struct LayoutParams {
@@ -66,6 +119,14 @@ struct LayoutParams {
qreal fontSize = 16;
qreal lineSpacing = 1.0;
QString baseFontFamily;
bool operator==(const LayoutParams &o) const
{
return qFuzzyCompare(contentWidth, o.contentWidth)
&& qFuzzyCompare(fontSize, o.fontSize)
&& qFuzzyCompare(lineSpacing, o.lineSpacing)
&& baseFontFamily == o.baseFontFamily;
}
};
namespace ChunkLayoutEngine {
@@ -54,6 +54,17 @@ struct InlineItem {
qreal cssWidth = -1; // px, -1 = auto
qreal cssHeight = -1;
qreal cssMaxWidth = -1;
bool operator==(const InlineItem &o) const
{
return kind == o.kind
&& text == o.text
&& style == o.style
&& imageUrl == o.imageUrl
&& qFuzzyCompare(cssWidth, o.cssWidth)
&& qFuzzyCompare(cssHeight, o.cssHeight)
&& qFuzzyCompare(cssMaxWidth, o.cssMaxWidth);
}
};
struct BoxStyle {
@@ -72,6 +83,24 @@ struct BoxStyle {
{
return paddingBottom > 0 || borderBottom > 0 || borderLeft > 0 || borderRight > 0 || background.isValid();
}
bool operator==(const BoxStyle &o) const
{
return qFuzzyCompare(marginTop, o.marginTop)
&& qFuzzyCompare(marginBottom, o.marginBottom)
&& qFuzzyCompare(marginLeft, o.marginLeft)
&& qFuzzyCompare(marginRight, o.marginRight)
&& qFuzzyCompare(paddingTop, o.paddingTop)
&& qFuzzyCompare(paddingBottom, o.paddingBottom)
&& qFuzzyCompare(paddingLeft, o.paddingLeft)
&& qFuzzyCompare(paddingRight, o.paddingRight)
&& qFuzzyCompare(borderTop, o.borderTop)
&& qFuzzyCompare(borderBottom, o.borderBottom)
&& qFuzzyCompare(borderLeft, o.borderLeft)
&& qFuzzyCompare(borderRight, o.borderRight)
&& borderColor == o.borderColor
&& background == o.background;
}
};
struct BlockItem {
@@ -90,6 +119,21 @@ struct BlockItem {
QVector<InlineItem> inlines;
QColor ruleColor; // Rule only; invalid = theme dim colour
bool operator==(const BlockItem &o) const
{
return kind == o.kind
&& box == o.box
&& align == o.align
&& qFuzzyCompare(textIndent, o.textIndent)
&& qFuzzyCompare(lineHeight, o.lineHeight)
&& qFuzzyCompare(fontSize, o.fontSize)
&& preformatted == o.preformatted
&& marker == o.marker
&& markerStyle == o.markerStyle
&& inlines == o.inlines
&& ruleColor == o.ruleColor;
}
};
struct ParseParams {
@@ -105,6 +149,15 @@ struct ContentChunk {
int unnestedContainers = 0;
bool isEmpty() const { return blocks.isEmpty(); }
bool operator==(const ContentChunk &o) const
{
return sectionHref == o.sectionHref
&& blocks == o.blocks
&& wordCount == o.wordCount
&& charCount == o.charCount
&& unnestedContainers == o.unnestedContainers;
}
};
class QDomElement;
+11
View File
@@ -36,6 +36,17 @@ struct Item {
{
Item i; i.type = ItemType::Penalty; i.width = w; i.penalty = p; i.flagged = flagged; i.tag = tag; return i;
}
bool operator==(const Item &o) const
{
return type == o.type
&& qFuzzyCompare(width, o.width)
&& qFuzzyCompare(stretch, o.stretch)
&& qFuzzyCompare(shrink, o.shrink)
&& qFuzzyCompare(penalty, o.penalty)
&& flagged == o.flagged
&& tag == o.tag;
}
};
struct Params {
+10
View File
@@ -11,6 +11,16 @@ struct BookPosition {
bool pageShift = true; // Comic mode only
bool mangaRTL = true; // Comic mode only
bool useBookColours = false; // Text mode only
bool operator==(const BookPosition &o) const
{
return chunkIndex == o.chunkIndex
&& qFuzzyCompare(intraOffset, o.intraOffset)
&& qFuzzyCompare(progress, o.progress)
&& pageShift == o.pageShift
&& mangaRTL == o.mangaRTL
&& useBookColours == o.useBookColours;
}
};
class BookPositionStore {
+956
View File
@@ -0,0 +1,956 @@
#include <QtTest>
#include <QDir>
#include <QSettings>
#include <QSignalSpy>
#include <QTemporaryFile>
#include "backend/AppState.h"
#include "backend/FormatReader.h"
#include "backend/ReadingModel.h"
#include "backend/reading/BookImageResolver.h"
#include "backend/reading/KnuthPlassItem.h"
#include "backend/reading/layout/ChunkLayoutEngine.h"
#include "backend/reading/layout/HtmlBlockParser.h"
#include "backend/reading/layout/KnuthPlass.h"
#include "backend/state/BookPositionStore.h"
// Mock BookImageResolver to test contract BookImageResolver
class MockBookImageResolver : public IBookImageResolver {
public:
QImage resolveImage(const QString &imageUrl) override
{
if (imageUrl == QLatin1String("image://epub/test.png")) {
QImage img(100, 50, QImage::Format_RGB32);
img.fill(Qt::red);
return img;
}
return {};
}
QSizeF imageSize(const QString &imageUrl) override
{
if (imageUrl == QLatin1String("image://epub/test.png")) {
return QSizeF(100, 50);
}
return {};
}
};
// Mock Reader for Text Mode
class SpecTestTextReader : public FormatReader {
public:
explicit SpecTestTextReader(int chunkCount = 40)
: m_count(chunkCount)
{
m_chunks.reserve(m_count);
for (int i = 0; i < m_count; ++i) {
ContentChunk chunk;
chunk.sectionHref = QStringLiteral("text/ch_%1.xhtml").arg(i);
chunk.wordCount = 10;
chunk.charCount = 60;
chunk.unnestedContainers = 0;
BlockItem p;
p.kind = BlockItem::Kind::Paragraph;
p.fontSize = 16.0;
p.lineHeight = 1.2;
p.align = TextAlign::Justify;
InlineItem t;
t.kind = InlineItem::Kind::Text;
t.text = QStringLiteral("Chunk content %1 with words to layout").arg(i);
p.inlines.append(t);
chunk.blocks.append(p);
m_chunks.append(chunk);
}
}
ReadingMode mode() const override { return ReadingMode::Text; }
bool open(const QString &) override { return true; }
QString lastError() const override { return {}; }
QString filePath() const override { return QStringLiteral("/path/to/spec_book.epub"); }
QString title() const override { return QStringLiteral("Spec Test Book"); }
QString author() const override { return QStringLiteral("Spec Author"); }
QString coverImageUrl() const override { return QStringLiteral("image://epub/cover.png"); }
QByteArray contentHash() const override { return QByteArrayLiteral("spec_content_hash_123"); }
bool loadMetadata(const QString &) override { return true; }
QVector<ContentChunk> chunks() const override { return m_chunks; }
private:
int m_count;
QVector<ContentChunk> m_chunks;
};
// Represents User / Actor
struct SpecUser {
QString id;
};
class TextLayoutEngineSpecTest : public QObject {
Q_OBJECT
private:
struct TestContext {
QTemporaryFile tempFile;
QSettings *settings = nullptr;
AppState *appState = nullptr;
BookPositionStore *positionStore = nullptr;
TestContext() {
tempFile.setFileTemplate(QDir::tempPath() + QStringLiteral("/spec-test-XXXXXX.ini"));
(void)tempFile.open();
tempFile.close();
settings = new QSettings(tempFile.fileName(), QSettings::IniFormat);
appState = new AppState(*settings);
positionStore = new BookPositionStore(*appState);
}
~TestContext() {
delete positionStore;
delete appState;
delete settings;
}
};
private slots:
// Obligation: entity-fields.User
void testUserEntityFields()
{
SpecUser user;
user.id = QStringLiteral("user-1");
QCOMPARE(user.id, QStringLiteral("user-1"));
}
// Obligations: value-equality.Size, entity-fields.Size
void testSizeValueEqualityAndFields()
{
QSizeF s1(200.0, 100.0);
QSizeF s2(200.0, 100.0);
QSizeF s3(300.0, 100.0);
QCOMPARE(s1.width(), 200.0);
QCOMPARE(s1.height(), 100.0);
QCOMPARE(s1, s2);
QVERIFY(s1 != s3);
}
// Obligations: value-equality.Rect, entity-fields.Rect
void testRectValueEqualityAndFields()
{
QRectF r1(10.0, 20.0, 100.0, 50.0);
QRectF r2(10.0, 20.0, 100.0, 50.0);
QRectF r3(15.0, 20.0, 100.0, 50.0);
QCOMPARE(r1.x(), 10.0);
QCOMPARE(r1.y(), 20.0);
QCOMPARE(r1.width(), 100.0);
QCOMPARE(r1.height(), 50.0);
QCOMPARE(r1, r2);
QVERIFY(r1 != r3);
}
// Obligations: value-equality.Color, entity-fields.Color
void testColorValueEqualityAndFields()
{
QColor c1(255, 128, 0, 255);
QColor c2(255, 128, 0, 255);
QColor c3(0, 0, 0, 255);
QCOMPARE(c1.red(), 255);
QCOMPARE(c1.green(), 128);
QCOMPARE(c1.blue(), 0);
QCOMPARE(c1.alpha(), 255);
QVERIFY(c1.isValid());
QCOMPARE(c1, c2);
QVERIFY(c1 != c3);
}
// Obligations: value-equality.TextStyle, entity-fields.TextStyle
void testTextStyleValueEqualityAndFields()
{
TextStyle st1;
st1.fontFamilies = {QStringLiteral("Serif")};
st1.fontSize = 18.0;
st1.weight = 700;
st1.italic = true;
st1.smallCaps = false;
st1.transform = TextTransform::Uppercase;
st1.letterSpacing = 1.5;
st1.underline = true;
st1.strikeOut = false;
st1.overline = false;
st1.link = true;
st1.color = QColor(Qt::darkGreen);
st1.background = QColor(Qt::yellow);
st1.baselineShift = 2.0;
TextStyle st2 = st1;
QCOMPARE(st1, st2);
st2.fontSize = 20.0;
QVERIFY(!(st1 == st2));
}
// Obligations: value-equality.BoxStyle, entity-fields.BoxStyle
void testBoxStyleValueEqualityAndFields()
{
BoxStyle b1;
b1.marginTop = 10;
b1.marginBottom = 10;
b1.marginLeft = 5;
b1.marginRight = 5;
b1.paddingTop = 4;
b1.paddingBottom = 4;
b1.paddingLeft = 8;
b1.paddingRight = 8;
b1.borderTop = 1;
b1.borderBottom = 1;
b1.borderLeft = 2;
b1.borderRight = 1;
b1.borderColor = QColor(Qt::gray);
b1.background = QColor(Qt::white);
QVERIFY(b1.blocksTopCollapse());
QVERIFY(b1.blocksBottomCollapse());
BoxStyle b2 = b1;
QCOMPARE(b1, b2);
b2.paddingTop = 0;
QVERIFY(!(b1 == b2));
BoxStyle bEmpty;
QVERIFY(!bEmpty.blocksTopCollapse());
QVERIFY(!bEmpty.blocksBottomCollapse());
}
// Obligations: value-equality.InlineItem, entity-fields.InlineItem
void testInlineItemValueEqualityAndFields()
{
InlineItem i1;
i1.kind = InlineItem::Kind::Image;
i1.text = QStringLiteral("caption");
i1.imageUrl = QStringLiteral("image://epub/fig1.png");
i1.cssWidth = 150;
i1.cssHeight = 75;
i1.cssMaxWidth = 300;
InlineItem i2 = i1;
QCOMPARE(i1, i2);
i2.imageUrl = QStringLiteral("image://epub/fig2.png");
QVERIFY(!(i1 == i2));
}
// Obligations: value-equality.KpItem, entity-fields.KpItem
void testKpItemValueEqualityAndFields()
{
KnuthPlass::Item k1 = KnuthPlass::Item::glue(10.0, 3.0, 2.0, 42);
KnuthPlass::Item k2 = KnuthPlass::Item::glue(10.0, 3.0, 2.0, 42);
KnuthPlass::Item k3 = KnuthPlass::Item::box(10.0, 42);
QCOMPARE(k1.type, KnuthPlass::ItemType::Glue);
QCOMPARE(k1.width, 10.0);
QCOMPARE(k1.stretch, 3.0);
QCOMPARE(k1.shrink, 2.0);
QCOMPARE(k1.tag, 42);
QCOMPARE(k1, k2);
QVERIFY(!(k1 == k3));
}
// Obligations: value-equality.BlockItem, entity-fields.BlockItem
void testBlockItemValueEqualityAndFields()
{
BlockItem blk1;
blk1.kind = BlockItem::Kind::Paragraph;
blk1.align = TextAlign::Center;
blk1.textIndent = 20.0;
blk1.lineHeight = 1.5;
blk1.fontSize = 16.0;
blk1.preformatted = false;
blk1.marker = QStringLiteral("1.");
blk1.ruleColor = QColor(Qt::red);
BlockItem blk2 = blk1;
QCOMPARE(blk1, blk2);
blk2.align = TextAlign::Left;
QVERIFY(!(blk1 == blk2));
}
// Obligations: value-equality.PositionedWordRun, entity-fields.PositionedWordRun
void testPositionedWordRunValueEqualityAndFields()
{
PositionedWordRun r1;
r1.text = QStringLiteral("hello");
r1.rect = QRectF(0, 0, 40, 16);
r1.baselineY = 12.0;
r1.color = QColor(Qt::black);
r1.background = QColor(Qt::transparent);
r1.surfaceBackground = QColor(Qt::white);
r1.link = false;
PositionedWordRun r2 = r1;
QCOMPARE(r1, r2);
r2.text = QStringLiteral("world");
QVERIFY(!(r1 == r2));
}
// Obligations: value-equality.PositionedLine, entity-fields.PositionedLine
void testPositionedLineValueEqualityAndFields()
{
PositionedLine l1;
l1.rect = QRectF(0, 0, 400, 20);
l1.baselineY = 15.0;
PositionedWordRun r;
r.text = QStringLiteral("line run");
l1.runs.append(r);
PositionedLine l2 = l1;
QCOMPARE(l1, l2);
l2.baselineY = 16.0;
QVERIFY(!(l1 == l2));
}
// Obligations: value-equality.PositionedImage, entity-fields.PositionedImage
void testPositionedImageValueEqualityAndFields()
{
PositionedImage img1;
img1.url = QStringLiteral("image://epub/pic.png");
img1.targetRect = QRectF(0, 0, 200, 100);
PositionedImage img2 = img1;
QCOMPARE(img1, img2);
img2.url = QStringLiteral("image://epub/other.png");
QVERIFY(!(img1 == img2));
}
// Obligations: value-equality.PositionedRule, entity-fields.PositionedRule
void testPositionedRuleValueEqualityAndFields()
{
PositionedRule r1;
r1.rect = QRectF(0, 10, 400, 1);
r1.color = QColor(Qt::gray);
PositionedRule r2 = r1;
QCOMPARE(r1, r2);
r2.rect = QRectF(0, 10, 500, 1);
QVERIFY(!(r1 == r2));
}
// Obligations: value-equality.PositionedDecoration, entity-fields.PositionedDecoration
void testPositionedDecorationValueEqualityAndFields()
{
PositionedDecoration d1;
d1.rect = QRectF(0, 0, 400, 80);
d1.background = QColor(Qt::lightGray);
d1.borderColor = QColor(Qt::blue);
d1.borderLeft = 3.0;
PositionedDecoration d2 = d1;
QCOMPARE(d1, d2);
d2.borderLeft = 4.0;
QVERIFY(!(d1 == d2));
}
// Obligations: value-equality.ChunkLayout, entity-fields.ChunkLayout
void testChunkLayoutValueEqualityAndFields()
{
ChunkLayout lay1;
lay1.totalHeight = 120.0;
lay1.contentWidth = 400.0;
PositionedRule rule;
rule.rect = QRectF(0, 0, 400, 1);
lay1.rules.append(rule);
ChunkLayout lay2 = lay1;
QCOMPARE(lay1, lay2);
lay2.totalHeight = 130.0;
QVERIFY(!(lay1 == lay2));
}
// Obligations: value-equality.LayoutParams, entity-fields.LayoutParams
void testLayoutParamsValueEqualityAndFields()
{
LayoutParams p1;
p1.contentWidth = 500;
p1.fontSize = 18;
p1.lineSpacing = 1.3;
p1.baseFontFamily = QStringLiteral("Georgia");
LayoutParams p2 = p1;
QCOMPARE(p1, p2);
p2.fontSize = 16;
QVERIFY(!(p1 == p2));
}
// Obligation: entity-fields.Book
void testBookEntityFields()
{
SpecTestTextReader reader(10);
QCOMPARE(reader.filePath(), QStringLiteral("/path/to/spec_book.epub"));
QCOMPARE(reader.contentHash(), QByteArrayLiteral("spec_content_hash_123"));
QCOMPARE(reader.title(), QStringLiteral("Spec Test Book"));
QCOMPARE(reader.author(), QStringLiteral("Spec Author"));
QCOMPARE(reader.chunks().size(), 10);
}
// Obligation: entity-fields.ContentChunk
void testContentChunkEntityFields()
{
ContentChunk chunk;
chunk.sectionHref = QStringLiteral("sec1.xhtml");
chunk.wordCount = 100;
chunk.charCount = 500;
chunk.unnestedContainers = 1;
QVERIFY(chunk.isEmpty());
BlockItem blk;
chunk.blocks.append(blk);
QVERIFY(!chunk.isEmpty());
ContentChunk chunk2 = chunk;
QCOMPARE(chunk, chunk2);
}
// Obligations: entity-fields.PreparedBlock, sum-type-variant.ContainerStart, sum-type-variant.ContainerEnd,
// sum-type-variant.Paragraph, sum-type-variant.ImageBlock, sum-type-variant.Rule
void testPreparedBlockAndVariants()
{
using PreparedBlock = ChunkLayoutEngine::PreparedBlock;
// ContainerStart variant
PreparedBlock cs;
cs.kind = PreparedBlock::Kind::ContainerStart;
cs.box.borderLeft = 3.0;
QCOMPARE(cs.kind, PreparedBlock::Kind::ContainerStart);
QCOMPARE(cs.box.borderLeft, 3.0);
// ContainerEnd variant
PreparedBlock ce;
ce.kind = PreparedBlock::Kind::ContainerEnd;
ce.box.marginBottom = 10.0;
QCOMPARE(ce.kind, PreparedBlock::Kind::ContainerEnd);
QCOMPARE(ce.box.marginBottom, 10.0);
// Paragraph variant
PreparedBlock p;
p.kind = PreparedBlock::Kind::Paragraph;
p.paragraph.align = TextAlign::Justify;
p.paragraph.textIndent = 16.0;
p.paragraph.lineHeight = 1.2;
p.paragraph.fontSize = 16.0;
p.paragraph.marker = QStringLiteral("*");
p.paragraph.kpItems.append(KnuthPlass::Item::box(20.0));
QCOMPARE(p.kind, PreparedBlock::Kind::Paragraph);
QCOMPARE(p.paragraph.align, TextAlign::Justify);
QCOMPARE(p.paragraph.textIndent, 16.0);
QCOMPARE(p.paragraph.kpItems.size(), 1);
// ImageBlock variant
PreparedBlock img;
img.kind = PreparedBlock::Kind::ImageBlock;
img.imageBlock.imageUrl = QStringLiteral("image://epub/fig.png");
img.imageBlock.naturalSize = QSizeF(200, 100);
img.imageBlock.cssWidth = 150.0;
img.imageBlock.cssHeight = 75.0;
img.imageBlock.cssMaxWidth = 400.0;
QCOMPARE(img.kind, PreparedBlock::Kind::ImageBlock);
QCOMPARE(img.imageBlock.imageUrl, QStringLiteral("image://epub/fig.png"));
QCOMPARE(img.imageBlock.naturalSize, QSizeF(200, 100));
// Rule variant
PreparedBlock r;
r.kind = PreparedBlock::Kind::Rule;
r.ruleColor = QColor(Qt::magenta);
QCOMPARE(r.kind, PreparedBlock::Kind::Rule);
QCOMPARE(r.ruleColor, QColor(Qt::magenta));
}
// Obligation: entity-fields.PreparedChunk
void testPreparedChunkEntityFields()
{
ChunkLayoutEngine::PreparedChunk prep;
ChunkLayoutEngine::PreparedBlock blk;
blk.kind = ChunkLayoutEngine::PreparedBlock::Kind::Rule;
prep.blocks.append(blk);
QCOMPARE(prep.blocks.size(), 1);
QCOMPARE(prep.blocks[0].kind, ChunkLayoutEngine::PreparedBlock::Kind::Rule);
}
// Obligation: entity-fields.ReadingSession
void testReadingSessionEntityFields()
{
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(20);
model.setReader(&reader);
QVERIFY(model.isTextMode());
QCOMPARE(model.totalPages(), 20);
QCOMPARE(model.currentPage(), 1);
QCOMPARE(model.progress(), 0.0);
QCOMPARE(model.useBookColours(), false);
}
// Obligations: value-equality.SavedPosition, entity-fields.SavedPosition
void testSavedPositionValueEqualityAndFields()
{
BookPosition pos1;
pos1.chunkIndex = 5;
pos1.intraOffset = 42.5;
pos1.progress = 0.25;
pos1.pageShift = true;
pos1.mangaRTL = false;
pos1.useBookColours = true;
QCOMPARE(pos1.chunkIndex, 5);
QCOMPARE(pos1.intraOffset, 42.5);
QCOMPARE(pos1.progress, 0.25);
QCOMPARE(pos1.useBookColours, true);
BookPosition pos2 = pos1;
QCOMPARE(pos1, pos2);
pos2.chunkIndex = 6;
QVERIFY(!(pos1 == pos2));
}
// Obligations: enum-comparable.TextAlign, enum-comparable.TextTransform,
// enum-comparable.InlineKind, enum-comparable.BlockKind, enum-comparable.KpItemType
void testEnumsComparable()
{
QVERIFY(TextAlign::Justify != TextAlign::Left);
QVERIFY(TextAlign::Left == TextAlign::Left);
QVERIFY(TextAlign::Center != TextAlign::Right);
QVERIFY(TextTransform::None != TextTransform::Uppercase);
QVERIFY(TextTransform::Lowercase != TextTransform::Capitalize);
QVERIFY(InlineItem::Kind::Text != InlineItem::Kind::Image);
QVERIFY(InlineItem::Kind::Image != InlineItem::Kind::LineBreak);
QVERIFY(BlockItem::Kind::ContainerStart != BlockItem::Kind::ContainerEnd);
QVERIFY(BlockItem::Kind::Paragraph != BlockItem::Kind::Rule);
QVERIFY(KnuthPlass::ItemType::Box != KnuthPlass::ItemType::Glue);
QVERIFY(KnuthPlass::ItemType::Glue != KnuthPlass::ItemType::Penalty);
}
// Obligations: contract-signature.BookImageResolver.image_size, contract-signature.BookImageResolver.resolve_image
void testBookImageResolverContract()
{
MockBookImageResolver resolver;
QSizeF size = resolver.imageSize(QStringLiteral("image://epub/test.png"));
QCOMPARE(size, QSizeF(100, 50));
QImage img = resolver.resolveImage(QStringLiteral("image://epub/test.png"));
QVERIFY(!img.isNull());
QCOMPARE(img.size(), QSize(100, 50));
QSizeF emptySize = resolver.imageSize(QStringLiteral("image://epub/missing.png"));
QVERIFY(emptySize.isEmpty());
}
// Obligations: config-default.default_font_size, config-default.default_line_spacing,
// config-default.default_content_width, config-default.kp_tolerance, config-default.kp_loose_tolerance,
// config-default.kp_line_penalty, config-default.kp_flagged_demerits, config-default.kp_fitness_demerits,
// config-default.visible_window_lead, config-default.visible_window_trail, config-default.wcag_minimum_contrast
void testConfigDefaults()
{
LayoutParams defParams;
QCOMPARE(defParams.fontSize, 16.0);
QCOMPARE(defParams.lineSpacing, 1.0);
QCOMPARE(defParams.contentWidth, 600.0);
KnuthPlass::Params kpParams;
QCOMPARE(kpParams.tolerance, 2.0);
QCOMPARE(kpParams.looseTolerance, 10.0);
QCOMPARE(kpParams.linePenalty, 10.0);
QCOMPARE(kpParams.flaggedDemerits, 100.0);
QCOMPARE(kpParams.fitnessDemerits, 100.0);
// Visible window lead = 5, trail = 25
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(40);
model.setReader(&reader);
// Verify initial visible window [0..25] measured synchronously
for (int i = 0; i <= 25; ++i) {
QVERIFY(model.data(model.index(i, 0), ReadingModel::PixelHeightRole).toReal() > 0);
}
// WCAG minimum contrast threshold is 3.0
QColor light(240, 240, 240);
QColor dark(20, 20, 20);
qreal cr = KnuthPlassItem::contrastRatio(light, dark);
QVERIFY(cr > 3.0);
}
// Obligations: transition-edge.ReadingSession.status.visible_ready_to_fully_measured,
// transition-edge.ReadingSession.status.visible_ready_to_visible_ready,
// transition-edge.ReadingSession.status.fully_measured_to_visible_ready,
// transition-rejected.ReadingSession.status.1,
// transition-terminal.ReadingSession.status.fully_measured
void testStateTransitions()
{
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(30);
// 1. Initial open enters visible_ready, starts measuring
model.setReader(&reader);
QVERIFY(model.measuring()); // status: visible_ready
// 2. While visible_ready, updating font metrics transitions visible_ready -> visible_ready
model.updateLayoutMetrics(600, 18, 1.0);
QVERIFY(model.measuring());
// 3. Wait for background calculation to complete -> transitions visible_ready -> fully_measured
QTRY_VERIFY_WITH_TIMEOUT(!model.measuring(), 5000);
QVERIFY(!model.measuring()); // fully_measured is terminal steady state
// 4. Updating font metrics from terminal fully_measured transitions back to visible_ready
model.updateLayoutMetrics(600, 20, 1.0);
QVERIFY(model.measuring()); // visible_ready
// Wait until it returns to fully_measured terminal state
QTRY_VERIFY_WITH_TIMEOUT(!model.measuring(), 5000);
QVERIFY(!model.measuring());
}
// Obligations: rule-success.OpenBook, rule-entity-creation.OpenBook.1
void testRuleOpenBook()
{
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(25);
QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady);
model.setReader(&reader);
QVERIFY(model.isTextMode());
QCOMPARE(model.totalPages(), 25);
QCOMPARE(restoreSpy.count(), 1);
QCOMPARE(restoreSpy.first().at(0).toInt(), 0);
QCOMPARE(restoreSpy.first().at(1).toReal(), 0.0);
}
// Obligations: rule-success.CompleteBackgroundLayout, rule-failure.CompleteBackgroundLayout.1,
// rule-failure.CompleteBackgroundLayout.2
void testRuleCompleteBackgroundLayout()
{
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(35);
model.setReader(&reader);
// rule-failure.CompleteBackgroundLayout.1 & 2:
// When model is reset or a new generation is triggered, stale background task results
// must not overwrite current layout.
int initialGenerationSpy = model.measuring();
QVERIFY(initialGenerationSpy);
// Trigger font change immediately before background finishes to increment generation
model.updateLayoutMetrics(600, 22, 1.0);
// Complete background layout applies for the latest generation only
QTRY_VERIFY_WITH_TIMEOUT(!model.measuring(), 5000);
// All rows now measured at the new font size
auto lay0 = model.data(model.index(0, 0), ReadingModel::LayoutRole).value<ChunkLayout>();
QVERIFY(!lay0.lines.isEmpty());
}
// Obligations: rule-success.UpdateFontMetrics, rule-failure.UpdateFontMetrics.1,
// rule-failure.UpdateFontMetrics.2
void testRuleUpdateFontMetrics()
{
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(20);
model.setReader(&reader);
QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady);
// rule-failure.UpdateFontMetrics.1: new_font_size <= 0 rejected
model.updateLayoutMetrics(600, -5, 1.0);
QCOMPARE(restoreSpy.count(), 0);
// rule-failure.UpdateFontMetrics.2: same font size and geometry rejected
model.updateLayoutMetrics(600, 16, 1.0);
QCOMPARE(restoreSpy.count(), 0);
// rule-success.UpdateFontMetrics: valid new font size triggers visible_ready & restoreReady
model.updateLayoutMetrics(600, 20, 1.0, 3);
QCOMPARE(restoreSpy.count(), 1);
QCOMPARE(restoreSpy.first().at(0).toInt(), 3);
}
// Obligations: rule-success.UpdateGeometryMetrics, rule-failure.UpdateGeometryMetrics.1,
// rule-failure.UpdateGeometryMetrics.2
void testRuleUpdateGeometryMetrics()
{
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(20);
model.setReader(&reader);
QSignalSpy dataSpy(&model, &ReadingModel::dataChanged);
// rule-failure.UpdateGeometryMetrics.1: new_content_width <= 0 or new_line_spacing <= 0 rejected
model.updateLayoutMetrics(-100, 16, 1.0);
QCOMPARE(dataSpy.count(), 0);
model.updateLayoutMetrics(600, 16, 0.0);
QCOMPARE(dataSpy.count(), 0);
// rule-failure.UpdateGeometryMetrics.2: unchanged metrics rejected
model.updateLayoutMetrics(600, 16, 1.0);
QCOMPARE(dataSpy.count(), 0);
// rule-success.UpdateGeometryMetrics: changed width or line spacing reflows
model.updateLayoutMetrics(800, 16, 1.4);
QVERIFY(dataSpy.count() >= 1);
auto lay0 = model.data(model.index(0, 0), ReadingModel::LayoutRole).value<ChunkLayout>();
QCOMPARE(lay0.contentWidth, 800.0);
}
// Obligations: rule-success.EnsureChunkLayoutOnScroll, rule-failure.EnsureChunkLayoutOnScroll.1,
// rule-failure.EnsureChunkLayoutOnScroll.2
void testRuleEnsureChunkLayoutOnScroll()
{
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(50);
model.setReader(&reader);
// Far-away chunk 45 is not initially laid out before background completes
// rule-success: querying chunk 45 computes its layout on demand
qreal height45 = model.data(model.index(45, 0), ReadingModel::PixelHeightRole).toReal();
QVERIFY(height45 > 0);
auto lay45 = model.data(model.index(45, 0), ReadingModel::LayoutRole).value<ChunkLayout>();
QVERIFY(!lay45.lines.isEmpty());
// rule-failure.1: requesting again is already measured (no re-measurement needed)
qreal height45Again = model.data(model.index(45, 0), ReadingModel::PixelHeightRole).toReal();
QCOMPARE(height45, height45Again);
// rule-failure.2: out of bounds index rejected safely
QVERIFY(!model.data(model.index(-1, 0), ReadingModel::LayoutRole).isValid());
QVERIFY(!model.data(model.index(100, 0), ReadingModel::LayoutRole).isValid());
}
// Obligations: rule-success.RecordReadingPosition, rule-entity-creation.RecordReadingPosition.1
void testRuleRecordReadingPosition()
{
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(20);
model.setReader(&reader);
QSignalSpy savedSpy(&model, &ReadingModel::positionSaved);
model.setScrollPosition(4, 18.5, 0.2);
QCOMPARE(savedSpy.count(), 1);
QCOMPARE(model.currentPage(), 5);
QCOMPARE(model.progress(), 0.2);
BookPosition loaded = ctx.positionStore->load(reader.contentHash());
QCOMPARE(loaded.chunkIndex, 4);
QCOMPARE(loaded.intraOffset, 18.5);
QCOMPARE(loaded.progress, 0.2);
}
// Obligations: rule-success.TogglePublisherColours, rule-entity-creation.TogglePublisherColours.1
void testRuleTogglePublisherColours()
{
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(20);
model.setReader(&reader);
QSignalSpy colourSpy(&model, &ReadingModel::useBookColoursChanged);
QCOMPARE(model.useBookColours(), false);
model.setUseBookColours(true);
QCOMPARE(model.useBookColours(), true);
QCOMPARE(colourSpy.count(), 1);
BookPosition loaded = ctx.positionStore->load(reader.contentHash());
QCOMPARE(loaded.useBookColours, true);
model.setUseBookColours(false);
QCOMPARE(model.useBookColours(), false);
BookPosition loadedAfter = ctx.positionStore->load(reader.contentHash());
QCOMPARE(loadedAfter.useBookColours, false);
}
// Obligation: invariant.VisibleWindowReadyBeforeRender
void testInvariantVisibleWindowReadyBeforeRender()
{
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(30);
QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady);
model.setReader(&reader);
// restoreReady emitted synchronously on open
QCOMPARE(restoreSpy.count(), 1);
int anchor = restoreSpy.first().at(0).toInt();
QCOMPARE(anchor, 0);
// Visible window [0..25] is immediately ready
for (int i = 0; i <= 25; ++i) {
auto lay = model.data(model.index(i, 0), ReadingModel::LayoutRole).value<ChunkLayout>();
QVERIFY(!lay.lines.isEmpty());
}
}
// Obligation: invariant.GenerationMonotonicity
void testInvariantGenerationMonotonicity()
{
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(40);
model.setReader(&reader);
// Fire multiple font updates in rapid succession
model.updateLayoutMetrics(600, 18, 1.0);
model.updateLayoutMetrics(600, 22, 1.0);
model.updateLayoutMetrics(600, 26, 1.0);
QTRY_VERIFY_WITH_TIMEOUT(!model.measuring(), 5000);
// Final layout must reflect the last generation (font size 26)
auto lay0 = model.data(model.index(0, 0), ReadingModel::LayoutRole).value<ChunkLayout>();
QVERIFY(!lay0.lines.isEmpty());
// Verify line height is larger for 26pt than default 16pt
QVERIFY(lay0.lines[0].rect.height() > 20.0);
}
// Obligation: invariant.ZeroReparseOnMetricsChange
void testInvariantZeroReparseOnMetricsChange()
{
// When layoutPreparedChunk is called with different LayoutParams,
// it reflows the prepared block without needing the raw HTML string or XML DOM.
ContentChunk chunk;
chunk.sectionHref = QStringLiteral("sec1.xhtml");
BlockItem p;
p.kind = BlockItem::Kind::Paragraph;
p.fontSize = 16.0;
InlineItem txt;
txt.kind = InlineItem::Kind::Text;
txt.text = QStringLiteral("First line of text that wraps based on available width.");
p.inlines.append(txt);
chunk.blocks.append(p);
auto prep = ChunkLayoutEngine::prepareChunk(chunk, 16.0);
QCOMPARE(prep.blocks.size(), 1);
LayoutParams pNarrow{300.0, 16.0, 1.0, {}};
LayoutParams pWide{800.0, 16.0, 1.0, {}};
auto layNarrow = ChunkLayoutEngine::layoutPreparedChunk(prep, pNarrow);
auto layWide = ChunkLayoutEngine::layoutPreparedChunk(prep, pWide);
QVERIFY(layNarrow.lines.size() >= layWide.lines.size());
QCOMPARE(layNarrow.contentWidth, 300.0);
QCOMPARE(layWide.contentWidth, 800.0);
}
// Obligation: invariant.ContrastSafetyFallback
void testInvariantContrastSafetyFallback()
{
// When low contrast occurs (< 3.0), KnuthPlassItem chooses black or white to maximize contrast
QColor darkBg(30, 30, 30);
QColor darkFg(40, 40, 40);
qreal lowRatio = KnuthPlassItem::contrastRatio(darkFg, darkBg);
QVERIFY(lowRatio < 3.0);
qreal crBlack = KnuthPlassItem::contrastRatio(Qt::black, darkBg);
qreal crWhite = KnuthPlassItem::contrastRatio(Qt::white, darkBg);
QVERIFY(crWhite > 3.0);
QVERIFY(crWhite > crBlack);
}
// Obligations: surface-actor.LibrarySurface, surface-provides.LibrarySurface
void testSurfaceLibrarySurface()
{
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(10);
// LibrarySurface provides OpenBookRequested (handled by setReader)
model.setReader(&reader);
QVERIFY(model.isTextMode());
QCOMPARE(model.totalPages(), 10);
}
// Obligations: surface-actor.ReadingSurface, surface-exposure.ReadingSurface, surface-provides.ReadingSurface
void testSurfaceReadingSurface()
{
TestContext ctx;
ReadingModel model(*ctx.positionStore);
SpecTestTextReader reader(15);
model.setReader(&reader);
// Exposes: title, author, status (measuring), current_chunk (currentPage), progress, use_book_colours
QCOMPARE(reader.title(), QStringLiteral("Spec Test Book"));
QCOMPARE(reader.author(), QStringLiteral("Spec Author"));
QCOMPARE(model.currentPage(), 1);
QCOMPARE(model.progress(), 0.0);
QCOMPARE(model.useBookColours(), false);
QVERIFY(model.property("measuring").isValid());
// Provides:
// 1. FontSizeChanged / ViewportGeometryChanged
model.updateLayoutMetrics(700, 18, 1.2);
// 2. ChunkScrolledIntoView
QVERIFY(model.data(model.index(10, 0), ReadingModel::PixelHeightRole).toReal() > 0);
// 3. ScrollPositionChanged
model.setScrollPosition(2, 10.0, 0.15);
QCOMPARE(model.currentPage(), 3);
// 4. PublisherColoursToggled
model.setUseBookColours(true);
QCOMPARE(model.useBookColours(), true);
}
// Obligations: surface-actor.LayoutEngineIntegration, surface-provides.LayoutEngineIntegration
void testSurfaceLayoutEngineIntegration()
{
MockBookImageResolver resolver;
ContentChunk chunk;
BlockItem p;
p.kind = BlockItem::Kind::Paragraph;
InlineItem img;
img.kind = InlineItem::Kind::Image;
img.imageUrl = QStringLiteral("image://epub/test.png");
p.inlines.append(img);
chunk.blocks.append(p);
// Demands BookImageResolver contract and performs thread-safe off-thread layout
auto prep = ChunkLayoutEngine::prepareChunk(chunk, 16.0, &resolver);
LayoutParams params{600.0, 16.0, 1.0, {}};
auto layout = ChunkLayoutEngine::layoutPreparedChunk(prep, params);
QCOMPARE(layout.images.size(), 1);
QCOMPARE(layout.images[0].url, QStringLiteral("image://epub/test.png"));
QCOMPARE(layout.images[0].targetRect.width(), 100.0);
QCOMPARE(layout.images[0].targetRect.height(), 50.0);
}
};
QTEST_MAIN(TextLayoutEngineSpecTest)
#include "TextLayoutEngineSpecTest.moc"