Skip to content

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

Merge pr/636: Tools: drag type-on-a-path start and end brackets (#636)

aiongg99e692298128
diff --cc ROADMAP.md
index a18cc8739,a213adda0..80bfdc044
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -128,8 -129,7 +128,9 @@@ list) · [roadmap.md](docs/roadmap.md)
Newest first.
+ - **2026-10-12** · Type on a path has start and end brackets, as in InDesign: selected path type shows them across the path, and dragging either with the Selection or Direct Selection tool moves where the text starts or ends (text past the end bracket is overset). `type.pathOptions {end}`; IDML reads and writes EndBracket. No readiness percentage change.
+- **2026-10-12** · The Pen tool continues an open path from either end point, as in InDesign: the cursor shows it over an end point, a click there carries on drawing that path, a drag first reshapes the end point's direction lines, and the other end closes it. Object › Paths › Reverse Path (`path.reverse`); `path.setAnchor`; `path.appendAnchor` and `path.close` take a subpath. No readiness percentage change.
+- **2026-10-12** · The Eyedropper puts a colour sampled from an image on the stroke when the toolbox's Stroke box is in front, as in InDesign (a line takes it on its stroke). No readiness percentage change.
- **2026-10-12** · Window close and application/menu Quit ask about unsaved documents; later Cancel keeps every tab open, including earlier Don't Save choices. Approvals are rechecked after edits. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.
- **2026-10-12** · Each running app keeps recovery data in its own locked folder; current folder and lock ownership are checked before writes and cleanup. Failed isolation disables recovery with a warning instead of sharing document IDs. No readiness percentage change.
- **2026-10-12** · Native engine saves and exports replace files atomically; failed writes retain the original, private staging preserves Unix permissions, and valid long filenames work. Desktop Services and CLI raster exports remain separate follow-ups. No readiness percentage change.
diff --cc crates/compose/src/lib.rs
index 124e93471,4aa16fd73..ccc66a137
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@@ -713,10 -414,11 +713,11 @@@ pub fn frame_specs(doc: &Document, sid
columns: 1,
inset: [0.0; 4],
first_baseline: designcraft_doc::FirstBaseline::Ascent,
- path: None,
+ // Keep the path identity: its synthetic area uses full line extents.
..tf.options.clone()
};
- (Rect::new(0.0, 0.0, (len - pt.start).max(1.0), size * 1.6), opts)
+ let end = pt.end.map_or(len, |e| e.clamp(0.0, len));
+ (Rect::new(0.0, 0.0, (end - pt.start).max(1.0), size * 1.6), opts)
}
None => (item.text_area(), tf.options.clone()),
};
diff --cc crates/compose/src/tests.rs
index f3eedc074,f5d0113c1..2c07450e9
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@@ -2496,40 -1461,12 +2496,40 @@@ fn custom_anchors_do_not_change_bottom_
}
#[test]
-fn cjk_bunri_does_not_split_double_dash() {
- for composer in [designcraft_doc::Composer::SingleLine, designcraft_doc::Composer::Paragraph] {
- let (d, sid, _) =
- doc_with("--", Rect::new(0.0, 0.0, 5.0, 100.0), ParaAttrs { composer: Some(composer), bunri_kinshi: Some(true), ..Default::default() });
- let cs = compose_story(&d, sid, &ComposeOptions::default());
- assert_eq!(all_lines(&cs).len(), 1);
+fn baseline_shift_keeps_its_metrics_and_glyph_offset_at_bottom() {
+ let (mut d, sid, _) = baseline_fit_doc("Map", 10.0);
+ let plain = compose_story(&d, sid, &ComposeOptions::default());
+ d.story_mut(sid).unwrap().format_chars(0..3, |f| f.over.baseline_shift = Some(-3.0));
+ let shifted = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!plain.is_overset() && !shifted.is_overset());
+ let (p, s) = (&plain.frames[0].lines[0], &shifted.frames[0].lines[0]);
+ assert_eq!(p.baseline, s.baseline);
+ assert!((s.descent - p.descent - 3.0).abs() < 1e-6);
+ assert!((s.glyphs[0].y - p.glyphs[0].y - 3.0).abs() < 1e-6);
+}
+
+#[test]
+fn path_text_keeps_the_original_vertical_fit_limit() {
+ // A path's synthetic layout area is not an ordinary text frame: admitting a
+ // second line would paint both lines on the same path, regardless of leading.
+ for separator in ['\n', designcraft_doc::story::FORCED_LINE_BREAK] {
+ for leading in [8.0, 10.0] {
+ let text = format!("HELLO{separator}WORLD");
+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default());
+ let it = d.item_mut(fid).unwrap();
+ it.shape = designcraft_doc::Shape::Path;
+ it.path = designcraft_geom::shapes::line(Point::ZERO, Point::new(200.0, 0.0));
+ it.text_frame_mut().unwrap().options.path =
- Some(designcraft_doc::PathType { start: 0.0, flip: false, align: designcraft_doc::PathAlign::Baseline });
++ Some(designcraft_doc::PathType { start: 0.0, end: None, flip: false, align: designcraft_doc::PathAlign::Baseline });
+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {
+ f.over.font_family = Some("Source Serif 4".into());
+ f.over.size = Some(20.0);
+ f.over.leading = Some(designcraft_doc::Leading::Points(leading));
+ });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert_eq!(cs.line_count(), 1, "{separator:?}, leading {leading}");
+ assert_eq!(cs.overset_at, Some("HELLO".len() + separator.len_utf8()));
+ }
}
}
diff --cc crates/idml/src/tests.rs
index 06990f531,8d27074e9..b08348259
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@@ -2608,827 -1455,26 +2608,851 @@@ 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.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);
+}
+
+#[test]
+fn same_para_style_spacing_imports_and_round_trips() {
+ 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]" SameParaStyleSpacing="0">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Gap</Content><Br/></CharacterStyleRange>
+ </ParagraphStyleRange>
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" SameParaStyleSpacing="Nothing">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Ignore</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#;
+ let d = import_idml(&fixture_with_story(story)).unwrap();
+ let st = d.stories.values().find(|s| s.text.contains("Gap")).unwrap();
+ assert_eq!(st.paras[0].para.same_para_style_spacing, Some(Some(0.0)));
+ // Ignore is an explicit "off", not an unset value.
+ assert_eq!(st.paras[1].para.same_para_style_spacing, Some(None));
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let b = back.stories.values().find(|s| s.text.contains("Gap")).unwrap();
+ assert_eq!(b.paras[0].para.same_para_style_spacing, Some(Some(0.0)));
+ // The explicit Ignore survives the round trip too.
+ assert_eq!(b.paras[1].para.same_para_style_spacing, Some(None));
+}
+
+/// SameParaStyleSpacing set as a `Properties` element on the based-on style (`Normal`) reaches
+/// the headings: consecutive headings sit one leading apart. SetIgnore keeps the usual spacing.
+#[test]
+fn same_para_style_spacing_from_a_based_on_style_element_closes_the_gap() {
+ let styles = r#"<?xml version="1.0" encoding="UTF-8"?>
+<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <RootCharacterStyleGroup Self="rc">
+ <CharacterStyle Self="CharacterStyle/$ID/[No character style]" Name="$ID/[No character style]"/>
+ </RootCharacterStyleGroup>
+ <RootParagraphStyleGroup Self="rp">
+ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" PointSize="12">
+ <Properties><AppliedFont type="string">Source Serif 4</AppliedFont><Leading type="unit">13</Leading></Properties>
+ </ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle">
+ <Properties><BasedOn type="string">$ID/[No paragraph style]</BasedOn><SameParaStyleSpacing type="unit">0</SameParaStyleSpacing></Properties>
+ </ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/Heading" Name="Heading" SpaceBefore="18" SpaceAfter="4.5">
+ <Properties><BasedOn type="object">ParagraphStyle/$ID/NormalParagraphStyle</BasedOn></Properties>
+ </ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/Loose" Name="Loose" SpaceBefore="18" SpaceAfter="4.5">
+ <Properties><BasedOn type="object">ParagraphStyle/$ID/NormalParagraphStyle</BasedOn><SameParaStyleSpacing type="enumeration">SetIgnore</SameParaStyleSpacing></Properties>
+ </ParagraphStyle>
+ </RootParagraphStyleGroup>
+</idPkg:Styles>"#;
+ let para = |style: &str, text: &str| {
+ format!(
+ r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/{style}"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>{text}</Content><Br/></CharacterStyleRange></ParagraphStyleRange>"#
+ )
+ };
+ let story = format!(
+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">{}{}{}{}</Story></idPkg:Story>"#,
+ para("Heading", "One"),
+ para("Heading", "Two"),
+ para("Loose", "Three"),
+ para("Loose", "Four")
+ );
+ let d = import_idml(&fixture_with_table_styles(styles, &story)).unwrap();
+ let sid = d.stories.iter().find(|(_, s)| s.text.contains("One")).map(|(id, _)| *id).unwrap();
+ let cs = designcraft_compose::compose_story(&d, sid, &Default::default());
+ let baseline = |para: usize| cs.frames[0].lines.iter().find(|l| l.para == para).unwrap().baseline;
+ assert!((baseline(1) - baseline(0) - 13.0).abs() < 1e-6, "{} {}", baseline(0), baseline(1));
+ assert!((baseline(3) - baseline(2) - 13.0 - 4.5 - 18.0).abs() < 1e-6, "{} {}", baseline(2), baseline(3));
+}
+
+/// Composed lines (baseline, left, right) of the only story.
+fn story_lines(d: &Document) -> Vec<(f64, f64, f64)> {
+ 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()
+}
+
+const PSR: &str = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle">"#;
+
+/// Lays out like the same story without the deleted paragraph.
+fn assert_deleted_para_takes_no_room(deleted: &str, deleted_text: &str) {
+ let tracked = tracked_story(&format!(
+ r#"{PSR}{CSR}<Content>First live paragraph.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>
+{deleted}
+{PSR}{CSR}<Content>Second live paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#
+ ));
+ let plain = tracked_story(&format!(
+ r#"{PSR}{CSR}<Content>First live paragraph.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>
+{PSR}{CSR}<Content>Second live paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#
+ ));
+ let d = import_idml_with(&fixture_with_story(&tracked), &|_| None).unwrap();
+ let story = d.stories.values().next().unwrap();
+ let marks: Vec<_> = story.runs().map(|(r, f)| (story.text[r].to_string(), f.over.change)).collect();
+ let want = vec![
+ ("First live paragraph.\n".to_string(), None),
+ (deleted_text.to_string(), Some(designcraft_doc::ChangeMark::Deleted)),
+ ("Second live paragraph.".to_string(), None),
+ ];
+ assert_eq!(marks, want);
+ let expected = story_lines(&import_idml_with(&fixture_with_story(&plain), &|_| None).unwrap());
+ assert_eq!(expected.len(), 2);
+ assert_eq!(story_lines(&d), expected);
+}
+
+#[test]
+fn tracked_deleted_paragraph_range_stays_deleted() {
+ assert_deleted_para_takes_no_room(
+ &format!(
+ r#"<Change Self="c1" ChangeType="DeletedText">{PSR}{CSR}<Content>Deleted text</Content><Br/></CharacterStyleRange></ParagraphStyleRange></Change>"#
+ ),
+ "Deleted text\n",
+ );
+}
+
+#[test]
+fn tracked_deleted_frame_break_does_not_break() {
+ let fb = "\u{E003}";
+ let nf = r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" ParagraphBreakType="NextFrame">"#;
+ // The change around the paragraph range.
+ assert_deleted_para_takes_no_room(
+ &format!(
+ r#"<Change Self="c1" ChangeType="DeletedText">{PSR}{CSR}<Content>Gone</Content></CharacterStyleRange>{nf}<Br/></CharacterStyleRange></ParagraphStyleRange></Change>"#
+ ),
+ &format!("Gone{fb}\n"),
+ );
+ // The change inside the character range.
+ assert_deleted_para_takes_no_room(
+ &format!(
+ r#"{PSR}{nf}<Change Self="c1" ChangeType="DeletedText"><Content>Gone</Content><Br/></Change></CharacterStyleRange></ParagraphStyleRange>"#
+ ),
+ &format!("Gone{fb}\n"),
+ );
+}
+
+#[test]
+fn live_frame_break_before_deleted_paragraph_still_breaks() {
+ let nf = r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" ParagraphBreakType="NextFrame">"#;
+ let first =
+ format!(r#"{PSR}{CSR}<Content>First live paragraph.</Content></CharacterStyleRange>{nf}<Br/></CharacterStyleRange></ParagraphStyleRange>"#);
+ let second = format!(r#"{PSR}{CSR}<Content>Second live paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#);
+ let deleted = format!(
+ r#"<Change Self="c1" ChangeType="DeletedText">{PSR}{CSR}<Content>Gone</Content><Br/></CharacterStyleRange></ParagraphStyleRange></Change>"#
+ );
+ let import = |body: String| import_idml_with(&fixture_with_story(&tracked_story(&body)), &|_| None).unwrap();
+ let reference = import(format!("{first}\n{second}"));
+ let sid = *reference.stories.keys().next().unwrap();
+ let per_frame: Vec<usize> =
+ designcraft_compose::compose_story(&reference, sid, &Default::default()).frames.iter().map(|f| f.lines.len()).collect();
+ assert!(per_frame.first() == Some(&1) && per_frame.get(1).is_some_and(|n| *n > 0), "the break sends the second paragraph on");
+ let expected = story_lines(&reference);
+ assert_eq!(story_lines(&import(format!("{first}\n{deleted}\n{second}"))), expected);
+}
+
+#[test]
+fn vertical_balance_columns_balances_the_imported_frame() {
+ let text = "Balanced columns end at about the same depth when the story ends in the frame. ".repeat(4);
+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">
+ <idPkg:Spread src="Spreads/Spread_s.xml"/>
+ <idPkg:Story src="Stories/Story_s1.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 400 400" ItemTransform="1 0 0 1 0 0"/>
+ <TextFrame Self="f" ParentStory="s1">
+ <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>
+ <PathPointType Anchor="0 0"/><PathPointType Anchor="0 150"/>
+ <PathPointType Anchor="300 150"/><PathPointType Anchor="300 0"/>
+ </PathPointArray></GeometryPathType></PathGeometry></Properties>
+ <TextFramePreference TextColumnCount="2" TextColumnGutter="12" VerticalBalanceColumns="true"/>
+ </TextFrame>
+ </Spread>
+ </idPkg:Spread>"#;
+ let story = format!(
+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange><CharacterStyleRange><Content>{text}</Content></CharacterStyleRange></ParagraphStyleRange>
+ </Story></idPkg:Story>"#
+ );
+ let mut d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", spread), ("Stories/Story_s1.xml", &story)])).unwrap();
+ let sid = *d.stories.keys().next().unwrap();
+ let per_column = |d: &Document| {
+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());
+ assert!(!cs.is_overset());
+ let ft = &cs.frames[0];
+ [0, 1].map(|c| ft.lines.iter().filter(|l| l.column == c).count())
+ };
+ let on = per_column(&d);
+ assert!(on[1] > 0 && on[0] - on[1] <= 1, "balanced: {on:?}");
+ let fid = d.stories[&sid].frames[0];
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.balance_columns = false;
+ let off = per_column(&d);
+ assert!(off[0] > off[1] + 1, "unbalanced: {off:?}");
+}
++
+ #[test]
+ fn type_on_a_path_keeps_its_start_and_end_brackets() {
+ use designcraft_geom::{Anchor, PathData, Point, SubPath};
+ for end in [Some(250.0), None] {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let id = designcraft_doc::ItemId(d.alloc());
+ let line = PathData::single(SubPath::new(vec![Anchor::corner(Point::new(100.0, 300.0)), Anchor::corner(Point::new(500.0, 300.0))], false));
+ let mut it = designcraft_doc::Item::new(id, lid, Shape::GraphicLine, line);
+ let sid = designcraft_doc::StoryId(d.alloc());
+ let mut tf = designcraft_doc::TextFrame { story: sid, options: Default::default() };
+ tf.options.path = Some(designcraft_doc::PathType { start: 30.0, end, ..Default::default() });
+ it.content = designcraft_doc::Content::Text(tf);
+ let mut story = designcraft_doc::Story::with_text(sid, "Along", Default::default());
+ story.frames = vec![id];
+ d.stories.insert(sid, std::sync::Arc::new(story));
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let pt = back.spreads[0].items[0].text_frame().unwrap().options.path.clone().unwrap();
+ assert!((pt.start - 30.0).abs() < 1e-6, "{pt:?}");
+ assert_eq!(pt.end.map(|e| e.round()), end, "an end bracket at the path's end is no end bracket");
+ }
+ }
diff --cc crates/tools/src/lib.rs
index c1b9a285d,02b790d55..0610e4581
--- a/crates/tools/src/lib.rs
+++ b/crates/tools/src/lib.rs
@@@ -361,16 -335,8 +361,18 @@@ pub enum Cursor
ResizeNeSw,
Rotate,
Pen,
+ /// The pen over a segment of a selected path: a click adds an anchor there.
+ PenAdd,
+ /// The pen over an anchor of a selected path: a click deletes it.
+ PenDelete,
+ /// The pen over the first anchor of the path it is drawing: a click closes it.
+ PenClose,
+ /// Convert Direction Point.
+ PenConvert,
+ /// The Pen over an open path's end point: a click continues the path.
+ PenContinue,
+ /// Over a type-on-a-path bracket: dragging it moves where the text starts or ends.
+ PathBracket,
Text,
Hand,
HandGrab,
diff --cc crates/tools/src/select.rs
index e21000641,fc9a8c316..7e9fe3270
--- a/crates/tools/src/select.rs
+++ b/crates/tools/src/select.rs
@@@ -53,18 -38,11 +53,23 @@@ enum Drag
start: Point,
cur: Point,
},
+ /// A press with the loaded text cursor.
+ Place {
+ start: Point,
+ cur: Point,
+ },
+ /// Dragging live-corner diamond `corner`. `frame` is read at pointer down: during the drag
+ /// the document is the previous preview.
+ Corner {
+ frame: LiveFrame,
+ corner: usize,
+ start: Point,
+ },
+ /// Dragging a type-on-a-path bracket along its path (`end`: the end bracket).
+ Bracket {
+ id: ItemId,
+ end: bool,
+ },
Anchor {
id: u64,
si: usize,
@@@ -683,7 -493,15 +739,15 @@@ impl Tool for SelectionTool
}
}
PointerKind::Drag => match self.drag.clone() {
+ Drag::Bracket { id, end } => {
+ let Some((warp, xf, _, _)) = path_type_of(cx, id) else { return vec![] };
+ if xf.determinant().abs() < 1e-12 {
+ return vec![];
+ }
+ let s = warp.nearest(xf.inverse() * p);
+ vec![Action::Preview("type.pathOptions".into(), json!({"id": id.0, if end { "end" } else { "start" }: s}))]
+ }
- Drag::Pending { start, hit } => {
+ Drag::Pending { start, hit, content } => {
if (p - start).hypot() < cx.tol(3.0) {
return vec![];
}
@@@ -954,7 -746,9 +1018,9 @@@
let release = self.shift_release.take();
let d = std::mem::replace(&mut self.drag, Drag::None);
match d {
- Drag::Move { .. } | Drag::Resize { .. } | Drag::Anchor { .. } | Drag::Rotate { .. } | Drag::Corner { .. } => vec![Action::Commit],
- Drag::Move { .. } | Drag::Resize { .. } | Drag::Anchor { .. } | Drag::Rotate { .. } | Drag::Bracket { .. } => {
++ Drag::Move { .. } | Drag::Resize { .. } | Drag::Anchor { .. } | Drag::Rotate { .. } | Drag::Corner { .. } | Drag::Bracket { .. } => {
+ vec![Action::Commit]
+ }
Drag::Pending { .. } => match release {
Some(id) => vec![Action::Exec("selection.toggle".into(), json!({"id": id}))],
None => vec![],
@@@ -1008,44 -806,20 +1074,48 @@@
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
- match &self.drag {
+ let mut out = match &self.drag {
+ Drag::Place { start, cur } if crate::thread::is_drag(cx, *start, *cur) => {
+ let Some((sr, r, guides)) = crate::thread::drag_frame(cx, *start, *cur) else { return vec![] };
+ let r = Rect::from_points(cx.layout.to_canvas(sr, Point::new(r.x0, r.y0)), cx.layout.to_canvas(sr, Point::new(r.x1, r.y1)));
+ std::iter::once(Overlay::Marquee(r)).chain(guides).collect()
+ }
Drag::Marquee { start, cur } => vec![Overlay::Marquee(Rect::from_points(*start, *cur))],
+ Drag::Move { content: true, exclude, .. } => {
+ let mut v: Vec<Overlay> = exclude.iter().map(|id| Overlay::ContentGhost(*id)).collect();
+ v.extend(self.guides.iter().cloned());
+ v
+ }
Drag::Move { .. } | Drag::Resize { .. } | Drag::Rotate { .. } | Drag::Anchor { .. } => self.guides.clone(),
+ Drag::None | Drag::Bracket { .. } => brackets(cx),
_ => vec![],
+ };
+ // The loaded text cursor places text: the frame's corners aren't edited meanwhile.
+ if !self.direct && self.loaded.and_then(|l| l.resolve(cx.doc)).is_none() {
+ if let Some(f) = self.live_corners(cx) {
+ out.extend(f.diamonds(cx.zoom).into_iter().map(Overlay::LiveCornerDiamond));
+ } else if let Some(f) = corners::live_frame(cx) {
+ out.push(Overlay::LiveCornerWidget(f.widget(cx.zoom)));
+ }
}
+ out
}
fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor {
+ if let Drag::Move { content: true, .. } = self.drag {
+ return Cursor::HandGrab;
+ }
+ if matches!(self.drag, Drag::Bracket { .. }) || (matches!(self.drag, Drag::None) && bracket_at(cx, p).is_some()) {
+ return Cursor::PathBracket;
+ }
if self.direct {
- return Cursor::ArrowHollow;
+ let over_content = matches!(self.drag, Drag::None)
+ && anchor_at(cx, p).is_none()
+ && cx.hit(p).is_some_and(|(_, id)| cx.doc.item(id).is_some_and(holds_content));
+ return if over_content { Cursor::Hand } else { Cursor::ArrowHollow };
+ }
+ if let Some(l) = self.loaded.and_then(|l| l.resolve(cx.doc)) {
+ return if crate::thread::port_at(cx, p).is_some() { Cursor::LoadedText } else { l.cursor(cx, p) };
}
match self.drag {
Drag::Move { .. } => return Cursor::Move,
diff --cc crates/tools/src/tests.rs
index 7bef4a0ca,e39f8d4ee..770de2164
--- a/crates/tools/src/tests.rs
+++ b/crates/tools/src/tests.rs
@@@ -752,841 -706,50 +752,889 @@@ fn pen_click_snaps_to_a_guide()
assert!((x - 100.0).abs() < 1e-6, "anchor x {x}");
}
+/// A text frame with overset text (selected), an empty frame and a threaded pair x → y, on page 1.
+struct ThreadDoc {
+ d: Document,
+ l: CanvasLayout,
+ s: Selection,
+ c: Cache,
+ /// The selected text frame.
+ a: ItemId,
+ /// An empty (unassigned) frame.
+ e: ItemId,
+ x: ItemId,
+ y: ItemId,
+}
+
+fn thread_doc() -> ThreadDoc {
+ let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() });
+ let lid = d.default_layer();
+ let (a, _) = d
+ .add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 250.0, 160.0), lid, &"Words flow on. ".repeat(40), ParaFormat::default())
+ .unwrap();
+ let e = ItemId(d.alloc());
+ d.insert_item(SpreadRef::Doc(0), Item::new(e, lid, Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 400.0, 250.0, 500.0))), None).unwrap();
+ let (x, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(300.0, 100.0, 450.0, 160.0), lid, "x", ParaFormat::default()).unwrap();
+ let (y, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(300.0, 400.0, 450.0, 500.0), lid, "", ParaFormat::default()).unwrap();
+ d.thread(x, y).unwrap();
+ let l = CanvasLayout::new(&d, false);
+ ThreadDoc { s: Selection::items(vec![a]), c: Cache::new(), l, d, a, e, x, y }
+}
+
+impl ThreadDoc {
+ fn cx(&self) -> ToolContext<'_> {
+ ctx(&self.d, &self.s, &self.c, &self.l)
+ }
+ /// Canvas point of a spread-0 point.
+ fn at(&self, x: f64, y: f64) -> Point {
+ self.l.to_canvas(SpreadRef::Doc(0), Point::new(x, y))
+ }
+ fn port(&self, id: ItemId, out: bool) -> Point {
+ thread::port_center(&self.d, &self.l, id, out, 1.0).unwrap()
+ }
+}
+
+fn click(t: &mut Box<dyn Tool>, cx: &ToolContext, p: Point, mods: Mods) -> Vec<Action> {
+ let mut v = t.pointer(cx, &PointerEvent::new(PointerKind::Down, p.x, p.y).with_mods(mods));
+ v.extend(t.pointer(cx, &PointerEvent::new(PointerKind::Up, p.x, p.y).with_mods(mods)));
+ v
+}
+
+fn thread_exec(p: serde_json::Value) -> Vec<Action> {
+ vec![Action::Exec("text.thread".into(), p)]
+}
+
+#[test]
+fn out_port_loads_text_and_a_click_threads_an_empty_frame() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ let port = td.port(td.a, true);
+ // The out port sits on the right edge, 12 px above the bottom-right corner.
+ assert!((port - td.at(250.0, 148.0)).hypot() < 1e-9, "{port:?}");
+ // A press just off the port's centre still loads (any zoom: tolerance is in pixels).
+ assert!(click(&mut t, &cx, port + designcraft_geom::Vec2::new(3.0, -3.0), Mods::default()).is_empty());
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::LoadedText);
+ let over_e = td.at(175.0, 450.0);
+ assert_eq!(t.cursor(&cx, over_e, Mods::default()), Cursor::ThreadLink);
+ // A frame something already threads into can't join; neither can the loaded frame itself.
+ assert_eq!(t.cursor(&cx, td.at(375.0, 450.0), Mods::default()), Cursor::NotAllowed);
+ assert_eq!(t.cursor(&cx, td.at(175.0, 130.0), Mods::default()), Cursor::LoadedText);
+ assert_eq!(click(&mut t, &cx, over_e, Mods::default()), thread_exec(serde_json::json!({"from": td.a.0, "to": td.e.0})));
+ // Unloaded again: the cursor and clicks are back to normal.
+ assert_eq!(t.cursor(&cx, over_e, Mods::default()), Cursor::Arrow);
+}
+
+#[test]
+fn ports_hit_at_any_zoom() {
+ let td = thread_doc();
+ let mut cx = td.cx();
+ cx.zoom = 4.0;
+ let port = thread::port_center(&td.d, &td.l, td.a, false, 4.0).unwrap();
+ assert!((port - td.at(100.0, 100.0 + 14.5 / 4.0)).hypot() < 1e-9);
+ assert_eq!(thread::port_at(&cx, port + designcraft_geom::Vec2::new(1.5, 1.5)), Some((td.a, false)));
+ assert_eq!(thread::port_at(&cx, port + designcraft_geom::Vec2::new(4.0, 0.0)), None, "8 screen px away at 4×");
+}
+
+#[test]
+fn loaded_click_on_empty_page_makes_a_column_frame() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ let col = td.d.spreads[0].pages[0].column_rects()[0];
+ let a = click(&mut t, &cx, td.at(200.0, 600.0), Mods::default());
+ assert_eq!(a, thread_exec(serde_json::json!({"from": td.a.0, "rect": [col.x0, 600.0, col.x1, col.y1], "spread": {"kind": "doc", "index": 0}})));
+}
+
+#[test]
+fn loaded_drag_makes_a_frame_of_that_size_and_shift_autoflows() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ let (p0, p1) = (td.at(320.0, 560.0), td.at(470.0, 700.0));
+ let shift = Mods { shift: true, ..Default::default() };
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p0.x, p0.y).with_mods(shift)).is_empty());
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, p1.x, p1.y).with_mods(shift)).is_empty());
+ assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::from_points(p0, p1))]);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, p1.x, p1.y).with_mods(shift));
+ assert_eq!(
+ a,
+ thread_exec(
+ serde_json::json!({"from": td.a.0, "rect": [320.0, 560.0, 470.0, 700.0], "spread": {"kind": "doc", "index": 0}, "autoflow": true})
+ )
+ );
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::Arrow, "autoflow unloads");
+}
+
+#[test]
+fn loaded_drag_snaps_like_frame_drawing() {
+ let td = thread_doc();
+ let cx = ToolContext { snap: SnapView::FACTORY, ..td.cx() };
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ let col = td.d.spreads[0].pages[0].column_rects()[0];
+ // Press and release a point or two inside the column's edges: both sides snap to them.
+ let (p0, p1) = (td.at(col.x0 + 1.5, 560.0), td.at(col.x1 - 2.0, 650.0));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p0.x, p0.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, p1.x, p1.y));
+ let Some(Overlay::Marquee(m)) = t.overlays(&cx).first().cloned() else { panic!("no marquee") };
+ assert!((m.x0 - td.at(col.x0, 0.0).x).abs() < 1e-9 && (m.x1 - td.at(col.x1, 0.0).x).abs() < 1e-9, "{m:?}");
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, p1.x, p1.y));
+ let [Action::Exec(id, p)] = a.as_slice() else { panic!("{a:?}") };
+ assert_eq!(id, "text.thread");
+ let r: Vec<f64> = p["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
+ assert_eq!((r[0], r[2]), (col.x0, col.x1), "{p}");
+}
+
+#[test]
+fn alt_click_stays_loaded() {
+ let mut td = thread_doc();
+ let original = td.d.clone();
+ let mut t = create("selection");
+ let alt = Mods { alt: true, ..Default::default() };
+ let col = td.d.spreads[0].pages[0].column_rects()[0];
+ let empty = td.at(200.0, 600.0);
+ let new_frame_from =
+ |f: ItemId| thread_exec(serde_json::json!({"from": f.0, "rect": [col.x0, 600.0, col.x1, col.y1], "spread": {"kind": "doc", "index": 0}}));
+ {
+ let cx = td.cx();
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), alt), thread_exec(serde_json::json!({"from": td.a.0, "to": td.e.0})));
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::LoadedText);
+ // The thread failed (the document is unchanged): still loaded from a.
+ assert_eq!(click(&mut t, &cx, empty, alt), new_frame_from(td.a));
+ }
+ // That click's command ran: the next click threads after the frame it added.
+ let (n, _) =
+ td.d.add_text_frame(SpreadRef::Doc(0), Rect::new(col.x0, 600.0, col.x1, col.y1), td.d.default_layer(), "", ParaFormat::default()).unwrap();
+ td.d.thread(td.a, n).unwrap();
+ {
+ let cx = td.cx();
+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), alt), thread_exec(serde_json::json!({"from": n.0, "to": td.e.0})));
+ }
+ // Undone: back on a, not on a's old neighbour or the frame the undo removed.
+ td.d = original;
+ {
+ let cx = td.cx();
+ assert_eq!(click(&mut t, &cx, empty, Mods::default()), new_frame_from(td.a));
+ }
+ // From x, which threads into y: when threading e in between fails, x stays loaded, not y.
+ let td = ThreadDoc { s: Selection::items(vec![td.x]), ..td };
+ let cx = td.cx();
+ click(&mut t, &cx, td.port(td.x, true), Mods::default());
+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), alt), thread_exec(serde_json::json!({"from": td.x.0, "to": td.e.0})));
+ assert_eq!(click(&mut t, &cx, empty, Mods::default()), new_frame_from(td.x));
+}
+
+#[test]
+fn escape_unloads_and_keeps_the_selection() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::Arrow);
+ // An ordinary click on empty space deselects again.
+ let p = td.at(500.0, 700.0);
+ assert_eq!(
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p.x, p.y)),
+ vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": []}))]
+ );
+}
+
+#[test]
+fn loaded_click_on_the_linked_frame_unthreads() {
+ // x is selected; its out port links to y.
+ let td = thread_doc();
+ let td = ThreadDoc { s: Selection::items(vec![td.x]), ..td };
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.x, true), Mods::default());
+ let over_y = td.at(375.0, 450.0);
+ assert_eq!(t.cursor(&cx, over_y, Mods::default()), Cursor::Unthread);
+ assert_eq!(
+ click(&mut t, &cx, over_y, Mods::default()),
+ vec![Action::Exec("text.unthread".into(), serde_json::json!({"frame": td.x.0, "side": "after"}))]
+ );
+ // From y's in port, x is the frame before.
+ let td = ThreadDoc { s: Selection::items(vec![td.y]), ..td };
+ let cx = td.cx();
+ click(&mut t, &cx, td.port(td.y, false), Mods::default());
+ assert_eq!(
+ click(&mut t, &cx, td.at(375.0, 130.0), Mods::default()),
+ vec![Action::Exec("text.unthread".into(), serde_json::json!({"frame": td.y.0, "side": "before"}))]
+ );
+}
+
+#[test]
+fn in_port_threads_in_front() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, false), Mods::default());
+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), Mods::default()), thread_exec(serde_json::json!({"from": td.e.0, "to": td.a.0})));
+}
+
+#[test]
+fn double_click_on_a_port_breaks_its_link() {
+ let td = thread_doc();
+ let td = ThreadDoc { s: Selection::items(vec![td.x]), ..td };
+ let cx = td.cx();
+ // A double click sent as such (control channel), and the canvas's second press.
+ let second = |p: Point| [PointerEvent::new(PointerKind::DoubleClick, p.x, p.y), PointerEvent::new(PointerKind::Down, p.x, p.y).with_clicks(2)];
+ let p = td.port(td.x, true);
+ for ev in second(p) {
+ let mut t = create("selection");
+ click(&mut t, &cx, p, Mods::default());
+ let a = t.pointer(&cx, &ev);
+ assert_eq!(a, vec![Action::Exec("text.unthread".into(), serde_json::json!({"frame": td.x.0, "side": "after"}))], "{ev:?}");
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, p.x, p.y)).is_empty());
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::Arrow);
+ // The in port of the first frame has no link: nothing to break.
+ let q = td.port(td.x, false);
+ for ev in second(q) {
+ assert!(t.pointer(&cx, &ev).is_empty(), "{ev:?}");
+ }
+ }
+}
+
+#[test]
+fn clicks_in_a_row_edit_and_select_text() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (fid, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 300.0, 200.0), lid, "Two words", ParaFormat::default()).unwrap();
+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let (x, y) = (150.0 + off.x, 110.0 + off.y);
+ let press = |n: u8| PointerEvent::new(PointerKind::Down, x, y).with_clicks(n);
+ // Selection tool: the second press of a double click edits the text there.
+ let mut t = create("selection");
+ let a = t.pointer(&cx, &press(1));
+ assert!(matches!(&a[0], Action::Exec(id, _) if id == "selection.set"), "{a:?}");
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y));
+ let a = t.pointer(&cx, &press(2));
+ assert_eq!(a.first(), Some(&Action::SwitchTool("type".into())));
+ assert!(matches!(&a[1], Action::Exec(id, p) if id == "text.placeCaret" && p["frame"] == fid.0), "{a:?}");
+ // Type tool: word, line, paragraph, then the story.
+ let mut t = create("type");
+ let unit = |a: Vec<Action>| match a.as_slice() {
+ [Action::Exec(id, p)] if id == "text.selectAt" => p["unit"].as_str().map(str::to_string),
+ [Action::Exec(id, _)] if id == "text.placeCaret" => None,
+ other => panic!("{other:?}"),
+ };
+ assert_eq!(unit(t.pointer(&cx, &press(1))), None);
+ for (n, want) in [(2, "word"), (3, "line"), (4, "paragraph"), (5, "story"), (9, "story")] {
+ assert_eq!(unit(t.pointer(&cx, &press(n))).as_deref(), Some(want), "{n} clicks");
+ }
+ // A double click sent as such (control channel) selects a word too.
+ assert_eq!(unit(t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, x, y))).as_deref(), Some("word"));
+ // Moving a little while pressed keeps the unit selected.
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x + 2.0, y)).is_empty());
+}
+
+/// A 100×100 frame at (100, 100) holding a 200×100 graphic that overhangs it.
+fn graphic_frame(doc: &mut Document) -> ItemId {
+ let id = ItemId(doc.alloc());
+ let mut item = Item::new(id, doc.default_layer(), Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)));
+ item.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {
+ asset: designcraft_doc::AssetId(1),
+ size: (200.0, 100.0),
+ xf: designcraft_geom::Affine::translate((50.0, 100.0)),
+ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
+ });
+ doc.insert_item(SpreadRef::Doc(0), item, None).unwrap();
+ id
+}
+
+fn preview_params(a: &[Action]) -> serde_json::Value {
+ match a.last() {
+ Some(Action::Preview(cmd, p)) if cmd == "transform.move" => p.clone(),
+ other => panic!("{other:?}"),
+ }
+}
+
+#[test]
+fn direct_selection_drags_content_inside_its_frame() {
+ let mut d = Document::new(&NewDocument::default());
+ let f = graphic_frame(&mut d);
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let none = Selection::default();
+ let mut t = create("directSelection");
+ let at = spread_pt(&l, 120.0, 130.0);
+ let a = t.pointer(&ctx(&d, &none, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y));
+ assert_eq!(a, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": true}))]);
+ let sel = Selection { content: true, ..Selection::items(vec![f]) };
+ let cx = ctx(&d, &sel, &c, &l);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, at.x + 15.0, at.y - 4.0));
+ assert_eq!(a.first(), Some(&Action::Begin("Move Content".into())));
+ let p = preview_params(&a);
+ assert_eq!(
+ (p["dx"].as_f64(), p["dy"].as_f64(), &p["content"], &p["ids"]),
+ (Some(15.0), Some(-4.0), &serde_json::json!(true), &serde_json::json!([f.0]))
+ );
+ assert_eq!(t.cursor(&cx, at, Mods::default()), Cursor::HandGrab);
+ assert!(t.overlays(&cx).contains(&Overlay::ContentGhost(f)));
+ // Shift keeps the drag on one axis.
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, at.x + 15.0, at.y - 4.0).with_mods(Mods { shift: true, ..Default::default() }));
+ let p = preview_params(&a);
+ assert_eq!((p["dx"].as_f64(), p["dy"].as_f64()), (Some(15.0), Some(0.0)));
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x + 15.0, at.y)), vec![Action::Commit]);
+}
+
+#[test]
+fn selection_tool_grabber_moves_content_elsewhere_moves_the_frame() {
+ let mut d = Document::new(&NewDocument::default());
+ let f = graphic_frame(&mut d);
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let frame = Selection::items(vec![f]);
+ let content = Selection { content: true, ..Selection::items(vec![f]) };
+ let centre = spread_pt(&l, 150.0, 150.0);
+ let mut t = create("selection");
+ // Hovering the grabber shows the hand; it is there on hover before any click, too.
+ assert_eq!(t.cursor(&ctx(&d, &Selection::default(), &c, &l), centre, Mods::default()), Cursor::Hand);
+ let g = select::grabbers(&ctx(&d, &Selection::default(), &c, &l), Some(centre));
+ assert!(matches!(g.as_slice(), [(id, p)] if *id == f && near(*p, centre)), "{g:?}");
+ // Press on the grabber: the content is selected; the drag moves it.
+ let a = t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Down, centre.x, centre.y));
+ assert_eq!(a, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": true}))]);
+ let a = t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Drag, centre.x - 20.0, centre.y + 10.0));
+ let p = preview_params(&a);
+ assert_eq!((p["dx"].as_f64(), p["dy"].as_f64(), &p["content"]), (Some(-20.0), Some(10.0), &serde_json::json!(true)));
+ assert_eq!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Up, centre.x - 20.0, centre.y + 10.0)), vec![Action::Commit]);
+ // A press elsewhere in the frame keeps the content selection; dragging selects and moves the frame.
+ let edge = spread_pt(&l, 115.0, 185.0);
+ assert!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Down, edge.x, edge.y)).is_empty());
+ let a = t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Drag, edge.x + 30.0, edge.y));
+ assert_eq!(a[0], Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0]})));
+ assert_eq!(a[1], Action::Begin("Move".into()));
+ let p = preview_params(&a);
+ assert_eq!((p["dx"].as_f64(), p.get("content"), p.get("ids")), (Some(30.0), None, None));
+ t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Up, edge.x + 30.0, edge.y));
+ // With the frame selected, a drag away from the grabber moves the frame.
+ t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Down, edge.x, edge.y));
+ let a = t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Drag, edge.x, edge.y + 30.0));
+ assert_eq!(a[0], Action::Begin("Move".into()));
+ assert_eq!(preview_params(&a).get("content"), None);
+}
+
+#[test]
+fn double_click_toggles_frame_and_content() {
+ let mut d = Document::new(&NewDocument::default());
+ let f = graphic_frame(&mut d);
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let at = spread_pt(&l, 120.0, 180.0);
+ let mut t = create("selection");
+ let frame = Selection::items(vec![f]);
+ let content = Selection { content: true, ..Selection::items(vec![f]) };
+ let set = |content: bool| vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": content}))];
+ // The canvas's presses in a row: the first selects the frame, the second its content.
+ let a = t.pointer(&ctx(&d, &Selection::default(), &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y));
+ assert_eq!(a, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": false}))]);
+ t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Up, at.x, at.y));
+ assert_eq!(t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y).with_clicks(2)), set(true));
+ assert!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Up, at.x, at.y)).is_empty());
+ // With the content selected, the first press keeps it and the second selects the frame.
+ assert!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y)).is_empty());
+ t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Up, at.x, at.y));
+ assert_eq!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y).with_clicks(2)), set(false));
+ // A double click sent as such (control channel) toggles too.
+ let dbl = PointerEvent::new(PointerKind::DoubleClick, at.x, at.y);
+ assert_eq!(t.pointer(&ctx(&d, &frame, &c, &l), &dbl), set(true));
+ assert_eq!(t.pointer(&ctx(&d, &content, &c, &l), &dbl), set(false));
+}
+
+/// A 200 × 150 pt rectangle frame, selected.
+fn live_corner_doc() -> (Document, ItemId) {
+ let mut d = Document::new(&NewDocument::default());
+ let id = add_rect(&mut d, Rect::new(100.0, 100.0, 300.0, 250.0));
+ (d, id)
+}
+
+fn corner_preview(a: &[Action]) -> Vec<(String, f64)> {
+ let p = match a {
+ [Action::Preview(cmd, p)] | [Action::Exec(cmd, p)] if cmd == "object.cornerOptions" => p,
+ other => panic!("{other:?}"),
+ };
+ p["corners"].as_array().unwrap().iter().map(|c| (c["shape"].as_str().unwrap().to_string(), c["size"].as_f64().unwrap())).collect()
+}
+
+fn diamonds(o: &[Overlay]) -> Vec<Point> {
+ o.iter().filter_map(|o| if let Overlay::LiveCornerDiamond(p) = o { Some(*p) } else { None }).collect()
+}
+
+#[test]
+fn live_corners_click_widget_then_drag_rounds_all_corners() {
+ let (d, id) = live_corner_doc();
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let at = |x, y| spread_pt(&l, x, y);
+ let mut t = create("selection");
+ // The widget sits on the right edge, a little below the top-right corner.
+ let w = at(300.0, 111.5);
+ assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::LiveCornerWidget(p) if near(*p, w))));
+ assert!(diamonds(&t.overlays(&cx)).is_empty());
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y)), vec![Action::Handled]);
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y)).is_empty());
+ // Without corner sizes the diamonds sit 12 px along the top and bottom edges.
+ let want = [at(112.0, 100.0), at(288.0, 100.0), at(288.0, 250.0), at(112.0, 250.0)];
+ let got = diamonds(&t.overlays(&cx));
+ assert!(got.len() == 4 && got.iter().zip(want).all(|(g, w)| near(*g, w)), "{got:?}");
+ assert!(!t.overlays(&cx).iter().any(|o| matches!(o, Overlay::LiveCornerWidget(_))));
+ // Drag the top-left diamond 20 pt toward the centre.
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, want[0].x, want[0].y));
+ assert_eq!(a, vec![Action::Begin("Corner Options".into())]);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, want[0].x + 20.0, want[0].y + 3.0));
+ assert_eq!(corner_preview(&a), vec![("rounded".to_string(), 20.0); 4]);
+ // The size stops at half the shorter side.
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, want[0].x + 500.0, want[0].y));
+ assert_eq!(corner_preview(&a), vec![("rounded".to_string(), 75.0); 4]);
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, want[0].x + 500.0, want[0].y)), vec![Action::Commit]);
+}
+
+#[test]
+fn live_corners_shift_drag_and_alt_click_change_one_corner() {
+ let (mut d, id) = live_corner_doc();
+ d.item_mut(id).unwrap().corners = designcraft_geom::corners::CornerOptions::uniform(designcraft_geom::corners::CornerShape::Rounded, 30.0);
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let at = |x, y| spread_pt(&l, x, y);
+ let mut t = create("selection");
+ let w = at(300.0, 111.5);
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y));
+ // With 30 pt corners the diamonds sit 30 pt along the edges.
+ let tr = at(270.0, 100.0);
+ assert!(diamonds(&t.overlays(&cx)).iter().any(|p| near(*p, tr)));
+ let shift = Mods { shift: true, ..Default::default() };
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, tr.x, tr.y).with_mods(shift));
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, tr.x - 10.0, tr.y).with_mods(shift));
+ let r = |n: f64| ("rounded".to_string(), n);
+ assert_eq!(corner_preview(&a), vec![r(30.0), r(40.0), r(30.0), r(30.0)]);
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, tr.x - 10.0, tr.y));
+ // Alt-click steps the bottom-right corner's shape; Shift+Alt steps every corner.
+ let br = at(270.0, 250.0);
+ let alt = Mods { alt: true, ..Default::default() };
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, br.x, br.y).with_mods(alt));
+ assert_eq!(corner_preview(&a), vec![r(30.0), r(30.0), ("inverseRounded".to_string(), 30.0), r(30.0)]);
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, br.x - 30.0, br.y).with_mods(alt)).is_empty());
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, br.x - 30.0, br.y)).is_empty());
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, br.x, br.y).with_mods(Mods { alt: true, shift: true, ..Default::default() }));
+ assert_eq!(corner_preview(&a), vec![("inverseRounded".to_string(), 30.0); 4]);
+}
+
+#[test]
+fn live_corners_end_on_escape_empty_click_and_other_selection() {
+ let (mut d, id) = live_corner_doc();
+ let other = add_rect(&mut d, Rect::new(400.0, 100.0, 500.0, 200.0));
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let w = spread_pt(&l, 300.0, 111.5);
+ let mut t = create("selection");
+ let enter = |t: &mut Box<dyn Tool>| {
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y));
+ assert_eq!(diamonds(&t.overlays(&cx)).len(), 4);
+ };
+ // Escape leaves corner editing and keeps the selection; the next Escape deselects.
+ enter(&mut t);
+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Handled]);
+ assert!(diamonds(&t.overlays(&cx)).is_empty());
+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": []}))]);
+ // A click on empty canvas.
+ enter(&mut t);
+ let e = spread_pt(&l, 350.0, 400.0);
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, e.x, e.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, e.x, e.y));
+ assert!(diamonds(&t.overlays(&cx)).is_empty());
+ // Another selection.
+ enter(&mut t);
+ let s2 = Selection { items: vec![other], ..Default::default() };
+ let cx2 = ctx(&d, &s2, &c, &l);
+ assert!(diamonds(&t.overlays(&cx2)).is_empty());
+ t.pointer(&cx2, &PointerEvent::new(PointerKind::Move, 0.0, 0.0));
+ assert!(diamonds(&t.overlays(&cx)).is_empty());
+ // A frame too small on screen has no widget.
+ let mut far = ctx(&d, &s, &c, &l);
+ far.zoom = 0.1;
+ assert!(!t.overlays(&far).iter().any(|o| matches!(o, Overlay::LiveCornerWidget(_))));
+}
+
+#[test]
+fn live_corner_diamonds_follow_a_rotated_frame() {
+ let mut d = Document::new(&NewDocument::default());
+ let id = add_rotated(&mut d, Rect::new(100.0, 100.0, 300.0, 250.0), 30.0);
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let m = l.xf(SpreadRef::Doc(0)) * d.item(id).unwrap().xf;
+ let mut t = create("selection");
+ // The widget: 11.5 pt from the top-right corner along the turned right edge.
+ let w = m * Point::new(300.0, 111.5);
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y));
+ let tl = m * Point::new(112.0, 100.0);
+ assert!(diamonds(&t.overlays(&cx)).iter().any(|p| near(*p, tl)), "{:?}", t.overlays(&cx));
+ // Dragging along the turned top edge sets the size.
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, tl.x, tl.y));
+ let to = m * Point::new(137.0, 100.0);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.x, to.y));
+ let got = corner_preview(&a);
+ assert!(got.iter().all(|(shape, size)| shape == "rounded" && (size - 25.0).abs() < 1e-6), "{got:?}");
+}
+
+#[test]
+fn pen_cursor_shows_add_delete_and_close() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (fid, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 200.0, 200.0), lid, "", ParaFormat::default()).unwrap();
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let selected = Selection::items(vec![fid]);
+ let none = Selection::default();
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let at = |x: f64, y: f64| Point::new(x + off.x, y + off.y);
+ let mut t = create("pen");
+ let m = Mods::default();
+
+ let cx = ctx(&d, &selected, &c, &l);
+ assert_eq!(t.cursor(&cx, at(200.0, 100.0), m), Cursor::PenDelete, "on a selected path's anchor");
+ assert_eq!(t.cursor(&cx, at(150.0, 101.0), m), Cursor::PenAdd, "on a selected path's outline");
+ assert_eq!(t.cursor(&cx, at(150.0, 150.0), m), Cursor::Pen, "inside, away from the outline");
+ let click = |t: &mut Box<dyn Tool>, cx: &ToolContext, p: Point| {
+ let down = t.pointer(cx, &PointerEvent::new(PointerKind::Down, p.x, p.y));
+ let up = t.pointer(cx, &PointerEvent::new(PointerKind::Up, p.x, p.y));
+ (down, up)
+ };
+ let (down, up) = click(&mut t, &cx, at(200.0, 100.0));
+ assert_eq!(down, vec![Action::Exec("path.deleteAnchor".into(), serde_json::json!({"id": fid.0, "subpath": 0, "anchor": 1}))]);
+ assert!(up.is_empty() && !t.busy(), "deleting starts no path");
+ let (down, _) = click(&mut t, &cx, at(150.0, 101.0));
+ assert!(matches!(&down[..], [Action::Exec(cmd, p)] if cmd == "path.addAnchor" && p["id"] == fid.0), "{down:?}");
+
+ // Unselected paths are drawn over; the first anchor of the path being drawn closes it.
+ let cx = ctx(&d, &none, &c, &l);
+ assert_eq!(t.cursor(&cx, at(200.0, 100.0), m), Cursor::Pen, "unselected path");
+ click(&mut t, &cx, at(300.0, 300.0));
+ assert_eq!(t.cursor(&cx, at(300.0, 300.0), m), Cursor::Pen, "one anchor cannot close yet");
+ click(&mut t, &cx, at(400.0, 300.0));
+ assert_eq!(t.cursor(&cx, at(301.0, 301.0), m), Cursor::PenClose, "on the first anchor");
+ assert_eq!(t.cursor(&cx, at(350.0, 350.0), m), Cursor::Pen, "elsewhere while drawing");
+}
+
+#[test]
+fn anchor_tools_show_pen_state_cursors() {
+ let d = Document::new(&NewDocument::default());
+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let p = Point::new(10.0, 10.0);
+ let cursor = |id: &str| create(id).cursor(&cx, p, Mods::default());
+ assert_eq!(cursor("addAnchor"), Cursor::PenAdd);
+ assert_eq!(cursor("deleteAnchor"), Cursor::PenDelete);
+ assert_eq!(cursor("convertDirection"), Cursor::PenConvert);
+}
+
+/// A text frame holding a 3×3 table of 80 pt columns, optionally rotated about its centre.
+fn table_frame(degrees: f64) -> (Document, ItemId) {
+ let mut d = Document::new(&NewDocument::default());
+ let layer = d.default_layer();
+ let (id, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 400.0, 400.0), layer, "", ParaFormat::default()).unwrap();
+ let tid = d.alloc();
+ d.story_mut(sid).unwrap().insert_table(0, designcraft_doc::Table::new(tid, 3, 3, 0, 0, 240.0));
+ d.item_mut(id).unwrap().xf = designcraft_geom::Affine::rotate_about(degrees.to_radians(), Point::new(250.0, 250.0));
+ (d, id)
+}
+
+#[test]
+fn type_tool_drags_a_table_column_border() {
+ for degrees in [0.0, 90.0] {
+ let (d, id) = table_frame(degrees);
+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let it = d.item(id).unwrap();
+ let sid = it.text_frame().unwrap().story;
+ let cs = c.get(&d, sid, None);
+ let cell = cs.frames[0].tables[0].cell(1, 0).unwrap();
+ let xf = cx.item_canvas_xf(id).unwrap() * d.text_xf(it);
+ let on_border = xf * Point::new(cell.rect.x1 + 1.0, (cell.rect.y0 + cell.rect.y1) / 2.0);
+ let dragged = xf * Point::new(cell.rect.x1 + 21.0, (cell.rect.y0 + cell.rect.y1) / 2.0);
+ let mut t = create("type");
+ let expected = if degrees == 0.0 { Cursor::ResizeH } else { Cursor::ResizeV };
+ assert_eq!(t.cursor(&cx, on_border, Mods::default()), expected);
+ // A click with a 1 px wobble on the border changes nothing.
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on_border.x, on_border.y)).is_empty());
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, on_border.x + 1.0, on_border.y)).is_empty());
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, on_border.x + 1.0, on_border.y)).is_empty());
+ // A press on the border starts a resize, not a text selection.
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on_border.x, on_border.y)).is_empty());
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, dragged.x, dragged.y));
+ assert_eq!(a[0], Action::Begin("Resize Column".into()));
+ let Action::Preview(cmd, p) = &a[1] else { panic!("{a:?}") };
+ assert_eq!(
+ (cmd.as_str(), &p["axis"], &p["index"], &p["frame"]),
+ ("table.resizeBorder", &serde_json::json!("column"), &serde_json::json!(0), &serde_json::json!(id.0))
+ );
+ assert!((p["delta"].as_f64().unwrap() - 20.0).abs() < 1e-6, "{p}");
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, dragged.x, dragged.y)), vec![Action::Commit]);
+ // Esc cancels a drag in progress.
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on_border.x, on_border.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, dragged.x, dragged.y));
+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, dragged.x, dragged.y)).is_empty());
+ // Inside the cell the Type tool places the caret as usual.
+ let inside = xf * Point::new(cell.rect.x0 + 20.0, (cell.rect.y0 + cell.rect.y1) / 2.0);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, inside.x, inside.y));
+ assert!(matches!(&a[..], [Action::Exec(cmd, _)] if cmd == "text.placeCaret"), "{a:?}");
+ }
+}
+
+#[test]
+fn eyedropper_samples_a_placed_image_and_matches_other_objects() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let photo = ItemId(d.alloc());
+ let mut it = Item::new(photo, lid, Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)));
+ it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {
+ asset: designcraft_doc::AssetId(1),
+ size: (100.0, 100.0),
+ xf: designcraft_geom::Affine::translate((0.0, 0.0)),
+ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
+ });
+ d.assets.insert(
+ designcraft_doc::AssetId(1),
+ std::sync::Arc::new(designcraft_doc::Asset {
+ id: designcraft_doc::AssetId(1),
+ name: "photo.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: std::sync::Arc::new(vec![]),
+ pixels: Some((100, 100)),
+ page: 0,
+ pdf_crop: Default::default(),
+ pdf_box: None,
+ }),
+ );
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ // An unfilled text frame over part of the photo lets it show through.
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(150.0, 150.0, 250.0, 250.0), lid, "x", ParaFormat::default()).unwrap();
+ let swatch = add_rect(&mut d, Rect::new(300.0, 100.0, 350.0, 150.0));
+ d.item_mut(swatch).unwrap().fill.swatch = "[Black]".into();
+ let target = add_rect(&mut d, Rect::new(400.0, 100.0, 450.0, 150.0));
+ // The photo's layer is locked: sampling it still works.
+ d.layers.iter_mut().for_each(|l| l.locked = true);
+ let s = Selection { items: vec![target], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let cx = ctx(&d, &s, &c, &l);
+ let mut t = create("eyedropper");
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ let sample = |x: f64, y: f64| Action::Exec("color.sample".into(), serde_json::json!({"at": [x, y], "spread": {"kind": "doc", "index": 0}}));
+ assert_eq!(a, vec![sample(120.0, 130.0)]);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 180.0 + off.x, 180.0 + off.y));
+ assert_eq!(a, vec![sample(180.0, 180.0)], "through the text frame");
+ // With the toolbox's Stroke box in front, the colour goes to the stroke (a line has no fill).
+ let mut cx_stroke = ctx(&d, &s, &c, &l);
+ cx_stroke.stroke_in_front = true;
+ let a = t.pointer(&cx_stroke, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ assert_eq!(
+ a,
+ vec![Action::Exec(
+ "color.sample".into(),
+ serde_json::json!({"at": [120.0, 130.0], "spread": {"kind": "doc", "index": 0}, "target": "stroke"})
+ )]
+ );
+ // A filled object is matched as before (here on a locked layer: not reachable, so nothing).
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 320.0 + off.x, 120.0 + off.y)).is_empty());
+ let mut d2 = d.clone();
+ d2.layers.iter_mut().for_each(|l| l.locked = false);
+ let cx = ctx(&d2, &s, &c, &l);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 320.0 + off.x, 120.0 + off.y));
+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": swatch.0}))]);
+ // An image the pointer can reach names its frame, whose attributes apply where no pixel shows.
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ let sampled = serde_json::json!({"at": [120.0, 130.0], "spread": {"kind": "doc", "index": 0}, "matchFrom": photo.0});
+ assert_eq!(a, vec![Action::Exec("color.sample".into(), sampled)]);
+ // Vector graphics and missing assets must retain the ordinary attribute-matching path.
+ for mime in ["application/pdf", "application/postscript", "image/svg+xml", "application/octet-stream"] {
+ std::sync::Arc::make_mut(d2.assets.get_mut(&designcraft_doc::AssetId(1)).unwrap()).mime = mime.into();
+ let cx = ctx(&d2, &s, &c, &l);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": photo.0}))], "{mime}");
+ }
+ d2.assets.clear();
+ let cx = ctx(&d2, &s, &c, &l);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": photo.0}))]);
+}
+
+#[test]
+fn double_clicking_a_handle_fits_the_frame_to_its_content_along_that_side() {
+ let mut d = Document::new(&NewDocument::default());
+ let id = add_rect(&mut d, Rect::new(100.0, 100.0, 300.0, 200.0));
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let cx = ctx(&d, &s, &c, &l);
+ let mut t = create("selection");
+ for ((x, y), axis) in [((300.0, 200.0), "both"), ((200.0, 200.0), "height"), ((300.0, 150.0), "width")] {
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, x + off.x, y + off.y));
+ assert_eq!(a, vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis}))], "{axis}");
+ }
+}
+
+#[test]
+fn fitting_handle_axes_follow_spread_and_frame_rotation() {
+ for spread_turn in 0..4 {
+ for frame_turn in 0..4 {
+ let mut d = Document::new(&NewDocument::default());
+ let id = add_rect(&mut d, Rect::new(100.0, 100.0, 300.0, 200.0));
+ d.item_mut(id).unwrap().xf = designcraft_geom::Affine::rotate(f64::from(frame_turn) * std::f64::consts::FRAC_PI_2);
+ Arc::make_mut(&mut d.spreads[0]).pages[0].view_rotation = spread_turn;
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let b = cx.selection_bounds().unwrap();
+ let mut t = create("selection");
+ let swapped = (spread_turn + frame_turn) % 2 == 1;
+ for (index, axis) in [(1, if swapped { "width" } else { "height" }), (3, if swapped { "height" } else { "width" }), (4, "both")] {
+ let p = select::handles(b)[index];
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, p.x, p.y));
+ assert_eq!(
+ a,
+ vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis}))],
+ "spread={spread_turn}, frame={frame_turn}, handle={index}"
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn pen_continues_an_open_path_from_either_end_point() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let id = ItemId(d.alloc());
+ let anchors = vec![
+ designcraft_geom::Anchor::corner(Point::new(100.0, 100.0)),
+ designcraft_geom::Anchor {
+ p: Point::new(200.0, 100.0),
+ h_in: Point::new(170.0, 80.0),
+ h_out: Point::new(230.0, 120.0),
+ kind: designcraft_geom::AnchorKind::Smooth,
+ },
+ ];
+ let mut it = Item::new(id, lid, Shape::Path, designcraft_geom::PathData::single(designcraft_geom::SubPath::new(anchors, false)));
+ it.stroke = Stroke::default();
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let at = |x: f64, y: f64| (x + off.x, y + off.y);
+ let ev = |k: PointerKind, (x, y): (f64, f64)| PointerEvent::new(k, x, y);
+ let mut t = create("pen");
+ // The cursor says the end point continues the path; elsewhere it's the plain pen.
+ assert_eq!(t.cursor(&cx, Point::new(at(200.0, 100.0).0, at(200.0, 100.0).1), Mods::default()), Cursor::PenContinue);
+ assert_eq!(t.cursor(&cx, Point::new(at(150.0, 300.0).0, at(150.0, 300.0).1), Mods::default()), Cursor::Pen);
+ // Clicking the last anchor adds nothing yet; the next click appends to that path.
+ assert!(t.pointer(&cx, &ev(PointerKind::Down, at(200.0, 100.0))).is_empty());
+ assert!(t.pointer(&cx, &ev(PointerKind::Up, at(200.0, 100.0))).is_empty(), "a click on the end point changes nothing");
+ t.pointer(&cx, &ev(PointerKind::Down, at(300.0, 200.0)));
+ let a = t.pointer(&cx, &ev(PointerKind::Up, at(300.0, 200.0)));
+ let [Action::Exec(cmd, p)] = a.as_slice() else { panic!("{a:?}") };
+ assert_eq!((cmd.as_str(), p["id"].as_u64(), p["subpath"].as_u64()), ("path.appendAnchor", Some(id.0), Some(0)));
+ assert_eq!((p["anchor"]["p"][0].as_f64(), p["anchor"]["p"][1].as_f64()), (Some(300.0), Some(200.0)));
+ // Clicking the first anchor of the other end closes it.
+ let a = t.pointer(&cx, &ev(PointerKind::Down, at(100.0, 100.0)));
+ assert_eq!(a, vec![Action::Exec("path.close".into(), serde_json::json!({"id": id.0, "subpath": 0}))]);
+ assert!(t.pointer(&cx, &ev(PointerKind::Up, at(100.0, 100.0))).is_empty());
+ // From the first anchor the path keeps its direction (arrowheads stay on their ends, and a
+ // press then Esc leaves nothing to undo): a drag there sets the first anchor's direction
+ // lines, and new anchors go before it.
+ let mut t = create("pen");
+ assert!(t.pointer(&cx, &ev(PointerKind::Down, at(100.0, 100.0))).is_empty());
+ t.pointer(&cx, &ev(PointerKind::Drag, at(80.0, 140.0)));
+ let a = t.pointer(&cx, &ev(PointerKind::Up, at(80.0, 140.0)));
+ assert_eq!(
+ a,
+ vec![Action::Exec(
+ "path.setAnchor".into(),
+ serde_json::json!({"id": id.0, "subpath": 0, "anchor": "first", "in": [80.0, 140.0], "out": [120.0, 60.0]})
+ )]
+ );
+ t.pointer(&cx, &ev(PointerKind::Down, at(20.0, 200.0)));
+ t.pointer(&cx, &ev(PointerKind::Drag, at(40.0, 220.0)));
+ let a = t.pointer(&cx, &ev(PointerKind::Up, at(40.0, 220.0)));
+ let [Action::Exec(cmd, p)] = a.as_slice() else { panic!("{a:?}") };
+ assert_eq!((cmd.as_str(), p["at"].as_str(), p["subpath"].as_u64()), ("path.appendAnchor", Some("start"), Some(0)));
+ assert_eq!(p["anchor"], serde_json::json!({"p": [20.0, 200.0], "in": [40.0, 220.0], "out": [0.0, 180.0]}));
+ let mut t = create("pen");
+ assert!(t.pointer(&cx, &ev(PointerKind::Down, at(100.0, 100.0))).is_empty());
+ assert!(t.pointer(&cx, &ev(PointerKind::Up, at(100.0, 100.0))).is_empty());
+ assert!(t.key(&cx, ToolKey::Escape, Mods::default()).iter().all(|a| !matches!(a, Action::Exec(c, _) if c.starts_with("path."))));
+ // Closed paths and locked paths aren't continued.
+ let mut d2 = d.clone();
+ d2.item_mut(id).unwrap().locked = true;
+ let cx = ctx(&d2, &s, &c, &l);
+ let t = create("pen");
+ assert_eq!(t.cursor(&cx, Point::new(at(200.0, 100.0).0, at(200.0, 100.0).1), Mods::default()), Cursor::Pen);
+}
++
+ #[test]
+ fn the_selection_tool_drags_a_path_type_bracket_along_its_path() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let id = ItemId(d.alloc());
+ let line = designcraft_geom::PathData::single(designcraft_geom::SubPath::new(
+ vec![designcraft_geom::Anchor::corner(Point::new(100.0, 300.0)), designcraft_geom::Anchor::corner(Point::new(500.0, 300.0))],
+ false,
+ ));
+ let mut it = Item::new(id, lid, Shape::GraphicLine, line);
+ let sid = designcraft_doc::StoryId(d.alloc());
+ let mut tf = designcraft_doc::TextFrame { story: sid, options: Default::default() };
+ tf.options.path = Some(designcraft_doc::PathType { start: 40.0, end: Some(300.0), ..Default::default() });
+ it.content = designcraft_doc::Content::Text(tf);
+ let mut st = designcraft_doc::Story::with_text(sid, "On the line", Default::default());
+ st.frames = vec![id];
+ d.stories.insert(sid, Arc::new(st));
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let at = |x: f64, y: f64| Point::new(x + off.x, y + off.y);
+ let ev = |k: PointerKind, p: Point| PointerEvent::new(k, p.x, p.y);
+ // Not selected: no brackets.
+ let none = Selection::default();
+ assert!(create("selection").overlays(&ctx(&d, &none, &c, &l)).is_empty());
+ let s = Selection { items: vec![id], ..Default::default() };
+ let cx = ctx(&d, &s, &c, &l);
+ let mut t = create("selection");
+ // Both brackets drawn across the path at 140 and 400 (a line and a tick each).
+ let o = t.overlays(&cx);
+ let xs: Vec<f64> = o.iter().filter_map(|o| if let Overlay::Line { a, b, .. } = o { (a.x == b.x).then_some(a.x - off.x) } else { None }).collect();
+ assert_eq!(xs, [140.0, 400.0], "{o:?}");
+ assert_eq!(t.cursor(&cx, at(140.0, 300.0), Mods::default()), Cursor::PathBracket);
+ assert_ne!(t.cursor(&cx, at(250.0, 300.0), Mods::default()), Cursor::PathBracket);
+ // Drag the start bracket: its distance along the path follows the pointer, off the path too.
+ assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, at(140.0, 301.0))), vec![Action::Begin("Move Bracket".into())]);
+ let a = t.pointer(&cx, &ev(PointerKind::Drag, at(220.0, 330.0)));
+ let [Action::Preview(cmd, p)] = a.as_slice() else { panic!("{a:?}") };
+ assert_eq!((cmd.as_str(), p["id"].as_u64()), ("type.pathOptions", Some(id.0)));
+ assert!((p["start"].as_f64().unwrap() - 120.0).abs() < 1e-6, "{p}");
+ assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, at(220.0, 330.0))), vec![Action::Commit]);
+ // The end bracket.
+ t.pointer(&cx, &ev(PointerKind::Down, at(400.0, 300.0)));
+ let a = t.pointer(&cx, &ev(PointerKind::Drag, at(450.0, 290.0)));
+ let [Action::Preview(_, p)] = a.as_slice() else { panic!("{a:?}") };
+ assert!((p["end"].as_f64().unwrap() - 350.0).abs() < 1e-6, "{p}");
+ }
diff --cc crates/ui-egui/src/cursors.rs
index c7dcd75ab,000000000..9960e2792
mode 100644,000000..100644
--- a/crates/ui-egui/src/cursors.rs
+++ b/crates/ui-egui/src/cursors.rs
@@@ -1,383 -1,0 +1,384 @@@
+//! Tool cursors drawn in code: black glyphs with a white halo, so they read on any page colour.
+//! The Selection tool's filled arrow, Direct Selection's hollow arrow, the pen nib with a badge for
+//! what a click does (add, delete, close, convert), and a curved double arrow for rotating.
+//! Cursors without a glyph stay system cursors.
+//!
+//! Linux and Windows show the glyphs as OS cursors ([`Images`]): the system moves them itself, so
+//! they never trail the pointer. macOS sizes a cursor bitmap in points (a Retina one would show
+//! twice as big, or blurred), so there the canvas paints the glyph at the pointer. The
+//! web build keeps the system cursors.
+
+use egui::epaint::{Mesh, TessellationOptions, Tessellator, Vertex};
+use egui::{Color32, CustomCursorImage, Pos2, Shape, Stroke, Vec2, pos2, vec2};
+
+use designcraft_tools::Cursor;
+
+const INK: Color32 = Color32::BLACK;
+const HALO: Color32 = Color32::WHITE;
+
+/// How the window shows a cursor glyph.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Mode {
+ /// As an OS cursor bitmap ([`Images`]).
+ Os,
+ /// Painted into the window at the pointer, the OS cursor hidden.
+ Painted,
+ /// Not at all: the system cursor stands in.
+ System,
+}
+
+pub const MODE: Mode = if cfg!(target_arch = "wasm32") {
+ Mode::System
+} else if cfg!(target_os = "macos") {
+ Mode::Painted
+} else {
+ Mode::Os
+};
+
+/// The shapes of one glyph: every halo goes under all the ink, so one part's halo never cuts
+/// through another part's ink.
+#[derive(Default)]
+struct Ink {
+ halo: Vec<Shape>,
+ ink: Vec<Shape>,
+}
+
+impl Ink {
+ fn halo(&mut self, s: Shape) {
+ self.halo.push(s);
+ }
+
+ fn add(&mut self, s: Shape) {
+ self.ink.push(s);
+ }
+
+ /// A filled outline with a halo around it.
+ fn poly(&mut self, pts: Vec<Pos2>, fill: Color32) {
+ self.halo(Shape::closed_line(pts.clone(), Stroke::new(3.0, HALO)));
+ self.add(Shape::convex_polygon(pts.clone(), fill, Stroke::NONE));
+ self.add(Shape::closed_line(pts, Stroke::new(1.0, INK)));
+ }
+
+ /// A haloed stroke.
+ fn line(&mut self, a: Pos2, b: Pos2) {
+ self.halo(Shape::line_segment([a, b], Stroke::new(3.0, HALO)));
+ self.add(Shape::line_segment([a, b], Stroke::new(1.2, INK)));
+ }
+
+ fn into_shapes(self) -> Vec<Shape> {
+ let mut out = self.halo;
+ out.extend(self.ink);
+ out
+ }
+}
+
+fn at(o: Pos2, pts: &[(f32, f32)]) -> Vec<Pos2> {
+ pts.iter().map(|&(x, y)| o + vec2(x, y)).collect()
+}
+
+/// The pointer arrow, tip at `o`: ink-filled (Selection) or hollow (Direct Selection).
+fn arrow(ink: &mut Ink, o: Pos2, hollow: bool) {
+ let pts = at(o, &[(0.0, 0.0), (0.0, 15.0), (3.8, 11.4), (6.4, 17.0), (8.6, 16.0), (6.1, 10.6), (11.0, 10.6)]);
+ ink.halo(Shape::closed_line(pts.clone(), Stroke::new(3.0, HALO)));
+ // The arrow is concave: fill it as two convex parts, then outline it.
+ let fill = if hollow { HALO } else { INK };
+ let part = |idx: &[usize]| idx.iter().filter_map(|&i| pts.get(i).copied()).collect::<Vec<_>>();
+ ink.add(Shape::convex_polygon(part(&[0, 1, 2, 5, 6]), fill, Stroke::NONE));
+ ink.add(Shape::convex_polygon(part(&[2, 3, 4, 5]), fill, Stroke::NONE));
+ ink.add(Shape::closed_line(pts, Stroke::new(1.0, INK)));
+}
+
+/// What the pen badge says a click does.
+#[derive(Clone, Copy)]
+enum Badge {
+ None,
+ Add,
+ Delete,
+ Close,
+ Convert,
+ Continue,
+}
+
+/// The pen nib, tip at `o` (top left), with a badge below right.
+fn pen(ink: &mut Ink, o: Pos2, badge: Badge) {
+ ink.poly(at(o, &[(0.0, 0.0), (4.0, 12.0), (8.0, 16.0), (16.0, 8.0), (12.0, 4.0)]), INK);
+ // The nib's slit and breather hole.
+ ink.add(Shape::line_segment([o + vec2(1.0, 1.0), o + vec2(5.5, 5.5)], Stroke::new(1.0, HALO)));
+ ink.add(Shape::circle_filled(o + vec2(6.5, 6.5), 1.4, HALO));
+ ink.line(o + vec2(10.0, 14.0), o + vec2(14.0, 18.0));
+ let b = o + vec2(16.0, 14.0);
+ match badge {
+ Badge::None => {}
+ Badge::Add => {
+ ink.line(b + vec2(0.0, 3.0), b + vec2(6.0, 3.0));
+ ink.line(b + vec2(3.0, 0.0), b + vec2(3.0, 6.0));
+ }
+ Badge::Delete => ink.line(b + vec2(0.0, 3.0), b + vec2(6.0, 3.0)),
+ Badge::Close => {
+ ink.halo(Shape::circle_stroke(b + vec2(3.0, 3.0), 3.0, Stroke::new(3.0, HALO)));
+ ink.add(Shape::circle_stroke(b + vec2(3.0, 3.0), 3.0, Stroke::new(1.2, INK)));
+ }
+ Badge::Convert => {
+ ink.line(b + vec2(0.0, 6.0), b + vec2(3.0, 0.0));
+ ink.line(b + vec2(3.0, 0.0), b + vec2(6.0, 6.0));
+ }
+ Badge::Continue => ink.line(b + vec2(1.0, 6.0), b + vec2(5.0, 0.0)),
+ }
+}
+
+/// A curved double arrow over the hotspot: an arc bowing up, an arrowhead at each end pointing on
+/// along the arc.
+fn rotate(ink: &mut Ink, o: Pos2) {
+ const R: f32 = 8.0;
+ let (a0, a1) = (std::f32::consts::PI * 0.12, std::f32::consts::PI * 0.88);
+ let on = |a: f32| o + vec2(a.cos() * R, -a.sin() * R);
+ let pts: Vec<Pos2> = (0..=12).map(|i| on(a0 + (a1 - a0) * i as f32 / 12.0)).collect();
+ ink.halo(Shape::line(pts.clone(), Stroke::new(3.2, HALO)));
+ ink.add(Shape::line(pts, Stroke::new(1.3, INK)));
+ for (a, away) in [(a0, -1.0f32), (a1, 1.0)] {
+ let t = vec2(-a.sin(), -a.cos()) * away;
+ let n = vec2(-t.y, t.x);
+ let (end, tip) = (on(a) - t * 1.5, on(a) + t * 4.5);
+ ink.poly(vec![tip, end + n * 1.8, end - n * 1.8], INK);
+ }
+}
+
+/// The shapes of cursor `c` with its hotspot at `p`, in points; `None` for system cursors.
+fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> {
+ let mut ink = Ink::default();
+ match c {
+ Cursor::Arrow => arrow(&mut ink, p, false),
+ Cursor::ArrowHollow => arrow(&mut ink, p, true),
+ Cursor::Pen => pen(&mut ink, p, Badge::None),
+ Cursor::PenAdd => pen(&mut ink, p, Badge::Add),
+ Cursor::PenDelete => pen(&mut ink, p, Badge::Delete),
+ Cursor::PenClose => pen(&mut ink, p, Badge::Close),
+ Cursor::PenConvert => pen(&mut ink, p, Badge::Convert),
+ Cursor::PenContinue => pen(&mut ink, p, Badge::Continue),
+ Cursor::Rotate => rotate(&mut ink, p),
+ _ => return None,
+ }
+ Some(ink.into_shapes())
+}
+
+/// The cursor bitmaps handed to the OS, by (cursor, pixels per point). Each glyph is rasterized
+/// once; handing the same `Arc` every frame lets the integration keep its OS cursor.
+#[derive(Default)]
+pub struct Images(Vec<(Cursor, f32, CustomCursorImage)>);
+
+impl Images {
+ /// Cursor `c` for `ppp` physical pixels per point; `None` for cursors without a glyph.
+ pub fn get(&mut self, c: Cursor, ppp: f32) -> Option<CustomCursorImage> {
+ if let Some((.., image)) = self.0.iter().find(|(k, s, _)| *k == c && *s == ppp) {
+ return Some(image.clone());
+ }
+ let image = rasterize(c, ppp)?;
+ // A few glyphs at the scales of the displays the window visited.
+ if self.0.len() >= 128 {
+ self.0.clear();
+ }
+ self.0.push((c, ppp, image.clone()));
+ Some(image)
+ }
+}
+
+/// The largest side of a cursor bitmap, in pixels (the glyphs span under 30 points).
+const MAX_SIDE: f32 = 256.0;
+
+/// Cursor `c` as a straight-alpha RGBA bitmap at `ppp` pixels per point, tessellated
+/// (anti-aliased) as egui would paint it, the hotspot on a pixel corner.
+pub(crate) fn rasterize(c: Cursor, ppp: f32) -> Option<CustomCursorImage> {
+ if !(ppp.is_finite() && ppp > 0.0) {
+ return None;
+ }
+ let shapes = glyph(c, Pos2::ZERO)?;
+ let mut tessellator = Tessellator::new(ppp, TessellationOptions::default(), [1, 1], vec![]);
+ let mut mesh = Mesh::default();
+ for shape in shapes {
+ tessellator.tessellate_shape(shape, &mut mesh);
+ }
+ let bounds = mesh.calc_bounds();
+ // The hotspot must lie inside the bitmap.
+ let min = (bounds.min.to_vec2() * ppp).floor().min(Vec2::ZERO);
+ let max = (bounds.max.to_vec2() * ppp).ceil().max(Vec2::splat(1.0));
+ let size = max - min;
+ if !(size.x <= MAX_SIDE && size.y <= MAX_SIDE) {
+ return None;
+ }
+ let (w, h) = (size.x as usize, size.y as usize);
+ let mut px = vec![[0.0; 4]; w * h];
+ let corner = |v: &Vertex| (v.pos.to_vec2() * ppp - min, v.color);
+ for &[i, j, k] in mesh.indices.as_chunks::<3>().0 {
+ if let (Some(a), Some(b), Some(c)) = (mesh.vertices.get(i as usize), mesh.vertices.get(j as usize), mesh.vertices.get(k as usize)) {
+ fill_triangle(&mut px, w, [corner(a), corner(b), corner(c)]);
+ }
+ }
+ let rgba: Vec<u8> = px
+ .iter()
+ .flat_map(|&[r, g, b, a]| {
+ let k = if a > 0.0 { 1.0 / a } else { 0.0 };
+ [r * k, g * k, b * k, a].map(|x| (x * 255.0).round().clamp(0.0, 255.0) as u8)
+ })
+ .collect();
+ Some(CustomCursorImage { rgba: rgba.into(), size: [w as u16, h as u16], hotspot: [-min.x as u16, -min.y as u16] })
+}
+
+/// Blend triangle `t` (pixel positions and premultiplied colours, interpolated across it) over `px`
+/// (premultiplied RGBA, `w` pixels a row) at the pixel centres it covers, as the GPU blends egui's
+/// meshes. A centre on an edge goes to one of the two triangles sharing it, so seams aren't doubled.
+fn fill_triangle(px: &mut [[f32; 4]], w: usize, t: [(Vec2, Color32); 3]) {
+ let edge = |a: Vec2, b: Vec2, p: Vec2| (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
+ let [a, mut b, mut c] = t;
+ let mut area = edge(a.0, b.0, c.0);
+ if area < 0.0 {
+ std::mem::swap(&mut b, &mut c);
+ area = -area;
+ }
+ if area.is_nan() || area <= 1e-6 || w == 0 {
+ return;
+ }
+ // Of the two triangles sharing an edge (walking it in opposite directions), one owns it.
+ let owns = |u: Vec2, v: Vec2| v.y > u.y || (v.y == u.y && v.x > u.x);
+ let h = px.len() / w;
+ let lo = a.0.min(b.0).min(c.0).max(Vec2::ZERO);
+ let hi = a.0.max(b.0).max(c.0).min(vec2(w as f32, h as f32));
+ for y in lo.y.floor() as usize..hi.y.ceil() as usize {
+ for x in lo.x.floor() as usize..hi.x.ceil() as usize {
+ let p = pos2(x as f32 + 0.5, y as f32 + 0.5).to_vec2();
+ let weights = [(b.0, c.0), (c.0, a.0), (a.0, b.0)].map(|(u, v)| (edge(u, v, p), owns(u, v)));
+ if !weights.iter().all(|&(e, own)| e > 0.0 || (e == 0.0 && own)) {
+ continue;
+ }
+ let Some(dst) = px.get_mut(y * w + x) else { continue };
+ let [wa, wb, wc] = weights.map(|(e, _)| e / area);
+ let src: [f32; 4] = std::array::from_fn(|i| {
+ let channel = |col: Color32| f32::from(col.to_array()[i]);
+ (wa * channel(a.1) + wb * channel(b.1) + wc * channel(c.1)) / 255.0
+ });
+ let keep = 1.0 - src[3];
+ *dst = std::array::from_fn(|i| src[i] + dst[i] * keep);
+ }
+ }
+}
+
+/// The system cursor for `c`: shown where the window has no glyph for it, or no bitmap cursors.
+pub fn system(c: Cursor) -> egui::CursorIcon {
+ use egui::CursorIcon as C;
+ match c {
+ Cursor::Arrow | Cursor::ArrowHollow => C::Default,
+ Cursor::Move => C::Move,
+ Cursor::Crosshair => C::Crosshair,
+ Cursor::ResizeH => C::ResizeHorizontal,
+ Cursor::ResizeV => C::ResizeVertical,
+ Cursor::ResizeNwSe => C::ResizeNwSe,
+ Cursor::ResizeNeSw => C::ResizeNeSw,
+ Cursor::Rotate => C::Alias,
+ Cursor::Pen | Cursor::PenAdd | Cursor::PenDelete | Cursor::PenClose | Cursor::PenConvert | Cursor::PenContinue => C::Crosshair,
++ Cursor::PathBracket => C::ResizeColumn,
+ Cursor::Text => C::Text,
+ Cursor::Hand => C::Grab,
+ Cursor::HandGrab => C::Grabbing,
+ Cursor::ZoomIn => C::ZoomIn,
+ Cursor::ZoomOut => C::ZoomOut,
+ Cursor::Eyedropper => C::Crosshair,
+ Cursor::LoadedText | Cursor::LoadedGraphic => C::Copy,
+ Cursor::ThreadLink => C::Alias,
+ Cursor::Unthread => C::NoDrop,
+ Cursor::NotAllowed => C::NotAllowed,
+ }
+}
+
+/// Show cursor `c` with the pointer at `hover` (screen points): set the OS cursor bitmap or paint
+/// the glyph per [`MODE`], and return the cursor icon to set.
+pub fn show(ctx: &egui::Context, images: &mut Images, c: Cursor, hover: Pos2) -> egui::CursorIcon {
+ match MODE {
+ Mode::Os => {
+ // The glyphs keep the system cursors' size whatever the interface scale.
+ let ppp = ctx.pixels_per_point() / ctx.zoom_factor().max(0.01);
+ ctx.set_cursor_image(images.get(c, ppp));
+ system(c)
+ }
+ Mode::Painted => {
+ let layer = egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("tool-cursor"));
+ // Divide by the zoom factor so the glyph keeps its size in physical pixels.
+ let scale = 1.0 / ctx.zoom_factor().max(0.01);
+ let painter = ctx.layer_painter(layer);
+ match glyph(c, Pos2::ZERO) {
+ Some(shapes) => {
+ let place = egui::emath::TSTransform::new(hover.to_vec2(), scale);
+ painter.extend(shapes.into_iter().map(|mut s| {
+ s.transform(place);
+ s
+ }));
+ egui::CursorIcon::None
+ }
+ None => system(c),
+ }
+ }
+ Mode::System => system(c),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Every cursor with a glyph.
+ const GLYPHS: [Cursor; 9] = [
+ Cursor::Arrow,
+ Cursor::ArrowHollow,
+ Cursor::Pen,
+ Cursor::PenAdd,
+ Cursor::PenDelete,
+ Cursor::PenClose,
+ Cursor::PenConvert,
+ Cursor::PenContinue,
+ Cursor::Rotate,
+ ];
+
+ fn alpha(img: &CustomCursorImage, x: usize, y: usize) -> u8 {
+ img.rgba.get((y * img.size[0] as usize + x) * 4 + 3).copied().unwrap_or(0)
+ }
+
+ #[test]
+ fn every_glyph_rasterizes_with_its_hotspot_inside() {
+ for c in GLYPHS {
+ for ppp in [1.0, 2.0] {
+ let img = rasterize(c, ppp).unwrap_or_else(|| panic!("{c:?} has no bitmap"));
+ let [w, h] = img.size.map(usize::from);
+ assert_eq!(img.rgba.len(), w * h * 4, "{c:?}");
+ let [hx, hy] = img.hotspot.map(usize::from);
+ assert!(hx < w && hy < h, "{c:?} hotspot {:?} outside {:?}", img.hotspot, img.size);
+ let inked = (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).filter(|&(x, y)| alpha(&img, x, y) > 128).count();
+ assert!(inked > 20, "{c:?} at {ppp}× is nearly empty ({inked} pixels)");
+ }
+ }
+ for c in [Cursor::Text, Cursor::Hand, Cursor::ZoomIn, Cursor::Crosshair] {
+ assert!(rasterize(c, 1.0).is_none(), "{c:?} stays a system cursor");
+ }
+ assert!(rasterize(Cursor::Pen, f32::NAN).is_none() && rasterize(Cursor::Pen, 0.0).is_none());
+ }
+
+ #[test]
+ fn the_selection_arrows_differ_in_fill() {
+ // A pixel inside the arrow's body, below the tip: ink for Selection, halo for Direct.
+ let centre = |c| {
+ let img = rasterize(c, 2.0).unwrap_or_else(|| panic!("{c:?}"));
+ let [hx, hy] = img.hotspot.map(usize::from);
+ let i = ((hy + 16) * img.size[0] as usize + hx + 4) * 4;
+ img.rgba.get(i..i + 4).map(|p| p.to_vec()).unwrap_or_default()
+ };
+ assert_eq!(centre(Cursor::Arrow), vec![0, 0, 0, 255], "Selection is filled");
+ assert_eq!(centre(Cursor::ArrowHollow), vec![255, 255, 255, 255], "Direct Selection is hollow");
+ }
+
+ #[test]
+ fn images_are_cached_by_cursor_and_scale() {
+ let mut images = Images::default();
+ let a = images.get(Cursor::Pen, 2.0).unwrap_or_else(|| panic!("pen"));
+ let b = images.get(Cursor::Pen, 2.0).unwrap_or_else(|| panic!("pen"));
+ assert!(std::sync::Arc::ptr_eq(&a.rgba, &b.rgba), "the same bitmap every frame");
+ assert_ne!(images.get(Cursor::Pen, 1.0).map(|i| i.size), Some(a.size));
+ assert!(images.get(Cursor::Text, 2.0).is_none());
+ }
+}