DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #247: IDML: layers import and export in stacking order; font names with a format suffix
aiongg83e1b768e62d
diff --cc crates/fonts/src/fontdb.rsindex 49e92ce91,14441e144..92afc91e6--- a/crates/fonts/src/fontdb.rs+++ b/crates/fonts/src/fontdb.rs@@@ -724,24 -712,15 +724,33 @@@ fn make_face(bytes: FontBytes, source:})}+/// A font's height above the baseline (font units) if it is plausible: above 0 and at most 4 em.+fn plausible(v: Option<f64>, upem: f64) -> Option<f64> {+ v.filter(|v| *v > 0.0 && *v <= 4.0 * upem)+}++/// The OS/2 typographic ascender in font units at `location`, if the font has an OS/2 table and+/// the value is [`plausible`].+fn typo_ascent(f: &skrifa::FontRef<'_>, location: &Location, upem: f64) -> Option<f64> {+ use skrifa::raw::TableProvider;+ let mut v = f.os2().ok()?.s_typo_ascender() as f64;+ if !location.coords().is_empty()+ && let Ok(mvar) = f.mvar()+ {+ v += mvar.metric_delta(skrifa::raw::tables::mvar::tags::HASC, location.coords()).map_or(0.0, |d| d.to_f64());+ }+ plausible(Some(v), upem)+}++ /// `family` without the font-format suffix layout apps append when a family is installed in+ /// several formats (`Minion Pro (OTF)` → `Minion Pro`), if it has one.+ fn without_format_suffix(family: &str) -> Option<&str> {+ const FORMATS: [&str; 5] = ["OTF", "TT", "TTF", "TTC", "T1"];+ let (base, suffix) = family.trim_end().strip_suffix(')')?.rsplit_once('(')?;+ let base = base.trim_end();+ (!base.is_empty() && FORMATS.iter().any(|f| f.eq_ignore_ascii_case(suffix.trim()))).then_some(base)+ }+/// The named style part of a style with axis settings (`Bold {wght:650}` → `Bold`).pub fn base_style(style: &str) -> &str {style.split('{').next().unwrap_or(style).trim()@@@ -1258,51 -1227,14 +1267,59 @@@ impl ScopedFonts<'_>/// Style names available for `family` (Regular first, then by weight).pub fn styles(&self, family: &str) -> Vec<String> {- let v = self.exact_styles(family);+ self.style_traits(family).into_iter().map(|t| t.2).collect()+ }++ /// Weight and italic of a style of `family`: from the font when it is known, else from the+ /// style's name.+ pub fn traits_of(&self, family: &str, style: &str) -> (f32, bool) {+ let base = base_style(style);+ self.style_traits(family)+ .into_iter()+ .find(|t| t.2.eq_ignore_ascii_case(base))+ .map_or((style_weight(base), style_italic(base)), |(italic, weight, _)| (weight, italic))+ }++ /// Style linking: the style of `family` that sets bold (`bold`) and italic (`italic`) as asked+ /// and keeps the other from `current` (Bold from Italic is Bold Italic). `None` when the+ /// family has no such style.+ pub fn linked_style(&self, family: &str, current: &str, bold: Option<bool>, italic: Option<bool>) -> Option<String> {+ let (weight, cur_italic) = self.traits_of(family, current);+ let want_italic = italic.unwrap_or(cur_italic);+ let want_weight = match bold {+ Some(true) => 700.0,+ Some(false) => 400.0,+ None => weight,+ };+ // Width words (Condensed, Extended…) of the current style are kept when the family allows.+ const WIDTHS: &[&str] = &["condensed", "compressed", "narrow", "extended", "expanded", "wide"];+ let widths = |s: &str| {+ let n = norm(s);+ WIDTHS.iter().filter(|w| n.contains(*w)).count()+ };+ let cur_widths = widths(current);+ self.style_traits(family)+ .into_iter()+ .filter(|(i, w, _)| *i == want_italic && bold.is_none_or(|b| b == (*w >= 600.0)))+ .min_by(|a, b| {+ let key = |t: &(bool, f32, String)| ((t.1 - want_weight).abs(), usize::from(widths(&t.2) != cur_widths), t.2.len());+ let (ka, kb) = (key(a), key(b));+ ka.0.total_cmp(&kb.0).then(ka.1.cmp(&kb.1)).then(ka.2.cmp(&kb.2))+ })+ .map(|t| t.2)+ }++ /// `(italic, weight, name)` of each style of `family` (the document's, loaded, or installed),+ /// Regular first, then by weight.+ fn style_traits(&self, family: &str) -> Vec<(bool, f32, String)> {++ let v = self.exact_style_traits(family);+ match without_format_suffix(family) {- Some(base) if v.is_empty() => self.exact_styles(base),++ Some(base) if v.is_empty() => self.exact_style_traits(base),+ _ => v,+ }+ }+- fn exact_styles(&self, family: &str) -> Vec<String> {++ fn exact_style_traits(&self, family: &str) -> Vec<(bool, f32, String)> {let mut v: Vec<(bool, f32, String)> = self.own().iter()diff --cc crates/idml/src/tests.rsindex de5895d4f,f64045047..c6411b42a--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -1244,131 -858,37 +1244,166 @@@ fn arabic_story_and_table_directions_suassert_eq!(st.tables.values().next().unwrap().options.direction, designcraft_doc::TextDirection::RightToLeft);}+#[test]+fn drop_caps_import_and_round_trip() {+ // A style with a drop cap, its character style and a nested style through it; a paragraph+ // overriding it locally.+ let opener = r#"<ParagraphStyle Self="ParagraphStyle/Opener" Name="Opener" DropCapCharacters="1" DropCapLines="3">+ <Properties><DropCapStyle type="object">CharacterStyle/Strong</DropCapStyle><AllNestedStyles type="list"><ListItem type="record">+ <AppliedCharacterStyle type="object">CharacterStyle/Strong</AppliedCharacterStyle><Delimiter type="enumeration">Dropcap</Delimiter>+ <Repetition type="long">1</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles></Properties>+ </ParagraphStyle>+ </RootParagraphStyleGroup>"#;+ let styles = STYLES.replace("</RootParagraphStyleGroup>", opener);+ let story = r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener" DropCapCharacters="2" DropCapLines="2" DropCapStyle="CharacterStyle/$ID/[No character style]">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Once upon a time</Content></CharacterStyleRange>+ </ParagraphStyleRange>+ </Story>+</idPkg:Story>"#;+ let bytes = zip_files(&[+ ("designmap.xml", DESIGNMAP),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Styles.xml", &styles),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", SPREAD),+ ("Stories/Story_s1.xml", story),+ ]);+ let check = |d: &Document| {+ let st = d.styles.para("Opener").unwrap();+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines), (Some(1), Some(3)));+ assert_eq!(st.para.drop_cap_style.as_deref(), Some("Strong"));+ let ns = st.para.nested_styles.clone().unwrap();+ assert_eq!((ns[0].style.as_str(), &ns[0].until), ("Strong", &designcraft_doc::NestedUntil::Dropcap));+ let p = &d.stories.values().find(|s| s.text.starts_with("Once")).unwrap().paras[0];+ assert_eq!((p.para.drop_cap_chars, p.para.drop_cap_lines), (Some(2), Some(2)));+ assert_eq!(p.para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE));+ };+ let d = import_idml_with(&bytes, &|_| None).unwrap();+ check(&d);+ // The drop cap's character style isn't written to IDML (InDesign sets it through a Dropcap+ // nested style); Align Left Edge and Scale for Descenders are, as DropcapDetail.+ let mut d = d;+ if let Some(s) = d.styles_mut().para_mut("Opener") {+ s.para.drop_cap_align_left = Some(false);+ s.para.drop_cap_scale_descenders = Some(true);+ }+ let bytes = export_idml(&d);+ assert!(!zip_text(&bytes, "").contains("DropCapStyle"));+ assert!(zip_text(&bytes, "Resources/Styles.xml").contains(r#"DropcapDetail="2""#));+ let back = import_idml(&bytes).unwrap();+ let st = back.styles.para("Opener").unwrap();+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines, st.para.drop_cap_style.as_deref()), (Some(1), Some(3), None));+ assert_eq!((st.para.drop_cap_align_left, st.para.drop_cap_scale_descenders), (Some(false), Some(true)));+ assert_eq!(st.para.nested_styles.as_ref().map(|n| n[0].until.clone()), Some(designcraft_doc::NestedUntil::Dropcap));+}++/// Frames take the corners and Text Frame Options they don't write from their object style chain,+/// then `[None]`. Per-corner attributes win over the legacy all-corners pair, at each level; a+/// corner shape without a radius takes the chain's radius.+#[test]+fn frames_inherit_object_style_corners_and_text_frame_options() {+ use designcraft_doc::{AutoSize, FirstBaseline, VerticalJustification};+ use designcraft_geom::corners::CornerShape as C;+ // Anchors in the order top-left, bottom-left, bottom-right, top-right.+ let path = |x: f64| {+ let pts: String = [(x, 0.0), (x, 50.0), (x + 50.0, 50.0), (x + 50.0, 0.0)]+ .iter()+ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))+ .collect();+ format!(+ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#+ )+ };+ let corners = |opt: &str, r: &str| {+ ["TopLeft", "TopRight", "BottomLeft", "BottomRight"].map(|n| format!(r#"{n}CornerOption="{opt}" {n}CornerRadius="{r}""#)).join(" ")+ };+ let inset = |v: f64| {+ format!(+ r#"<Properties><InsetSpacing type="list">{}</InsetSpacing></Properties>"#,+ r#"<ListItem type="unit">V</ListItem>"#.replace('V', &v.to_string()).repeat(4)+ )+ };+ let designmap = format!(+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="20.2" Self="d">+<RootObjectStyleGroup Self="ro">+ <ObjectStyle Self="ObjectStyle/$ID/[None]" Name="$ID/[None]" {none}>+ <TextFramePreference TextColumnCount="1" TextColumnGutter="12" AutoSizingReferencePoint="CenterPoint" AutoSizingType="Off"/>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Rounded" Name="Rounded" TopLeftCornerOption="RoundedCorner" TopRightCornerOption="RoundedCorner" BottomLeftCornerOption="RoundedCorner" BottomRightCornerOption="RoundedCorner" TopLeftCornerRadius="6">+ <Properties><BasedOn type="object">ObjectStyle/$ID/[None]</BasedOn></Properties>+ <TextFramePreference TextColumnCount="2" TextColumnGutter="18" VerticalJustification="CenterAlign" FirstBaselineOffset="LeadingOffset" MinimumFirstBaselineOffset="4" IgnoreWrap="true" AutoSizingType="HeightOnly">{inset}</TextFramePreference>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Child" Name="Child" TopRightCornerOption="BevelCorner">+ <Properties><BasedOn type="object">ObjectStyle/Rounded</BasedOn></Properties>+ </ObjectStyle>+</RootObjectStyleGroup>+<Story Self="s1"/>+<Spread Self="sp1"><Page Self="p1"/>+<TextFrame Self="tf" ParentStory="s1" AppliedObjectStyle="ObjectStyle/Child" BottomRightCornerOption="InverseRoundedCorner" BottomRightCornerRadius="11.34">{p0}<TextFramePreference TextColumnCount="3"/></TextFrame>+<Rectangle Self="legacy" AppliedObjectStyle="ObjectStyle/Rounded" CornerOption="BevelCorner" CornerRadius="5" TopLeftCornerOption="InsetCorner">{p1}</Rectangle>+<Rectangle Self="one" TopRightCornerOption="RoundedCorner" TopRightCornerRadius="11.34">{p2}</Rectangle>+<Rectangle Self="plain" AppliedObjectStyle="ObjectStyle/Rounded">{p3}</Rectangle>+</Spread>+</Document>"#,+ none = corners("None", "12"),+ inset = inset(3.0),+ p0 = path(0.0),+ p1 = path(100.0),+ p2 = path(200.0),+ p3 = path(300.0),+ );+ let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap();+ let item = |n: usize| d.spreads[0].items[n].clone();+ // Path order: top-left, bottom-left, bottom-right, top-right.+ let shapes = |n: usize| item(n).corners.corners.map(|c| (c.shape, c.size));+ assert_eq!(shapes(0), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::InverseRounded, 11.34), (C::Bevel, 12.0)]);+ assert_eq!(shapes(1), [(C::Inset, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0)]);+ assert!(item(2).corners.corners.iter().enumerate().all(|(i, c)| (c.shape == C::Rounded) == (i == 3)));+ assert_eq!(item(2).corners.corners[3].size, 11.34);+ assert_eq!(shapes(3), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::Rounded, 12.0), (C::Rounded, 12.0)]);+ let tf = item(0);+ let o = &tf.text_frame().unwrap().options;+ assert_eq!((o.columns, o.gutter, o.inset), (3, 18.0, [3.0; 4]));+ assert_eq!((o.vertical_justification, o.first_baseline, o.first_baseline_min), (VerticalJustification::Center, FirstBaseline::Leading, 4.0));+ assert_eq!((o.ignore_wrap, o.auto_size, o.auto_size_ref), (true, AutoSize::HeightOnly, 4));+}+++ /// InDesign's designmap lists layers back to front; `Document::layers[0]` is the front layer.+ #[test]+ fn layers_import_and_export_in_stacking_order() {+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">+ <Layer Self="L1" Name="Background"/>+ <Layer Self="L2" Name="Content"/>+ <idPkg:Spread src="Spreads/Spread_s.xml"/>+ </Document>"#;+ let spread = r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+ <Spread Self="s">+ <Page Self="p" GeometricBounds="0 0 100 100" ItemTransform="1 0 0 1 0 0"/>+ <Rectangle Self="r" ItemLayer="L1">+ <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>+ <PathPointType Anchor="0 0"/><PathPointType Anchor="0 100"/>+ <PathPointType Anchor="100 100"/><PathPointType Anchor="100 0"/>+ </PathPointArray></GeometryPathType></PathGeometry></Properties>+ </Rectangle>+ </Spread>+ </idPkg:Spread>"#;+ let d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", spread)])).unwrap();+ let names = |d: &Document| d.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();+ assert_eq!(names(&d), ["Content", "Background"]);+ assert_eq!(d.spreads[0].items[0].layer, d.layers[1].id, "the rectangle stays on Background");++ let bytes = export_idml(&d);+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();+ let mut map = String::new();+ std::io::Read::read_to_string(&mut zip.by_name("designmap.xml").unwrap(), &mut map).unwrap();+ let (bg, content) = (map.find(r#"Name="Background""#).unwrap(), map.find(r#"Name="Content""#).unwrap());+ assert!(bg < content, "designmap lists the back layer first");+ let back = import_idml(&bytes).unwrap();+ assert_eq!(names(&back), ["Content", "Background"]);+ assert_eq!(back.spreads[0].items[0].layer, back.layers[1].id);+ }