-- 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 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 kp_items: List 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 } 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 images: List rules: List decorations: List 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 total_chunks: chunks.count } entity ContentChunk { section_href: String blocks: List 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 } 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 } 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 prepared_chunks: List 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?"