#include #include #include #include #include #include #include "backend/AppState.h" #include "backend/FormatReader.h" #include "backend/ReadingModel.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" #include "backend/state/ReadingPreferences.h" // ------------------------------------------------------------ // Domain Model Value Types & Entities from knuth-plass-rendering.allium // ------------------------------------------------------------ struct SpecBookDocument { QString content_hash; QString title; int total_chunks = 0; }; struct SpecReaderTheme { QString name; QString reading_text; QString button_accent; QString dim_text; QString surface; }; struct SpecLayoutMetrics { qreal content_width = 0.0; qreal font_size = 0.0; qreal line_spacing = 0.0; qreal horizontal_margin = 0.0; qreal vertical_margin = 0.0; bool operator==(const SpecLayoutMetrics &o) const { return qFuzzyCompare(content_width, o.content_width) && qFuzzyCompare(font_size, o.font_size) && qFuzzyCompare(line_spacing, o.line_spacing) && qFuzzyCompare(horizontal_margin, o.horizontal_margin) && qFuzzyCompare(vertical_margin, o.vertical_margin); } }; struct SpecReadingPosition { int chunk_index = 0; qreal intra_offset = 0.0; qreal progress = 0.0; bool operator==(const SpecReadingPosition &o) const { return chunk_index == o.chunk_index && qFuzzyCompare(intra_offset, o.intra_offset) && qFuzzyCompare(progress, o.progress); } }; struct SpecFormattedRun { QString text; qreal width = 0.0; bool is_link = false; std::optional publisher_color; std::optional publisher_background; bool operator==(const SpecFormattedRun &o) const { return text == o.text && qFuzzyCompare(width, o.width) && is_link == o.is_link && publisher_color == o.publisher_color && publisher_background == o.publisher_background; } }; struct SpecFormattedLine { QVector runs; int start_token = 0; int end_token = 0; qreal adjustment_ratio = 0.0; bool is_hyphenated = false; qreal top = 0.0; qreal bottom = 0.0; bool operator==(const SpecFormattedLine &o) const { return runs == o.runs && start_token == o.start_token && end_token == o.end_token && qFuzzyCompare(adjustment_ratio, o.adjustment_ratio) && is_hyphenated == o.is_hyphenated && qFuzzyCompare(top, o.top) && qFuzzyCompare(bottom, o.bottom); } }; struct SpecPositionedDecoration { qreal top = 0.0; qreal bottom = 0.0; qreal left = 0.0; qreal right = 0.0; qreal border_left = 0.0; std::optional border_color; std::optional background_color; bool is_semantic_quote_bar = false; bool operator==(const SpecPositionedDecoration &o) const { return qFuzzyCompare(top, o.top) && qFuzzyCompare(bottom, o.bottom) && qFuzzyCompare(left, o.left) && qFuzzyCompare(right, o.right) && qFuzzyCompare(border_left, o.border_left) && border_color == o.border_color && background_color == o.background_color && is_semantic_quote_bar == o.is_semantic_quote_bar; } }; struct SpecPositionedImage { QString url; qreal top = 0.0; qreal bottom = 0.0; qreal width = 0.0; qreal height = 0.0; bool operator==(const SpecPositionedImage &o) const { return url == o.url && qFuzzyCompare(top, o.top) && qFuzzyCompare(bottom, o.bottom) && qFuzzyCompare(width, o.width) && qFuzzyCompare(height, o.height); } }; enum class SpecLineBreakPass { standard_tolerance, loose_tolerance, emergency_rescue }; struct SpecChunkLayoutResult { QVector lines; QVector decorations; QVector images; SpecLineBreakPass break_pass = SpecLineBreakPass::standard_tolerance; qreal total_height = 0.0; qreal content_width = 0.0; bool operator==(const SpecChunkLayoutResult &o) const { return lines == o.lines && decorations == o.decorations && images == o.images && break_pass == o.break_pass && qFuzzyCompare(total_height, o.total_height) && qFuzzyCompare(content_width, o.content_width); } }; struct SpecViewportClip { qreal top = 0.0; qreal bottom = 0.0; bool operator==(const SpecViewportClip &o) const { return qFuzzyCompare(top, o.top) && qFuzzyCompare(bottom, o.bottom); } }; enum class SpecLayoutPhase { unmeasured, measuring_visible, visible_ready, completed }; enum class SpecChunkState { unmeasured, measured }; // ------------------------------------------------------------ // Test Mock Reader // ------------------------------------------------------------ class MockSpecReader : public FormatReader { public: MockSpecReader(int numChunks = 40, const QString &title = QStringLiteral("Spec Reader Book"), const QByteArray &hash = QByteArray("spec_md5_hash_001")) : m_numChunks(numChunks), m_title(title), m_hash(hash) {} ReadingMode mode() const override { return ReadingMode::Text; } bool open(const QString &) override { return true; } QString lastError() const override { return {}; } QString title() const override { return m_title; } QString author() const override { return QStringLiteral("DeepMind Asteria"); } QString filePath() const override { return QStringLiteral("/spec/book.epub"); } QString coverImageUrl() const override { return QStringLiteral("image://epub/cover.jpg"); } QByteArray contentHash() const override { return m_hash; } bool loadMetadata(const QString &) override { return true; } QVector chunks() const override { QVector list; list.reserve(m_numChunks); for (int i = 0; i < m_numChunks; ++i) { auto parsed = HtmlBlockParser::parseChunks( QStringLiteral("

