Skip to content

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

Merge #787: EPUB/HTML: generic font fallback from the font's class, and optional font embedding

aiongg11e4a7f60e63
diff --cc crates/engine/src/cmd/export.rs
index a668a9b33,7975c6842..f562295dc
--- 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), 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\", 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})",
@@@ -158,10 -210,6 +211,11 @@@ fn export_epub(s: &mut Session, p: &Val
};
}
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 c1b78f239,b2c73b532..265c23ea2
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@@ -1111,46 -967,65 +1233,105 @@@ 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)), ..Default::default() }),
+ );
+ 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],
+ clip: None,
+ wrap: Default::default(),
+ });
+ 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"));
+
+ 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());