Skip to content

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

Merge #783: EPUB: real modified time, a stable unique identifier, and a cover image file

aiongg73112e882f5a
diff --cc crates/engine/src/cmd/export.rs
index 5fca76420,0b4a91d32..b85e24791
--- 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\", 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 not 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), 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 not 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})",
@@@ -177,20 -130,27 +177,34 @@@ 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(std::fs::read(path).map_err(|e| crate::EngineError::Other(format!("{path}: {e}")))?),
+ 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,
+ 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;
@@@ -783,64 -686,30 +797,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/epub/src/lib.rs
index c8985a7aa,8de906466..8f2467417
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@@ -26,97 -20,56 +26,143 @@@ 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>>,
+ /// 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)
+}
+
+ /// 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)]
@@@ -193,15 -147,7 +240,16 @@@ 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,
+ generic_families: BTreeMap::new(),
+ fonts: Vec::new(),
++ modified: None,
+ }
}
}
@@@ -1059,8 -732,9 +1107,9 @@@ 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, true, &|name, _, _| name.to_string());
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",
@@@ -1083,13 -757,13 +1132,17 @@@
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();
@@@ -1120,16 -794,13 +1173,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)?;