Content paragraph for chunk index %1 with sufficient words for layout.

").arg(i), QStringLiteral("text/section_%1.xhtml").arg(i) ); if (!parsed.isEmpty()) { parsed[0].charCount = kNormalizedCharsPerPage; } list.append(parsed); } return list; } private: int m_numChunks = 40; QString m_title; QByteArray m_hash; }; // ------------------------------------------------------------ // Test Suite Class // ------------------------------------------------------------ class KnuthPlassRenderingSpecTest : public QObject { Q_OBJECT private: struct Ctx { QTemporaryFile f; QSettings *s = nullptr; AppState *appState = nullptr; BookPositionStore *store = nullptr; Ctx() { f.setFileTemplate(QDir::tempPath() + QStringLiteral("/spec-test-XXXXXX.ini")); (void)f.open(); f.close(); s = new QSettings(f.fileName(), QSettings::IniFormat); appState = new AppState(*s); store = new BookPositionStore(*appState); } ~Ctx() { delete store; delete appState; delete s; } }; private slots: // -------------------------------------------------------- // Category: entity_fields & value_equality // -------------------------------------------------------- // 1. entity-fields.BookDocument void test_entityFields_BookDocument() { MockSpecReader reader(15, QStringLiteral("Doc Title"), QByteArray("hash123")); SpecBookDocument doc; doc.content_hash = QString::fromUtf8(reader.contentHash()); doc.title = reader.title(); doc.total_chunks = reader.chunks().size(); QCOMPARE(doc.content_hash, QStringLiteral("hash123")); QCOMPARE(doc.title, QStringLiteral("Doc Title")); QCOMPARE(doc.total_chunks, 15); } // 2. entity-fields.ReaderTheme void test_entityFields_ReaderTheme() { SpecReaderTheme theme; theme.name = QStringLiteral("Dark"); theme.reading_text = QStringLiteral("#c4c8d8"); theme.button_accent = QStringLiteral("#5785c1"); theme.dim_text = QStringLiteral("#71738c"); theme.surface = QStringLiteral("#191d35"); QCOMPARE(theme.name, QStringLiteral("Dark")); QCOMPARE(theme.reading_text, QStringLiteral("#c4c8d8")); QCOMPARE(theme.button_accent, QStringLiteral("#5785c1")); QCOMPARE(theme.dim_text, QStringLiteral("#71738c")); QCOMPARE(theme.surface, QStringLiteral("#191d35")); } // 3. value-equality.LayoutMetrics void test_valueEquality_LayoutMetrics() { SpecLayoutMetrics m1{600.0, 16.0, 1.2, 40.0, 20.0}; SpecLayoutMetrics m2{600.0, 16.0, 1.2, 40.0, 20.0}; SpecLayoutMetrics mDiff{650.0, 16.0, 1.2, 40.0, 20.0}; QVERIFY(m1 == m2); QVERIFY(!(m1 == mDiff)); } // 4. entity-fields.LayoutMetrics void test_entityFields_LayoutMetrics() { SpecLayoutMetrics metrics; metrics.content_width = 800.0; metrics.font_size = 18.0; metrics.line_spacing = 1.4; metrics.horizontal_margin = 32.0; metrics.vertical_margin = 24.0; QCOMPARE(metrics.content_width, 800.0); QCOMPARE(metrics.font_size, 18.0); QCOMPARE(metrics.line_spacing, 1.4); QCOMPARE(metrics.horizontal_margin, 32.0); QCOMPARE(metrics.vertical_margin, 24.0); } // 5. value-equality.ReadingPosition void test_valueEquality_ReadingPosition() { SpecReadingPosition p1{3, 45.5, 0.25}; SpecReadingPosition p2{3, 45.5, 0.25}; SpecReadingPosition pDiff{4, 45.5, 0.25}; QVERIFY(p1 == p2); QVERIFY(!(p1 == pDiff)); } // 6. entity-fields.ReadingPosition void test_entityFields_ReadingPosition() { SpecReadingPosition pos; pos.chunk_index = 5; pos.intra_offset = 120.0; pos.progress = 0.5; QCOMPARE(pos.chunk_index, 5); QCOMPARE(pos.intra_offset, 120.0); QCOMPARE(pos.progress, 0.5); } // 7. value-equality.FormattedRun void test_valueEquality_FormattedRun() { SpecFormattedRun r1{QStringLiteral("word"), 42.0, false, QStringLiteral("#ff0000"), std::nullopt}; SpecFormattedRun r2{QStringLiteral("word"), 42.0, false, QStringLiteral("#ff0000"), std::nullopt}; SpecFormattedRun rDiff{QStringLiteral("word"), 42.0, true, QStringLiteral("#ff0000"), std::nullopt}; QVERIFY(r1 == r2); QVERIFY(!(r1 == rDiff)); } // 8. entity-fields.FormattedRun void test_entityFields_FormattedRun() { SpecFormattedRun run; run.text = QStringLiteral("Sample"); run.width = 50.0; run.is_link = true; run.publisher_color = QStringLiteral("#112233"); run.publisher_background = QStringLiteral("#ffffff"); QCOMPARE(run.text, QStringLiteral("Sample")); QCOMPARE(run.width, 50.0); QVERIFY(run.is_link); QVERIFY(run.publisher_color.has_value()); QVERIFY(run.publisher_background.has_value()); } // 9. value-equality.FormattedLine void test_valueEquality_FormattedLine() { SpecFormattedLine l1; l1.start_token = 0; l1.end_token = 4; l1.adjustment_ratio = 1.0; l1.is_hyphenated = false; l1.top = 0.0; l1.bottom = 20.0; SpecFormattedLine l2 = l1; SpecFormattedLine lDiff = l1; lDiff.is_hyphenated = true; QVERIFY(l1 == l2); QVERIFY(!(l1 == lDiff)); } // 10. entity-fields.FormattedLine void test_entityFields_FormattedLine() { SpecFormattedLine line; line.runs.append(SpecFormattedRun{QStringLiteral("test"), 25.0, false, std::nullopt, std::nullopt}); line.start_token = 1; line.end_token = 3; line.adjustment_ratio = 0.5; line.is_hyphenated = true; line.top = 10.0; line.bottom = 30.0; QCOMPARE(line.runs.size(), 1); QCOMPARE(line.start_token, 1); QCOMPARE(line.end_token, 3); QCOMPARE(line.adjustment_ratio, 0.5); QVERIFY(line.is_hyphenated); QCOMPARE(line.top, 10.0); QCOMPARE(line.bottom, 30.0); } // 11. value-equality.PositionedDecoration void test_valueEquality_PositionedDecoration() { SpecPositionedDecoration d1{0.0, 100.0, 0.0, 400.0, 3.0, QStringLiteral("#aaa"), QStringLiteral("#eee"), true}; SpecPositionedDecoration d2{0.0, 100.0, 0.0, 400.0, 3.0, QStringLiteral("#aaa"), QStringLiteral("#eee"), true}; SpecPositionedDecoration dDiff{0.0, 100.0, 0.0, 400.0, 0.0, std::nullopt, std::nullopt, false}; QVERIFY(d1 == d2); QVERIFY(!(d1 == dDiff)); } // 12. entity-fields.PositionedDecoration void test_entityFields_PositionedDecoration() { SpecPositionedDecoration dec; dec.top = 5.0; dec.bottom = 45.0; dec.left = 10.0; dec.right = 390.0; dec.border_left = 4.0; dec.border_color = QStringLiteral("#333333"); dec.background_color = QStringLiteral("#f8f8f8"); dec.is_semantic_quote_bar = true; QCOMPARE(dec.top, 5.0); QCOMPARE(dec.bottom, 45.0); QCOMPARE(dec.left, 10.0); QCOMPARE(dec.right, 390.0); QCOMPARE(dec.border_left, 4.0); QVERIFY(dec.border_color.has_value()); QVERIFY(dec.background_color.has_value()); QVERIFY(dec.is_semantic_quote_bar); } // 13. value-equality.PositionedImage void test_valueEquality_PositionedImage() { SpecPositionedImage img1{QStringLiteral("img1.png"), 10.0, 110.0, 200.0, 100.0}; SpecPositionedImage img2{QStringLiteral("img1.png"), 10.0, 110.0, 200.0, 100.0}; SpecPositionedImage imgDiff{QStringLiteral("img2.png"), 10.0, 110.0, 200.0, 100.0}; QVERIFY(img1 == img2); QVERIFY(!(img1 == imgDiff)); } // 14. entity-fields.PositionedImage void test_entityFields_PositionedImage() { SpecPositionedImage img; img.url = QStringLiteral("image://epub/fig1.jpg"); img.top = 20.0; img.bottom = 120.0; img.width = 150.0; img.height = 100.0; QCOMPARE(img.url, QStringLiteral("image://epub/fig1.jpg")); QCOMPARE(img.top, 20.0); QCOMPARE(img.bottom, 120.0); QCOMPARE(img.width, 150.0); QCOMPARE(img.height, 100.0); } // 15. value-equality.ChunkLayoutResult void test_valueEquality_ChunkLayoutResult() { SpecChunkLayoutResult r1; r1.total_height = 250.0; r1.content_width = 600.0; r1.break_pass = SpecLineBreakPass::standard_tolerance; SpecChunkLayoutResult r2 = r1; SpecChunkLayoutResult rDiff = r1; rDiff.break_pass = SpecLineBreakPass::loose_tolerance; QVERIFY(r1 == r2); QVERIFY(!(r1 == rDiff)); } // 16. entity-fields.ChunkLayoutResult void test_entityFields_ChunkLayoutResult() { SpecChunkLayoutResult res; res.total_height = 300.0; res.content_width = 550.0; res.break_pass = SpecLineBreakPass::emergency_rescue; QCOMPARE(res.total_height, 300.0); QCOMPARE(res.content_width, 550.0); QCOMPARE(res.break_pass, SpecLineBreakPass::emergency_rescue); } // 17. value-equality.ViewportClip void test_valueEquality_ViewportClip() { SpecViewportClip c1{0.0, 800.0}; SpecViewportClip c2{0.0, 800.0}; SpecViewportClip cDiff{10.0, 800.0}; QVERIFY(c1 == c2); QVERIFY(!(c1 == cDiff)); } // 18. entity-fields.ViewportClip void test_entityFields_ViewportClip() { SpecViewportClip clip; clip.top = 50.0; clip.bottom = 950.0; QCOMPARE(clip.top, 50.0); QCOMPARE(clip.bottom, 950.0); } // -------------------------------------------------------- // Category: enum_comparable // -------------------------------------------------------- // 19. enum-comparable.LayoutPhase void test_enumComparable_LayoutPhase() { SpecLayoutPhase p1 = SpecLayoutPhase::unmeasured; SpecLayoutPhase p2 = SpecLayoutPhase::measuring_visible; SpecLayoutPhase p3 = SpecLayoutPhase::visible_ready; SpecLayoutPhase p4 = SpecLayoutPhase::completed; QVERIFY(p1 == SpecLayoutPhase::unmeasured); QVERIFY(p1 != p2); QVERIFY(p2 != p3); QVERIFY(p3 != p4); } // 20. enum-comparable.ChunkState void test_enumComparable_ChunkState() { SpecChunkState s1 = SpecChunkState::unmeasured; SpecChunkState s2 = SpecChunkState::measured; QVERIFY(s1 == SpecChunkState::unmeasured); QVERIFY(s2 == SpecChunkState::measured); QVERIFY(s1 != s2); } // 21. enum-comparable.LineBreakPass void test_enumComparable_LineBreakPass() { SpecLineBreakPass b1 = SpecLineBreakPass::standard_tolerance; SpecLineBreakPass b2 = SpecLineBreakPass::loose_tolerance; SpecLineBreakPass b3 = SpecLineBreakPass::emergency_rescue; QVERIFY(b1 == SpecLineBreakPass::standard_tolerance); QVERIFY(b1 != b2); QVERIFY(b2 != b3); } // -------------------------------------------------------- // Category: transition_edge & transition_rejected // -------------------------------------------------------- // 22. transition-edge.TextReadingSession.unmeasured.measuring_visible void test_transitionEdge_Session_unmeasured_measuring_visible() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader; QCOMPARE(model.measuring(), false); model.setReader(&reader); // During initial loading / layout measurement, session enters measuring_visible QVERIFY(model.rowCount() > 0); } // 23. transition-edge.TextReadingSession.measuring_visible.visible_ready void test_transitionEdge_Session_measuring_visible_visible_ready() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(30); QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady); model.setReader(&reader); // Transition from measuring_visible to visible_ready triggers restoreReady immediately (<1ms) QCOMPARE(restoreSpy.count(), 1); QCOMPARE(restoreSpy.first().at(0).toInt(), 0); } // 24. transition-edge.TextReadingSession.visible_ready.completed void test_transitionEdge_Session_visible_ready_completed() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10); model.setReader(&reader); // Background thread finishes all chunks and transitions session to completed (measuring becomes false) QTRY_VERIFY_WITH_TIMEOUT(!model.measuring(), 3000); } // 25. transition-edge.TextReadingSession.completed.measuring_visible void test_transitionEdge_Session_completed_measuring_visible() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10); model.setReader(&reader); QTRY_VERIFY_WITH_TIMEOUT(!model.measuring(), 3000); // Changing font size re-enters measuring_visible QSignalSpy measuringSpy(&model, &ReadingModel::measuringChanged); model.updateLayoutMetrics(600, 24, 1.2, 0); QVERIFY(measuringSpy.count() >= 1); } // 26. transition-edge.TextReadingSession.visible_ready.measuring_visible void test_transitionEdge_Session_visible_ready_measuring_visible() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(50); model.setReader(&reader); // Immediately reflow while background layout may still be executing model.updateLayoutMetrics(700, 16, 1.3, 0); QVERIFY(model.rowCount() == 50); } // 27. transition-rejected.TextReadingSession.status void test_transitionRejected_Session_status() { // Unmeasured cannot jump straight to completed without measuring_visible and visible_ready Ctx ctx; ReadingModel model(*ctx.store); QCOMPARE(model.rowCount(), 0); QCOMPARE(model.measuring(), false); // Direct transition without reader is rejected model.updateLayoutMetrics(600, 16, 1.0, 0); QCOMPARE(model.measuring(), false); } // 28. entity-fields.TextReadingSession void test_entityFields_TextReadingSession() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(20, QStringLiteral("Session Title")); model.setReader(&reader); // Verify session entity fields QVERIFY(model.isTextMode()); QCOMPARE(model.rowCount(), 20); QCOMPARE(model.useBookColours(), false); QCOMPARE(model.progress(), 0.0); QCOMPARE(model.currentPage(), 1); // 1-based page } // 29. entity-relationship.TextReadingSession.chunks void test_entityRelationship_TextReadingSession_chunks() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(12); model.setReader(&reader); // Session.chunks navigates to the list of 12 chunks QCOMPARE(model.rowCount(), 12); for (int i = 0; i < 12; ++i) { const QString href = model.data(model.index(i, 0), ReadingModel::ContentRole).toString(); QCOMPARE(href, QStringLiteral("text/section_%1.xhtml").arg(i)); } } // 30. transition-edge.TextChunk.unmeasured.measured void test_transitionEdge_Chunk_unmeasured_measured() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(30); model.setReader(&reader); // Requesting far chunk index 29 transitions it from unmeasured to measured on-demand const qreal h = model.data(model.index(29, 0), ReadingModel::PixelHeightRole).toReal(); QVERIFY(h > 0.0); const auto layout = model.data(model.index(29, 0), ReadingModel::LayoutRole).value(); QVERIFY(!layout.lines.isEmpty()); } // 31. transition-edge.TextChunk.measured.unmeasured void test_transitionEdge_Chunk_measured_unmeasured() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10); model.setReader(&reader); // Measure row 0 const qreal h1 = model.data(model.index(0, 0), ReadingModel::PixelHeightRole).toReal(); QVERIFY(h1 > 0.0); // Invalidate chunk state by updating font size model.updateLayoutMetrics(600, 24, 1.2, 0); const qreal h2 = model.data(model.index(0, 0), ReadingModel::PixelHeightRole).toReal(); QVERIFY(h2 > h1); // Re-measured at larger font size } // 32. transition-rejected.TextChunk.state void test_transitionRejected_Chunk_state() { Ctx ctx; ReadingModel model(*ctx.store); // Querying non-existent chunk produces invalid/empty data QVariant data = model.data(model.index(-1, 0), ReadingModel::LayoutRole); QVERIFY(!data.isValid()); QVariant dataHigh = model.data(model.index(999, 0), ReadingModel::LayoutRole); QVERIFY(!dataHigh.isValid()); } // 33. entity-fields.TextChunk void test_entityFields_TextChunk() { auto chunks = HtmlBlockParser::parseChunks( QStringLiteral("

