Files
asteria-qt/AGENTS.md
T
Agel 832e24c6f7 fix(linux): preserve AppImage executable bit via .tar.gz and auto-integrate Ubuntu icons
Browsers strip POSIX executable permissions (+x) from raw .AppImage files
downloaded directly over HTTP, leaving the downloaded binary non-executable in
Ubuntu Files (Nautilus). Additionally, Ubuntu displays a generic cog icon for
standalone AppImages in both Nautilus and the Ubuntu Dock on Wayland unless
desktop metadata, high-DPI icons, and GVfs custom icon attributes are
registered.

- Wrap `Asteria-<arch>.AppImage` (`0755`) in a `.AppImage.tar.gz` archive in
  `package-linux.sh` and point CI wiki links to the archive so extracting the
  download preserves executable permissions out of the box.
- Copy `.DirIcon` as a regular PNG file rather than a symlink so SquashFS icon
  extractors that do not follow symlinks receive valid image bytes.
- Add non-blocking first-launch integration in `AppRun` to install `hicolor`
  icons and `asteria-qt.desktop` (`StartupWMClass=asteria-qt`) under
  `XDG_DATA_HOME` and apply `metadata::custom-icon` on `$APPIMAGE` via `gio`
  for Nautilus.
- Embed 128x128, 256x256, and 512x512 icons in Qt resources and register them
  with `QApplication::setWindowIcon()`.
2026-11-19 14:49:54 +01:00

