DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge idml-deleted-text: IDML: tracked deleted text takes no room in the layout (#581)
aiongge2eae1c62b47
diff --cc crates/compose/src/lib.rsindex 00097bf4c,1c24df693..5ff6cdc74--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -740,11 -498,12 +740,12 @@@ fn compose_with_db(doc: &Document, stor};let para_ranges = story.para_ranges();let np = para_ranges.len();+ let deleted = deleted_paras(story, ¶_ranges);let hyph_exceptions = doc.hyphenation_exception_map();- let mut list_counter: u32 = 0;- // Named lists number independently of layout: one pass up front.- let named_numbers: Vec<Option<u32>> = {- let mut counters: std::collections::HashMap<String, u32> = std::collections::HashMap::new();+ let mut list_counter = ListCounter::default();+ // Named lists number independently of layout: one pass up front, for the labels.+ let named_labels: Vec<Option<String>> = {+ let mut counters: std::collections::HashMap<String, ListCounter> = std::collections::HashMap::new();story.paras.iter()@@@ -809,8 -567,29 +811,29 @@@pi = j;continue 'paras;}+ if deleted.get(pi).copied().unwrap_or(false) {+ // A deleted paragraph takes no room; for keeps it stands in for the one before it.+ let filler = info.last().map_or(+ ParaInfo {+ start: (cur.fi, cur.col),+ at_top: cur.last_baseline.is_none(),+ end: (cur.fi, cur.col),+ lines: 0,+ lines_in_end_col: 0,+ keep_with_next: 0,+ keep_together: false,+ keep_all: false,+ keep_first: 1,+ keep_last: 1,+ },+ |p| ParaInfo { lines_in_end_col: 0, ..p.clone() },+ );+ info.push(filler);+ pi += 1;+ continue;+ }let pf = &story.paras[pi];- let (pp, base_chars) = doc.styles.resolve_para(pf);+ let (mut pp, base_chars) = doc.styles.resolve_para(pf);// A break character that ends the previous paragraph sends this one on, like a start option.let after_break = pi.checked_sub(1)diff --cc crates/idml/src/export.rsindex 54383b569,8e9706ca0..0ddf21f16--- a/crates/idml/src/export.rs+++ b/crates/idml/src/export.rs@@@ -2948,170 -2686,11 +2968,179 @@@ fn topic_self(path: &[String]) -> Strins}+/// Package metadata: the creation and modification times that date variables show.+fn metadata_xmp(d: &Document) -> String {+ use designcraft_doc::vars::format_date;+ let iso = |t: i64| format!("{}:{:02}Z", format_date(t, "yyyy-MM-ddTHH:mm"), t.rem_euclid(60));+ let modified = if d.modified > 0 { d.modified } else { d.created };+ format!(+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description rdf:about=\"\" xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\">\n <xmp:CreateDate>{}</xmp:CreateDate>\n <xmp:ModifyDate>{}</xmp:ModifyDate>\n </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n",+ iso(d.created),+ iso(modified)+ )+}++/// A text variable definition with its type's settings element.+fn text_variable_el(v: &designcraft_doc::vars::TextVariable) -> El {+ use designcraft_doc::vars::{Use, VarKind};+ let pref = |name: &str| El::new(name).attr("TextBefore", &v.before);+ let (ty, settings) = match &v.kind {+ VarKind::Custom { text } => ("CustomTextType", Some(pref("CustomTextVariablePreference").attr("Contents", text))),+ VarKind::LastPageNumber { section } => (+ "LastPageNumberType",+ Some(+ pref("PageNumberVariablePreference").attr("Format", "Current").attr("Scope", if *section { "SectionScope" } else { "DocumentScope" }),+ ),+ ),+ VarKind::ChapterNumber => ("ChapterNumberType", Some(pref("ChapterNumberVariablePreference").attr("Format", "Current"))),+ VarKind::FileName { extension } => {+ ("FileNameType", Some(pref("FileNameVariablePreference").attr("IncludePath", "false").attr("IncludeExtension", bool_s(*extension))))+ }+ VarKind::CreationDate { format } => ("CreationDateType", Some(pref("DateVariablePreference").attr("Format", format))),+ VarKind::ModificationDate { format } => ("ModificationDateType", Some(pref("DateVariablePreference").attr("Format", format))),+ VarKind::OutputDate { format } => ("OutputDateType", Some(pref("DateVariablePreference").attr("Format", format))),+ VarKind::RunningHeader { style, use_, character } => {+ let (ty, el, key, style_ref) = if *character {+ (+ "MatchCharacterStyleType",+ "MatchCharacterStylePreference",+ "AppliedCharacterStyle",+ names::style_self("CharacterStyle", CHAR_BUILTINS, style),+ )+ } else {+ (+ "MatchParagraphStyleType",+ "MatchParagraphStylePreference",+ "AppliedParagraphStyle",+ names::style_self("ParagraphStyle", PARA_BUILTINS, style),+ )+ };+ let strategy = if *use_ == Use::LastOnPage { "LastOnPage" } else { "FirstOnPage" };+ (+ ty,+ Some(pref(el).attr(key, style_ref).attr("SearchStrategy", strategy).attr("ChangeCase", "None").attr("DeleteEndPunctuation", "false")),+ )+ }+ VarKind::Imported { variable_type, settings_element, settings, .. } => {+ let el = (!settings_element.is_empty()).then(|| El { name: settings_element.clone(), attrs: settings.clone(), children: vec![] });+ (variable_type.as_str(), el)+ }+ };+ let mut e = El::new("TextVariable").attr("Self", format!("dTextVariablen{}", v.name)).attr("Name", &v.name).attr("VariableType", ty);+ if let Some(mut s) = settings {+ if !matches!(v.kind, VarKind::Imported { .. }) {+ s.set("TextAfter", &v.after);+ }+ e.push(s);+ }+ e+}++/// Auto tate-chu-yoko, Japanese composition and grid settings of a paragraph range or style.+fn cjk_settings_para(el: &mut El, a: &ParaAttrs) {+ if let Some(v) = a.auto_tcy {+ el.set("AutoTcy", v);+ }+ if let Some(v) = a.auto_tcy_include_roman {+ el.set("AutoTcyIncludeRoman", bool_s(v));+ }+ if let Some(v) = a.rotate_roman {+ el.set("RotateSingleByteCharacters", bool_s(v));+ }+ if let Some(v) = a.roman_word_break {+ el.set("AllowArbitraryHyphenation", bool_s(v));+ }+ if let Some(v) = a.grid_gyoudori {+ el.set("GridGyoudori", v);+ }+ if let Some(v) = a.paragraph_gyoudori {+ el.set("ParagraphGyoudori", bool_s(v));+ }+}++impl Ex<'_> {+ /// Kenten Settings, Kenten Color and Shatai of a character range or style.+ fn cjk_settings_chars(&self, el: &mut El, props: &mut Vec<El>, a: &CharAttrs) {+ use designcraft_doc::cjk_settings::KentenKind;+ if let Some(k) = a.kenten_kind+ && a.kenten != Some(false)+ {+ el.set("KentenKind", crate::cjk::kenten_kind_out(k));+ if k != KentenKind::Custom {+ el.attrs.retain(|(n, _)| n != "KentenCustomCharacter");+ } else if let Some(c) = &a.kenten_character {+ el.set("KentenCustomCharacter", c);+ }+ }+ if let Some(f) = &a.kenten_font {+ props.push(p("KentenFont", "string", if f.is_empty() { "$ID/".to_string() } else { f.clone() }));+ }+ if let Some(st) = &a.kenten_font_style {+ props.push(if st.is_empty() { p("KentenFontStyle", "enumeration", "Nothing") } else { p("KentenFontStyle", "string", st.clone()) });+ }+ if let Some(Some(v)) = a.kenten_size {+ el.set("KentenFontSize", num(v));+ }+ if let Some(v) = a.kenten_x_scale {+ el.set("KentenXScale", num(v * 100.0));+ }+ if let Some(v) = a.kenten_y_scale {+ el.set("KentenYScale", num(v * 100.0));+ }+ if let Some(v) = a.kenten_distance {+ el.set("KentenPlacement", num(v));+ }+ if let Some(v) = a.kenten_position {+ el.set("KentenPosition", crate::cjk::kenten_position_out(v));+ }+ if let Some(v) = a.kenten_alignment {+ el.set("KentenAlignment", crate::cjk::kenten_alignment_out(v));+ }+ if let Some(v) = &a.kenten_character_set {+ el.set("KentenCharacterSet", v);+ }+ // The text's own colour is the string "Text Color" (a property); a swatch is a reference.+ for (key, color) in [("KentenFillColor", &a.kenten_fill), ("KentenStrokeColor", &a.kenten_stroke)] {+ match color {+ Some(c) if c.is_empty() => props.push(p(key, "string", "Text Color")),+ Some(c) => el.set(key, self.sw(c)),+ None => {}+ }+ }+ for (key, tint) in [("KentenTint", a.kenten_fill_tint), ("KentenStrokeTint", a.kenten_stroke_tint)] {+ if let Some(t) = tint {+ el.set(key, t.map_or_else(|| "-1".to_string(), |t| num(f64::from(t) * 100.0)));+ }+ }+ if let Some(w) = a.kenten_stroke_weight {+ el.set("KentenWeight", w.map_or_else(|| "-1".to_string(), num));+ }+ if let Some(v) = a.kenten_overprint_fill {+ el.set("KentenOverprintFill", crate::cjk::overprint_out(v));+ }+ if let Some(v) = a.kenten_overprint_stroke {+ el.set("KentenOverprintStroke", crate::cjk::overprint_out(v));+ }+ if let Some(v) = a.shatai_magnification {+ el.set("ShataiMagnification", num(v));+ }+ if let Some(v) = a.shatai_angle {+ el.set("ShataiDegreeAngle", num(v * crate::cjk::SHATAI_ANGLE_UNITS));+ }+ if let Some(v) = a.shatai_adjust_rotation {+ el.set("ShataiAdjustRotation", bool_s(v));+ }+ if let Some(v) = a.shatai_adjust_tsume {+ el.set("ShataiAdjustTsume", bool_s(v));+ }+ }+}+++ /// The IDML `ChangeType` of a tracked change.+ fn change_type(mark: Option<designcraft_doc::ChangeMark>) -> Option<&'static str> {+ match mark {+ Some(designcraft_doc::ChangeMark::Deleted) => Some("DeletedText"),+ Some(designcraft_doc::ChangeMark::Inserted) => Some("InsertedText"),+ _ => None,+ }+ }diff --cc crates/idml/src/import.rsindex ea5f16012,91f486995..87fc538db--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@@ -2021,15 -1725,6 +2021,16 @@@ impl<'r> Importer<'r>t}+ /// The format of the text in a `CharacterStyleRange`: its style, and its local attributes over- /// the enclosing paragraph range's.- fn range_format(&mut self, c: &El, pchars: &CharAttrs) -> CharFormat {++ /// the enclosing paragraph range's, inside a tracked change if `outer` (the enclosing format) is.++ fn range_format(&mut self, c: &El, pchars: &CharAttrs, outer: &CharFormat) -> CharFormat {+ let style = c.get("AppliedCharacterStyle").map(|r| self.char_style_ref(r)).unwrap_or_else(|| st::NO_CHAR_STYLE.into());+ let mut over = pchars.clone();+ over.merge(&self.char_attrs(c));++ over.change = over.change.or(outer.over.change);+ CharFormat { style, over }+ }+fn walk_story(&mut self, e: &El, b: &mut StoryBuilder, pf: &ParaFormat, pchars: &CharAttrs, cf: &CharFormat, brk: Option<&str>) {for n in &e.children {match n {@@@ -2044,13 -1739,14 +2045,13 @@@{*last = npf.clone();}- self.walk_story(c, b, &npf, &chars, cf, None);+ // Text and markers outside any character range (a destination or a+ // cross-reference source at paragraph level) take the paragraph's format.+ let pcf = CharFormat { style: st::NO_CHAR_STYLE.into(), over: chars.clone() };+ self.walk_story(c, b, &npf, &chars, &pcf, None);}"CharacterStyleRange" => {- let ncf = self.range_format(c, pchars);- let style = c.get("AppliedCharacterStyle").map(|r| self.char_style_ref(r)).unwrap_or_else(|| st::NO_CHAR_STYLE.into());- let mut over = pchars.clone();- over.merge(&self.char_attrs(c));- over.change = over.change.or(cf.over.change);- let ncf = CharFormat { style, over };++ let ncf = self.range_format(c, pchars, cf);let bt = c.get("ParagraphBreakType").filter(|t| *t != "Anywhere");b.last = ncf.clone();self.walk_story(c, b, pf, pchars, &ncf, bt);@@@ -2114,9 -1810,11 +2115,9 @@@"CrossReferenceSource" => {// The generated text is regenerated from the format.b.xrefs.push((c.get("Self").unwrap_or("").to_string(), c.get("AppliedFormat").unwrap_or("").to_string()));- let inner = c.find("CharacterStyleRange");- let f = match inner.and_then(|r| r.get("AppliedCharacterStyle")) {- Some(r) => CharFormat { style: self.char_style_ref(r), over: pchars.clone() },- None => cf.clone(),- };+ // A source at paragraph level wraps a range; inside a range it holds the+ // text directly and takes that range's format.- let f = c.find("CharacterStyleRange").map_or_else(|| cf.clone(), |r| self.range_format(r, pchars));++ let f = c.find("CharacterStyleRange").map_or_else(|| cf.clone(), |r| self.range_format(r, pchars, cf));b.push(&designcraft_doc::XREF_MARK.to_string(), &f);}"Footnote" => {@@@ -2191,11 -1876,18 +2192,22 @@@b.push(&designcraft_doc::OBJECT_MARK.to_string(), cf);}}+ "TextVariableInstance" => {+ let t = self.text_variable_instance(c);+ b.push(&t, cf);+ }+ "Change" => {+ // Tracked changes: deleted text stays in the story, marked, and takes no+ // room in the layout.+ let mut ncf = cf.clone();+ match c.get("ChangeType") {+ Some("DeletedText") => ncf.over.change = Some(designcraft_doc::ChangeMark::Deleted),+ Some("InsertedText" | "MovedText") => ncf.over.change = Some(designcraft_doc::ChangeMark::Inserted),+ _ => {}+ }+ self.walk_story(c, b, pf, pchars, &ncf, brk);+ }- "Properties" | "Note" | "TextFrame" | "StoryPreference" | "InCopyExportOption" | "TextVariableInstance" => {}+ "Properties" | "Note" | "StoryPreference" | "InCopyExportOption" => {}_ => self.walk_story(c, b, pf, pchars, cf, brk),},Node::Pi(t, v) if t == "ACE" => {diff --cc crates/idml/src/tests.rsindex 5dad8d0a5,9a397b2e7..6ae6747de--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -2589,587 -1455,54 +2589,639 @@@ fn list_numbering_format_expression_andcheck(&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.clone();+ 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.clone();+ 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()]);+}++/// One single-column text frame at (0, 0)-(300, 200) on page 1, beside a 100 pt wide rectangle+/// with a bounding-box wrap and `wrap_props` inside its `TextWrapPreference/Properties`.+fn custom_wrap_fixture(wrap_props: &str) -> Vec<u8> {+ let rect = |w: f64, h: f64| {+ format!(+ r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray><PathPointType Anchor="0 0"/><PathPointType Anchor="0 {h}"/><PathPointType Anchor="{w} {h}"/><PathPointType Anchor="{w} 0"/></PathPointArray></GeometryPathType></PathGeometry>"#+ )+ };+ let spread = format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Spread Self="sp1" PageCount="2" ItemTransform="1 0 0 1 0 0">+ <Page Self="p1" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 -500 -350"/>+ <Page Self="p2" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 0 -350"/>+ <TextFrame Self="t1" ParentStory="s1" PreviousTextFrame="n" NextTextFrame="n" ItemLayer="L1" ItemTransform="1 0 0 1 -450 -300">+ <Properties>{frame}</Properties>+ </TextFrame>+ <Rectangle Self="w" ItemLayer="L1" ItemTransform="1 0 0 1 -450 -300">+ <Properties>{obj}</Properties>+ <TextWrapPreference TextWrapMode="BoundingBoxTextWrap" TextWrapSide="BothSides"><Properties>{wrap_props}<TextWrapOffset Top="0" Left="0" Bottom="0" Right="0"/></Properties></TextWrapPreference>+ </Rectangle>+ </Spread>+</idPkg:Spread>"#,+ frame = rect(300.0, 200.0),+ obj = rect(100.0, 200.0),+ );+ let words = "wrap ".repeat(120);+ let story = format!(+ 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/$ID/NormalParagraphStyle"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>{words}</Content></CharacterStyleRange></ParagraphStyleRange></Story>+</idPkg:Story>"#+ );+ 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),+ ])+}++/// The custom boundary: 40 pt wide, the full height of the 100 pt wide rectangle.+const NARROW_WRAP_PATH: &str = r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray><PathPointType Anchor="0 0" LeftDirection="0 0" RightDirection="0 0"/><PathPointType Anchor="0 200" LeftDirection="0 200" RightDirection="0 200"/><PathPointType Anchor="40 200" LeftDirection="40 200" RightDirection="40 200"/><PathPointType Anchor="40 0" LeftDirection="40 0" RightDirection="40 0"/></PathPointArray></GeometryPathType></PathGeometry>"#;++fn wrapping_item(d: &Document) -> &designcraft_doc::Item {+ d.spreads[0].items.iter().find(|i| i.wrap.mode != designcraft_doc::WrapMode::None).unwrap()+}++/// Leftmost line start in the frame.+fn first_line_x(d: &Document) -> f64 {+ let sid = *d.stories.keys().next().unwrap();+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());+ assert!(cs.frames[0].lines.len() > 3);+ cs.frames[0].lines.iter().map(|l| l.x0).fold(f64::INFINITY, f64::min)+}++#[test]+fn custom_wrap_boundary_imports_composes_and_round_trips() {+ let plain = import_idml_with(&custom_wrap_fixture(""), &|_| None).unwrap();+ assert_eq!(wrapping_item(&plain).wrap.path, None);+ assert!(first_line_x(&plain) >= 100.0 - 1e-6, "the frame's bounds push text to x = 100");++ let d = import_idml_with(&custom_wrap_fixture(NARROW_WRAP_PATH), &|_| None).unwrap();+ let path = wrapping_item(&d).wrap.path.clone().unwrap();+ assert_eq!(path.bounds(), Some(Rect::new(0.0, 0.0, 40.0, 200.0)));+ let x = first_line_x(&d);+ assert!((40.0 - 1e-6..100.0).contains(&x), "lines start at the custom boundary's edge, not the frame's: {x}");++ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(wrapping_item(&back).wrap.path, Some(path));+}++#[test]+fn hostile_custom_wrap_boundary_is_dropped() {+ let nan = NARROW_WRAP_PATH.replacen(r#"Anchor="40 200""#, r#"Anchor="NaN 200""#, 1);+ let inf = NARROW_WRAP_PATH.replacen(r#"Anchor="40 200""#, r#"Anchor="inf 200""#, 1);+ let huge = format!(+ r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{}</PathPointArray></GeometryPathType></PathGeometry>"#,+ r#"<PathPointType Anchor="1 1"/>"#.repeat(50_000)+ );+ let empty = r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray/></GeometryPathType></PathGeometry>"#;+ for props in [nan.as_str(), inf.as_str(), huge.as_str(), empty] {+ let d = import_idml_with(&custom_wrap_fixture(props), &|_| None).unwrap();+ let it = wrapping_item(&d);+ assert_eq!(it.wrap.mode, designcraft_doc::WrapMode::BoundingBox);+ assert_eq!(it.wrap.path, None);+ assert!(first_line_x(&d) >= 100.0 - 1e-6);+ }+}++/// A family name keeps its spaces ("Minion Pro " is a font of its own) and `FontStyle="Nothing"`+/// leaves the style to the paragraph, also after an export.+#[test]+fn applied_font_keeps_spaces_and_font_style_nothing_inherits() {+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Text%3aBody" FontStyle="Bold">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" FontStyle="Nothing"><Properties><AppliedFont type="string">DC Space </AppliedFont></Properties><Content>Spaced</Content></CharacterStyleRange>+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" FontStyle="$ID/Nothing"><Content> plain</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let check = |d: &Document| {+ let s = d.stories.values().find(|s| s.text.contains("Spaced")).unwrap();+ let (_, base) = d.styles.resolve_para(&s.paras[0]);+ let runs: Vec<_> = s.runs().map(|(_, f)| f.clone()).collect();+ assert_eq!(runs[0].over.font_family.as_deref(), Some("DC Space "));+ for f in &runs {+ assert_eq!(d.styles.resolve_char(&base, f).font_style, "Bold", "the enclosing range's style");+ }+ };+ let d = import_idml(&fixture_with_story(story)).unwrap();+ check(&d);+ check(&import_idml(&export_idml(&d)).unwrap());+}+++ fn tracked_story(body: &str) -> String {+ format!(+ 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">{body}</Story>+ </idPkg:Story>"#+ )+ }++ const CSR: &str = r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]">"#;++ #[test]+ fn tracked_deleted_text_takes_no_room_and_round_trips() {+ let psr = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle">"#;+ let kwn = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle" KeepWithNext="2">"#;+ let tracked = tracked_story(&format!(+ r#"{psr}{CSR}<Content>The first paragraph keeps a </Content><Change Self="c1" ChangeType="DeletedText"><Content>deleted </Content></Change><Content>word.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>+ {kwn}{CSR}<Change Self="c2" ChangeType="DeletedText"><Br/></Change></CharacterStyleRange></ParagraphStyleRange>+ {psr}{CSR}<Change Self="c3" ChangeType="InsertedText"><Content>New </Content></Change><Content>second paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#+ ));+ let plain = tracked_story(&format!(+ r#"{psr}{CSR}<Content>The first paragraph keeps a word.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>+ {psr}{CSR}<Content>New second paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#+ ));+ let lines = |d: &Document| {+ let sid = *d.stories.keys().next().unwrap();+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());+ cs.frames.iter().flat_map(|f| f.lines.iter().map(|l| (l.baseline, l.x0, l.end_x))).collect::<Vec<_>>()+ };+ let d = import_idml_with(&fixture_with_story(&tracked), &|_| None).unwrap();+ let story = d.stories.values().next().unwrap();+ assert_eq!(story.text, "The first paragraph keeps a deleted word.\n\nNew second paragraph.");+ let marks = |s: &designcraft_doc::Story| s.runs().map(|(r, f)| (s.text[r].to_string(), f.over.change)).collect::<Vec<_>>();+ use designcraft_doc::ChangeMark::{Deleted, Inserted};+ let want = vec![+ ("The first paragraph keeps a ".to_string(), None),+ ("deleted ".to_string(), Some(Deleted)),+ ("word.\n".to_string(), None),+ ("\n".to_string(), Some(Deleted)),+ ("New ".to_string(), Some(Inserted)),+ ("second paragraph.".to_string(), None),+ ];+ assert_eq!(marks(story), want);+ let reference = import_idml_with(&fixture_with_story(&plain), &|_| None).unwrap();+ let expected = lines(&reference);+ assert!(expected.len() >= 2);+ assert_eq!(lines(&d), expected);+ // Export writes the changes back as `Change` elements.+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(marks(back.stories.values().next().unwrap()), want);+ }