Files
asteria-qt/AGENTS.md
T
2026-10-25 20:12:23 +01:00

268 lines
11 KiB
Markdown

# 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.
---
## Format Support
Active implementation: **EPUB, CBZ, CBR, Folder of images**
Queued for reimplementation on new render pipeline: **TXT, FB2**
Full target format list:
| Format | Active | Approach |
|---|---|---|
| EPUB | Yes | Unzip (`ZipByteSource`) + parse OPF spine + CSS parser + Knuth-Plass text layout |
| CBZ | Yes | Unzip (`ZipByteSource`) + `ComicReader` + `MangaPagination` (single/dual page spread) |
| CBR | Yes | `libarchive` (`RarByteSource`) + `ComicReader` + `MangaPagination` |
| Folder | Yes | Directory scan (`DirByteSource`) + `ComicReader` + `MangaPagination` |
| FB2 | Queued | `QXmlStreamReader` + convert sections to chunks for `ChunkLayoutEngine` |
| TXT | Queued | `QTextStream` + encoding detection + paginate for `ChunkLayoutEngine` |
| 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` |
---
## Build & Install
### Dependencies
- Qt 6.10+ components: `Core`, `Gui`, `Qml`, `Quick`, `Widgets`, `Concurrent`, `Svg`, `QuickControls2`, `Test`, `Xml`, `Network`, optional `DBus`.
- Third-party packages: `minizip`, `libarchive`.
- Graphics API: Vulkan (Windows, Linux), Metal (macOS) configured via `QQuickWindow::setGraphicsApi()`.
### Windows Build Environment
Qt 6.10.3 at `C:\msys64\opt\qt\6.10.3\mingw_64`. 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.10.3\mingw_64"
PATH="/c/msys64/mingw64/bin:$PATH" "C:/msys64/mingw64/bin/ninja.exe" -C build
PATH="/c/msys64/opt/qt/6.10.3/mingw_64/bin:/c/msys64/mingw64/bin:$PATH" "C:/msys64/mingw64/bin/ctest.exe" --test-dir build --output-on-failure
```
### Linux Build Environment (Ubuntu 24.04)
```bash
cmake -S . -B build -G Ninja \
-DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_PREFIX_PATH=/opt/qt/6.10.3/gcc_64
ninja -C build
ctest --test-dir build --output-on-failure
```
### macOS Build Environment
```bash
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.10.3/macos
cmake --build build --parallel
ctest --test-dir build --output-on-failure
```
---
## Architecture
Backend (C++) handles all file I/O, format parsing, text layout calculation, and image decoding. QML handles UI. Communication is through `QObject` models and context properties.
### QObjects Exposed to QML
| Object | 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`), and manga page pairs. |
| `readingPreferences` (`ReadingPreferences`) | Font size, line spacing, horizontal margin, vertical margin (`QSettings`). |
| `uiState` (`UiState`) | Current theme, last page, sidebar open state, last file path, custom theme colors, window geometry. |
| `historyModel` (`HistoryModel`) | `QAbstractListModel` of recent books with async metadata extraction and reading progress. |
| `isDebugBuild` | Boolean constant indicating debug build. |
### Additional Registered Types & Providers
- **`KnuthPlassItem`** (`Asteria` module): Custom `QQuickPaintedItem` that draws `ChunkLayout` via `QPainter`.
- **`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/...`: `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 QStringList chunks() const; // Text mode: HTML fragments
};
```
---
## Rendering Architecture
### 1. Text Mode (`ScrollPageView.qml`)
- `ReadingModel` manages a list of HTML chunks.
- When viewport geometry or font preferences change, `ReadingModel::updateLayoutMetrics()` runs `ChunkLayoutEngine` off-thread:
- `HtmlBlockParser` extracts structured blocks (`Paragraph`, `ImageBlock`, `Rule`, `Container`).
- `CssParser` evaluates stylesheets and styles inline tags.
- `KnuthPlass` computes optimal justified/aligned line breaks.
- `BookImageResolver` resolves embedded image dimensions and URLs.
- Off-thread calculation stores `ChunkLayout` and pixel heights.
- Rendered in a virtualized `ListView` (`cacheBuffer: 600`, high flick velocity) using `KnuthPlassItem`.
- 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
- **Position Persistence**: `BookPositionStore` persists `BookPosition` (`chunkIndex`, `intraOffset`, `progress`, `pageShift`, `mangaRTL`) indexed by file content MD5 (`contentHash()`), ensuring state survives file renames or moves.
- **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)`
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
```
src/
main.cpp
backend/
AppCoordinator.h/cpp
AppState.h/cpp
FormatReader.h
HistoryModel.h/cpp
IFileDialogService.h
NativeFileDialogService.h/cpp
PortalFileDialogService.h/cpp
ReadingModel.h/cpp
book/
Book.h/cpp
formats/
AsyncImageResponse.h/cpp
EntryImageProvider.h/cpp
EpubReader.h/cpp
FileIconProvider.h/cpp
FormatRegistry.h/cpp
HtmlEntities.h/cpp
IByteSource.h
ImageExtensions.h
ImageScaling.h
ImageUrl.h/cpp
WebImageProvider.h/cpp
comic/
ComicReader.h/cpp
sources/
DirByteSource.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
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
components/
ErrorPopup.qml
FlatIconButton.qml
Footer.qml
Header.qml
LabeledSlider.qml
MangaPageView.qml
ScrollPageView.qml
SettingsPopup.qml
SideBar.qml
SideBarButton.qml
pages/
CustomThemePage.qml
HistoryPage.qml
ReaderPage.qml
StarterPage.qml
```
---
## Qt Conventions
- **Qt 6.10+** preferred — no Qt5 compat shims.
- All UI in **QML**; C++ for logic, parsing, and heavy computation.
- Expose C++ to QML via `rootContext()->setContextProperty()` or `qmlRegisterType`.
- Main window starts with opacity 0 and ticks to 1 on a short timer to prevent white window flash during initial render.