Define the behavioral contract for reading FictionBook (.fb2, .fbz, and .fb2.zip) documents while maximizing code reuse with the existing EPUB pipeline: - Support both uncompressed XML and ZIP-packed FB2 containers, selecting the first .fb2 entry (or first archive entry as fallback) and labeling .fb2.zip as FB2 in history. - Auto-detect BOM and XML prolog encodings (including legacy Cyrillic encodings via iconv/QStringDecoder) with UTF-8 fallback. - Expose base64 <binary> resources through the existing IByteSource and image://fb2/<id>?src=<filePath> provider infrastructure so EntryImageProvider and BookImageResolver work without format-specific branching. - Share CSS cascading, image URL resolution, and ~512-character ContentChunk partitioning with EpubReader via a unified DOM-to-chunk pipeline, mapping FB2 semantic elements (<title>, <subtitle>, <epigraph>, <cite>, <poem>/<stanza>/<v>, <text-author>, <empty-line/>, <emphasis>, <strikethrough>, and <stylesheet>) onto existing layout primitives.
315 lines
12 KiB
Plaintext
315 lines
12 KiB
Plaintext
-- allium: 3
|
|
-- fb2-format.allium
|
|
|
|
-- Scope: FB2 (FictionBook 2.0 / 2.1) e-book format support and shared DOM/CSS/chunking pipeline with EPUB
|
|
-- Includes:
|
|
-- - Registration of .fb2, .fbz, and .fb2.zip file formats in FormatRegistry and HistoryModel
|
|
-- - Raw XML and ZIP-compressed FB2 container loading and MD5 content hashing
|
|
-- - Character encoding detection (BOM and XML prolog encoding, including legacy Cyrillic encodings via iconv/QStringDecoder) with UTF-8 fallback
|
|
-- - Metadata extraction (<book-title>, <author> list formatting, <coverpage> with <binary> fallback)
|
|
-- - Embedded <binary> base64 image extraction via image://fb2/<binaryId>?src=<filePath>
|
|
-- - Shared DOM styling (<stylesheet type="text/css">), image URL resolution, FB2 semantic element mapping, and ContentChunk partitioning
|
|
-- Excludes:
|
|
-- - Multi-column <table> grid layout
|
|
-- - Knuth-Plass line-breaking internals and QQuickPaintedItem rendering
|
|
|
|
------------------------------------------------------------
|
|
-- Value Types
|
|
------------------------------------------------------------
|
|
|
|
value AuthorName {
|
|
first_name: String?
|
|
middle_name: String?
|
|
last_name: String?
|
|
nickname: String?
|
|
|
|
has_structured_name: first_name != null or middle_name != null or last_name != null
|
|
}
|
|
|
|
value BinaryResource {
|
|
id: String
|
|
content_type: String?
|
|
decoded_bytes: String
|
|
}
|
|
|
|
value ContentChunkValue {
|
|
section_href: String
|
|
blocks_count: Integer
|
|
word_count: Integer
|
|
char_count: Integer
|
|
unnested_containers: Integer
|
|
}
|
|
|
|
------------------------------------------------------------
|
|
-- Contracts
|
|
------------------------------------------------------------
|
|
|
|
contract SharedDomChunkPipeline {
|
|
cascade_and_chunk: (dom_root: Any, stylesheet_texts: List<String>, scheme: String, source_path: String, section_href: String, target_chars: Integer) -> List<ContentChunkValue>
|
|
|
|
@invariant DeterministicChunking
|
|
-- Given identical DOM structure, CSS rules, and target_chars (512),
|
|
-- produces identical ContentChunk sequences for both EPUB spine items and FB2 sections.
|
|
|
|
@guidance
|
|
-- Reuse the CSS cascade, image href/l:href/xlink:href rewriting (via ImageUrl::resolve),
|
|
-- and HtmlBlockParser::parseChunks logic across EpubReader and Fb2Reader.
|
|
}
|
|
|
|
------------------------------------------------------------
|
|
-- Enumerations
|
|
------------------------------------------------------------
|
|
|
|
enum Fb2ContainerKind { plain_xml | zip_archive }
|
|
|
|
enum Fb2LoadStatus { idle | loading_metadata | loading_full | loaded | failed }
|
|
|
|
enum HistoryFormatLabel { `FB2` | `FBZ` }
|
|
|
|
------------------------------------------------------------
|
|
-- Entities and Variants
|
|
------------------------------------------------------------
|
|
|
|
entity ReaderClient {
|
|
name: String
|
|
}
|
|
|
|
entity Fb2Book {
|
|
client: ReaderClient
|
|
file_path: String
|
|
extension_kind: `fb2` | `fbz` | `fb2.zip`
|
|
container_kind: Fb2ContainerKind
|
|
format_label: HistoryFormatLabel
|
|
status: Fb2LoadStatus
|
|
|
|
content_hash: String when status = loaded
|
|
title: String when status = loaded
|
|
authors: List<AuthorName> when status = loaded
|
|
author: String when status = loaded
|
|
cover_image_url: String? when status = loaded
|
|
chunks: List<ContentChunkValue> when status = loaded
|
|
binaries: List<BinaryResource> when status = loaded
|
|
error_message: String when status = failed
|
|
|
|
transitions status {
|
|
idle -> loading_metadata
|
|
idle -> loading_full
|
|
loading_metadata -> loaded
|
|
loading_metadata -> failed
|
|
loading_full -> loaded
|
|
loading_full -> failed
|
|
terminal: loaded, failed
|
|
}
|
|
|
|
expected_format_label:
|
|
if extension_kind = `fbz`: `FBZ`
|
|
else: `FB2`
|
|
}
|
|
|
|
------------------------------------------------------------
|
|
-- Config
|
|
------------------------------------------------------------
|
|
|
|
config {
|
|
target_chunk_chars: Integer = 512
|
|
max_heading_depth: Integer = 6
|
|
}
|
|
|
|
------------------------------------------------------------
|
|
-- Rules
|
|
------------------------------------------------------------
|
|
|
|
rule StartOpenFb2Book {
|
|
when: OpenFb2Requested(client, book)
|
|
requires: book.client = client
|
|
requires: book.status = idle
|
|
ensures: book.status = loading_full
|
|
}
|
|
|
|
rule StartLoadFb2Metadata {
|
|
when: LoadFb2MetadataRequested(client, book)
|
|
requires: book.client = client
|
|
requires: book.status = idle
|
|
ensures: book.status = loading_metadata
|
|
}
|
|
|
|
rule ResolveZipContainerEntry {
|
|
when: InspectZipArchive(client, book, archive_entries)
|
|
requires: book.client = client
|
|
requires: book.status in {loading_metadata, loading_full}
|
|
requires: book.container_kind = zip_archive
|
|
requires: archive_entries.count = 0
|
|
ensures:
|
|
book.status = failed
|
|
book.error_message = "Archive contains no readable FB2 entry"
|
|
@guidance
|
|
-- When archive_entries is non-empty, select the first entry ending with ".fb2"
|
|
-- (case-insensitive), or fall back to the first entry in the archive if none ends with ".fb2".
|
|
}
|
|
|
|
rule FailOnInvalidOrMalformedXml {
|
|
when: Fb2XmlParsed(client, book, is_well_formed_xml, root_tag_name)
|
|
requires: book.client = client
|
|
requires: book.status in {loading_metadata, loading_full}
|
|
requires: not is_well_formed_xml or root_tag_name != "FictionBook"
|
|
ensures:
|
|
book.status = failed
|
|
book.error_message = "Invalid or malformed FictionBook XML"
|
|
}
|
|
|
|
rule CompleteMetadataLoad {
|
|
when: Fb2MetadataExtracted(client, book, hash_md5, raw_book_title, filename_stem, parsed_authors, formatted_authors, resolved_cover_id, binary_resources)
|
|
requires: book.client = client
|
|
requires: book.status = loading_metadata
|
|
let effective_title =
|
|
if raw_book_title != "": raw_book_title
|
|
else: filename_stem
|
|
let cover_url =
|
|
if resolved_cover_id != null: build_fb2_image_url(resolved_cover_id, book.file_path)
|
|
else: null
|
|
ensures:
|
|
book.status = loaded
|
|
book.content_hash = hash_md5
|
|
book.title = effective_title
|
|
book.authors = parsed_authors
|
|
book.author = formatted_authors
|
|
book.cover_image_url = cover_url
|
|
book.chunks = []
|
|
book.binaries = binary_resources
|
|
@guidance
|
|
-- Author formatting: for each <author> in <title-info>, join non-empty
|
|
-- <first-name>, <middle-name>, <last-name> with spaces (falling back to <nickname>
|
|
-- if all three are empty); join multiple authors with ", ".
|
|
-- Cover resolution: take first <image> in <title-info><coverpage> (strip leading '#');
|
|
-- if absent, fall back to first <binary> whose id contains "cover" (case-insensitive)
|
|
-- and whose content-type starts with "image/" (or is empty).
|
|
}
|
|
|
|
rule CompleteFullOpenWithSections {
|
|
when: Fb2DocumentParsed(client, book, hash_md5, raw_book_title, filename_stem, parsed_authors, formatted_authors, resolved_cover_id, binary_resources, extracted_chunks)
|
|
requires: book.client = client
|
|
requires: book.status = loading_full
|
|
requires: extracted_chunks.count > 0
|
|
let effective_title =
|
|
if raw_book_title != "": raw_book_title
|
|
else: filename_stem
|
|
let cover_url =
|
|
if resolved_cover_id != null: build_fb2_image_url(resolved_cover_id, book.file_path)
|
|
else: null
|
|
ensures:
|
|
book.status = loaded
|
|
book.content_hash = hash_md5
|
|
book.title = effective_title
|
|
book.authors = parsed_authors
|
|
book.author = formatted_authors
|
|
book.cover_image_url = cover_url
|
|
book.chunks = extracted_chunks
|
|
book.binaries = binary_resources
|
|
@guidance
|
|
-- Decode XML bytes by detecting BOM or XML declaration encoding (including windows-1251,
|
|
-- koi8-r, cp866 via iconv/QStringDecoder), falling back to UTF-8.
|
|
-- Content order: prepend <description><title-info><annotation> (if present),
|
|
-- followed by all <body> elements in document order (including notes/comments bodies).
|
|
-- Start a new chunk at each <annotation>, <body>, and <section> boundary,
|
|
-- using the section's id attribute (or synthetic id like "annotation", "body-0/section-1")
|
|
-- as section_href, and partition sections exceeding config.target_chunk_chars (512).
|
|
-- Map FB2 tags:
|
|
-- <title> -> h1..h6 according to section nesting depth (capped at config.max_heading_depth = 6)
|
|
-- <subtitle> -> centered bold subheading
|
|
-- <epigraph>, <cite> -> blockquote container
|
|
-- <poem>, <stanza>, <v> -> indented verse blocks
|
|
-- <text-author>, <date> -> right-aligned italic paragraph
|
|
-- <empty-line/> -> vertical margin spacer
|
|
-- <emphasis> -> italic, <strikethrough> -> strikeOut
|
|
-- <stylesheet type="text/css"> -> cascaded via Css::StyleSheet
|
|
}
|
|
|
|
rule CompleteFullOpenWithEmptyBodyFallback {
|
|
when: Fb2DocumentParsed(client, book, hash_md5, raw_book_title, filename_stem, parsed_authors, formatted_authors, resolved_cover_id, binary_resources, extracted_chunks)
|
|
requires: book.client = client
|
|
requires: book.status = loading_full
|
|
requires: extracted_chunks.count = 0
|
|
let effective_title =
|
|
if raw_book_title != "": raw_book_title
|
|
else: filename_stem
|
|
let cover_url =
|
|
if resolved_cover_id != null: build_fb2_image_url(resolved_cover_id, book.file_path)
|
|
else: null
|
|
let fallback_chunk = ContentChunkValue{
|
|
section_href: book.file_path,
|
|
blocks_count: 1,
|
|
word_count: 0,
|
|
char_count: 0,
|
|
unnested_containers: 0
|
|
}
|
|
ensures:
|
|
book.status = loaded
|
|
book.content_hash = hash_md5
|
|
book.title = effective_title
|
|
book.authors = parsed_authors
|
|
book.author = formatted_authors
|
|
book.cover_image_url = cover_url
|
|
book.chunks = [fallback_chunk]
|
|
book.binaries = binary_resources
|
|
}
|
|
|
|
------------------------------------------------------------
|
|
-- Invariants
|
|
------------------------------------------------------------
|
|
|
|
invariant LoadedBookHasNonEmptyTitle {
|
|
for book in Fb2Books:
|
|
book.status = loaded implies book.title != ""
|
|
}
|
|
|
|
invariant FormatLabelMatchesExtension {
|
|
for book in Fb2Books:
|
|
book.format_label = book.expected_format_label
|
|
}
|
|
|
|
------------------------------------------------------------
|
|
-- Surfaces
|
|
------------------------------------------------------------
|
|
|
|
surface Fb2FormatReaderSurface {
|
|
facing client: ReaderClient
|
|
|
|
context book: Fb2Book where client = client
|
|
|
|
exposes:
|
|
client.name
|
|
book.status
|
|
book.file_path
|
|
book.format_label
|
|
book.content_hash when book.status = loaded
|
|
book.title when book.status = loaded
|
|
book.authors when book.status = loaded
|
|
book.author when book.status = loaded
|
|
book.cover_image_url when book.status = loaded
|
|
book.chunks when book.status = loaded
|
|
book.binaries when book.status = loaded
|
|
book.error_message when book.status = failed
|
|
|
|
provides:
|
|
OpenFb2Requested(client, book)
|
|
when book.status = idle
|
|
LoadFb2MetadataRequested(client, book)
|
|
when book.status = idle
|
|
InspectZipArchive(client, book, archive_entries)
|
|
when book.status in {loading_metadata, loading_full} and book.container_kind = zip_archive
|
|
Fb2XmlParsed(client, book, is_well_formed_xml, root_tag_name)
|
|
when book.status in {loading_metadata, loading_full}
|
|
Fb2MetadataExtracted(client, book, hash_md5, raw_book_title, filename_stem, parsed_authors, formatted_authors, resolved_cover_id, binary_resources)
|
|
when book.status = loading_metadata
|
|
Fb2DocumentParsed(client, book, hash_md5, raw_book_title, filename_stem, parsed_authors, formatted_authors, resolved_cover_id, binary_resources, extracted_chunks)
|
|
when book.status = loading_full
|
|
|
|
contracts:
|
|
fulfils SharedDomChunkPipeline
|
|
|
|
@guarantee UnifiedImageProviderScheme
|
|
-- All FB2 variants (.fb2, .fbz, .fb2.zip) resolve embedded <binary> images
|
|
-- via image://fb2/<binaryId>?src=<filePath> through IByteSource,
|
|
-- gracefully ignoring missing or corrupt <binary> references without failing open().
|
|
}
|