Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge PR #783

Brandon Thomas0e5dac86f169
diff --cc crates/engine/src/cmd/datamerge/mod.rs
index eda169b12,4c258f1c9..c54dfa9b0
--- a/crates/engine/src/cmd/datamerge/mod.rs
+++ b/crates/engine/src/cmd/datamerge/mod.rs
@@@ -767,19 -767,23 +767,26 @@@ fn read_path(path: &str) -> std::result
read_path_capped(path, MAX_DATA_FILE_BYTES)
}
- fn read_path_capped(path: &str, cap: u64) -> std::result::Result<Vec<u8>, String> {
+ /// The file at `path`, refused when it is larger than `cap` bytes. The read itself stops past
+ /// `cap`, so a device or a file that grows while it is read can't exhaust memory.
+ pub(crate) fn read_path_capped(path: &str, cap: u64) -> std::result::Result<Vec<u8>, String> {
- use std::io::Read;
+ let too_big = || format!("{path}: the file is larger than {} MiB", cap / (1024 * 1024));
- let missing = |e: std::io::Error| {
- if e.kind() == std::io::ErrorKind::NotFound { format!("{path}: the file is missing") } else { format!("{path}: {e}") }
+ match crate::io::metadata(path) {
- Ok(m) if m.len() > cap => return Err(format!("{path}: the data file is larger than {} MiB", cap / (1024 * 1024))),
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err(format!("{path}: the data file is missing")),
++ Ok(m) if m.len() > cap => return Err(too_big()),
++ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err(format!("{path}: the file is missing")),
+ _ => {}
+ }
+ // The roots' own message when they refuse the path.
+ crate::file_access::check_read(path)?;
- match crate::io::read(path) {
- Ok(b) => Ok(b),
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(format!("{path}: the data file is missing")),
- Err(e) => Err(format!("{path}: {e}")),
++ let b = match crate::io::read_capped(path, cap) {
++ Ok(b) => b,
++ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err(format!("{path}: the file is missing")),
++ Err(e) => return Err(format!("{path}: {e}")),
+ };
- if std::fs::metadata(path).map_err(missing)?.len() > cap {
- return Err(too_big());
- }
- let mut b = Vec::new();
- std::fs::File::open(path).map_err(missing)?.take(cap.saturating_add(1)).read_to_end(&mut b).map_err(missing)?;
+ if b.len() as u64 > cap {
+ return Err(too_big());
}
+ Ok(b)
}
fn parent_dir(path: &str) -> Option<PathBuf> {
diff --cc crates/engine/src/cmd/export.rs
index 09fdea678,c29a3a66e..f2f014c8b
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@@ -12,7 -12,7 +12,7 @@@ pub fn specs() -> Vec<CommandSpec>
"{path?, pages?: \"1-3,5\" | [1,3] (1-based positions; default all), flatten?: high|medium|low|ppi (Transparency Flattener: spreads with transparency are rasterised), spreads?: bool, fullScreen?: bool, bookmarksPanel?: bool, pageLayout?: single|continuous|twoUp|twoUpCover|twoUpContinuous, view?: fitPage|fitWidth|actual, advanceSeconds?: number (interactive PDF), bleed?: bool (document bleed), marks?: bool | {crop?, bleed?, pageInfo?, weight?, offset?}, standard?: \"none\"|\"x4\"|\"a2b\", compressImages?: bool, tagged?: bool (structure tree: stories as paragraphs, figures with alt text), media?: bool (interactive: embed placed video and sound), title?, author?} → {path, bytes, pages, warnings} (no path: {base64, …})",
has_doc, export_pdf),
cmd!(noundo "file.exportEpub", "Export EPUB (Reflowable)…", ["File"], None,
- "{path?, title?, author?, language?: \"en\", tocTitle?: str (the table of contents' title; from the language by default), cover?: bool (the first page as the cover image), embedFonts?: bool (package the stylesheet's fonts whose licence allows it, whole files), fixedLayout?: bool (pre-paginated: each page as an image with its text)} → {path, bytes, warnings} (no path: {base64, bytes, warnings}); warnings name images without alt text, exported as decorative, and fonts that could not be embedded",
- "{path?, title?, author?, language?: \"en\", identifier?: str (dc:identifier; a stable urn:uuid by default), coverImage?: path (a PNG or JPEG as the cover), cover?: bool (the first page as the cover image), fixedLayout?: bool (pre-paginated: each page as an image with its text)} → {path, bytes} (no path: {base64, bytes})",
++ "{path?, title?, author?, language?: \"en\", identifier?: str (dc:identifier; a stable urn:uuid by default), coverImage?: path (a PNG or JPEG as the cover), tocTitle?: str (the table of contents' title; from the language by default), cover?: bool (the first page as the cover image), embedFonts?: bool (package the stylesheet's fonts whose licence allows it, whole files), fixedLayout?: bool (pre-paginated: each page as an image with its text)} → {path, bytes, warnings} (no path: {base64, bytes, warnings}); warnings name images without alt text, exported as decorative, and fonts that could not be embedded",
has_doc, export_epub),
cmd!(noundo "file.exportFixedEpub", "Export EPUB (Fixed Layout)…", ["File"], None,
"{path?, title?, author?, language?} — pre-paginated EPUB → {path, bytes} (no path: {base64, bytes})",
@@@ -176,21 -130,27 +176,35 @@@ fn export_epub(s: &mut Session, p: &Val
let mut rr = designcraft_render::Renderer::new();
rr.threads = designcraft_render::default_threads();
let ropts = designcraft_render::RenderOptions { printing_only: true, ..Default::default() };
+ let mut warnings: Vec<String> = Vec::new();
- let cover = (want_cover && !fixed).then(|| rr.render_page(&st.doc, &s.cache, 0, 2.0, false, &ropts).map(|img| img.to_png())).flatten();
+ // A cover image file (PNG or JPEG), else the first page rendered when `cover` asks for it.
+ let cover = match p.get("coverImage").and_then(Value::as_str).filter(|_| !fixed) {
+ Some(path) => Some(super::datamerge::read_path_capped(path, super::datamerge::MAX_IMAGE_FILE_BYTES).map_err(crate::EngineError::Other)?),
+ None => (want_cover && !fixed).then(|| rr.render_page(&st.doc, &s.cache, 0, 2.0, false, &ropts).map(|img| img.to_png())).flatten(),
+ };
+ if let Some(c) = &cover
+ && !(c.starts_with(b"\x89PNG") || c.starts_with(&[0xFF, 0xD8, 0xFF]))
+ {
+ return Err(crate::EngineError::Other("the cover image must be a PNG or JPEG file".into()));
+ }
let opts = designcraft_epub::EpubOptions {
title: p.get("title").and_then(Value::as_str).map(str::to_string),
author: p.get("author").and_then(Value::as_str).map(str::to_string),
language: p.get("language").and_then(Value::as_str).unwrap_or("en").to_string(),
- identifier: None,
+ identifier: p.get("identifier").and_then(Value::as_str).map(str::to_string),
cover,
+ toc_title: p.get("tocTitle").and_then(Value::as_str).map(str::to_string),
+ generic_families: generic_families(&st.doc),
+ fonts: if p.get("embedFonts").and_then(Value::as_bool).unwrap_or(false) && !fixed {
+ embedded_fonts(&st.doc, &mut warnings)
+ } else {
+ Vec::new()
+ },
+ // The export time; on the web the document's own save time stands in.
+ #[cfg(not(target_arch = "wasm32"))]
+ modified: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok().and_then(|d| i64::try_from(d.as_secs()).ok()),
+ #[cfg(target_arch = "wasm32")]
+ modified: None,
};
if fixed {
let d = &st.doc;
@@@ -732,64 -686,30 +746,88 @@@ mod text_tests
assert!(p1.contains("width=612, height=792") && p1.contains("Page one words"), "{p1}");
}
+ /// #775: the fallback follows the font's class, and embedFonts packages the stylesheet's fonts
+ /// (and reports those it can't).
+ #[test]
+ fn epub_font_fallbacks_and_embedding() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 1})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Sans", "chars": {"fontFamily": "Source Sans 3", "fontStyle": "Regular"}})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Gone", "chars": {"fontFamily": "No Such Font Family", "fontStyle": "Regular"}}))
+ .unwrap();
+ s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "Words", "caret": false})).unwrap();
+ let r = s.execute("file.exportEpub", &json!({})).unwrap();
+ let mut z = unzip(r["base64"].as_str().unwrap());
+ let css = read(&mut z, "OEBPS/style.css");
+ assert!(css.contains("font-family: \"Source Sans 3\", sans-serif;"), "{css}");
+ assert!(!css.contains("@font-face") && r["warnings"] == json!([]), "nothing embedded unless asked");
+ let r = s.execute("file.exportEpub", &json!({"embedFonts": true})).unwrap();
+ let mut z = unzip(r["base64"].as_str().unwrap());
+ let css = read(&mut z, "OEBPS/style.css");
+ assert!(css.contains("@font-face { font-family: \"Source Sans 3\"; src: url(\"fonts/"), "{css}");
+ let opf = read(&mut z, "OEBPS/content.opf");
+ let font = opf.split("href=\"fonts/").nth(1).and_then(|r| r.split('"').next()).map(|n| format!("OEBPS/fonts/{n}"));
+ assert!(font.as_ref().is_some_and(|f| z.by_name(f).is_ok_and(|e| e.size() > 1000)), "{opf}");
+ let warnings = r["warnings"].as_array().unwrap();
+ assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("No Such Font Family")), "{warnings:?}");
+ let html = s.execute("file.exportHtml", &json!({})).unwrap()["text"].as_str().unwrap().to_string();
+ assert!(html.contains("\"Source Sans 3\", sans-serif;"));
+ }
+
+ /// A font whose licence allows embedding bitmaps only (fsType bit 9) is not packaged whole,
+ /// and a Semibold style asks for the Semibold face's weight, not Bold's.
+ #[test]
+ fn epub_embedding_follows_bitmap_only_licences_and_weights() {
+ use designcraft_fonts::testing::{font_with, with_fs_type};
+ const BITMAP: &str = "DocFont Epub Bitmap Only";
+ for fs_type in [0x0200, 0x0208] {
+ designcraft_fonts::FontDb::global()
+ .add_font(with_fs_type(font_with(&format!("{BITMAP} {fs_type:04x}"), &['W']).unwrap(), fs_type).unwrap());
+ }
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 1})).unwrap();
+ for fs_type in [0x0200, 0x0208] {
+ let family = format!("{BITMAP} {fs_type:04x}");
+ s.execute("style.paragraph.create", &json!({"name": family, "chars": {"fontFamily": family, "fontStyle": "Regular"}})).unwrap();
+ }
+ s.execute("style.paragraph.create", &json!({"name": "Semi", "chars": {"fontFamily": "Source Sans 3", "fontStyle": "Semibold"}})).unwrap();
+ s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "Words", "caret": false})).unwrap();
+ let r = s.execute("file.exportEpub", &json!({"embedFonts": true})).unwrap();
+ let mut z = unzip(r["base64"].as_str().unwrap());
+ let css = read(&mut z, "OEBPS/style.css");
+ assert!(!css.contains(&format!("@font-face {{ font-family: \"{BITMAP}")), "{css}");
+ let warnings = r["warnings"].to_string();
+ for fs_type in [0x0200, 0x0208] {
+ assert!(warnings.contains(&format!("{BITMAP} {fs_type:04x} Regular`: its licence doesn't allow embedding")), "{warnings}");
+ }
+ let semi = css.lines().find(|l| l.contains(".semi {")).unwrap_or_default();
+ assert!(semi.contains("font-weight: 600;"), "{css}");
+ }
+
+ /// #771, #773: a cover image file and an identifier through the command; the package's
+ /// modified time is the export's.
+ #[test]
+ fn epub_cover_image_file_and_identifier() {
+ let dir = std::env::temp_dir().join(format!("dc-epub-cover-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let jpg = dir.join("cover.jpg");
+ std::fs::write(&jpg, [0xFF, 0xD8, 0xFF, 0xE0, 0, 16]).unwrap();
+ let bad = dir.join("cover.txt");
+ std::fs::write(&bad, b"not an image").unwrap();
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 1})).unwrap();
+ s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "Words", "caret": false})).unwrap();
+ let r = s.execute("file.exportEpub", &json!({"coverImage": jpg.to_str().unwrap(), "identifier": "urn:isbn:9780000000002"})).unwrap();
+ let mut z = unzip(r["base64"].as_str().unwrap());
+ let opf = read(&mut z, "OEBPS/content.opf");
+ assert!(opf.contains("<dc:identifier id=\"bookid\">urn:isbn:9780000000002</dc:identifier>"), "{opf}");
+ assert!(opf.contains("href=\"images/cover.jpg\" media-type=\"image/jpeg\""), "{opf}");
+ assert!(!opf.contains("2026-01-01T00:00:00Z"), "the export time, not a fixed date: {opf}");
+ assert!(z.by_name("OEBPS/images/cover.jpg").is_ok());
+ assert!(s.execute("file.exportEpub", &json!({"coverImage": bad.to_str().unwrap()})).is_err());
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
#[test]
fn flattener_rasterises_spreads_with_transparency() {
let mut s = Session::new();
diff --cc crates/engine/src/io.rs
index 7bc7d533c,000000000..2c9a8520a
mode 100644,000000..100644
--- a/crates/engine/src/io.rs
+++ b/crates/engine/src/io.rs
@@@ -1,103 -1,0 +1,114 @@@
+//! Reading and writing the files a command names by path.
+//!
+//! Every such read and write goes through this module, so the automation roots
+//! ([`crate::file_access`]) are checked in one place. A command module that called `std::fs`
+//! itself would bypass them: a test in `file_access` keeps that from happening.
+//!
+//! A path the roots refuse reads as a file that isn't there where the caller only asks whether
+//! it is ([`is_file`], [`is_dir`], [`exists`], [`metadata`]), and as the roots' own message where
+//! it asks for the bytes.
+
+use std::fs::Metadata;
+use std::path::Path;
+
+/// The bytes of the file at `path`, inside the automation read root when there is one.
+pub fn read_file(path: impl AsRef<Path>) -> Result<Vec<u8>, String> {
+ let path = path.as_ref();
+ crate::file_access::check_read(path)?;
+ std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))
+}
+
+/// [`read_file`] with the file system's own error, for callers that tell "missing" from other
+/// failures. A refused path is a `PermissionDenied` error carrying the roots' message.
+pub fn read(path: impl AsRef<Path>) -> std::io::Result<Vec<u8>> {
+ let path = path.as_ref();
+ crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
+ std::fs::read(path)
+}
+
++/// [`read`] that stops past `cap` bytes: at most `cap + 1` bytes are read, so a device or a file
++/// that grows while it is read can't exhaust memory. The caller compares the length with `cap`.
++pub fn read_capped(path: impl AsRef<Path>, cap: u64) -> std::io::Result<Vec<u8>> {
++ use std::io::Read;
++ let path = path.as_ref();
++ crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
++ let mut b = Vec::new();
++ std::fs::File::open(path)?.take(cap.saturating_add(1)).read_to_end(&mut b)?;
++ Ok(b)
++}
++
+/// The text of the file at `path`, inside the automation read root when there is one.
+pub fn read_to_string(path: impl AsRef<Path>) -> Result<String, String> {
+ let path = path.as_ref();
+ crate::file_access::check_read(path)?;
+ std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))
+}
+
+/// Write `bytes` to the file at `path`, inside the automation write root when there is one.
+pub fn write_file(path: impl AsRef<Path>, bytes: &[u8]) -> Result<(), String> {
+ let path = path.as_ref();
+ crate::file_access::check_write(path)?;
+ // Replaced atomically where there is a real file system (see `atomic`).
+ #[cfg(not(target_arch = "wasm32"))]
+ let written = crate::atomic::write_atomic(path, bytes);
+ #[cfg(target_arch = "wasm32")]
+ let written = std::fs::write(path, bytes);
+ written.map_err(|e| format!("{}: {e}", path.display()))
+}
+
+/// Atomically replace the file at `path` with the contents of `staged`, a private temporary file
+/// the engine made itself (so it is not checked), inside the automation write root when there is
+/// one.
+#[cfg(not(target_arch = "wasm32"))]
+pub fn replace_with(path: impl AsRef<Path>, staged: impl AsRef<Path>) -> std::io::Result<()> {
+ let path = path.as_ref();
+ crate::file_access::check_write(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
+ let mut input = std::fs::File::open(staged)?;
+ crate::atomic::write_atomic_with(path, |file| std::io::copy(&mut input, file).map(|_| ()))
+}
+
+/// Could the file at `path` be opened for writing (without truncating it)? Inside the automation
+/// write root when there is one.
+pub fn writable(path: impl AsRef<Path>) -> std::io::Result<()> {
+ let path = path.as_ref();
+ crate::file_access::check_write(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
+ std::fs::OpenOptions::new().write(true).open(path).map(drop)
+}
+
+/// The canonical form of `path` (links resolved), inside the automation read root when there is
+/// one.
+pub fn canonicalize(path: impl AsRef<Path>) -> std::io::Result<std::path::PathBuf> {
+ let path = path.as_ref();
+ crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
+ std::fs::canonicalize(path)
+}
+
+/// What the file system says about `path` (links followed), inside the automation read root when
+/// there is one. A refused path is a `PermissionDenied` error carrying the roots' message.
+pub fn metadata(path: impl AsRef<Path>) -> std::io::Result<Metadata> {
+ let path = path.as_ref();
+ crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
+ std::fs::metadata(path)
+}
+
+/// Is there a file at `path` that automation may read?
+pub fn is_file(path: impl AsRef<Path>) -> bool {
+ metadata(path).is_ok_and(|m| m.is_file())
+}
+
+/// Is there a folder at `path` that automation may read?
+pub fn is_dir(path: impl AsRef<Path>) -> bool {
+ metadata(path).is_ok_and(|m| m.is_dir())
+}
+
+/// Is there anything at `path` that automation may read?
+pub fn exists(path: impl AsRef<Path>) -> bool {
+ metadata(path).is_ok()
+}
+
+/// The entries of the folder at `path`, inside the automation read root when there is one.
+pub fn read_dir(path: impl AsRef<Path>) -> std::io::Result<std::fs::ReadDir> {
+ let path = path.as_ref();
+ crate::file_access::check_read(path).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
+ std::fs::read_dir(path)
+}
diff --cc crates/epub/src/lib.rs
index 2ae33fd6b,8de906466..32e327aa3
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@@ -25,115 -20,56 +25,161 @@@ pub struct EpubOptions
pub language: String,
/// Stable identifier (urn:uuid:…); derived from the title when absent.
pub identifier: Option<String>,
- /// Cover image (PNG), shown first and marked as the book's cover.
+ /// Cover image (PNG or JPEG), shown first and marked as the book's cover.
pub cover: Option<Vec<u8>>,
+ /// Title of the navigation (table of contents); from `language` when absent.
+ pub toc_title: Option<String>,
+ /// Generic CSS family (`serif`, `sans-serif`, `monospace`, `cursive`, `fantasy`) per font
+ /// family, from the fonts' classification; families not in it are guessed from their name.
+ pub generic_families: BTreeMap<String, String>,
+ /// Font files packaged with the book and declared with `@font-face`.
+ pub fonts: Vec<EmbeddedFont>,
+ /// `dcterms:modified` (Unix seconds, UTC); the document's last save, else its creation, when
+ /// absent.
+ pub modified: Option<i64>,
}
+/// A font file packaged with an EPUB: the face of `family` in `style` (`Bold Italic`…).
+#[derive(Clone, Debug)]
+pub struct EmbeddedFont {
+ pub family: String,
+ pub style: String,
+ pub data: Vec<u8>,
+}
+
+/// The `(family, style)` pairs the stylesheet names, one each, in style order: the fonts an
+/// export can embed.
+pub fn stylesheet_fonts(doc: &Document) -> Vec<(String, String)> {
+ let st: &Styles = &doc.styles;
+ let mut out: Vec<(String, String)> = Vec::new();
+ for ps in &st.paragraph {
+ if ps.name == designcraft_doc::NO_PARA_STYLE {
+ continue;
+ }
+ let (_, cp) = st.resolve_para_style(&ps.name);
+ let f = (cp.font_family.clone(), cp.font_style.clone());
+ if !f.0.is_empty() && !out.contains(&f) {
+ out.push(f);
+ }
+ }
+ out
+}
+
+/// The CSS generic family for `family`: the known one, else a guess from the name
+/// (`… Mono`/`Courier`/`… Code` → monospace, `… Sans`/`Gothic`/`Grotesk`/`Helvetica`/`Arial`/
+/// `Verdana` → sans-serif), else serif.
+fn generic_family<'a>(family: &str, known: &'a BTreeMap<String, String>) -> &'a str {
+ const GENERIC: [&str; 6] = ["serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui"];
+ if let Some(g) = known.get(family).and_then(|g| GENERIC.iter().find(|x| **x == g.as_str())) {
+ return g;
+ }
+ let f = family.to_lowercase();
+ let has = |words: &[&str]| words.iter().any(|w| f.contains(w));
+ if has(&["mono", "courier", " code", "consol"]) {
+ "monospace"
+ } else if has(&["sans", "gothic", "grotesk", "grotesque", "helvetica", "arial", "verdana"]) {
+ "sans-serif"
+ } else {
+ "serif"
+ }
+}
+
+/// CSS weight and style of a style name (`Semibold Italic` → 600, italic).
+fn css_weight_style(style: &str) -> (u16, &'static str) {
+ let s = style.to_lowercase().replace([' ', '-'], "");
+ let weight = [
+ ("thin", 100),
+ ("extralight", 200),
+ ("ultralight", 200),
+ ("light", 300),
+ ("medium", 500),
+ ("semibold", 600),
+ ("demibold", 600),
+ ("extrabold", 800),
+ ("ultrabold", 800),
+ ("bold", 700),
+ ("black", 900),
+ ("heavy", 900),
+ ]
+ .iter()
+ .find(|(n, _)| s.contains(n))
+ .map_or(400, |(_, w)| *w);
+ (weight, if s.contains("italic") || s.contains("oblique") { "italic" } else { "normal" })
+}
+
+/// Package path and media type of an embedded font (`fonts/{k}-{family}-{style}.{ext}`).
+fn font_file(k: usize, f: &EmbeddedFont) -> (String, &'static str) {
+ let (ext, mime) = match f.data.get(..4) {
+ Some(b"OTTO") => ("otf", "font/otf"),
+ Some(b"wOFF") => ("woff", "font/woff"),
+ Some(b"wOF2") => ("woff2", "font/woff2"),
+ _ => ("ttf", "font/ttf"),
+ };
+ let name: String =
+ format!("{}-{}", f.family, f.style).chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect();
+ let name = name.split('-').filter(|p| !p.is_empty()).collect::<Vec<_>>().join("-");
+ (format!("fonts/{k}-{name}.{ext}"), mime)
+}
+
+/// The table of contents' title in `language` (a BCP 47 tag or a language name's code), English
+/// for languages without one here.
+pub fn contents_title(language: &str) -> &'static str {
+ let code = language.split(['-', '_']).next().unwrap_or("").to_ascii_lowercase();
+ match code.as_str() {
+ "nl" => "Inhoud",
+ "de" => "Inhalt",
+ "fr" => "Table des matières",
+ "es" | "pt" => "Índice",
+ "it" => "Indice",
+ "ja" => "目次",
+ "zh" => "目录",
+ _ => "Contents",
+ }
+}
+
+ /// An ISO 8601 UTC timestamp (`2026-10-13T09:30:00Z`) for Unix seconds `t`.
+ fn iso8601(t: i64) -> String {
+ let (days, secs) = (t.div_euclid(86_400), t.rem_euclid(86_400));
+ // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
+ let z = days + 719_468;
+ let era = z.div_euclid(146_097);
+ let doe = z - era * 146_097;
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let day = doy - (153 * mp + 2) / 5 + 1;
+ let month = if mp < 10 { mp + 3 } else { mp - 9 };
+ let year = yoe + era * 400 + i64::from(month <= 2);
+ format!("{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", secs / 3600, secs % 3600 / 60, secs % 60)
+ }
+
+ /// The package's `dcterms:modified`: the given time, else the document's last save or creation.
+ fn modified(doc: &Document, opts: &EpubOptions) -> String {
+ let t = opts.modified.or((doc.modified > 0).then_some(doc.modified)).or((doc.created > 0).then_some(doc.created));
+ t.map_or_else(|| "2026-01-01T00:00:00Z".to_string(), iso8601)
+ }
+
+ /// The book's identifier: the given one, else a `urn:uuid` derived from the title and the
+ /// document's creation time, so a book keeps its identifier from export to export and two books
+ /// with the same title don't share one.
+ fn identifier(doc: &Document, opts: &EpubOptions, title: &str) -> String {
+ if let Some(id) = opts.identifier.clone().filter(|i| !i.trim().is_empty()) {
+ return id;
+ }
+ // Two FNV-1a 64-bit hashes (different offsets) as 128 bits, shaped as a version-5-style UUID.
+ let seed = format!("{title}\n{}", doc.created);
+ let fnv = |offset: u64| seed.bytes().fold(offset, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3));
+ let (a, b) = (fnv(0xcbf2_9ce4_8422_2325), fnv(0x84222325_cbf29ce4));
+ let hi = (a & 0xffff_ffff_ffff_0fff) | 0x5000;
+ let lo = (b & 0x3fff_ffff_ffff_ffff) | 0x8000_0000_0000_0000;
+ format!("urn:uuid:{:08x}-{:04x}-{:04x}-{:04x}-{:012x}", hi >> 32, (hi >> 16) & 0xffff, hi & 0xffff, lo >> 48, lo & 0xffff_ffff_ffff)
+ }
+
+ /// Package name and media type of a cover image: JPEG by its signature, else PNG.
+ fn cover_file(data: &[u8]) -> (&'static str, &'static str) {
+ if data.starts_with(&[0xFF, 0xD8, 0xFF]) { ("images/cover.jpg", "image/jpeg") } else { ("images/cover.png", "image/png") }
+ }
+
/// A page of a fixed-layout EPUB: its image (PNG), size in points and text (kept for search,
/// read-aloud and accessibility).
#[derive(Clone, Debug)]
@@@ -210,16 -147,7 +257,17 @@@ pub fn export_fixed_epub(doc: &Document
impl Default for EpubOptions {
fn default() -> Self {
- EpubOptions { title: None, author: None, language: "en".into(), identifier: None, cover: None, modified: None }
+ EpubOptions {
+ title: None,
+ author: None,
+ language: "en".into(),
+ identifier: None,
+ cover: None,
+ toc_title: None,
+ generic_families: BTreeMap::new(),
+ fonts: Vec::new(),
++ modified: None,
+ }
}
}
@@@ -1319,31 -732,18 +1367,32 @@@ pub fn export_epub(doc: &Document, opts
let io = |e: std::io::Error| EpubError(e.to_string());
let zerr = |e: zip::result::ZipError| EpubError(e.to_string());
let title = opts.title.clone().unwrap_or_else(|| doc.title.clone());
- let id = opts.identifier.clone().unwrap_or_else(|| format!("urn:designcraft:{}", slug(&title)));
+ let id = identifier(doc, opts, &title);
+ let modified = modified(doc, opts);
- let (body, images, toc) = body_html(doc, &|name, _, _| name.to_string());
+ let (body, images, toc) = body_html(doc, &|name, _, _| name.to_string(), true);
let lang = language_tag(&opts.language);
- let chapter = format!(
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\" xml:lang=\"{lang}\" lang=\"{lang}\">\n<head><meta charset=\"utf-8\"/><title>{}</title><link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"/></head>\n<body>\n{body}</body>\n</html>\n",
- xml_text(&title)
- );
- let mut nav_items = String::new();
- for (a, label) in &toc {
- let _ = write!(nav_items, "<li><a href=\"content.xhtml#{a}\">{}</a></li>", xml_text(label));
+ // One file per chapter (split before each h1), so e-readers needn't load the whole book.
+ let chapters: Vec<String> = split_chapters(&body)
+ .into_iter()
+ .map(|part| {
+ format!(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\" xml:lang=\"{lang}\" lang=\"{lang}\">\n<head><meta charset=\"utf-8\"/><title>{}</title><link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"/></head>\n<body>\n{part}</body>\n</html>\n",
+ xml_text(&title)
+ )
+ })
+ .collect();
+ // The file each navigation target (an element id) ended up in.
+ let mut files: BTreeMap<String, String> = BTreeMap::new();
+ for (k, c) in chapters.iter().enumerate() {
+ for rest in c.split(" id=\"").skip(1) {
+ if let Some(id) = rest.split('"').next() {
+ files.entry(id.to_string()).or_insert_with(|| chapter_file(k));
+ }
+ }
}
+ // Note links whose target ended up in another file (endnotes end the book) point at it.
+ let chapters: Vec<String> = chapters.iter().enumerate().map(|(k, c)| link_across_chapters(c, &chapter_file(k), &files)).collect();
+ let mut nav_items = nav_list(&toc, &files);
if nav_items.is_empty() {
nav_items = format!("<li><a href=\"content.xhtml\">{}</a></li>", xml_text(&title));
}
@@@ -1364,18 -757,18 +1413,22 @@@
for (k, (name, (mime, _))) in images.iter().enumerate() {
let _ = writeln!(manifest, "<item id=\"img{k}\" href=\"{}\" media-type=\"{}\"/>", xml_attr(name), xml_attr(mime));
}
+ for (k, f) in opts.fonts.iter().enumerate() {
+ let (name, mime) = font_file(k, f);
+ let _ = writeln!(manifest, "<item id=\"font{k}\" href=\"{}\" media-type=\"{mime}\"/>", xml_attr(&name));
+ }
// Cover: an image page first in reading order.
- if opts.cover.is_some() {
- manifest.push_str("<item id=\"cover-img\" href=\"images/cover.png\" media-type=\"image/png\" properties=\"cover-image\"/>\n<item id=\"cover\" href=\"cover.xhtml\" media-type=\"application/xhtml+xml\"/>\n");
+ if let Some(c) = &opts.cover {
+ let (name, mime) = cover_file(c);
+ let _ = writeln!(
+ manifest,
+ "<item id=\"cover-img\" href=\"{name}\" media-type=\"{mime}\" properties=\"cover-image\"/>\n<item id=\"cover\" href=\"cover.xhtml\" media-type=\"application/xhtml+xml\"/>"
+ );
}
let cover_spine = if opts.cover.is_some() { "<itemref idref=\"cover\"/>\n" } else { "" };
let author = opts.author.as_deref().map(|a| format!("<dc:creator>{}</dc:creator>", xml_text(a))).unwrap_or_default();
let opf = format!(
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"3.0\" unique-identifier=\"bookid\" xml:lang=\"{lang}\">\n<metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<dc:identifier id=\"bookid\">{}</dc:identifier>\n<dc:title>{}</dc:title>\n<dc:language>{lang}</dc:language>{author}\n<meta property=\"dcterms:modified\">2026-01-01T00:00:00Z</meta>\n<meta name=\"generator\" content=\"DesignCraft\"/>\n</metadata>\n<manifest>\n{manifest}</manifest>\n<spine>\n{cover_spine}{spine}</spine>\n</package>\n",
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"3.0\" unique-identifier=\"bookid\" xml:lang=\"{lang}\">\n<metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<dc:identifier id=\"bookid\">{}</dc:identifier>\n<dc:title>{}</dc:title>\n<dc:language>{lang}</dc:language>{author}\n<meta property=\"dcterms:modified\">{modified}</meta>\n<meta name=\"generator\" content=\"DesignCraft\"/>\n</metadata>\n<manifest>\n{manifest}</manifest>\n<spine>\n{cover_spine}<itemref idref=\"content\"/>\n</spine>\n</package>\n",
++ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"3.0\" unique-identifier=\"bookid\" xml:lang=\"{lang}\">\n<metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<dc:identifier id=\"bookid\">{}</dc:identifier>\n<dc:title>{}</dc:title>\n<dc:language>{lang}</dc:language>{author}\n<meta property=\"dcterms:modified\">{modified}</meta>\n<meta name=\"generator\" content=\"DesignCraft\"/>\n</metadata>\n<manifest>\n{manifest}</manifest>\n<spine>\n{cover_spine}{spine}</spine>\n</package>\n",
xml_text(&id),
xml_text(&title)
);
@@@ -1404,16 -794,13 +1457,17 @@@
z.start_file(format!("OEBPS/{name}"), stored).map_err(zerr)?;
z.write_all(data).map_err(io)?;
}
+ for (k, f) in opts.fonts.iter().enumerate() {
+ z.start_file(format!("OEBPS/{}", font_file(k, f).0), deflate).map_err(zerr)?;
+ z.write_all(&f.data).map_err(io)?;
+ }
if let Some(c) = &opts.cover {
- z.start_file("OEBPS/images/cover.png", stored).map_err(zerr)?;
+ z.start_file(format!("OEBPS/{}", cover_file(c).0), stored).map_err(zerr)?;
z.write_all(c).map_err(io)?;
let xhtml = format!(
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\" xml:lang=\"{lang}\">\n<head><meta charset=\"utf-8\"/><title>{}</title><style>body{{margin:0;text-align:center}} img{{max-width:100%;max-height:100vh}}</style></head>\n<body epub:type=\"cover\"><img src=\"images/cover.png\" alt=\"{}\"/></body>\n</html>\n",
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\" xml:lang=\"{lang}\">\n<head><meta charset=\"utf-8\"/><title>{}</title><style>body{{margin:0;text-align:center}} img{{max-width:100%;max-height:100vh}}</style></head>\n<body epub:type=\"cover\"><img src=\"{}\" alt=\"{}\"/></body>\n</html>\n",
xml_text(&title),
+ cover_file(c).0,
xml_attr(&title)
);
z.start_file("OEBPS/cover.xhtml", deflate).map_err(zerr)?;
@@@ -1454,266 -841,52 +1508,312 @@@ mod tests
assert!(z.by_name("OEBPS/nav.xhtml").is_ok());
}
+ /// #766: anchored graphics are exported where they are anchored (inline in the text, an
+ /// above-line object as a block of its own), and their images go into the package.
+ #[test]
+ fn anchored_objects_are_exported_in_place() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 200.0), lid, "AB\nCD", ParaFormat::default()).unwrap();
+ let aid = AssetId(d.alloc());
+ d.assets.insert(
+ aid,
+ Arc::new(Asset {
+ page: 0,
+ id: aid,
+ name: "dot.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: Arc::new(vec![7]),
+ pixels: Some((1, 1)),
+ }),
+ );
+ let graphic = |d: &mut Document, alt: &str| {
+ let mut item = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)));
+ item.alt_text = alt.into();
+ item.content = Content::Graphic(Graphic {
+ asset: aid,
+ size: (1.0, 1.0),
+ xf: Affine::IDENTITY,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ });
+ item
+ };
+ let inline = designcraft_doc::AnchoredObject::new(graphic(&mut d, "inline"), designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 });
+ let above = designcraft_doc::AnchoredObject::new(
+ graphic(&mut d, "above"),
+ designcraft_doc::AnchorPosition::AboveLine { align: designcraft_doc::anchored::AnchorAlign::Center, space_before: 0.0, space_after: 0.0 },
+ );
+ let st = d.story_mut(sid).unwrap();
+ st.insert_object(1, inline);
+ // Byte offsets: "A" (1), the mark (3), "B\nC" (3): the second object goes between C and D.
+ st.insert_object(7, above);
+ let bytes = export_epub(&d, &EpubOptions::default()).unwrap();
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
+ let mut html = String::new();
+ z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut html).unwrap();
+ let img = |alt: &str| format!("<img src=\"images/dot-{}.png\" alt=\"{alt}\"/>", aid.0);
+ assert!(html.contains(&format!("A{}B</p>", img("inline"))), "{html}");
+ assert!(html.contains(&format!("C<span class=\"anchored\" style=\"display:block;text-align:center\">{}</span>D", img("above"))), "{html}");
+ assert!(z.by_name(&format!("OEBPS/images/dot-{}.png", aid.0)).is_ok(), "the image is in the package");
+ let page = export_html(&d, &HtmlOptions::default());
+ assert!(page.contains("alt=\"inline\"") && page.contains("alt=\"above\""), "{page}");
+ // story_html on its own still leaves objects out.
+ assert!(!story_html(&d, sid).contains("<img"));
+ }
+
+ fn st_typed(d: &mut Document, sid: StoryId) {
+ if let Some(st) = d.story_mut(sid) {
+ st.paras[8].style = "Typed".into();
+ }
+ }
+
+ /// #767: consecutive `li` paragraphs share one list (`ol` for a numbered style), and
+ /// consecutive `pre` paragraphs of one style one block with their lines on separate lines.
+ #[test]
+ fn lists_and_preformatted_blocks_are_grouped() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ for (name, tag, list) in [
+ ("Bullet", "li", Some(designcraft_doc::ListType::Bullets)),
+ ("Number", "li", Some(designcraft_doc::ListType::Numbers)),
+ ("Typed", "li", None),
+ ("Code", "pre", None),
+ ] {
+ let para = designcraft_doc::ParaAttrs { list_type: list, ..Default::default() };
+ d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle {
+ name: name.into(),
+ based_on: None,
+ next_style: None,
+ para,
+ chars: CharAttrs::default(),
+ shortcut: String::new(),
+ });
+ d.styles_mut().export_tags.insert(format!("p:{name}"), designcraft_doc::ExportTag { tag: tag.into(), class: String::new() });
+ }
+ let text = "Intro\nfirst\nsecond\none\ntwo\nx = 1\ny = 2\nEnd\n• typed";
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 300.0), lid, text, ParaFormat::default()).unwrap();
+ let st = d.story_mut(sid).unwrap();
+ for (i, style) in ["Bullet", "Bullet", "Number", "Number", "Code", "Code"].into_iter().enumerate() {
+ st.paras[i + 1].style = style.into();
+ }
+ let html = story_html(&d, sid);
+ let li = |c: &str, t: &str| format!("<li class=\"{c}\">{t}</li>");
+ assert!(
+ html.contains(&format!(
+ "<ul>\n{}\n{}\n</ul>\n<ol>\n{}\n{}\n</ol>\n",
+ li("bullet", "first"),
+ li("bullet", "second"),
+ li("number", "one"),
+ li("number", "two")
+ )),
+ "{html}"
+ );
+ assert!(html.contains("<pre class=\"code\">x = 1\ny = 2</pre>\n<p class=\"basic-paragraph\">End</p>"), "{html}");
+ assert_eq!(html.matches("<pre").count(), 1, "{html}");
+ // A style without a list type of its own (typed bullets) gets no second marker.
+ st_typed(&mut d, sid);
+ let html = story_html(&d, sid);
+ assert!(html.contains("<ul style=\"list-style:none\">\n<li class=\"typed\">• typed</li>\n</ul>\n"), "{html}");
+ }
+
+ /// #769, #770: the navigation lists the h1–h3 headings (nested by level) and links to them,
+ /// with its title in the book's language; without headings, each story's first paragraph.
+ #[test]
+ fn navigation_follows_the_headings() {
+ let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() });
+ let lid = d.default_layer();
+ for (name, tag) in [("Chapter", "h1"), ("Section", "h2")] {
+ d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle {
+ name: name.into(),
+ based_on: None,
+ next_style: None,
+ para: Default::default(),
+ chars: CharAttrs::default(),
+ shortcut: String::new(),
+ });
+ d.styles_mut().export_tags.insert(format!("p:{name}"), designcraft_doc::ExportTag { tag: tag.into(), class: String::new() });
+ }
+ let text = "One\nBody\nOne point one\nMore\nTwo\nText";
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 300.0), lid, text, ParaFormat::default()).unwrap();
+ let st = d.story_mut(sid).unwrap();
+ for (i, style) in [(0, "Chapter"), (2, "Section"), (4, "Chapter")] {
+ st.paras[i].style = style.into();
+ }
+ // A story that starts with body text adds nothing to the table of contents.
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 400.0, 300.0, 500.0), lid, "Text after the figure.", ParaFormat::default()).unwrap();
+ let read = |d: &Document, opts: &EpubOptions, path: &str| {
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(d, opts).unwrap())).unwrap();
+ let mut s = String::new();
+ z.by_name(path).unwrap().read_to_string(&mut s).unwrap();
+ s
+ };
+ let nl = EpubOptions { language: "nl".into(), ..Default::default() };
+ let nav = read(&d, &nl, "OEBPS/nav.xhtml");
+ let link = |f: &str, t: &str, l: &str| format!("<a href=\"{f}#{t}\">{l}</a>");
+ // Each h1 starts a chapter file (#768).
+ let want = format!(
+ "<h1>Inhoud</h1><ol><li>{}<ol><li>{}</li></ol></li><li>{}</li></ol>",
+ link("content.xhtml", "s0-p0", "One"),
+ link("content.xhtml", "s0-p2", "One point one"),
+ link("content2.xhtml", "s0-p4", "Two")
+ );
+ assert!(nav.contains(&want), "{nav}");
+ assert!(!nav.contains("Text after the figure"), "{nav}");
+ let content = read(&d, &nl, "OEBPS/content.xhtml");
+ assert!(content.contains("<h1 id=\"s0-p0\" class=\"chapter\">One</h1>") && content.contains("<h2 id=\"s0-p2\""), "{content}");
+ let custom = EpubOptions { toc_title: Some("In dit boek".into()), ..Default::default() };
+ assert!(read(&d, &custom, "OEBPS/nav.xhtml").contains("<h1>In dit boek</h1>"));
+ // Without headings: one entry per story, its first paragraph.
+ let mut plain = Document::new(&NewDocument::default());
+ let lid = plain.default_layer();
+ plain.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Opening\nrest", ParaFormat::default()).unwrap();
+ let nav = read(&plain, &EpubOptions::default(), "OEBPS/nav.xhtml");
+ assert!(nav.contains(&format!("<h1>Contents</h1><ol><li>{}</li></ol>", link("content.xhtml", "s0", "Opening"))), "{nav}");
+ // A heading shallower than the one before it but deeper than its parent stays under the
+ // parent: h1 A, h3 B, h2 C nest B and C under A.
+ let e = |t: &str, l: u8| (t.to_string(), t.to_string(), l);
+ let l = |t: &str| link("content.xhtml", t, t);
+ assert_eq!(
+ nav_list(&[e("A", 1), e("B", 3), e("C", 2), e("D", 1)], &BTreeMap::new()),
+ format!("<li>{}<ol><li>{}</li><li>{}</li></ol></li><li>{}</li>", l("A"), l("B"), l("C"), l("D"))
+ );
+ assert_eq!(
+ nav_list(&[e("A", 1), e("B", 2), e("C", 3), e("D", 1)], &BTreeMap::new()),
+ format!("<li>{}<ol><li>{}<ol><li>{}</li></ol></li></ol></li><li>{}</li>", l("A"), l("B"), l("C"), l("D"))
+ );
+ }
+
+ /// #768: the book is split into one file per chapter, before each h1, with well-formed
+ /// sections; the spine and manifest list the files in order.
+ #[test]
+ fn chapters_are_split_at_h1() {
+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });
+ let lid = d.default_layer();
+ d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle {
+ name: "Chapter".into(),
+ based_on: None,
+ next_style: None,
+ para: Default::default(),
+ chars: CharAttrs::default(),
+ shortcut: String::new(),
+ });
+ d.styles_mut().export_tags.insert("p:Chapter".into(), designcraft_doc::ExportTag { tag: "h1".into(), class: String::new() });
+ // A title page without a heading, then a story that opens with a chapter and has a
+ // second one in the middle.
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Title page", ParaFormat::default()).unwrap();
+ let (_, sid) = d
+ .add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 200.0, 300.0, 400.0), lid, "One\nFirst text\nTwo\nSecond text", ParaFormat::default())
+ .unwrap();
+ let st = d.story_mut(sid).unwrap();
+ st.paras[0].style = "Chapter".into();
+ st.paras[2].style = "Chapter".into();
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(&d, &EpubOptions::default()).unwrap())).unwrap();
+ let mut read = |path: &str| {
+ let mut s = String::new();
+ z.by_name(path).unwrap().read_to_string(&mut s).unwrap();
+ s
+ };
+ let (c1, c2, c3) = (read("OEBPS/content.xhtml"), read("OEBPS/content2.xhtml"), read("OEBPS/content3.xhtml"));
+ assert!(c1.contains("Title page") && !c1.contains("One"), "{c1}");
+ assert!(c2.contains("<section id=\"s1\">\n<h1 id=\"s1-p0\"") && c2.contains("First text") && !c2.contains("Two"), "{c2}");
+ assert!(c3.contains("<section>\n<h1 id=\"s1-p2\""), "{c3}");
+ for c in [&c1, &c2, &c3] {
+ assert_eq!(c.matches("<section").count(), c.matches("</section>").count(), "{c}");
+ assert!(!c.contains(CHAPTER_MARK));
+ }
+ let opf = read("OEBPS/content.opf");
+ assert!(opf.contains("<itemref idref=\"content\"/>\n<itemref idref=\"content2\"/>\n<itemref idref=\"content3\"/>\n</spine>"), "{opf}");
+ assert!(opf.contains("<item id=\"content3\" href=\"content3.xhtml\""), "{opf}");
+ let nav = read("OEBPS/nav.xhtml");
+ assert!(nav.contains("href=\"content2.xhtml#s1-p0\"") && nav.contains("href=\"content3.xhtml#s1-p2\""), "{nav}");
+ assert!(z.by_name("OEBPS/content4.xhtml").is_err());
+ // HTML stays one page, without the marks.
+ let html = export_html(&d, &HtmlOptions::default());
+ assert!(!html.contains(CHAPTER_MARK) && html.contains("Second text"));
+ }
+
+ /// Note links stay working across chapter files: a link whose target ended up in another
+ /// file (endnotes end the book) names that file; one in its own file stays as it is.
+ #[test]
+ fn note_links_point_at_the_chapter_file_of_their_target() {
+ let files: BTreeMap<String, String> =
+ [("enref-1", "content.xhtml"), ("fn-1", "content.xhtml"), ("fnref-1", "content.xhtml"), ("en-1", "content2.xhtml")]
+ .into_iter()
+ .map(|(id, f)| (id.to_string(), f.to_string()))
+ .collect();
+ let first = "<p>First<a id=\"enref-1\" href=\"#en-1\">1</a><a id=\"fnref-1\" href=\"#fn-1\">*</a></p><aside id=\"fn-1\"><a href=\"#fnref-1\">*</a></aside><a href=\"#gone\">x</a>";
+ assert_eq!(
+ link_across_chapters(first, "content.xhtml", &files),
+ "<p>First<a id=\"enref-1\" href=\"content2.xhtml#en-1\">1</a><a id=\"fnref-1\" href=\"#fn-1\">*</a></p><aside id=\"fn-1\"><a href=\"#fnref-1\">*</a></aside><a href=\"#gone\">x</a>"
+ );
+ let last = "<li id=\"en-1\"><a href=\"#enref-1\">1</a> End note</li>";
+ assert_eq!(link_across_chapters(last, "content2.xhtml", &files), "<li id=\"en-1\"><a href=\"content.xhtml#enref-1\">1</a> End note</li>");
+ }
+
+ #[test]
+ fn split_chapters_keeps_sections_well_formed() {
+ let m = CHAPTER_MARK;
+ assert_eq!(split_chapters("<section id=\"s0\">\n<p>a</p>\n</section>\n"), vec!["<section id=\"s0\">\n<p>a</p>\n</section>\n"]);
+ assert_eq!(
+ split_chapters(&format!("<section id=\"s0\">\n{m}<h1>A</h1>\n</section>\n")),
+ vec!["<section id=\"s0\">\n<h1>A</h1>\n</section>\n"]
+ );
+ assert_eq!(
+ split_chapters(&format!("<section id=\"s0\">\n<p>a</p>\n{m}<h1>B</h1>\n</section>\n")),
+ vec!["<section id=\"s0\">\n<p>a</p>\n</section>\n", "<section>\n<h1>B</h1>\n</section>\n"]
+ );
+ assert_eq!(split_chapters(""), vec![String::new()]);
+ }
+
+ #[test]
+ fn iso8601_timestamps() {
+ for (t, want) in [
+ (0, "1970-01-01T00:00:00Z"),
+ (951_782_400, "2000-02-29T00:00:00Z"),
+ (1_791_891_000, "2026-10-13T11:30:00Z"),
+ (-86_400, "1969-12-31T00:00:00Z"),
+ ] {
+ assert_eq!(iso8601(t), want);
+ }
+ }
+
+ /// #771, #773: dcterms:modified is a real time, the default identifier is a stable urn:uuid
+ /// that differs between documents with the same title, and a JPEG cover keeps its type.
+ #[test]
+ fn package_metadata_and_cover_image() {
+ let opf = |d: &Document, opts: &EpubOptions| {
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(d, opts).unwrap())).unwrap();
+ let mut s = String::new();
+ z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut s).unwrap();
+ let names: Vec<String> = z.file_names().map(str::to_string).collect();
+ (s, names)
+ };
+ let id_of = |opf: &str| opf.split("<dc:identifier id=\"bookid\">").nth(1).and_then(|r| r.split('<').next()).unwrap_or_default().to_string();
+ let mut a = Document::new(&NewDocument::default());
+ a.title = "Same".into();
+ a.created = 1_700_000_000;
+ let mut b = a.clone();
+ b.created = 1_700_000_001;
+ let (oa, _) = opf(&a, &EpubOptions::default());
+ let (oa2, _) = opf(&a, &EpubOptions::default());
+ let (ob, _) = opf(&b, &EpubOptions::default());
+ assert!(id_of(&oa).starts_with("urn:uuid:") && id_of(&oa).len() == 45, "{}", id_of(&oa));
+ assert_eq!(id_of(&oa), id_of(&oa2), "stable from export to export");
+ assert_ne!(id_of(&oa), id_of(&ob), "not shared by two books with the same title");
+ // Modified: the given time, else the document's save (or creation) time.
+ assert!(oa.contains("<meta property=\"dcterms:modified\">2023-11-14T22:13:20Z</meta>"), "{oa}");
+ let at = EpubOptions { modified: Some(1_791_891_000), ..Default::default() };
+ assert!(opf(&a, &at).0.contains("2026-10-13T11:30:00Z"));
+ // A JPEG cover is packaged as such.
+ let jpeg = EpubOptions { cover: Some(vec![0xFF, 0xD8, 0xFF, 0xE0, 1, 2]), ..Default::default() };
+ let (o, names) = opf(&a, &jpeg);
+ assert!(o.contains("href=\"images/cover.jpg\" media-type=\"image/jpeg\" properties=\"cover-image\""), "{o}");
+ assert!(names.contains(&"OEBPS/images/cover.jpg".to_string()), "{names:?}");
+ }
+
#[test]
fn styles_whose_names_slug_alike_keep_their_own_classes() {
let mut d = Document::new(&NewDocument::default());