436 lines
29 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# AGENTS.md
This file provides guidance to AI coding assistants (Claude Code, Antigravity, etc.) when working with code in this repository.
## Project Overview
Asteria Qt is a cross-platform desktop book/document reader built with Qt6/C++. It is a reimplementation of [asteria-bookreader](../asteria-bookreader) (Electron/React) using a native Qt stack.
**Core Mission:** Asteria Qt is strictly focused on **rendering performance**. The architecture is engineered from the ground up for smooth scrolling, high refresh rates (60fps+), low UI latency, off-thread layout calculations, virtualized rendering, and instant image display across large documents and high-resolution comic archives.
**Target platforms:** Windows, Linux, and macOS
---
## Mandatory Rules for AI Agents
1. **Keep Documentation Updated (AGENTS.md):** Whenever you make architectural changes, add/modify readers or models, change state persistence, alter layout pipelines, or add QML components, **you MUST update `AGENTS.md` in the same commit/task**. Never allow documentation to diverge from the codebase.
2. **Preserve Rendering Performance:** Do not introduce UI-thread blocking operations. Heavy file parsing, layout calculation, image scaling, and metadata extraction must run asynchronously or off-thread.
3. **Strictly Follow SOLID Principles:** Keep format decoders, layout engines, image providers, and UI models cleanly decoupled.
4. **Maintain High Test Coverage (80%+):** Use the `Qt Test` (`QTest`) framework. Always run `ctest --test-dir build --output-on-failure` after code modifications.
5. **Do not add generic skills to repo**: Only add skills that are specific to the application and do not have broad applicability.
---
## Format Support
Active implementation: **EPUB, FB2 (.fb2, .fbz, .fb2.zip), TXT, CBZ, CBR, Folder of images**
Queued for reimplementation on new render pipeline: Mobi, PDB, RTF
Full target format list:
| Format | Active | Approach |
|----------|---------|-----------------------------------------------------------------------------------------------------------------------------------------|
| EPUB | Yes | Unzip (`ZipByteSource`) + parse OPF spine + CSS parser + `HtmlBlockParser` to `DocumentChunkBuilder` + Knuth-Plass |
| FB2 | Yes | `Fb2ByteSource` (plain XML / ZIP) + `TextEncoding` + direct `DocumentChunkBuilder` streaming + Knuth-Plass |
| TXT | Yes | `TextEncoding` + direct streaming into `DocumentChunkBuilder` + Knuth-Plass |
| PDF | Planned | `QtPdf` module (`QPdfDocument`, Qt 6.4+) |
| DOC | Planned | `libwpd` or antiword subprocess |
| RTF | Planned | `QTextDocumentReader` or RTF→HTML |
| HTML/HTM | Planned | `HtmlBlockParser` / `ChunkLayoutEngine` |
| DOCX | Planned | Unzip + parse `word/document.xml` (`QXmlStreamReader`) |
| DJVU | Planned | `DjVuLibre` |
| ODT | Planned | Unzip + parse OpenDocument XML |
| CHM | Planned | `CHMLib` |
| PDB | Planned | To be determined |
| CBZ | Yes | Unzip (`ZipByteSource`) + `ComicReader` + `MangaPagination` (single/dual page spread) |
| CBR | Yes | `libarchive` (`RarByteSource`) + `ComicReader` + `MangaPagination` |
| Folder | Yes | Open an image in dir and then Directory scan (`DirByteSource`) + `ComicReader` + `MangaPagination` |
---
## Build & Install
### Dependencies
- Qt 6.12+ components: `Core`, `Gui`, `Qml`, `Quick`, `Widgets`, `Concurrent`, `Svg`, `QuickControls2`, `Test`, `Xml`, `Network`, optional `DBus`.
- Third-party packages: `minizip`, `libarchive`, `iconv`, optional `uchardet`.
### Windows Build Environment (x86_64 Native MSYS2)
Qt 6 at `C:\msys64\opt\qt\6.12.0\mingw_64` (or `C:\msys64\mingw64`). MinGW toolchain at `C:\msys64\mingw64\bin\`:
```bash
PATH="/c/msys64/mingw64/bin:$PATH" "C:/msys64/mingw64/bin/cmake.exe" \
-S . -B build -G Ninja \
-DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_MAKE_PROGRAM="C:/msys64/mingw64/bin/ninja.exe" \
-DCMAKE_C_COMPILER="C:/msys64/mingw64/bin/gcc.exe" \
-DCMAKE_CXX_COMPILER="C:/msys64/mingw64/bin/g++.exe" \
-DCMAKE_PREFIX_PATH="c:\msys64\opt\qt\6.12.0\mingw_64"
PATH="/c/msys64/mingw64/bin:$PATH" "C:/msys64/mingw64/bin/ninja.exe" -C build
PATH="/c/msys64/opt/qt/6.12.0/mingw_64/bin:/c/msys64/mingw64/bin:$PATH" "C:/msys64/mingw64/bin/ctest.exe" --test-dir build --output-on-failure
```
### Windows Cross-Compilation Environment (x86_64 & ARM64 on Linux host / CI)
Cross-compiled using `llvm-mingw` (`x86_64-w64-mingw32` and `aarch64-w64-mingw32`) and prebuilt MSYS2 (`clang64` and `clangarm64`) Qt 6.12.0 + third-party library packages (`libarchive`, `libiconv`, `minizip`, `uchardet`, `zlib`), resolved with full transitive runtime dependencies via `scripts/download-mingw-arm64-qt.py --arch {x86_64,arm64}`:
```bash
# Windows x86_64
PKG_CONFIG_PATH="/opt/mingw-sysroot/lib/pkgconfig" cmake -B build-windows -G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_TOOLCHAIN_FILE=scripts/mingw-w64-toolchain.cmake \
-DCMAKE_PREFIX_PATH="/opt/qt/6.12.0/mingw_64;/opt/mingw-sysroot" \
-DCMAKE_FIND_ROOT_PATH="/opt/qt/6.12.0/mingw_64;/opt/mingw-sysroot" \
-DQT_HOST_PATH="/opt/qt/6.12.0/gcc_64"
cmake --build build-windows --target asteria-qt
# Windows ARM64
PKG_CONFIG_PATH="/opt/mingw-arm64-sysroot/lib/pkgconfig" cmake -B build-windows-arm64 -G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_TOOLCHAIN_FILE=scripts/mingw-w64-arm64-toolchain.cmake \
-DCMAKE_PREFIX_PATH="/opt/qt/6.12.0/mingw_arm64;/opt/mingw-arm64-sysroot" \
-DCMAKE_FIND_ROOT_PATH="/opt/qt/6.12.0/mingw_arm64;/opt/mingw-arm64-sysroot" \
-DQT_HOST_PATH="/opt/qt/6.12.0/gcc_64"
cmake --build build-windows-arm64 --target asteria-qt
```
Packaging (includes automated transitive PE DLL bundling and import verification via `scripts/verify-windows-dlls.py`):
```bash
packaging/package-windows.sh build-windows /opt/qt/6.12.0/mingw_64 /opt/mingw-sysroot dist x86_64
packaging/package-windows.sh build-windows-arm64 /opt/qt/6.12.0/mingw_arm64 /opt/mingw-arm64-sysroot dist arm64
```
### Linux Build Environment (Ubuntu 24.04 — x86_64 & ARM64)
Setup via `sudo scripts/install-deps-ubuntu.sh` (add `--with-arm64` to also install Ubuntu `arm64` multiarch packages and `linux_gcc_arm64` Qt 6.12.0; CI targets also use `--skip-qt` and `--only-arm64`):
```bash
# Native x86_64 build & tests
cmake -S . -B build -G Ninja \
-DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_PREFIX_PATH=/opt/qt/6.12.0/gcc_64
ninja -C build
ctest --test-dir build --output-on-failure
# Cross-compiled ARM64 build
cmake -S . -B build-linux-arm64 -G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_TOOLCHAIN_FILE=scripts/linux-arm64-toolchain.cmake \
-DCMAKE_PREFIX_PATH=/opt/qt/6.12.0/gcc_arm64 \
-DQT_HOST_PATH=/opt/qt/6.12.0/gcc_64
cmake --build build-linux-arm64 --target asteria-qt
```
AppImage Packaging (uses `scripts/bundle-linux-appdir.py` + `appimagetool` for both `x86_64` and `arm64`, outputting `Asteria-<arch>.AppImage` (`0755`) and a permission-preserving `Asteria-<arch>.AppImage.tar.gz` archive; `AppRun` auto-integrates `~/.local/share/applications/asteria-qt.desktop`, `hicolor` icons, and Nautilus `metadata::custom-icon` on first launch):
```bash
packaging/package-linux.sh build-linux /opt/qt/6.12.0/gcc_64 dist x86_64
packaging/package-linux.sh build-linux-arm64 /opt/qt/6.12.0/gcc_arm64 dist arm64
```
### GitLab CI Split Docker Images (`docker/Dockerfile.build`)
The CI environment is split into 4 multi-stage targets on `ubuntu:24.04` sharing a common `base` layer (core CLI tools, host `QT_LINUX_DIR` for `QT_HOST_PATH`, and `gitlab-runner`) plus `linux-base` / `windows-base` intermediate layers:
| Image | Docker `--target` | Runner Tag | Purpose |
|---|---|---|---|
| `${CI_REGISTRY_IMAGE}/build-linux-x86_64:latest` | `linux-x86_64` | `linux-x86_64` | `build-linux`, `test-linux`, `package-linux`, `update-wiki` |
| `${CI_REGISTRY_IMAGE}/build-linux-arm64:latest` | `linux-arm64` | `linux-arm64` | `build-linux-arm64`, `package-linux-arm64` |
| `${CI_REGISTRY_IMAGE}/build-windows-x86_64:latest` | `windows-x86_64` | `windows-x86_64` | `build-windows`, `package-windows` |
| `${CI_REGISTRY_IMAGE}/build-windows-arm64:latest` | `windows-arm64` | `windows-arm64` | `build-windows-arm64`, `package-windows-arm64` |
In `.gitlab-ci.yml`, `image-rebuild` pipelines rebuild only the affected target image(s) when relevant files change, or all 4 in parallel when `FORCE_REBUILD_IMAGE=true`.
### macOS Build Environment
```bash
scripts/install-deps-macos.sh
export PKG_CONFIG_PATH="$(brew --prefix libarchive)/lib/pkgconfig:$PKG_CONFIG_PATH"
cmake -B build -G Ninja \
-DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_PREFIX_PATH=/opt/qt/6.12.0/macos
cmake --build build --parallel
ctest --test-dir build --output-on-failure
```
> If Homebrew package updates (e.g. `minizip`) invalidate cached Cellar paths, add `--fresh` (`cmake --fresh -B build ...` or `cmake --fresh --preset debug`) to reconfigure with a clean cache.
Packaging:
```bash
packaging/package-macos.sh build /opt/qt/6.12.0/macos dist
```
Local GitLab Runner (shell executor):
```bash
# First-time registration
RUNNER_TOKEN="glrt-..." scripts/start-runner-macos.sh
# Subsequent runs
scripts/start-runner-macos.sh
```
### Semantic Versioning & CI Release Pipeline
- **Current Version (`VERSION`)**: Tracked in the repository root as `MAJOR.MINOR.PATCH` (automatically updated on `master` after each successful pipeline; bump manually when advancing `MAJOR` or `MINOR`).
- **Version Resolution (`scripts/compute-version.sh`)**:
- **On `master`**: Reads and outputs `MAJOR.MINOR.PATCH` directly from `VERSION`.
- **On feature branches**: Outputs a SemVer 2.0.0 pre-release string `MAJOR.MINOR.PATCH-<sanitized-branch>.<short-sha>` (e.g., `0.1.2-fix-epub.62c08ac`).
- **Build & Metadata Propagation**: `CMakeLists.txt` resolves `ASTERIA_VERSION` (or accepts `-DASTERIA_VERSION=...`), populates `PROJECT_VERSION`, `ASTERIA_VERSION_STRING`, `QApplication::applicationVersion()`, `AppInfo.version`, macOS bundle `Info.plist` (`CFBundleShortVersionString` / `CFBundleVersion`), and Windows `VS_VERSION_INFO` via `src/asteria.rc.in`.
- **CI Isolation, Auto-Bump & Token Rotation (`.gitlab-ci.yml`, `scripts/bump-version.sh`)**:
- `update-wiki` and `bump-version` run strictly on `master` (non-MR pipelines). Feature branches never update the wiki, create tags, or bump `VERSION`.
- At the end of a successful `master` pipeline (`release` stage, after packaging and `update-wiki`), `bump-version` runs `scripts/bump-version.sh`:
1. Checks `GITLAB_TOKEN` expiration via GitLab API and, if within `TOKEN_ROTATE_THRESHOLD_DAYS` (default `30`) and the `GITLAB_TOKEN` CI/CD variable is API-writable, self-rotates the token and updates the CI/CD variable automatically.
2. Creates release tag `vX.Y.Z` at `CI_COMMIT_SHA` via the GitLab Tags API (if absent).
3. Increments `PATCH` in `VERSION` (`X.Y.(Z+1)`), commits `chore: bump version to ... [skip ci]` on `master` via the GitLab Repository Commits API (skipping if remote `VERSION` is already ahead). Tag pipelines (`$CI_COMMIT_TAG`) are skipped in `workflow: rules:` to prevent loops.
### VS Code & CMake Presets
Pre-configured tasks, launch configurations, and CMake presets are available:
- **CMake Presets**: `cmake --preset <debug|release>`, `cmake --build --preset <debug|release>`, `ctest --preset <debug|release>`.
- **VS Code Tasks (`.vscode/tasks.json`)**:
- `CMake: Build (Debug)` (default build shortcut: `Cmd+Shift+B` / `Ctrl+Shift+B`)
- `CMake: Build (Release)`
- `CTest: Run Tests (Debug)` / `CTest: Run Tests (Release)`
- `Run: Asteria (Debug)` / `Run: Asteria (Release)`
- **VS Code Launch Targets (`.vscode/launch.json`)**:
- `Debug: Asteria (Debug - CodeLLDB)` & `Debug: Asteria (Debug - C/C++ cppdbg)`
- `Run: Asteria (Release - CodeLLDB)` & `Run: Asteria (Release - C/C++ cppdbg)`
---
## Architecture
Backend (C++) handles all file I/O, format parsing, text layout calculation, and image decoding. QML handles UI. Communication is through declarative compile-time singletons and types registered in the `Asteria` QML module via `QmlRegistrations.h` and `qt_add_qml_module`.
### Declarative Singletons & Types Exposed to QML (`Asteria` module)
| Type / Singleton | Responsibility |
|---|---|
| `Book` (`Book`) | Open/close book, async loading, error state, metadata (title, author, coverImageUrl). Owns `FormatReader`. |
| `ReadingModel` (`ReadingModel`) | `QAbstractListModel` exposing chunks (`ContentRole`, `LayoutRole`, `PixelHeightRole`), layout updates, reading mode (`isTextMode`, `isMangaMode`), normalized pagination (`currentPage`, `totalPages`, `currentChunk`), manga page pairs, and per-book toggles (`pageShift`, `mangaRTL`, `useBookColours`). |
| `ReadingPreferences` (`ReadingPreferences`) | Font size, line spacing, horizontal margin, vertical margin (`QSettings`). |
| `UiState` (`UiState`) | Current theme, last page, sidebar open state, reader bars visibility (`barsVisible`), last file path, custom theme colors, window geometry. |
| `HistoryModel` (`HistoryModel`) | `QAbstractListModel` of recent books with async metadata extraction and reading progress. Entries store strongly-typed `QDateTime lastOpened`, immediately drop bogus/unparseable dates on deserialization, and are maintained strictly in descending chronological order (`lastOpened desc`). |
| `AppInfo` | Exposes compile-time build configuration (`AppInfo.isDebugBuild`, `AppInfo.version`). |
Backend singletons are exposed using `QML_FOREIGN` wrapper structs in `src/backend/QmlRegistrations.h`. This decouples backend classes from Qt QML engine headers in headless unit test suites while enabling static type checking, Ahead-Of-Time compilation via `qmlcachegen`, and zero-warning `qmllint` passes.
### Additional Registered Types & Providers
- **`KnuthPlassItem`** (`Asteria` module): Custom `QQuickPaintedItem` registered declaratively via `QML_ELEMENT` that draws `ChunkLayout` via `QPainter`. Supports `useBookColours`, `surfaceColor`, theme colour overrides, and WCAG contrast safety fallback for publisher colours.
- **`ThemePalette`** (`Asteria` module): Declarative theme palette base QML type defining all 20 color keys, extended by `DarkTheme`, `LightTheme`, and `ThemeManager.customTheme` for compile-time property verification.
- **`ChunkLayout`**: Declared metatype storing positioned text lines, word runs, inline/block images, rules, and block decorations.
- **Image Providers**:
- `image://fileicon/...`: `FileIconProvider`
- `image://web/...`: `WebImageProvider`
- `image://cbz/...`, `image://cbr/...`, `image://dir/...`, `image://epub/...`, `image://fb2/...`: `EntryImageProvider` registered via `FormatRegistry::registerImageProviders`.
- **`AppCoordinator`**: C++ coordinator wiring signals between `Book`, `ReadingModel`, `HistoryModel`, `UiState`, `ReadingPreferences`, and `AppState`.
---
## Content Model & Reader Interface (`FormatReader.h`)
```cpp
enum class ReadingMode { Comic, Text };
struct PageInfo {
QString imageUrl;
QSize naturalSize;
};
class FormatReader {
public:
virtual ~FormatReader() = default;
virtual ReadingMode mode() const = 0;
virtual bool open(const QString &filePath) = 0;
virtual bool loadMetadata(const QString &filePath);
virtual QString lastError() const = 0;
virtual QString filePath() const = 0;
virtual QString title() const = 0;
virtual QString author() const;
virtual QString coverImageUrl() const;
virtual QByteArray contentHash() const = 0; // MD5 hash for stable persistent state
virtual QVector<PageInfo> pages() const; // Comic mode
virtual QVector<ContentChunk> chunks() const; // Text mode: structured content chunks
};
```
---
## Rendering Architecture
### 1. Text Mode (`ScrollPageView.qml`)
- `ReadingModel` manages a list of `ContentChunk`s (`QVector<ContentChunk>`).
- **Format-Agnostic IR Pipeline (`DocumentIr.h`, `DocumentChunkBuilder.h`)**:
- Readers build intermediate representation (`ContentChunk`, `BlockItem`, `InlineItem`, `BoxStyle`) directly via `DocumentChunkBuilder` without allocating intermediate HTML DOM trees or serializing HTML strings.
- `DocumentChunkBuilder` streams and partitions content chunks (target ~512 chars), normalizes inter-word spacing, trims paragraph whitespace, and handles cross-chunk container splitting and reopening (`unnestedContainers`).
- `HtmlBlockParser` serves as the unified XML/HTML-to-IR converter streaming directly into `DocumentChunkBuilder`. It handles both XHTML (EPUB) and FictionBook (FB2) elements with native semantic tag defaults, CSS cascade, container nesting, and inline styling.
- `Fb2Reader` streams XML sections directly into `HtmlBlockParser::parseChunks()` without synthetic HTML DOM allocations.
- `EpubReader` resolves spine XHTML DOM nodes against in-memory CSS stylesheets (`Css::StyleSheet`) via `HtmlBlockParser::parseChunks()`, streaming directly into `DocumentChunkBuilder` with on-the-fly image URL resolution and zero DOM string mutations.
- `TxtReader` streams plain text files (`.txt`) directly into `DocumentChunkBuilder`, identifying Gutenberg metadata headers (`Title`, `Author`), unwrapping paragraph lines, detecting scene transitions, and validating content against binary, encrypted, or corrupted payloads (null bytes, control characters >2%, and excessive unmappable replacement characters >20%).
- `TextEncoding` provides unified BOM/XML/HTML/uchardet/heuristic/iconv encoding detection across `FB2`, `TXT`, and queued formats (`MOBI`, `PDB`).
- `HtmlBlockParser` and `Fb2Reader` normalize paragraph typography across EPUB (`<div class="paragraph">` and `<p>`) and FB2 (`<p>`): unstyled paragraphs default to zero vertical margins (`marginTop = 0`, `marginBottom = 0`) and `2.0em` first-line indent (`textIndent = 2.0 * baseFontSize`), eliminating `ContainerStart`/`ContainerEnd` box allocation overhead and preventing blank vertical gaps between prose/dialogue lines. Explicit CSS margins in publisher stylesheets override this default. Shorthand `margin` and `padding` (1 to 4 token syntax) are fully parsed.
- Headings (`h1`..`h6`) default to left-aligned (`TextAlign::Left`) without first-line indentation (`textIndent = 0`). In `Fb2Reader`, `<title>` flattens child `<p>` lines separated by `<br/>` with `text-align: left; text-indent: 0;`, preventing nested paragraph indent on titles. Scene transitions via FB2 `<empty-line>` use explicit margins to provide intended section gaps.
- When viewport geometry or font preferences change, `ReadingModel::updateLayoutMetrics()` runs `ChunkLayoutEngine` off-thread:
- Pre-parsed `BlockItem`s in `ContentChunk` scale dynamically with user font preferences in `ChunkLayoutEngine::prepareBlocks()` with zero HTML/XML re-parsing.
- `KnuthPlass` computes optimal justified/aligned line breaks. Inline forced breaks (`<br/>`, `InlineItem::Kind::LineBreak`) use `finishLine()` to append infinite stretch glue (`kInfiniteStretch`), ensuring short lines ending at `<br/>` are not justified to full width and do not push the paragraph into loose/emergency fallback passes.
- Overly stretched line fallback: When a line's stretch ratio in a justified paragraph exceeds `tolerance` (`line.ratio > 2.0`), `ChunkLayoutEngine` falls back to natural inter-word spacing (left alignment) rather than stretching words across the viewport with large gaps.
- `BookImageResolver` resolves embedded image dimensions and URLs.
- Off-thread calculation stores `ChunkLayout` and pixel heights.
- **Two-Phase Visible-First Layout**: On book open and font changes, `ReadingModel::startLayoutMeasurement()` computes layout for the visible window around the anchor chunk synchronously (<1ms) and emits `restoreReady(chunkIndex, intraOffset)` immediately so the visible screen renders on the first frame, while the background thread computes remaining off-screen chunks and updates only non-visible model ranges. On-demand layout guards ensure any chunk scrolled to before background completion is measured instantly.
- Rendered in a strictly virtualized `ListView` (`cacheBuffer: 0`, `reuseItems: true`, high flick velocity) using `KnuthPlassItem` as the direct delegate, preserving smooth scrolling without allocating off-screen delegate textures.
- **Debug Chunk Index**: In debug builds (`isDebugBuild`), displays the chunk index at the top-left of each list item (`x: 4, y: 2`), ignoring `horizontalMargin`.
- **Clip-Rect Culling in `KnuthPlassItem`**: `paint()` inspects `painter->clipBoundingRect()`, skips decorations/rules outside the clip, uses $O(\log N)$ binary search (`std::lower_bound`) to draw only lines intersecting the clip, and skips off-screen image decoding/resolution completely.
- **Publisher Colours vs Theme**: Controlled by per-book `useBookColours` setting (default `false`).
- When off: paints with theme palette (`readingText`, `dimText`, `buttonAccent`), omitting publisher backgrounds and border boxes (semantic blockquote bars with only `borderLeft` and no explicit border colour are drawn in `dimText`).
- When on: paints publisher backgrounds and border colours, using WCAG contrast calculation (`contrastRatio < 3.0`) to automatically select high-contrast black or white text when publisher or theme text colours would be unreadable on the effective background.
- Toggling `useBookColours` operates entirely at paint time in `KnuthPlassItem`—zero off-thread relayout, zero position shift, and instant response.
- **Normalized Page Counting & Viewport Invariance**: In text mode, `totalPages` and `currentPage` report normalized pages based on publishing standards (1,800 characters per page "Normopage" / 30 lines × 60 characters, ~250–300 words).
- Derived from an $O(1)$ prefix sum array (`m_chunkCumulativeChars`) and the intra-chunk scroll offset (`intraFraction = intraOffset / totalHeight`), ensuring page numbers and total page counts remain 100% constant across window resizing, maximizing, font scaling, and line spacing adjustments. Standalone illustration images are weighted as 1 standard page (1,800 characters).
- `ReadingModel::currentChunk` exposes the internal 0-based layout chunk index (`0 .. rowCount - 1`) used by `ScrollPageView.qml` and `ChunkLayoutEngine` for layout calculations and scroll anchoring, cleanly decoupled from user-facing `currentPage`.
- Scrolling tracks top visible chunk and `intraOffset`.
### 2. Manga / Comic Mode (`MangaPageView.qml`)
- Driven by `MangaPagination`.
- Dynamically pairs pages into two-page spreads when in landscape mode, maintaining spine alignment (no seams between pages).
- Supports RTL mode (`mangaRTL` property), cover page shift (`pageShift`), and touch/swipe gestures or 3-zone tap navigation.
---
## Position Restoration & State Persistence
- **History Persistence & Ordering**: `AppState` persists the history list. On deserialization (`HistoryModel::load`), timestamps are converted to strongly-typed `QDateTime`, and bogus or unparseable timestamps are immediately dropped. Loaded entries are sorted in descending chronological order (`lastOpened desc`). Runtime updates (`addOrUpdateBook`) preserve this descending chronological order without inversions.
- **Position Persistence**: `BookPositionStore` persists `BookPosition` (`chunkIndex`, `intraOffset`, `progress`, `pageShift`, `mangaRTL`, `useBookColours`) indexed by file content MD5 (`contentHash()`), ensuring state survives file renames or moves.
- **UI State Persistence**: `UiState` persists `themeName`, `lastPage`, `sidebarOpen`, `barsVisible`, `lastFilePath`, `customTheme`, and window geometry. Distraction-free chrome toggling via spacebar toggles `barsVisible` without destroying the persistent `sidebarOpen` user preference; effective sidebar visibility in reader mode is gated by `(!inReader || barsVisible) && uiState.sidebarOpen`. Navigating away from the reader to `History` or `Custom Theme` (or opening a new file) closes the active/loading book via `Book.close()` (cancelling in-flight loads, snapshotting progress into `HistoryModel`, resetting `ReadingModel`, and clearing `UiState.lastFilePath`), while opening the `Settings` popup keeps the current book open.
- **Restoration Flow**:
- Text mode: `ReadingModel` computes layout for the saved anchor chunk first, then emits `restoreReady(chunkIndex, intraOffset)`. `ScrollPageView` positions the `ListView` at `chunkIndex` and applies `intraOffset`.
- Comic mode: `restoreReady(chunkIndex)` triggers `MangaPageView.showPair(pairIndexForChunk(chunkIndex))`.
---
## Format Registry
Driven by `FormatSpec` table built in `main.cpp`:
- `FormatSpec::comic(ext, matchesDirectory, scheme, makeSource)`
- `FormatSpec::epub(makeSource)`
- `FormatSpec::fb2(ext, makeSource)`
- `FormatSpec::txt(ext)`
Each format registers its file extension / directory matcher, reader factory, `IByteSource` factory, and image URL scheme in a single table entry.
---
## Design & Color Scheme
Asteria supports **Dark**, **Light**, and user-editable **Custom** themes:
- Managed by `ThemeManager.qml` singleton (`pragma Singleton`).
- Color definitions reside in `DarkTheme.qml`, `LightTheme.qml`, and `ThemeManager.customTheme`.
- In QML, all colors are referenced via `ThemeManager.currentTheme.<colorKey>` (e.g. `ThemeManager.currentTheme.surface`).
- Custom theme colors can be edited in `CustomThemePage.qml` and are persisted in `UiState`.
- Never hardcode hex values in QML components.
---
## File Structure
```
VERSION
scripts/
bump-version.sh
compute-version.sh
src/
asteria.rc.in
main.cpp
backend/
AppCoordinator.h/cpp
AppState.h/cpp
FormatReader.h
HistoryModel.h/cpp
IFileDialogService.h
MacMenuBar.h/mm
NativeFileDialogService.h/cpp
PortalFileDialogService.h/cpp
QmlRegistrations.h
ReadingModel.h/cpp
book/
Book.h/cpp
formats/
AsyncImageResponse.h/cpp
AuthorAttribution.h/cpp
EntryImageProvider.h/cpp
EpubReader.h/cpp
Fb2Reader.h/cpp
Fb2Types.h
FileIconProvider.h/cpp
FormatRegistry.h/cpp
HtmlEntities.h/cpp
IByteSource.h
ImageExtensions.h
ImageScaling.h
ImageUrl.h/cpp
TextEncoding.h/cpp
TxtReader.h/cpp
WebImageProvider.h/cpp
comic/
ComicReader.h/cpp
sources/
DirByteSource.h/cpp
Fb2ByteSource.h/cpp
RarByteSource.h/cpp
ZipByteSource.h/cpp
reading/
BookImageResolver.h/cpp
KnuthPlassItem.h/cpp
MangaPagination.h/cpp
layout/
ChunkLayoutEngine.h/cpp
CssParser.h/cpp
DocumentChunkBuilder.h/cpp
DocumentIr.h
HtmlBlockParser.h/cpp
KnuthPlass.h/cpp
state/
BookPositionStore.h/cpp
ReadingPreferences.h/cpp
UiState.h/cpp
qml/
DarkTheme.qml
LightTheme.qml
Main.qml
ThemeManager.qml
ThemePalette.qml
components/
ErrorPopup.qml
FlatIconButton.qml
Footer.qml
Header.qml
LabeledSlider.qml
LabeledSwitch.qml
MangaPageView.qml
ScrollPageView.qml
SettingsPopup.qml
SideBar.qml
SideBarButton.qml
UpdatePopup.qml
pages/
CustomThemePage.qml
HistoryPage.qml
ReaderPage.qml
StarterPage.qml
specs/
knuth-plass-rendering.allium
tests/
AppCoordinatorTest.cpp
AppStateTest.cpp
EntryImageProviderTest.cpp
FileIconProviderTest.cpp
FormatRegistryTest.cpp
HistoryModelTest.cpp
ReadingModelTest.cpp
book/
BookTest.cpp
formats/
CbzReaderTest.cpp
EpubReaderTest.cpp
Fb2ReaderTest.cpp
FolderReaderTest.cpp
ImageUrlTest.cpp
TextEncodingTest.cpp
TxtReaderTest.cpp
WebImageProviderTest.cpp
reading/
KnuthPlassRenderingSpecTest.cpp
ChunkLayoutEngineTest.cpp
KnuthPlassTest.cpp
CssParserTest.cpp
MangaPaginationTest.cpp
TextLayoutEngineSpecTest.cpp
state/
BookPositionStoreTest.cpp
ReadingPreferencesTest.cpp
UiStateTest.cpp
```
---
## Qt Conventions
- **Qt 6.12+** preferred — no Qt5 compat shims.
- All UI in **QML**; C++ for logic, parsing, and heavy computation.
- Expose C++ backend singletons declaratively in the `Asteria` QML module via `QML_FOREIGN` wrappers (`QmlRegistrations.h`) and `QML_ELEMENT` for custom items (`KnuthPlassItem`). Avoid runtime `rootContext()->setContextProperty()` so `qmllint` and `qmlcachegen` statically type-check all bindings and properties ahead of time.
- Main window starts with opacity 0 and ticks to 1 on a short timer to prevent white window flash during initial render.