21 KiB
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 (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
- 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.mdin the same commit/task. Never allow documentation to diverge from the codebase. - 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.
- Strictly Follow SOLID Principles: Keep format decoders, layout engines, image providers, and UI models cleanly decoupled.
- Maintain High Test Coverage (80%+): Use the
Qt Test(QTest) framework. Always runctest --test-dir build --output-on-failureafter code modifications. - 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), CBZ, CBR, Folder of images
Queued for reimplementation on new render pipeline: TXT
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 | Queued | TextEncoding + direct streaming into DocumentChunkBuilder + Knuth-Plass |
| 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.10+ components:
Core,Gui,Qml,Quick,Widgets,Concurrent,Svg,QuickControls2,Test,Xml,Network, optionalDBus. - Third-party packages:
minizip,libarchive,iconv.
Windows Build Environment
Qt 6.10.3 at C:\msys64\opt\qt\6.10.3\mingw_64. MinGW toolchain at C:\msys64\mingw64\bin\:
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)
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
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
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 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), 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). |
isDebugBuild |
Boolean constant indicating debug build. |
Additional Registered Types & Providers
KnuthPlassItem(Asteriamodule): CustomQQuickPaintedItemthat drawsChunkLayoutviaQPainter. SupportsuseBookColours,surfaceColor, theme colour overrides, and WCAG contrast safety fallback for publisher colours.ChunkLayout: Declared metatype storing positioned text lines, word runs, inline/block images, rules, and block decorations.- Image Providers:
image://fileicon/...:FileIconProviderimage://web/...:WebImageProviderimage://cbz/...,image://cbr/...,image://dir/...,image://epub/...,image://fb2/...:EntryImageProviderregistered viaFormatRegistry::registerImageProviders.
AppCoordinator: C++ coordinator wiring signals betweenBook,ReadingModel,HistoryModel,UiState,ReadingPreferences, andAppState.
Content Model & Reader Interface (FormatReader.h)
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)
ReadingModelmanages a list ofContentChunks (QVector<ContentChunk>).- Format-Agnostic IR Pipeline (
DocumentIr.h,DocumentChunkBuilder.h):- Readers build intermediate representation (
ContentChunk,BlockItem,InlineItem,BoxStyle) directly viaDocumentChunkBuilderwithout allocating intermediate HTML DOM trees or serializing HTML strings. DocumentChunkBuilderstreams and partitions content chunks (target ~512 chars), normalizes inter-word spacing, trims paragraph whitespace, and handles cross-chunk container splitting and reopening (unnestedContainers).HtmlBlockParserserves as the unified XML/HTML-to-IR converter streaming directly intoDocumentChunkBuilder. It handles both XHTML (EPUB) and FictionBook (FB2) elements with native semantic tag defaults, CSS cascade, container nesting, and inline styling.Fb2Readerstreams XML sections directly intoHtmlBlockParser::parseChunks()without synthetic HTML DOM allocations.EpubReaderresolves spine XHTML DOM nodes against in-memory CSS stylesheets (Css::StyleSheet) viaHtmlBlockParser::parseChunks(), streaming directly intoDocumentChunkBuilderwith on-the-fly image URL resolution and zero DOM string mutations.TextEncodingprovides unified BOM/XML/HTML/iconv encoding detection acrossFB2and queued formats (TXT,MOBI,PDB).
- Readers build intermediate representation (
HtmlBlockParserandFb2Readernormalize paragraph typography across EPUB (<div class="paragraph">and<p>) and FB2 (<p>): unstyled paragraphs default to zero vertical margins (marginTop = 0,marginBottom = 0) and2.0emfirst-line indent (textIndent = 2.0 * baseFontSize), eliminatingContainerStart/ContainerEndbox allocation overhead and preventing blank vertical gaps between prose/dialogue lines. Explicit CSS margins in publisher stylesheets override this default. Shorthandmarginandpadding(1 to 4 token syntax) are fully parsed.- Headings (
h1..h6) default to left-aligned (TextAlign::Left) without first-line indentation (textIndent = 0). InFb2Reader,<title>flattens child<p>lines separated by<br/>withtext-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.
- Format-Agnostic IR Pipeline (
- When viewport geometry or font preferences change,
ReadingModel::updateLayoutMetrics()runsChunkLayoutEngineoff-thread:- Pre-parsed
BlockItems inContentChunkscale dynamically with user font preferences inChunkLayoutEngine::prepareBlocks()with zero HTML/XML re-parsing. KnuthPlasscomputes optimal justified/aligned line breaks.BookImageResolverresolves embedded image dimensions and URLs.- Off-thread calculation stores
ChunkLayoutand pixel heights.
- Pre-parsed
- 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 emitsrestoreReady(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) usingKnuthPlassItemas 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), ignoringhorizontalMargin.
- Debug Chunk Index: In debug builds (
- Clip-Rect Culling in
KnuthPlassItem:paint()inspectspainter->clipBoundingRect(), skips decorations/rules outside the clip, usesO(\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
useBookColourssetting (defaultfalse).- When off: paints with theme palette (
readingText,dimText,buttonAccent), omitting publisher backgrounds and border boxes (semantic blockquote bars with onlyborderLeftand no explicit border colour are drawn indimText). - 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
useBookColoursoperates entirely at paint time inKnuthPlassItem—zero off-thread relayout, zero position shift, and instant response.
- When off: paints with theme palette (
- Normalized Page Counting & Viewport Invariance: In text mode,
totalPagesandcurrentPagereport 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::currentChunkexposes the internal 0-based layout chunk index (0 .. rowCount - 1) used byScrollPageView.qmlandChunkLayoutEnginefor layout calculations and scroll anchoring, cleanly decoupled from user-facingcurrentPage.
- Derived from an
- 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 (
mangaRTLproperty), cover page shift (pageShift), and touch/swipe gestures or 3-zone tap navigation.
Position Restoration & State Persistence
- History Persistence & Ordering:
AppStatepersists the history list. On deserialization (HistoryModel::load), timestamps are converted to strongly-typedQDateTime, 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:
BookPositionStorepersistsBookPosition(chunkIndex,intraOffset,progress,pageShift,mangaRTL,useBookColours) indexed by file content MD5 (contentHash()), ensuring state survives file renames or moves. - UI State Persistence:
UiStatepersiststhemeName,lastPage,sidebarOpen,barsVisible,lastFilePath,customTheme, and window geometry. Distraction-free chrome toggling via spacebar togglesbarsVisiblewithout destroying the persistentsidebarOpenuser preference; effective sidebar visibility in reader mode is gated by(!inReader || barsVisible) && uiState.sidebarOpen. - Restoration Flow:
- Text mode:
ReadingModelcomputes layout for the saved anchor chunk first, then emitsrestoreReady(chunkIndex, intraOffset).ScrollPageViewpositions theListViewatchunkIndexand appliesintraOffset. - Comic mode:
restoreReady(chunkIndex)triggersMangaPageView.showPair(pairIndexForChunk(chunkIndex)).
- Text mode:
Format Registry
Driven by FormatSpec table built in main.cpp:
FormatSpec::comic(ext, matchesDirectory, scheme, makeSource)FormatSpec::epub(makeSource)FormatSpec::fb2(ext, makeSource)Each format registers its file extension / directory matcher, reader factory,IByteSourcefactory, and image URL scheme in a single table entry.
Design & Color Scheme
Asteria supports Dark, Light, and user-editable Custom themes:
- Managed by
ThemeManager.qmlsingleton (pragma Singleton). - Color definitions reside in
DarkTheme.qml,LightTheme.qml, andThemeManager.customTheme. - In QML, all colors are referenced via
ThemeManager.currentTheme.<colorKey>(e.g.ThemeManager.currentTheme.surface). - Custom theme colors can be edited in
CustomThemePage.qmland are persisted inUiState. - 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
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
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
components/
ErrorPopup.qml
FlatIconButton.qml
Footer.qml
Header.qml
LabeledSlider.qml
LabeledSwitch.qml
MangaPageView.qml
ScrollPageView.qml
SettingsPopup.qml
SideBar.qml
SideBarButton.qml
pages/
CustomThemePage.qml
HistoryPage.qml
ReaderPage.qml
StarterPage.qml
specs/
knuth-plass-rendering.allium
tests/
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
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.10+ preferred — no Qt5 compat shims.
- All UI in QML; C++ for logic, parsing, and heavy computation.
- Expose C++ to QML via
rootContext()->setContextProperty()orqmlRegisterType. - Main window starts with opacity 0 and ticks to 1 on a short timer to prevent white window flash during initial render.