DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge branch 'pr415' into tmp415
moppeeer6d2cfe04b7e7
diff --cc crates/engine/src/cmd/object.rsindex aa5a2cc01,0456dd05c..01aa9af5f--- a/crates/engine/src/cmd/object.rs+++ b/crates/engine/src/cmd/object.rs@@@ -42,7 -31,7 +42,7 @@@ pub fn specs() -> Vec<CommandSpec>"Move",["Object", "Transform"],None,- "{dx, dy, copy?: bool, ids?, toSpread?} → {moved, ids: the objects moved (with copy, the copies)}",- "{dx, dy, copy?: bool, ids?, toSpread?, content?: bool (move the placed graphic or pasted-in items inside each frame; the frame stays. Default: whether the selection is content, when neither ids nor copy is given)}",++ "{dx, dy, copy?: bool, ids?, toSpread?, content?: bool (move the placed graphic or pasted-in items inside each frame; the frame stays. Default: whether the selection is content, when neither ids nor copy is given)} → {moved, ids: the objects moved (with copy, the copies)}",has_selection,transform_move),@@@ -1048,9 -983,9 +1056,9 @@@ fn transform_move(s: &mut Session, p: &if it.locked {continue;}- it.xf = Affine::translate((dx, dy)) * it.xf;+ it.xf = Affine::translate(v) * it.xf;}- Ok(json!({"moved": ids.len()}))+ Ok(json!({"moved": ids.len(), "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))})}@@@ -3183,147 -2774,74 +3234,219 @@@ mod blend_mode_tests}}+#[cfg(test)]+mod copy_ids_tests {+ use serde_json::json;++ #[test]+ fn copies_report_their_ids() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let a = s.execute("frame.create", &json!({"rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap();+ let ids = |r: &serde_json::Value| r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect::<Vec<_>>();+ let selected = |s: &crate::Session| s.doc().unwrap().selection.items.iter().map(|i| i.0).collect::<Vec<_>>();+ // Moving reports what moved; copying reports the copies, which are selected.+ assert_eq!(ids(&s.execute("transform.move", &json!({"dx": 5, "dy": 0, "ids": [a]})).unwrap()), [a]);+ let r = s.execute("transform.move", &json!({"dx": 100, "dy": 0, "copy": true, "ids": [a]})).unwrap();+ let copy = ids(&r);+ assert!(copy.len() == 1 && copy[0] != a && s.doc().unwrap().doc.item(designcraft_doc::ItemId(copy[0])).is_some(), "{r}");+ assert_eq!(selected(&s), copy);+ // Edit › Duplicate.+ let r = s.execute("edit.duplicate", &json!({})).unwrap();+ let dup = ids(&r);+ assert!(dup.len() == 1 && dup[0] != copy[0], "{r}");+ assert_eq!(selected(&s), dup);+ // Step and Repeat: every copy.+ let r = s.execute("edit.stepAndRepeat", &json!({"count": 3, "dx": 0, "dy": 60, "ids": [a]})).unwrap();+ assert_eq!((r["created"].as_u64(), ids(&r).len()), (Some(3), 3), "{r}");+ assert!(ids(&r).iter().all(|i| s.doc().unwrap().doc.item(designcraft_doc::ItemId(*i)).is_some()));+ }+}++#[cfg(test)]+mod swatch_name_tests {+ use serde_json::json;++ #[test]+ fn fills_and_strokes_must_name_a_swatch_and_change_nothing_otherwise() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let id = s.execute("frame.create", &json!({"rect": [0, 0, 100, 100]})).unwrap()["id"].clone();+ for (cmd, params, hint) in [+ ("object.fill", json!({"swatch": "Paper", "ids": [id]}), Some("[Paper]")),+ ("object.fill", json!({"swatch": "[black]", "ids": [id]}), Some("[Black]")),+ ("object.fill", json!({"swatch": "Missing Ink", "ids": [id]}), None),+ ("object.stroke", json!({"swatch": "#ff0000", "weight": 4, "ids": [id]}), None),+ ("object.stroke", json!({"gapSwatch": "paper", "ids": [id]}), Some("[Paper]")),+ ] {+ let before = s.doc().unwrap().doc.clone();+ let e = s.execute(cmd, ¶ms).unwrap_err().to_string();+ assert!(e.contains("no swatch named") && e.contains("swatch.create"), "{cmd}: {e}");+ if let Some(h) = hint {+ assert!(e.contains(&format!("did you mean `{h}`")), "{cmd}: {e}");+ }+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{cmd}: nothing changed");+ }+ // Real names, [None] included, still work.+ for sw in ["[Paper]", "[None]", "C=100 M=0 Y=0 K=0"] {+ s.execute("object.fill", &json!({"swatch": sw, "ids": [id]})).unwrap();+ s.execute("object.stroke", &json!({"swatch": sw, "ids": [id]})).unwrap();+ }+ }+}++#[cfg(test)]+mod path_edit_tests {+ use designcraft_doc::ItemId;+ use designcraft_geom::Point;+ use serde_json::json;++ fn session_with_path() -> (crate::Session, u64) {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let id = s+ .execute(+ "path.create",+ &json!({"anchors": [{"p": [100, 100]}, {"p": [200, 100], "in": [170, 80], "out": [230, 120]}, {"p": [300, 200]}]}),+ )+ .unwrap()["id"]+ .as_u64()+ .unwrap();+ (s, id)+ }++ fn anchors(s: &crate::Session, id: u64) -> Vec<designcraft_geom::Anchor> {+ let d = &s.doc().unwrap().doc;+ let it = d.item(ItemId(id)).unwrap();+ let xf = d.parent_xf(&d.find(ItemId(id)).unwrap()) * it.xf;+ it.path.subpaths[0].anchors.iter().map(|a| a.transform(xf)).collect()+ }++ #[test]+ fn reverse_path_swaps_ends_and_direction_lines() {+ let (mut s, id) = session_with_path();+ s.execute("path.reverse", &json!({"ids": [id]})).unwrap();+ let a = anchors(&s, id);+ assert_eq!(a.iter().map(|a| a.p).collect::<Vec<_>>(), [Point::new(300.0, 200.0), Point::new(200.0, 100.0), Point::new(100.0, 100.0)]);+ assert_eq!((a[1].h_in, a[1].h_out), (Point::new(230.0, 120.0), Point::new(170.0, 80.0)));+ assert!(s.execute("path.reverse", &json!({"ids": [id], "subpath": 3})).is_err());+ }++ #[test]+ fn anchors_go_on_the_named_open_subpath_and_set_anchor_reshapes_one() {+ let (mut s, id) = session_with_path();+ s.execute("path.appendAnchor", &json!({"id": id, "subpath": 0, "anchor": {"p": [400, 250]}})).unwrap();+ assert_eq!(anchors(&s, id).last().unwrap().p, Point::new(400.0, 250.0));+ assert!(s.execute("path.appendAnchor", &json!({"id": id, "subpath": 1, "anchor": {"p": [0, 0]}})).is_err());+ // Direction lines on the last anchor: collinear and opposite make it smooth.+ s.execute("path.setAnchor", &json!({"id": id, "anchor": "last", "in": [380, 230], "out": [420, 270]})).unwrap();+ let last = *anchors(&s, id).last().unwrap();+ assert_eq!((last.h_in, last.h_out, last.kind), (Point::new(380.0, 230.0), Point::new(420.0, 270.0), designcraft_geom::AnchorKind::Smooth));+ s.execute("path.setAnchor", &json!({"id": id, "anchor": 0, "p": [90, 110]})).unwrap();+ assert_eq!(anchors(&s, id)[0].p, Point::new(90.0, 110.0));+ assert!(s.execute("path.setAnchor", &json!({"id": id, "anchor": 9, "p": [0, 0]})).is_err());+ assert!(s.execute("path.setAnchor", &json!({"id": id, "anchor": "last"})).is_err(), "nothing to set");+ // Closing one subpath; then it takes no more anchors.+ s.execute("path.close", &json!({"id": id, "subpath": 0})).unwrap();+ assert!(s.execute("path.appendAnchor", &json!({"id": id, "anchor": {"p": [0, 0]}})).is_err());+ assert!(s.execute("path.close", &json!({"id": id, "subpath": 4})).is_err());+ }+}++#[cfg(test)]+mod spread_target_tests {+ use super::*;++ #[test]+ fn creating_on_a_parent_spread_and_rejecting_unknown_spreads() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 1, "facingPages": false})).unwrap();+ let parent = json!({"kind": "parent", "index": 0});+ let r = s.execute("frame.create", &json!({"spread": parent, "rect": [0, 0, 100, 100]})).unwrap();+ let id = ItemId(r["id"].as_u64().unwrap());+ assert_eq!(s.doc().unwrap().doc.find(id).unwrap().spread, SpreadRef::Parent(0));+ s.execute("line.create", &json!({"spread": parent, "a": [0, 0], "b": [50, 50]})).unwrap();+ assert_eq!(s.doc().unwrap().doc.parents[0].items.len(), 2);++ // Each of these used to land on the first body page.+ for bad in+ [json!("A-Parent"), json!("0"), json!(-1), json!(1.5), json!({"kind": "master", "index": 0}), json!({"kind": "parent"}), json!([0])]+ {+ assert!(s.execute("frame.create", &json!({"spread": bad, "rect": [0, 0, 100, 100]})).is_err(), "frame.create spread {bad}");+ assert!(s.execute("line.create", &json!({"spread": bad, "a": [0, 0], "b": [50, 50]})).is_err(), "line.create spread {bad}");+ }+ assert!(s.doc().unwrap().doc.spreads[0].items.is_empty());+ }+}+++ #[cfg(test)]+ mod content_move_tests {+ use super::*;++ /// A session with a 40×20 image placed in a frame at (100, 100)–(300, 300).+ fn placed() -> (Session, ItemId) {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();+ let f = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();+ s.execute("place.load", &json!({"base64": super::super::base64_encode(&png)})).unwrap();+ s.execute("place.drop", &json!({"frame": f})).unwrap();+ (s, ItemId(f))+ }++ /// Spread bounds of the frame and of its graphic.+ fn boxes(s: &Session, id: ItemId) -> (Rect, Rect) {+ let it = s.doc().unwrap().doc.item(id).unwrap().clone();+ let g = it.graphic().unwrap();+ (it.bounds(), (it.xf * g.xf).transform_rect_bbox(Rect::new(0.0, 0.0, g.size.0, g.size.1)))+ }++ fn near(a: Rect, b: Rect) -> bool {+ [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-6)+ }++ #[test]+ fn content_moves_inside_the_frame_in_one_undo_step() {+ let (mut s, f) = placed();+ let (frame0, g0) = boxes(&s, f);+ s.execute("selection.set", &json!({"ids": [f.0], "content": true})).unwrap();+ s.execute("transform.move", &json!({"dx": 10, "dy": -5})).unwrap();+ let (frame1, g1) = boxes(&s, f);+ assert!(near(frame1, frame0), "the frame stays");+ assert!(near(g1, g0 + Vec2::new(10.0, -5.0)), "{g1:?}");+ s.execute("edit.undo", &json!({})).unwrap();+ assert!(near(boxes(&s, f).1, g0));+ // Explicit ids with `content` act on the content whatever the selection is.+ s.execute("selection.set", &json!({"ids": [f.0]})).unwrap();+ s.execute("transform.move", &json!({"ids": [f.0], "content": true, "dx": 3})).unwrap();+ assert!(near(boxes(&s, f).0, frame0) && near(boxes(&s, f).1, g0 + Vec2::new(3.0, 0.0)));+ // A frame selection moves frame and content together.+ s.execute("transform.move", &json!({"dx": 4})).unwrap();+ assert!(near(boxes(&s, f).0, frame0 + Vec2::new(4.0, 0.0)) && near(boxes(&s, f).1, g0 + Vec2::new(7.0, 0.0)));+ }++ #[test]+ fn content_moves_on_the_page_axes_in_a_rotated_frame_and_pasted_items_move_too() {+ let (mut s, f) = placed();+ s.execute("transform.rotate", &json!({"ids": [f.0], "angle": 90})).unwrap();+ let (frame0, g0) = boxes(&s, f);+ s.execute("transform.move", &json!({"ids": [f.0], "content": true, "dx": 10})).unwrap();+ let (frame1, g1) = boxes(&s, f);+ assert!(near(frame1, frame0) && near(g1, g0 + Vec2::new(10.0, 0.0)), "{g0:?} → {g1:?}");+ // Items pasted into a frame are its content.+ let a = s.execute("frame.create", &json!({"rect": [400, 100, 420, 120], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [a]})).unwrap();+ s.execute("edit.copy", &json!({})).unwrap();+ let b = s.execute("frame.create", &json!({"rect": [400, 300, 500, 400], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [b]})).unwrap();+ s.execute("edit.pasteInto", &json!({})).unwrap();+ let kids = |s: &Session| {+ let it = s.doc().unwrap().doc.item(ItemId(b)).unwrap().clone();+ (it.bounds(), it.children().iter().map(|c| it.xf.transform_rect_bbox(c.bounds())).collect::<Vec<_>>())+ };+ let (fb0, k0) = kids(&s);+ s.execute("transform.move", &json!({"ids": [b], "content": true, "dx": 5, "dy": 6})).unwrap();+ let (fb1, k1) = kids(&s);+ assert!(near(fb1, fb0) && near(k1[0], k0[0] + Vec2::new(5.0, 6.0)), "{k0:?} → {k1:?}");+ }+ }diff --cc crates/tools/src/select.rsindex fc9a8c316,46e0533df..f4b0472db--- a/crates/tools/src/select.rs+++ b/crates/tools/src/select.rs@@@ -493,15 -522,7 +578,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![];}@@@ -805,21 -853,28 +919,32 @@@}}- fn overlays(&self, _cx: &ToolContext) -> Vec<Overlay> {+ fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {match &self.drag {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![],}}fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor {+ if matches!(self.drag, Drag::Bracket { .. }) || (matches!(self.drag, Drag::None) && bracket_at(cx, p).is_some()) {+ return Cursor::PathBracket;+ }+ if let Drag::Move { content: true, .. } = self.drag {+ return Cursor::HandGrab;+ }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 };}match self.drag {Drag::Move { .. } => return Cursor::Move,diff --cc crates/tools/src/tests.rsindex 6776902aa,659f2c523..82dd7725a--- a/crates/tools/src/tests.rs+++ b/crates/tools/src/tests.rs@@@ -706,173 -706,105 +706,276 @@@ fn pen_click_snaps_to_a_guide()assert!((x - 100.0).abs() < 1e-6, "anchor x {x}");}+#[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 is reversed first; a drag there sets its direction lines.+ let mut t = create("pen");+ let a = t.pointer(&cx, &ev(PointerKind::Down, at(100.0, 100.0)));+ assert_eq!(a, vec![Action::Exec("path.reverse".into(), serde_json::json!({"ids": [id.0], "subpath": 0}))]);+ 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": "last", "in": [120.0, 60.0], "out": [80.0, 140.0]})+ )]+ );+ // 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}");+}++#[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)),+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [0.0; 4],+ });+ 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,+ }),+ );+ 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");+ // 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}))]);+ // 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}))]);+}+++ /// 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)),+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [0.0; 4],+ });+ 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 dbl = PointerEvent::new(PointerKind::DoubleClick, at.x, at.y);+ let frame = Selection::items(vec![f]);+ let a = t.pointer(&ctx(&d, &frame, &c, &l), &dbl);+ assert_eq!(a, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": true}))]);+ let content = Selection { content: true, ..Selection::items(vec![f]) };+ let a = t.pointer(&ctx(&d, &content, &c, &l), &dbl);+ assert_eq!(a, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": false}))]);+ }