DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #343 update: Tabs commands return the stored list; tab lists from files are sanitized
aiongga4ac6b039ca0
diff --cc crates/idml/src/tests.rsindex 36e3c5203,6f395c821..06e0f7237--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -2339,270 -1400,29 +2339,297 @@@ 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 doc = import_idml(&fixture_with_story(&story)).unwrap();+ 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");+ }