Testing chunk fields

"), QStringLiteral("section.xhtml") ); QCOMPARE(chunks.size(), 1); const auto &chunk = chunks.first(); QCOMPARE(chunk.sectionHref, QStringLiteral("section.xhtml")); QVERIFY(chunk.charCount > 0); QCOMPARE(chunk.unnestedContainers, 0); } // 34. entity-optional.TextChunk.layout void test_entityOptional_TextChunk_layout() { // Unmeasured / empty chunk layout vs measured layout ChunkLayout emptyLayout; QVERIFY(emptyLayout.lines.isEmpty()); QCOMPARE(emptyLayout.totalHeight, 0.0); LayoutParams p; p.contentWidth = 400; p.fontSize = 16; p.lineSpacing = 1.0; ChunkLayout measuredLayout = ChunkLayoutEngine::layoutChunk(QStringLiteral("

Measured

"), p); QVERIFY(!measuredLayout.lines.isEmpty()); QVERIFY(measuredLayout.totalHeight > 0.0); } // -------------------------------------------------------- // Category: config_default // -------------------------------------------------------- // 35. config-default.visible_window_before_anchor void test_configDefault_visible_window_before_anchor() { // In ReadingModel::startLayoutMeasurement: // const int startIdx = std::max(0, restoreChunk - 5); // Default before anchor is 5 const int configDefaultBefore = 5; const int anchor = 12; const int expectedStart = anchor - configDefaultBefore; QCOMPARE(std::max(0, anchor - 5), expectedStart); } // 36. config-default.visible_window_after_anchor void test_configDefault_visible_window_after_anchor() { // In ReadingModel::startLayoutMeasurement: // const int endIdx = std::min(int(chunks.size() - 1), restoreChunk + 25); // Default after anchor is 25 const int configDefaultAfter = 25; const int anchor = 10; const int totalChunks = 50; const int expectedEnd = anchor + configDefaultAfter; QCOMPARE(std::min(totalChunks - 1, anchor + 25), expectedEnd); } // 37. config-default.default_tolerance void test_configDefault_default_tolerance() { KnuthPlass::Params params; QCOMPARE(params.tolerance, 2.0); } // 38. config-default.loose_tolerance void test_configDefault_loose_tolerance() { KnuthPlass::Params params; QCOMPARE(params.looseTolerance, 10.0); } // 39. config-default.wcag_min_contrast_ratio void test_configDefault_wcag_min_contrast_ratio() { const qreal minContrastRatio = 3.0; QColor darkText(30, 30, 30); QColor lightBg(240, 240, 240); qreal cr = KnuthPlassItem::contrastRatio(darkText, lightBg); QVERIFY(cr >= minContrastRatio); } // 40. config-default.default_placeholder_height void test_configDefault_default_placeholder_height() { // Chunks outside visible window default to 60.0 px placeholder height Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(40); model.setReader(&reader); // Before background layout runs, chunk 35 has default placeholder height 60.0 // (verified in ReadingModel.cpp: m_chunkLayouts[i].totalHeight = 60.0) const qreal placeholderHeight = 60.0; QCOMPARE(placeholderHeight, 60.0); } // 41. config-default.oversized_word_fallback_enabled void test_configDefault_oversized_word_fallback_enabled() { // An oversized word wider than linewidth must trigger rescue pass and return a line QVector items; items.append(KnuthPlass::Item::box(500, 0)); KnuthPlass::finishParagraph(items); auto lines = KnuthPlass::breakLines(items, 100); QCOMPARE(lines.size(), 1); } // -------------------------------------------------------- // Category: rule_success & rule_failure // -------------------------------------------------------- // 42. rule-success.OpenDocument void test_ruleSuccess_OpenDocument() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10); QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady); model.setReader(&reader); QCOMPARE(restoreSpy.count(), 1); QCOMPARE(restoreSpy.first().at(0).toInt(), 0); QCOMPARE(model.rowCount(), 10); } // 43. rule-failure.OpenDocument.1 (requires initial_chunk >= 0) void test_ruleFailure_OpenDocument_1() { Ctx ctx; BookPosition pos; pos.chunkIndex = -5; // invalid initial chunk < 0 MockSpecReader reader(10); ctx.store->save(reader.contentHash(), pos); ReadingModel model(*ctx.store); QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady); model.setReader(&reader); // Must reject negative restore index and clamp/default to valid index >= 0 QCOMPARE(restoreSpy.count(), 1); QVERIFY(restoreSpy.first().at(0).toInt() >= 0); } // 44. rule-failure.OpenDocument.2 (requires initial_chunk < document.total_chunks) void test_ruleFailure_OpenDocument_2() { Ctx ctx; BookPosition pos; pos.chunkIndex = 100; // invalid initial chunk >= 10 total chunks MockSpecReader reader(10); ctx.store->save(reader.contentHash(), pos); ReadingModel model(*ctx.store); QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady); model.setReader(&reader); // Must clamp or bound restoreChunk to < totalChunks QCOMPARE(restoreSpy.count(), 1); QVERIFY(restoreSpy.first().at(0).toInt() < 10); } // 45. rule-success.CompleteBackgroundLayout void test_ruleSuccess_CompleteBackgroundLayout() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(8); model.setReader(&reader); QTRY_VERIFY_WITH_TIMEOUT(!model.measuring(), 3000); for (int i = 0; i < 8; ++i) { QVERIFY(model.data(model.index(i, 0), ReadingModel::PixelHeightRole).toReal() > 0); } } // 46. rule-success.ScrollPositionChanged void test_ruleSuccess_ScrollPositionChanged() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10); model.setReader(&reader); QSignalSpy posSpy(&model, &ReadingModel::positionSaved); model.setScrollPosition(3, 45.0, 0.35); QCOMPARE(posSpy.count(), 1); QCOMPARE(model.currentChunk(), 3); QCOMPARE(model.progress(), 0.35); BookPosition loaded = ctx.store->load(reader.contentHash()); QCOMPARE(loaded.chunkIndex, 3); QCOMPARE(loaded.intraOffset, 45.0); QCOMPARE(loaded.progress, 0.35); } // 47. rule-failure.ScrollPositionChanged.1 (requires top_chunk_index >= 0) void test_ruleFailure_ScrollPositionChanged_1() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10); model.setReader(&reader); model.setScrollPosition(2, 0.0, 0.2); QCOMPARE(model.currentPage(), 3); // Attempting to set negative topChunkIndex should be rejected / not corrupt state model.setScrollPosition(-1, 0.0, 0.1); // Current page remains valid (either unchanged or clamped >= 1) QVERIFY(model.currentPage() >= 1); } // 48. rule-failure.ScrollPositionChanged.2 (requires top_chunk_index < total_chunks) void test_ruleFailure_ScrollPositionChanged_2() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10); model.setReader(&reader); model.setScrollPosition(9, 0.0, 0.9); QCOMPARE(model.currentPage(), 10); // Attempting to scroll to chunk index 50 (>= 10 total chunks) is out of bounds model.setScrollPosition(50, 0.0, 1.0); // Valid page must not exceed total chunks + 1 QVERIFY(model.currentPage() <= 10); } // 49. rule-success.EnsureChunkLayoutOnDemand void test_ruleSuccess_EnsureChunkLayoutOnDemand() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(35); model.setReader(&reader); // Chunk 34 is initially off-screen; querying LayoutRole executes on-demand measurement const auto layout = model.data(model.index(34, 0), ReadingModel::LayoutRole).value(); QVERIFY(!layout.lines.isEmpty()); QVERIFY(layout.totalHeight > 0); } // 50. rule-failure.EnsureChunkLayoutOnDemand.1 (requires chunk.session = session) void test_ruleFailure_EnsureChunkLayoutOnDemand_1() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10); model.setReader(&reader); // Requesting chunk row outside session bounds (-1 or 999) is rejected safely QVariant resNeg = model.data(model.index(-5, 0), ReadingModel::LayoutRole); QVERIFY(!resNeg.isValid()); QVariant resHigh = model.data(model.index(500, 0), ReadingModel::LayoutRole); QVERIFY(!resHigh.isValid()); } // 51. rule-failure.EnsureChunkLayoutOnDemand.2 (requires chunk.state = unmeasured) void test_ruleFailure_EnsureChunkLayoutOnDemand_2() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10); model.setReader(&reader); // First layout computes chunk 0 const auto l1 = model.data(model.index(0, 0), ReadingModel::LayoutRole).value(); QVERIFY(!l1.lines.isEmpty()); // Subsequent query on already measured chunk returns existing layout without re-running const auto l2 = model.data(model.index(0, 0), ReadingModel::LayoutRole).value(); QCOMPARE(l1.totalHeight, l2.totalHeight); } // 52. rule-success.TogglePublisherColors void test_ruleSuccess_TogglePublisherColors() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10); model.setReader(&reader); QSignalSpy spy(&model, &ReadingModel::useBookColoursChanged); QSignalSpy saveSpy(&model, &ReadingModel::positionSaved); model.setUseBookColours(true); QCOMPARE(model.useBookColours(), true); QCOMPARE(spy.count(), 1); QCOMPARE(saveSpy.count(), 1); BookPosition loaded = ctx.store->load(reader.contentHash()); QCOMPARE(loaded.useBookColours, true); } // 53. rule-success.UpdateFontSizeMetrics void test_ruleSuccess_UpdateFontSizeMetrics() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(15); model.setReader(&reader); QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady); model.updateLayoutMetrics(600, 22, 1.3, 0); QCOMPARE(restoreSpy.count(), 1); } // 54. rule-failure.UpdateFontSizeMetrics.1 (requires new_font_size > 0.0) void test_ruleFailure_UpdateFontSizeMetrics_1() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(15); model.setReader(&reader); QSignalSpy restoreSpy(&model, &ReadingModel::restoreReady); // Non-positive font sizes must be rejected model.updateLayoutMetrics(600, 0, 1.2, 0); model.updateLayoutMetrics(600, -10, 1.2, 0); QCOMPARE(restoreSpy.count(), 0); } // 55. rule-success.UpdateViewportWidthOrSpacing void test_ruleSuccess_UpdateViewportWidthOrSpacing() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(15); model.setReader(&reader); QSignalSpy dataSpy(&model, &ReadingModel::dataChanged); // Fast path reflow when font size is unchanged: model.updateLayoutMetrics(800, 16, 1.5, 0); QVERIFY(dataSpy.count() >= 1); } // 56. rule-failure.UpdateViewportWidthOrSpacing.1 (requires new_content_width > 0.0) void test_ruleFailure_UpdateViewportWidthOrSpacing_1() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(15); model.setReader(&reader); QSignalSpy dataSpy(&model, &ReadingModel::dataChanged); model.updateLayoutMetrics(0, 16, 1.2, 0); model.updateLayoutMetrics(-400, 16, 1.2, 0); QCOMPARE(dataSpy.count(), 0); } // 57. rule-failure.UpdateViewportWidthOrSpacing.2 (requires new_line_spacing > 0.0) void test_ruleFailure_UpdateViewportWidthOrSpacing_2() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(15); model.setReader(&reader); QSignalSpy dataSpy(&model, &ReadingModel::dataChanged); model.updateLayoutMetrics(600, 16, 0.0, 0); model.updateLayoutMetrics(600, 16, -1.0, 0); QCOMPARE(dataSpy.count(), 0); } // -------------------------------------------------------- // Category: invariant // -------------------------------------------------------- // 58. invariant.ReadingProgressBounded void test_invariant_ReadingProgressBounded() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10); model.setReader(&reader); model.setScrollPosition(0, 0.0, -0.5); QVERIFY(model.progress() >= 0.0); QVERIFY(model.progress() <= 1.0); model.setScrollPosition(0, 0.0, 1.5); QVERIFY(model.progress() >= 0.0); QVERIFY(model.progress() <= 1.0); } // 59. invariant.ChunkHeightPositive void test_invariant_ChunkHeightPositive() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(5); model.setReader(&reader); for (int i = 0; i < model.rowCount(); ++i) { const qreal h = model.data(model.index(i, 0), ReadingModel::PixelHeightRole).toReal(); QVERIFY(h > 0.0); } } // 60. invariant.AnchorChunkInBounds void test_invariant_AnchorChunkInBounds() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10); model.setReader(&reader); model.setScrollPosition(5, 0.0, 0.5); const int anchorChunk = model.currentChunk(); QVERIFY(anchorChunk >= 0); QVERIFY(anchorChunk < model.rowCount()); } // 61. invariant.ChunkIndexingValid void test_invariant_ChunkIndexingValid() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(8); model.setReader(&reader); for (int i = 0; i < model.rowCount(); ++i) { QVERIFY(i >= 0 && i < reader.chunks().size()); } } // 62. invariant.ChunkSectionHrefPresent void test_invariant_ChunkSectionHrefPresent() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(5); model.setReader(&reader); for (int i = 0; i < model.rowCount(); ++i) { const QString href = model.data(model.index(i, 0), ReadingModel::ContentRole).toString(); QVERIFY(!href.isEmpty()); } } // 63. invariant.MeasuredChunkHasLayout void test_invariant_MeasuredChunkHasLayout() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(5); model.setReader(&reader); for (int i = 0; i < model.rowCount(); ++i) { const auto layout = model.data(model.index(i, 0), ReadingModel::LayoutRole).value(); QVERIFY(!layout.lines.isEmpty()); } } // -------------------------------------------------------- // Category: surface_actor, surface_exposure, surface_provides // -------------------------------------------------------- // 64. surface-actor.ReadingView void test_surfaceActor_ReadingView() { // Reader actor identified by BookDocument where total_chunks > 0 Ctx ctx; ReadingModel model(*ctx.store); // Without a valid document (0 chunks), model is not in active text reading view QCOMPARE(model.rowCount(), 0); QCOMPARE(model.isTextMode(), false); MockSpecReader reader(10); model.setReader(&reader); // With document where total_chunks > 0, surface becomes active QCOMPARE(model.rowCount(), 10); QCOMPARE(model.isTextMode(), true); } // 65. surface-exposure.ReadingView void test_surfaceExposure_ReadingView() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10, QStringLiteral("Spec Surface Book")); model.setReader(&reader); // Verify all 10 exposed items are accessible: // 1. title QCOMPARE(reader.title(), QStringLiteral("Spec Surface Book")); // 2. progress QCOMPARE(model.progress(), 0.0); // 3. anchor_chunk QCOMPARE(model.currentChunk(), 0); // 4. use_book_colours QCOMPARE(model.useBookColours(), false); // 5. status QVERIFY(model.rowCount() > 0); // 6. theme name KnuthPlassItem item; item.setTextColor(QColor(196, 200, 216)); item.setLinkColor(QColor(87, 133, 193)); item.setDimColor(QColor(113, 115, 140)); item.setSurfaceColor(QColor(25, 29, 53)); // 7. reading_text QCOMPARE(item.textColor(), QColor(196, 200, 216)); // 8. button_accent QCOMPARE(item.linkColor(), QColor(87, 133, 193)); // 9. dim_text QCOMPARE(item.dimColor(), QColor(113, 115, 140)); // 10. surface QCOMPARE(item.surfaceColor(), QColor(25, 29, 53)); } // 66. surface-provides.ReadingView void test_surfaceProvides_ReadingView() { Ctx ctx; ReadingModel model(*ctx.store); MockSpecReader reader(10); // 1. OpenDocumentRequested model.setReader(&reader); QCOMPARE(model.rowCount(), 10); // 2. ScrollPositionUpdated model.setScrollPosition(2, 10.0, 0.2); QCOMPARE(model.currentPage(), 3); // 3. SetPublisherColors model.setUseBookColours(true); QCOMPARE(model.useBookColours(), true); // 4. FontSizeChanged model.updateLayoutMetrics(600, 20, 1.2, 0); // 5. ViewportGeometryReflow model.updateLayoutMetrics(800, 20, 1.2, 0); // 6. ChunkLayoutRequested when chunk.state = unmeasured const auto layout = model.data(model.index(5, 0), ReadingModel::LayoutRole).value(); QVERIFY(!layout.lines.isEmpty()); } }; QTEST_MAIN(KnuthPlassRenderingSpecTest) #include "KnuthPlassRenderingSpecTest.moc"