DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge pr/630: Tools: the Pen continues an open path from either end point (#630)
aiongg575839cc4f1c
diff --cc ROADMAP.mdindex 21ed577ee,4f42aa6ba..a18cc8739--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -128,7 -129,7 +128,8 @@@ list) · [roadmap.md](docs/roadmap.md)Newest first.+ - **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/engine/src/cmd/object.rsindex 59fc5e711,e79009e7e..29aa8dc09--- a/crates/engine/src/cmd/object.rs+++ b/crates/engine/src/cmd/object.rs@@@ -3937,279 -2913,87 +4063,337 @@@ mod tint_alone_testsuse serde_json::json;#[test]- fn fills_and_strokes_must_name_a_swatch_and_change_nothing_otherwise() {+ fn a_tint_alone_keeps_each_swatch_and_leaves_no_stroke_alone() {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}");+ let a = s.execute("frame.create", &json!({"rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("frame.create", &json!({"rect": [60, 0, 110, 50]})).unwrap()["id"].as_u64().unwrap();+ s.execute("object.fill", &json!({"swatch": "[Black]", "ids": [a]})).unwrap();+ s.execute("object.fill", &json!({"swatch": "C=100 M=0 Y=0 K=0", "ids": [b]})).unwrap();+ s.execute("object.stroke", &json!({"swatch": "[None]", "ids": [a, b]})).unwrap();+ // Fill tint on both: each keeps its swatch.+ s.execute("object.fill", &json!({"tint": 0.25, "ids": [a, b]})).unwrap();+ let item = |s: &crate::Session, id: u64| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().clone();+ assert_eq!((item(&s, a).fill.swatch.as_str(), item(&s, a).fill.tint), ("[Black]", 0.25));+ assert_eq!((item(&s, b).fill.swatch.as_str(), item(&s, b).fill.tint), ("C=100 M=0 Y=0 K=0", 0.25));+ // A swatch alone is 100%.+ s.execute("object.fill", &json!({"swatch": "[Paper]", "ids": [a]})).unwrap();+ assert_eq!(item(&s, a).fill.tint, 1.0);+ // A stroke tint on no stroke: still no stroke.+ s.execute("object.stroke", &json!({"tint": 0.5, "ids": [a]})).unwrap();+ assert!(item(&s, a).stroke.is_none(), "{:?}", item(&s, a).stroke);+ assert!(s.execute("object.fill", &json!({"ids": [a]})).is_err(), "neither swatch nor tint");+ }+}++#[cfg(test)]+mod content_transform_tests {+ use serde_json::json;++ use crate::Session;++ /// A rotated graphic frame holding a 200 x 100 image, its content selected.+ fn rotated_frame_with_image() -> (Session, u64) {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let f = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();+ let png = designcraft_render::Rendered { width: 200, height: 100, pixels: vec![200u8; 200 * 100 * 4] }.to_png();+ s.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&png), "name": "a.png", "frame": f})).unwrap();+ s.execute("transform.rotate", &json!({"ids": [f], "angle": -45})).unwrap();+ s.execute("selection.set", &json!({"ids": [f], "content": true})).unwrap();+ (s, f)+ }++ #[test]+ fn rotating_the_content_leaves_the_frame_as_it_is() {+ let (mut s, f) = rotated_frame_with_image();+ let before = s.execute("transform.info", &json!({"ids": [f]})).unwrap();+ assert!((before["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6 && (before["content"]["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6);+ // The tutorial's step: the image straightened inside its tilted frame.+ s.execute("transform.set", &json!({"rotation": 0})).unwrap();+ let after = s.execute("transform.info", &json!({"ids": [f]})).unwrap();+ assert!((after["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6, "the frame stays at -45: {after}");+ assert!(after["content"]["rotation"].as_f64().unwrap().abs() < 1e-6, "the image is upright: {after}");+ // Scale and position act on the image too.+ s.execute("transform.set", &json!({"scaleX": 50, "scaleY": 50})).unwrap();+ let info = s.execute("transform.info", &json!({"ids": [f]})).unwrap();+ assert!((info["content"]["scaleX"].as_f64().unwrap() - 50.0).abs() < 1e-6, "{info}");+ assert!((info["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6);+ // One undo step each.+ s.execute("edit.undo", &json!({})).unwrap();+ s.execute("edit.undo", &json!({})).unwrap();+ let undone = s.execute("transform.info", &json!({"ids": [f]})).unwrap();+ assert!((undone["content"]["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6, "{undone}");+ }++ #[test]+ fn with_the_graphic_selected_transform_info_reports_the_graphic() {+ let (mut s, f) = rotated_frame_with_image();+ s.execute("transform.set", &json!({"rotation": 0})).unwrap();+ // What the Control bar and Properties read: the graphic's 0, not the frame's -45, so a+ // spinner step from it gives 1, not -44.+ let info = s.execute("transform.info", &json!({})).unwrap();+ assert!(info["rotation"].as_f64().unwrap().abs() < 1e-6, "{info}");+ let rot = info["rotation"].as_f64().unwrap() + 1.0;+ s.execute("transform.set", &json!({"rotation": rot})).unwrap();+ let after = s.execute("transform.info", &json!({"ids": [f]})).unwrap();+ assert!((after["content"]["rotation"].as_f64().unwrap() - 1.0).abs() < 1e-6, "{after}");+ assert!((after["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6, "the frame stays: {after}");+ // `id` names the target explicitly, like `ids`: the frame.+ let by_id = s.execute("transform.info", &json!({"id": f})).unwrap();+ assert!((by_id["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6, "{by_id}");+ }++ #[test]+ fn the_graphic_moves_to_x_and_y_from_the_rulers_zero_point() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let f = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();+ let png = designcraft_render::Rendered { width: 200, height: 100, pixels: vec![200u8; 200 * 100 * 4] }.to_png();+ s.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&png), "name": "a.png", "frame": f})).unwrap();+ s.execute("view.zeroPoint", &json!({"at": [72, 36]})).unwrap();+ s.execute("selection.set", &json!({"ids": [f], "content": true})).unwrap();+ s.execute("transform.set", &json!({"x": 10, "y": 20, "ref": 0})).unwrap();+ // The graphic's top-left, measured from the zero point (what the Transform fields show).+ let d = &s.doc().unwrap().doc;+ let id = designcraft_doc::ItemId(f);+ let loc = d.find(id).unwrap();+ let it = d.item(id).unwrap();+ let g = it.graphic().unwrap();+ let b = (d.parent_xf(&loc) * it.xf * g.xf).transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1));+ let o = d.ruler_origin(loc.spread, b.center().x).unwrap();+ assert!(o.x > 0.0 && o.y > 0.0, "the zero point moved: {o:?}");+ assert!((b.x0 - o.x - 10.0).abs() < 1e-6 && (b.y0 - o.y - 20.0).abs() < 1e-6, "{b:?} from {o:?}");+ // The frame stays.+ assert!((it.bounds().x0 - 100.0).abs() < 1e-6, "{:?}", it.bounds());+ }++ #[test]+ fn a_locked_frame_records_no_undo_step() {+ let (mut s, f) = rotated_frame_with_image();+ s.execute("object.lock", &json!({"ids": [f]})).unwrap();+ s.execute("selection.set", &json!({"ids": [f], "content": true})).unwrap();+ let undo = s.doc().unwrap().history.undo.len();+ assert_eq!(s.execute("transform.set", &json!({"rotation": 0})).unwrap()["changed"], 0);+ assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no empty undo step");+ }++ #[test]+ fn a_frame_selection_still_transforms_the_frame_and_an_empty_frame_has_no_content() {+ let (mut s, f) = rotated_frame_with_image();+ // `content: false` (or a frame selection) turns frame and image together.+ s.execute("transform.set", &json!({"rotation": 0, "content": false})).unwrap();+ let info = s.execute("transform.info", &json!({"ids": [f]})).unwrap();+ assert!(info["rotation"].as_f64().unwrap().abs() < 1e-6, "{info}");+ let e = s.execute("frame.create", &json!({"rect": [400, 100, 500, 200], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();+ assert!(s.execute("transform.set", &json!({"ids": [e], "content": true, "rotation": 10})).is_err());+ }+}++#[cfg(test)]+mod fit_text_frame_tests {+ use super::*;++ fn frame(s: &mut Session, rect: [f64; 4], text: &str) -> ItemId {+ let id = ItemId(s.execute("frame.create", &json!({"rect": rect, "content": "text", "text": text})).unwrap()["id"].as_u64().unwrap());+ s.execute("selection.set", &json!({"ids": [id.0]})).unwrap();+ s.execute("type.char", &json!({"attrs": {"size": 30}})).unwrap();+ id+ }++ fn bounds(s: &Session, id: ItemId) -> Rect {+ s.doc().unwrap().doc.item(id).unwrap().bounds()+ }++ #[test]+ fn fit_frame_to_content_fits_a_text_frame_to_its_text() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let id = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "INDESIGN");+ // The height only (a top or bottom handle): the width stays.+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ids": [id.0]})).unwrap();+ let h = bounds(&s, id);+ assert!(h.x1 == 500.0 && h.y0 == 100.0 && h.height() > 30.0 && h.height() < 45.0, "{h:?}");+ // Both (a corner handle, or the menu): around the line.+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "ids": [id.0]})).unwrap();+ let b = bounds(&s, id);+ assert!(b.x0 == 100.0 && b.width() > 100.0 && b.width() < 250.0, "{b:?}");+ let d = s.doc().unwrap().doc.clone();+ let sid = d.item(id).unwrap().text_frame().unwrap().story;+ assert!(!s.cache.get(&d, sid, None).is_overset(), "still fits");+ }++ #[test]+ fn fit_frame_to_content_grows_a_frame_with_overset_text() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let id = frame(&mut s, [100.0, 100.0, 300.0, 140.0], "one two three four five six seven eight nine ten eleven twelve");+ let d = s.doc().unwrap().doc.clone();+ let sid = d.item(id).unwrap().text_frame().unwrap().story;+ assert!(s.cache.get(&d, sid, None).is_overset());+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ids": [id.0]})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ assert!(!s.cache.get(&d, sid, None).is_overset(), "{:?}", bounds(&s, id));+ assert!(bounds(&s, id).height() > 100.0);+ assert!(s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "diagonal", "ids": [id.0]})).is_err());+ }++ #[test]+ fn fitting_text_keeps_columns_and_vertical_justification() {+ use designcraft_doc::VerticalJustification::{Bottom, Center, Justify, Top};+ for columns in [1, 2] {+ for justification in [Top, Bottom, Center, Justify] {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let id = frame(&mut s, [100.0, 100.0, 500.0, 500.0], "one two three four five six seven eight nine ten eleven twelve");+ let options = &mut Arc::make_mut(&mut s.doc_mut().unwrap().doc).item_mut(id).unwrap().text_frame_mut().unwrap().options;+ options.columns = columns;+ options.vertical_justification = justification;+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height"})).unwrap();+ let d = &s.doc().unwrap().doc;+ let it = d.item(id).unwrap();+ let tf = it.text_frame().unwrap();+ let composed = s.cache.get(d, tf.story, None);+ assert!(!composed.is_overset(), "{columns} {justification:?}");+ assert!(it.bounds().height() < 250.0, "{columns} {justification:?}: {:?}", it.bounds());+ assert_eq!(tf.options.vertical_justification, justification);+ assert_eq!(tf.options.columns, columns);+ if columns == 2 {+ let ft = composed.frame(id).unwrap();+ assert!(ft.lines.iter().any(|l| l.column == 1), "both columns stay in use: {ft:?}");+ }}- 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();+ }++ #[test]+ fn graphic_fitting_obeys_each_axis_and_locked_text_and_graphics_stay_put() {+ for graphic in [false, true] {+ for lock_layer in [false, true] {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let id = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "Fit me");+ if graphic {+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();+ s.execute("file.place", &json!({"base64": super::super::file::base64_encode(&png), "name": "test.png", "frame": id.0})).unwrap();+ let it = Arc::make_mut(&mut s.doc_mut().unwrap().doc).item_mut(id).unwrap();+ let Content::Graphic(g) = &mut it.content else { panic!("graphic") };+ g.xf = Affine::translate((80.0, 90.0)) * Affine::scale(3.0);+ let original = it.inner_bounds();+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ids": [id.0]})).unwrap();+ let fitted = s.doc().unwrap().doc.item(id).unwrap().inner_bounds();+ assert_eq!(fitted, Rect::new(80.0, original.y0, 200.0, original.y1));+ Arc::make_mut(&mut s.doc_mut().unwrap().doc).item_mut(id).unwrap().path = shapes::rectangle(original);+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ids": [id.0]})).unwrap();+ assert_eq!(s.doc().unwrap().doc.item(id).unwrap().inner_bounds(), Rect::new(original.x0, 90.0, original.x1, 150.0));+ Arc::make_mut(&mut s.doc_mut().unwrap().doc).item_mut(id).unwrap().path = shapes::rectangle(original);+ }+ let before = bounds(&s, id);+ if lock_layer {+ let layer = s.doc().unwrap().doc.item(id).unwrap().layer;+ Arc::make_mut(&mut s.doc_mut().unwrap().doc).layer_mut(layer).unwrap().locked = true;+ } else {+ Arc::make_mut(&mut s.doc_mut().unwrap().doc).item_mut(id).unwrap().locked = true;+ }+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "ids": [id.0]})).unwrap();+ assert_eq!(bounds(&s, id), before, "graphic={graphic}, layer={lock_layer}");+ }+ }+ }++ #[test]+ fn an_unfittable_frame_returns_an_error_without_changing_any_target() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let a = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "Fits");+ let b = frame(&mut s, [100.0, 400.0, 500.0, 600.0], "Cannot fit");+ Arc::make_mut(&mut s.doc_mut().unwrap().doc).item_mut(b).unwrap().text_frame_mut().unwrap().options.first_baseline_min = 30_000.0;+ let before = [bounds(&s, a), bounds(&s, b)];+ assert!(s.execute("object.fit", &json!({"mode": "fitFrameToContent", "ids": [a.0, b.0]})).is_err());+ assert_eq!([bounds(&s, a), bounds(&s, b)], before);+ }+}++#[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 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());+ }+ }diff --cc crates/tools/src/lib.rsindex 85f662843,4dad3be41..c1b9a285d--- a/crates/tools/src/lib.rs+++ b/crates/tools/src/lib.rs@@@ -361,14 -335,8 +361,16 @@@ pub enum CursorResizeNeSw,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,Text,Hand,HandGrab,diff --cc crates/tools/src/pen.rsindex e6a98c527,21e90f734..e7df8a958--- a/crates/tools/src/pen.rs+++ b/crates/tools/src/pen.rs@@@ -1,7 -1,7 +1,8 @@@//! Pen tool (P): click for corner points, drag for smooth points, click the first point to close,//! Enter/Esc (or switching tools) to finish an open path. Each anchor is its own undo step, as in-//! InDesign. Clicking an end point of an open path (the cursor shows it) continues that path from-//! there; dragging from it first reshapes its direction lines.+//! InDesign. Between paths, a click on a selected path's anchor deletes it and a click on its- //! outline adds an anchor; the cursor shows which.++//! outline adds an anchor; clicking an end point of an open path continues that path from there++//! (dragging from it first reshapes its direction lines). The cursor shows which.use designcraft_doc::{ItemId, SpreadRef};use designcraft_geom::{BezPath, Point};@@@ -28,40 -65,7 +68,45 @@@ fn anchor_json(a: &(Point, Point, Pointjson!({"p": [a.0.x, a.0.y], "in": [a.1.x, a.1.y], "out": [a.2.x, a.2.y]})}+/// What a pen click at the pointer does instead of placing an anchor.+#[derive(Debug, PartialEq)]+enum Hover {+ Place,+ /// Close the path being drawn (the pointer is on its first anchor).+ Close,+ /// Delete anchor (subpath, anchor) of a selected path.+ Delete(u64, usize, usize),+ /// Add an anchor on a selected path's outline.+ Add(ItemId),++ /// Continue subpath `.1` of open path `.0` from its last (`.2`) or first anchor.++ Continue(ItemId, usize, bool),+}+impl PenTool {+ /// What a click at canvas point `p` does.+ fn hover_at(&self, cx: &ToolContext, p: Point) -> Hover {+ if let Some(sr) = self.spread {+ if self.anchors.len() >= 2+ && let Some(first) = self.anchors.first()+ && (first.0 - cx.layout.to_spread(sr, p)).hypot() <= cx.tol(6.0)+ {+ return Hover::Close;+ }+ return Hover::Place;+ }+ if !self.anchors.is_empty() {+ return Hover::Place;+ }++ if let Some((id, si, at_end)) = endpoint_at(cx, p) {++ return Hover::Continue(id, si, at_end);++ }+ let ids = &cx.selection.items;+ if let Some((id, si, ai, None)) = anchor_at_in(cx, ids, p) {+ return Hover::Delete(id, si, ai);+ }+ segment_at(cx, ids, p).map_or(Hover::Place, Hover::Add)+ }+fn finish(&mut self) -> Vec<Action> {self.path = None;self.spread = None;@@@ -123,22 -159,29 +200,29 @@@ impl Tool for PenToolvec![]}PointerKind::Down => {- // Close on the first anchor.- if self.anchors.len() >= 2- && let Some(first) = self.anchors.first()- && (first.0 - sp).hypot() <= cx.tol(6.0)- {- let out = match self.path {- Some(id) => {- let mut p = json!({"id": id});- if let Some(si) = self.subpath {- p["subpath"] = json!(si);+ match self.hover_at(cx, ev.pos) {+ Hover::Close => {+ let out = match self.path {- Some(id) => vec![Action::Exec("path.close".into(), json!({"id": id}))],++ Some(id) => {++ let mut p = json!({"id": id});++ if let Some(si) = self.subpath {++ p["subpath"] = json!(si);++ }++ vec![Action::Exec("path.close".into(), p)]+ }- vec![Action::Exec("path.close".into(), p)]- }- None => vec![],- };- self.finish();- return out;- }- // On an open path's end point: continue that path.- if self.anchors.is_empty()- && let Some((id, si, at_end)) = endpoint_at(cx, ev.pos)- {- return self.continue_from(cx, id, si, at_end);+ None => vec![],+ };+ self.finish();+ return out;+ }++ Hover::Continue(id, si, at_end) => return self.continue_from(cx, id, si, at_end),+ Hover::Delete(id, si, ai) => {+ return vec![Action::Exec("path.deleteAnchor".into(), json!({"id": id, "subpath": si, "anchor": ai}))];+ }+ Hover::Add(id) => {+ return vec![Action::Exec("path.addAnchor".into(), json!({"id": id.0, "at": [sp.x, sp.y], "tolerance": cx.tol(5.0)}))];+ }+ Hover::Place => {}}let p = self.snap_click(cx, snap_spread, sp, ev.mods.shift);if self.anchors.is_empty() {@@@ -207,12 -262,7 +303,13 @@@}fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor {- if self.anchors.is_empty() && endpoint_at(cx, p).is_some() { Cursor::PenContinue } else { Cursor::Pen }+ match self.hover_at(cx, p) {+ Hover::Place => Cursor::Pen,+ Hover::Close => Cursor::PenClose,++ Hover::Continue(..) => Cursor::PenContinue,+ Hover::Delete(..) => Cursor::PenDelete,+ Hover::Add(_) => Cursor::PenAdd,+ }}fn busy(&self) -> bool {diff --cc crates/tools/src/tests.rsindex 41ec201a0,f8f58c7d3..a181a0e6b--- a/crates/tools/src/tests.rs+++ b/crates/tools/src/tests.rs@@@ -752,771 -706,61 +752,830 @@@ 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 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);+ }diff --cc crates/ui-egui/src/cursors.rsindex 4c7195618,000000000..c7dcd75abmode 100644,000000..100644--- a/crates/ui-egui/src/cursors.rs+++ b/crates/ui-egui/src/cursors.rs@@@ -1,371 -1,0 +1,383 @@@+//! 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 => C::Crosshair,++ Cursor::Pen | Cursor::PenAdd | Cursor::PenDelete | Cursor::PenClose | Cursor::PenConvert | Cursor::PenContinue => C::Crosshair,+ 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; 8] =- [Cursor::Arrow, Cursor::ArrowHollow, Cursor::Pen, Cursor::PenAdd, Cursor::PenDelete, Cursor::PenClose, Cursor::PenConvert, Cursor::Rotate];++ 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());+ }+}diff --cc crates/ui-egui/src/i18n.rsindex 4e5f0b25f,39b31ca0c..d2495d19c--- a/crates/ui-egui/src/i18n.rs+++ b/crates/ui-egui/src/i18n.rs@@@ -61,10 -55,8 +61,12 @@@ const TABLE: &[(&str, [&str; 5])] = &("Cut", ["Ausschneiden", "Couper", "Cortar", "カット", "剪切"]),("Copy", ["Kopieren", "Copier", "Copiar", "コピー", "复制"]),("Paste", ["Einfügen", "Coller", "Pegar", "ペースト", "粘贴"]),+ (+ "Paste Vector Art",+ ["Vektorgrafik einfügen", "Coller l’illustration vectorielle", "Pegar ilustración vectorial", "ベクトルアートをペースト", "粘贴矢量图稿"],+ ),+ ("Reverse Path", ["Pfadrichtung umkehren", "Inverser le tracé", "Invertir trazado", "パスの方向反転", "反转路径"]),+ ("Set Anchor", ["Ankerpunkt festlegen", "Définir le point d’ancrage", "Definir punto de ancla", "アンカーポイントを設定", "设置锚点"]),("Clear", ["Löschen", "Effacer", "Borrar", "消去", "清除"]),("Duplicate", ["Duplizieren", "Dupliquer", "Duplicar", "複製", "重复"]),("Select All", ["Alles auswählen", "Tout sélectionner", "Seleccionar todo", "すべてを選択", "全选"]),diff --cc crates/ui-egui/src/i18n/ar.rsindex 91eeb287a,d02370d52..83940f39f--- a/crates/ui-egui/src/i18n/ar.rs+++ b/crates/ui-egui/src/i18n/ar.rs@@@ -30,7 -30,8 +30,9 @@@ pub(super) const TABLE: &[(&str, &str)("Cut", "قص"),("Copy", "نسخ"),("Paste", "لصق"),+ ("Paste Vector Art", "لصق رسم متجه"),+ ("Reverse Path", "عكس المسار"),+ ("Set Anchor", "تعيين نقطة الارتساء"),("Clear", "مسح"),("Delete", "حذف"),("Duplicate", "تكرار"),diff --cc crates/ui-egui/src/i18n/it.rsindex a97fab40f,e61d461a0..0e69ad41c--- a/crates/ui-egui/src/i18n/it.rs+++ b/crates/ui-egui/src/i18n/it.rs@@@ -28,7 -28,8 +28,9 @@@ pub(super) const TABLE: &[(&str, &str)("Cut", "Taglia"),("Copy", "Copia"),("Paste", "Incolla"),+ ("Paste Vector Art", "Incolla grafica vettoriale"),+ ("Reverse Path", "Inverti tracciato"),+ ("Set Anchor", "Imposta ancoraggio"),("Clear", "Cancella"),("Duplicate", "Duplica"),("Select All", "Seleziona tutto"),diff --cc crates/ui-egui/src/i18n/ja.rsindex b67aeafaa,7dd06af9c..f56c4d319--- a/crates/ui-egui/src/i18n/ja.rs+++ b/crates/ui-egui/src/i18n/ja.rs@@@ -30,7 -30,8 +30,9 @@@ pub(super) const TABLE: &[(&str, &str)("Cut", "カット"),("Copy", "コピー"),("Paste", "ペースト"),+ ("Paste Vector Art", "ベクトルアートをペースト"),+ ("Reverse Path", "パスの方向反転"),+ ("Set Anchor", "アンカーポイントを設定"),("Clear", "消去"),("Duplicate", "複製"),("Select All", "すべてを選択"),diff --cc crates/ui-egui/src/i18n/pt_br.rsindex 2634d7368,ea7f5291c..0d8c83768--- a/crates/ui-egui/src/i18n/pt_br.rs+++ b/crates/ui-egui/src/i18n/pt_br.rs@@@ -31,7 -31,8 +31,9 @@@ pub(super) const TABLE: &[(&str, &str)("Cut", "Recortar"),("Copy", "Copiar"),("Paste", "Colar"),+ ("Paste Vector Art", "Colar arte vetorial"),+ ("Reverse Path", "Inverter demarcador"),+ ("Set Anchor", "Definir ponto de ancoragem"),("Clear", "Limpar"),("Delete", "Excluir"),("Duplicate", "Duplicar"),diff --cc crates/ui-egui/src/i18n/uk.rsindex ecd8b7999,96bd9bb3e..f08a20bf7--- a/crates/ui-egui/src/i18n/uk.rs+++ b/crates/ui-egui/src/i18n/uk.rs@@@ -29,7 -31,8 +29,9 @@@ pub(super) const TABLE: &[(&str, &str)("Cut", "Вирізати"),("Copy", "Копіювати"),("Paste", "Вставити"),+ ("Paste Vector Art", "Вставити векторну графіку"),+ ("Reverse Path", "Розвернути контур"),+ ("Set Anchor", "Задати прив’язку"),("Clear", "Очистити"),("Duplicate", "Дублювати"),("Select All", "Виділити все"),