Skip to content

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

Merge PR #787

Brandon Thomasf726d40ff433
diff --cc crates/engine/src/cmd/export.rs
index 986df19c2,28c068bf4..09fdea678
--- 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), 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",
- "{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})",
++ "{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",
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})",
@@@ -137,7 -184,12 +184,13 @@@ fn export_epub(s: &mut Session, p: &Val
language: p.get("language").and_then(Value::as_str).unwrap_or("en").to_string(),
identifier: None,
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()
+ },
};
if fixed {
let d = &st.doc;
@@@ -158,10 -210,6 +211,11 @@@
};
}
let bytes = designcraft_epub::export_epub(epub_doc, &opts).map_err(|e| crate::EngineError::Other(e.to_string()))?;
- let warnings: Vec<String> = designcraft_epub::images_without_alt(epub_doc)
- .into_iter()
- .map(|name| format!("{name}: no alt text (Object Export Options); exported as decorative (alt=\"\")"))
- .collect();
++ warnings.extend(
++ designcraft_epub::images_without_alt(epub_doc)
++ .into_iter()
++ .map(|name| format!("{name}: no alt text (Object Export Options); exported as decorative (alt=\"\")")),
++ );
match p.get("path").and_then(Value::as_str) {
Some(path) => {
#[cfg(not(target_arch = "wasm32"))]
diff --cc crates/epub/src/lib.rs
index d87d39c22,6d204c7e4..2ae33fd6b
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@@ -27,26 -22,95 +27,113 @@@ pub struct EpubOptions
pub identifier: Option<String>,
/// Cover image (PNG), 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>,
+ }
+
+ /// 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",
+ }
+}
+
/// 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)]
@@@ -123,7 -187,15 +210,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, toc_title: None }
+ EpubOptions {
+ title: None,
+ author: None,
+ language: "en".into(),
+ identifier: None,
+ cover: None,
++ toc_title: None,
+ generic_families: BTreeMap::new(),
+ fonts: Vec::new(),
+ }
}
}
@@@ -1278,7 -844,8 +1391,7 @@@ pub fn export_epub(doc: &Document, opts
("META-INF/container.xml", container.as_bytes()),
("OEBPS/content.opf", opf.as_bytes()),
("OEBPS/nav.xhtml", nav.as_bytes()),
- ("OEBPS/style.css", stylesheet(doc).as_bytes()),
+ ("OEBPS/style.css", stylesheet_with(doc, &opts.generic_families, &opts.fonts).as_bytes()),
- ("OEBPS/content.xhtml", chapter.as_bytes()),
] {
z.start_file(name, deflate).map_err(zerr)?;
z.write_all(data).map_err(io)?;
@@@ -1654,44 -961,68 +1771,106 @@@ mod tests
assert_eq!(base64(b"M"), "TQ==");
}
+ /// #774: an image without alt text is decorative (`alt=""`) and reported, and package names
+ /// come from the original file names.
+ #[test]
+ fn images_get_readable_names_and_no_file_name_alt() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let place = |d: &mut Document, name: &str, mime: &str, alt: &str, y: f64| {
+ let aid = AssetId(d.alloc());
+ d.assets.insert(
+ aid,
+ Arc::new(Asset { page: 0, id: aid, name: name.into(), mime: mime.into(), link: None, data: Arc::new(vec![1]), pixels: Some((1, 1)) }),
+ );
+ let mut item = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(36.0, y, 72.0, y + 36.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],
+ });
+ d.insert_item(SpreadRef::Doc(0), item, None).unwrap();
+ aid.0
+ };
+ let a = place(&mut d, "/tmp/Anim Frame (1).GIF", "image/gif", "", 36.0);
+ let b = place(&mut d, "photo.jpg", "image/jpeg", "A heron", 120.0);
+ let c = place(&mut d, "???.png", "image/png", "Mark", 200.0);
+ assert_eq!(images_without_alt(&d), vec!["/tmp/Anim Frame (1).GIF".to_string()]);
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(&d, &EpubOptions::default()).unwrap())).unwrap();
+ let mut x = String::new();
+ z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut x).unwrap();
+ assert!(x.contains(&format!("<img src=\"images/anim-frame-1-{a}.gif\" alt=\"\"/>")), "{x}");
+ assert!(x.contains(&format!("<img src=\"images/photo-{b}.jpg\" alt=\"A heron\"/>")), "{x}");
+ assert!(x.contains(&format!("<img src=\"images/{c}.png\" alt=\"Mark\"/>")), "{x}");
+ assert!(z.by_name(&format!("OEBPS/images/anim-frame-1-{a}.gif")).is_ok());
+ }
+
+ /// #775: the generic fallback follows the font, and embedded fonts are packaged and declared.
+ #[test]
+ fn generic_fallbacks_and_embedded_fonts() {
+ let none = BTreeMap::new();
+ for (family, want) in [
+ ("Source Serif 4", "serif"),
+ ("Source Sans 3", "sans-serif"),
+ ("Microsoft Sans Serif", "sans-serif"),
+ ("JetBrains Mono", "monospace"),
+ ("Courier New", "monospace"),
+ ("Franklin Gothic", "sans-serif"),
+ ("Garamond", "serif"),
+ ] {
+ assert_eq!(generic_family(family, &none), want, "{family}");
+ }
+ let known: BTreeMap<String, String> =
+ [("Montserrat".to_string(), "sans-serif".to_string()), ("Odd".to_string(), "nonsense".to_string())].into();
+ assert_eq!(generic_family("Montserrat", &known), "sans-serif");
+ assert_eq!(generic_family("Odd", &known), "serif", "only CSS generic families are used");
+ assert_eq!(css_weight_style("Semibold Italic"), (600, "italic"));
+ assert_eq!(css_weight_style("Bold"), (700, "normal"));
+ assert_eq!(css_weight_style("Extra Bold"), (800, "normal"));
+ assert_eq!(css_weight_style("Regular"), (400, "normal"));
+ assert_eq!(css_weight_style("Light"), (300, "normal"));
+ assert_eq!(css_weight_style("Thin Oblique"), (100, "italic"));
+ assert_eq!(css_weight_style("Black"), (900, "normal"));
+
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Hello", ParaFormat::default()).unwrap();
+ if let Some(basic) = d.styles_mut().paragraph.iter_mut().find(|s| s.name == story::BASIC_PARAGRAPH) {
+ basic.chars.font_family = Some("Montserrat".into());
+ basic.chars.font_style = Some("Bold Italic".into());
+ }
+ assert_eq!(stylesheet_fonts(&d), vec![("Montserrat".to_string(), "Bold Italic".to_string())]);
+ let opts = EpubOptions {
+ generic_families: known,
+ fonts: vec![EmbeddedFont { family: "Montserrat".into(), style: "Bold Italic".into(), data: b"OTTO font".to_vec() }],
+ ..Default::default()
+ };
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(&d, &opts).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 css = read("OEBPS/style.css");
+ assert!(
+ css.starts_with(
+ "@font-face { font-family: \"Montserrat\"; src: url(\"fonts/0-montserrat-bold-italic.otf\"); font-weight: 700; font-style: italic; }"
+ ),
+ "{css}"
+ );
+ assert!(css.contains("font-family: \"Montserrat\", sans-serif;"), "{css}");
+ let opf = read("OEBPS/content.opf");
+ assert!(opf.contains("<item id=\"font0\" href=\"fonts/0-montserrat-bold-italic.otf\" media-type=\"font/otf\"/>"), "{opf}");
+ assert_eq!(read("OEBPS/fonts/0-montserrat-bold-italic.otf"), "OTTO font");
+ // HTML takes the generic families too, and embeds nothing.
+ let html = export_html(&d, &HtmlOptions { generic_families: opts.generic_families.clone(), ..Default::default() });
+ assert!(html.contains("\"Montserrat\", sans-serif;") && !html.contains("@font-face"), "{html}");
+ }
+
#[test]
fn metadata_is_serialized_for_its_output_context() {
let mut d = Document::new(&NewDocument::default());