Skip to content

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

Merge idml-feathers: IDML: gradient and directional feathers import and export

aiongg15bcbae7549d
diff --cc crates/idml/src/import.rs
index c4ce496f0,1a4fa1565..eda364410
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@@ -2483,10 -2092,32 +2483,22 @@@ impl<'r> Importer<'r>
{
it.effects = Effects { feather: f.num("Width").unwrap_or(9.0), ..it.effects.clone() };
}
+ if let Some(g) = t.find("GradientFeatherSetting")
+ && g.boolean("Applied") == Some(true)
+ {
+ it.effects.gradient_feather = gradient_feather_in(g);
+ }
+ if let Some(df) = t.find("DirectionalFeatherSetting")
+ && df.boolean("Applied") == Some(true)
+ {
+ let w = |k: &str| finite(df.num(k)).unwrap_or(0.0).max(0.0);
+ it.effects.directional_feather =
+ DirectionalFeather { on: true, widths: [w("TopWidth"), w("LeftWidth"), w("BottomWidth"), w("RightWidth")] };
+ }
}
// Text wrap.
- if let Some(w) = e.find("TextWrapPreference") {
- let mut tw = TextWrap {
- mode: names::wrap_mode_in(w.get("TextWrapMode").unwrap_or("None")),
- invert: w.get("Inverse") == Some("true"),
- side: names::wrap_side_in(w.get("TextWrapSide").unwrap_or("BothSides")),
- ..TextWrap::default()
- };
- if let Some(o) = w.prop_el("TextWrapOffset") {
- tw.offsets =
- [o.num("Top").unwrap_or(0.0), o.num("Left").unwrap_or(0.0), o.num("Bottom").unwrap_or(0.0), o.num("Right").unwrap_or(0.0)];
- }
- it.wrap = tw;
+ if let Some(w) = self.with_style(e, "TextWrapPreference") {
+ it.wrap = text_wrap(&w);
}
// Type on a path.
if tag != "TextFrame"
@@@ -2769,70 -2357,40 +2781,104 @@@
}
}
+/// The object style category flag that turns an effect element on or off.
+fn effect_flag(effect: &str) -> Option<&'static str> {
+ Some(match effect {
+ "BlendingSetting" => "EnableTransparency",
+ "DropShadowSetting" => "EnableDropShadow",
+ "FeatherSetting" => "EnableFeather",
+ "InnerShadowSetting" => "EnableInnerShadow",
+ "OuterGlowSetting" => "EnableOuterGlow",
+ "InnerGlowSetting" => "EnableInnerGlow",
+ "BevelAndEmbossSetting" => "EnableBevelEmboss",
+ "SatinSetting" => "EnableSatin",
+ "DirectionalFeatherSetting" => "EnableDirectionalFeather",
+ "GradientFeatherSetting" => "EnableGradientFeather",
+ _ => return None,
+ })
+}
+
+/// Lays `top` over `base`: attributes one by one, child elements matched by name and merged the same
+/// way, text replaced. A property given in one form (attribute or `Properties` child) replaces the
+/// other form in `base`.
+fn overlay(base: &mut El, top: &El, depth: usize) {
+ if depth > 32 {
+ *base = top.clone();
+ return;
+ }
+ for (k, v) in &top.attrs {
+ base.set(k, v);
+ if let Some(Node::El(p)) = base.children.iter_mut().find(|n| matches!(n, Node::El(p) if p.local() == "Properties")) {
+ p.children.retain(|n| !matches!(n, Node::El(x) if x.local() == k));
+ }
+ }
+ if let Some(p) = top.find("Properties") {
+ let names: Vec<&str> = p.elements().map(El::local).collect();
+ base.attrs.retain(|(k, _)| !names.contains(&k.as_str()));
+ }
+ let has_text = top.children.iter().any(|n| matches!(n, Node::Text(t) | Node::CData(t) if !t.trim().is_empty()));
+ if has_text {
+ base.children.retain(|n| !matches!(n, Node::Text(_) | Node::CData(_)));
+ }
+ // The k-th child of a name merges with the k-th child of that name in `base` (repeated elements
+ // such as gradient stops pair up in order).
+ let mut seen: HashMap<&str, usize> = HashMap::new();
+ for n in &top.children {
+ match n {
+ Node::El(c) => {
+ let k = seen.entry(c.local()).or_insert(0);
+ let slot = base
+ .children
+ .iter_mut()
+ .filter_map(|b| match b {
+ Node::El(b) if b.local() == c.local() => Some(b),
+ _ => None,
+ })
+ .nth(*k);
+ *k += 1;
+ match slot {
+ Some(b) => overlay(b, c, depth + 1),
+ None => base.children.push(n.clone()),
+ }
+ }
+ Node::Text(_) | Node::CData(_) if has_text => base.children.push(n.clone()),
+ _ => {}
+ }
+ }
+ fn finite(v: Option<f64>) -> Option<f64> {
+ v.filter(|v| v.is_finite())
+ }
+
+ /// A `GradientFeatherSetting`. The model holds two opacity stops at the ends of the gradient: the
+ /// first and last `OpacityGradientStop` give them; with a linear vector, their `Location`s move its
+ /// ends.
+ fn gradient_feather_in(g: &El) -> GradientFeather {
+ let def = GradientFeather::default();
+ let angle = finite(g.num("Angle")).unwrap_or(0.0);
+ let mut stops: Vec<(f64, f64)> = g
+ .find_all("OpacityGradientStop")
+ .filter_map(|s| Some((finite(s.num("Location"))?.clamp(0.0, 100.0) / 100.0, finite(s.num("Opacity"))?.clamp(0.0, 100.0) / 100.0)))
+ .collect();
+ stops.sort_by(|a, b| a.0.total_cmp(&b.0));
+ let (first, last) = match (stops.first(), stops.last()) {
+ (Some(&a), Some(&b)) => (a, b),
+ _ => ((0.0, def.start as f64), (1.0, def.end as f64)),
+ };
+ let start: Option<[f64; 2]> = g
+ .prop("GradientStart")
+ .and_then(|s| s.split_whitespace().map(|v| v.parse().ok().filter(|v: &f64| v.is_finite())).collect::<Option<Vec<f64>>>())
+ .and_then(|v| v.try_into().ok());
+ let radial = g.get("Type") == Some("Radial");
+ let vector = match (start, finite(g.num("Length"))) {
+ (Some([x, y]), Some(len)) if len > 0.0 => {
+ let a = angle.to_radians();
+ let (dx, dy) = (len * a.cos(), -len * a.sin());
+ let (l0, l1) = if !radial && last.0 > first.0 { (first.0, last.0) } else { (0.0, 1.0) };
+ Some([x + dx * l0, y + dy * l0, x + dx * l1, y + dy * l1])
+ }
+ _ => None,
+ };
+ GradientFeather { on: true, radial, angle, start: first.1 as f32, end: last.1 as f32, vector }
}
/// Drop-shadow angle (degrees) from IDML offsets (inverse of export's mapping).
diff --cc crates/idml/src/lib.rs
index 1f9d25661,5e37dd83f..2e8158378
--- a/crates/idml/src/lib.rs
+++ b/crates/idml/src/lib.rs
@@@ -32,16 -32,10 +32,17 @@@
//! - Nested/GREP/line styles, bullets & numbering details (bullet glyph, number format), OpenType
//! feature flags, paragraph borders, grid alignment, custom dashed stroke styles; column rule
//! stroke type and overprint.
- //! - Mixed inks, gradient stop opacity and gradient feathers, effects other than drop shadow and
- //! basic feather, EPS/PDF/AI placed graphics (imported as images when the data is available),
+ //! - Mixed inks, gradient stop opacity, gradient feather stops between the first and last, its
+ //! midpoints and highlight, directional feather angle, noise, choke and shape mode, other effects
+ //! than drop shadow and the feathers, stroke/fill/content transparency, EPS/PDF/AI placed graphics (imported as images when the data is available),
//! clipping paths, compound-path fill rules.
+//! - Placed PDFs: the page (`PageNumber`) and crop choice (`PDFCrop`) round-trip, and
+//! `GraphicBounds` span the chosen box. Where that box sits on the page needs the PDF parsed,
+//! which this crate doesn't do: the engine finds it after import (`file.openIdml`), and when the
+//! PDF's data isn't available the page's crop box fills `GraphicBounds`. The content crops
+//! (`CropContentVisibleLayers`, `CropContentAllLayers`) are the bounds of the page's
+//! non-transparent pixels on a render about 2048 pixels on its long side, so they can differ
+//! from a vector bounding box by a fraction of a point.
//! - Unknown elements are ignored; nothing is preserved opaquely for round-trip yet.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
diff --cc crates/idml/src/tests.rs
index 34a024ea9,976d308ae..880314136
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@@ -2384,381 -1400,92 +2384,469 @@@ fn list_numbering_format_expression_and
check(&import_idml(&export_idml(&d)).unwrap());
}
+/// InDesign can write `AppliedFont` with its `$ID/` prefix (`$ID/Source Serif 4`). The text is
+/// set in that family instead of counting as a missing font drawn in the fallback.
+#[test]
+fn applied_font_with_an_id_prefix_names_the_family() {
+ let styles = STYLES.replace(">Source Serif 4</AppliedFont>", ">$ID/Source Serif 4</AppliedFont>");
+ let story = STORY.replace(
+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14">"#,
+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14"><Properties><AppliedFont type="string">$ID/Source Serif 4</AppliedFont></Properties>"#,
+ );
+ 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 d = import_idml_with(&bytes, &|_| None).unwrap();
+ let fonts: Vec<&str> = d.styles.paragraph.iter().filter_map(|s| s.chars.font_family.as_deref()).collect();
+ assert!(!fonts.is_empty() && fonts.iter().all(|f| *f == "Source Serif 4"), "{fonts:?}");
+ let (sid, story) = d.stories.iter().next().unwrap();
+ let bold = story.runs().find(|(r, _)| story.text[r.clone()].starts_with("bold")).unwrap().1;
+ assert_eq!(bold.over.font_family.as_deref(), Some("Source Serif 4"));
+ // The bundled family draws the text (an unknown family would fall back to Source Sans 3).
+ let cs = designcraft_compose::compose_story(&d, *sid, &Default::default());
+ let first_para = story.text.find('\n').unwrap();
+ let families: Vec<&str> = cs
+ .frames
+ .iter()
+ .flat_map(|f| &f.lines)
+ .flat_map(|l| &l.glyphs)
+ .filter(|g| g.visible && g.len > 0 && g.byte < first_para)
+ .map(|g| g.face.get().family.as_str())
+ .collect();
+ assert!(!families.is_empty() && families.iter().all(|f| *f == "Source Serif 4"), "{families:?}");
+}
+
+#[test]
+fn list_tab_position_round_trips_as_a_tab_stop() {
+ use designcraft_doc::{ListType, ParaAttrs, ParagraphStyle, TabAlign, TabStop};
+ let stop = |position, align| TabStop { position, align, leader: String::new(), align_on: String::new() };
+ let mut d = Document::new(&NewDocument::default());
+ std::sync::Arc::make_mut(&mut d.styles).paragraph.push(ParagraphStyle {
+ name: "List".into(),
+ based_on: None,
+ next_style: None,
+ para: ParaAttrs { list_type: Some(ListType::Bullets), list_tab: Some(Some(24.0)), ..Default::default() },
+ chars: CharAttrs::default(),
+ shortcut: String::new(),
+ });
+ let local = ParaAttrs {
+ list_type: Some(ListType::Bullets),
+ list_tab: Some(Some(36.0)),
+ tabs: Some(vec![stop(100.0, TabAlign::Right)]),
+ ..Default::default()
+ };
+ let ended = ParaAttrs { list_type: Some(ListType::None), ..Default::default() };
+ let lid = d.default_layer();
+ for (i, (text, style, para)) in
+ [("Local\tx", "", local), ("Styled\ty", "List", ParaAttrs::default()), ("Ended\tz", "List", ended)].into_iter().enumerate()
+ {
+ let pf = ParaFormat { style: if style.is_empty() { ParaFormat::default().style } else { style.into() }, para, ..Default::default() };
+ let y = 40.0 + 100.0 * i as f64;
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, y, 300.0, y + 80.0), lid, text, pf).unwrap();
+ }
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let tabs = |prefix: &str| {
+ let s = back.stories.values().find(|s| s.text.starts_with(prefix)).unwrap();
+ back.styles.resolve_para(&s.paras[0]).0.tabs
+ };
+ assert_eq!(tabs("Local"), vec![stop(36.0, TabAlign::Left), stop(100.0, TabAlign::Right)]);
+ assert_eq!(tabs("Styled"), vec![stop(24.0, TabAlign::Left)]);
+ assert_eq!(tabs("Ended"), vec![], "a paragraph that ends the list has no list tab stop");
+}
+
+#[test]
+fn round_trips_the_zero_point_and_ruler_origin() {
+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });
+ d.settings.zero_point = [36.0, 18.5];
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(back.settings.zero_point, [36.0, 18.5]);
+ for origin in [designcraft_doc::RulerOrigin::Page, designcraft_doc::RulerOrigin::Spine, designcraft_doc::RulerOrigin::Spread] {
+ d.settings.ruler_origin = origin;
+ assert_eq!(import_idml(&export_idml(&d)).unwrap().settings.ruler_origin, origin);
+ }
+ // A hostile ZeroPoint lands on the pasteboard; a malformed one is ignored.
+ let fixture = |zp: &str| {
+ let designmap = format!(
+ r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d" ZeroPoint="{zp}">
+ <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"/></Spread>
+ </idPkg:Spread>"#;
+ import_idml(&zip_files(&[("designmap.xml", &designmap), ("Spreads/Spread_s.xml", spread)])).unwrap()
+ };
+ let [x, y] = fixture("1e300 -1e300").settings.zero_point;
+ assert!(x.is_finite() && y.is_finite() && x < 1e4 && y > -1e4, "{x} {y}");
+ assert_eq!(fixture("12").settings.zero_point, [0.0, 0.0]);
+ assert_eq!(fixture("NaN 4").settings.zero_point, [0.0, 0.0]);
+}
+
+#[test]
+fn kenten_shatai_and_grid_settings_import_and_round_trip() {
+ use designcraft_doc::cjk::CharacterAlignment;
+ use designcraft_doc::cjk_settings::{AdornmentOverprint, KentenAlignment, KentenKind, KentenPosition};
+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" AutoTcy="3" AutoTcyIncludeRoman="true" RotateSingleByteCharacters="true" AllowArbitraryHyphenation="true" GridAlignment="AlignEmCenter" GridAlignFirstLineOnly="true" GridGyoudori="2" ParagraphGyoudori="true">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" KentenKind="KentenSmallBlackCircle" KentenFontSize="6" KentenXScale="80" KentenYScale="120" KentenPlacement="1.5" KentenPosition="BelowLeft" KentenAlignment="AlignKentenLeft" KentenCharacterSet="CharacterInput" KentenTint="50" KentenStrokeTint="-1" KentenWeight="0.5" KentenOverprintFill="OverprintOn" KentenOverprintStroke="Auto" ShataiMagnification="20" ShataiDegreeAngle="6000" ShataiAdjustRotation="true" ShataiAdjustTsume="false"><Properties><KentenFont type="string">$ID/</KentenFont><KentenFontStyle type="enumeration">Nothing</KentenFontStyle><KentenFillColor type="string">Text Color</KentenFillColor></Properties><Content>甲乙</Content></CharacterStyleRange>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" KentenKind="Custom" KentenCustomCharacter="★"><Content>丙</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#;
+ let doc = import_idml(&fixture_with_story(story)).unwrap();
+ let st = doc.stories.values().find(|s| s.text.contains("甲乙")).unwrap();
+ let runs: Vec<CharAttrs> = st.runs().map(|(_, f)| f.over.clone()).collect();
+ let a = &runs[0];
+ assert_eq!((a.kenten, a.kenten_kind, a.kenten_character.as_deref()), (Some(true), Some(KentenKind::SmallBlackCircle), Some("\u{2022}")));
+ assert_eq!((a.kenten_size, a.kenten_x_scale, a.kenten_y_scale, a.kenten_distance), (Some(Some(6.0)), Some(0.8), Some(1.2), Some(1.5)));
+ assert_eq!((a.kenten_position, a.kenten_alignment), (Some(KentenPosition::BelowLeft), Some(KentenAlignment::Start)));
+ assert_eq!((a.kenten_font.as_deref(), a.kenten_font_style.as_deref(), a.kenten_fill.as_deref()), (Some(""), Some(""), Some("")));
+ assert_eq!((a.kenten_fill_tint, a.kenten_stroke_tint, a.kenten_stroke_weight), (Some(Some(0.5)), Some(None), Some(Some(0.5))));
+ assert_eq!((a.kenten_overprint_fill, a.kenten_overprint_stroke), (Some(AdornmentOverprint::On), Some(AdornmentOverprint::Auto)));
+ assert_eq!(a.kenten_character_set.as_deref(), Some("CharacterInput"));
+ assert_eq!(
+ (a.shatai_magnification, a.shatai_angle, a.shatai_adjust_rotation, a.shatai_adjust_tsume),
+ (Some(20.0), Some(60.0), Some(true), Some(false))
+ );
+ let custom = runs.iter().find(|r| r.kenten_kind == Some(KentenKind::Custom)).unwrap();
+ assert_eq!(custom.kenten_character.as_deref(), Some("★"));
+ let p = &st.paras[0].para;
+ assert_eq!((p.auto_tcy, p.auto_tcy_include_roman, p.rotate_roman, p.roman_word_break), (Some(3), Some(true), Some(true), Some(true)));
+ assert_eq!((p.grid_align, p.grid_reference), (Some(designcraft_doc::GridAlign::FirstLineOnly), Some(CharacterAlignment::EmCenter)));
+ assert_eq!((p.grid_gyoudori, p.paragraph_gyoudori), (Some(2), Some(true)));
+
+ let back = import_idml(&export_idml(&doc)).unwrap();
+ let st2 = back.stories.values().find(|s| s.text.contains("甲乙")).unwrap();
+ let runs2: Vec<CharAttrs> = st2.runs().map(|(_, f)| f.over.clone()).collect();
+ for (a, b) in runs.iter().zip(&runs2) {
+ assert_eq!((a.kenten, a.kenten_kind, &a.kenten_character), (b.kenten, b.kenten_kind, &b.kenten_character));
+ assert_eq!(
+ (a.kenten_size, a.kenten_x_scale, a.kenten_y_scale, a.kenten_distance),
+ (b.kenten_size, b.kenten_x_scale, b.kenten_y_scale, b.kenten_distance)
+ );
+ assert_eq!(
+ (a.kenten_position, a.kenten_alignment, &a.kenten_character_set),
+ (b.kenten_position, b.kenten_alignment, &b.kenten_character_set)
+ );
+ assert_eq!((&a.kenten_font, &a.kenten_font_style, &a.kenten_fill), (&b.kenten_font, &b.kenten_font_style, &b.kenten_fill));
+ assert_eq!(
+ (a.kenten_fill_tint, a.kenten_stroke_tint, a.kenten_stroke_weight),
+ (b.kenten_fill_tint, b.kenten_stroke_tint, b.kenten_stroke_weight)
+ );
+ assert_eq!((a.kenten_overprint_fill, a.kenten_overprint_stroke), (b.kenten_overprint_fill, b.kenten_overprint_stroke));
+ assert_eq!(
+ (a.shatai_magnification, a.shatai_angle, a.shatai_adjust_rotation, a.shatai_adjust_tsume),
+ (b.shatai_magnification, b.shatai_angle, b.shatai_adjust_rotation, b.shatai_adjust_tsume)
+ );
+ }
+ let p2 = &st2.paras[0].para;
+ assert_eq!(
+ (p.auto_tcy, p.auto_tcy_include_roman, p.rotate_roman, p.roman_word_break),
+ (p2.auto_tcy, p2.auto_tcy_include_roman, p2.rotate_roman, p2.roman_word_break)
+ );
+ assert_eq!(
+ (p.grid_align, p.grid_reference, p.grid_gyoudori, p.paragraph_gyoudori),
+ (p2.grid_align, p2.grid_reference, p2.grid_gyoudori, p2.paragraph_gyoudori)
+ );
+}
+
+#[test]
+fn ruby_settings_import_from_idml_and_round_trip() {
+ use designcraft_doc::cjk_settings::AdornmentOverprint;
+ use designcraft_doc::ruby::{RubyAlignment, RubyOverhang, RubyParentSpacing, RubyPosition, RubyType};
+ // InDesign's names: RubyFlag is a number, colours and fonts are properties.
+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" RubyFlag="1" RubyString="かん じ" RubyType="PerCharacterRuby" RubyAlignment="RubyCenter" RubyPosition="BelowLeft" RubyYOffset="-1.4173228" RubyFontSize="-1" RubyXScale="90" RubyParentOverhangAmount="RubyOverhangNoLimit" RubyParentSpacing="RubyParentBothSides" RubyAutoAlign="false" RubyAutoScaling="true" RubyParentScalingPercent="40" RubyAutoTcyDigits="2" RubyTint="-1" RubyOverprintFill="Auto"><Properties><RubyFont type="string">$ID/</RubyFont><RubyFontStyle type="enumeration">Nothing</RubyFontStyle><RubyFill type="string">Text Color</RubyFill></Properties><Content>漢字</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#;
+ let doc = import_idml(&fixture_with_story(story)).unwrap();
+ let a = doc.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();
+ assert_eq!(a.ruby.as_deref(), Some("かん じ"));
+ assert_eq!(a.ruby_type, Some(RubyType::PerCharacter));
+ assert_eq!(a.ruby_alignment, Some(RubyAlignment::Center));
+ assert_eq!(a.ruby_position, Some(RubyPosition::BelowLeft));
+ assert_eq!(a.ruby_y_offset, Some(-1.4173228));
+ assert_eq!(a.ruby_font_size, Some(None));
+ assert_eq!(a.ruby_x_scale, Some(0.9));
+ assert_eq!(a.ruby_overhang_amount, Some(RubyOverhang::NoLimit));
+ assert_eq!(a.ruby_parent_spacing, Some(RubyParentSpacing::BothSides));
+ assert_eq!((a.ruby_auto_align, a.ruby_auto_scaling, a.ruby_scaling_min), (Some(false), Some(true), Some(0.4)));
+ assert_eq!(a.ruby_auto_tcy_digits, Some(2));
+ assert_eq!((a.ruby_font.as_deref(), a.ruby_font_style.as_deref(), a.ruby_fill.as_deref()), (Some(""), Some(""), Some("")));
+ assert_eq!((a.ruby_fill_tint, a.ruby_overprint_fill), (Some(None), Some(AdornmentOverprint::Auto)));
+
+ // Every setting survives export and import.
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 300.0, 200.0), lid, "漢字", ParaFormat::default()).unwrap();
+ d.story_mut(sid).unwrap().format_chars(0.."漢字".len(), |f| {
+ let o = &mut f.over;
+ o.ruby = Some("かん じ".into());
+ o.ruby_type = Some(RubyType::PerCharacter);
+ o.ruby_alignment = Some(RubyAlignment::OneAki);
+ o.ruby_position = Some(RubyPosition::BelowLeft);
+ o.ruby_x_offset = Some(1.5);
+ o.ruby_y_offset = Some(-1.25);
+ o.ruby_font = Some("Source Sans 3".into());
+ o.ruby_font_style = Some("Bold".into());
+ o.ruby_font_size = Some(Some(7.0));
+ o.ruby_x_scale = Some(0.9);
+ o.ruby_y_scale = Some(1.1);
+ o.ruby_open_type_pro = Some(false);
+ o.ruby_auto_tcy_digits = Some(3);
+ o.ruby_auto_tcy_include_roman = Some(true);
+ o.ruby_auto_tcy_auto_scale = Some(false);
+ o.ruby_overhang = Some(true);
+ o.ruby_overhang_amount = Some(RubyOverhang::HalfChar);
+ o.ruby_parent_spacing = Some(RubyParentSpacing::EqualAki);
+ o.ruby_auto_align = Some(false);
+ o.ruby_auto_scaling = Some(true);
+ o.ruby_scaling_min = Some(0.5);
+ o.ruby_fill = Some("[Black]".into());
+ o.ruby_fill_tint = Some(Some(0.5));
+ o.ruby_stroke = Some(String::new());
+ o.ruby_stroke_tint = Some(None);
+ o.ruby_stroke_weight = Some(Some(0.25));
+ o.ruby_overprint_fill = Some(AdornmentOverprint::On);
+ o.ruby_overprint_stroke = Some(AdornmentOverprint::Off);
+ });
+ let a = d.stories[&sid].runs().next().unwrap().1.over.clone();
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let b = back.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();
+ macro_rules! same {
+ ($($f:ident),*) => { $( assert_eq!(a.$f, b.$f, stringify!($f)); )* };
+ }
+ same!(
+ ruby,
+ ruby_type,
+ ruby_alignment,
+ ruby_position,
+ ruby_x_offset,
+ ruby_y_offset,
+ ruby_font,
+ ruby_font_style,
+ ruby_font_size,
+ ruby_x_scale,
+ ruby_y_scale,
+ ruby_open_type_pro,
+ ruby_auto_tcy_digits,
+ ruby_auto_tcy_include_roman,
+ ruby_auto_tcy_auto_scale,
+ ruby_overhang,
+ ruby_overhang_amount,
+ ruby_parent_spacing,
+ ruby_auto_align,
+ ruby_auto_scaling,
+ ruby_scaling_min,
+ ruby_fill,
+ ruby_fill_tint,
+ ruby_stroke,
+ ruby_stroke_tint,
+ ruby_stroke_weight,
+ ruby_overprint_fill,
+ ruby_overprint_stroke
+ );
+}
+
+/// A file's tab list is sanitized as the Tabs commands check theirs: a hostile one imports
+/// within the limits instead of failing the import.
+#[test]
+fn hostile_tab_lists_import_within_the_limits() {
+ let item = |position: &str, leader: &str| {
+ format!(
+ r#"<ListItem type="record"><Alignment type="enumeration">LeftAlign</Alignment><AlignmentCharacter type="string">.</AlignmentCharacter><Leader type="string">{leader}</Leader><Position type="unit">{position}</Position></ListItem>"#
+ )
+ };
+ let mut items: String = (0..500).rev().map(|i| item(&(i * 3).to_string(), "")).collect();
+ items.push_str(&item("NaN", ""));
+ items.push_str(&item("1e300", "0123456789"));
+ let story = format!(
+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">
+ <Properties><TabList type="list">{items}</TabList></Properties>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Many tabs</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#
+ );
+ let report = import_idml_report(&fixture_with_story(&story), &|_| None).unwrap();
+ assert!(report.warnings.iter().any(|w| w.starts_with("tab lists repaired to fit the limits") && w.ends_with("): 1")), "{:?}", report.warnings);
+ let doc = report.document;
+ let tabs = doc.stories.values().find(|s| s.text.contains("Many tabs")).unwrap().paras[0].para.tabs.clone().unwrap();
+ assert_eq!(tabs.len(), designcraft_doc::MAX_TAB_STOPS);
+ assert!(tabs.iter().all(|t| t.position.is_finite() && t.leader.chars().count() <= designcraft_doc::MAX_TAB_LEADER));
+ assert!(tabs.windows(2).all(|w| w[0].position < w[1].position), "sorted");
+ assert_eq!((tabs[0].position, tabs[99].position), (0.0, 297.0), "the first stops by position");
+ // A list within the limits, unsorted and with a char stop on `.`, imports without a warning.
+ let fine = format!(
+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">
+ <Properties><TabList type="list">{}{}<ListItem type="record"><Alignment type="enumeration">CharacterAlign</Alignment><AlignmentCharacter type="string">.</AlignmentCharacter><Leader type="string"></Leader><Position type="unit">40</Position></ListItem></TabList></Properties>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Few tabs</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#,
+ item("90", "."),
+ item("12", "")
+ );
+ let report = import_idml_report(&fixture_with_story(&fine), &|_| None).unwrap();
+ assert!(report.warnings.is_empty(), "{:?}", report.warnings);
+}
+
+#[test]
+fn cell_edge_gap_colours_and_tints_import_and_round_trip_per_edge() {
+ let styles = CASCADE_STYLES.replace(
+ r#"TopEdgeStrokeType="StrokeStyle/$ID/Dashed""#,
+ r#"TopEdgeStrokeType="StrokeStyle/$ID/Dashed" TopEdgeStrokeGapColor="Color/Paper" TopEdgeStrokeGapTint="60" BottomEdgeStrokeGapColor="Color/Brand""#,
+ );
+ let story = CASCADE_STORY.replace(
+ r#"<Cell Name="1:1">"#,
+ r#"<Cell Name="1:1" LeftEdgeStrokeType="StrokeStyle/$ID/Dotted" LeftEdgeStrokeGapColor="Color/Brand" LeftEdgeStrokeGapTint="30" RightEdgeStrokeGapColor="Color/Paper">"#,
+ );
+ let gaps = |d: &Document| {
+ let base = d.styles.cell.iter().find(|s| s.name == "Base").unwrap().strokes.clone();
+ let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();
+ let cell = table.cell(1, 1).unwrap().strokes.clone();
+ (base.map(|e| (e.gap_color, e.gap_tint)), cell.map(|e| (e.gap_color, e.gap_tint)))
+ };
+ let d = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();
+ d.check().unwrap();
+ let (style, cell) = gaps(&d);
+ assert_eq!(style[0], (Some("[Paper]".to_string()), Some(0.6)));
+ assert_eq!(style[2], (Some("Brand".to_string()), None));
+ assert_eq!((style[1].clone(), style[3].clone()), ((None, None), (None, None)));
+ assert_eq!(cell[1], ("Brand".to_string(), 0.3), "left");
+ assert_eq!(cell[3], ("[Paper]".to_string(), 1.0), "right");
+ assert_eq!(cell[0].0, "[Paper]", "the Base style's top gap colour reaches the cell");
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(gaps(&back), (style, cell));
+}
+
+#[test]
+fn em_box_first_baseline_offset_round_trips() {
+ use designcraft_doc::FirstBaseline;
+ let first = |d: &Document| d.spreads[0].items[0].text_frame().unwrap().options.first_baseline;
+ let d = inset_fixture(r#"<TextFramePreference FirstBaselineOffset="EmboxHeight"/>"#, "");
+ assert_eq!(first(&d), FirstBaseline::EmboxHeight);
+ assert_eq!(first(&import_idml(&export_idml(&d)).unwrap()), FirstBaseline::EmboxHeight);
+ let unknown = inset_fixture(r#"<TextFramePreference FirstBaselineOffset="SomethingElse"/>"#, "");
+ assert_eq!(first(&unknown), FirstBaseline::Ascent);
+}
+
+#[test]
+fn imports_and_round_trips_text_wrap_side_and_contour_type() {
+ let wrap = r#"<TextWrapPreference TextWrapMode="Contour" TextWrapSide="LeftSide"><ContourOption ContourType="BoundingBox" IncludeInsideEdges="false"/></TextWrapPreference><Image Self="im""#;
+ let spread = SPREAD.replace(r#"<Image Self="im""#, wrap);
+ assert_ne!(spread, SPREAD);
+ 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 mut d = import_idml(&bytes).unwrap();
+ let id = d.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().id;
+ let w = d.item(id).unwrap().wrap;
+ assert_eq!(
+ (w.mode, w.side, w.contour),
+ (designcraft_doc::WrapMode::Contour, designcraft_doc::WrapSide::LeftSide, designcraft_doc::ContourType::BoundingBox)
+ );
+ // Every side and contour type survives export and import (detected edges included, which
+ // composition follows as the frame's path).
+ d.item_mut(id).unwrap().wrap.side = designcraft_doc::WrapSide::AwayFromSpine;
+ d.item_mut(id).unwrap().wrap.contour = designcraft_doc::ContourType::DetectEdges;
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let w = back.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().wrap;
+ assert_eq!((w.side, w.contour), (designcraft_doc::WrapSide::AwayFromSpine, designcraft_doc::ContourType::DetectEdges));
+ fn feather_fixture(transparency: &str) -> Document {
+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">
+ <idPkg:Spread src="Spreads/Spread_s.xml"/>
+ </Document>"#;
+ let rect = |id: &str, inner: &str| {
+ format!(
+ r#"<Rectangle Self="{id}" ItemTransform="1 0 0 1 0 0">
+ <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>
+ {inner}
+ </Rectangle>"#
+ )
+ };
+ let spread = format!(
+ r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
+ <Spread Self="s">
+ <Page Self="p" GeometricBounds="0 0 200 200" ItemTransform="1 0 0 1 0 0"/>
+ {}{}
+ </Spread>
+ </idPkg:Spread>"#,
+ rect("a", transparency),
+ rect("b", "")
+ );
+ import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", &spread)])).unwrap()
+ }
+
+ #[test]
+ fn imports_gradient_and_directional_feathers() {
+ let d = feather_fixture(
+ r#"<TransparencySetting>
+ <GradientFeatherSetting Applied="true" Type="Linear" Angle="0" Length="50" GradientStart="10 20">
+ <OpacityGradientStop Self="s0" Opacity="90" Location="20"/>
+ <OpacityGradientStop Self="s2" Opacity="10" Location="80" Midpoint="40"/>
+ <OpacityGradientStop Self="s1" Opacity="55" Location="50" Midpoint="50"/>
+ </GradientFeatherSetting>
+ <DirectionalFeatherSetting Applied="true" LeftWidth="3" RightWidth="4" TopWidth="5" BottomWidth="6" Angle="0" Noise="0" ChokeAmount="0"/>
+ </TransparencySetting>"#,
+ );
+ let items = &d.spreads[0].items;
+ let gf = &items[0].effects.gradient_feather;
+ assert!(gf.on && !gf.radial);
+ assert!((gf.start - 0.9).abs() < 1e-6 && (gf.end - 0.1).abs() < 1e-6, "{gf:?}");
+ let v = gf.vector.unwrap();
+ for (a, b) in v.iter().zip([20.0, 20.0, 50.0, 20.0]) {
+ assert!((a - b).abs() < 1e-9, "{v:?}");
+ }
+ let df = &items[0].effects.directional_feather;
+ assert!(df.on);
+ assert_eq!(df.widths, [5.0, 3.0, 6.0, 4.0]);
+ assert_eq!(items[1].effects, designcraft_doc::Effects::default());
+
+ // Not applied: the settings stay off.
+ let off = feather_fixture(
+ r#"<TransparencySetting>
+ <GradientFeatherSetting Applied="false" Length="50" GradientStart="10 20"/>
+ <DirectionalFeatherSetting Applied="false" LeftWidth="3"/>
+ </TransparencySetting>"#,
+ );
+ assert_eq!(off.spreads[0].items[0].effects, designcraft_doc::Effects::default());
+ }
+
+ #[test]
+ fn gradient_and_directional_feathers_round_trip() {
+ use designcraft_doc::{DirectionalFeather, GradientFeather, Item, ItemId};
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let add = |d: &mut Document, effects: designcraft_doc::Effects| {
+ let mut it = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(40.0, 40.0, 140.0, 120.0)));
+ it.effects = effects;
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ };
+ let linear = designcraft_doc::Effects {
+ gradient_feather: GradientFeather { on: true, radial: false, angle: 0.0, start: 0.75, end: 0.25, vector: Some([50.0, 60.0, 110.0, 60.0]) },
+ directional_feather: DirectionalFeather { on: true, widths: [1.0, 2.0, 3.0, 4.0] },
+ ..Default::default()
+ };
+ let radial = designcraft_doc::Effects {
+ gradient_feather: GradientFeather { on: true, radial: true, angle: 30.0, start: 0.0, end: 1.0, vector: None },
+ ..Default::default()
+ };
+ add(&mut d, linear.clone());
+ add(&mut d, radial.clone());
+ add(&mut d, designcraft_doc::Effects::default());
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let effects: Vec<_> = back.spreads[0].items.iter().map(|i| i.effects.clone()).collect();
+ assert_eq!(effects, [linear, radial, designcraft_doc::Effects::default()]);
}