mbook
mbook is a file format for books: chapters in Markdown, pictures in AVIF, and small typed tables that describe the book, all stored as independent OpenZL frames inside one indexed container.
The pairing of OpenZL and AVIF is what makes a book small and quick: an illustrated EPUB of 7.0 MB became an mbook file of 1.6 MB that opens in 80 µs and decodes its text at more than a gigabyte per second. The conditions are in RFC 0001, A converted book.
This site holds the specification of the format and the documentation of the three crates built on it.
| Part | What it is | Start at |
|---|---|---|
| The format | The specification every reader and writer is checked against, and the decisions behind it | RFC 0001 |
mbook | The Rust library that reads, edits and writes mbook files | mbook |
mbook-converter | The Rust library that turns EPUB, FB2, PDF and five other formats into mbook, and back | mbook-converter |
mbook-ui | The application: a library of books, a reader and an editor | mbook-ui |
Where to start
| If you want to… | Read |
|---|---|
| see what the format gains over EPUB and FB2 | RFC 0001, Motivation |
| see what a file contains and how it is opened | RFC 0001, guide-level explanation |
| implement a reader or a writer | RFC 0001, reference-level explanation |
| understand why the format looks this way | Decision records |
| read or write books from Rust | Using mbook |
| look up a type or a call of the library | mbook, API reference, or docs.rs |
| convert a book into mbook, or export one | Using mbook-converter |
| know what a conversion keeps and what it drops | Conversion rules |
| read and edit books without writing code | Using the application |
| work on the application | mbook-ui, Architecture |
| know what is still open | Unresolved questions of RFC 0001, and "Settled and open questions" of mbook, mbook-converter and mbook-ui |
Two kinds of document
The format is specified; the crates are described.
| The format | A crate | |
|---|---|---|
| Documents | RFC 0001 and the decision records | The pages of mbook, mbook-converter and mbook-ui |
| Says | What a file MUST contain and what a reader MUST do with it | What the code does today, and why it is built this way |
| Binds | Every implementation of the format, in any language | This repository only |
| A choice between alternatives is recorded | As a decision record (ADR) | In the "Rationale and alternatives" table of the crate's Design page |
| Changes | When the format changes | With the code, in the same change |
An RFC specifies behaviour: it is what an implementation is checked against. A decision record explains one choice the RFC makes: the options that were compared, the trade-off, and what follows from it. The RFC links to the records instead of repeating them.
The pages of a crate are not normative. They describe what exists, mark what is not implemented, and where they say that something "must" hold, they state an invariant of this code that a test or a review keeps. RFC 0002 to RFC 0004, which described the three crates in earlier versions of this site, became these pages; the old addresses lead to them.
| Page of a crate | What it answers |
|---|---|
| Overview | What the crate is, what it is for, its goals and non-goals. |
| Guide | How each task is done, with its code or its screen. |
| API reference, Conversion rules, Architecture | What exactly the crate does: its types, its rules, its parts. |
| Design | Its dependencies, what the design costs, the alternatives that were rejected, and what is still open. |
Documents
| Document | Title | Status |
|---|---|---|
| RFC 0001 | The mbook file format, version 1 | Draft |
| ADR-0001 … ADR-0011 | Decisions behind RFC 0001 | See the overview |
| mbook | The library that reads and writes the format | Implements the whole of RFC 0001 |
| mbook-converter | Import from eight formats, export to the same eight | Implemented; limits per format |
| mbook-ui | The reading and editing application | A first version; what is implemented |
Outline of an RFC
| Section | What it answers |
|---|---|
| Summary | What is proposed, in a paragraph. |
| Motivation | Why the format needs it; goals and non-goals. |
| Guide-level explanation | How it looks to someone packing or reading a book. |
| Reference-level explanation | The normative rules an implementation follows. |
| Drawbacks | What the design costs. |
| Rationale and alternatives | The decisions taken, with links to their records. |
| Prior art | Related formats and what was taken from them. |
| Unresolved questions | What must be settled before the RFC is accepted. |
| Future possibilities | What the design leaves room for. |
Reading the normative text
The key words MUST, MUST NOT, REQUIRED, SHOULD, SHOULD NOT, RECOMMENDED, MAY and OPTIONAL are to be interpreted as described in RFC 2119 and RFC 8174 when, and only when, they appear in capitals. They are used in the Reference-level explanation of an RFC and nowhere else: everything outside that section, and every page of a crate, is informative.
Building this site
The site is an mdBook in the docs
folder of the
repository, with
mdbook-mermaid for the diagrams.
It is published to GitHub Pages from the main branch.
Extract the diagram scripts once:
mdbook-mermaid install docs
Then serve the book with live reload:
mdbook serve docs --open
The HTML is written to target/book.
RFC 0001: The mbook file format, version 1
| Status | Draft |
| Start date | 2026-11-21 |
| Format version defined | 1.0 |
| File extension | .mbook |
Summary
An mbook file is one indexed container of independent OpenZL frames. The first five frames are fixed: a format header, the book's metadata, a table of every resource, the table of contents, and a table of heading anchors. Chapters follow as GitHub Flavored Markdown without raw HTML, and pictures as AVIF files stored without recompression. A book may also carry diagrams, described in Mermaid notation, and formulas, written in the notation of KaTeX; a chapter shows them the way it shows a picture. Markdown refers to pictures, diagrams, formulas and other chapters by relative path; the resource table maps a path to a frame. A link into a chapter names a heading, or any other line that the chapter gives a name to with one line of Markdown.
Motivation
A book file should be small, open instantly, load only what is on screen, and be readable by a small program. Each format in use gives up at least one of these:
- EPUB is a ZIP of XHTML and CSS. Showing it correctly needs a web engine, and its metadata is spread over several XML files.
- FB2 is a single XML document. Nothing can be read without parsing all of it, and pictures are Base64 text inside the XML.
- Markdown in a folder is easy to write and to render, but it is not one file, carries no metadata, and has no index.
mbook keeps the Markdown-and-pictures model and packs it into a container that already provides random access, per-resource checksums and typed data. Two codecs do the heavy work: OpenZL compresses text and tables, and AVIF holds the pictures.
- A book is a fraction of the size. An EPUB of 7.0 MB became an mbook file of 1.6 MB, more than four times smaller (A converted book). Most of that is AVIF; the text is smaller as well, because Markdown carries less markup than XHTML.
- A book is on screen before the eye notices. A reader fetches the footer, the index and the first five frames, and can then show the title, the cover and the table of contents. For that book the tables were ready in 80 µs.
- Decoding is never the slow part. Each chapter, picture, diagram and formula is decoded on its own, and text decodes at more than a gigabyte per second: the largest chapter of that book in 0.1 ms.
- Nothing has to be parsed to find something. The descriptive tables are
typed columns, so no JSON, XML or TOML parser is needed, and the container
layer can be built for
no_stdtargets. - No part of it is exotic. Every frame is an ordinary OpenZL frame that uses only standard codecs. A stock OpenZL decoder can decode any frame extracted from the file, and any AVIF decoder shows a picture.
Goals
| Goal | How the design meets it |
|---|---|
| A small file | Pictures are AVIF; text and tables are OpenZL frames; columns have types, so numbers are stored as numbers. A 7.0 MB EPUB became 1.6 MB (A converted book). |
| Open a book without reading all of it | Footer, directory and five small frames are enough for title, cover and contents: 80 µs for a book of 167 contents entries. |
| Decode only what is shown | One frame per chapter, picture, diagram and formula. |
| Decoding that is never the slow part | Text decodes at more than 1 GB/s, tens of times faster than the same text is parsed as Markdown. Pictures are stored AVIF files, read without a second decompression. |
| A page that does not jump | The resources table gives the size of every picture before one is decoded, so a reader lays out the page first. |
| Formulas and diagrams that follow the text | Stored as their source, not as pictures of it; the reader sets them in its own size and tone. |
| Readers without a web engine | Markdown without raw HTML; no CSS, no scripts. |
| Readers without text-format parsers | Metadata and navigation are typed columns. |
| Round trip with a plain folder | Chapters refer to pictures and chapters by relative path. |
| Recognisable by simple tools | A constant signature at fixed file offsets. |
Non-goals
- Fixed layout. Fonts, margins and pagination belong to the reader.
- Editing in place. A file is written once; changing a book means repacking it.
- Protection. No encryption, signatures or rights management.
- Audio and video. Left to a later version (Future possibilities).
Guide-level explanation
What is in a file
flowchart TD
meta["1 · meta<br/>key, value"]
res["2 · resources<br/>kind, path, width, height"]
toc["3 · toc<br/>level, title, resource, offset"]
anc["4 · anchors<br/>resource, offset, name"]
ch["text resources<br/>chapters in Markdown"]
own["anchor table of a chapter<br/>offset, name"]
pic["picture resources<br/>AVIF files"]
fig["diagram and formula resources<br/>Mermaid and KaTeX text"]
meta -- "cover: a path" --> res
ch -- "path of a link or picture" --> res
res -- "row number is the resource number" --> fig
ch -- "fragment of a link:<br/>a heading" --> anc
ch -- "fragment of a link:<br/>another line" --> own
own -- "offset in the resource<br/>that follows it" --> ch
res -- "row number is the resource number" --> ch
res -- "row number is the resource number" --> pic
toc -- "resource, offset" --> ch
anc -- "resource, offset" --> ch
Resource 0, the format header, refers to nothing and is not shown. In file order:
resource 0 format "MBOOK\0", major, minor 8 bytes, stored
resource 1 meta key, value strings
resource 2 resources kind, path, width, height one row per resource
resource 3 toc level, title, resource, offset table of contents
resource 4 anchors resource, offset, name heading anchors
resource 5… landmarks, when the book has any; the cover picture; then
chapters, then pictures, diagrams and formulas;
a chapter that names other lines follows its own anchor table
index + footer provided by the container
Unpacked, a book is a folder that any Markdown viewer can show:
ch01.md
ch02.md
img/cover.avif
img/fig-3.avif
dia/route.mmd
math/speed.tex
What a chapter looks like
# Chapter 3. The Seventh Proof
Text with a footnote[^n1] and a [link to the first chapter](ch01.md#chapter-1).

A line of verse\
and the second line.
[^n1]: The text of the footnote.
img/fig-3.avifis looked up in the resource table and gives the number of the frame that holds the picture, together with its pixel size.ch01.md#chapter-1is looked up in the resource table (the chapter) and then in the anchor table (the position inside it). A name that is not that of a heading is looked up in the anchor table of the chapter itself (Anchors that are not headings).- A paragraph that contains only a picture is a figure; the link title is its caption.
A complete example
A book with two chapters, a cover and one figure has nine resources. Its four tables, as rows:
meta
| key | value |
|---|---|
title | The Example |
lang | en |
id | urn:uuid:3f1c2a7e-8a54-4d0b-9c1e-6b2f0d9a7e11 |
author | A. Writer |
cover | img/cover.avif |
resources
| row | kind | path | width | height |
|---|---|---|---|---|
| 0–4 | 0 | 0 | 0 | |
| 5 | 2 | img/cover.avif | 1200 | 1800 |
| 6 | 1 | ch01.md | 0 | 0 |
| 7 | 1 | ch02.md | 0 | 0 |
| 8 | 2 | img/fig-1.avif | 1600 | 900 |
toc
| level | title | resource | offset |
|---|---|---|---|
| 1 | Chapter 1. Arrival | 6 | 0 |
| 2 | The station | 6 | 130 |
| 1 | Chapter 2. The letter | 7 | 0 |
anchors
| resource | offset | name |
|---|---|---|
| 6 | 0 | chapter-1-arrival |
| 6 | 130 | the-station |
| 7 | 0 | chapter-2-the-letter |
The link [the station](ch01.md#the-station) in chapter 2 resolves to
ch01.md (row 6 of resources), then to the anchors row with resource 6
and name the-station: byte 130 of chapter 1, where the line
## The station begins.
Written with mopenzl 0.2.5, this file is laid out as follows. The two picture payloads are stand-ins of 18,000 and 42,000 bytes.
| Resource | File offset | Record size | Decoded size |
|---|---|---|---|
| 0 format | 8 | 56 | 8 |
| 1 meta | 64 | 181 | 103 |
| 2 resources | 245 | 209 | 123 |
| 3 toc | 454 | 157 | 77 |
| 4 anchors | 611 | 146 | 72 |
5 img/cover.avif | 757 | 18,052 | 18,000 |
6 ch01.md | 18,809 | 262 | 279 |
7 ch02.md | 19,071 | 149 | 101 |
8 img/fig-1.avif | 19,220 | 42,052 | 42,000 |
Everything a library view needs is in the first 757 bytes plus the cover.
Anchors that are not headings
The anchors table names headings. A chapter can name any other line as
well, with an anchor definition in front of it: a link reference definition
that names itself. Here chapter 1 names its figure:
The train was late.
[fig-1]: #fig-1

A Markdown renderer shows nothing for the line [fig-1]: #fig-1. Chapter 2
can now link to the figure as [the figure](ch01.md#fig-1).
The packer records where the named line is, in a small table of the chapter's own: the resource just before the chapter.
| row | kind | path |
|---|---|---|
| 5 | 2 | img/cover.avif |
| 6 | 3 | |
| 7 | 1 | ch01.md |
| 8 | 1 | ch02.md |
| 9 | 2 | img/fig-1.avif |
Resource 6 is the anchor table of ch01.md:
| offset | name |
|---|---|
| 43 | fig-1 |
Chapter 2 names nothing besides its heading, so it has no such table. The
rows of toc and anchors now say 7 and 8 where they said 6 and 7.
A reader does not look for anchor definitions, and does not decode these
tables when it opens a book. It decodes one when a link leads to a name that
anchors does not have for that chapter.
Landmarks
The contents list the parts of a book by title. Landmarks answer another question: where is the place of a certain kind? A book that has them carries one more small table:
| kind | title | resource | offset |
|---|---|---|---|
start | 8 | 0 | |
glossary | Glossary of terms | 12 | 0 |
index | 13 | 420 |
A reading application can then offer "go to the beginning" or "index"
without guessing from titles, and can open a new book at start, where the
text begins, instead of at its title page. The table is a resource of its
own, right after the five fixed ones; a book without landmarks does not have
it, and nothing else in the file changes.
Diagrams and formulas
A diagram and a formula are text too, each in a notation of its own. A book
stores that text, not a picture of it: dia/route.mmd holds
flowchart LR
station[The station] --> letter[The letter]
and math/speed.tex holds v = \frac{s}{t}. A chapter shows them the way it
shows a picture:

The train kept  all the way.
- The first paragraph holds nothing else, so the diagram is a figure with a caption. The formula stands inside a line and is set as a part of it; a formula alone in a paragraph is set as a display formula.
- The resource table says what a path names:
kind5 is a diagram andkind6 a formula. They have no size in the table; a reader lays them out in the size and the tone of its text. - The words in the brackets are shown, or spoken, by a reader that cannot draw the diagram or set the formula. A reader based on an earlier draft of version 1.0 also shows the alternative text.
| row | kind | path | width | height |
|---|---|---|---|---|
| 9 | 5 | dia/route.mmd | 0 | 0 |
| 10 | 6 | math/speed.tex | 0 | 0 |
How a reader opens a book
sequenceDiagram
actor U as User
participant R as Reader
participant C as Container
participant D as AVIF decoder
R->>C: read footer and directory
R->>C: decode resources 0 to 4
R-->>U: title, authors, contents
R->>C: decode the cover named by meta
R->>D: AVIF bytes
D-->>U: cover picture
U->>R: choose a contents entry
R->>C: decode that chapter
R-->>U: text, with space reserved for pictures
R->>C: decode a picture when it scrolls into view
R->>D: AVIF bytes
D-->>U: picture
- Check the file signature at fixed offsets (Detection).
- Read the container footer and directory.
- Decode resources 0 to 4. They are a few kilobytes even for a large book.
- Show the title and authors from
meta, the cover named by thecoverkey, and the tree fromtoc. - On navigation, decode the chapter frame; decode picture frames as they scroll into view, and the frames of the diagrams and formulas the chapter shows when it is laid out.
- When a link with a fragment is followed and
anchorshas no such name for the target chapter, decode the anchor table in front of that chapter.
How a packer builds a book
flowchart TD
src["Source<br/>FB2, EPUB or a folder"] --> conv["Convert<br/>chapters to Markdown,<br/>pictures to AVIF"]
conv --> parse["Parse chapters<br/>headings, links, pictures"]
parse --> ok{"Every reference<br/>resolves?"}
ok -- no --> err["Stop and report<br/>the reference"]
ok -- yes --> tab["Build tables<br/>meta, resources,<br/>toc, anchors"]
tab --> out["Write the container"]
- Convert every picture to AVIF. This is the only lossy step and it happens before anything is written to a frame.
- Normalise chapters to the Markdown dialect below and split them at top-level headings.
- Parse each chapter once to collect headings (for
tocandanchors) and anchor definitions (for the chapter's anchor table), and to validate every link and picture reference. - Write resources 0 to 4, then the cover, the chapters, the pictures, the diagrams and the formulas. A chapter with anchor definitions is preceded by its anchor table.
Integration points
| Concern | Provided by | Used for |
|---|---|---|
| Container, directory, checksums | mopenzl framing (FramedWriter, FramedSeekReader) | Writing resources in order; reading one resource by number. |
| Typed columns | mopenzl input (Numbers, Strings) and TypedOutput | Building and reading the four tables. |
| Markdown | Any parser of the dialect that reports byte offsets | Writers: headings, anchor definitions, references, validation. Readers: rendering. |
| AVIF encoding | Any AV1 still-image encoder | Writers only. |
| AVIF decoding | The platform's decoder or a library | Readers only. |
| Mermaid diagrams | Any renderer of the notation | Readers only, and optional: without one the alternative text is shown. |
| KaTeX formulas | Any typesetter of the notation | Readers only, and optional in the same way. |
Reading the resource table with mopenzl (built with the framed feature)
takes no parsing beyond slicing the returned columns:
use mopenzl::framing::FramedDecompressor;
use std::fs::File;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut decoder = FramedDecompressor::new(Default::default())?;
let mut book = decoder.framed_seek_reader(File::open("book.mbook")?)?;
// Resource 2 is the `resources` table: kind, path, width, height.
let table = book.read_resource(2)?;
let [kind, path, width, height, ..] = &table.outputs[..] else {
return Err("the resources table has too few columns".into());
};
let mut start = 0;
for (row, len) in path.string_lens().iter().enumerate() {
let end = start + *len as usize;
let name = std::str::from_utf8(&path.content()[start..end])?;
let w = u32::from_le_bytes(width.content()[row * 4..][..4].try_into()?);
let h = u32::from_le_bytes(height.content()[row * 4..][..4].try_into()?);
println!("{row}: kind {} {name:?} {w}x{h}", kind.content()[row]);
start = end;
}
Ok(())
}
For the example book above it prints:
0: kind 0 "" 0x0
…
5: kind 2 "img/cover.avif" 1200x1800
6: kind 1 "ch01.md" 0x0
7: kind 1 "ch02.md" 0x0
8: kind 2 "img/fig-1.avif" 1600x900
Reference-level explanation
Conventions
- Resources are numbered from 0 in container order.
- All integers are unsigned and little-endian.
- An offset is a count of bytes from the start of a decoded chapter.
- Reader means software that opens mbook files; writer means software that produces them.
- A reader that rejects a file reports an error and shows no content from it.
Container
An mbook file MUST be exactly one mopenzl framed container of wire
version 1, as specified by
architecture/framing.md
in mopenzl. In short, and informatively:
8 bytes "MOZFRM", version 1, reserved 0
N records "RSRC", metadata length, frame length, decoded size,
metadata, header checksum, one OpenZL frame
directory "INDX", count, N × (offset, length, decoded size), checksum
32 bytes "MOZEND", version 1, reserved 0,
directory offset, directory length, total length
Requirements on every resource:
- Its frame MUST be a valid OpenZL frame of format version 27.
- Its frame MUST use only standard OpenZL codecs. Custom codecs and external dictionaries MUST NOT be used.
- Writers SHOULD NOT attach container metadata fields to a resource. Readers MUST ignore any that are present, except as stated for resource 0.
A file MUST contain at least five resources.
Tables
Resources 1 to 4, and every resource of kind 3 or 4, are tables. A table is
one frame with several typed inputs; each input is a column and each element
is a row.
| Column type | OpenZL input |
|---|---|
u8 | numeric, width 1 |
u32 | numeric, width 4 |
| string | string; every element MUST be valid UTF-8 |
- The columns of a table MUST appear in the order given in its definition.
- All defined columns MUST have the same number of elements. A table MAY have zero rows unless stated otherwise.
- A reader MUST reject a file in which a defined column is missing or has another type or width.
- A reader MUST ignore inputs that follow the defined columns. Later minor versions add columns only at the end.
- Writers MAY choose any graph of standard codecs for a table.
Resource 0: format header
The decoded content of resource 0 is one serial output of exactly 8 bytes:
| Bytes | Field | Value |
|---|---|---|
| 0–5 | prefix | 4D 42 4F 4F 4B 00 (MBOOK and a zero byte) |
| 6 | major | 1 |
| 7 | minor | 0 |
Writers MUST encode resource 0 as follows, so that its bytes land at fixed file offsets:
- no container metadata fields;
- the OpenZL store graph;
- OpenZL format version 27;
- content checksum and compressed checksum both enabled.
With this encoding the record of resource 0 occupies file bytes 8 to 63, and the first 53 bytes of every mbook file are identical:
0000 4d 4f 5a 46 52 4d 01 00 52 53 52 43 00 00 00 00 MOZFRM..RSRC....
0010 1c 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 ................
0020 8e 00 8c ba db a5 b1 d7 03 01 09 f8 01 01 08 4d ...............M
0030 42 4f 4f 4b 00 01 00 52 f8 76 ac 1b 24 43 5c 00 BOOK...R.v..$C\.
The listing is the complete 64-byte prefix of a version 1.0 file, produced by
mopenzl 0.2.5. major is at file offset 53 and minor at 54. Bytes 55 to 62
are frame checksums and change with the version bytes. Resource 1 always
starts at file offset 64.
Detection
A file is recognised as mbook when both hold:
- bytes 0 to 5 are
MOZFRM; - bytes 47 to 52 are
MBOOKfollowed by a zero byte.
Detection is a hint for file managers and libraries. Before showing content, a reader MUST decode resource 0 through the container and reject the file unless the result is exactly 8 bytes that begin with the prefix.
Versioning
| Change | Field | Reader behaviour |
|---|---|---|
| Incompatible | major | MUST reject a file whose major is greater than the reader supports. |
| Compatible addition | minor | MUST accept a greater minor and skip what it does not know. |
Compatible additions are limited to: new columns at the end of a table, new
meta keys, and new values of kind. Everything else requires a new major.
Kinds 5 and 6 are part of version 1.0. They were added while 1.0 was still
a draft (ADR-0011).
Resource 1: meta
| # | Column | Type |
|---|---|---|
| 0 | key | string |
| 1 | value | string |
- A key MUST match
[a-z0-9]+(-[a-z0-9]+)*. - A key MAY repeat where the table below allows it; the order of rows with the same key is significant (for example, the order of authors).
- Readers MUST ignore keys they do not know.
- Keys that begin with
x-are reserved for private use and will never be defined by this format.
| Key | Count | Value |
|---|---|---|
title | exactly 1 | Title of the book; not empty. |
lang | 1 or more | BCP 47 language tag; the first is the main language. |
id | exactly 1 | Identifier that stays the same across re-packings of the same book. A urn:uuid: URN is RECOMMENDED. |
author | 0 or more | Name of one author, as displayed. |
translator | 0 or more | Name of one translator, as displayed. |
series | 0 or 1 | Name of the series. |
series-index | 0 or 1 | Position in the series, a decimal number such as 2 or 2.5. |
publisher | 0 or 1 | Name of the publisher. |
date | 0 or 1 | Publication date: YYYY, YYYY-MM or YYYY-MM-DD. |
isbn | 0 or more | ISBN-13 or ISBN-10, digits only. |
genre | 0 or more | One free-form genre or tag. |
annotation | 0 or 1 | Plain-text description; paragraphs are separated by an empty line. |
cover | 0 or 1 | path of a picture resource. |
Resource 2: resources
| # | Column | Type |
|---|---|---|
| 0 | kind | u8 |
| 1 | path | string |
| 2 | width | u32 |
| 3 | height | u32 |
Row i describes resource i. The number of rows MUST equal the number of resources in the container directory.
kind | Meaning | Decoded content |
|---|---|---|
| 0 | Service resource | Defined by its position. |
| 1 | Text | One serial output: a chapter (Text resources). |
| 2 | Picture | One serial output: an AVIF file (Picture resources). |
| 3 | Chapter anchors | A table that names positions of the next resource (Chapter anchor tables). |
| 4 | Landmarks | A table of notable places of the book (Landmarks). |
| 5 | Diagram | One serial output: text in Mermaid notation (Diagram and formula resources). |
| 6 | Formula | One serial output: text in the notation of KaTeX (Diagram and formula resources). |
- Rows 0 to 4 MUST have
kind0. No other row may havekind0 in version 1.0. - A row of
kind3 MUST be followed by a row ofkind1. A text resource therefore has at most one anchor table, the resource before it. - At most one row may have
kind4. - A reader MUST skip a resource whose
kindit does not know: it is not decoded, and references to it are treated as unresolved. - Reading order is the order of rows with
kind1. widthandheightMUST be zero unlesskindis 2.
Rules for path:
- It MUST be empty when
kindis 0, 3 or 4 and non-empty otherwise. - Non-empty paths MUST be unique within the table, compared byte for byte.
- It is one or more segments joined by
/. A segment MUST NOT be empty,.or.., and MUST NOT contain/,\, or a character below U+0020. A path therefore never starts or ends with/. - Writers SHOULD restrict segments to
[a-z0-9._-]and SHOULD number generated names sequentially (img/0001.avif), which compresses best.
Writers SHOULD place the landmarks, when the book has any, at position 5,
then the resource named by cover, then all text resources, each directly
after its anchor table when it has one, then the remaining pictures, then
the diagrams, then the formulas. Apart from an anchor table and its chapter,
readers MUST NOT depend on this order.
Resource 3: toc
| # | Column | Type |
|---|---|---|
| 0 | level | u8 |
| 1 | title | string |
| 2 | resource | u32 |
| 3 | offset | u32 |
Rows form a tree listed in pre-order.
levelMUST be at least 1. The first row MUST have level 1, and a row's level MUST NOT exceed the previous row's level by more than 1.titleMUST NOT be empty. It is plain text, not Markdown.resourceMUST be the number of a resource withkind1.offsetMUST be a valid position in that chapter.- A row whose
offsetis not 0 MUST have the sameresourceandoffsetas a row ofanchors. The target of a contents entry can therefore always be written as a link destination: a path and an optional fragment. A row of a chapter anchor table does not satisfy this rule: it is not read when a file is opened. - Rows MUST be in reading order: by position of
resourcein the reading order, then byoffset.
The table MAY be empty. It need not list every heading.
Resource 4: anchors
| # | Column | Type |
|---|---|---|
| 0 | resource | u32 |
| 1 | offset | u32 |
| 2 | name | string |
One row gives a name to a position inside a chapter. This table holds the names of headings; names of other positions are in chapter anchor tables. Link fragments are resolved through these tables only; readers do not derive anchor names from heading text.
resourceMUST be the number of a resource withkind1.offsetMUST be a valid position in that chapter.nameMUST NOT be empty and MUST be unique among rows with the sameresource.- Rows MUST be sorted by
resource, then byoffset.
Writers SHOULD emit one row for every heading of every chapter, with the
name GitHub would generate for that heading: the heading's text in lower case,
with punctuation removed, spaces replaced by -, and -1, -2, … appended to
repeated names within a chapter. For example, Chapter 3. The Seventh Proof
becomes chapter-3-the-seventh-proof. A heading whose name would be empty,
such as one made of punctuation only, gets no row.
Writers SHOULD NOT put a row into this table for a position that is not the start of a heading: the table is decoded whenever a file is opened.
Chapter anchor tables
A resource of kind 3 gives names to positions of the text resource that
follows it. It lets a link lead to a line that is not a heading: a paragraph,
a figure, a row of a table.
| # | Column | Type |
|---|---|---|
| 0 | offset | u32 |
| 1 | name | string |
offsetMUST be a valid position in the chapter that follows the table.nameMUST NOT be empty, MUST be unique within the table, and MUST NOT equal thenameof a row ofanchorsfor the same chapter. A fragment therefore names one position, whichever table holds it.- Rows MUST be sorted by
offset. Two rows MAY have the sameoffset. - The table MAY be empty. Writers SHOULD NOT write a table without rows: a chapter that needs no such name has no anchor table.
Writers SHOULD emit one row for every anchor definition of the chapter. A row MAY name a position that has no anchor definition.
Readers SHOULD NOT decode a chapter anchor table before it is needed to resolve a fragment.
Landmarks
A resource of kind 4 lists notable places of the book. A file has at most
one.
| # | Column | Type |
|---|---|---|
| 0 | kind | string |
| 1 | title | string |
| 2 | resource | u32 |
| 3 | offset | u32 |
kindMUST match[a-z0-9]+(-[a-z0-9]+)*. Kinds that begin withx-are reserved for private use and will never be defined by this format.titleis plain text and MAY be empty.resourceMUST be the number of a resource withkind1.offsetMUST be a valid position in that chapter. Anoffsetthat is not 0 MUST equal theoffsetof a row ofanchorsfor that chapter, or of a row of the chapter's anchor table: the target of a landmark can then be written as a link destination, a path and an optional fragment.- A kind MAY repeat, except
start. The order of rows is the order in which an application lists them. - The table MAY be empty. Writers SHOULD NOT write a table without rows.
| Kind | The place where |
|---|---|
start | the text of the book begins |
title-page | the title page is |
dedication | the dedication is |
epigraph | the epigraph of the book is |
foreword | a foreword begins |
preface | a preface begins |
introduction | an introduction begins |
prologue | the prologue begins |
epilogue | the epilogue begins |
conclusion | a conclusion begins |
afterword | an afterword begins |
acknowledgements | the acknowledgements are |
appendix | an appendix begins |
notes | the notes of the book are collected |
glossary | the glossary begins |
bibliography | the bibliography begins |
index | the index begins |
list-of-figures | the list of figures is |
list-of-tables | the list of tables is |
about-the-author | the author is introduced |
copyright | the copyright page is |
colophon | the colophon is |
There is no kind for a table of contents that is set in the text: the toc
table is the contents of a book.
- A reader shows a landmark by its
title, or, when the title is empty, by its own name for the kind. A reader MUST skip a row whose kind it does not know and whose title is empty. - A reader that opens a book for the first time SHOULD show the place of
startwhen the book has one. - A reader MAY decode the table when it opens a file or when the landmarks are first wanted.
Positions
A position is a pair of a text resource number and an offset. An offset is
valid when it is 0, or when it is less than the chapter's decoded length and
the byte before it is a line feed (U+000A). toc and anchors offsets
SHOULD point at the first byte of a heading line.
Because positions are byte offsets into decoded text, a book with a given id
whose chapters change is a different edition: positions saved by a reader are
not guaranteed to survive it.
Text resources
A text resource decodes to one serial output, the chapter.
Encoding
- UTF-8 without a byte order mark.
- Lines end with a single line feed (U+000A).
- No character below U+0020 other than line feed and tab.
- Writers SHOULD normalise text to Unicode NFC and SHOULD keep a chapter under 256 KiB by splitting at top-level headings.
- Typographic punctuation (quotes, dashes, ellipses) is stored as the final characters. Readers MUST NOT rewrite punctuation.
Dialect
A chapter is parsed as CommonMark 0.31.2 with these extensions, as defined by the GitHub Flavored Markdown Spec 0.29-gfm:
| Extension | Notes |
|---|---|
| Tables | |
| Task list items | Rendered as read-only checkboxes. |
| Strikethrough | One or two tildes, as in the GFM spec. Writers escape a literal tilde as \~. |
| Autolinks (extended) | Bare www. and http(s):// text becomes a link. |
| Footnotes | [^label] and [^label]: text, as GitHub renders them. |
The following MUST NOT appear in a chapter, and writers MUST reject or convert input that contains them:
- HTML blocks and raw inline HTML;
- picture destinations with a URI scheme (pictures fetched from a network);
- link destinations with a scheme other than
http,httpsormailto.
Not part of the dialect, and therefore shown as literal text: math ($…$),
alert blocks (> [!NOTE]), heading attributes ({#id}), superscript and
subscript markers, wiki links, emoji shortcodes and metadata blocks. A code
block whose language is mermaid is a code block. A formula and a diagram
are resources of their own, shown with the syntax of a picture
(Diagram and formula resources).
A footnote definition MUST be in the same chapter as the references to it.
Anchor definitions
A chapter names a line that is not a heading with an anchor definition: a
link reference definition, as CommonMark defines it, whose destination is #
followed by its own label.
[fig-1]: #fig-1

- The name is the destination without its
#, percent-decoded. A link reference definition is an anchor definition when its name equals its label as written, byte for byte. It MAY have a title, which is ignored. - It names the first byte of the line on which it starts. A reader that moves to that position shows what follows the definition, because the definition itself is not rendered.
- A definition whose name is that of an
anchorsrow of the chapter, or of an earlier anchor definition of the chapter, names nothing. It stays an ordinary link reference definition. - Writers SHOULD record every anchor definition in the anchor table of its chapter.
- Readers MUST NOT resolve a fragment by looking for an anchor definition; they resolve it through the tables. A reader needs no code for anchor definitions: a CommonMark renderer produces no output for a link reference definition.
An anchor definition is also what it looks like. A reference link in the
same chapter, [the figure][fig-1], is a link with the destination #fig-1
and resolves to the named line.
Two rules of CommonMark matter to a writer. A link reference definition cannot interrupt a paragraph, so it follows an empty line or starts a block. And a line after it that holds only a quoted or parenthesised string is read as its title, so such a line needs an empty line in front of it.
Resolving destinations
flowchart TD
dest["Destination"] --> scheme{"Starts with<br/>a URI scheme?"}
scheme -- yes --> allowed{"A link with http,<br/>https or mailto?"}
allowed -- yes --> ext["External link"]
allowed -- no --> bad["Unresolved"]
scheme -- no --> split["Split at the first #<br/>and percent-decode"]
split --> empty{"Path part<br/>empty?"}
empty -- yes --> frag
empty -- no --> rel["Resolve against the<br/>chapter's folder"]
rel --> found{"Equals a path<br/>in resources?"}
found -- no --> bad
found -- yes --> frag{"Has a<br/>fragment?"}
frag -- no --> whole["The picture, or<br/>offset 0 of the chapter"]
frag -- yes --> named{"Name is in anchors<br/>for that chapter?"}
named -- yes --> pos["Resource and offset"]
named -- no --> table{"Name is in the chapter's<br/>own anchor table?"}
table -- yes --> pos
table -- no --> bad
For every link and picture, a reader takes the destination after CommonMark has processed escapes and entities, then:
- If it starts with a URI scheme (
[A-Za-z][A-Za-z0-9+.-]*:), it is external. - Otherwise it is internal. Split it at the first
#into a path part and an optional fragment, and percent-decode both. An internal destination MUST NOT contain?or start with/, and MUST decode to valid UTF-8. - If the path part is empty, the target is the current chapter.
- Otherwise resolve the path part against the current chapter's
pathwith its last segment removed, applying.and..segments. A..that would leave the root is an error. The result MUST equal thepathof a row inresources.
| Reference | Target | Fragment |
|---|---|---|
Picture  | kind 2, 5 or 6: a picture, a diagram or a formula | not allowed |
Link [text](dest) | kind 1 | optional; MUST equal, byte for byte, the name of an anchors row of the target chapter or of a row of that chapter's anchor table |
A link without a fragment leads to offset 0 of the target chapter.
Writers MUST NOT produce a file with a reference that fails these rules. A reader that meets one anyway SHOULD show the link text or the picture's alternative text and continue.
Rendering
- Each text resource starts a new chapter; readers SHOULD start it on a new page or screen.
- A paragraph whose only content is one picture is a figure: it is shown as a block, and the picture's title, when present, is its caption. Any other picture is inline.
- The same holds for a diagram and for a formula, which the syntax of a picture shows as well. A formula that is a figure is set as a display formula; any other formula is set in the style of running text, on the baseline of its line.
- A reader that cannot show a picture, a diagram or a formula SHOULD show its alternative text in its place.
- Readers SHOULD reserve space for a picture from
widthandheightbefore decoding it. - Readers MUST NOT fetch any network resource while rendering, and MUST NOT open an external link without an action by the user.
- Fonts, sizes, margins and alignment are chosen by the reader. The format carries no style information.
Picture resources
A picture resource decodes to one serial output: a complete AVIF file.
- The file MUST contain a primary image item. A reader MAY play an image sequence and MUST otherwise show the primary item.
widthandheightinresourcesMUST be non-zero and equal to the size in pixels of the primary item as displayed, after its crop, rotation and mirror properties are applied.- Writers SHOULD use the OpenZL store graph: AVIF payloads are already entropy-coded and do not shrink.
Diagram and formula resources
A diagram resource (kind 5) and a formula resource (kind 6) each decode
to one serial output: text.
- The text has the encoding of a chapter: UTF-8 without a byte order mark, lines that end with a line feed, and no character below U+0020 other than line feed and tab.
- The text MUST contain a character that is not white space.
- A diagram is described in the notation of Mermaid. Mermaid 11 is the reference for authors. The source is the text inside a Mermaid code fence.
- A formula is written in the notation of KaTeX. KaTeX
0.16 is the reference for authors. The source is LaTeX in math mode,
without the
$or\[that surround a formula in running text. Whether it is set as a display formula is decided by where the chapter shows it (Rendering), not by the resource. widthandheightinresourcesare zero. A reader lays a diagram and a formula out itself, in the size and the tone of its text.- Writers SHOULD end the
pathof a diagram with.mmdand that of a formula with.tex, and SHOULD store a formula that a book shows more than once as one resource. - Writers SHOULD give every reference to a diagram or to a formula an alternative text that says in words what it shows: it is all that a reader without a renderer has.
Neither notation has a specification; each is defined by its implementation. A writer is therefore not required to check the text against the notation, and a reader is not required to render it:
- A reader MAY render no diagrams, no formulas, or only a part of either notation. For what it does not render it shows the alternative text of the reference.
- A reader MUST NOT run a script, follow a link or fetch anything on
behalf of a diagram or a formula: a
clickof Mermaid and\href,\urland\includegraphicsof KaTeX do nothing. - A reader MAY refuse a diagram or a formula that would take more time or memory than it allows, and then shows the alternative text.
Conformance
A reader MUST reject a file when:
- the container fails its own validation;
- resource 0 is not a valid format header, or
majoris not supported; - any of resources 1 to 4 is not a table of the defined shape, or breaks a MUST rule of its section.
A reader MUST NOT reject a file because of unknown meta keys, unknown
kind values, extra table columns, or errors confined to one text, picture,
diagram or formula resource, to one chapter anchor table or to the landmarks;
it reports those where they are met. A chapter anchor table that is not a table of the defined shape, or
that breaks a MUST rule of its section, is such an error: the chapter it
belongs to can still be shown, and a link that needs the table is unresolved.
A landmarks table of another shape, or one that breaks a MUST rule of
its section, is such an error too: the book is read as one without
landmarks.
One rule of the tables cannot be checked from the tables: whether a position is preceded by a line feed needs the text of its chapter. A reader checks the rest of a valid position when it opens a file, and this part when it decodes the chapter; a failure there is an error confined to that chapter. For a row of a chapter anchor table, a reader checks the rest when it decodes the table, and this part when it has decoded both the table and the chapter; a failure there is an error confined to that table.
A writer MUST produce files that satisfy every MUST in this document.
Security considerations
- Untrusted input. Every length and count comes from the file. Readers MUST bound allocations before decoding and MAY reject files that exceed limits they document. The mopenzl defaults (10,000 resources, 256 MiB of decoded content, 1 GiB container) are too small for some picture-heavy books; implementations are expected to choose their own.
- No active content. Raw HTML is excluded, so a chapter cannot carry scripts, styles or embedded frames.
- No tracking. Pictures cannot name network locations, and readers do not fetch anything while rendering.
- Path traversal.
pathcannot contain.., a leading/or a backslash, so unpacking into a folder cannot write outside it. Tools MUST still validate paths before creating files. - Picture decoders. AVIF decoding is the largest attack surface a reader inherits; pictures are untrusted input to that decoder.
- Diagram and formula renderers. Their source is untrusted input as well. Both notations can name links and, in their original implementations, scripts and remote pictures; a reader acts on none of them. A short source can ask for an unbounded layout (a macro that expands without end, a graph of thousands of nodes), so a reader bounds the work it does for one.
- Integrity, not authenticity. Checksums detect damage. Nothing in the format authenticates a file or its origin.
Drawbacks
- Independent frames compress text worse than one solid archive: each chapter starts with an empty window. The loss is estimated at 15–20% of the text, which is usually small next to the pictures. See Future possibilities.
- The container is specific to mopenzl. Individual frames are standard
OpenZL, but the outer
MOZFRMlayout has one implementation today. - Per-resource overhead is 74 to 76 bytes (a 24-byte directory entry and 50 to 52 bytes of record and frame headers for a stored frame). It is negligible for pages and photographs and noticeable for thousands of pictures of a few hundred bytes each.
- No HTML means no escape hatch. Layout that Markdown cannot express (centred text, columns, drop capitals) cannot be stored at all.
- Positions are byte offsets, so editing a chapter invalidates bookmarks
and requires rebuilding
toc,anchorsand the chapter's anchor table. - A fragment is looked up in two places. A name that is not a heading's costs one more frame to decode when its link is followed, and a reader that opens a file lazily cannot tell such a link from a broken one before that.
- Two more renderers, defined by their implementations. A reader that shows diagrams and formulas needs a Mermaid renderer and a formula typesetter, and neither notation has a specification. Two readers may draw the same diagram differently, and a reader without them shows only the alternative text. See ADR-0011.
- No size for a diagram or a formula. A reader cannot reserve its space before it has laid it out.
- Uneven parser support for one extension. Not every CommonMark library implements extended autolinks; see ADR-0006.
Rationale and alternatives
Each choice below has its own decision record with the options compared, the trade-off and the consequences.
| Decision | Main alternative rejected | Record |
|---|---|---|
| One framed container, one OpenZL frame per resource | A single solid frame; a ZIP archive | ADR-0001 |
| Pictures are stored AVIF files | AVIF as a custom OpenZL codec | ADR-0002 |
| An 8-byte format header as resource 0 | A container metadata field | ADR-0003 |
| Tables are typed columns, one per frame | JSON or TOML documents | ADR-0004 |
| References by path through a resource table | Frame numbers in Markdown | ADR-0005 |
| GitHub Flavored Markdown without raw HTML | CommonMark with heading attributes | ADR-0006 |
| Byte offsets and a stored anchor table | Readers computing GitHub anchors | ADR-0007 |
| Names of lines that are not headings in a table before their chapter | All names in resource 4; links only to headings | ADR-0008 |
| A line is named by a link reference definition in its chapter | {#id} attributes; names given to the writer apart from the text | ADR-0009 |
| Landmarks in an optional table of their own | A sixth fixed resource; keys of meta | ADR-0010 |
| Diagrams and formulas as resources of their own kinds, shown like pictures | ```mermaid fences and $…$ in the dialect; pictures only | ADR-0011 |
Prior art
| Format | Taken from it | Left behind |
|---|---|---|
| EPUB | Manifest of resources, reading order, separate navigation document, landmarks, identification by a fixed first entry | XHTML and CSS, several XML metadata files |
| FB2 | Metadata vocabulary (authors, translators, series, annotation, genres), one file per book | A single XML document, Base64 pictures |
| mdBook | Chapters as Markdown files with relative links | A build step that produces HTML |
| CBZ | Pictures as independent, directly addressable entries | No metadata or text |
Unresolved questions
- CommonMark version. GFM 0.29-gfm is based on CommonMark 0.29, while current parsers follow 0.31.2. This draft names 0.31.2 as the base; the edge cases that differ should be listed or declared irrelevant.
- Footnotes have no formal specification. The draft points at GitHub's behaviour; a precise definition or a reference implementation is needed.
- Anchor names. The GitHub algorithm is described informally and only recommended. Decide whether to specify it exactly for writers.
- Resource limits. Should the format state minimum limits every reader supports (resources, chapter size, picture size)?
metavocabulary. The key list, the requiredid, and plain-textannotationare a first proposal.- Media type.
.mbookis used as the extension; no media type is registered. - Links to pictures. Links currently target chapters only. A link to a picture ("open full size") may be worth allowing.
- Chapter anchor tables. Their
kindcode, the tie to a chapter by position, and the rule that a contents row needs ananchorsrow are proposals of ADR-0008. - Landmarks. The limit of one
start, and what a reader does with a kind it does not know, are proposals of ADR-0010. - Anchor definitions. The rule that tells an anchor definition from any other link reference definition, and what happens to a repeated name, are proposals of ADR-0009.
Future possibilities
- A shared dictionary for text. A Zstandard dictionary stored as its own
resource would recover most of the compression lost to independent chapters.
It needs a new
kindand a rule for loading it before text frames. - Compact AVIF storage for books with thousands of tiny pictures, as described in ADR-0002, if measurements justify a custom codec.
- Video and long animations. A resource is decoded whole, so video needs a logical resource made of several frames (segments) and a table that lists them.
- Full-text search index as a service table of typed columns.
- Alert blocks as a dialect addition in a later minor version; until then they degrade to literal text. Formulas were once expected here too and became resources instead (ADR-0011).
- Other notations, such as a table of data drawn as a chart, as further kinds shown with the syntax of a picture.
- Embedded fonts and layout hints, if a use case appears that reader settings cannot cover.
Appendix: measurements
Informative. Synthetic books, encoded with mopenzl 0.2.5 at its default level and graph on one machine; decoding time is the mean of 20 runs.
| Book | Resources | resources table | Per resource | Decoding |
|---|---|---|---|---|
| Novel, 40 chapters and 30 pictures | 75 | 475 B | 6.3 B | 24 µs |
| Textbook, 3,000 formula pictures | 3,065 | 11 KB | 3.7 B | 0.14 ms |
| Comic, 5,000 pages of one size | 5,005 | 4.7 KB | 0.9 B | 0.15 ms |
| 10,000 pictures with hash-like names | 10,105 | 118 KB | 11.7 B | 0.5 ms |
| 100,000 pictures | 101,005 | 362 KB | 3.6 B | 2.7 ms |
For a sample book with 8 meta rows and 120 toc rows, the meta record was
398 bytes and the toc record 849 bytes. An empty four-column table is 77
bytes.
A converted book
Informative. A technical book of 11 chapters, 167 contents entries and 45
pictures, published as an EPUB, was converted with mbook-converter 0.3.0 at
its defaults: AVIF quality 80 and speed 6, and mopenzl 0.2.6 at its default
level. AVIF at this quality is lossy; the text is unchanged by compression.
| Part | EPUB | mbook |
|---|---|---|
| Whole file | 7,001,213 B | 1,608,479 B |
| Pictures | 6,705,021 B, 45 PNG and JPEG files | 1,382,138 B, 43 AVIF files |
| Text, metadata, navigation and index | 247,429 B of deflated XHTML, CSS and XML | 226,341 B |
| Embedded font | 40,495 B | none: fonts belong to the reader |
The chapters are 858,730 bytes of XHTML in the EPUB and 621,498 bytes of Markdown in the mbook file. The converter kept 43 of the 45 picture files. The conversion took 3.1 s on the machine named below.
Times are the best of repeated runs on one machine (an Apple M5 Pro), with the file in the page cache.
| Step | Time |
|---|---|
| Open the mbook file; title, contents and the list of every resource are ready | 80 µs |
The same title and contents from the EPUB, with rbook 0.7 | 164 µs |
| Read the bytes of the cover | 4 µs |
| Decode the largest chapter, 174,933 B | 108 µs |
Decode it and parse it into a tree with markdown 1.0 | 6.2 ms |
All chapters together decode at 1,370 MB/s. The Russian translation of the same book, with the same pictures, went from 7,104,418 to 1,715,352 bytes; it opens in 117 µs, against 199 µs for its EPUB, and its text decodes at 1,760 MB/s.
This is one book. The size of a converted book follows its pictures: a novel without any shrinks far less than an illustrated manual.
Decision records
Each record explains one choice made by RFC 0001: the situation, the options compared, the trade-off, and the consequences.
The records are about the format only. A choice made by one of the crates is in the "Rationale and alternatives" table of its Design page: mbook, mbook-converter, mbook-ui.
| ADR | Decision | Status |
|---|---|---|
| 0001 | One mopenzl framed container; one OpenZL frame per resource | Accepted |
| 0002 | Pictures are AVIF files stored without a custom codec | Accepted |
| 0003 | Resource 0 is an 8-byte format header | Accepted |
| 0004 | Tables are typed OpenZL columns, one table per frame | Accepted |
| 0005 | Markdown refers to resources by path; a table maps paths to frames | Proposed |
| 0006 | Chapters are GitHub Flavored Markdown without raw HTML | Accepted |
| 0007 | Positions are byte offsets; heading anchors are stored in a table | Accepted |
| 0008 | Names of lines that are not headings are stored in a table before their chapter | Accepted |
| 0009 | A chapter names a line with a link reference definition that names itself | Accepted |
| 0010 | Landmarks are an optional table in a resource of its own | Accepted |
| 0011 | Diagrams and formulas are resources of their own kinds, shown the way a picture is | Accepted |
Status values
| Status | Meaning |
|---|---|
| Proposed | Written into the RFC draft, not yet confirmed by the format author. |
| Accepted | Confirmed by the format author. Details marked proposed inside a record are still open. |
| Superseded | Replaced by a later record, which is linked from the old one. |
How the options are compared
A file format has no servers or request rates, so the records replace the usual service dimensions with the ones that matter here:
| Dimension | Question |
|---|---|
| Reader complexity | How much code does a reader need, and which libraries? |
| File size | What does the choice cost in bytes? |
| Compatibility | Do existing tools and decoders keep working? |
| Evolution | How does the choice age when the format grows? |
Sizes and timings quoted in the records were measured on synthetic books with mopenzl 0.2.5; they show orders of magnitude, not guarantees.
ADR-0001: Independent frames in an indexed container
Status: Accepted
Date: 2026-11-21
Deciders: Format author
Context
A book is read in pieces: the title and cover in a library view, one chapter at a time while reading, pictures as they scroll into view. The file must give each piece without decoding the others, over a local disk or over HTTP range requests. The descriptive data (metadata, contents) is tabular.
Decision
An mbook file is one mopenzl framed container. Every part of the book (header, each table, each chapter, each picture) is its own resource, and every resource is exactly one ordinary OpenZL frame.
Options considered
| Dimension | A: framed container, one frame per resource | B: one solid frame | C: ZIP archive |
|---|---|---|---|
| Reader complexity | One library: container and codecs together | Lowest | ZIP reader plus a codec |
| Random access | Whole resource, through a checked directory | None: everything before the target is decoded | Whole entry, through the central directory |
| File size | Text compresses per chapter; 74–76 B per stored resource | Best text compression | Text compresses per entry; about 76 B plus the name twice per entry |
| Typed data | Native typed inputs per frame | Native, but all in one frame | None; entries are bytes |
| Compatibility | Frames are standard OpenZL; the outer layout has one implementation | Any OpenZL decoder | Any ZIP tool |
| Evolution | New resource kinds are new rows | Layout changes break the whole stream | New entries are ignored by old readers |
Chosen: A.
Trade-off analysis
- B gives the smallest text but cannot open a chapter or a picture without decoding what precedes it, which rules out lazy loading.
- C matches A on random access and is readable by every tool, but its entries are opaque bytes: tables would need a text format and a parser (ADR-0004).
- A costs text compression (each chapter starts with an empty window; the loss is estimated at 15–20% of the text) and depends on a container with a single implementation. In return it has typed frames, per-resource graphs and checksums, and a seek index, with no extra library.
Consequences
- Easier: lazy loading, HTTP range reads, per-resource integrity checks, storing pictures uncompressed next to compressed text.
- Harder: matching the text compression of a solid archive.
- Harder: third-party implementations must implement the
MOZFRMlayout. - To revisit: a shared text dictionary (Future possibilities), and the container's default limits, which are too small for picture-heavy books.
Action items
- Wrap
FramedSeekReaderandFramedWriterinmbook. - Choose and document mbook's own
FramingConfiglimits. - Measure text compression per chapter against a solid frame on real books.
ADR-0002: Pictures are stored AVIF files
Status: Accepted
Date: 2026-11-21
Deciders: Format author
Context
Pictures are AVIF. OpenZL allows custom codecs, so AVIF could be a codec inside the frame's graph instead of opaque bytes. Two things constrain the choice:
- An OpenZL codec must regenerate its input exactly; the frame's content checksum (on by default) verifies it.
- A frame that uses a custom codec can only be decoded by an application that registers the same codec.
Decision
A picture resource holds a complete AVIF file, written with the OpenZL store graph. Version 1 defines no custom codec. Converting a source picture to AVIF is a step of the packer, done before the frame is written.
Options considered
| Dimension | A: stored AVIF file | B: lossy pixel codec in the graph | C: lossless AVIF repacking codec |
|---|---|---|---|
| Reader complexity | Hand the bytes to any AVIF decoder | Must bundle an AV1 decoder inside the OpenZL codec; output is raw pixels | Must register the codec; output is an AVIF file |
| File size | AVIF size plus 50–52 B of headers | Same payload | Saves an estimated few hundred bytes per picture |
| Compatibility | Any OpenZL decoder extracts the file | Breaks the lossless contract; rejected by the content checksum | Frames unreadable without the codec |
| Evolution | Nothing to version | Codec becomes part of the format | Codec identifier becomes part of the format |
Chosen: A.
Trade-off analysis
- B is not viable. Pixels in, AV1 out, different pixels back is not a reversible transform. It would only work with content checksums disabled, and decoding would yield tens of megabytes of raw pixels per page instead of a file the platform can decode, tile and colour-manage itself.
- C is viable but pays little. It removes the ISOBMFF boxes and rebuilds them on decoding. That matters only for books with thousands of pictures of a few hundred bytes each, and it costs the property that every frame is standard OpenZL.
- A keeps the format free of custom codecs. Because a frame always decodes to "an AVIF file", C can be added later without changing what readers receive.
Consequences
- Easier: readers use the platform's AVIF decoder; frames stay decodable by a stock OpenZL decoder.
- Harder: nothing is saved on AVIF container overhead for tiny pictures.
- To revisit: option C, if measurements on books with many tiny pictures justify it. Formulas are no longer such pictures: they are stored as their source (ADR-0011).
Action items
- Packer: convert source pictures to AVIF before writing frames.
- Packer: record displayed
widthandheightin the resource table. - Measure AVIF container overhead on a book with many small pictures.
ADR-0003: A format header as the first frame
Status: Accepted (the 8-byte layout and the pinned encoding are proposed)
Date: 2026-11-21
Deciders: Format author
Context
The container's own signature, MOZFRM, says "mopenzl framed container", not
"book". A file manager, a library scanner or file(1) needs to recognise an
mbook file, and a reader needs the format version before it interprets
anything else.
Decision
Resource 0 is a format header: the prefix MBOOK and a zero byte, then
major and minor, 8 bytes in total. It is written with the store graph
and a pinned encoding, so its bytes appear unchanged at file offset 47.
Options considered
| Dimension | A: stored 8-byte frame | B: metadata field on resource 0 | C: version key in the meta table |
|---|---|---|---|
| Reader complexity | Decode one tiny frame | Read a record header | Decode and search a table |
| Detection without OpenZL | Yes, fixed offset 47 | Yes, fixed offset 32 | No |
| Integrity | Frame checksums cover the version | Header checksum covers the field | Frame checksums cover the table |
| Compatibility | Ordinary frame | Uses the container's metadata for format semantics | Ordinary frame |
| Evolution | Fixed size; growth needs a new major | Free-form value | Free-form value |
Chosen: A.
Trade-off analysis
- C hides the version inside compressed data whose shape depends on the version being read.
- B is the smallest change, but it puts format semantics into the container's metadata layer, and the header cannot be handled like every other resource.
- A costs 56 bytes and one constraint on writers: store graph, OpenZL format version 27, both checksums on, no metadata. Without the pinned encoding a different frame header could move the prefix. In return the first 53 bytes of every file are constant.
Consequences
- Easier: one-line detection rules; a version that is decoded and checksummed like everything else.
- Harder: writers must reproduce the pinned encoding exactly.
- To revisit: the pinned OpenZL format version, when OpenZL defines a newer one.
Action items
- Add the 64-byte prefix of a 1.0 file as a test vector in
mbook. - Implement detection by fixed offsets and full validation by decoding.
- Test that a file with a greater
majoris rejected and a greaterminoris accepted.
ADR-0004: Tables are typed columns
Status: Accepted (one table per frame is proposed)
Date: 2026-11-21
Deciders: Format author
Context
Four parts of a book are tables: metadata (key, value), the resource list, the table of contents and the heading anchors. They are read at every open and can have thousands of rows. An OpenZL frame can carry several typed inputs (integers of a fixed width, strings with lengths) and returns them with their types.
Decision
Each table is one frame. Each column is one typed input, in a fixed order. Later minor versions add columns only at the end, and readers ignore columns they do not know.
Options considered
| Dimension | A: typed columns, one table per frame | B: JSON or TOML in a serial frame | C: typed columns, all tables in one frame |
|---|---|---|---|
| Reader complexity | No parser; slices of integers and strings | Needs a text parser and a schema layer | Same as A |
| File size | 849 B for a 120-row contents table | 957 B for the same table | Saves about 76 B per merged table |
| Compatibility | Any OpenZL decoder returns the columns | Any tool reads the text | Same as A |
| Evolution | Append columns per table | Add keys freely | Appending to one table renumbers the others |
| Inspectability | Needs a dump tool | Human-readable after decoding | Needs a dump tool |
Chosen: A.
Trade-off analysis
- The size difference between A and B is small. The deciding factor is the parser: columns need none, which keeps the container layer small and usable without the standard library.
- B is easier to inspect and to extend with nested values. Flat key/value rows cover the metadata needed so far.
- C saves a few hundred bytes per book and makes column positions global: no table could grow without shifting another. One frame per table keeps each table's positions private.
Consequences
- Easier: zero-dependency readers; large tables stay compact (a 100,000-row resource table measured 362 KB and decoded in under 3 ms).
- Harder: no nested values; a debugging tool is needed to look inside.
- Harder: column order is fixed forever within a major version.
- To revisit: nested metadata, if a use case needs more than key/value rows.
Action items
- Define table readers and builders in
mbook. - Reject a table whose columns differ in row count, type or width.
- Add a
dumpcommand that prints tables as text.
ADR-0005: References by path through a resource table
Status: Proposed
Date: 2026-11-21
Deciders: Format author
Context
Markdown must point at pictures and at other chapters, and each of those is a frame in the container. The container's directory lists only offsets and sizes; a resource's name, if any, is in its own record header.
Decision
Markdown uses ordinary relative paths (img/fig-3.avif, ch01.md). Resource
2 is a table with one row per resource: kind, path, and the pixel size of
pictures. A reader resolves a path to a row, and the row number is the
resource number.
Options considered
| Dimension | A: paths and a resource table | B: frame numbers in Markdown | C: paths matched against record headers |
|---|---|---|---|
| Reader complexity | One table lookup | None | One header read per resource to build the map |
| File size | 1–12 B per resource | 0 | A name per record header, uncompressed |
| Compatibility | Unpacked chapters are valid Markdown with working links | Links mean nothing outside the container | Same as A |
| Evolution | Repacking and reordering keep links valid | Any reordering rewrites chapter text | Same as A |
| Layout before decoding | Picture sizes are in the table | Not available | Not available |
Chosen: A.
Trade-off analysis
- B is the smallest, but it ties chapter text to the physical layout and gives up the property that a book unpacks into a folder a Markdown viewer can show.
- C avoids a table but needs a read per resource before the first link can be resolved, which is slow over a network, and has no place for picture sizes.
- A adds a table that is small in every measured case and is read once at open. It also lists kinds, so readers know the reading order and can reserve space for pictures before decoding them.
Consequences
- Easier: pack from and unpack to a plain folder; reorder resources freely.
- Easier: readers lay out text before pictures are decoded.
- Harder: writers must keep the table and the container directory in step.
- To revisit: hash-like names compress poorly (11.7 B per row against 3.6 B for sequential names); writers should generate sequential names.
Action items
- Implement destination resolution exactly as the RFC specifies.
- Validate paths (no
.., no leading/, unique) in the packer. - Implement unpack-to-folder and pack-from-folder as a round trip test.
ADR-0006: GitHub Flavored Markdown without raw HTML
Status: Accepted (GFM); the exclusion of raw HTML is proposed
Date: 2026-11-21
Deciders: Format author
Context
"Markdown" is a family of dialects. Two readers must render the same chapter the same way, so the format has to name one dialect. The dialect also decides what a reader must contain: Markdown that permits HTML needs an HTML engine.
Decision
Chapters are CommonMark with the GitHub Flavored Markdown extensions (tables,
task list items, strikethrough, extended autolinks) and GitHub-style
footnotes. Raw HTML, network pictures and link schemes other than http,
https and mailto are not allowed.
Options considered
| Dimension | A: GFM without raw HTML | B: CommonMark with heading attributes | C: full GFM including HTML |
|---|---|---|---|
| Reader complexity | Markdown parser only | Markdown parser only | Markdown parser and an HTML engine |
| File size | Same | Same | Same |
| Compatibility | Renders the same on GitHub and in GFM viewers | {#id} shows as literal text on GitHub | Accepts any GitHub document |
| Evolution | Additions (math, alerts) degrade to text | Same | Anything can be smuggled in as HTML |
| Safety | No active content | No active content | Scripts, styles and remote content must be filtered |
Chosen: A.
Trade-off analysis
- B was the first draft. It gives authors explicit anchor names, but in a syntax GitHub does not have, and it is a dialect nobody writes by default.
- C accepts every existing document and brings the web engine that the format exists to avoid. It also reopens tracking and script injection.
- A is a strict subset of what GitHub renders: every chapter is valid GFM,
but not every GFM document is a valid chapter. Documents that use
<br>,<sub>or<img width>must be converted when packed.
Two details follow from choosing GFM:
- A single tilde now marks strikethrough, so packers escape literal tildes.
- Extended autolinks have uneven library support. Of the two Rust parsers
tried,
markdown1.0.0 implements the whole dialect and reports byte offsets;pulldown-cmark0.13.5 does not turn bare URLs into links.
Consequences
- Easier: authors use a dialect they know; books can be previewed on GitHub.
- Easier: readers need no HTML, CSS or script handling.
- Harder: layout that Markdown cannot express cannot be stored.
- Harder: anchors are no longer chosen by the author (ADR-0007). Later, a name for a line that is not a heading was given back in plain GFM, as a link reference definition (ADR-0009).
- To revisit: alert blocks; the exact CommonMark version; a formal definition of footnotes. Math did not become a part of the dialect: formulas are resources (ADR-0011).
Action items
- Packer: reject or convert raw HTML and disallowed schemes.
- Packer: escape literal tildes when importing prose.
- Build a conformance set of chapters and expected parse results.
ADR-0007: Byte offsets and a stored anchor table
Status: Accepted (the anchor table); byte offsets in toc are proposed.
Extended by ADR-0008, which adds names for
positions that are not headings
Date: 2026-11-21
Deciders: Format author
Context
Three things point into the middle of a chapter: entries of the table of
contents, links with a fragment (ch01.md#the-station), and a reader's
bookmarks. With GitHub Flavored Markdown
(ADR-0006) an anchor is not written by the
author. GitHub derives it from the heading text, and that rule is defined
only by its implementation.
Decision
A position is a text resource number and a byte offset into the decoded chapter. The table of contents stores positions. Resource 4 is a table that maps anchor names to positions; the writer fills it using GitHub's naming rule, and readers only look names up.
Options considered
| Dimension | A: offsets and a stored anchor table | B: readers compute GitHub anchors | C: explicit {#id} attributes |
|---|---|---|---|
| Reader complexity | Table lookup | Must reproduce GitHub's algorithm exactly | Parser extension for attributes |
| File size | About 150 B for three anchors; grows with headings | 0 | A few bytes per heading in the text |
| Compatibility | Chapters stay plain GFM | Chapters stay plain GFM | Not GFM |
| Evolution | The naming rule can change without touching readers | Any change breaks old readers | Stable |
| Risk | Table and text can disagree if a writer is wrong | Two readers can disagree | None |
Chosen: A.
Trade-off analysis
- B needs no table, but it makes an unspecified algorithm part of every reader. Any difference in Unicode case mapping or punctuation handling produces links that work in one reader and not in another.
- C is exact and simple, and was dropped together with the dialect that supported it.
- A runs the algorithm once, in the writer, where the result is checked against every link of the book. The cost is one small table, and a class of writer bugs in which the table and the text disagree.
Byte offsets were chosen over character or block indices because they need no parsing to apply and are the value a parser already reports for a heading.
Consequences
- Easier: links never depend on a reader's Markdown implementation.
- Easier: contents entries, links and bookmarks share one kind of position.
- Easier: a contents row with a non-zero offset must match an anchor row
(decided 2026-11-21), so a contents target is a path and an optional anchor
name, and an editing library never handles raw offsets
(
mbook, Navigation). - Harder: editing a chapter invalidates saved positions and requires
rebuilding
tocandanchors. - To revisit: whether the GitHub naming rule should be specified exactly for writers, or stay a recommendation.
- Later: resource 4 holds the names of headings only. Names of other positions go into a table of their chapter (ADR-0008).
Action items
- Packer: generate anchor names and verify every link fragment.
- Packer: check that every offset is at the start of a line.
- Reader: resolve fragments by exact byte comparison after percent-decoding.
ADR-0008: Anchors that are not headings live in a table before their chapter
Status: Accepted; the points under "Proposed details" are proposed
Date: 2026-11-21
Deciders: Format author
Context
ADR-0007 gives every heading a name in
resource 4, and a link reaches it as ch01.md#the-station. Books in other
formats link to more than headings: EPUB and FB2 let any element carry an
identifier, and cross-references such as "see figure 3" or an index entry
lead to a paragraph, a figure or a row of a table.
A converter (mbook-converter) could only send such
a link to the nearest heading above its target. The format itself did not
forbid other rows in resource 4, but that table is decoded whenever a file is
opened: a reference work with a name on every paragraph would pay for all of
them before showing its title.
Decision
A link destination stays what it is: a chapter path and, after #, a name
inside that chapter. The names of headings stay in resource 4. Every other
named position of a chapter is stored in an anchor table of that chapter:
a resource of its own, placed immediately before the chapter.
Options considered
| Dimension | A: a table before each chapter; headings stay in resource 4 | B: every anchor in resource 4 | C: every anchor in a table before its chapter; no resource 4 | D: no new anchors; links go to the nearest heading |
|---|---|---|---|---|
| Reader complexity | One more table shape; a fragment is looked up in two places | Unchanged | One table shape; a fragment always needs a second frame | Unchanged |
| Cost of opening a file | Grows with headings only | Grows with every anchor of the book | Constant | Grows with headings only |
| Cost of following a link | One more small frame, next to the target chapter, for a name that is not a heading | None | One more small frame for every fragment | None |
| File size | A record and a table header per chapter that has such anchors, about 150 bytes | A few bytes per anchor | The same overhead for every chapter with a heading | 0 |
| What can be checked when a file is opened | Contents rows and links to headings | Everything | Nothing about fragments | Everything |
| Precision of converted links | Exact, to the line | Exact, to the line | Exact, to the line | The heading above the target |
Chosen: A.
Trade-off analysis
- D needs no change and loses information: a link to a paragraph lands on the heading above it. Technical and scholarly books are mostly made of such links.
- B is the smallest change, and makes the cost of opening a file depend on how densely a converter names positions.
- C has one mechanism instead of two, but a reader could no longer check the contents against the anchors, or resolve a link to a heading, without reading a frame per chapter.
- A keeps what a reader needs at once (headings, for the contents and for most links) where it is read at once, and moves the open-ended rest next to the chapter it describes. The cost is two places to look a name up, and one more frame to decode when a link names a place that is not a heading.
A separate frame was chosen over a second output of the chapter's own frame, so that a link can be resolved without decoding the text, and the text without decoding the names.
Proposed details
Decided by the format author: the two-part destination, the table in its own frame before the chapter, and resource 4 kept for headings. Written into RFC 0001 as proposals:
| Detail | Proposal |
|---|---|
| How the table is marked | A new kind, 3, in the resource table |
| How it is tied to its chapter | By position: the next resource is the chapter. No path, no extra column |
| Its columns | offset (u32), name (string) |
| Names | One namespace per chapter: a name is unique across resource 4 and the chapter's table |
| Contents rows | Still match a row of resource 4, so that they stay checkable when a file is opened |
| The start-of-line rule | Checked when the table and the text of the chapter are both decoded |
Consequences
- Easier: a converter keeps the exact target of every internal link.
- Easier: opening a book costs the same however many places a chapter names.
- Easier: a chapter and the names inside it sit next to each other in the file, so one read fetches both.
- Harder: a reader resolves a fragment in two steps, and the second one does I/O.
- Harder: a reader that opens a file lazily cannot tell a link to a missing name from a link to a name of the chapter's table without reading that table.
- Open here, settled by ADR-0009: where a writer learns the names. They are written in the Markdown of the chapter.
- To revisit: whether a contents row may lead to a position of a chapter's table.
Action items
- Reader: accept
kind3, tie the table to the next resource, and resolve fragments through it. - Writer: emit the table before a chapter that has such anchors, and none otherwise.
- Converter: name the targets of internal links
(
mbook-converter, Links and footnotes).
ADR-0009: A line is named by a link reference definition in its chapter
Status: Accepted; the points under "Proposed details" are proposed
Date: 2026-11-21
Deciders: Format author
Context
ADR-0008 lets a link lead to a line that is not a heading, through a table of names and byte offsets in front of the chapter. It did not say where a writer learns those names.
The first implementation took them from the caller: a name and a byte offset for a text already given. An offset belongs to one version of a text, so replacing the text had to drop every name of the chapter. Correcting one letter of a converted book removed all its link targets, and nothing in the new text could bring them back: the dialect (ADR-0006) has no way to mark a place. A book unpacked into a folder lost the names as well, because they existed only in the table.
Decision
A chapter names a line in its own Markdown, with a link reference definition that names itself, placed in front of the line:
[fig-1]: #fig-1

A writer finds these anchor definitions when it parses the chapter and fills the chapter's anchor table from them, as it fills resource 4 from the headings. Readers keep resolving fragments through the tables only.
Options considered
| Dimension | A: a link reference definition that names itself | B: {#id} attributes kept in the chapter | C: {#id} accepted by the writer and removed from the stored text | D: names and offsets given by the caller | E: as D, with offsets carried across an edit by comparing lines |
|---|---|---|---|---|---|
| Reader complexity | None: CommonMark renders nothing for a definition | Every reader must find and hide the attribute | None | None | None |
| Compatibility | Plain GFM; invisible on GitHub and in any viewer | Literal {#id} text everywhere but in mbook readers | Plain GFM | Plain GFM | Plain GFM |
| Survives an edit of the chapter | Yes: the name is part of the text | Yes | Only through a second form of the text that still has the marks | No | Mostly; a rewritten line is a guess |
| Survives unpacking into a folder | Yes | Yes | No | No | No |
| File size | One short line per name, besides the table row | A few bytes per name, besides the table row | The table row | The table row | The table row |
| Risk | A definition written for another purpose is taken for a name | A second dialect to specify | Two texts of one chapter that can disagree | An offset that outlives its text | A name that silently moves to another line |
Chosen: A.
Trade-off analysis
- B is the syntax of the first draft of the format. It was dropped with
ADR-0006 because it is not GFM: a chapter would show
{#fig-1}wherever it is viewed outside an mbook reader, and every reader would need a parser extension to hide it. - C keeps the stored text clean and moves the problem into the library: the text a program reads back has no marks, so editing it loses the names unless a second accessor returns the marked text.
- D was implemented first. It works for a converter, which builds a text once, and fails for any later edit.
- E repairs D with a heuristic. A name follows its line exactly when the line is unchanged, and by position when it was rewritten, which can be wrong without any error.
- A uses a construct every CommonMark parser already has and every renderer already hides. The name travels with the text through edits, through a folder of Markdown files and through any tool that handles GFM. The table of ADR-0008 stays what a reader uses; it is derived data, like the anchors of headings.
A link reference definition can also be used as intended: [the figure][fig-1]
in the same chapter is an ordinary link to #fig-1, and resolves to the
line the definition names.
Proposed details
Decided by the format author: names are written in the Markdown of the chapter, as link reference definitions. Written into RFC 0001 as proposals:
| Detail | Proposal |
|---|---|
| Which definitions are anchor definitions | Those whose destination is # followed by their own label, compared byte for byte after percent-decoding the destination |
| The position named | The first byte of the line on which the definition starts |
| A name that a heading of the chapter already has | The definition is an ordinary one and names nothing |
| A name defined twice | The first definition names its line; later ones name nothing |
| Rows of the table without a definition | Allowed; a reader does not compare the table with the text |
| A title on the definition | Allowed and ignored |
Consequences
- Easier: an editing library computes every offset from the text again, and
an edit keeps the names it does not delete
(
mbook, Extra anchors). - Easier: unpacking a book into a folder and packing it again keeps every link target.
- Easier: a converter writes one line of Markdown per link target instead of
tracking byte offsets (
mbook-converter, Links and footnotes). - Harder: a writer must know two rules of CommonMark. A definition cannot interrupt a paragraph, so it needs an empty line or the start of a block before it; and a following line that is only a quoted or parenthesised string would be read as its title, so such a line needs an empty line before it.
- Harder: a row of a table cannot be named, because a definition cannot stand inside a GFM table. The table as a whole can.
- To revisit: whether the self-naming rule is too easy to meet by accident.
Action items
- Writer: collect anchor definitions when a chapter is parsed and fill its anchor table from them.
- Library: remove the calls that took a name and an offset.
- Converter: emit an anchor definition in front of every link target that is not a heading.
ADR-0010: Landmarks are a table of their own, present only when a book has them
Status: Accepted; the points under "Proposed details" are proposed
Date: 2026-11-21
Deciders: Format author
Context
A book has places a reader wants to reach without looking for them: where
the text begins, the glossary, the index, the notes. The table of contents
does not answer "where is the index": it lists titles, in the order of the
text, and an application cannot tell which entry is which. EPUB solves this
with a second list next to the contents, the landmarks, in which every
entry has a kind from a fixed vocabulary. A converter
(mbook-converter) had nowhere to put that list.
Decision
A book may carry landmarks: a list in which each row has a kind, an
optional title and a place in the book. The place is what a link names: a
chapter, and optionally a named position inside it. The list is stored as a
table in a resource of its own, of a new kind, 4, and a book without
landmarks has no such resource.
Options considered
| Dimension | A: an optional resource of a new kind | B: a sixth fixed resource | C: keys of meta |
|---|---|---|---|
| Reader complexity | One more table shape; found through the resource table | One more table shape; found by number | None: a key and a link destination |
| Cost of opening a file | None; the table is decoded when it is wanted | One more frame for every book | None |
| File size | About 150 bytes, only in books that have landmarks | About 150 bytes in every book | A few bytes per landmark |
| Compatibility | A new kind is a compatible addition; no number changes | Every resource number after 4 changes; existing files and examples become invalid | A new key is a compatible addition |
| Evolution | Columns can be added at the end | Columns can be added at the end | A landmark is one string: no room for a title or for more |
Chosen: A.
Trade-off analysis
- B makes landmarks as easy to read as the contents, and charges every book for a table most books do not have. It also moves the cover and every chapter up by one number, in a format whose first five resources were fixed on purpose (ADR-0003).
- C is how the cover is named today. A landmark, though, needs a title that an application can show ("Glossary of terms"), may repeat (several appendices), and is navigation, not a description of the book.
- A follows the anchor tables of chapters (ADR-0008): what only some books need lives in a resource that only those books have, and the resource table already says where it is.
Proposed details
Decided by the format author: landmarks exist, their place is named like the
target of a link, and they are an optional resource of kind 4 with the
columns kind, title, resource, offset. The list of kinds was settled
on 2026-11-21 as well:
- It is the structural vocabulary of EPUB, with the names written out
(
list-of-figuresforloi,startforbodymatter). - The narrative parts are kinds of their own:
introduction,prologue,epilogue,conclusion. about-the-authoris added, although EPUB has no such type: it is among the places books most often have.- A table of contents set in the text is not a kind. The
toctable is the contents of a book, and a second one in the text only repeats it. acknowledgementsis spelled the British way; EPUB writesacknowledgments.- The three kinds of notes of EPUB (
footnotes,endnotes,rearnotes) are one kind,notes.
Written into RFC 0001 as proposals:
| Detail | Proposal |
|---|---|
| How many such resources | At most one per file |
| Where it stands | Directly after resource 4, before the cover |
| The form of a kind | That of a meta key: [a-z0-9]+(-[a-z0-9]+)*, with x- for private use |
| Repetition | Any kind may repeat, except start |
| A position inside a chapter | Must match a row of anchors or of the chapter's anchor table, so that it can be written as a link destination |
| An unknown kind | Shown by its title; skipped when it has none |
| A damaged table | An error confined to the landmarks: the book is still read |
Consequences
- Easier: an application can offer "go to the beginning", "glossary" and "index" without guessing from titles.
- Easier: a reader that opens a book for the first time can start at the text instead of the cover page.
- Easier: the landmarks of an EPUB survive conversion.
- Harder: a reader has a second list of places besides the contents, and the two can disagree.
- Harder: the names of kinds are a vocabulary this format now maintains.
- To revisit: whether
startshould also be reachable without decoding a table, as ametakey.
Action items
- Reader: accept
kind4, at most once, and read the table on request. - Writer: emit the table after resource 4 when a book has landmarks.
- Converter: carry over the landmarks of EPUB 3 and the guide of EPUB 2.
ADR-0011: Diagrams and formulas are resources of their own kinds, shown the way a picture is
Status: Accepted
Date: 2026-11-22
Deciders: Format author
Context
A textbook has formulas on every page and a technical book has diagrams. Until now a book could carry them only as pictures: the packer drew each one and stored it as an AVIF file (ADR-0002). A picture of a formula does not follow the size of the text, its typeface or the page tone, cannot be read aloud, and cannot be corrected without the tool that drew it. The appendix of RFC 0001 measures a textbook with 3,000 such pictures.
Both have a notation that is text. A diagram is described in Mermaid, a formula in the LaTeX subset that KaTeX sets. Two things constrain how a book stores them:
- A chapter is GitHub Flavored Markdown without raw HTML (ADR-0006), and an unpacked book is a folder that any Markdown viewer shows.
- A reader that does not know a later addition must still show the book (RFC 0001).
Decision
A book may carry diagrams and formulas. Each is a resource of its own, with a path, like a picture:
kind | Resource | Decoded content |
|---|---|---|
| 5 | Diagram | UTF-8 text in Mermaid notation |
| 6 | Formula | UTF-8 text in the notation of KaTeX |
A chapter shows one the way it shows a picture, , and
the resource table tells which of the three a path names. Alone in a
paragraph it is a figure; inside a line it is a part of that line. The
alternative text is what a reader shows when it cannot draw the diagram or
set the formula.
Options considered
| Dimension | A: resources of new kinds, shown like pictures | B: additions to the dialect (```mermaid fences, $…$) | C: pictures only, as before |
|---|---|---|---|
| Reader complexity | A Mermaid renderer and a formula typesetter, both optional: without them the alternative text is shown | The same two, plus a Markdown parser with a math extension; without them the source is shown as code and as literal $…$ | None beyond AVIF |
| File size | The source, compressed, plus 74 to 76 bytes per resource | The source inside its chapter, compressed with it | An AVIF file per formula: several hundred bytes at least |
| Compatibility | A new kind is a compatible addition: an older reader skips the resource and shows the alternative text | A chapter is no longer plain GFM for parsers without math; $ in prose (prices) changes meaning in existing books | Every reader shows it |
| Evolution | A kind per notation; a later notation is one more kind | Every notation is a dialect change and needs a new escape rule | Nothing to evolve; nothing to edit either |
| Reuse | A formula used ten times is stored once | Repeated in the text | Stored once |
Chosen: A.
Trade-off analysis
- C is what the format did. It asks nothing of a reader and gives up everything that makes a formula text: size, tone, speech and correction.
- B is what GitHub renders, and the first draft of the format listed
math among the future additions to the dialect. It changes what a chapter
is:
$5 and $10in a novel becomes a formula, so existing text needs escaping, and a parser without the extension shows the delimiters. A reader that cannot draw a diagram shows its source as a code block, with no words that say what the diagram is of. - A leaves the dialect alone.
is Markdown every parser reads; only the kind of the target is new, and a reader learns it from the table it already has. The price is one small frame for each formula, and a plain Markdown viewer over an unpacked book shows a broken image with the alternative text, where B would show at least the source.
The alternative text decides it. A book meant to be read by everyone needs a fallback in words for each diagram and formula, and the picture syntax is the one place in GFM that has such a field.
Format details
The format author confirmed these details on 2026-11-22. RFC 0001 records the format rules.
| Detail | Decision |
|---|---|
| The codes | kind 5 for a diagram, 6 for a formula |
| The reference | The picture syntax; no syntax of its own |
| Display or inline | A formula alone in a paragraph is set as a display formula, any other as a part of its line |
| The size columns | Zero: a reader lays a diagram and a formula out itself |
| The encoding | That of a chapter: UTF-8, line feeds, no other control character but tab |
| An empty source | Not allowed: a writer refuses it |
| The version of a notation | Mermaid 11 and KaTeX 0.16 are references for authors. A reader shows the alternative text for what it cannot render. |
| Checking the notation | Not a writer's duty: mbook stores the source as text and links no renderer |
| The recommended file names | .mmd for a diagram, .tex for a formula |
| The cover | Stays a picture |
| The format version | Stays 1.0 while the format is a draft, although a new kind is the kind of change minor exists for |
| Active content | A reader runs no script, follows no link and fetches nothing for a diagram or a formula |
Consequences
- Easier: a formula follows the size, the typeface and the page tone of the text, and a diagram the page tone.
- Easier: an editor changes a diagram or a formula as text, in the book.
- Easier: a formula-heavy book is smaller, a few dozen bytes of source per formula instead of an AVIF file.
- Harder: a reader that wants to show them needs two more renderers, and both notations are defined by an implementation, not by a specification.
- Harder: the size of a diagram or a formula is not in the tables, so a reader cannot reserve its space before it is laid out.
- Harder: a Markdown viewer over an unpacked folder shows the alternative text only.
- To revisit: a converter that turns
```mermaidfences and$…$of a Markdown source into these resources; whether a reader should be told which version of a notation a book was written for; the per-resource overhead for books with thousands of one-letter formulas.
Action items
- Reader: give kinds 5 and 6 ids of their own and read them as text.
- Writer: store diagrams and formulas after the pictures; accept them as targets of the picture syntax.
- Application: render both, and edit them in the book editor.
- Converter: carry over the diagrams and formulas of a Markdown source.
mbook
| Crate | mbook |
| API documentation | docs.rs/mbook |
| Source | crates/mbook |
| Implements | RFC 0001, format version 1.0 |
| Minimum Rust | 1.89 |
| Status | Draft: the API may still change with the format |
mbook is the Rust library that reads and writes mbook files. It has two
central types:
BookReader<R>reads a book lazily from anything that can seek. Opening it costs the directory and five small frames; each chapter, picture, diagram and formula, and the anchor table of each chapter, is decoded when asked for.Bookis a whole book in memory that can be changed and written out. It is how a book is created, and how an existing one is edited.
A source that cannot seek is served by both: BookReader::buffered keeps the
compressed bytes in memory and still decodes on demand, and Book::read
decodes everything in one pass.
[dependencies]
mbook = "0.3"
| Page | What it answers |
|---|---|
| Guide | How is a book shown, read, edited and created? Each task with its code. |
| API reference | Which types and calls exist, what each reads from the source, and when it fails. |
| Design | Which crates the library is built on, what the design costs, and why it looks this way. |
The two types
flowchart LR
file["File, or any<br/>Read + Seek"] -- "open / new" --> reader
stream["Any Read"] -- "buffered" --> reader
stream -- "Book::read" --> book
scratch["Book::new"] --> book
reader["BookReader<br/>lazy, read-only"] -- "load" --> book
book["Book<br/>in memory, editable"] -- "write / save" --> out["A new .mbook file"]
BookReader<R> | Book | |
|---|---|---|
| Holds | The four tables and the source | Every chapter, picture, diagram and formula, decoded |
| Memory | Kilobytes for a novel | The decoded size of the book |
| Can change the book | No | Yes |
| Addresses a resource by | ChapterId, PictureId, DiagramId or FormulaId, its number in the file | Path |
| Typical user | A reading application | A converter or an editor |
Resource numbers are exact and cheap for a reader, but they shift whenever a
resource is added or removed. A Book therefore uses paths, which are unique
and are what Markdown links already use; numbers are assigned when it is
written.
What it is for
RFC 0001 defines bytes. A program that shows or produces books should not handle typed columns, resource numbers and the container itself. Four tasks must each take a few lines:
| Task | Who does it |
|---|---|
| Show a title, a cover and contents without reading the file | Library views, file managers |
| Show one chapter and its pictures | Readers |
| Change metadata or text of an existing book | Editors, library managers |
| Build a book from converted sources | Packers and converters |
Goals
| Goal | How the design meets it |
|---|---|
| Reading costs what is shown | BookReader decodes the tables once and one resource per call. |
| One reading API for files and streams | BookReader::buffered turns any Read into the same reader type. |
| An invalid book cannot be written | Book::write checks every MUST of RFC 0001 first. |
| Edits cannot leave stale navigation | Anchors and contents offsets are computed from the text when writing. |
| The call site reads like the task | Paths, titles and link destinations as arguments; no row numbers when building. |
| mopenzl stays an implementation detail | No mopenzl type appears in a public signature. |
Non-goals
- Rendering Markdown, decoding AVIF, drawing diagrams or setting formulas. Chapters are returned as text, pictures as AVIF bytes, and diagrams and formulas as their source. The crate links no Mermaid and no KaTeX implementation and does not check their notation.
- Converting from other formats. FB2, EPUB and image conversion belong to crates built on this one.
- Editing in place, or without loading the book. The format excludes the
first. For the second, editing always goes through a
Bookin memory and saving always writes a new file; no streaming editor is planned. - Asynchronous I/O and
no_stdin the first version. Table encoding and validation are kept free of I/O so that both can be added later.
Using mbook
Every task below takes a few lines. The examples leave out the surrounding
function; each ? returns an mbook::Error. The same
examples are compiled as the doc tests of the crate, where they are complete.
Showing a book in a library
use mbook::BookReader;
let mut book = BookReader::open("example.mbook")?;
let meta = book.meta();
println!("{} by {}", meta.title(), meta.authors().collect::<Vec<_>>().join(", "));
if let Some(avif) = book.read_cover()? {
// hand the bytes to an AVIF decoder
}
open reads the footer, the directory and resources 0 to 4. read_cover
reads one more frame.
Reading a chapter
use mbook::{BookReader, Destination};
for entry in book.toc() {
println!("{}{}", " ".repeat(entry.level as usize - 1), entry.title);
}
let first = book.chapters().next().expect("a book with text").id;
let text = book.read_chapter(first)?;
// While rendering: what does this link or picture destination point to?
match book.resolve(first, "img/fig-1.avif") {
Ok(Destination::Picture(id)) => {
let size = book.picture(id).map(|p| p.size); // reserve space first
let avif = book.read_picture(id)?; // decode when visible
}
Ok(Destination::Diagram(id)) => {
let mermaid = book.read_diagram(id)?; // draw it, or show the alt text
}
Ok(Destination::Formula(id)) => {
let katex = book.read_formula(id)?; // set it, or show the alt text
}
Ok(Destination::Chapter(position)) => { /* jump to position */ }
Ok(Destination::ExtraAnchor(chapter)) => { /* a place in `chapter`; see below */ }
Ok(Destination::External) => { /* open only when the user asks */ }
Err(_) => { /* show the link text or the alternative text */ }
}
resolve reads nothing, so it can be called for every link of a chapter
while it is laid out. A link to a heading, or to the start of a chapter, is
answered in full. A link to another named line, such as
ch01.md#fig-1, is answered with Destination::ExtraAnchor: the name may be
in the anchor table of that chapter, which is not read when a book is opened.
When the user follows the link, read_resolve reads that table:
match book.read_resolve(first, "ch01.md#fig-1")? {
Destination::Chapter(position) => { /* jump to position */ }
_ => { /* as above */ }
}
Methods that only look into the tables take &self and cannot fail with an
I/O error. Methods that touch the source start with read_ and take
&mut self.
A chapter, a picture, a diagram and a formula have different id types, so
read_chapter cannot be called with the id of a picture. Ids come from the reader. To keep one outside
the program, for a bookmark, store its number and ask the reader for the id
again:
let saved = (position.chapter.number(), position.offset);
// … later, with the same book open
let chapter = book.chapter_id(saved.0); // None: not a chapter of this book
Reading from a source that cannot seek
use mbook::{Book, BookReader};
use std::io;
// The same lazy reader, over a buffer that holds the compressed file.
let mut book = BookReader::buffered(io::stdin().lock())?;
// Or everything decoded at once.
let book = Book::read(io::stdin().lock())?;
for chapter in book.chapters() {
println!("{}: {} bytes", chapter.path(), chapter.text().len());
}
Editing a book
use mbook::Book;
let mut book = Book::open("example.mbook")?;
book.meta_mut().set_title("The Example, 2nd edition")?;
book.meta_mut().add_author("B. Editor")?;
if let Some(chapter) = book.chapter_mut("ch02.md") {
let fixed = chapter.text().replace("teh", "the");
chapter.set_text(fixed)?;
}
book.remove_picture("img/unused.avif");
book.save("example.mbook")?;
save writes a temporary file next to the target and renames it into place,
so an interrupted save never damages the original. The byte offsets that the
contents and the anchors need are recomputed for ch02.md; nothing has to be
rebuilt by hand.
There is no rename. A resource moves to another path by being removed and added again; links to the old path are then reported when the book is saved.
let index = book.chapters().iter().position(|c| c.path() == "ch02.md").unwrap();
let old = book.remove_chapter("ch02.md").unwrap();
book.insert_chapter(index, "part1/ch02.md", old.text())?;
Creating a book
use mbook::{Book, Toc, TocItem};
use std::fs;
let mut book = Book::new("The Example", "en")?;
book.meta_mut().add_author("A. Writer")?;
book.set_cover("img/cover.avif", fs::read("img/cover.avif")?)?;
book.add_chapter("ch01.md", fs::read_to_string("ch01.md")?)?;
book.add_chapter("ch02.md", fs::read_to_string("ch02.md")?)?;
book.add_picture("img/fig-1.avif", fs::read("img/fig-1.avif")?)?;
book.save("example.mbook")?;
Book::newgives the book a new UUID version 7 as itsid.- Chapters are in reading order in the order they are added.
- CRLF and CR line endings become line feeds and a byte order mark is dropped;
chapter.text()returns the text as it will be stored. - The pixel size of a picture is read from the AVIF file.
- By default the contents are built from the headings. To choose the entries, name them the way a link would:
book.set_toc(Toc::Explicit(vec![
TocItem::new(1, "Arrival", "ch01.md"),
TocItem::new(2, "The station", "ch01.md#the-station"),
TocItem::new(1, "The letter", "ch02.md"),
]));
Diagrams and formulas
A diagram is added as its description in Mermaid notation and a formula in the notation of KaTeX. A chapter shows either the way it shows a picture:
book.add_diagram("dia/route.mmd", "flowchart LR\n station --> letter\n")?;
book.add_formula("math/speed.tex", r"v = \frac{s}{t}")?;
book.add_chapter("ch03.md", "\

The train kept  all the way.
")?;
// Later: correct the formula without touching the chapter.
book.formula_mut("math/speed.tex").unwrap().set_source(r"v = \frac{\Delta s}{\Delta t}")?;
- The source is stored as text, with the line endings of a chapter. The notation is not checked: a reading application shows the alternative text of what it cannot render.
- A reference with the syntax of a picture resolves when it names a picture, a diagram or a formula. A link to one of them does not.
Naming a line that is not a heading
Headings get their anchors by themselves. Any other line gets a name from one line of Markdown in front of it, an anchor definition:
book.add_chapter("ch01.md", "\
Chapter 1
[fig-3]: #fig-3

")?;
// In another chapter: [the figure](ch01.md#fig-3)
A Markdown renderer shows nothing for [fig-3]: #fig-3. The name is part of
the text, so it is still there after the text is edited:
let chapter = book.chapter_mut("ch01.md").unwrap();
chapter.set_text(chapter.text().replace("teh", "the"))?;
assert_eq!(chapter.extra_anchors()[0].name, "fig-3");
When something is wrong
Rules about one item are checked when the item is given, so the error points at the call that caused it. Rules that connect items are checked when the book is written, because a book under construction is allowed to be incomplete.
use mbook::{Error, ProblemKind};
match book.save("example.mbook") {
Err(Error::Invalid(problems)) => {
for p in problems.iter() {
if let ProblemKind::UnresolvedLink(dest) = &p.kind {
eprintln!("{:?}, byte {:?}: link to {dest} leads nowhere", p.path, p.offset);
}
}
}
other => other?,
}
Book::check runs the same checks without writing and reports every problem,
not only the first.
API reference
The signatures below are the public surface of the crate as implemented, grouped by type, with what each call reads and when it fails. The item-by-item documentation, with an example for every call, is on docs.rs.
Shared value types
pub struct ChapterId(/* private */); // a resource of kind 1
pub struct PictureId(/* private */); // a resource of kind 2
pub struct DiagramId(/* private */); // a resource of kind 5
pub struct FormulaId(/* private */); // a resource of kind 6
impl ChapterId { pub fn number(self) -> u32; } // its number in the file
impl PictureId { pub fn number(self) -> u32; }
impl DiagramId { pub fn number(self) -> u32; }
impl FormulaId { pub fn number(self) -> u32; }
pub struct Size { pub width: u32, pub height: u32 }
pub struct Position { pub chapter: ChapterId, pub offset: u32 }
pub struct Version { pub major: u8, pub minor: u8 }
pub struct ChapterEntry<'a> {
pub id: ChapterId,
pub path: &'a str,
pub decoded_len: u64, // from the container directory
}
pub struct PictureEntry<'a> {
pub id: PictureId,
pub path: &'a str,
pub size: Size,
pub decoded_len: u64,
}
pub struct DiagramEntry<'a> { pub id: DiagramId, pub path: &'a str, pub decoded_len: u64 }
pub struct FormulaEntry<'a> { pub id: FormulaId, pub path: &'a str, pub decoded_len: u64 }
pub struct TocEntry { pub level: u8, pub title: String, pub position: Position }
pub struct LandmarkEntry { pub kind: String, pub title: String, pub position: Position }
pub struct Anchor { pub offset: u32, pub name: String }
pub enum Destination {
External,
Chapter(Position),
Picture(PictureId),
Diagram(DiagramId),
Formula(FormulaId),
ExtraAnchor(ChapterId), // only from BookReader::resolve
}
// The raw resource table, for tools that list a file.
pub enum ResourceKind { // non-exhaustive
Service, Text, Picture, ChapterAnchors, Landmarks, Diagram, Formula, Unknown(u8),
}
pub struct Resource<'a> {
pub number: u32,
pub kind: ResourceKind,
pub path: &'a str,
pub size: Option<Size>,
pub decoded_len: u64,
}
/// The detection rule of RFC 0001; needs the first 53 bytes of a file.
pub fn is_mbook(prefix: &[u8]) -> bool;
- The four id types are
Copy, ordered and hashable. They have no public constructor: an id is obtained from aBookReader, which hands out aChapterIdonly for a text resource, aPictureIdonly for a picture, aDiagramIdonly for a diagram and aFormulaIdonly for a formula. - An id is a number inside one file. It is not stable across re-packings of a book; the stable name of a resource is its path.
Meta
One type serves both BookReader (through &Meta) and Book (through
&mut Meta).
impl Meta {
pub fn title(&self) -> &str;
pub fn language(&self) -> &str; // the main language
pub fn languages(&self) -> impl Iterator<Item = &str>;
pub fn id(&self) -> &str;
pub fn authors(&self) -> impl Iterator<Item = &str>;
pub fn translators(&self) -> impl Iterator<Item = &str>;
pub fn series(&self) -> Option<Series<'_>>; // name and index
pub fn publisher(&self) -> Option<&str>;
pub fn date(&self) -> Option<&str>;
pub fn isbns(&self) -> impl Iterator<Item = &str>;
pub fn genres(&self) -> impl Iterator<Item = &str>;
pub fn annotation(&self) -> Option<&str>;
pub fn cover(&self) -> Option<&str>; // a path
pub fn get(&self, key: &str) -> Option<&str>; // any key, first value
pub fn get_all(&self, key: &str) -> impl Iterator<Item = &str>;
pub fn iter(&self) -> impl Iterator<Item = (&str, &str)>;
pub fn set_title(&mut self, title: impl Into<String>) -> Result<()>;
pub fn set_language(&mut self, tag: impl Into<String>) -> Result<()>;
pub fn set_id(&mut self, id: impl Into<String>) -> Result<()>;
pub fn add_author(&mut self, name: impl Into<String>) -> Result<()>;
pub fn set_series(&mut self, name: impl Into<String>, index: Option<&str>) -> Result<()>;
pub fn set_cover(&mut self, path: impl Into<String>) -> Result<()>;
// … one setter or adder per key defined by RFC 0001
pub fn set(&mut self, key: &str, value: impl Into<String>) -> Result<()>;
pub fn add(&mut self, key: &str, value: impl Into<String>) -> Result<()>;
pub fn remove(&mut self, key: &str) -> Result<()>;
}
setreplaces every row of a key with one row;addappends a row.- A
Metaalways satisfies the counts of RFC 0001:removefails fortitle,langandid, andaddfails for a key that allows one value and already has it. - Unknown keys, including
x-keys, are kept and written back unchanged.
BookReader<R>
impl BookReader<File> {
pub fn open(path: impl AsRef<Path>) -> Result<Self>;
}
impl BookReader<Cursor<Vec<u8>>> {
pub fn buffered(reader: impl Read) -> Result<Self>;
}
impl<R: Read + Seek> BookReader<R> {
pub fn new(source: R) -> Result<Self>;
pub fn with_options(source: R, options: &ReadOptions) -> Result<Self>;
// From the tables; no I/O.
pub fn version(&self) -> Version;
pub fn meta(&self) -> &Meta;
pub fn toc(&self) -> &[TocEntry];
pub fn chapters(&self) -> impl ExactSizeIterator<Item = ChapterEntry<'_>>; // reading order
pub fn pictures(&self) -> impl ExactSizeIterator<Item = PictureEntry<'_>>;
pub fn diagrams(&self) -> impl ExactSizeIterator<Item = DiagramEntry<'_>>;
pub fn formulas(&self) -> impl ExactSizeIterator<Item = FormulaEntry<'_>>;
pub fn chapter(&self, id: ChapterId) -> Option<ChapterEntry<'_>>;
pub fn picture(&self, id: PictureId) -> Option<PictureEntry<'_>>;
pub fn diagram(&self, id: DiagramId) -> Option<DiagramEntry<'_>>;
pub fn formula(&self, id: FormulaId) -> Option<FormulaEntry<'_>>;
pub fn find_chapter(&self, path: &str) -> Option<ChapterEntry<'_>>;
pub fn find_picture(&self, path: &str) -> Option<PictureEntry<'_>>;
pub fn find_diagram(&self, path: &str) -> Option<DiagramEntry<'_>>;
pub fn find_formula(&self, path: &str) -> Option<FormulaEntry<'_>>;
pub fn cover(&self) -> Option<PictureEntry<'_>>;
pub fn chapter_id(&self, number: u32) -> Option<ChapterId>; // checked
pub fn picture_id(&self, number: u32) -> Option<PictureId>; // checked
pub fn diagram_id(&self, number: u32) -> Option<DiagramId>; // checked
pub fn formula_id(&self, number: u32) -> Option<FormulaId>; // checked
pub fn anchors(&self, chapter: ChapterId) -> &[Anchor]; // of headings
pub fn resolve(&self, from: ChapterId, destination: &str)
-> Result<Destination, ResolveError>;
pub fn resources(&self) -> impl ExactSizeIterator<Item = Resource<'_>>; // every row
// Seek, read and decode one resource.
pub fn read_chapter(&mut self, id: ChapterId) -> Result<String>;
pub fn read_extra_anchors(&mut self, chapter: ChapterId) -> Result<Vec<Anchor>>;
pub fn read_landmarks(&mut self) -> Result<Vec<LandmarkEntry>>;
pub fn read_resolve(&mut self, from: ChapterId, destination: &str)
-> Result<Destination>;
pub fn read_picture(&mut self, id: PictureId) -> Result<Vec<u8>>;
pub fn read_diagram(&mut self, id: DiagramId) -> Result<String>; // Mermaid
pub fn read_formula(&mut self, id: FormulaId) -> Result<String>; // KaTeX
pub fn read_cover(&mut self) -> Result<Option<Vec<u8>>>;
pub fn load(&mut self) -> Result<Book>; // decode everything
pub fn into_inner(self) -> R;
}
| Call | Reads from the source | Fails when |
|---|---|---|
open, new, buffered | Footer, directory, resources 0 to 4 | The file must be rejected under Conformance, or a limit is exceeded. |
| Table accessors | Nothing | Never; unknown ids give None or an empty slice. |
resolve | Nothing | The destination is unresolved under Resolving destinations, as far as resources 2 and 4 can tell. |
read_extra_anchors | The anchor table of one chapter; nothing when it has none | I/O; a damaged frame; the table is not of the defined shape or breaks a rule of Chapter anchor tables; the id came from another book. |
read_landmarks | The landmarks table; nothing when the book has none | I/O; a damaged frame; the table is not of the defined shape or breaks a rule of Landmarks. |
read_resolve | That table, and only when the fragment is not the anchor of a heading | Error::Unresolved when the destination is unresolved; otherwise as read_extra_anchors. |
read_chapter, read_picture | One record | I/O; a damaged frame; the resource exceeds its limit; the text is not UTF-8, or a stored position in it is not at the start of a line; the id came from another book. |
read_diagram, read_formula | One record | I/O; a damaged frame; the resource exceeds its limit; the source is not UTF-8; the id came from another book. |
load | Every text, picture, diagram, formula and anchor table record, and the landmarks | As above, for any resource; an extra anchor is not at the start of a line; or the decoded book exceeds the file limit. |
- An error in one resource does not poison the reader; other resources can still be read.
resolvetakes the destination after the Markdown parser has processed escapes and entities, and applies the steps of RFC 0001. Withread_resolveit is all a reading application needs for links and pictures.- A fragment is resolved in two steps, because RFC 0001 stores names in
two places.
resolveknows the anchors of headings. For any other fragment it looks at the resource table: when the target chapter has an anchor table it returnsDestination::ExtraAnchor, andResolveError::UnknownAnchorwhen it has none.read_resolvetakes the second step and never returnsExtraAnchor. - The anchor table of a chapter cannot show whether an offset is at the
start of a line.
read_extra_anchorsandread_resolvecheck everything else;loadandBook::read, which have the text as well, check this too. - An anchor table that breaks a rule fails the calls that read it, and
nothing else: its chapter is still read by
read_chapter. - Landmarks are read on request, by
read_landmarks; opening a book does not decode them. A landmarks table that breaks a rule fails that call andload, and nothing else. A landmark inside a chapter needs an anchor at its offset:read_landmarkschecks that against the anchors of headings and, when the chapter has an anchor table of its own, leaves the rest toload, which has that table. - A resource of an unknown
kindis listed byresourcesonly. It has no id type, so it cannot be decoded, andloadandBook::readleave it behind: a file of a later minor version loses such resources when it is edited. - The tables cannot show whether a stored position is at the start of a line;
that needs the text.
read_chapterchecks the positions of the chapter it decodes, and fails for that chapter only. - A diagram and a formula are read as text and not looked into. The
crate does not parse either notation, so
read_diagramsucceeds for a source no renderer accepts, and for an empty one, which RFC 0001 forbids writers to store: the application shows the alternative text. - The types rule out reading a picture as a chapter. They cannot rule out an
id taken from another book: such an id gives
Nonefrom the table accessors andError::NoSuchResourcefrom theread_calls. - A
BookReaderisSendwhenRis. To decode on several threads, open one reader per thread.
Book
impl Book {
pub fn new(title: impl Into<String>, language: impl Into<String>) -> Result<Self>;
pub fn open(path: impl AsRef<Path>) -> Result<Self>;
pub fn read(reader: impl Read) -> Result<Self>;
pub fn read_with(reader: impl Read, options: &ReadOptions) -> Result<Self>;
pub fn check(&self) -> Result<(), Problems>;
pub fn write(&self, writer: impl Write) -> Result<()>;
pub fn write_with(&self, writer: impl Write, options: &WriteOptions) -> Result<()>;
pub fn save(&self, path: impl AsRef<Path>) -> Result<()>;
pub fn meta(&self) -> &Meta;
pub fn meta_mut(&mut self) -> &mut Meta;
pub fn chapters(&self) -> &[Chapter]; // reading order
pub fn chapter(&self, path: &str) -> Option<&Chapter>;
pub fn chapter_mut(&mut self, path: &str) -> Option<&mut Chapter>;
pub fn add_chapter(&mut self, path: impl Into<String>, text: impl Into<String>)
-> Result<&mut Chapter>;
pub fn insert_chapter(&mut self, index: usize, path: impl Into<String>,
text: impl Into<String>) -> Result<&mut Chapter>;
pub fn move_chapter(&mut self, path: &str, index: usize) -> Result<()>;
pub fn remove_chapter(&mut self, path: &str) -> Option<Chapter>;
pub fn pictures(&self) -> &[Picture];
pub fn picture(&self, path: &str) -> Option<&Picture>;
pub fn add_picture(&mut self, path: impl Into<String>, avif: impl Into<Vec<u8>>)
-> Result<&Picture>;
pub fn remove_picture(&mut self, path: &str) -> Option<Picture>;
pub fn set_cover(&mut self, path: impl Into<String>, avif: impl Into<Vec<u8>>)
-> Result<&Picture>; // add_picture + meta cover
pub fn diagrams(&self) -> &[Diagram];
pub fn diagram(&self, path: &str) -> Option<&Diagram>;
pub fn diagram_mut(&mut self, path: &str) -> Option<&mut Diagram>;
pub fn add_diagram(&mut self, path: impl Into<String>, source: impl Into<String>)
-> Result<&mut Diagram>;
pub fn remove_diagram(&mut self, path: &str) -> Option<Diagram>;
pub fn formulas(&self) -> &[Formula];
pub fn formula(&self, path: &str) -> Option<&Formula>;
pub fn formula_mut(&mut self, path: &str) -> Option<&mut Formula>;
pub fn add_formula(&mut self, path: impl Into<String>, source: impl Into<String>)
-> Result<&mut Formula>;
pub fn remove_formula(&mut self, path: &str) -> Option<Formula>;
pub fn toc(&self) -> &Toc;
pub fn set_toc(&mut self, toc: Toc);
pub fn landmarks(&self) -> &[Landmark];
pub fn set_landmarks(&mut self, landmarks: Vec<Landmark>) -> Result<()>;
}
impl Chapter {
pub fn path(&self) -> &str;
pub fn text(&self) -> &str;
pub fn anchors(&self) -> &[Anchor]; // of headings
pub fn extra_anchors(&self) -> &[Anchor]; // of lines it names
pub fn set_text(&mut self, text: impl Into<String>) -> Result<()>;
}
impl Picture {
pub fn path(&self) -> &str;
pub fn size(&self) -> Size;
pub fn data(&self) -> &[u8];
}
impl Diagram { // Formula is the same
pub fn path(&self) -> &str;
pub fn source(&self) -> &str;
pub fn set_source(&mut self, source: impl Into<String>) -> Result<()>;
}
Book::new creates the three required meta rows and fails only for an
empty title. id is urn:uuid: followed by a UUID version 7 generated by the
uuid crate. A converter that has a stable identifier replaces it with
meta_mut().set_id.
add_chapter, insert_chapter and set_text normalise the text before
storing it: CRLF and lone CR become a line feed, and a leading byte order mark
is removed. Nothing else is changed.
add_diagram, add_formula and set_source normalise a source the same
way, and refuse one without a character that is not white space. A diagram
and a formula can be changed in place, unlike a picture: their source is
text an editor works on, and removing and adding one again would move it to
the end of its list.
Navigation
pub enum Toc {
FromHeadings { max_level: u8 }, // Book::new uses 6: every heading
Explicit(Vec<TocItem>), // what a loaded book has
}
pub struct TocItem {
pub level: u8,
pub title: String,
pub chapter: String, // a path
pub anchor: Option<String>, // None is the start of the chapter
}
impl TocItem {
/// `href` is a link destination: `ch01.md` or `ch01.md#the-station`.
pub fn new(level: u8, title: impl Into<String>, href: &str) -> Self;
}
A Book never stores a byte offset that the caller has to keep correct:
- Anchors belong to their chapter.
add_chapterandset_textcompute them from the headings with the naming rule of RFC 0001. The rule is defined by GitHub's implementation, so the names come from a port of it, thegithub-sluggercrate. A heading whose name would be empty, such as# ***, gets no anchor, because the format does not allow an empty name. A chapter loaded from a file keeps the anchors stored in that file until its text is replaced, so links written against another writer's names keep working. - Contents entries name their target by chapter path and anchor, exactly as a link does. The offset is looked up when the book is written.
- Every stored contents row can be named this way, because RFC 0001
requires a contents row with a non-zero offset to match an anchor row
(Resource 3:
toc). A loaded row becomes the chapter's path and the name of the first anchor at that position.
Landmarks
pub struct Landmark {
pub kind: String, // `start`, `glossary`, `index`, …
pub title: String, // may be empty
pub chapter: String, // a path
pub anchor: Option<String>, // None is the start of the chapter
}
impl Landmark {
/// `href` is a link destination: `back/index.md` or `ch01.md#fig-1`.
pub fn new(kind: impl Into<String>, title: impl Into<String>, href: &str) -> Self;
}
The landmarks of a book are a list, set
as a whole with set_landmarks, like the contents.
- A landmark names its target the way a link does, by chapter path and anchor; its offset is looked up when the book is written. Unlike a contents item it may lead to an extra anchor as well as to a heading, because RFC 0001 lets a landmark match a row of either table.
set_landmarkschecks what concerns the list alone: the form of every kind, and that at most one landmark is thestart. Whether a landmark leads somewhere connects it with the chapters and is checked bycheckandwrite, asDanglingLandmark.- An empty list removes the landmarks; a book without them is written without the table.
- A loaded landmark becomes the chapter's path and the name of the first anchor at its position, of a heading before an extra one.
Extra anchors
A heading names itself. Any other line is named by an
anchor definition in the text of
its chapter: [fig-1]: #fig-1. The extra anchors of a chapter are written as
its anchor table, and a chapter
without them gets no table.
- Extra anchors are computed from the text, by the same parse that finds
the headings.
add_chapter,insert_chapterandset_textcompute them; no call takes a name or an offset. An edit therefore keeps every name whose definition it keeps, and removes a name by removing its line. - A definition that repeats the name of a heading of the chapter, or of an earlier anchor definition, adds no anchor, as RFC 0001 says.
- The definition stays in the text:
chapter.text()returns it, and a reading application gets it fromread_chapterand renders nothing for it. - A contents item leads to a chapter or to a heading, not to an extra
anchor: RFC 0001 wants a contents row inside a chapter to match a row of
anchors. An item that names an extra anchor is reported asDanglingTocItem. - A loaded chapter keeps the extra anchors stored in its file, under the same rule as its heading anchors: until its text is replaced. A file from another writer may name a line without an anchor definition; that name is lost when the text is replaced.
Where each rule is checked
| Rule of RFC 0001 | Checked by | Reported as |
|---|---|---|
| Path syntax, path uniqueness | add_chapter, insert_chapter, add_picture, set_cover | Error::InvalidPath, Error::DuplicatePath |
| A position in the reading order exists | insert_chapter, move_chapter | Error::IndexOutOfRange |
| The chapter to move exists | move_chapter | Error::NoSuchPath |
| Text encoding: no control characters other than line feed and tab | add_chapter, insert_chapter, set_text, after normalising | Error::InvalidText, with the byte offset |
| The same rule, for a chapter that was loaded and never replaced | check, write | Problems |
| The picture is an AVIF file with a primary item | add_picture | Error::InvalidPicture |
| The source of a diagram or a formula: the encoding of a chapter, and not empty | add_diagram, add_formula, set_source, after normalising | Error::InvalidDiagram, Error::InvalidFormula, with a SourceError as its source |
| The same rules, for a diagram or a formula that was loaded and never replaced | check, write | Problems, with the path of the diagram or the formula |
meta key syntax and counts | Meta setters | Error::InvalidMeta |
The form of a landmark's kind; one start at most | set_landmarks | Error::InvalidLandmark, with a LandmarkError as its source |
| Every landmark leads to a chapter or to an anchor of it | check, write | Problems |
| No raw HTML, allowed URI schemes | check, write | Problems |
| Every link and picture reference resolves, a fragment against the anchors of headings and the extra anchors of its chapter; a picture reference names a picture, a diagram or a formula | check, write | Problems |
cover names a picture | check, write | Problems |
| Contents entries resolve; levels form a tree | check, write | Problems |
writerunscheckfirst and writes nothing if it fails.- Loading is lenient where RFC 0001 tells readers to be: a chapter with a broken link loads. The problem is reported when that book is written, because a writer MUST NOT produce such a file.
- Line endings and a byte order mark are the only things the crate repairs. Raw HTML and control characters are the converter's job; the error or the problem says where the offence is.
What write produces
Resources 0 to 4, then the landmarks when the book has any, then the cover,
then chapters in reading order, each directly after its anchor table when it
has extra anchors, then the remaining pictures, the diagrams and the
formulas, as RFC 0001 recommends. Pictures use the store graph; diagrams
and formulas are compressed like chapters.
The same Book written twice with the same options gives identical bytes.
Options and limits
#[non_exhaustive]
pub struct Limits {
pub max_resources: usize,
pub max_resource_bytes: u64, // decoded size of one resource
pub max_file_bytes: u64,
}
#[non_exhaustive] pub struct ReadOptions { pub limits: Limits }
#[non_exhaustive] pub struct WriteOptions { pub level: Option<i32>, pub limits: Limits }
Limits are applied before allocating, as RFC 0001 requires of readers. They
replace the mopenzl defaults, which are too small for picture-heavy books.
| Limit | Limits::default() | Reason |
|---|---|---|
max_resources | 1,000,000 | Ten times the largest book measured in RFC 0001; the directory is then 24 MB. |
max_resource_bytes | 64 MiB | The default frame limit of mopenzl. |
max_file_bytes | 16 GiB | Room for a comic of several thousand large pages. |
- A lazy reader decodes one resource at a time, so
max_resource_bytesis all that bounds its memory. A resource above the limit fails when it is read, not when the file is opened. - A
Bookholds everything decoded.max_file_bytestherefore also bounds the decoded size of a book thatBook::readorBookReader::loadbuilds. WriteOptions::leveloutside the range of the compressor is brought into that range.
Errors
One Error enum, non-exhaustive, with Result<T> = Result<T, Error>.
| Variant | Meaning |
|---|---|
Io | The source or the sink failed. |
NotMbook | No valid format header. |
UnsupportedVersion(Version) | major is newer than this crate. |
Container | The container or a frame is damaged. The mopenzl error is the source(), as a boxed dyn Error. |
Malformed { resource, reason } | A table breaks a MUST of RFC 0001. |
Limit | A configured limit was exceeded. |
NoSuchResource | A read_ call was given an id from another book. |
InvalidDiagram, InvalidFormula | The source given for a diagram or a formula is empty or holds a control character. The SourceError is the source(). |
Unresolved | read_resolve was given a destination that leads nowhere. The ResolveError is the source(). |
InvalidPath, DuplicatePath, InvalidText, InvalidPicture, InvalidMeta, InvalidLandmark | An argument to a Book or Meta method broke a rule. |
NoSuchPath, IndexOutOfRange | move_chapter or insert_chapter named a chapter or a position that does not exist. |
Invalid(Problems) | write or save refused the book. |
Design
What the library is built on, what its design costs, and the choices behind it. A choice between alternatives is recorded in the table of Rationale and alternatives; the choices of the file format itself are the decision records.
Dependencies and features
| Feature | Default | Enables | Brings in |
|---|---|---|---|
read | yes | BookReader, Book::read, Book::open | mopenzl decoding |
write | yes | Book::new and every call that changes, checks or saves a Book | mopenzl encoding, markdown, github-slugger, uuid, bytes, tempfile |
thiserror and percent-encoding are used with either feature.
-
At least one of the two must be enabled. With
readalone aBookis a fully loaded book that can be looked at but not changed. -
A reading application that builds with
readonly gets no Markdown parser from this crate;resolveneeds none. -
markdown1.0.0 is the parser that ADR-0006 found to cover the whole dialect and to report byte offsets. -
A mechanism comes from an established crate; only the rules of the format are written here.
Need Crate Heading and link analysis markdown1.0.0Anchor names by GitHub's rule github-sluggerPercent-decoding of destinations percent-encodingReading and writing integers in byte buffers bytesSaving through a temporary file tempfileBook identifiers uuidError types thiserror -
The pixel size of a picture is the one thing read by code of this crate, about 150 lines over
bytesthat walk the AVIF boxes to the properties of the primary item. The crates looked at, and what stands in the way of each:Crate Why it does not fit image0.25AVIF needs the C library libdav1d; the picture is decoded in full to learn its size; the size is that of the decoded frame, before crop and rotation. imagesize0.15Takes the largest ispebox of the file: ignores the crop and which item a property belongs to.avif-parse2Needs Rust 1.90, above the minimum of this crate, and is MPL-2.0. zenavif-parse0.6Gives the right size on the test files, but is MPL-2.0 and brings about 25 crates for three properties. The format author decided on 2026-11-21 to keep the code of this crate. No image decoder is linked.
Required from mopenzl
BookReader needs mopenzl 0.2.6 or later. Earlier versions offered random
access only through FramedSeekReader<'a, R>, which borrows its decoder, so
one struct could not hold the decoder, the source and the directory.
Version 0.2.6 adds a directory that owns its data and two calls on the
decoder:
/// A validated directory, detached from the source and the decoder.
pub struct FramedIndex { /* base offset, entries */ }
impl Deref for FramedIndex { type Target = [ResourceInfo]; }
impl FramedDecompressor {
/// Reads the header, the footer and the directory; decodes nothing.
pub fn framed_index<R: Read + Seek>(&self, source: R)
-> Result<FramedIndex, FramedError>;
/// Seeks to one record, reads it and decodes it.
pub fn read_indexed_resource<R: Read + Seek>(
&mut self, source: R, index: &FramedIndex, resource: usize,
) -> Result<DecodedResource, FramedError>;
}
BookReader holds a FramedDecompressor, a FramedIndex and the source as
three plain fields.
Drawbacks
- Two types to learn. A program that reads and then edits meets both, and resources are addressed by number in one and by path in the other.
- Editing loads the whole book. Changing the title of a 2 GB comic decodes 2 GB into memory and writes 2 GB back. This cost is accepted.
- Unchanged chapters are compressed again on save. Pictures are stored, so they cost a copy and a checksum; text costs a real compression pass.
- The write side carries a Markdown parser, although the crate renders nothing.
- Two calls resolve a link.
resolvecannot say where a fragment leads when it is not a heading's, and a reading application has to handleDestination::ExtraAnchor. bufferedwaits for the end of the stream before anything can be shown, because the directory is at the end of the file.
Rationale and alternatives
| Decision | Chosen | Rejected | Why |
|---|---|---|---|
| Name of the crate | mbook, the name of the format | mbook-core | Decided by the format author. The library is the reference implementation of the format; crates built on it, such as mbook-converter, carry a suffix. |
| Shape of the API | BookReader for lazy reading, Book for the editable model | One type generic over its storage | A lazy read can fail and needs &mut; an in-memory read cannot and does not. One type would force the weaker signature on both. |
A BookSource trait implemented by both | Same problem, plus a trait in every caller's signatures. | ||
| Streams that cannot seek | buffered gives the ordinary reader; Book::read gives the model | A third, forward-only reader type | Reading applications get one API. Memory is the compressed size instead of the decoded size. |
| Editing | Load into Book, change, write a new file | Nothing else was considered | Decided by the format author: one in-memory model serves both creating and editing. |
Addressing in Book | Path | Resource number; opaque handles | Numbers shift on every insertion. Paths are stable, unique, and already what chapters use. |
| Navigation data | Derived from text at write time | Editable toc and anchors tables with offsets | An offset that is still a valid position after an edit points at the wrong heading without any error. |
| Anchors of lines that are not headings | Read from anchor definitions in the text (ADR-0009) | add_anchor(name, offset), dropped by set_text | Implemented first and removed: correcting one letter of a chapter deleted all its link targets. |
The same, with offsets carried across set_text by comparing lines | A rewritten line is matched by position, which can name the wrong line without any error. | ||
Landmarks in Book | A list replaced as a whole, each target named by path and anchor | add_landmark and remove_landmark | The contents work the same way; one call keeps the rule about start in one place. |
Landmarks in BookReader | Read on request, by read_landmarks | Decoded when a book is opened | RFC 0001 keeps them out of the resources every book has; most books have none. |
| Resolving a fragment that is not a heading's | resolve without I/O returns ExtraAnchor; read_resolve reads the table | resolve reads the table itself | Table lookups take &self and do no I/O; a renderer calls resolve for every link of a page. |
| The reader keeps every anchor table it has read | Memory would grow with the chapters visited, for a table of a few hundred bytes that sits next to the chapter. | ||
| When rules are checked | One-item rules at the call, cross-item rules at write | Everything at write | The error names the call that caused it. |
| Everything at the call | A chapter could not be added before the pictures it shows. | ||
Ids in BookReader | ChapterId and PictureId, and later DiagramId and FormulaId | One ResourceId | Reading a picture as a chapter becomes a compile error instead of WrongKind at run time. |
| Diagrams and formulas in the API | Two types, Diagram and Formula, with calls of their own | One Figure type with a kind | A diagram cannot be handed to a formula typesetter by mistake, and the two lists of an editor are two calls. The price is the same six calls twice. |
| Changing a diagram or a formula | diagram_mut and set_source | Remove and add, as for a picture | Its source is text that is edited; removing it would move it to the end of its list and leave the book, for a moment, with references that lead nowhere. |
| Checking Mermaid and KaTeX notation | Not done | A parser of each behind a feature | Neither notation has a specification, a parser would tie a book to one implementation's version, and RFC 0001 lets a reader fall back to the alternative text. |
| A UUID for every resource | The format has nowhere to store one, and the path is already a stable unique name. UUID version 7 is used for the book's id only. | ||
| Line endings and byte order marks | Normalised silently | Rejected with an error | The meaning of the text does not change, and every caller would write the same replacement. |
| Moving a resource to another path | Remove and add | A rename that rewrites links | The crate would start editing chapter text it was given. |
| Helpers | Established crates for mechanisms; own code for the rules of the format | Hand-written cursors, decoders and temporary files | Less code to test and to keep correct; the exception is listed under Dependencies and features. |
| mopenzl in the API | Hidden behind Error::Container and Limits | Re-exporting FramedError and FramingConfig | A mopenzl major version would become an mbook major version. |
Prior art
| Crate | Taken from it | Left behind |
|---|---|---|
zip | A reader generic over Read + Seek; entries decoded on request | Entries borrowed from the archive, which makes holding two at once awkward |
epub | EpubDoc::new(path) as the one-line entry point; typed metadata getters | A cursor ("current page") inside the document object |
std::fs | open for a path, new for a value; read_ for calls that do I/O | |
toml_edit | A document model that is loaded, changed and written back |
Settled and open questions
The questions raised by the first draft were settled by the format author on 2026-11-21:
| Question | Decision |
|---|---|
| How is a book edited? | Only through a Book in memory. |
| Which Markdown parser does the write side use? | markdown 1.0.0. |
Where does the id of a new book come from? | Book::new generates a UUID version 7 with the uuid crate. |
| Are resources identified by UUID as well? | No. Only the book's id is a UUID. |
| CRLF line endings and a byte order mark? | Normalised silently. |
| A contents row at a position without an anchor? | Forbidden by RFC 0001; a contents target is a chapter and an optional anchor. |
| Renaming a resource? | Not provided; remove and add. |
| How are reader resources identified? | ChapterId, PictureId, DiagramId and FormulaId. |
Limits::default()? | 1,000,000 resources, 64 MiB per resource, 16 GiB per file. |
| Can a link lead to a line that is not a heading? | Yes, through the anchor table of its chapter (ADR-0008). |
| Where do the names of such lines come from? | From anchor definitions in the text of the chapter (ADR-0009). |
| Can a book list its notable places? | Yes, as landmarks in an optional table (ADR-0010). |
| Can a book carry diagrams and formulas as text? | Yes, as resources shown like pictures (ADR-0011); decided on 2026-11-22. |
The change required from mopenzl (Required from mopenzl) is a dependency, not an open question of this design.
Still proposed, and not confirmed by the format author:
- the names
extra_anchors,read_extra_anchors,read_resolveandDestination::ExtraAnchor; - the names
Landmark,LandmarkEntry,landmarks,set_landmarksandread_landmarks; - that a contents item cannot lead to an extra anchor.
Future possibilities
- Reusing buffers.
read_chapter_intoandread_picture_intofor readers that decode many resources in a row. - Asynchronous sources, for books opened over a network with range requests.
no_stdreading from a byte slice, using the container layer'sno_stdbuild.- Packing and unpacking a folder, as a small crate on top: the model already maps one to one onto files.
mbook-converter
| Crate | mbook-converter |
| API documentation | docs.rs/mbook-converter |
| Source | crates/mbook-converter |
| Builds on | mbook; RFC 0001, format version 1.0 |
| Minimum Rust | 1.89; 1.98 with the export feature |
| Status | Draft: the API may still change |
mbook-converter imports books into mbook and exports existing books to
other formats. Its central type, Converter, has four import entry points:
Result: an mbook file written to any Write | Result: a Book in memory | |
|---|---|---|
Source: any Read | convert | load |
| Source: a byte slice | convert_slice | load_slice |
Each import format has a Cargo feature enabled by default. The optional
export feature enables all writers. A format is read by an established crate (unpdf for PDF, rbook
for EPUB, and so on); this crate adds what is a rule of mbook: which chapter
a piece of text belongs to, what a link or a picture is called after
conversion, what the Markdown dialect allows, and that every picture becomes
AVIF.
What is implemented lists, format by format, what the crate does not do yet.
[dependencies]
mbook-converter = "0.3"
| Page | What it answers |
|---|---|
| Guide | How is a book converted, corrected and exported? Each task with its code. |
| API reference | Which types, features, options and errors exist, and what each export format keeps. |
| Conversion rules | What happens to chapters, links, pictures and metadata, format by format, and what each format cannot do yet. |
| Design | Which crates read each format, what the design costs, and why it looks this way. |
How a conversion runs
flowchart LR
src["Source<br/>any Read,<br/>or a byte slice"] --> det["Detect<br/>the format"]
det --> fe["Front end<br/>one established<br/>crate per format"]
fe --> draft["Draft<br/>metadata, Markdown,<br/>pictures, outline"]
draft --> asm["Assembler<br/>chapters, paths, links,<br/>dialect, AVIF"]
asm --> book["Book<br/>of mbook"]
book --> out["Any Write<br/>an .mbook file"]
- The format is detected from the content, unless the caller names it.
- The front end of that format parses the source with its crate and hands over a draft: metadata, Markdown in source order with the source's own names in links and pictures, the pictures, and an outline when there is one.
- The assembler is the same for every format. It cuts the text into chapters, gives chapters and pictures their paths, re-targets links, brings the Markdown into the dialect of RFC 0001, and encodes pictures as AVIF.
- The result is a
Bookofmbook.convertwrites it;loadreturns it.
What it is for
RFC 0001 describes a
packer that starts from FB2, EPUB or a folder, and
mbook leaves conversion to "crates
built on this one". Without such a crate every application that imports books
writes the same code: parse the source, produce Markdown without raw HTML,
re-encode pictures, rename every reference, build the contents.
| Task | Who does it |
|---|---|
| Convert a file on disk | A command-line tool, a library manager |
| Convert an upload or a download without a temporary file | A server, a reading application |
| Convert, then correct the metadata before saving | A library manager |
| Ship only the formats an application needs | An embedded or mobile reader |
Goals
| Goal | How the design meets it |
|---|---|
| No file paths in the API | Sources are Read or &[u8]; the result goes to Write or stays a Book. |
| A sink that cannot seek is enough | The file is written in one forward pass by Book::write. |
| Pay only for the formats used | One feature per format; a disabled format costs no dependency. |
| The rules of mbook are written once | Every front end hands over the same draft; one assembler builds the book. |
| A converted book is always valid | The book goes through Book::check before a byte is written. |
| Losses are visible | Whatever cannot be represented is reported as a Warning, not dropped silently. |
| Parsers are not written here | Each format is read by an established crate. |
Non-goals
- Keeping the layout. Fonts, colours, CSS, page geometry and fixed positions are dropped; RFC 0001 excludes them from the format.
- Removing protection. A protected source is refused.
- Recognising text in pictures. The pages of a scanned PDF are stored as pictures.
- Fetching anything. A picture or a stylesheet named by a network address is never downloaded.
- Asynchronous I/O, as in
mbook.
Using mbook-converter
The examples leave out the surrounding function; each ? returns an
mbook_converter::Error.
Converting a file
use mbook_converter::Converter;
use std::fs::File;
use std::io::BufWriter;
let source = File::open("book.epub")?;
let sink = BufWriter::new(File::create("book.mbook")?);
let report = Converter::new().convert(source, sink)?;
println!("converted from {}", report.format);
for warning in &report.warnings {
eprintln!("{warning}");
}
The source may be anything that implements Read: a file, standard input, a
network stream, an entry of an archive. It is never asked to seek.
Converting bytes that are already in memory
let bytes: &[u8] = /* an upload, a memory-mapped file, include_bytes! */;
let mut mbook = Vec::new();
Converter::new().convert_slice(bytes, &mut mbook)?;
convert_slice exists because a slice can be read at any position: formats
that need random access use it in place, where a Read has to be buffered
first (Sources and memory).
Correcting the book before it is written
use std::io;
let mut converted = Converter::new().load(io::stdin().lock())?;
let book = &mut converted.book;
book.meta_mut().set_title("The Example")?;
book.meta_mut().set_language("en")?;
book.save("example.mbook")?;
converted.book is an ordinary Book: every
call of mbook works on it.
Exporting a book
use mbook_converter::{Converter, Format, mbook::Book};
use std::fs::File;
use std::io::BufWriter;
let book = Book::open("example.mbook")?;
let sink = BufWriter::new(File::create("example.epub")?);
Converter::export(&book, Format::Epub, sink)?;
Enable the converter’s export feature to use this call. An application can
pass a book already in memory and use Format::extension() for the suggested
file name. Format::is_enabled() reports which import formats are enabled.
Diagrams and formulas are written as pictures; one that cannot be drawn
becomes its alternative text.
Drawing a diagram or a formula
use mbook_converter::figure::{self, Palette, Setting};
let night = Palette { ink: 0xb8b8b8, page: 0x000000 };
let diagram = figure::diagram("flowchart LR\n A --> B", night)?;
let formula = figure::formula(r"v = \frac{s}{t}", Setting::Line, night)?;
// Scale both to text of 18 pixels.
let width = formula.width() * 18.0 / formula.em();
std::fs::write("flow.svg", diagram.svg())?;
The same export feature enables figure. A reader gives the colours of
its page and scales the figure to its text; a formula inside a line is set
with Setting::Line and placed on the line at baseline().
Choosing formats and settings
# Cargo.toml: only EPUB and FB2
mbook-converter = { version = "0.3", default-features = false, features = ["epub", "fb2"] }
use mbook_converter::{ConvertOptions, Converter, Format};
let mut options = ConvertOptions::default();
options.format = Some(Format::Fb2); // do not detect
options.pictures.quality = 60; // smaller pictures
let converter = Converter::with_options(options);
A source in a format whose feature is off is still recognised, so the error names it:
match converter.convert_slice(bytes, &mut mbook) {
Err(Error::FormatDisabled(format)) => eprintln!("built without support for {format}"),
other => { other?; }
}
What is lost
A conversion that succeeds may still have dropped something: a table with
merged cells, a picture in a format that cannot be decoded, a link into the
middle of a paragraph. Each loss is one Warning in the report, with the
place in the source where the front end knows it. An application decides
whether to show them.
API reference
The signatures below are the public surface of the crate as implemented. The item-by-item documentation is on docs.rs.
Public surface
pub struct Converter { /* options */ }
impl Converter {
pub fn new() -> Self; // also Default
pub fn with_options(options: ConvertOptions) -> Self;
// Source to file.
pub fn convert(&self, source: impl Read, sink: impl Write) -> Result<Report>;
pub fn convert_slice(&self, source: &[u8], sink: impl Write) -> Result<Report>;
// Source to model.
pub fn load(&self, source: impl Read) -> Result<Converted>;
pub fn load_slice(&self, source: &[u8]) -> Result<Converted>;
#[cfg(feature = "export")]
pub fn export(book: &mbook::Book, format: Format, sink: impl Write) -> Result<()>;
}
#[cfg(feature = "export")]
pub mod figure {
pub fn diagram(source: &str, palette: Palette) -> Result<Figure, FigureError>;
pub fn formula(source: &str, setting: Setting, palette: Palette)
-> Result<Figure, FigureError>;
pub enum Setting { Block, Line }
pub struct Palette { pub ink: u32, pub page: u32 } // also Default
pub struct Figure { /* SVG and measures */ } // svg, into_svg, width, height, baseline, em
#[non_exhaustive]
pub enum FigureError { Empty, Diagram(String), Formula(String), Renderer }
}
#[non_exhaustive]
pub struct Converted { pub book: mbook::Book, pub report: Report }
#[non_exhaustive]
pub struct Report { pub format: Format, pub warnings: Vec<Warning> }
#[non_exhaustive]
pub enum Format { Epub, Fb2, Pdf, Cbz, Docx, Html, Markdown, Text }
impl Format {
pub const ALL: &'static [Format];
pub const fn is_enabled(self) -> bool; // was its feature compiled in?
#[cfg(feature = "export")]
pub const fn extension(self) -> &'static str; // e.g. "md"
}
impl Display for Format { /* "epub", "fb2", … */ }
impl FromStr for Format { /* the same names, and common file extensions */ }
// The four structs of options and limits; see "Options and limits".
pub use mbook;
convert(source, sink)isload(source)followed bybook.write_with(sink, &options.write). Nothing is written to the sink unless the whole conversion succeeded.- A
Converterholds only its options. It isSend + Sync, and one value serves any number of conversions. Formathas every variant whatever features are enabled, so amatchon it does not depend on the feature set.mbookis re-exported:Book,WriteOptions,Limitsandmbook::Errorappear in this API. No type of any other dependency does; the rule ofmbookapplies to this crate as well.
Export
Converter::export takes an existing Book and a target format. The single
export feature enables the public export API, all eight writers, their
AVIF decoder, and the mbook read API. It works independently of the import
features, including in a build with only export enabled.
The call returns Error::Io if the sink fails or Error::Export with the
target and source error if encoding fails. The decoder bounds both the
primary and alpha coded dimensions at 100 million pixels per plane. The
caller owns the destination and can use a temporary file to publish it
atomically.
The export feature currently needs Rust 1.98. Its minimum can increase
independently of the Rust 1.89 minimum for the default import build.
| Format | Output |
|---|---|
| EPUB | EPUB 3 with XHTML chapters in reading order, contents, landmarks, links, footnotes, metadata, a PNG cover and illustrations, and diagrams and formulas as PNG resources. |
| DOCX | Editable Word paragraphs and headings, lists numbered by Word, basic inline styles, PNG pictures, diagrams and formulas, and core metadata. Tables are flattened into paragraphs. |
| FB2 | FictionBook 2 XML with chapter sections, basic inline styles, metadata and Base64-encoded PNG pictures, diagrams and formulas. An item of a list is a paragraph that opens with its marker. |
| A paginated document with selectable text, PNG illustrations, diagrams and formulas, and embedded Noto Sans. Glyph coverage is limited to the bundled font. A formula inside a line is drawn on a line of its own. | |
| CBZ | The paginated edition rasterized as numbered PNG pages, with a ComicInfo.xml metadata entry. |
| HTML | One self-contained document with contents, local links and PNG data URLs. |
| Markdown | One document with namespaced anchors and footnotes, AVIF data URLs for pictures, and img elements with PNG data URLs for diagrams and formulas. Support for inline HTML and data URLs varies across Markdown viewers. |
| Plain text | UTF-8 text in reading order with the alternative text of pictures, diagrams and formulas. An item of a list opens with its marker and is indented by two spaces for each list it is nested in. |
Chapter links and anchors are retained in EPUB, HTML and Markdown. Other writers flatten links to their visible text. When an output needs PNG, the decoder uses the coded AVIF pixels. AVIF container crop, rotation and mirror properties are not applied by these writers. Markdown embeds the original AVIF. Export does not fetch network resources.
Lists
EPUB, HTML and Markdown keep the lists of a book as lists. DOCX, FB2 and plain text write every paragraph of an item as a paragraph of its own, so that an item and the list nested in it are apart:
- In DOCX the items are numbered by Word. Every list has a numbering of its
own: bullets
•,◦and▪by level, or decimal numbers that start at the number of its first item. A level is indented by half an inch, and Word has nine; a list nested deeper takes the ninth. A later paragraph of an item is indented as far as its text, without a marker. - FB2 and plain text have no lists: the first paragraph of an item opens
with
•or its number, such as3..
A Word document exported this way is read back with the same lists.
Landmarks in an EPUB
The landmarks of the book are
listed in the landmarks navigation of the EPUB, after the cover page when
the book has a cover, and, for the kinds that EPUB 2 has a type for, in the
guide of the package as well. No other writer keeps them.
- A kind is written as its type of the EPUB structural semantics
vocabulary:
startasbodymatter,notesasendnotes,acknowledgementsasacknowledgments,title-pageastitlepage,list-of-figuresandlist-of-tablesasloiandlot,copyrightascopyright-page, and every other kind by its own name. In the guide,startistext,notesisnotes, andintroduction,prologue,epilogue,conclusion,afterwordandappendixhave no reference. - A landmark leads to the document of its chapter, and to the anchor it names in it.
- A landmark without a title gets the name of its kind in English, such as
StartorIndex, since a link of the navigation must have text. - Left out are
about-the-authorand the kinds for private use (x-…), which EPUB has no type for, and a landmark whose chapter or anchor the book does not have. - A book with neither landmarks nor a cover has no
landmarksnavigation.
An EPUB exported this way gives the same landmarks when it is imported again, except that a landmark without a title gets the name it was written with.
Diagrams and formulas are drawn by figure in
dark ink on a white page and written as PNG pictures, except in plain text.
A figure is scaled so that its text has the size of the body text of the
output: 16 CSS pixels in EPUB, HTML and Markdown, 16 pixels in FictionBook,
11 points in DOCX and PDF. It is drawn at two pixels per unit of that size,
three per point in PDF, and one in FictionBook, which has no size for a
picture; a figure that would take more than 16,777,216 pixels is drawn less
sharply. A diagram is drawn on the colour of the page, a formula on a
transparent background. A formula alone in its paragraph is a display
formula, and any other formula is set in its line (RFC 0001,
"Rendering"). EPUB, HTML and Markdown write a figure as an img element:
one alone in its paragraph is centred at its width, and one inside a line
takes the height of its drawing and is lowered to the baseline of the line.
A diagram or a formula that cannot be drawn is written as its alternative
text and does not fail the export. The labels of a diagram use the fonts
of the system, with the bundled Noto Sans for any family the system lacks.
Diagrams and formulas
figure::diagram draws a diagram in Mermaid notation with merman, and
figure::formula sets a formula in the notation of KaTeX with RaTeX. Each
gives a Figure: an SVG document, its width and height, the baseline of a
formula (the height for a diagram), and em, the size of text it was drawn
for (16 for a diagram, 20 for a formula). A page scales a figure by the
ratio of its own text size to em. The colours are a Palette of ink and
page; the default is #1b1b1b on white. Setting::Block sets a display
formula and Setting::Line one in the style of running text; a diagram is
the same in both.
- Leading and trailing white space of a source is not part of it; an empty
source is
FigureError::Empty. - A source that is not a diagram or a formula is
FigureError::DiagramorFigureError::Formula, with the message of the renderer as text, so the error can be cloned and kept with a cache entry. - A panic of a renderer is caught and reported as
FigureError::Renderer. - Mermaid runs in strict mode, so a
clickdoes nothing, and labels are written as SVG text withoutforeignObject. A remote image in a diagram and the target of\hrefin a formula are not part of the drawing. - The glyphs of a formula are outlines. A letter that the KaTeX fonts lack, such as a Cyrillic one, is drawn with a system font and given the room of its real glyph.
mbook-ui draws the figures of its pages with the same calls. EPUB, DOCX, PDF and CBZ buffer the output
document in memory before writing it to the sink.
Formats and features
| Feature | Source format | Front-end crate | Status |
|---|---|---|---|
epub | EPUB 2 and 3 | rbook | Confirmed format; crate proposed |
fb2 | FictionBook 2, plain and inside a ZIP (.fb2.zip) | quick-xml, zip | Confirmed |
pdf | unpdf | Confirmed | |
cbz | Comic book archive: a ZIP of pictures | zip, alphanumeric-sort | Confirmed |
docx | Word documents | undoc | Confirmed format; crate proposed |
html | One HTML document | htmd | Confirmed format; crate proposed |
md | One Markdown document | markdown, github-slugger | Confirmed |
txt | Plain text | none | Confirmed |
defaultenables every feature of the table.- The opt-in
rayonfeature encodes the pictures of a source on all cores at once instead of one after another (Pictures). The book is the same, byte for byte. Without a format that carries pictures it does nothing. - A build must enable an import format or
export; otherwise compilation fails with a message, as inmbook. - A feature enables only the dependencies its format needs. Shared mechanisms
have no feature of their own: the HTML-to-Markdown crate comes with
epubandhtml, the picture codecs with every format that carries pictures. The build script of the crate tells the compiler which of these groups is in use, so that the list of formats in a group is written once. zipandmarkdownare dependencies of every build: the first is needed to tell the formats that are ZIP archives apart, the second reads every chapter.- Every single-feature build must compile without warnings, including its documentation.
mbookis used with itswritefeature only.
Not in the first version, for lack of a maintained crate that meets the license and the minimum Rust version: Mobipocket, KF8/AZW3, DjVu, RTF, CBR (Future possibilities).
Options and limits
#[non_exhaustive]
pub struct ConvertOptions {
pub format: Option<Format>, // None: detect
pub pictures: PictureOptions,
pub limits: ConvertLimits,
pub write: mbook::WriteOptions, // used by convert and convert_slice
}
#[non_exhaustive]
pub struct PictureOptions {
pub quality: u8, // 1 to 100
pub speed: u8, // 1 (smallest file) to 10 (fastest)
}
#[non_exhaustive]
pub struct ConvertLimits {
pub max_source_bytes: u64,
pub max_picture_pixels: u64,
pub book: mbook::Limits,
}
| Setting | Default | Reason |
|---|---|---|
pictures.quality | 80 | Decided by the format author; not measured yet. |
pictures.speed | 6 | Decided by the format author; not measured yet. |
limits.max_source_bytes | 2 GiB | Proposed. Bounds the buffer of a source that cannot seek. |
limits.max_picture_pixels | 100,000,000 | Proposed. A page scanned at 600 dpi is about 35 million pixels. |
limits.book | Limits::default() | The same limits the written file is read with. |
- All three structs implement
Defaultand are changed by assigning their fields, likeReadOptionsofmbook. - A value outside its range is brought into the range.
limits.book.max_resource_bytesalso bounds one unpacked entry of an archive and one decoded Base64 picture;limits.book.max_file_bytesbounds the sum of everything unpacked.
Errors and warnings
One Error enum, non-exhaustive, built with thiserror, and
Result<T> = Result<T, Error>.
| Variant | Meaning |
|---|---|
Io | The source or the sink failed. |
UnknownFormat | The content matches no format of Detection. |
FormatDisabled(Format) | The format was recognised or named, and its feature is off. |
Source { format, .. } | The front-end crate could not parse the source. Its error is the source(), as a boxed dyn Error. |
Export { format, .. } | The writer or picture codec failed. Its error is the source(), as a boxed dyn Error. |
Protected(Format) | The source is encrypted or under rights management. |
Empty | Nothing in the source could be converted. |
Limit | An import limit or the export pixel limit was exceeded. |
Book | mbook refused a call, the final check or the write. Its error is the source(). |
#[non_exhaustive]
pub struct Warning {
pub kind: WarningKind,
pub location: Option<String>, // the source's name for the place, when known
}
#[non_exhaustive]
pub enum WarningKind {
MarkupDropped(String), // what: "sub", "table with merged cells", …
PictureDropped(String), // the source's name of the picture
LinkRetargeted(String), // a contents entry: its destination in the source
LinkDropped(String),
MetadataDropped(String), // the key
MetadataMissing(String), // the key that got a stand-in value
}
impl Display for Warning { /* one line, without a trailing full stop */ }
Warnings are in the order in which the assembler met them.
Conversion rules
What the converter does with a source, from the first byte to the finished
Book. The rules of Assembling the book are the same
for every format; Rules per format says what each front
end hands over, and What is implemented what it cannot
do yet.
Sources and memory
The converter accepts a forward-only Read and a slice.
- A
Readis read to its end into memory before anything else happens, bounded byConvertLimits::max_source_bytes. Three things need all of it: the format is detected from the content, anidmay be computed from every byte, and most front-end crates want the whole source. - A slice is used in place. No copy of the source is made by this crate.
A front-end crate may still make one:
rbookwants an owned source. - After that, every front end starts from the same thing, the bytes of the source.
Consequences that hold for every format:
- Peak memory is about the source plus the converted book. The result is
a
Book, and aBookholds every chapter and picture (mbook, Drawbacks). Conversion is streaming at its edges, aReadin and aWriteout; it is not a constant-memory pipeline. - The pictures of the source are held, as the front end extracted them, until the book is assembled.
Detection
When ConvertOptions::format is None, the format is taken from the
content.
| Format | Recognised by |
|---|---|
%PDF- within the first 1,024 bytes | |
| EPUB | A ZIP whose mimetype entry is application/epub+zip, or that contains META-INF/container.xml |
| DOCX | A ZIP that contains word/document.xml |
| FB2 in a ZIP | A ZIP with exactly one entry whose name ends in .fb2 |
| CBZ | Any other ZIP in which every entry is a picture, a folder or ComicInfo.xml |
| FB2 | An XML document whose root element is FictionBook |
| HTML | A document that starts with <!DOCTYPE html or <html, in any letter case |
| Markdown, text | Never detected; only when named |
- Rows are tried in this order; the first match wins.
- A file name is never used: a stream has none.
- A source that matches no row fails with
Error::UnknownFormat. A source that matches a format whose feature is off fails withError::FormatDisabled.
The draft
A front end is private code. It produces the same things for every format, and nothing else crosses into the assembler:
| Part | Content |
|---|---|
| Metadata | Values for the keys of meta, unchecked |
| Sections | Markdown in reading order; each section has the source's name for it (a file of an EPUB, a section of an FB2 document) and may contain raw HTML and destinations in the source's own terms |
| Marks | An element of the source that a link may lead to is marked in the Markdown of its section with an anchor definition in front of its block, named by the identifier it has in the source |
| Pictures | For each source name: the picture as the source has it |
| Cover | The source name of the picture that is the cover |
| Outline | Optional: level, title and a destination in the source's own terms |
| Landmarks | Optional: a kind of RFC 0001, a title and a destination in the source's own terms |
| Warnings | What the front end itself could not keep |
A front end must not build chapters, paths or tables itself.
Assembling the book
The steps below are the conversion rules of this crate. They do not depend on the source format.
Chapters and paths
- One section becomes one chapter. A front end chooses its sections so that each starts at a top-level division of the source (Rules per format).
- A chapter above 256 KiB must be split, as RFC 0001 recommends: at its top-level headings first, then at the paragraph boundary nearest to the limit.
- A section without text and without a picture produces no chapter.
- Chapters are named
ch0001.md,ch0002.md, … in reading order. Pictures are namedimg/0001.avif,img/0002.avif, … in the order of their first use, and the coverimg/cover.avif.
Markdown
Every chapter is parsed with markdown 1.0.0, configured for the
dialect as in mbook, and changed at the
positions the parser reports:
| Found | Becomes | Warning |
|---|---|---|
Inline <br> | A hard line break, written \ and a line feed | No |
| Any other raw inline HTML tag | Nothing; the text between the tags stays | MarkupDropped, once per tag name |
| An HTML block | Nothing | MarkupDropped |
| A picture whose source name the draft knows | A picture with the new path | No |
| A picture the draft does not have, cannot decode, or that names a network address | Its alternative text | PictureDropped |
A link with scheme http, https or mailto | Unchanged | No |
| A link with any other scheme | Its text | LinkDropped |
| A link into the book | See Links and footnotes | |
| A character below U+0020 other than line feed and tab | Nothing | No |
Text is normalised to Unicode NFC.
Links and footnotes
Source formats link to any element. mbook names a heading by itself and any other line through an anchor definition in front of it (ADR-0009), so the target of a link is kept to the line.
| Target in the source | Destination after conversion | Warning |
|---|---|---|
| A file, a section or a page | The chapter that starts there | No |
| A heading | That heading: the chapter's path and the anchor mbook computed | No |
| Any other block: a paragraph, a figure, a list item, a block quote, a table | That block, named by an anchor definition in front of it | No |
| An element inside a block, such as a word of a paragraph or a row of a table | The block that contains it, named the same way | No |
| Nothing that was converted | The link becomes its text | LinkDropped |
- A front end marks every element that has an identifier. The assembler
keeps a mark only when a link of the book, or an entry of the contents,
leads to it, and removes the others.
mbookfinds the definitions that are kept and fills the anchor table of the chapter; the converter handles no byte offsets. - The name is the identifier of the source, with everything but letters,
digits,
-,_and.replaced by-. When the chapter already has an anchor with that name, of a heading for example,-2,-3, … is appended; every link is rewritten anyway, so a name need not survive. - When an identifier is used twice in a section, the first element that carries it is the target.
- Links are re-targeted after every chapter has its final text: the anchor of a heading is known only then.
- A link that the source marks as a note reference (
epub:type="noteref"in EPUB,<a type="note">in FB2) becomes a footnote:[^n]at the reference and[^n]: textat the end of the same chapter, as RFC 0001 requires. The text of the note is copied into every chapter that refers to it and is removed from where it stood.
Pictures
| Source picture | Stored as |
|---|---|
An AVIF file that Book::add_picture accepts | The same bytes |
| JPEG, PNG, GIF, WebP, BMP | Decoded, turned upright by its orientation tag, encoded as AVIF |
| An animated GIF or WebP | Its first frame, encoded the same way |
| Anything else (SVG, JPEG 2000, TIFF, WMF) | Not stored; see Markdown |
- A picture is stored once, however often it is used. Two source names with the same bytes share one resource.
- A picture that no chapter shows and that is not the cover is not stored.
- Before decoding, the pixel count declared by the picture must be
compared with
ConvertLimits::max_picture_pixels. - Encoding uses
PictureOptions::qualityandPictureOptions::speed. - Without the
rayonfeature, a picture is encoded when a chapter first shows it. With it, the cover and every picture a chapter shows are encoded before the chapters are rewritten, on all cores of therayonpool thatrav1eencodes on as well; the chapters then take the finished files. The pictures go in runs whose declared pixels add up to at most 32,000,000, so that memory stays close to that of one large picture; a picture with more is encoded alone. Paths are given in the order of first use either way, and the files are the same.
Metadata
Values come from the front end and are passed to the setters of
Meta. A value that a setter refuses is
dropped with a MetadataDropped warning; it does not fail the conversion.
| Key | Rule |
|---|---|
title | The source's title; otherwise the text of the first top-level heading; otherwise Untitled, with a MetadataMissing warning |
lang | The source's language tags; otherwise und, with a MetadataMissing warning |
id | The source's identifier: a UUID becomes urn:uuid: and the UUID in lower case, anything else is kept. Without one: a UUID version 5 computed from the source bytes, so that converting the same file twice gives the same id |
date | Shortened to YYYY, YYYY-MM or YYYY-MM-DD |
isbn | Digits only; an identifier of the source that is a valid ISBN also fills this key |
annotation | Plain text: markup is removed and paragraphs are separated by an empty line |
cover | Set by Book::set_cover when the source names a cover picture that could be stored |
Where each key comes from:
| Key | EPUB | FB2 | CBZ (ComicInfo.xml) | DOCX | HTML | |
|---|---|---|---|---|---|---|
title | dc:title | book-title | Title | Title | Title | title |
lang | dc:language | lang | LanguageISO | dc:language | lang of html | |
id | The unique dc:identifier | document-info/id | ||||
author | dc:creator | title-info/author | Author | Writer | Creator | meta author |
translator | dc:contributor with role trl | translator | Translator | |||
series, series-index | belongs-to-collection and group-position, or calibre:series | sequence | Series, Number | |||
publisher | dc:publisher | publish-info/publisher | Publisher | |||
date | dc:date | publish-info/year, otherwise title-info/date | Year, Month, Day | |||
isbn | An identifier that is an ISBN | publish-info/isbn | ||||
genre | dc:subject | genre | Keywords | Genre | Keywords | meta keywords |
annotation | dc:description | annotation | Subject | Summary | Subject and description | meta description |
cover | The manifest's cover image | coverpage | The first page of a scan | The first page |
Markdown and plain text carry no metadata that is read.
A cell is filled only as far as the front-end crate exposes the field.
Contents
- With an outline in the draft, the contents are
Toc::Explicit: one item per outline entry. An entry leads to a chapter or to a heading, because a contents item cannot name an extra anchor (mbook, Extra anchors): an entry whose target is another element leads to the nearest heading above it, or to the start of its chapter, with aLinkRetargetedwarning. - An entry whose target was not converted is left out with a
LinkDroppedwarning. - Without one, the contents are
Toc::FromHeadings.
Landmarks
A landmark of the draft becomes one of the book.
- Its destination is re-targeted like a link, to the line: a landmark may lead to an extra anchor, so nothing is moved to a heading.
- A landmark whose target was not converted is left out with a
LinkDroppedwarning, and so is a secondstart.
Only EPUB has landmarks of its own: the landmarks navigation of EPUB 3,
otherwise the guide of EPUB 2. Their types are mapped to the kinds of
RFC 0001 (bodymatter becomes start, loi becomes list-of-figures,
copyright-page becomes copyright, and so on). Three sorts of entry
produce no landmark: the cover, which is a picture in mbook; a table of
contents set in the text (toc), which the contents of the book replace;
and types without a counterpart.
The final check
The assembled book must pass Book::check before it is returned or
written. A failure is reported as Error::Book and means a defect of this
crate, not of the source.
Rules per format
| Format | Sections | Outline | Notes |
|---|---|---|---|
| EPUB | One per spine item, in spine order | The navigation document, otherwise the NCX | A page that only shows the cover picture is skipped. A picture in the spine is a figure. The landmarks of the book are carried over. |
| FB2 | One per top-level section of the main body; what stands between them gets sections of its own | None; headings are used | See the table below. The main body is the first one not named notes or comments. |
| One per first-level entry of the document outline, rendered from its pages; otherwise cut at top-level headings | The document outline | Markdown is rendered by unpdf with Markdown tables, without front matter and page markers. A document without a text layer becomes one section in which every page is a figure, rendered at 150 dpi or less. | |
| CBZ | One per folder of the archive, headed by the name of the folder; one for an archive without folders | None; headings are used | Entries in natural order of their names; every page is a figure, and the first page is the cover. ComicInfo.xml fills the metadata. |
| DOCX | Cut at top-level headings | None; headings are used | Markdown is rendered by undoc. A numbered or bulleted paragraph is an item of a list, and an item of a deeper level of Word is nested in the item before it. A footnote is moved into the section that refers to it. |
| HTML | Cut at top-level headings | None; headings are used | The encoding is taken from a byte order mark, from the document, or guessed. Only pictures given as data: addresses can be stored. |
| Markdown | Cut at top-level headings | None; headings are used | The encoding is detected. Every heading is marked with the name GitHub derives from it, so that [see](#the-heading) keeps working across chapters. A metadata block at the start (front matter) is removed with MarkupDropped. Pictures cannot be found from a stream and become their alternative text. |
| Text | One | None | The encoding is detected; paragraphs are separated by empty lines; Markdown punctuation is escaped. |
HTML, and the HTML inside an EPUB, is converted the same way:
script, style, forms and embedded objects are dropped; sub, sup and
u keep their text and are reported once as MarkupDropped; a table with
merged cells is flattened and reported; every element with an id is marked;
a note reference of EPUB (epub:type="noteref") whose note is in the same
document becomes a footnote.
FictionBook is converted element by element by this crate:
| FB2 | Markdown |
|---|---|
title of a section at depth n | A heading of level n, at most 6 |
subtitle | A heading one level below its section's |
p | A paragraph |
emphasis, strong, strikethrough, code | The matching inline markup |
sub, sup, style | The text alone, with MarkupDropped |
epigraph, cite, the annotation of a section | A block quote; text-author is its last paragraph |
poem | One paragraph per stanza, with a hard line break after every v; its title is a bold line |
empty-line | A paragraph boundary |
table | A table; merged cells are split, with MarkupDropped |
image | A picture; alone in a paragraph, it is a figure |
a | A link, or a footnote when its type is note or its target is in the notes body |
body named notes or comments | The source of footnote texts; it produces no section |
binary | A picture |
| An element the format does not define | Its text |
A source that is protected, with a password or by rights management, fails
with Error::Protected for every format. A source with no text and no
picture that could be stored fails with Error::Empty.
What is implemented
Every format of Formats and features is implemented and tested against sources built in memory by its tests. What each front end does not do:
| Format | Limits of the front end |
|---|---|
| EPUB | XHTML in an encoding other than UTF-8 and UTF-16 is read as UTF-8. A plain-text description loses its paragraph breaks, because rbook joins its lines. A note in another file than its reference stays a link. An archive entry declared larger than the resource limit refuses the book, even an entry the book does not use. |
| FB2 | A table keeps no alignment. The style and lang attributes are ignored. The document is decoded as a whole before it is parsed. Elements nested deeper than 256 levels are refused with Error::Limit. |
Headings are what unpdf finds: per page, by font size, at most four levels. A picture stands at the end of its page, not where it is drawn, and one narrower or lower than 64 pixels is left out. An outline entry with a named destination has no page and joins the entry before it. A scanned document has no contents. Every page of a scan is held as pixels until the book is assembled. Whether unpdf escapes a lone ~ was not verified. | |
| CBZ | ComicInfo.xml is read in UTF-8 only; of its fields the title, series, number, writer, translator, publisher, date, language, genre and summary are used. |
| DOCX | A link to a bookmark of the document becomes its text: undoc does not read bookmarks. A heading is found only when its style has an outline level. A note is plain text. Letters and Roman numerals of a list become decimal numbers. A paragraph with text between two items ends their list, so the item after it starts a new one, at its own number; an empty paragraph does not. An item more than one level deeper than the item before it is nested one level. Underline, superscript and subscript reach the assembler as raw HTML and are removed with MarkupDropped. The language is read from the core properties only. undoc unpacks entries under its own bound, 100 times their packed size, not under the limits of this crate. |
| HTML | A form and what it contains is dropped. CDATA sections of XHTML are not read. A document nested deeper than 128 levels becomes one paragraph of text, with MarkupDropped: htmd walks the tree recursively. An element with a name HTML does not define cannot be a link target. |
| Markdown | Front matter is removed, not read. Pictures are dropped: a stream has no folder to find them in. |
| Text | No structure is recognised: no headings, no lists. |
The assembler implements every rule of Assembling the book.
Security considerations
- A source is untrusted input to this crate, to its front-end crate and
to the picture decoders. The converter has no
unsafecode of its own; its dependencies are not covered by that statement. - Limits cover what the converter allocates: the buffered source, unpacked entries, decoded pictures and the book. Memory that a front-end crate allocates while it parses is bounded only through the size of the source handed to it.
- Archives. An entry is unpacked only up to its limit, whatever size its header declares.
- Nothing is fetched. Network addresses in a source are never opened.
- No path of the source reaches the book. Chapters and pictures get generated names, so a hostile entry name cannot become a resource path.
- No active content survives. Scripts and styles are dropped with the raw HTML, and the final check rejects a book that still contains any.
Design
Which decisions are confirmed, which crates read each format, what the design costs, and the choices behind it.
What is settled
The format author settled the points below on 2026-11-21. Every other detail of this section is proposed and listed again under Settled and open questions where a choice is open.
| Decision | Status |
|---|---|
| The crate converts EPUB, FB2, PDF, CBZ, DOCX, HTML, Markdown and plain text into mbook | Confirmed |
| Mobipocket is not converted until a maintained crate reads it | Confirmed |
| One Cargo feature per import format; every import format enabled by default | Confirmed |
| Conversion from an I/O source and from a byte slice | Confirmed |
Formats are read by established crates such as unpdf | Confirmed |
Pictures are encoded as AVIF by image with its avif feature, which uses ravif and rav1e; dependencies under BSD licenses are accepted | Confirmed |
| A link to an element that is not a heading keeps its target: the converter writes an anchor definition in front of it (ADR-0008, ADR-0009) | Confirmed |
A source without an identifier gets a UUID version 5 computed from its bytes as id | Confirmed |
A source without a title or a language gets Untitled and und, each with a warning | Confirmed |
| A PDF without a text layer is converted page by page into pictures | Confirmed |
| A comic archive has one chapter per folder | Confirmed |
Two kinds of source, Read and a slice; no entry point for Read + Seek | Confirmed |
| Pictures are encoded with quality 80 and speed 6 unless the options say otherwise | Confirmed |
Encoding the pictures in parallel is behind the opt-in rayon feature | Confirmed on 2026-11-24 |
| A contents entry of the source that does not lead to a heading leads to the nearest heading above its target | Confirmed |
| The landmarks of a source become landmarks of the book (ADR-0010) | Confirmed |
Streaming means a Read as the source and a Write as the sink; the book is held in memory while it is converted (Sources and memory) | Confirmed |
Dependencies
Every dependency was checked on 2026-11-21 against crates.io and its repository, and those of figures on 2026-11-22: the version in use is the latest one unless the notes say otherwise, and the column "Last release" shows how alive the crate is.
| Need | Crate | License | Last release | Notes |
|---|---|---|---|---|
| PDF to Markdown, pictures, outline, pages as pictures | unpdf 0.55, without default features, with raster | MIT | 2026-11 | Headings are found per page, by font size. Pictures are listed per page, not where they are drawn, and those under 64 pixels are left out. |
| EPUB package, spine, navigation, resources | rbook 0.7, without default features | Apache-2.0 | 2026-11 | Reads EPUB only; Mobipocket and KF8 are announced. |
| HTML to Markdown (EPUB, HTML) | htmd 0.6 | Apache-2.0 | 2026-11 | Writes the Markdown, with its own escaping; see below. |
XML events (FictionBook, ComicInfo.xml) | quick-xml 0.42 with encoding | MIT | 2026-08 | |
| Word to Markdown | undoc 0.28, with docx only | MIT | 2026-11 | Headings need an outline level in their style. Bookmarks are not read, so links inside a document become text. Notes are plain text. A nested item is indented by two spaces a level, whatever the marker of its parent; see "Nested items of a Word list" below. Only w:start of a numbering is read, not an override of it. |
| ZIP archives | zip 9 | MIT | 2026-11 | |
| Dialect parsing with byte offsets | markdown 1.0.0 | MIT | 2025-04 | Already used by mbook. |
| Picture decoding and AVIF encoding | image 0.25 with avif, which encodes through ravif 0.13 and rav1e 0.8 | MIT OR Apache-2.0; BSD-3-Clause; BSD-2-Clause | 2026-03 | |
Encoding pictures in parallel (rayon) | rayon 1.10 | MIT OR Apache-2.0 | 2026-11 | Already in the tree: image, ravif and rav1e encode a picture on its pool. |
Base64 (pictures of FictionBook and of data: addresses) | base64 0.23 | MIT OR Apache-2.0 | 2026-08 | |
| Names of headings by GitHub's rule (Markdown) | github-slugger 0.1 | MIT | 2023-06 | One release; a port of a frozen algorithm. Already used by mbook. |
| The order of the pages of a comic | alphanumeric-sort 1.5 | MIT | 2026-07 | |
| Unicode NFC | unicode-normalization 0.1 | MIT OR Apache-2.0 | 2026-10 | |
| Text encodings | encoding_rs 0.8, chardetng 1 | Apache-2.0 OR MIT | 2026-10, 2026-03 | |
| Name-based UUID | uuid 1 with v5 | Apache-2.0 OR MIT | 2026-11 | Already in the workspace. |
| Error types | thiserror 2 | MIT OR Apache-2.0 | 2026-09 | Already in the workspace. |
Mermaid diagrams as SVG (export) | merman 0.11, without default features, with all-diagrams, svg and layout-cytoscape | MIT OR Apache-2.0 | 2026-11 | Without ELK, whose layout is EPL-2.0, and without math in labels. Moved from mbook-ui on 2026-11-22. |
KaTeX formulas as SVG (export) | ratex-parser, ratex-layout, ratex-types, ratex-svg with embed-fonts, ratex-font, ratex-unicode-font 0.1 | MIT | 2026-11 | Glyphs as outlines. Moved from mbook-ui. |
Glyph metrics of system fonts; the configuration of merman and the walk over a parsed formula (export) | ab_glyph 0.2, serde_json 1 | Apache-2.0; MIT OR Apache-2.0 | 2025-09, 2026-10 | Moved from mbook-ui. |
Rasterising a drawn figure for the writers (export) | resvg 0.46 with text, system-fonts and memmap-fonts | Apache-2.0 OR MIT | 2026-11 | 0.50 is the latest release; 0.46 is the version GPUI depends on, so the application keeps one copy of resvg, usvg and fontdb. Without raster-images: a drawn figure holds no pictures. |
The format author accepted dependencies under BSD-2-Clause and BSD-3-Clause
on 2026-11-21: they ask only that the license text is kept. image itself
contains no AV1 encoder, so its avif feature cannot be had without ravif
and rav1e.
One mechanism is written in this crate: escaping text as Markdown, about
forty lines in markdown.rs, used where a front end writes Markdown itself
(FictionBook, plain text, comic archives). What must be escaped is a rule of
the mbook dialect, not of Markdown in general: a single tilde marks
strikethrough, and the parser that decides is markdown 1.0.0. The function
is tested against that parser. comrak and pulldown-cmark-to-cmark write
Markdown for their own parsers and dialects, and would add a second Markdown
implementation to the dependency tree.
HTML is written as Markdown by htmd, including its escaping, which was
checked against the dialect: a lone tilde, emphasis marks, the starts of
headings, lists and quotes, brackets and literal tags all come back as text.
xhtml.rs adds what Markdown output would otherwise lose, as handlers of
htmd and as edits of the Markdown it wrote:
| Added here | Why htmd alone is not enough |
|---|---|
script, style, forms and embedded objects are skipped | Their content would be written as text. |
s, strike, del as ~~…~~ | Written as plain text. |
Marks for elements with an id | Identifiers are dropped. |
| Footnotes of EPUB | Not recognised. |
| A caption of a figure as the title of its picture | Written as a separate paragraph. |
| A table without a header row | Written as paragraphs; here its first row becomes the header. |
pre without code, and pictures inside svg | Not handled. |
MarkupDropped for sub, sup, u and merged cells | Dropped silently. |
| A line break inside a heading or a cell becomes a space | It would break the heading or the row. |
Two properties of htmd shape that code. A handler is registered for a list
of element names, there is no handler for every element, so the same handler
is registered for about a hundred names, and an element with a name outside
that list cannot be marked. And a handler must be 'static, so it cannot
call the mappings of links and pictures that a front end supplies: handlers
leave the addresses as they are, and the mappings are applied afterwards, to
the Markdown, by the same code that the assembler uses.
Mobipocket is not converted (decided by the format author on
2026-11-21). A front end was written on mobi 0.8 and removed again. The
crate has had no release since 2022 and depends on the unmaintained
encoding 0.2. Writing against it showed more: its record access slices
without checking and panics on a damaged file, its text accessor drops the
last text record, and its PalmDOC decompressor shortens a match that is
longer than its distance, which shifts every byte offset after it. Only its
header parser could be used; cutting the records and unpacking the text had
to be written here, which is a parser of a binary format in all but name.
No other crate with a permissive license reads the format: boko is under
the GPL, and rbook has only announced it.
The structure of FictionBook is read by this crate, as events of
quick-xml (decided by the format author on 2026-11-21). The fb2 crate was
used first and dropped: it has had no release since 2023, pins quick-xml
0.30, fails on a whole document for a series number such as 1.5 or for an
empty body, and loses the order between the text of a section and its
subsections.
Crates that were looked at and ruled out:
| Crate | Why it does not fit |
|---|---|
fb2 0.4 | Unmaintained since 2023; the defects above. |
mobi 0.8 | Unmaintained since 2022; the defects above. |
palmdoc-compression 0.3 | Would replace one of the three parts mobi gets wrong; last release 2024, about 200 recent downloads. Not evaluated. |
natord 1 | No release since 2015; replaced by alphanumeric-sort. |
ebook-rs 0.19 | Reads FictionBook, Mobipocket and KF8, but is three months old with 66 releases, cannot switch formats off, and always brings aes, regex, whatlang, serde_json and parking_lot. Its source was not read. |
epub 2.1 | GPL-3.0-or-later. |
html2md 0.2 | GPL-3.0-or-later. |
boko 0.6 | GPL-3.0-or-later, and needs Rust 1.91. |
html-to-markdown-rs 3 | Needs Rust 1.99. |
kreuzberg 4, hayro 0.9 | Need Rust 1.91 and 1.92. |
mdka 3.3 | No hook to rewrite a link or a picture; writes raw <a id> and <br>. |
anytomd 1.3 | No EPUB, FB2 or PDF; no hook for links; brings an HTTP client by default. |
pdf-extract, lopdf | Plain text without headings, tables or an outline; unpdf gives all three. |
Drawbacks
- Memory is the size of the book, not of a window. The whole
Bookexists before the first byte is written, and for most formats the source is held as well. - AVIF encoding dominates the time. The pure-Rust encoder needs seconds
for a large page; a comic of several hundred pages takes minutes. The
rayonfeature spreads the pictures over the cores; a small picture alone keeps only a few of them busy. - The dependency tree is large with default features: an AV1 encoder,
an HTML parser, two versions of
quick-xml, a PDF parser. - The quality of a conversion is the quality of the front-end crate. A
PDF has no chapters or paragraphs of its own; what
unpdfreconstructs is what the book contains. - A link is kept to the block, not to the word. A link to an element inside a paragraph leads to the start of that paragraph, a link to a row of a table to the table, and a contents entry that does not name a heading to the heading above its target.
- One build per feature. The completion checks of the repository run Clippy, the tests and the documentation once for every format alone.
- Four entry points for one operation, because Rust cannot choose
between a
Readand a slice by itself.
Rationale and alternatives
| Decision | Chosen | Rejected | Why |
|---|---|---|---|
| Where formats are parsed | An established crate per format | Parsers of this crate over zip and quick-xml | Decided by the format author. Less code to keep correct; the cost is memory and a larger tree. |
| What a front end returns | A draft in the source's terms; one assembler | Each front end builds a Book | Paths, links, the dialect and pictures would be implemented once per format. |
| Result of a conversion | A Book, then Book::write | A writer that emits resources while the source is read | Decided by the format author: a Read in and a Write out is enough. The tables are the first resources of a file and describe everything after them; mbook writes only from a Book. |
| Sources | Read and &[u8] | Paths | A caller opens a file in one line; a stream has no path. |
One entry point over a Source enum | &[u8] is itself a Read, so a conversion from both cannot be chosen by a trait. | ||
| Sources that could seek | Buffered like any Read | A third entry point for Read + Seek | Decided by the format author: the API stays at two kinds of source. A caller that minds the copy maps the file into memory and passes the slice. |
| Finding the format | From the content | From a file extension | Streams have no names, and extensions are wrong often enough. |
| A disabled format | The variant stays; Error::FormatDisabled | Variants behind cfg | A match on Format would change with the feature set, and the error could not say what is missing. |
| Pictures | Encoded by this crate | An encoder supplied by the caller | Works without setup. A trait for other encoders can be added without breaking the API. |
| AVIF encoder | rav1e, through ravif and the avif feature of image; pure Rust | libavif or libaom | Decided by the format author. No C toolchain, and one crate both decodes the source pictures and encodes the result; slower than the C encoders, which are under BSD licenses as well. |
| Constructs that cannot be kept | Dropped with a warning | An error | A book without one table is more useful than no book. |
| Links to elements that are not headings | Kept, as anchor definitions in the target chapter | Sent to the nearest heading | Decided by the format author, who changed the format for it (ADR-0008, ADR-0009). |
| Missing title or language | A stand-in value and a warning | An error | The caller can correct a Book; it cannot correct a failed conversion. |
| Final validation | Book::check of mbook | Checks of this crate | One definition of a valid book. |
| Export input | A borrowed Book | A second set of stream and slice entry points | A caller can export an edited in-memory book. Book::open or Book::read can load a saved one. |
| Export writers | epub-builder, docx-rs, krilla, xmlwriter and the Markdown serializers of pulldown-cmark and pulldown-cmark-to-cmark | Hand-built ZIP and PDF document packages or shelling out to a converter | The libraries handle the formats and work without an installed converter. |
| Nested items of a Word list | Before undoc renders the document, the level of every item in its model is set to the one whose two spaces a level reach the text of the parent item: one more level under - , two under 1. or 10. | Reindenting the Markdown undoc renders; rendering the lists without undoc; leaving it to undoc | CommonMark nests an item only when it is indented as far as the text of its parent, and undoc indents two spaces a level, which is enough under a bullet only, so an item under a number joined the list of its parent and a bullet under a number split that list in three. In the rendered text an item cannot be told from a line of text that starts with spaces, and rendering lists here would repeat the escaping and the runs of undoc. The model is public and the level is used only for the indent. The cost is a dependence on the two spaces a level of undoc 0.28, which the tests of the importer check. |
| Lists in an exported Word document | Word numbering: one abstract numbering for each list of the book, with its start in the level of the list, and every paragraph of an item a paragraph of its own | Paragraphs with the marker as text; one numbering for all lists, restarted with an override of the level | With the marker as text an item had no indent, a tight nested list ran into the paragraph of its parent, and a document read back had text where the lists were. Word continues counting across the numberings of one abstract numbering unless it is overridden, and undoc does not read the override, so a list that starts at 3 would come back from 1. One numbering for each list costs a few hundred bytes of numbering.xml per list. |
| Landmarks in an EPUB | The writer replaces the landmarks navigation and adds to the guide in the archive epub-builder generated, rewriting those two documents with zip and copying every other entry as it is | The reftype of epub-builder; writing the EPUB package without epub-builder | A reftype belongs to a whole document of the spine and takes one of 17 fixed types, so the anchor of a landmark, a second landmark of one chapter and six kinds would be lost, and epub-builder does not make its archive trait public to change the files it writes. Writing the package by hand would replace the library for one table. The cost is a second pass over the archive in memory and a dependence on the paths and the <guide> that epub-builder 0.8 writes, which the tests of the writer check. |
| CBZ pages | Rasterize the paginated edition with unpdf | Export only embedded pictures | A text-only book also produces readable pages. |
| Encoding pictures in parallel | Behind the opt-in rayon feature: the pictures the chapters show are found first, encoded on the rayon pool in runs of at most 32,000,000 declared pixels, and stored in the order of first use | Always in parallel; encoding as each chapter shows a picture, as without the feature; std::thread::scope | Decided by the format author to put it behind a feature. Measured on a 7 MB EPUB with 45 pictures (25.5 megapixels in all, the largest 1.9) on an Apple M-series processor with the NEON assembly of rav1e: 3.9 s before, 2.6 s with it on eight threads, 5.6 s and 4.3 s on four; the bytes are the same. rav1e already works on the pool of rayon, so one pool shares the cores between pictures and within one; threads of their own would compete with it. The budget keeps the memory of a run near that of one picture at the limit of max_picture_pixels; it is a constant, not an option, and was chosen without a measurement of memory. The price is a second walk over each chapter to find its pictures. |
| Export feature | One opt-in feature for all writers | An export switch for each format or writing enabled by default | One dependency setting enables every output while the import-only build keeps its dependency set and minimum Rust version. |
| Export picture decoding | avif-decode 3 on rav1d | image with avif-native or avif-decode 1 with libaom | The feature shares the decoder with the application. avif-native links to system dav1d, and the older decoder builds libaom with CMake. |
| Diagrams and formulas in an export | Drawn as SVG and written as PNG pictures | Their alternative text, the earlier behaviour; SVG pictures; Mermaid fences and $…$ in Markdown | Decided by the format author on 2026-11-22: figures go out as pictures. FictionBook and many Word and EPUB readers show no SVG, and an SVG diagram depends on the fonts of the reader for its labels; PNG looks the same everywhere. |
| Where figures are drawn | The public figure module of this crate, used by export and by mbook-ui | A private copy for export beside the one of mbook-ui; a crate of its own | Decided by the format author on 2026-11-22. One renderer, so an export looks like the reader; the cost is four public items under export. A crate of its own would be published and versioned for two users. |
| A figure that cannot be drawn | Its alternative text, and the export goes on | An export error | RFC 0001 lets a reader show the alternative text; a book with one broken formula is still worth exporting. A picture that cannot be decoded still fails the export, as before. |
| The size of a figure in an export | Scaled to the body text of the output, drawn at two pixels per unit | The pixels of the drawing as they are | A formula drawn for 20-pixel text would stand out of a 16-pixel line, and a single pixel per unit blurs on a dense screen. |
Prior art
| Tool | Taken from it | Left behind |
|---|---|---|
Calibre ebook-convert | Input plugins that produce one intermediate book; one output stage | An intermediate of XHTML and CSS |
| Pandoc | Readers, one document model, writers | A model that covers every construct of every format |
unpdf, undoc, MarkItDown | Markdown as the result of extraction; pictures as separate resources | Raw HTML as a fallback |
mbook | open-like entry points, Limits, non-exhaustive options and errors |
Settled and open questions
The questions of the first draft were settled by the format author on 2026-11-21; see What is settled. Two were settled by the implementation:
| Question | Outcome |
|---|---|
| Which crate writes Markdown for FB2 and text? | None: escaping is a function of this crate, tested against markdown 1.0.0 (Dependencies). |
How does this crate keep its markdown configuration equal to that of mbook? | Both call markdown::ParseOptions::gfm(), and every converted book passes Book::check, which parses each chapter with the configuration of mbook. |
Still proposed: the names of the public items, and every front-end crate marked so in Formats and features.
Future possibilities
- Conversion in bounded memory: a writer in
mbookthat spools encoded resources to a temporary file and writes the tables last, fed by front ends that emit sections as they parse. - Progress and cancellation, for the minutes a large comic takes.
- A caller-supplied picture encoder, for hardware or C encoders.
- More formats when a suitable crate exists: Mobipocket and KF8/AZW3
(announced for
rbook, which already reads EPUB here), DjVu, RTF, CBR. - SVG and JPEG 2000 pictures, rendered or decoded before encoding.
- A strict mode that turns chosen warnings into errors.
- Metadata from the front matter of a Markdown document, and pictures
given to a Markdown or HTML document as
data:addresses or by a caller. - A command-line tool on top of this crate and
mbook.
mbook-ui
| Package | mbook-ui, the application called mbook; not published to crates.io |
| Installers | GitHub Releases: macOS on arm64 and x86-64, Windows on x86-64, Android on arm64 |
| Source | crates/mbook-ui; the Android shell in crates/mbook-android |
| Builds on | mbook; mbook-converter |
| Minimum Rust | 1.100 |
| Status | A first version; see Status and verification |
mbook-ui is a reading application built on mbook and mbook-converter.
It has three screens:
| Screen | What it does | Built on |
|---|---|---|
| Library | Shows the books the application keeps, as covers | The catalogue; BookReader::open and read_cover |
| Reader | Shows a reflowable chapter with scrolling or pagination | BookReader, read lazily |
| Editor | Changes the metadata, chapters, landmarks and pictures of a book | Book, in memory |
Opening a file that is not yet in the library adds it: an mbook file is
copied, a file in any format that
mbook-converter reads is
converted first. Everything that
reads a file runs on the background executor of GPUI; what decodes, parses,
converts or encodes runs on a pool of rayon with half the threads of the
system, which the executor awaits. The main thread only draws and reacts.
The interface is built with GPUI Kit: on the GPUI Fast engine on the desktop, and on gpui-pre with the platform of gpui-mobile on Android. Window width selects the compact, medium or expanded layout. The application has shells for the desktop and for Android (Android); there is no iOS shell.
A first version exists. What is implemented says what it does, where it differs from these pages, and what has not been tried outside of tests.
cargo run -p mbook-ui
The AVIF decoder needs NASM at build time on x86 and x86-64.
| Page | What it answers |
|---|---|
| Using the application | What do the library, the reader, the editor and the settings do? |
| Architecture | Where does each piece of work run, what is stored where, and how do import, reading, editing and updates work? |
| Appearance and accessibility | Which colours, type and motion does the interface use, and what does it promise to assistive technology? |
| Android | How is the APK built and released, and where does the Android application differ from the desktop? |
| Status and verification | What exists today, where does it fall short, and how was it checked? |
| Design | Which decisions are confirmed, which crates are used, what does the design cost, and why does it look this way? |
The three screens
flowchart LR
file["A file:<br/>mbook, EPUB, FB2,<br/>PDF, CBZ, DOCX, …"] -- "open, drop" --> imp["Import"]
imp -- "copy or convert" --> lib["Library"]
lib -- "open" --> reader["Reader<br/>BookReader, lazy"]
lib -- "edit" --> editor["Editor<br/>Book, in memory"]
reader -- "edit this book" --> editor
editor -- "save" --> lib
The model is Apple Books for the Mac: a quiet library where the covers carry the colour, and a reader whose controls step aside. What is taken from it and what is left out is listed under Prior art.
What it is for
The repository has a format, a library and a converter, and no way to look at
a book. A reader is also the first real consumer of BookReader: the claims
of RFC 0001 (a book opens without being read in full;
only what is on screen is decoded) are only shown to hold by an application
that depends on them.
| Task | Screen |
|---|---|
| Keep books in one place and find one | Library |
| Open an EPUB, FB2 or PDF without thinking about formats | Library, through import |
| Read, and come back to the same place | Reader |
| Correct a title, a cover or a typo after a conversion | Editor |
Goals
| Goal | How the design meets it |
|---|---|
| The interface never waits for a book | No call that touches a file or parses runs on the main thread (Threads). |
| One code base for desktop and mobile | Layout depends on a size class of the window; platform code stays in a thin shell (Layout). |
| The library survives its index | The mbook files hold the metadata; the catalogue can be rebuilt from them (The catalogue). |
| A failed import or save loses nothing | A file enters the library, and replaces a book, only by a rename (Import, Editing). |
| Little own code | Components, the Markdown view, the text editor, dialogs and lists come from GPUI Kit; paths, updates and the store from established crates. |
| What is read is what was edited | The editor's preview and the reader are the same view with the same style. |
| Usable without sight, without a pointer and without fine motor control | Every screen meets WCAG 2.2 at level AA where it applies to an application (Accessibility). |
Non-goals
- A store, an account or synchronisation. The library is a folder on one device.
- Two-page spreads. See Future possibilities.
- Annotations: highlights, notes and bookmarks.
- A streaming editor.
mbookhas none; a book is edited as a wholeBook. - An iOS shell. The design keeps it possible; the application ships for the desktop and for Android.
Using the application
What a person sees and does on each screen. How the screens are built is on Architecture.
Size classes
The layout follows the width of the window. A narrow desktop window gets the phone layout, and a tablet in landscape gets the desktop one.
| Class | Window width | Navigation | Typical device |
|---|---|---|---|
| Compact | below 600 px | A stack of screens; a bar at the bottom | Phone; a narrow window |
| Medium | 600 to 959 px | A stack; panels slide over the content | Tablet in portrait; half a screen |
| Expanded | 960 px and more | A sidebar beside the content; panels dock | Desktop; tablet in landscape |
Library
Expanded
+----------------+----------------------------------------------------------+
| [ Search ] | Continue reading |
| | +------+ The Master and Margarita |
| Library | |cover | Mikhail Bulgakov |
| [L] All books | | | Chapter 7, 38% [ Read ] |
| [B] Reading | +------+ |
| [✓] Finished | -------------------------------------------------------- |
| | All books [Sort] [+] |
| | +-----+ +-----+ +-----+ +-----+ +-----+ +-----+ |
| | | | | | | | | | | | | | |
| | | | | | | | | | | ... | | | |
| | +-----+ +-----+ +-----+ +-----+ +-----+ +-----+ |
| | 38% … NEW … 72% … Converting |
| [ Import ^2 ] | |
+----------------+----------------------------------------------------------+
Compact
+---------------------------+
| Library [+] |
| [ Search ] |
| +-----+ +-----+ +-----+ |
| | | | | | | |
| +-----+ +-----+ +-----+ |
| 38% … NEW … 72% … |
| +-----+ +-----+ +-----+ |
| | | | | | | |
+---------------------------+
| Reading Library Search |
+---------------------------+
- The sidebar uses icons for All books, Reading and Finished. The sort icon opens a menu with the current order marked.
- A cover keeps its own proportions; covers are aligned at the bottom of a row, as on a shelf. A book without a cover gets one drawn from its title.
- Under a cover: the percentage read,
Finished, or aNEWbadge. A neutral hover highlight leaves a small inset around the cover and reading status. The ellipsis opens the book menu. - A book that is still being converted is already on the shelf, with its file name and the state of the import.
- The menu of a book (right click, the
…button, or a long press): Open, Edit, Show the file, Export, Share, Remove. - Share opens the share sheet of the system with the mbook file of the book: AirDrop, Messages and Mail on macOS, Nearby Sharing and installed apps on Windows, and the messengers and social networks installed there that accept a file. What happens next is up to the app chosen.
- Files are added with
+, by dropping them on the window, or by opening them with mbook from a file manager or another app, which offers mbook for every format it reads; one file opened this way opens its book. The system picker lists mbook and the extensions accepted by the converter. - New book… asks for a title. Confirming creates a book in the library and opens its empty first chapter in the Markdown editor. The title and language can be changed in Details.
Reader
- Read in one scrolling column. Page Up and Page Down move by a screen; Home and End move to the chapter boundaries. The footer and chapter shortcuts can advance to the next chapter, and so does a swipe to the left, with a finger or two on a trackpad; a swipe to the right goes to the previous one. Read one page at a time adds page turns and book-wide page numbers; there a swipe turns a page. A number is approximate until the reader has measured every chapter at the current typography.
- The reading slider previews the chapter and progress while seeking. It appears on hover, while in use, or on keyboard focus. Progress can be hidden from the appearance panel. While the controls are hidden, the header keeps its space, and so does the footer of one page at a time. A scrolling text runs to the bottom of the window under its footer, which stays; the text fades into the page behind its buttons and status, and scrolled to the end of a chapter, its last line stops above them. Move the pointer, tap the middle of the text, scroll back or press a key to show the controls; they also come back at the end of a chapter. A tap or a swipe on a notification is the notification's, not the text's.
- A book opened for the first time opens where its text begins, past the cover and the title page, when the book marks that place. After that it reopens where it was left.
- Contents marks the current entry. When the book marks notable places, such as its notes, glossary or index, the panel lists them first under Go to, by the name the book gives them or the name of their kind, and the entries follow under Contents. Choosing one goes there, and Escape or Return to previous passage comes back. Contents and Aa open in popovers on expanded windows and bottom sheets on smaller windows.
- Aa offers typeface, size and theme. Advanced appearance includes line height, width, paragraph spacing, heavier text, paging, motion and progress visibility. Reset appearance keeps the current reading place.
- Find in book (Command+F or Control+F) searches visible chapter text without regard to case. Matches wrap across chapters. The bar shows the chapter and excerpt. For supported Markdown spans the text is highlighted. Use the arrows, Return or Shift+Return to move between results. Closing the bar takes the reader back to the passage where they opened it.
- Click or tap a picture, a diagram or a formula that stands alone in its
paragraph to see it over the whole window. It opens fitted to the window.
Zoom in and Zoom out change its size a step at a time, as do
+and-(with or without Command or Control), a pinch, or the wheel with Command or Control held. A step stops at the size the picture has in the book and at the fitted size; Fit to window or0goes back to the fitted size. An enlarged picture is moved by dragging it or by scrolling. Escape, Close or a click beside the picture closes it. A picture inside a line of text, a picture that is a link and a reference-style picture![…][name]do not open. - Links, GFM footnote references and contents entries can be followed and revisited with Escape or Return to previous passage. A web link opens in the system browser. A book reopens at its saved chapter and source offset.
Editor
The editor speaks of a book the way its author does: chapters have a number and a title, a picture has a description, a link leads to a place. The paths of files stay visible beside the titles, because links use them, but nothing is asked for by path unless the path itself is being changed.
Expanded
+------------------+--------------------------------------------------------+
| < The Quiet Orchard Unsaved changes [ Save ] |
+------------------+--------------------------------------------------------+
| Book | 2 The harvest ch02.md Visual Source Split Preview … |
| Details +--------------------------------------------------------+
| Cover | Undo Redo | Heading 1 B I S | Link Picture Insert |
| Contents +--------------------------------------------------------+
| Pictures | The harvest |
| Landmarks | |
| Problems (2) | The apples came late that year. |
| Chapters [+ New]| |
| 1 The gate | |
| 2 The harvest | |
| 3 Notes | |
+------------------+--------------------------------------------------------+
Medium: the list slides over the content from "Book and chapters".
Compact: it opens in the chapter; the menu button beside Back slides the
same list over it. Back leaves the editor.
Finding the way. One list holds everything: the sections about the whole book under Book, then the chapters in reading order under Chapters.
- A chapter is listed by its number and the title its first heading gives it. A chapter without a heading is an Untitled chapter. A chapter with changes that are not saved says edited.
- The bar over a chapter repeats its number and title, and shows the path of its file.
Writing a chapter.
- New chapter… stands over the list of chapters, so that a long book
does not push it out of sight. It asks for a title. The chapter is added after the last
one, starts with that title as a heading of the first level, and is
opened. Its file gets the next free name of the form
chNN.md. A chapter may be added without a title. - The bar offers Visual, Source, Split and Preview, by name in an expanded or medium window and by icon in a compact one. Split is available in expanded windows. Editing opens the first chapter in Visual for both new and existing books.
- Find in chapter and the platform's Find shortcut search the open chapter, including unsaved edits. Visual selects the matching text. Source and Split search the Markdown source and select the match on the source side. Preview opens the matching block. The same navigation keys and buttons as in the reader move between matches.
- Visual edits Markdown as blocks. One toolbar holds undo and redo, the heading level and inline formatting, quotes and list indents, then what is put into the text: Link, Picture and the Insert menu with tables, code blocks, rules and lists. Code blocks offer a language picker.
- Click or Tab into a table cell to edit it. Row and column grips open controls for insertion, deletion and alignment. Tables and code blocks can move between top-level blocks by dragging their handles. Task items can be checked in the editor.
- The menu at the end of the bar (Chapter actions) moves the chapter up or down in the reading order, renames its file and removes it. Renaming and removing ask first.
- Source and the source side of Split highlight Markdown syntax. Source can edit picture alternative text and destinations, and footnote and reference definitions.
Putting a picture into a chapter. Picture opens one dialog.
- It shows the pictures of the book as thumbnails. Choosing one, describing it and confirming puts it where the caret is, with a path relative to the chapter.
- Add from your computer… takes a file instead. The file is encoded, added to the pictures of the book and put where the caret is, in one go. Dropping picture files on the chapter does the same.
- The description is what is read to someone who cannot see the picture. It may be left empty.
- Pictures in this chapter previews the pictures the chapter refers to.
Diagrams and formulas. The Diagrams and Formulas sections add, edit and remove resources. The dialog takes most of the window. In a wide window the drawing stands beside the source; in a narrow one it is under it. The source field highlights Mermaid or LaTeX syntax as you type. Choose Preview to see the result or a renderer error; a resource that is edited is drawn as its dialog opens. The drawing is fitted into the preview, a small one up to twice its size in the text. When a large one is shown smaller, Actual size shows it at its size in the text, scrolling, and Fit fits it again. Editing a source keeps its book path and the chapter references that use it. In Visual, Diagram or Formula inserts an existing resource at the caret. An empty alternative text field uses the resource kind as the description. The chapter's Preview shows the same rendering as the reader.
Linking. Link opens one dialog.
- With words selected, they become the link. With nothing selected, the dialog also asks for the words and inserts them. With the caret in a link, the dialog edits it and offers Remove the link.
- Where the link leads is typed as a web address, or chosen as a place of the book: a chapter by number and title, then its start, one of its headings or a line it names. A choice fills in the relative destination, which stays editable.
The contents. The Contents section shows what a reader is shown as the contents, and says where it comes from.
- Contents that follow the headings list every heading of every chapter. To rename an entry, its heading is changed; a new heading adds one.
- A book made from another format keeps the contents of its source as a list of its own. The section says so, and Build the contents from the headings replaces the list after a question.
- An entry of such a list ends with a menu. Edit… asks for its title and for where it leads: a chapter, and its start or one of its headings, chosen by title. Nest under the entry above and Move out one level change its level, and the entries under it move with it. Remove… asks first. Add an entry… opens the same dialog; choosing a heading fills in its words as the title.
- Nobody orders the list by hand. An entry sits where its place is in the book, and one that is given another place moves there. The entries of a chapter go with it when it moves up or down, and keep leading to it when its file is renamed. They are removed with it, and the question before a chapter is removed says how many there are. Landmarks do the same.
- An entry whose heading is gone is marked "leads nowhere", and one whose heading was moved past another in the text "out of order". The section counts both, and Put the entries in the order of the book sorts the list. The Problems section leads here with Open Contents.
- Choosing an entry opens its chapter.
The whole book.
-
Details is a form over the metadata of RFC 0001: title, authors, language, series, publisher, date, annotation.
-
Pictures shows a gallery with a preview, dimensions, size and a remove control for each picture. Pictures and the Cover accept AVIF, JPEG, PNG, GIF, WebP and BMP. Adding one offers the name of its file in the book, a quality and maximum output dimensions. It starts at quality 80 and the original dimensions.
-
Landmarks marks the places a reading application can take a reader to (RFC 0001). The section opens with what that gives a reader, then shows two parts:
- Where the text begins, in a block of its own with a band of the accent: where a new book opens instead of at its cover or title page. The block says whether the place is marked, and Mark where the text begins…, Change… and Remove set or clear it. A book has one.
- Other places: every other landmark, listed by the name a reader is shown, with its kind beside a title that stands in for it and where it leads under it. Add a landmark… asks what the place is, the name readers see and where it is. The kinds are grouped by what a reader looks for: looked up while reading (notes, glossary, index and the like), parts of the text, and pages about the book. Under the choice a line says what a reader gets from it. The name is optional, and the name of the kind is its placeholder; a name that only repeats the kind is not stored. A new landmark is put among the others in the order of the book. A kind the editor does not know, such as one for private use, is listed as the book writes it and kept when its place is changed.
Each landmark leads to a place chosen like the destination of a link: a chapter, and its start or a named place in it. A landmark keeps leading to its chapter when the file of the chapter is renamed, and is removed with the chapter.
-
Problems lists what
Book::checkreports, each with its chapter and place; choosing one opens that place. A book with problems is not saved. -
Save replaces the book in the library. For a book with automatic contents, Save builds the contents from the current chapter headings. Use Command+S on macOS or Ctrl+S on other platforms. On macOS the File menu also offers Save.
Settings
One screen, reached from the library: a page on an expanded window, a pushed screen on a compact one.
| Setting | Choices | Default |
|---|---|---|
| Typeface of books | Literata, Noto Sans, System and installed families | Literata |
| Size of the text | 16 to 80 logical px in Aa, with a shortcut to 44 px | 20 compact / 22 wider at first opening |
| Line height of the text | 1.30 to 2.00 in 0.05 steps | 1.60 |
| Page tone | Paper, Neutral, Sepia, Night, High contrast, or Follow the system | Follows the system |
| Wide-window column | 45 to 80 zero-glyph advances | 60 |
| Paragraph gap | 0 to 2 em | 0.7 em |
| Heavier text | 400 or 500 where the family supplies it | 400 |
| Reading layout | Scroll or pages | Scroll |
| Page-turn animation | Off or on, subject to reduced motion | Off |
| Reading progress | Visible or hidden | Visible |
| Language | System language, English, Русский | System language |
| Size of the interface | 100% to 200% | 100% |
| Controls of the reader | Hide while reading, or always shown | Hide while reading |
| Motion | As the system says, or reduced | As the system says |
| Check for updates | On, off | On |
A change shows at once in an open book. A page tone that follows the system is Paper while the system is light and Night while it is dark.
The interface is in English and in Russian. With System language it is in the first language of the system it is translated into, and in English when the system prefers none of them; the choice names the language it stands for, and each language is named in itself, so that a person who cannot read the current one finds theirs. A new language shows at once, the menu bar of macOS included; a message already on the screen keeps its language (Languages).
Using the application without a pointer or without sight
- Keyboard. Every action has a key or is reached with Tab and the arrow keys; what has the focus is outlined. The shelf is a grid the arrows move through; Return opens a book, and the menu key opens its menu.
- Screen readers. A cover is announced as "The Master and Margarita, by Mikhail Bulgakov, 38 percent read". A chapter is read as headings, paragraphs, lists and tables; a picture is read by its alternative text. The end of an import, and a failed one, are spoken.
- Low vision. The interface scales to 200%, at which a desktop window takes the compact layout instead of cutting anything off. Text and controls keep the contrast of level AA in every page tone.
- Touch and tremor. Nothing needs a drag, a hover or a timed gesture: a chapter is moved with "Move up" and "Move down", a picture is added from a dialog as well as by dropping it, and the controls of the reader can be kept on screen.
Architecture
How the application is put together: its modules, where each piece of work runs, what is stored where, and how a book is imported, read, edited and updated. A sentence with "must" states an invariant of the code that a test or a review keeps.
Crate and workspace
crates/mbook-ui is one package with a library and a binary.
crates/mbook-android is the shell of Android.
| Target | Contains |
|---|---|
Library mbook_ui | Every model and view, and run(Application, Roots). It names no platform, except where Android has no counterpart of a desktop crate: the file picker and the insets of the window. |
Binary mbook | The allocator, the platform of the desktop, the directories from dirs, a call to run. Empty when built for Android. |
Library mbook_android, a cdylib | The allocator, android_main, the platform of gpui-mobile, the roots from the files of the application, a call to run (Android). Empty on every other target. |
- A shell must stay a shell: it sets the global allocator, builds the
Applicationand the roots, and passes them on. - The engine is chosen per target in the manifest. On the desktop
gpui-kitandgpui-kit-markdown-editorare used with the featuregpui-fast; on Android without it, on gpui-pre, which is the engine gpui-mobile implements its platform for. Cargo leaves the features of a target table out of a build for another target, so one build never holds both engines. Application code importsgpui_kit::*only and never namesgpui,gpui-fastorgpui-pre. - Code for one platform is chosen by
cfg(target_os = "android"). It is kept to the file picker, the insets, the export that ends in the share sheet, and the bar of a page; the desktop counterpart is the code without the attribute. - The allocator is set in the shells, not in the library, so that tests and other shells choose their own.
- Both packages set their own
rust-version, 1.100, and are not published to crates.io.mbookandmbook-converterkeep the 1.89 of the workspace. - The lints of the workspace apply unchanged to
mbook-ui.mbook-androidrepeats them withunsafe_codedenied instead of forbidden, for the unmangled name ofandroid_main, which has the one#[expect].
The modules follow the layers of Feature-Sliced Design. A layer uses only the layers below it.
| Layer | Slices |
|---|---|
app | run, the window, the root view, menus and keys |
pages | library, reader, editor, settings |
widgets | chapter_view, the text of a chapter, which the reader and the preview of the editor share. Every other part of a screen belongs to its page until a second page needs it. |
features | import_book, reading_position, appearance, edit_book, search_library, search_text, auto_update |
entities | book (an open book), catalogue (the store), picture (decoding and its cache), figure (diagram and formula rendering) |
shared | roots (directories), model (the key of a book, a place in one), layout (size classes), theme (colour tokens), actions, ui (presets over Kit components), assets |
State lives in model entities; a view observes a model and calls its
methods. A view holds no BookReader, no Book and no path.
Threads
| Work | Runs on | Priority |
|---|---|---|
| Drawing; changing entities; reading snapshots | Main thread | |
| Opening the catalogue; its reads and writes | Background | Medium |
BookReader::open; building the snapshot of a book | Background | High |
read_chapter; resolving its links and pictures | Pool | High |
| Following a link | Background | High |
| Parsing Markdown for display | Background, by the text view of GPUI Kit | |
read_picture; decoding AVIF; scaling | Pool | Medium |
| Reading diagram and formula sources and drawing SVG | Pool | High for the current chapter |
| Detecting a format; copying a file; recording a book in the catalogue | Background | Medium |
Converter::convert | Pool, one conversion at a time | Low |
| Making the thumbnail of a cover | Pool; the file is written on the background | Low |
Book::open, every change of a Book, check, save | Pool, for the task that owns the book | Medium |
| Decoding a picture added in the editor and encoding it as AVIF | Pool, one at a time | Low |
| Writing a book in another format | Pool | Low |
| Filtering the library | Pool | High |
| Matching text in the reader and chapter editor | Pool | |
| Checking for an update; downloading it | Background | Low |
- Code on the main thread must not call a
read_method ofBookReader, any method ofBookorConverter, a function ofstd::fs, the catalogue, or a decoder. - Background work is started with the background executor of GPUI and
returns a
Task. The entity that asked keeps theTask; dropping the entity cancels it. - Pool is the global thread pool of
rayon, whichshared::computebuilds when the application starts: half the threads the system offers, one at least, each with a stack of 16 MiB and namedmbook-compute-N. The converter and the AV1 encoder compute on the same pool. A task of the background executor hands its computation over withcompute::spawnand awaits the future it gets, doing nothing else meanwhile; the executor keeps reading and writing files, the catalogue and the network. - A step that both reads and computes runs where most of its time goes: preparing a chapter reads and decompresses it and then parses it, on the pool; an import probes, copies and records the book on the background, and converts it and makes its thumbnail on the pool.
- The pool has no priorities: work runs in the order it is handed over. A panic of the work is resumed in the task that awaits it.
- Cancelling takes effect between steps. Work the pool has not started does
not run once its task is dropped. A conversion or a decode that has
started runs to its end, and its result is discarded: the converter has no
cancellation (
mbook-converter, Future possibilities). - A result that arrives for a state the user has left must be dropped: every request carries the generation of the view that made it.
- Conversions run one at a time. The converter is built with its
rayonfeature and encodes the pictures of a book on every thread of the pool, and each conversion holds its source and its book in memory (mbook-converter, Sources and memory).
Storage
The shell hands the library two directories, the roots. On desktop they
come from dirs:
dirs::data_dir()/mbook/ kept; backed up with the user's data
catalog.redb the catalogue
books/<key>.mbook one file per book
books/.incoming/ files of imports that have not finished
dirs::cache_dir()/mbook/ may be deleted at any time
covers/<key>.jpg thumbnails of covers
update/ a downloaded update
share/share-*/<title>.mbook books handed to the share sheet, until the next start
<key>is a UUID version 7 made when the book is added. It is not theidof the book's metadata: that is any string, and an edit may change it.- A file must enter
books/by a rename frombooks/.incoming/, which is on the same volume. A reader therefore never sees half a file. books/.incoming/is emptied when the application starts.- Everything under the cache root must be reproducible from the data root.
- When
dirsknows no directory for the platform, the shell supplies the roots itself. Tests pass temporary directories. - On Android the roots are
mbook/andcache/in the private folder of the files of the application (Android).
The catalogue
The catalogue is one redb database. It holds two kinds of data:
| Table | Key | Holds | Can be rebuilt |
|---|---|---|---|
books | key | id, title, authors, language, series, the size of the file and of the cover, the time added, the format it was converted from | Yes, from the files in books/ |
state | key | The last place read, the time of the last opening, whether the book is finished | No |
settings | name | Page tone, typeface, text size, the size of the window, whether updates are checked | No |
- The mbook files are the source of truth for metadata. A row of
booksis a copy that spares the application from opening every file at start. - When the database is missing or cannot be opened, the application
must rebuild
booksby opening every file ofbooks/withBookReader::open, which reads the tables and nothing else. Reading places and settings are then lost; the books are not. The file that could not be opened is kept beside the new one ascatalog.redb.damaged, and the user is told once. - Two cases are not damage, and the file must not be replaced: a database written by a newer version of the application, and one that another running copy of the application holds open. Both end in an error screen that says which.
- A place is stored as the path of a chapter and a byte offset, not as a
resource number: numbers change when a book is saved again
(
mbook, Shared value types), paths do not. When the offset is no longer at the start of a block, the reader opens the block that contains it; when the chapter is gone, the start of the book. - Progress is the decoded length of the chapters before the place, plus the offset, over the decoded length of all chapters. Both come from the directory of the file; nothing is decoded for it.
- Rows are encoded with the value types of
redb; the encoding is proposed. The database carries a schema version.
Import
stateDiagram-v2
[*] --> Queued
Queued --> Probing
Probing --> Copying: is_mbook
Probing --> Converting: any other format
Copying --> Indexing
Converting --> Indexing
Indexing --> Done
Probing --> Failed
Copying --> Failed
Converting --> Failed
Indexing --> Failed
Done --> [*]
| Step | What happens |
|---|---|
| Probing | The first 53 bytes are given to mbook::is_mbook. |
| Copying | An mbook file is copied into books/.incoming/ and opened with BookReader::open, which rejects a file that is not valid. |
| Converting | Converter::convert reads the file and writes into books/.incoming/. The format is detected from the content; for Markdown and plain text, which are never detected, it is taken from the extension of the file name with Format::from_str. |
| Indexing | The file is renamed into books/. Its metadata go into books, and its cover, decoded and scaled, into covers/. |
- The native picker filters by the book extensions, including ZIP containers for supported sources. The application checks the extension again after selection. Conversion and drag-and-drop still inspect the source content.
- The original file is neither moved nor changed.
- A book whose
idis already in the library is not added again; the existing book is opened. The converter gives a source without an identifier anidcomputed from its bytes, so the same file is recognised. - A failed import leaves nothing in
books/and no row. The error is shown on the entry of the import, in the words of the converter'sError. - The warnings of a
Reportare counted on the entry and listed on request. They are not kept after the application closes. - Opening one file opens the reader when its import is done. Adding several files only adds them.
- A phone cannot hold a source of 2 GiB and its book. On a compact device
the shell lowers
ConvertLimits(proposed; the values are not chosen).
Export
The library book menu offers Export. The application enables the
converter’s export feature, so its
submenu lists all eight formats. Selecting a format opens a native save
dialog with the book title and the format extension. Dismissing the dialog
ends the action.
The background executor opens the saved library book and writes the chosen format to a temporary file in the destination directory. The finished file is published only if the destination name is available. The application announces success or failure in the window.
Android has no save dialog that returns a path. There the format is written
under the same name into a folder of its own, <cache>/share/export-*/, and
the file goes to the share sheet as Share sends a book; saving to a
folder is one of its targets. A failure is announced; a shown sheet is not.
Share
The library book menu offers Share. The library file,
books/<key>.mbook, is named by its key, and that name is what a recipient
would see. So the background executor first puts the book in a folder of its
own, <cache>/share/share-*/<title>.mbook, under the name Export
suggests: a hard link, or a copy where the cache is on another volume. The
folder of each share is new, so two books of one title do not replace each
other while an app still reads the first. The shares stay until the next
start, when Roots::prepare removes them: the app a book is shared with
reads the file after the sheet has closed.
Back on the main thread, the path goes to the share sheet of the platform
through robius-share, with the title of the
book as the title and the subject of the share. The call returns once the
sheet is shown:
- on macOS an
NSSharingServicePickershown at the content view of the key window, which puts it beside the window rather than at the menu; - on Windows the
DataTransferManagerof the foreground window, with the file as a storage item; - on Linux
robius-sharehands the file to the desktop portal or toxdg-open; there is no Linux build of the application yet; - on Android an
ACTION_SENDchooser, whichrobius-sharedoes not take part in. A file of the application cannot be read by another app, so the interface asksMbookActivitythrough JNI to share it: the activity lends it throughMbookFiles, a read-only content provider of its own that serves only<cache>/share, and starts the chooser on its own thread. The call returns at once (Android).
The application learns nothing of what the reader chooses in the sheet. A copy that cannot be made, or a sheet that cannot be shown, is announced in the window with its cause; a shown sheet is not announced. The file is shared as it is in the library, not converted: a reader needs an mbook reader to open it, and Export gives the other formats.
Opening files from the system
The application registers itself for the book formats, so that a file
manager offers it for a book and a double click or Open with starts it
with the file. The formats are those of BOOK_FILE_EXTENSIONS, the list
the picker filters by.
| System | Where the formats are declared | How a file arrives |
|---|---|---|
| macOS | The Info.plist of the bundle: assets/macos/document-types.plist, which cargo-bundle adds (osx_info_plist_exts). It exports the type io.github.m-compressors.mbook.book for .mbook, which the application owns, and makes it an alternative viewer of the other extensions. | application:openURLs:, which GPUI hands to on_open_urls as file: URLs, also when the file starts the application. |
| Windows | The registry of the current user, written by the application at each start on the background executor, since the installer registers nothing: the program identifier mbook.Book with the command "mbook.exe" "%1", .mbook owned by it, and mbook.Book under OpenWithProgids of every other extension, which adds the application to Open with and leaves the default program as the user chose it. | The command line of a new process. |
| Android | The manifest: VIEW intents of content: and file: URIs, and SEND and SEND_MULTIPLE, for the MIME types of the formats and application/octet-stream, the type an mbook file comes with. | OpenActivity opens the document and brings up MbookActivity; the document is copied into <cache>/opened/<n>/<name> on a thread of its own; the interface takes the paths once a second (Android). |
| Linux | Nothing: there is no Linux build. | The command line. |
runtakes the files of the command line, and registers for the URLs of the platform. Afile:URL is decoded to its path; a URL of another scheme, or a file of another host, is left out.- The files wait in a global until the library is open, and are then added
as dropped files are: one file opens its book once it is in the library,
and a book whose
idis already there is opened instead of added again. - A second start on Windows opens a second window: nothing passes the file to the running application.
Reading
An open book is an entity with two parts.
| Part | Lives | Contains |
|---|---|---|
| Snapshot | Main thread, immutable | Title and authors; the contents; the landmarks; for each chapter its number, path and decoded length |
| Source | Behind a mutex that only background tasks lock | The BookReader<File> |
- The snapshot is built once, on the background, when the book is opened.
The main thread must not lock the source, not even for a table lookup.
The landmarks are read with
read_landmarksat the same time. A table of landmarks that cannot be read leaves the book without them; it opens and reads as before. - A book without a stored place opens at its first
startlandmark, and at the start of its first chapter when it marks none. A stored place always wins, so a book once opened reopens where it was left. - A chapter is prepared on the background in one task:
read_chapter, thenresolvefor every link and picture destination of the text, then the byte offset of every top-level block, found withmarkdown, the parsermbookitself uses. The main thread receives the text, a map from destination toDestination, the figure sources, and the offsets. - The reader and editor preview use the Markdown view of GPUI Kit. The scrolling reader lets the list handle wheel and touchpad events. The list of the Kit takes no padding from outside, so a scrolling text is followed by one more block: a paragraph of invisible characters that a plugin draws as empty room as tall as the footer and the bottom inset of the window. Scrolled to its end, the text stops above the footer. The room is not one of the blocks of the text: offsets, the reading place and the end of the chapter leave it out, and a paged text has none. The optional paged reader measures the top-level blocks and gives the list a viewport exactly as tall as the selected page's content. A short last page leaves blank space below it. Page breaks and picture sizes are calculated from the full available sheet height.
- Paragraphs split at rendered line boundaries, avoiding a single line at either end of a break when there is room. A heading stays with the content that follows when they fit together. Other blocks move intact to the next page if they fit there. A block taller than a page splits on the body text line grid because the Kit does not expose its own internal line boundaries.
- Each chapter contributes its measured page count to the book total. Until a chapter has been paginated, its count is estimated from its decoded length and the observed density of measured, multi-page chapters. With no such chapter, the column size and typography supply the initial density. The counts are kept for the current window and typography.
- The reading slider maps its fraction back into the decoded lengths in the snapshot, then opens the passage at the resulting byte offset. The start and end include empty first or last chapters. The bottom strip keeps its dimensions as the slider appears and disappears.
- The stored place remains the chapter path and a byte offset. For a viewport or page starting inside a block, the reader estimates the byte offset from that block's vertical fraction. Scrolling uses the list’s proportional anchor on remeasurement. Pagination finds the new page from its block anchor. The layouts exchange the chapter source offset. After an in-app edit, a short quotation can relocate the source block. The reader writes the position at most once a second and when the book closes.
- Find starts with the current chapter and reads one chapter at a time on the background. It searches words shown by Markdown, including headings, link labels, code and alternative text. It keeps the current match and its source span for navigation and highlighting. Only the chapter shown by a match is laid out. Changing the query or closing the bar cancels the remaining chapter reads.
- After a change to the window or typography, the reader recalculates the
pages and keeps the page containing the reading anchor. A contents
entry, link or saved place does the same with its destination offset.
A destination that resolved to
Destination::ExtraAnchoris completed withread_resolveon the background when the link is followed. - Turning past the last page opens the first page of the next chapter. Turning back from the first page opens the last page of the previous chapter. Page turns take effect immediately by default. The optional animation is subject to the reduced-motion setting.
- Editing a book closes its source first, so that the file can be replaced on every platform; the reader reopens the book afterwards.
Pictures
GPUI decodes no AVIF, so the application does:
read_picturegives the bytes of the file.avif-decodedecodes them to 8-bit RGBA. It does not apply the crop, the rotation and the mirroring an AVIF file may ask for, so the application does, by the rulesmbookreads the size of a picture with: the decoded picture then has the size the tables of the book give.- The picture is scaled down to fit the text column and the available page height, keeping its proportions.
- The result is given to GPUI as a rendered image.
- A picture is requested when the Markdown view lays it out. The three steps run off the main thread. The AVIF decoder runs on a scoped thread with its own stack because native executor threads can have small stacks. The view reserves the picture's space from its size in the book tables.
- Decoded pictures are cached by their fitted dimensions. After a resize, the placeholder and the decode use the new size. The cache is bounded by bytes, with the least recently shown leaving first. The bound depends on the size class (proposed: 256 MiB expanded, 64 MiB compact).
- The thumbnail of a cover is made once, at import or after a save, 400 px wide, and stored as a JPEG file that GPUI loads by its path.
- A picture that cannot be decoded shows its alternative text. It never fails the chapter.
Seeing a picture larger
The Markdown view of GPUI Kit draws a picture as an image that answers no
click. The chapter view therefore takes a paragraph that holds nothing but
one picture, written , away from the Kit with a block
plugin of its own. The plugin draws the picture from the same source and at
the same size as the Kit, so the layout and the pages do not change, and
tells the reader when it is clicked or tapped. A block diagram or formula
answers the same way. A picture in a line of text, a linked picture and a
reference-style picture stay with the Kit and do not answer.
- The reader shows what was clicked over the whole window, in a viewer that belongs to the reader page. The viewer takes the focus; the keys of the reader do not reach the text under it.
- A picture is read and decoded again on the background at its own size, not at the size of the column. A picture of more than 16,000,000 pixels is decoded at that many and scaled up. The decoded picture belongs to the viewer, not to the cache of the chapter, and is released when the viewer closes.
- The scale is a part of the picture's own size, in which a pixel of the picture is a logical pixel, as in the text. At first the picture fits the window, enlarged at most four times to do so. It may be reduced to the smaller of the fitted and its own size, and enlarged to four times the larger of them. A step is a factor of 1.25 and stops at the fitted and at the own size.
- A zoom keeps the part of the picture under the pointer, or in the middle for a button or a key, where it was. A drag of more than four logical pixels moves an enlarged picture and does not close the viewer.
- A figure is drawn for the viewer as SVG at a density that is a power of two, so it is rasterised again only when its size doubles or halves, with at most 16,000,000 pixels. The drawing before stands in while the next is rasterised. The viewer keeps its own drawings, apart from the one the text shows, and releases them when it closes.
Diagrams and formulas
References to diagrams and formulas use the
Markdown image syntax of RFC 0001.
The source dialogs use GPUI Kit's code editor with Tree-sitter grammars for
Mermaid and LaTeX. The highlighting is independent of rendering.
The application draws with the figure module of mbook-converter, the
one export uses: merman for Mermaid and RaTeX for KaTeX. It renders the
source on a background task and passes SVG to GPUI. A bounded cache
is keyed by source, page colours and formula style.
The Markdown view centres a block figure, fits its drawing to the column and page and displays its caption when supplied. Inline formulas follow the baseline of the surrounding text. Unavailable drawings show the alternative text. Figures use the page tone and scale with the text. All drawing is local. The application does not follow links or execute commands from figure sources.
Editing
- The library creates new books with
Book::new, the entered title and the language tagund. It adds an emptych01.md, writes the book intobooks/.incoming/and uses the same install and catalogue step as an import. The editor opens after the file and its catalogue row are in place.
sequenceDiagram
participant V as Views (main thread)
participant S as EditSession (main thread)
participant T as Book task (background)
V->>S: change, check, save
S->>T: command, in order
T->>T: Book::set_text, check, save
T-->>S: outline, problems, or error
S-->>V: notify
- A session starts with
Book::openon the background. TheBookis then owned by one background task for as long as the session lives. - The session sends that task commands over a channel, and the task applies them in the order they were sent. A save therefore always includes the edits made before it.
- The main thread holds an outline: the metadata, the paths and sizes of chapters and pictures, the paths of diagrams and formulas, the landmarks and the problems last reported. The task sends a new outline after each command that changes it.
- The Markdown text of the chapter is in the source editor of GPUI Kit. Source and Split use its Tree-sitter Markdown grammar.
- Visual uses
gpui-kit-markdown-editorwith the GPUI Fast engine. Enter starts a paragraph, and the block editor owns selections, structured edits, and undo and redo. Committed transactions update the chapter's Markdown buffer. Opening or closing Visual leaves the source intact. - The application compares the editor's GFM blocks before and after edits
with
similar. Unchanged blocks keep their original Markdown whenever they can be put back without changing the block structure. If the initial import changes the top-level block structure, the chapter is available in Source. The Visual picture preview and the gallery use the same bounded cache and load pictures by book path through the editing task. - The source text is
sent to the task as
Chapter::set_textwhen typing pauses for 400 ms, when another chapter is opened, and before a check or a save. - The preview is the Markdown view of the reader, given the text of the editor. The text updates immediately. The editing task resolves figure references from the current draft after a short pause, including reference-style images. The view then draws them using the same code as the reader.
- An error of a call (
InvalidText,InvalidPath,DuplicatePath,InvalidPicture,InvalidDiagram,InvalidFormula,InvalidMeta) is shown at the control that caused it, with the byte offset when the error has one. - Save runs
Book::check, thenBook::saveonto the file of the library, which writes a temporary file beside it and renames it into place. A book with problems is not written, and the problems are shown. Save sends chapter text and pending Details edits before the save command. After a save the row ofbooksand the thumbnail are made again. - Undo inside a chapter is the editor's own. Removing a diagram or formula
asks for confirmation. References to a removed resource are reported by
Book::checkand block saving until they are updated or removed. - Removing a chapter or a picture asks first and cannot be undone.
- Changes in Landmarks replace the landmark list through
Book::set_landmarks. An edited landmark keeps its position and the others keep theirs. A new one goes after the last landmark that leads to the same place or an earlier one, by chapter in reading order and then by the order of the places in the chapter; landmarks that lead nowhere are passed over. An edit or a removal is dropped when the list changed under the dialog. If a chapter or anchor no longer exists, the next check or save reports the dangling landmark. The Landmarks section can retarget or remove it. - A chapter moves to another path by being removed and inserted at the same
position, since
Bookhas no rename; the links that broke are then among the problems. - A new chapter gets the first free path of the form
chNN.mdand the text# Title, followed by an empty line, when a title was entered. The title is escaped so that it is read back as the same words. - The outline carries, for every chapter, the places a link or a landmark
can name: its headings, with their level and their text without markup,
and the lines an anchor definition names. They are found from the anchors
Bookkeeps; only the block of each heading is parsed again, and the whole chapter when that block has a bracket, which may refer to a definition elsewhere. The list of chapters, the dialogs of a link and of a landmark and the Contents section all read them from there. - The outline carries the contents as a reader is shown them. For automatic
contents they are computed from those headings by the rule
Bookwrites them with (mbook); for a stored list they are its items. - A link made with nothing selected is typed by the block editor as plain text, selected and then linked, so that the editor escapes the words and writes the destination.
- A picture is put into a chapter as
, pasted into the block editor as Markdown. The path is relative to the chapter and percent-encoded; the description is escaped.- A picture chosen from a file for a chapter remembers that chapter. When the book has taken the picture and Visual still shows that chapter, the picture is put at the caret. Otherwise it stays among the pictures of the book and a notification says how to place it.
- A drop on the chapter takes the files with the extension of a picture and leaves the others to the window, which imports books.
- A book with an empty contents list uses automatic contents when opened
in the editor. Save builds the list from the current chapter headings
and records the mode in the private metadata key
x-mbook-ui-contentswith valueheadings. Reopening such a book in the editor restores the mode for subsequent edits. - A book with entries and no automatic mode keeps the contents of its file,
item by item. Removing a heading can make an item lead nowhere, and
moving a heading past another in the text can make one fall out of order;
either blocks the save. The outline marks each such item
by the walk
Bookwrites the contents with, so the Contents section shows which entries to change. The editor also offers to switch to automatic contents from headings. - The items of such a list follow their chapter.
- Moving a chapter sorts the list again, by the rule of the sorting control below, when the list was in the order of the book before the move. A list that was out of order already is left as it is: the editor does not rearrange what the author has not sorted.
- A chapter that gets another path takes the items that led into it along, and so do the landmarks, of every kind. The links of other chapters do not follow; they are reported by the check.
- Removing a chapter removes the items that led into it, and the items under them move up as they do when one entry is removed. A list left without items gives way to automatic contents. The landmarks that led into the chapter are removed too, of every kind: a landmark has no place without its chapter, and one left behind would only block the save.
- A list the book keeps is changed by commands of the editing task that
name an entry by its position in the last outline. The section takes no
second change until the first is answered.
- An entry needs a title and a place the contents can lead to: a chapter, or one of its headings. A line that an anchor definition names is not offered, because the format does not allow it (RFC 0001).
- A new entry is put after the last entry that leads to the same place or an earlier one, at the level of the entry above it. An entry given another place is taken out and put back by the same rule with the level it had.
- A level is kept between what the entry above allows and what the entry below needs. Moving an entry in or out moves the entries under it too; removing one, or moving it elsewhere, brings them one level up. A list that follows the rules of the format therefore still follows them after any of these changes.
- Sorting is stable by chapter and offset. An entry that leads nowhere stays behind the entry it followed, and a level the new order does not allow is brought up.
- A list that loses its last entry gives way to automatic contents, as an empty list does when a book is opened.
- Text that
Chapter::set_textrefused stays in the editor as a draft, and the book is not saved while a draft exists: nothing typed is dropped. - A picture, or a cover, is added from a file in AVIF, JPEG, PNG, GIF, WebP
or BMP, the formats
mbook-converterreads (mbook-converter, Pictures). The native picker and its selection check use the extensions of these formats.- The application decodes and orients every selected file, takes the first frame of an animation, and encodes AVIF at the chosen quality and speed 6. Optional width and height limits fit the result without upscaling or changing its proportions. The encoding runs on a separate task. The command that adds the picture is sent when the bytes are ready.
- The path the user gives ends in
.avif; the editor proposes the name of the file with that extension. - A picture of more than 100,000,000 pixels, the limit of the converter, must be refused before it is decoded in full.
- A save waits for the pictures that are still being encoded.
- A file that cannot be decoded is reported at the control that added it, and nothing is added.
- Leaving the editor with unsaved changes asks whether to save them. Unsaved changes do not survive the application closing.
Layout
- A view must take its layout from the size class of its window and from nothing else. It must not test the operating system.
- The size class is computed from the width of the window and the scale of the interface, by the entity that holds the settings; a view asks it while it draws.
- What a pointer reveals by hovering must also be reachable without one: by a tap, a long press or a visible control.
- On a touch device every control is at least 44 px in both directions.
- Views keep clear of the safe-area insets of the window, which they get
from
shared::safe_area::insets: the larger of what GPUI reports and, on Android, what gpui-mobile measures, since it does not report them to GPUI yet. The bar of a page and the bottom bars draw their background under the system bars and keep their content clear of them.
| Element | Compact | Medium | Expanded |
|---|---|---|---|
| Sections of the library | A bar at the bottom | A sidebar that slides over | A fixed sidebar |
| Columns of the shelf | As many covers of 104 px as fit | Covers of 132 px | Covers of 132 px |
| Contents of a book | A sheet | A sheet | A popover |
| Text column | Available width less 20 px per side, or 16 px at widths up to 340 px | Default 60 zero-glyph advances with at least 32 px per side | Default 60 zero-glyph advances with at least 32 px per side |
| Editor | Visual, Source or Preview; the list slides over from a menu button in the header | Visual, Source or Preview; the list slides over | The list beside Visual, Source, Split or Preview |
| Menu of a book | A long press | A long press, or … | A right click, or … |
Languages
The interface is in English and in Russian. English is the language every other falls back to: a text that has no translation is shown in English.
- Where the text is. Every text a person sees or hears — labels,
buttons, menus, messages, the names a screen reader announces, the errors
of this crate — is in
crates/mbook-ui/locales/*.yml, one file per part of the application (app,library,reader,editor,settings…). A key has an English and a Russian text with the same%{values}. A view looks a key up witht!ofrust-i18nwhile it draws. - Counts. A text with a number, such as "3 books", has a form per
plural category of the CLDR:
oneandotherin English,one,fewandmanyin Russian ("1 книга", "3 книги", "5 книг").shared::i18n::count_textasksicu_pluralsfor the category and replaces%{count}. - The language of the process. There is one: the one
rust-i18nkeeps, which GPUI Component also translates its own controls in.Appearancesets it, from the language setting, when the settings are read and whenever the setting changes, and every window draws again. A test never sets it, so that the tests, whose threads share it, run in English. - At start. Before the first screen, the application takes the first of the languages the system lists, in its order of preference, that the interface is translated into, and English when it lists none. The screen that says the library is opening is drawn in it. Once the settings are read, a chosen language replaces it.
- A change of language shows in every view when it is next drawn, which
is at once. The menu bar of macOS is made again, and so are the
placeholders of the search fields of the library, the reader and the
editor, which observe the global
InterfaceLanguagethroughshared::ui::follow_language; a dialog makes its own when it opens. Text made once and kept stays in the language it was made in: a message already on the screen, such as the status of an import or a failed update, and the labels of the footnotes of a chapter until the chapter is read again. - Not translated: the names of formats, the name of the application,
the text of a book, and the messages of the
mbookandmbook-convertercrates that an error of this crate quotes as its cause. - A new language is a code in
shared::i18n::Language, its plural rules there, and its text beside each key; a test fails while a key lacks it.
Updates
Updates exist on desktop only, behind the Cargo feature self-update, which
a build for a store or a package manager leaves off.
- A release is a tag of the repository on GitHub,
vX.Y.Z, whereX.Y.Zis the version of the workspace. A maintainer starts.github/workflows/release.ymlby hand with the tag selected as the ref. The tag must contain the workflow version to run. The workflow checks the selected tag against the workspace version and publishesmbookandmbook-converterto crates.io through Trusted Publishing. It skips crate versions already present in the registry. Once both libraries are published, it creates the GitHub release if needed and builds and uploads the application installers and update archives for that tag. - The workflow builds for macOS on arm64 and x86-64 and for Windows on x86-64. There is no Linux build.
- Each platform gets two files: an installer for a person (
.dmg,.msi) and an archivembook-<tag>-<target>.tar.gzfor the application to update itself from. The archive holds the application bundle on macOS and the installer on Windows. - The bundle, the executable and the installer are signed with a self-signed certificate, so that the identity of the application stays the same from one version to the next. The systems do not trust such a certificate: Gatekeeper and SmartScreen warn at the first start.
- The archive is signed with zipsign. The private key and the certificate
are secrets of the repository (
ZIPSIGN_KEY,BINARY_SIGN,BINARY_SIGN_PASSWORD); the public key iscrates/mbook-ui/assets/update.pub, built into the application. - The check asks the GitHub releases of the repository for the latest version and compares it with the version of the package. An update is offered once that release has the archive for the running platform. The check runs at start and once a day in release builds and can be turned off in the settings.
- The update banner occupies a row below the title bar on every page. Update notifications appear at the bottom of the window.
self_updateis used with its blockingureqtransport inside a background task. The application has no second runtime.- An update is offered, never installed unasked. It is downloaded to
update/under the cache root. - A downloaded archive must be verified against a public key built into
the application before anything is replaced (the
signaturesfeature). - Installing waits while an import is running or a book is open in the editor, and so does the restart that follows it: it must not replace the application under a conversion, nor restart it over unsaved changes.
| Platform | What is replaced |
|---|---|
| macOS | The whole application bundle, from a .tar.gz, so that its signature stays valid |
| Windows | Nothing by the application: the installer from the verified archive is started, and replaces the version itself |
| Linux | Nothing: no release is built for it |
Errors
- The library has one
Errorenum, non-exhaustive, built withthiserror. The errors ofmbook,mbook-converter, the store and the decoder are its sources. - An error is turned into a sentence for the user in the view that shows it, not where it arises.
- A failure of one book, chapter or picture must not close the application or another book.
- A failure is never kept to itself: a catalogue that cannot be read or changed is reported on the library, with a way to try again, and settings that cannot be saved on the settings screen.
Security considerations
- A book is untrusted input. Its limits are those of
mbookandmbook-converter; the application adds none of its own parsers. - Markdown of a book has no raw HTML and no scripts (ADR-0006). A picture is only ever taken from the book; a network address in a picture is not fetched.
- An external link is opened by the system browser, and only when the user follows it.
- An update replaces the program. It is accepted only with a valid signature, over TLS, from the releases of this repository.
Appearance and accessibility
The colours, type and motion of the interface, and what the application promises to someone who uses it without sight, without a pointer or without fine motor control. Where the first version gives less than this page asks is listed under Status and verification.
Visual direction
The covers are the only saturated colour of the library; the reader shows nothing but the page. One accent marks what is selected and how far a book has been read.
| Token | Light | Dark | Used for |
|---|---|---|---|
| Canvas | #F4F5F7 | #15161A | The background of the library |
| Surface | #FFFFFF | #1E2026 | Sidebars, sheets, menus |
| Ink | #16181D | #ECEDEF | Text |
| Ink, muted | #5F6673 | #9AA0AB | Authors, captions |
| Line | #E3E5EA | #2C2F37 | Separators, which carry no meaning |
| Outline | #7C8390 | #747B89 | The border of a field, the track of a progress line, the edge of a control |
| Iris (accent) | #4650D8 | #8C93FF | Selection, progress, the primary button |
| Page tone | Background | Text | Muted | Link | Selection background | Search background |
|---|---|---|---|---|---|---|
| Paper | #F7F4ED | #2B2926 | #69645C | #533C87 | #DED5F1 | #FFEA9E |
| Neutral | #FAFAF8 | #262626 | #626262 | #4D458E | #DED9F2 | #FFEA9E |
| Sepia | #F1E6CF | #3B3026 | #6B5B49 | #56336F | #D9C8E2 | #FFEA9E |
| Night | #1E2024 | #D8D7D3 | #A6A8AD | #BCA9EA | #44375D | #403214 |
| High contrast | #FFFFFF | #000000 | #505050 | #000080 | #FFFF00 | #FFD880 |
-
Type. The book uses its chosen typeface. Bundled Literata and Noto Sans include true regular, medium, bold and the corresponding italics. System uses the platform UI family. Older installed family choices are retained. Paragraphs align at the start with no indent. Semantic emphasis comes from the Markdown source.
-
Measure. A single centered column uses 60 advances of the family’s zero glyph at the current weight and size. Compact windows use the available width. The default line height is 1.6.
-
Icon. An open book on the navy of these design documents:
crates/mbook-ui/assets/icon.svg, drawn once and rendered to the PNG the bundle and the Windows executable take. -
Motion answers an action: a screen is pushed, a sheet rises, the controls of the reader fade and page turns slide and fade. The system setting that reduces motion turns the transitions off.
Appearance
- The local catalogue stores reading preferences. At the first reader opening, it chooses 20 logical px below 600 px or 22 px otherwise and saves that value. Resizing and changing window orientation keep the value. Catalogues with a previously saved size keep it, including legacy sizes below 16 px. A saved Dusk choice uses Night.
- Startup registers the local faces before opening a window. If a requested family is missing, the first available bundled face or the platform system family is used. The stored family name is retained.
- Both bundled families ship as native TrueType instances in 400, 500 and 700, upright and italic. GPUI Fast's font matcher selects discrete faces. Literata uses the upstream 12-point optical cut, and Noto Sans uses its standard width. The renderer makes no per-size optical axis adjustment.
- The page tone is scoped to the reading surface. The interface projects the matching light or dark chrome. Reading tones use opaque colors.
- The renderer paints selection and search backgrounds under the existing glyph colors. Ordinary page text meets 7:1 in both states. Selected links retain their underline and link color, which achieves at least 4.5:1 against the selection and search backgrounds.
Accessibility
The application conforms to WCAG 2.2 at level AA, read for a native application. GPUI reports its elements to the platform through AccessKit; an element is reported when it has an identifier and a role.
What assistive technology is told
- Every control must have a role and a name. A control that shows only an icon gets its name as a label, and shows the same words as a tooltip.
- The name of a book on the shelf is its title, its authors and its state:
the percentage read,
new, or the step of its import. The progress line under a cover is not a separate element. - A state that colour shows must also be in the name or in text beside it: selected, current chapter, unsaved, failed, has problems.
- The text of a chapter is reported with its structure, which the Markdown view of GPUI Kit provides: headings with their level, lists, tables, links, code.
- A picture of a book is reported as an image named by its alternative text. A picture with an empty alternative text is not reported.
- The language of a book, from its metadata, is given to the elements that show its text, so that a screen reader speaks it in the right voice.
- A change the user did not cause in the focused element must be announced: an import that finished or failed, problems found by a save, an update that is ready. A change that follows from an action is announced by the element that changed. GPUI has no live regions: an announcement is a notification with the alert role, and text that changes in place has the status role. An announcement stays until it is dismissed: by its close button, which a pointer reveals, or by a tap or a sideways swipe on a touch screen. Notifications are as wide as the window allows, up to 382 px, and start below the system bars of a phone.
- An identifier of an element must stay the same while the element means the same thing: the identifier of a book is its key, of a chapter its path. Assistive technology then does not hear a list as replaced when it is redrawn.
Keyboard and focus
- Every action must be reachable from the keyboard alone, and no element may hold the focus without a way to leave it by key.
- The order of focus follows the order of reading: sidebar, then content, then panels.
- The focused element must show an outline of at least 2 px in the accent colour, with a contrast of 3:1 against what is beside it. The outline appears for focus that came from the keyboard.
- A dialog, a sheet and a popover keep the focus inside while they are open, close with Escape, and return the focus to the control that opened them.
- In the Markdown editor Tab indents. Escape followed by Tab leaves the editor, and the editor says so in its description.
- Opening a screen moves the focus to its heading or its first control; going back returns it to the control that led there.
- Keys are bound through the key map of GPUI, so that they are listed in the menus and can be changed in one place.
| Key | Action |
|---|---|
| Tab, Shift+Tab | Next and previous control |
| Arrows | Move inside a grid, a list or a menu |
| Return, Space | Activate; in the reader, Space turns a page |
| Escape | Close a panel; leave the editor; go back |
| The platform's Open, Save, Find, Settings | The same in the application |
| Page Up, Page Down, Home, End | Move in a chapter |
| The platform's bracket keys | Previous and next chapter |
Seeing
- Text must have a contrast of at least 4.5:1 against its background, and the border or glyph that identifies a control at least 3:1. The tokens of Visual direction meet this in both appearances and in every page tone; a test computes it.
- The colour
Lineis for decoration only. Whatever must be seen to use a control usesOutline. - The size of the interface is one setting that scales every length of the interface. The size class is computed from the width of the window divided by that scale, so that a scaled window reflows instead of clipping.
- The text of a book is never justified and never set narrower than the reader chose. Its size, line height and typeface are settings; no text is drawn as a picture.
- Nothing flashes.
Pointer and touch
- A control is at least 24 px in both directions for a pointer and 44 px on a touch device.
- Whatever a drag does must also be possible without one: a chapter has "Move up" and "Move down".
- Whatever a hover or a long press reveals must also have a visible control or a menu entry.
Time and motion
- The controls of the reader hide only while nothing inside them has the focus and the pointer is not over them, and never when the setting keeps them shown. They return on any key. The fade and the page turn animation are skipped when reduced motion is active.
- No message disappears by itself while it still asks for an action.
- When the system, or the setting, asks for reduced motion, every transition is replaced by an immediate change. GPUI Kit reads the system setting on macOS, Windows and Linux.
Words
- An error names what went wrong and what can be done, in text, at the control it belongs to.
- A field of a form has a visible label, which is also its name.
Android
How the application runs on Android, how its APK is built and released, and where it differs from the desktop. A sentence with "must" states an invariant of the code that a test or a review keeps.
| Package | io.github.m_compressors.mbook, an APK for arm64-v8a |
| Android | 8.0 (API 26) and later; built against API 35 |
| Source | crates/mbook-android |
| Platform | gpui-mobile, on the gpui-pre engine of GPUI Kit |
| Installer | mbook-vX.Y.Z-android-arm64.apk on GitHub Releases |
The Android application is the same library, mbook_ui, as on the desktop,
started by a shell of its own. Its screens, layouts and storage are the ones
the other pages of this section describe; this page lists only what is
different.
Building the APK
crates/mbook-android/android.sh builds the library and packs the APK with
the tools of the Android SDK; there is no Gradle project. It needs:
| Tool | Where it comes from |
|---|---|
The Rust target aarch64-linux-android | rustup target add aarch64-linux-android |
The Android SDK, with platforms;android-35 and build-tools | ANDROID_HOME |
| The Android NDK | ANDROID_NDK_HOME, else ANDROID_NDK_LATEST_HOME, else the newest under $ANDROID_HOME/ndk |
| A JDK 17 or newer | JAVA_HOME, or javac on the PATH |
jq and zip | the PATH |
crates/mbook-android/android.sh clippy # lint mbook-ui and mbook-android for Android
crates/mbook-android/android.sh apk # an APK of the pre-release profile
crates/mbook-android/android.sh apk --release # an APK of the release profile
The APK is written to target/android/mbook-<version>-android-arm64.apk.
Without a keystore it is signed with a debug key made once in
target/android/debug.keystore. It installs with adb install, but it
cannot replace an APK signed with another key, nor be replaced by one:
Android then asks for the old one to be removed first, which removes its
library. MBOOK_APK_KEYSTORE, MBOOK_APK_KEYSTORE_PASSWORD and
MBOOK_APK_KEY_ALIAS (by default mbook) name the key a release is signed
with.
Continuous integration runs both commands on every push and keeps the APK of the run as an artifact.
What the APK holds
| Part | Made from |
|---|---|
lib/arm64-v8a/libmbook_android.so | The library of mbook-android, built for aarch64-linux-android with the C compiler of the NDK for API 26, stripped of its symbols |
classes.dex | The classes of the example application of gpui-mobile that mbook needs, and MbookActivity, OpenActivity and MbookFiles of crates/mbook-android/android/java, compiled with javac and d8 |
AndroidManifest.xml, the theme | crates/mbook-android/android/; the version of the workspace goes into versionName, and major × 1,000,000 + minor × 1,000 + patch into versionCode |
| The launcher icon | crates/mbook-ui/assets/icon@2x.png |
assets/fonts/NotoColorEmoji.ttf | The emoji font of the example application of gpui-mobile, with its licence beside it |
- The Java activities and the font are taken from the checkout of gpui-mobile
that Cargo built against, found with
cargo metadata. A later commit of gpui-mobile that moves them makes the script stop with a message. - Of gpui-mobile's Java, only what mbook uses is compiled:
GpuiInputActivity, whichMbookActivityextends, and the classes its Rust code calls with mbook's features (GpuiPathPicker,GpuiHelper,GpuiPlatformView,GpuiClipboard), with what they refer to. That code is compiled without warnings or notes, since it is not mbook's and some of it uses deprecated APIs of Android; mbook's own Java must pass-Xlint:all -Werror. - The emoji font is bundled because gpui-mobile draws colour emoji from bitmap glyphs only, and the emoji font of Android 13 and later has vector glyphs. It adds about 10 MB.
- The APK is aligned for pages of 16 KiB and signed with the APK Signature Schemes v2 and v3.
The shell
mbook-android is a library of type cdylib. The activity of the APK,
MbookActivity, is the GpuiInputActivity of gpui-mobile, a
NativeActivity that loads it and gives the keyboard of the system an
input connection, with the documents other apps hand over. android-activity
then calls android_main on a thread of its own, which:
- sends
logrecords to logcat under the tagmbook, and a panic too; - creates the platform of gpui-mobile;
- builds the roots from the files of the application;
- calls
mbook_ui::runwith anApplicationon that platform.
android_main must keep its unmangled name: android-activity finds it by
that name. The shell sets mimalloc3 as its allocator, as the desktop
binary does.
The manifest names the configuration changes the activity handles itself: rotation, size, keyboard, navigation, density and dark mode. Android therefore keeps the activity across them, and gpui-mobile adapts its window in place.
Opening a document from another app
The manifest offers mbook for viewing and for sharing documents of the
types of the formats it converts, and of application/octet-stream, the
type an mbook file comes with (Opening files from the system).
- A document comes as a
content:URI that only the activity may read, or as afile:URI from an app that still sends one. It is received byOpenActivity, an activity without a window or native code, in whatever task the other app starts it, and for a result if it asks for one, as Telegram does. It opens the stream of each document at once, since the permission to read it lasts only as long as the activity, startsMbookActivityin its own task, where the running interface comes to the front, and finishes. A secondMbookActivityin the task of the other app could not run the interface, which runs in the first. - A document must belong to another app: a
content:URI of a provider of another package, or afile:URI whose canonical path is outside the private storage of mbook (its data folder and its device-protected data folder). Any app can startOpenActivity, and mbook reads what it is given with its own permissions, so a URI of mbook itself is refused and logged instead of being copied. - The documents are copied into
<cache>/opened/<n>/under the name the provider shows, on a thread of their own, and the paths are queued. A name without an extension gets the one of the document's MIME type, from which the importer reads the format. - Nothing wakes the interface for it: a task of the interface asks the activity for the queued paths once a second, through JNI, and adds them as dropped files are. The copy in the cache stays; Android may remove it when it needs room.
- A recreated activity does not take its old intent again.
Where it differs from the desktop
| Part | On Android |
|---|---|
| Engine | gpui-pre instead of GPUI Fast; see Crate and workspace |
| Roots | <files>/mbook/ for the data and <files>/cache/ for the cache, where <files> is the private folder of the application. Uninstalling the application removes its library. |
| Adding a book, choosing a picture | The document picker of the system. It copies each chosen document into the cache of the application and returns the copies; it has no filter, so a file of another kind is refused after it is chosen. |
| Export | Has no save dialog: the converted copy goes to the share sheet, whose targets include saving to a folder (Export). |
| Share | Through MbookActivity.share, which lends the file with MbookFiles, a read-only content provider for <cache>/share, and starts the chooser on the thread of the activity (Share). |
| Clipboard | The clipboard of the system, through ClipboardManager: the clipboard feature of gpui-mobile calls GpuiClipboard for every read and write. Copy in the edit menu of a long-press selection, in the reader and in text fields, puts the text where other apps can paste it, and Paste takes what they copied. The menu is the one GPUI Kit draws, not the floating toolbar of Android. If the call fails, the text stays inside the process and the failure goes to logcat. |
| Book menu | Has no Show the file: the library is in the private storage of the application, which no file manager shows, and gpui-mobile cannot reveal a path. The file leaves through Share and Export. |
| Updates | None in the application: a newer APK signed with the same key installs over the older one and keeps the library. |
| Header | A plain bar, not the title bar of the Kit: there is no window to move or to minimise. |
| System bars | The window covers the screen. Views keep clear of the bars as gpui-mobile measures them (Layout). |
Limits
- arm64 only. No APK is built for 32-bit ARM or for x86-64 emulators.
- API 35 is the last target the theme works for. Android 15 draws an application that targets API 35 under its bars, and gpui-mobile measures the bars from a content view that then covers the whole screen. The theme opts out of that, which an application that targets API 36 cannot do. Moving on needs gpui-mobile to report the insets of the system through GPUI.
- The process ends with the activity. GPUI cannot start again in a
process on the thread
android-activitygives a new activity: its window would stay black. SoMbookActivityends the process once it is destroyed, after the interface has stopped, and the next start is a fresh one. A change the manifest does not name, such as the language of the system, therefore restarts the application. gpui-mobile has a second entry point that keeps the interface across activities, which needs a host activity of its own. - The navigation bar of gesture navigation is not reported by every device: on some, the handle is drawn over the bottom of the library's bar.
- gpui-mobile is a pinned commit of an open pull request, longbridge/gpui-mobile#56, fetched from the repository; see Dependencies.
- Documents are polled. The interface asks the activity once a second for documents it received, for as long as it runs.
- No tests run on Android. The code shared with the desktop is tested there; what only Android compiles is linted in continuous integration and was tried on one phone (What is implemented).
Status and verification
What the first version does, where it differs from the other pages of this section, and how it was checked.
What is implemented
The first version implements what the other pages of this section describe, with the differences below. The headless tests cover layout and interaction. The redesigned screens were also exercised on macOS with an imported illustrated book. Screen-reader use and native builds on Windows and Linux still need verification.
Seen in the pictures and left as it is: a notification stays over the right end of the header for a while. A long word on a cover drawn from a title can break in its middle.
| Part | State |
|---|---|
| Library | New book… creates a titled book and opens its first chapter in the editor. Cover tiles show a new badge, reading percentage or completion status below the cover. The card of the book being read shows how far it was read, not the name of its chapter: the catalogue stores the path of a chapter, not its title. A change of the catalogue that failed is followed by a reload, and a reload that succeeds clears the message, so that failure may pass unseen. |
| Export | The book menu exports the saved book in all eight converter output formats through a native save dialog. |
| Share | The book menu shows the share sheet of the platform with a copy of the mbook file named after the book. The headless tests check the copy, its name and the title it is given, and the announcement of a failure. The sheet was opened on macOS from the menu and offered AirDrop, Messages, Notes and Freeform for the named file; it has not been tried on Windows. On macOS it appears beside the window, not at the menu: robius-share takes no anchor. |
| Import | "Add a book…" and the Open key show a picker filtered to supported book extensions. Files can also be dropped on the window. Opening a file with the application from the system works through the formats it registers (Opening files from the system). The tests cover the URLs and paths, the queue until the library is open, the registry entries of Windows and the formats the plist and the manifest declare; opening a file from Finder, Explorer or an Android file manager has not been tried, and the Windows code is compiled by continuous integration only. |
| Reader | Scrolling, optional pagination, whole-book search with return to the original passage, auto-hiding controls and optional progress. A book read for the first time opens at its start landmark, and the contents panel lists the landmarks under Go to. Pagination supplies whole-book page estimates and scales pictures to the page. Pictures and diagrams scale to fit a page. Mermaid diagrams and KaTeX formulas use the page tone and display alternative text when rendering fails. A picture, diagram or formula alone in its paragraph opens over the window with zoom; one in a line of text, a linked one and a reference-style picture do not. Other tall blocks can be clipped through a line. |
| Editor | Chapter search works on the current draft in Visual, Source, Split and Preview. Editing opens the first chapter in Visual. Chapters are listed and chosen by number and title. Visual supports tables, nested and task lists, quotes and code blocks. A link is made from selected or newly entered words and can lead to a chapter or a heading chosen by title. A picture is chosen from the thumbnails of the book or taken from a file, with a description, and put at the caret. The Contents section shows the contents and where they come from. The entries of a stored list are edited, added, nested and removed one by one, are kept in the order of the book, and are marked when they lead nowhere or are out of order. They follow their chapter when it moves or its file is renamed, and are removed with it. The Landmarks section marks where the text begins in a block of its own and adds, edits and removes landmarks of every kind of RFC 0001, chosen from a grouped list that says what each gives a reader. The picture gallery shows thumbnails and picture import offers encoding settings. Diagrams and Formulas have syntax-highlighted source dialogs that take most of the window, a preview beside the source in a wide window that fits the drawing or shows it at its size, and removal controls. Visual inserts figure references, and Preview and Split render them. Footnotes and reference definitions are edited in Source. Source and Split highlight Markdown syntax. The platform Save shortcut works while editing. A picture cannot be put into the text from Source, and choosing a contents entry opens its chapter at the top. Dropping a file on a chapter has not been tried outside of tests, which call the handler directly. |
| Settings | As designed. The size of the interface is applied when the slider is released, because it moves the slider. |
| Languages | English and Russian, chosen from the system at start or in the settings. The tests check the choice of the language, the plural forms and that every key has both texts, and run in English. The Russian screens were looked at in the pictures of the visual test at every width: every text is Russian but the names of formats and typefaces, the text of the books and an error message a scene makes up. A change of language leaves the messages already shown, the placeholders of a dialog that is open and the footnote labels of an open chapter in the previous language. An error quoted from mbook or mbook-converter stays in English. |
| Updates | The banner sits below the window controls, and update notifications appear at the bottom. The check and the installation are written and tested against scripted releases and signed archives made by the tests. The installer is compiled on macOS and Windows. |
| Release workflow | The workflow produced installers and update archives for v0.1.0. The Trusted Publishing step awaits its first run. The macOS and Windows x64 jobs make NASM available before building. The Android job has not run: it needs the secrets ANDROID_KEYSTORE and ANDROID_KEYSTORE_PASSWORD, which are not set. |
| Android | android.sh built a signed APK on macOS with NDK 30, build-tools 35 and OpenJDK 21. It was installed with adb on one phone with Android 16 (arm64, Mali-G615): it starts in about 0.3 s on Vulkan, shows the library in the compact layout with the bar of the page under the status bar, and loads the bundled emoji font. Tried by hand there, since the phone refuses input from adb: adding a book through the document picker of the system works, and so do the bar of a page under the status bar, notifications that fit the screen, the reader's swipe between chapters, and the footer of a scrolling text, with the text fading into the page behind it. Sharing through robius-share showed no sheet; through the activity of mbook-android the share sheet of the system opened. Opening a book from another app was tried with a VIEW intent for an mbook file in Downloads: the book was added and opened. Export on Android has not been tried. Copying to the clipboard of the system and pasting from it, through the clipboard feature of gpui-mobile, has not been tried on the phone: before it, Copy kept the text inside the application. The navigation bar of gesture navigation is reported as 0 px there, so its handle is drawn over the bottom bar. No iOS build exists. |
| Typeface | Literata and Noto Sans are bundled for offline rendering. System and installed family choices use the platform’s font catalogue. |
| Transitions | Reading controls fade if motion is enabled. Page turns are immediate by default and can use a slide when enabled. |
Where assistive technology gets less than Accessibility asks:
- The structure of a chapter is not reported. The Markdown view of GPUI Kit gives its headings, lists and tables no roles. The text of a chapter is one element with the article role, named by the title of the chapter.
- The language of a book is not reported: GPUI has no property for it.
- The link in the About dialog cannot be reached by keyboard: the link of GPUI Kit takes no focus.
- A picture cannot be opened larger from the keyboard: the pictures of a chapter take no focus, as its links do not. Once open, the viewer is used with keys alone.
- A few parts of Kit controls are reported without a role: the frame of a text field, the search field inside a select, the track of a slider. The controls they belong to have roles and names.
- The Kit's minimize, maximize, restore and close buttons lack roles in the headless tree. On Windows, GPUI handles their hit testing in the window's non-client area.
Testing
- Logic sits in models and in plain functions: the size class, the import state machine, the catalogue, progress, block offsets, the outline. Each has unit tests beside it.
- Models and views are tested in headless windows with the
test-supportfeature ofgpui-kit: a test imports a book built in a temporary root, opens it, edits it and saves it. - The rule of Threads is tested: with the background executor held back, a view must still draw, showing its loading state.
- In the unit tests
compute::spawndoes its work when its future is first polled, on the thread that polls it, so the test executor of GPUI orders all work as it did before the pool. The pool itself is tested inshared::compute. The visual test runs the real pool, and waits until it has ended the work of a step before it draws. - Every layout is drawn at 390, 800 and 1280 px of width. With the Cargo
feature
visual,cargo test -p mbook-ui --features visual --test visualrenders every screen without a window, in these widths and in a light and a dark page tone, intotarget/visual/: 160 pictures for a person to look at. WithMBOOK_VISUAL_LANGUAGE=ruit draws them in Russian, intotarget/visual/ru/; the scenes reach their controls by the keys of their names, so every one is drawn in either language. The renderer exists on macOS; elsewhere the test says so and passes. - Accessibility is tested, not reviewed:
- a unit test computes the contrast of every pair of tokens that Accessibility puts together;
- for each screen a test reads the accessibility tree of a headless window and checks that every application control has a role and a name. The window buttons drawn by GPUI Kit are outside this check;
- for each screen a test completes its main task with keys alone: add a book, open it, move to another chapter, edit and save.
Reading verification
| Bundled font | Version | Source | License and shipped instances |
|---|---|---|---|
| Literata | 3.103 | Google Fonts, Literata | SIL OFL 1.1, Literata-OFL.txt. TrueType, 12-point optical cut, upright and italic at 400/500/700. |
| Noto Sans | 2.015 | Google Fonts, Noto Sans | SIL OFL 1.1, NotoSans-OFL.txt. TrueType, standard width, upright and italic at 400/500/700. |
The original copyright and license metadata remains in the embedded files.
The static instances were generated with FontTools and use consistent
family names for native weight matching. The assets and notices are under
crates/mbook-ui/assets/fonts. Each face’s character map was checked for
the mixed-script sample, including combining acute accents and the ruble
sign.
| Tone | Body | Muted | Link | Selected body | Selected link | Search body | Search link | Focus accent on page |
|---|---|---|---|---|---|---|---|---|
| Paper | 13.20 | 5.34 | 8.09 | 10.29 | 6.30 | 12.10 | 7.41 | 5.62 |
| Neutral | 14.48 | 5.84 | 7.86 | 11.04 | 5.99 | 12.62 | 6.85 | 5.91 |
| Sepia | 10.36 | 5.27 | 8.08 | 8.13 | 6.34 | 10.70 | 8.35 | 4.99 |
| Night | 11.33 | 6.86 | 7.77 | 7.48 | 5.13 | 8.66 | 5.94 | 6.01 |
| High contrast | 21.00 | 8.06 | 16.01 | 19.56 | 14.91 | 15.39 | 11.73 | 6.18 |
Ratios use the WCAG 2.2 relative luminance calculation. Tests compare unrounded values. The first three columns use the page background. Chrome tests also cover on-accent labels, control outlines and focus against both chrome surfaces.
Run cargo test -p mbook-ui --features visual --test visual --locked to
capture 05c-reading-mode-* and 05d-reading-mode-enlarged-* in
target/visual. These open a Russian mbook fixture in the real reader.
The latter uses 44 logical px. The captures use a macOS headless renderer
on an Apple M5 Pro running macOS 26.6.2 at 2× density, with desktop and
phone-width viewports.
The first five full Russian prose lines inspected in the 1280 px Literata
capture contain 55–64 characters, including internal spaces. In the
390 px capture, the six full lines of the first paragraph contain
24–32 characters. The layout tests cover widths from 320 through 1920 logical px. The native font probe
checks distinct face IDs and the required glyphs for regular, medium, bold
and their italics. The visual command also writes
target/visual/reading-latency.csv with five first-frame samples each for
theme changes, 1 px text increases and page turns at 1280 × 780 logical px.
It measures dispatch and headless frame rendering on the CPU, rather than
display presentation. Five warm samples in a debug build gave median /
maximum times of 17.72 / 22.25 ms for themes, 17.80 / 21.34 ms for text
size, and 10.01 / 10.36 ms for page turns. The sample was the bundled
Russian fixture at 44 px, with page animation disabled. The timings do not
cover real-display latency or a cold open. The regression suite separately
exercises chapters of roughly 55,000 and 200,000 characters and retains a
test for switching layouts inside a long paragraph.
Remaining checks and limitations
- There are currently desktop shells only. The phone captures exercise the compact layout on macOS. Physical phone behavior, Dynamic Type, Android font scaling, Windows at 100% and 125%, and Linux are untested. Resize the native window through 320, 360, 390, 430, 768, 1280 and 1920 logical px, then repeat on each desktop backend at its system scale.
- VoiceOver and NVDA are untested. Open a book and use Tab, Shift+Tab, Escape, Home, End and Page Up/Down to read and operate Contents, Aa and Find. Check that focus remains visible, returns to its trigger and that the page is readable. The Markdown toolkit currently omits heading, list and book-language semantics. Native high-contrast preference mapping beyond the light/dark system preference is unverified. Browser zoom and CSS text-spacing overrides do not apply to the native app.
- Book-style first-line indent, language-aware hyphenation, and custom letter and word spacing are unimplemented. Footnote definitions render inline in the chapter. Bookmarks and user annotations are unimplemented.
- The chapter and source block survive reflow where the toolkit’s block map agrees with the book. The offset within a block is approximate, so text far into a very long paragraph and mixed-height blocks can move by more than one rendered line. In paged mode, oversized lists and tables can still split through a line. Test by switching layouts halfway through a long paragraph and comparing the first visible phrase before and after.
- The font assets are local. Test a missing family by selecting one on another system, removing it, and reopening the same catalogue offline. Slow network, platform font-registration failure and cold-start flash were not verified on physical displays.
User-validation pilot
Recruit 8–12 readers across ages, routine text-enlargement preferences and desktop and phone use. When a phone build is available, compare Paper / Literata with Neutral / Noto Sans in separate 20–30 minute sessions, with a break. If Night is included, use a third session. Counterbalance order and assign comparable unfamiliar Russian passages of similar length and difficulty. Record device, scale, actual size, lighting, order and baseline discomfort. Collect discomfort on a 0–10 scale before and after, comfort and willingness to continue on a 1–7 scale after, several comprehension questions, lost-line incidents, setting changes and open comments. Treat reading speed as secondary. Use observations to refine defaults while retaining individual settings.
Design
Which decisions are confirmed, which crates the application is built on, what the design costs, and the choices behind it.
What is settled
The format author settled the points below on 2026-11-21. Every other detail of this section is proposed, and listed under Settled and open questions where a choice is open.
| Decision | Status |
|---|---|
The interface is built with gpui-kit on the gpui-fast engine | Confirmed |
The allocator is mimalloc3 | Confirmed |
| The application has a library of books | Confirmed |
It opens every format mbook-converter converts | Confirmed |
| A book that is not mbook is converted when it is opened, and the result is kept in the library | Confirmed |
| A book can be edited | Confirmed |
CPU-bound work runs on a pool of rayon with half the threads of the system, which the background executor awaits | Confirmed on 2026-11-24 |
| The prototype is modelled on Apple Books for the Mac | Confirmed |
| The layout is responsive, so that desktop and mobile share it | Confirmed |
The directories of the application come from the dirs crate | Confirmed |
Updates are installed from GitHub releases with the self_update crate | Confirmed |
The crate is mbook-ui, and the application is called mbook | Confirmed |
| An import leaves the original file where it is; the library gets a copy | Confirmed |
A book whose id is already in the library is not added again; the existing one is opened | Confirmed |
Pictures are decoded by avif-decode; the package requires Rust 1.100 | Confirmed |
| Literata is the default reading choice and the typeface is configurable | Confirmed. Literata and Noto Sans are bundled. |
| The modules follow Feature-Sliced Design | Confirmed |
| A release is a tag on GitHub; its binaries are built by a workflow started by hand for that tag | Confirmed |
| Releases are signed with keys generated for the project and kept as secrets of the repository | Confirmed |
| The icon is an open book on the navy of the design documents | Confirmed |
| Saving an edit replaces the book in the library | Confirmed |
The editor accepts pictures that are not AVIF and encodes them with the image crate | Confirmed |
The catalogue is a redb database | Confirmed |
| The application is built for Android; there it runs on gpui-pre with the platform of gpui-mobile, while the desktop stays on GPUI Fast | Confirmed on 2026-11-23 |
| The release workflow builds an APK | Confirmed on 2026-11-23 |
Dependencies
Checked on 2026-11-21 against crates.io. A crate only this package uses is declared in its own manifest; the manifest of the workspace keeps what several packages share.
| Crate | Version, last release | License | Used for |
|---|---|---|---|
gpui-kit, feature gpui-fast | 0.10.0, 2026-11-16 | Apache-2.0 | The interface; brings GPUI Fast 0.1 |
rfd | 0.17.2 | MIT | Native book and picture pickers with extension filters |
robius-share, desktop only | 0.3.0, 2026-07-18; Project Robius, repository pushed 2026-11-13 | MIT | The share sheet of the platform; Rust 1.77. On Windows it brings windows 0.56 beside the versions GPUI uses |
mimalloc3 | 0.1.61, 2026-11-17 | MIT | The allocator of the binary |
dirs | 7.0.0, 2026-09-05 | MIT OR Apache-2.0 | The roots on desktop |
self_update | 1.3.3, 2026-10-27 | MIT | Updates; Rust 1.88 |
redb | 5.0.0, 2026-11-18 | MIT OR Apache-2.0 | The catalogue; Rust 1.90 |
avif-decode | 3.0.0, 2026-09-20 | BSD-3-Clause | Decoding pictures; Rust 1.98 |
image | The version and features of the workspace, with nasm on ARM; GPUI brings the same crate | MIT OR Apache-2.0 | Decoding and AVIF encoding of pictures added in the editor; scaling |
futures | already in the tree of GPUI | MIT OR Apache-2.0 | The channel of the editing task; the future of work on the pool |
rayon | The version of the workspace; already in the tree of image, ravif and rav1e | MIT OR Apache-2.0 | The pool of CPU-bound work |
tree-sitter-mermaid, codebook-tree-sitter-latex | 0.3.5 and 0.6.1 | MIT | Syntax highlighting in the Mermaid and KaTeX source dialogs |
rust-i18n | 4.2.4, 2026-09-29; Longbridge, the authors of GPUI Component | MIT | The texts of locales/ and the language of the process; GPUI Component already uses it, so its controls and the application share one language |
sys-locale | 0.3.2, 2024-11-01; 1Password | MIT OR Apache-2.0 | The languages of the system in order of preference, on every platform including Android |
icu_plurals, icu_locale_core | 2.4.0, 2026-10-22; ICU4X of Unicode; icu_locale_core already in the tree | Unicode-3.0 | The plural category of a count |
uuid, tempfile, thiserror, markdown | The versions of the workspace | Keys; files of imports; errors; block offsets | |
gpui-pre-mobile (gpui-mobile), Android only | Commit d8945a8 of longbridge/gpui-mobile#56, opened 2026-11-11; repository pushed 2026-11-03 | GPL-3.0-or-later OR AGPL-3.0-or-later OR Apache-2.0, used under Apache-2.0 | The GPUI platform of Android: window, input, renderer, document picker and, with its clipboard feature, the clipboard of the system; its Java activities and emoji font go into the APK |
android-activity, android_logger, log (in mbook-android) | 0.6, 0.15, 0.4 | MIT OR Apache-2.0 | NativeActivity glue that calls android_main; logcat |
jni, log, Android only | 0.22, the version gpui-mobile uses; 0.4 | MIT OR Apache-2.0 | Asking the activity for the documents it received; logging a Java exception |
windows-registry, Windows only | 0.6.1, of windows-rs; already in the tree of GPUI | MIT OR Apache-2.0 | Registering the book formats for the current user; a safe API, so the crate keeps unsafe_code forbidden |
gpui-mobile is taken from its repository, pinned to a commit: its only release on crates.io, 0.1.0, is built for gpui-pre 0.3.5, and GPUI Kit 0.10 pins gpui-pre 0.3.12. The pull request moves it to 0.3.12 without changes to its code. Its default features bring about thirty platform modules (camera, contacts, location, notifications…); they are off. Its README calls it an experimental platform release: composition through the keyboard of the system and the lifecycle of an activity are incomplete.
avif-decode brings rav1d (BSD-2-Clause, a port of dav1d to Rust; last
release 1.1.0 of 2025-05-07) and avif-parse (MPL-2.0). The assembly
enabled by avif-decode for x86 and x86-64 requires NASM at build time.
The font sources and notices are listed in
Reading verification.
Ruled out:
| Crate | Reason |
|---|---|
image with avif-native | Needs the C library dav1d on the machine that builds and on the one that runs |
zenavif, rav1d-safe | AGPL-3.0, or a commercial license |
rusqlite | See Rationale and alternatives |
kael_share 0.4.1 | Calls a named sharing service directly instead of showing the picker, and shares no file on Windows |
istmo-share 0.1.1-alpha | An alpha whose API changes between releases; needs the window registry and runtime of the istmo framework |
gpui-mobile 0.1.0 on crates.io (itsbalamurali/gpui-mobile) | Declares no dependency, not even on GPUI: it implements no platform for the GPUI of the Kit |
cargo-apk, xbuild | cargo-apk is deprecated in favour of xbuild and packs no Java code, which the activities of gpui-mobile are; xbuild packs it through Gradle. android.sh compiles them with the tools of the SDK |
fluent-bundle | A second system of translation beside the rust-i18n of GPUI Component, with a language of its own to keep in two places; its plurals are what icu_plurals gives |
gettext-rs | Binds the C library gettext, which a build for Windows and Android must bring |
intl_pluralrules 7.0.2 | No release since 2022-10-19; ICU4X, which follows the CLDR, is already in the tree |
cargo-ndk | Sets the same four variables android.sh sets; a tool to install on every machine for no other gain |
| A Gradle project | Gradle and the Android Gradle plugin are downloaded on every clean build, for an APK of one activity without AndroidX |
Drawbacks
- A large dependency. GPUI and its component library are far larger than the rest of the workspace together, and the engine is young: GPUI Fast is at version 0.1.
- The checks of the repository grow. Clippy, tests and documentation of the workspace now build GPUI, and continuous integration needs a display server's libraries on Linux.
- An editing session holds the whole book decoded, as
Bookdoes. A comic of several hundred pages may not fit on a phone. - Accessibility depends on a young integration. What a screen reader hears is what GPUI and AccessKit pass on; a gap there is a gap here.
- A running conversion cannot be stopped, only ignored. Neither can the encoding of a picture, which takes seconds for a large one.
- Large blocks. A page boundary through an oversized code block, list or table is limited by the geometry the Markdown view exposes.
- Two copies of a book after import: the original and the one in the library.
- A stored place is approximate after an edit of its chapter.
- A second minimum Rust version in the workspace.
- Two engines. Android runs on gpui-pre, the desktop on GPUI Fast. The code is the same and the tests run on GPUI Fast only; a difference of the engines shows on a phone first.
- A platform from a pull request. gpui-mobile is a pinned commit of an open pull request, an experimental release by its own account, mostly the work of one author. Its Java activities and emoji font are taken from its example application, whose layout may change.
- Android limits listed under Android: arm64 only, a theme that does not work for API 36, a black screen after the activity is recreated.
- A content provider of this repository lends shared files on Android: a small amount of Java to keep, because the FileProvider of AndroidX needs Gradle.
Rationale and alternatives
| Decision | Chosen | Rejected | Why |
|---|---|---|---|
| Toolkit | GPUI Kit on GPUI Fast | Decided by the format author. | |
| Engine on Android | gpui-pre, with the platform of gpui-mobile | GPUI Fast with a platform of this repository | GPUI Fast has no Android platform; for iOS its platform crate takes the iOS crate of gpui-pre. gpui-mobile is the only Android platform for GPUI and is written for gpui-pre; writing one is most of gpui-mobile again. The application compiles and its tests pass on gpui-pre unchanged. |
| The Android entry point | A crate of its own, mbook-android, with the lints of the workspace but unsafe_code denied, and one #[expect] on android_main | android_main in mbook-ui; the host-driven entry point of gpui-mobile | #[unsafe(no_mangle)] is unsafe code, which mbook-ui forbids, and a forbidden lint cannot be expected. The host-driven entry point survives a recreated activity but needs JNI functions of this crate and an activity of its own. |
| Packing the APK | android.sh: javac, d8, aapt2, zipalign and apksigner of the SDK | Gradle; cargo-apk; xbuild | See Ruled out under Dependencies. |
| System bars on Android | Opt out of the edge-to-edge layout of API 35, and pad views by the bars gpui-mobile measures | targetSdkVersion 34; JNI code of this crate that reads WindowInsets | gpui-mobile reads the bars from the content view, which edge-to-edge makes the whole screen. API 34 leaves the current target of Google Play behind; JNI code needs a second Java activity. |
| Export on Android | The converted file goes to the share sheet | prompt_for_new_path; the save picker of gpui-mobile | gpui-mobile answers prompt_for_new_path with no path, and its save picker returns a content: URI, which std::fs cannot write. |
| Clipboard on Android | The clipboard feature of gpui-mobile, with its GpuiClipboard packed into the APK; the edit menu of GPUI Kit | gpui-mobile without the feature; a clipboard class of this repository; the floating text toolbar of Android (ActionMode) | Without the feature gpui-mobile keeps copied text in a string of the process, so Copy reached no other app. The class of gpui-mobile is the twenty lines a class of this repository would be. The toolbar of Android belongs to a View that owns the selection; GPUI draws the text itself, so it would need the bounds of the selection and every command passed through JNI, for the same four commands the menu of the Kit already offers on every platform. |
| Share on Android | MbookActivity.share with MbookFiles, a read-only content provider of this repository, started on the thread of the activity without waiting | robius-share, as on the desktop; the share module of gpui-mobile; the FileProvider of AndroidX | robius-share showed no sheet on the phone it was tried on: it copied the file to Download/Robius Share/, left it there, and blocked the thread of the interface on a latch until the thread of the activity had run, which android-activity's handshakes can make wait for the interface. It also never clears a Java exception it causes. The share module of gpui-mobile shares text only, and the FileProvider of AndroidX needs Gradle. |
| A sideways swipe over a scrolling text | Steps to the next or the previous chapter; one swipe steps once, and a movement mostly up or down never does | Nothing; a tap at the edge as for a page | A phone reader expects a swipe to turn; the chapter is the page of a scrolling text. GPUI reports a pan as scrolling, so the same code serves a trackpad. |
| The footer of a scrolling text | Fixed over the text, which runs under it and fades into the paper behind the controls | Its room kept below the text; over the text only while the controls are shown; fully transparent | On a phone the kept room was a sixth of the screen with nothing in it, and a footer that hid left no way to the next chapter while scrolling. Fully transparent, its arrows and status were lost in the lines under them. The text view of the Kit cannot pad the end of its list, so the text is followed by an empty block as tall as the footer: scrolled to its end, the last line stops above the controls. A paged text keeps the room, since its pages are cut to the height above the footer. |
| Bringing the hidden controls back while scrolling | Scrolling back, and the end of a chapter | Only a tap or the pointer | A reader who wants the controls scrolls back, as in other readers; at the end of a chapter the next one is what a reader wants. |
| A tap or a swipe on something over the text | Belongs to what is on top: the reader checks the hitbox of its text at the point | The bounds of the text | A notification lies over the text; a tap on it turned the page and a swipe over it changed the chapter. |
| Dismissing an announcement on a touch screen | A tap, or a sideways swipe over it | Its close button; hiding it after a time | The close button of the Kit shows on hover only, which a touch screen has not. A time limit would fail WCAG 2.2.1 for a message the user did not cause. |
| Registering the formats on Windows | The application writes them to the registry of the current user at each start | Entries of the installer; nothing | The installer of cargo-bundle cannot hold file types, and writing the WiX source of the installer by hand is a second build to keep. The price is that uninstalling leaves the entries, which then point at a missing program. |
| Registering the formats other than mbook | Open with and an alternative handler, never the default | Making mbook the default for EPUB, PDF and the rest | The user chose a program for those; mbook converts them on the way in. |
| Documents handed to the Android activity | Copied into the cache by an activity of this repository, and taken by the interface once a second | A JNI function the activity calls; the deep links of gpui-mobile | A JNI function is a second unmangled entry point in mbook-android; the deep links of gpui-mobile go to its example activity and carry URLs, not readable files. |
| Where another app's document is received on Android | OpenActivity, without a window or native code, which starts MbookActivity in its own task | The intent filters on MbookActivity | An app that starts the receiver for a result, as Telegram does, gets a second MbookActivity in its own task, which cannot run the interface and closes; the document was imported, but mbook did not come up. |
| A destroyed activity on Android | Ends the process | Keeping the process, as Android does | GPUI cannot start again in a process on the thread of a new activity, and the window of that activity stays black. The price is a fresh start after the language of the system changes. |
| The sections of the editor in a compact window | A sheet from a menu button beside Back, as in a medium window | A screen of its own that Back returns to | Back that first opened the list and only then left the editor read as a bug; a menu button says what it opens. |
| Translations | rust-i18n with a YAML file per part of the application, keys named by part and purpose; counts by the plural rules of the CLDR | Fluent; gettext; the English text as key | GPUI Component translates its controls with rust-i18n in a language of the process; a second system would need the language set twice. A key by purpose keeps a reworded English text from breaking its translations. |
| The language at start | The first language of the system the interface has, else English | The first language of the system, else English; English always | A Russian speaker whose system lists German first still gets Russian; a language without a translation would be all fallback. |
| The language setting | System language, then every language named in itself; stored by its code, no row while it follows the system | The names in the current language | A person who cannot read the current language finds theirs. No row keeps a change of the system's language working, as for the page tone. |
| The language in tests | Never set: the tests run in English and a test checks the language Appearance chooses, not the text | Setting it per test | The language of rust-i18n belongs to the process, and the tests of a crate run on several threads at once. |
| File picker filters | Native dialogs through rfd | GPUI file prompts | GPUI Kit 0.10 cannot pass extension filters to its platform picker. |
| Sending a book to other people | The share sheet of the platform through robius-share, with the mbook file | Share links of social networks; code of this crate on AppKit and WinRT | A share link carries text and a web address, and a library book has no address. Calling the platform directly needs unsafe, which the workspace forbids; robius-share keeps it in a maintained crate. |
| Export destination | Native save dialog and temporary file in the destination directory | Convert directly into the chosen file | The completed file is published in one operation and an existing file cannot be overwritten. |
| Landmarks section | The start in a block of its own, then the other landmarks as a list | One row for every kind, filled or empty; one list with the start among the rest | The start is the one landmark a reader meets without asking and a book has one. Twenty-two rows would bury the few places a book has. |
| Choosing the kind of a landmark | One menu grouped by what a reader looks for, the places looked up while reading first, with a line that says what the choice gives | An alphabetical menu; the identifiers of the format | Authors choose by purpose, and the line answers why a place is worth marking. |
| Landmarks in the reader | Listed under Go to above the entries in the contents panel, in the order of the book | A control of their own in the header; mixed among the entries | The header already holds five controls; the order of the book is the order RFC 0001 asks an application to list them in, and mixed in they would read as chapters. |
| Where a new book opens | The start landmark, only while no place is stored | Always at start; at the first chapter as before | A reader who has turned back to the title page expects to come back to it. |
| Position of a new landmark | In the order of the book among the others | At the end of the list | RFC 0001 makes the stored order the order an application lists them in. |
| Where CPU-bound work runs | The global pool of rayon with half the threads of the system and a stack of 16 MiB, through compute::spawn, whose future the background executor awaits; files, the catalogue and the network stay on the executor | Everything on the background executor of GPUI, the choice until 2026-11-24; a pool with every thread | Decided by the format author on 2026-11-24. The converter and rav1e compute on the pool of rayon anyway, so the work of the application joins them there instead of competing with them from the threads of the executor; half the threads stay for the executor, drawing and the system, so a long import does not slow the interface. The stack is larger than the 2 MiB of a thread of the standard library because parsing nested Markdown, laying out a diagram and encoding a picture recurse; it is reserved, not used. The price: the pool has no priorities, cancelling reaches work only before it starts, and an import has half the cores (the EPUB of the record below: 4.3 s on four threads, 2.6 s on eight). |
| What decides a layout | The width of the window | The platform | A narrow desktop window and a phone need the same layout; a platform test gives two code paths that drift apart. |
| Primary flow | Continuous vertical scrolling per chapter, with saved pagination as an alternative | Paged-only navigation | Scroll uses the native gesture path and leaves ordinary text free of page masks. |
| Reading | BookReader, lazily | Book for everything | A Book decodes every chapter and picture before the first line is shown. |
| Finding text in a book | Scan chapter text on demand | Index the whole book at open | Opening a book stays lazy. Search retains its current match and reads no pictures, with a chapter scan for each step. |
| Access to the reader | A snapshot on the main thread; the source behind a mutex for background tasks | Table lookups on the main thread | A lookup would wait for a mutex that a read holds during I/O. |
| Rendering Markdown | The Markdown view of GPUI Kit | A renderer of this crate | It virtualises, selects text, parses off the main thread, and is built on the same markdown crate as mbook. |
| Paginating a chapter | Break the chapter using the measured GPUI Kit blocks | A custom Markdown renderer or a fixed max_lines value | Measurements include proportional wrapping, headings and images while chapter-wide references stay with the Kit. |
| Whole-book page numbers | Combine measured chapters and estimates for the current layout | A fixed count in the file or a full-book layout pass on open | Reflow changes the rendered count. Estimates let the book open lazily, and each measured chapter replaces its estimate. |
| Seeking within the book | Use the decoded chapter lengths and an offset | Index every page before allowing a seek | Chapter lengths are already in the snapshot and locate a destination even before its chapter is measured. |
| Stored place | Chapter path and byte offset | Resource number and offset | Numbers change when a book is written again. |
| Creating a book | Create a titled book with one empty chapter and open it in the editor | Ask for chapter paths before opening the editor | A writer can start with the title and go straight to writing. The title and chapter paths remain editable. |
| Editing | One background task owns the Book; commands in order | A Book behind a mutex, one task per change | Separate tasks may run out of order: a save could miss the edit before it. |
| Visual chapter editing | Use the GPUI Kit block editor and restore intact source blocks with similar | Extend the inline Markdown projection | The block editor provides table and list structure, selection and undo. Restoring unchanged blocks protects source spelling and heading anchors. |
| How a chapter is named in the editor | Its number and the title of its first heading; the path beside it | The path alone | An author knows a chapter by its title. The path stays in sight because links and problems name it. |
| Adding a chapter | Ask for a title; propose the path | Ask for a path | The title is what the author has in mind, and it becomes the heading the contents are built from. The path can be changed afterwards. |
| Putting a picture into a chapter | One dialog in the chapter: the pictures of the book, or a file that is added on the way | Add the picture in Pictures first, then pick its path from a menu in the chapter | The second way takes three screens and needs the name of a file to be remembered. |
| Where chapter actions are | A menu with words: Move up, Move down, Rename the file, Remove the chapter | A row of icons beside the views | Arrows beside a title read as "previous" and "next". The actions are rare and one of them cannot be undone. |
| Where the contents are explained | A section of their own that shows them | Only the control that rebuilds them among the problems | An author who asks how to change the contents finds neither a list nor a rule otherwise. |
| The order of a stored contents list | The editor keeps it: an entry sits where its place is in the book | Controls that move an entry up and down | The format refuses a list that is not in reading order, so almost every move by hand would be a mistake to undo. A moved chapter takes its entries along, a removed one takes them away, and one control sorts a list that an edit of the text left out of order. |
| The level of a contents entry | Two menu items that move it in or out with the entries under it | A level number in the dialog | The level that is allowed depends on the entries around it. Moving in and out, as an outliner does, cannot produce a list the format refuses. |
| The places a link can lead to | Carried in the outline, from the anchors Book keeps | A public call of mbook that lists the contents | The API of mbook stays as it is. The price is that the rule which lists a heading is written here a second time, with a test. |
| Escaping the words the editor writes into Markdown | A function of this crate, tested by reading the result back with markdown | mdast_util_to_markdown 0.0.2 | That crate is a pre-release without the GFM extensions. mbook-converter escapes with a function of its own for the same reason (Dependencies); it is not public, and the API of mbook-converter stays as it is. A link needs none of it: the block editor types and links the words. |
| Where an edit is saved | Over the book in the library, by a rename | Always a new copy | Decided by the format author. The library is the working copy; the original file was never touched. |
| Catalogue | redb | SQLite through rusqlite | Decided by the format author. Pure Rust: nothing to cross-compile for a phone. The price is no SQL; a library is filtered in memory. |
| No catalogue; open every file at start | Reading places and settings need a store anyway, and a shelf of thousands should not wait for thousands of files. | ||
| Source of truth for metadata | The mbook files | The catalogue | An edit changes the file; a lost catalogue then costs no book. |
| Key of a book | A UUID made at import | The id of the metadata | That id is any string and may be edited. |
| Directories | dirs, handed in by the shell | Paths built in the library | Decided by the format author; handing them in keeps tests and mobile shells possible. |
| Installing updates | self_update, blocking transport on the background | Its asynchronous transport | Decided by the format author to use the crate. The blocking transport needs no Tokio runtime beside GPUI. |
| Update banner placement | Below the title bar | Above the whole page | Native macOS window controls stay at the top of the window when the banner appears. |
| AVIF decoder | avif-decode on rav1d | dav1d in C | Decided by the format author. No C toolchain; the same reason as for the encoder of mbook-converter. |
| Minimum Rust version | 1.100 for this package | The 1.89 of the workspace | Decided by the format author. avif-decode needs 1.98 and redb 1.90; an application is built by its maintainers, not by users of a library. |
| Typeface of books | Bundled Literata and Noto Sans, plus System and installed choices | Only installed families | Rendering is available offline on a fresh installation. |
| Building a release | A workflow started by hand for a tag | Building on every tag | Decided by the format author. The workflow publishes the libraries for the tag before building the application. |
| Drawing diagrams and formulas | Render source with the figure module of mbook-converter (merman and RaTeX), then give SVG to GPUI | Convert sources to AVIF; render with a web view | SVG lets the reader choose its own page colours and sizes. The source remains editable and rendering stays local. |
| Encoding the pictures of an import | mbook-converter with its rayon feature | Its default, one picture after another | Decided by the format author. An import of a 7 MB EPUB with 45 pictures took 2.6 s instead of 3.9 s on eight threads of an Apple M-series processor; the converter's own record has the details (Rationale). |
| Assembly of the AVIF encoder | The NEON assembly of rav1e on ARM (aarch64), through the nasm feature of image; pure Rust on x86 | Pure Rust everywhere; the assembly on x86 as well | Proposed, not yet confirmed by the format author. Importing a 7 MB EPUB with 45 pictures took 10.5 s on four cores of an Apple M-series processor without it and 5.5 s with it; a phone took about a minute. On ARM the feature needs only the C compiler, which the Android build has for its C dependencies already; on x86 it needs NASM, which the release builds install for rav1d but a contributor may not have. The price is an assembler step in the ARM builds, beside the "no C toolchain" reason of the AVIF decoder. The library mbook-converter stays pure Rust. |
| Pictures added in the editor | Encoded here, with image | A public encoder in mbook-converter | Decided by the format author. The API of mbook-converter stays as it is; the price is that quality and speed are written in two crates. |
| Size class under a scaled interface | Width divided by the scale | Width in pixels | At 200% a desktop window has room for the compact layout only; clipping or a horizontal scroll bar fails WCAG 1.4.10. |
| Reordering chapters | A drag, and "Move up" and "Move down" | A drag alone | WCAG 2.5.7: a drag needs an alternative. |
| Thumbnails | JPEG files in the cache | Decoding every cover at start | The shelf then needs no AVIF decoder to appear. |
| Making a picture of the text open larger | A block plugin of the chapter view that draws a picture alone in its paragraph as the Kit does, and answers a click | Wrapping each picture in a link of the text; a hit test over the whole text | GPUI Kit 0.10 lets no click reach an image of its Markdown view. A link would change the text that offsets, search and copying use; a hit test would need the bounds of the images, which the Kit does not give. The price is that a picture in a line of text does not open. |
| The preview in the dialog of a diagram or a formula | The drawing beside the source in a wide window, fitted into the room left by the source and enlarged up to twice, with Actual size to see a large one at its size in the text and scroll it | A fixed dialog of 570 pixels with the drawing under the source, at most 180 pixels high; the full-window viewer of the reader | A large diagram fitted into 180 pixels could not be read, and the source scrolled in a field of six lines. Beside the source, the drawing gets the height of the window while both stay in sight. A dialog cannot open the viewer of the reader over itself. |
| What the viewer shows of a picture | The picture decoded again at its own size, up to 16,000,000 pixels | The bitmap fitted to the column, scaled up | The point of the viewer is to see more than the column shows. |
| Where the viewer lives | In the reader page | In widgets | Only the reader opens it; a part of a screen moves to widgets when a second page needs it. |
| How often a figure is drawn for the viewer | At densities that are powers of two | At every zoom; once at the largest zoom | Every step would rasterise and keep a new image; one large raster costs memory at every zoom and blurs when reduced far. |
Prior art
| Application | Taken from it | Left behind |
|---|---|---|
| Apple Books for the Mac | Cover-first shelves, single-page reading with quiet controls, an always-visible page number, a reading position slider, and page tones | Store, two-page spreads, collections, and annotations |
| Calibre | A library that owns copies of the books; converting on import; an editor with source and preview | A database as the source of truth; a window per tool |
| Zed | Entities as models; tasks owned by their entity; nothing blocking on the main thread |
Settled and open questions
Proposed and not confirmed by the format author:
| Question | Proposed |
|---|---|
| How a row of the catalogue is encoded | The value types of redb, without a serialisation crate |
| Notarising the macOS build, and a certificate of an authority for Windows | Not done: the certificate is self-signed |
| A release for Linux | Not built |
| The limits of conversion and of the picture cache on a compact device | Not chosen |
| The Android package name | io.github.m_compressors.mbook: the identifier of the bundle, with _, since a package name has no - |
| The oldest Android | API 26, where Vulkan is part of the platform, as gpui-mobile chose |
| The architectures of the APK | arm64-v8a only |
| The keystore of the APK | A PKCS #12 keystore generated for the project, kept as the secret ANDROID_KEYSTORE; not yet generated |
| A pre-release on Android | Gets the versionCode of its release, so the release does not replace it; releases are tagged vX.Y.Z only |
| The formats registered | All of BOOK_FILE_EXTENSIONS, .zip and .txt among them; mbook owns .mbook only |
Needs a change outside this crate:
- Progress and cancellation of a conversion are
future possibilities of
mbook-converter; until then an import shows no percentage. The same holds for a picture being encoded in the editor.
The first version answered the questions a spike was to answer:
| Question | Answer |
|---|---|
| Do the macros of GPUI compile under the lints of the workspace? | Yes, with unsafe_code = "forbid" and Clippy's pedantic denied. |
| Does the Markdown view of GPUI Kit tell which block is at the top? | It lays out one item per top-level block, in the order of the source, but does not give its offset. The application keeps the offsets markdown finds and maps one to the other. |
| Does it reserve the size of a picture that is loading? | No: a pending picture is measured as a small square. The application hands it a transparent picture of the final size first. |
| Can GPUI announce a message, and give an element a language? | It has no live regions and no language. See Accessibility and What is implemented. |
| Is there a GPUI backend for Android? | Not for GPUI Fast. gpui-mobile is one for gpui-pre, and the application runs on it: checked on 2026-11-23 on a phone with Android 16. |
Not answered: how the Markdown view behaves with one chapter of several megabytes, and whether the system's setting for more contrast reaches the application.
Future possibilities
- Two-page spreads, which need two independently positioned columns.
- Scrolling from one chapter into the next.
- A shell for iOS. gpui-mobile has an iOS platform too; it needs an Xcode project and the scenes the iOS 27 SDK requires (longbridge/gpui-mobile#44).
- The insets of the system from gpui-mobile, which would lift the API 35 limit of the theme, and its host-driven entry point, which survives a recreated activity.
- Highlights, notes and bookmarks, stored beside the reading place.
- Collections in the library.
- A journal of unsaved edits, replayed after a crash.
- Undo for changes of structure.
- Links that follow a renamed chapter: the links of other chapters into it would be rewritten.
- Turning automatic contents into a list, for an author who wants to leave headings out of the contents.
- Showing where a picture is used, and offering to remove the ones no chapter refers to.
- Conversion progress and cancellation, when
mbook-converterhas them.