Skip to content

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

Merge upstream main d07cbbe9

aiongg3acd29bef2d6
diff --cc crates/tools/src/lib.rs
index 0fd5cf51c,2542767ab..19e21a682
--- a/crates/tools/src/lib.rs
+++ b/crates/tools/src/lib.rs
@@@ -335,14 -371,10 +371,18 @@@ pub enum Cursor
ResizeNeSw,
Rotate,
Pen,
+ /// The pen over a segment of a selected path: a click adds an anchor there.
+ PenAdd,
+ /// The pen over an anchor of a selected path: a click deletes it.
+ PenDelete,
+ /// The pen over the first anchor of the path it is drawing: a click closes it.
+ PenClose,
+ /// Convert Direction Point.
+ PenConvert,
+ /// The Pen over an open path's end point: a click continues the path.
+ PenContinue,
+ /// Over a type-on-a-path bracket: dragging it moves where the text starts or ends.
+ PathBracket,
Text,
Hand,
HandGrab,
diff --cc crates/tools/src/pen.rs
index 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, Point
json!({"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 PenTool
vec![]
}
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.rs
index 9c5f6bb0a,6f8493dc4..1b656b3ae
--- a/crates/tools/src/tests.rs
+++ b/crates/tools/src/tests.rs
@@@ -706,52 -714,456 +714,506 @@@ fn pen_click_snaps_to_a_guide()
assert!((x - 100.0).abs() < 1e-6, "anchor x {x}");
}
+#[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 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());
+ }
+
+ #[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}))]);
+ }
diff --cc crates/ui-egui/src/canvas.rs
index d8888885f,9c39f0c39..835147716
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@@ -337,8 -353,37 +353,38 @@@ pub fn show(app: &mut DesignApp, ui: &m
} else {
app.session.cursor(xf.to_canvas(p), ui.input(|i| mods(i, false)), app.view_info())
};
- ui.ctx().set_cursor_icon(cursor_icon(c));
+ let icon = crate::cursors::show(ui.ctx(), &mut app.cursors, c, p);
+ ui.ctx().set_cursor_icon(icon);
+ draw_cursor_badge(&painter, p, c, &t);
+ }
+ }
+
+ /// The loaded text cursor's badge beside the system cursor: lines of text, a closed chain
+ /// (a click threads) or a broken one (a click unthreads). Drawn in code.
+ fn draw_cursor_badge(painter: &egui::Painter, p: Pos2, c: Cursor, t: &Tokens) {
+ if !matches!(c, Cursor::LoadedText | Cursor::ThreadLink | Cursor::Unthread) {
+ return;
+ }
+ let r = Rect::from_min_size(p + vec2(12.0, 12.0), vec2(20.0, 16.0));
+ painter.rect_filled(r, 3.0, t.measure_bg);
+ let ink = Stroke::new(1.5, t.measure_text);
+ let c0 = r.center();
+ match c {
+ Cursor::LoadedText => {
+ for (dy, w) in [(-4.0, 12.0), (0.0, 12.0), (4.0, 8.0)] {
+ painter.line_segment([pos2(c0.x - 6.0, c0.y + dy), pos2(c0.x - 6.0 + w, c0.y + dy)], ink);
+ }
+ }
+ _ => {
+ let gap = if c == Cursor::Unthread { 2.5 } else { -2.0 };
+ for side in [-1.0, 1.0] {
+ let link = Rect::from_center_size(pos2(c0.x + side * (3.5 + gap / 2.0), c0.y), vec2(9.0, 6.0));
+ painter.rect_stroke(link, 3.0, ink, StrokeKind::Middle);
+ }
+ if c == Cursor::Unthread {
+ painter.line_segment([pos2(c0.x + 2.0, c0.y - 6.0), pos2(c0.x - 2.0, c0.y + 6.0)], ink);
+ }
+ }
}
}
@@@ -1776,33 -2145,86 +2120,113 @@@ mod tests
}
}
+ /// A text frame holding `text`, the Type tool, and a harness stepping at 60 fps (clicks in a
+ /// row must land within the double-click delay).
+ fn typing(text: &str) -> (Harness<'static, DesignApp>, u64) {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let r = app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "text": text})).unwrap();
+ let id = r["id"].as_u64().unwrap();
+ app.run("tool.select", json!({"tool": "type"})).unwrap();
+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
+ |ui, app: &mut DesignApp| {
+ let ctx = ui.ctx().clone();
+ app.logic(&ctx);
+ app.ui(ui);
+ },
+ app,
+ );
+ h.run_steps(4);
+ (h, id)
+ }
+
+ /// The screen point over the first line of frame `id` where a click puts the caret at a byte
+ /// in `bytes`.
+ fn screen_at(h: &mut Harness<'_, DesignApp>, id: u64, bytes: std::ops::Range<usize>) -> Pos2 {
+ let mut x = 74.0;
+ let p = loop {
+ assert!(x < 400.0, "no point on the first line hits {bytes:?}");
+ h.state_mut().run("text.placeCaret", json!({"frame": id, "point": [x, 80.0]})).unwrap();
+ if h.state().session.doc().unwrap().selection.text.is_some_and(|t| bytes.contains(&t.focus)) {
+ break Point::new(x, 80.0);
+ }
+ x += 1.0;
+ };
+ h.state_mut().run("edit.deselectAll", json!({})).unwrap();
+ let app = h.state();
+ let c = app.session.layout().to_canvas(SpreadRef::Doc(0), p);
+ Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(c)
+ }
+
+ fn click(h: &mut Harness<'_, DesignApp>, p: Pos2) {
+ for pressed in [true, false] {
+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
+ h.step();
+ }
+ }
+
+ fn selected(h: &Harness<'_, DesignApp>) -> std::ops::Range<usize> {
+ h.state().session.doc().unwrap().selection.text.map(|t| t.range()).unwrap_or_default()
+ }
+
+ #[test]
+ fn clicks_in_a_row_select_word_line_paragraph_with_return_and_story() {
+ let text = "One two. Three four! Five six.\nSecond para here.";
+ let (mut h, id) = typing(text);
+ // Inside "Three": double-click selects the word, then line and paragraph with return.
+ let p = screen_at(&mut h, id, 10..14);
+ h.hover_at(p);
+ h.step();
+ let mut got = vec![];
+ for _ in 0..5 {
+ click(&mut h, p);
+ let r = selected(&h);
+ got.push(text[r].to_string());
+ }
+ assert_eq!(got[1..], ["Three", "One two. Three four! Five six.", "One two. Three four! Five six.\n", text], "{got:?}");
+ assert!(got[0].is_empty(), "one click places the caret: {got:?}");
+ }
+
+ #[test]
+ fn slow_clicks_do_not_add_up() {
+ let (mut h, id) = typing("One two. Three four!");
+ let p = screen_at(&mut h, id, 10..14);
+ h.hover_at(p);
+ h.step();
+ for _ in 0..3 {
+ click(&mut h, p);
+ h.run_steps(30);
+ }
+ assert!(selected(&h).is_empty(), "three clicks half a second apart leave a caret: {:?}", selected(&h));
+ }
+
+ #[test]
+ fn tools_show_their_own_cursors_over_the_page() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let mut h = harness(app);
+ let p = h.state().canvas_rect.unwrap().center();
+ let mut shown = |tool: &str| {
+ h.state_mut().run("tool.select", json!({"tool": tool})).unwrap();
+ h.hover_at(p);
+ h.run_steps(2);
+ let out = &h.output().platform_output;
+ (out.cursor_icon, out.cursor_image.clone())
+ };
+ let (pen, direct, text) = (shown("pen"), shown("directSelection"), shown("type"));
+ let ppp = h.ctx.pixels_per_point();
+ let images = &mut h.state_mut().cursors;
+ match crate::cursors::MODE {
+ crate::cursors::Mode::Os => {
+ assert_eq!(pen.1, images.get(Cursor::Pen, ppp), "Pen");
+ assert_eq!(direct.1, images.get(Cursor::ArrowHollow, ppp), "Direct Selection");
+ assert_eq!(text, (egui::CursorIcon::Text, None), "the I-beam stays a system cursor");
+ }
+ crate::cursors::Mode::Painted => assert_eq!((pen.0, direct.0), (egui::CursorIcon::None, egui::CursorIcon::None)),
+ crate::cursors::Mode::System => assert_eq!(pen, (egui::CursorIcon::Crosshair, None)),
+ }
+ }
+
#[test]
fn rulers_open_no_units_menu_without_a_document() {
let mut h = harness(DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()));
diff --cc crates/ui-egui/src/cursors.rs
index f3cbf95ed,000000000..9960e2792
mode 100644,000000..100644
--- a/crates/ui-egui/src/cursors.rs
+++ b/crates/ui-egui/src/cursors.rs
@@@ -1,369 -1,0 +1,384 @@@
+//! Tool cursors drawn in code: black glyphs with a white halo, so they read on any page colour.
+//! The Selection tool's filled arrow, Direct Selection's hollow arrow, the pen nib with a badge for
+//! what a click does (add, delete, close, convert), and a curved double arrow for rotating.
+//! Cursors without a glyph stay system cursors.
+//!
+//! Linux and Windows show the glyphs as OS cursors ([`Images`]): the system moves them itself, so
+//! they never trail the pointer. macOS sizes a cursor bitmap in points (a Retina one would show
+//! twice as big, or blurred), so there the canvas paints the glyph at the pointer. The
+//! web build keeps the system cursors.
+
+use egui::epaint::{Mesh, TessellationOptions, Tessellator, Vertex};
+use egui::{Color32, CustomCursorImage, Pos2, Shape, Stroke, Vec2, pos2, vec2};
+
+use designcraft_tools::Cursor;
+
+const INK: Color32 = Color32::BLACK;
+const HALO: Color32 = Color32::WHITE;
+
+/// How the window shows a cursor glyph.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Mode {
+ /// As an OS cursor bitmap ([`Images`]).
+ Os,
+ /// Painted into the window at the pointer, the OS cursor hidden.
+ Painted,
+ /// Not at all: the system cursor stands in.
+ System,
+}
+
+pub const MODE: Mode = if cfg!(target_arch = "wasm32") {
+ Mode::System
+} else if cfg!(target_os = "macos") {
+ Mode::Painted
+} else {
+ Mode::Os
+};
+
+/// The shapes of one glyph: every halo goes under all the ink, so one part's halo never cuts
+/// through another part's ink.
+#[derive(Default)]
+struct Ink {
+ halo: Vec<Shape>,
+ ink: Vec<Shape>,
+}
+
+impl Ink {
+ fn halo(&mut self, s: Shape) {
+ self.halo.push(s);
+ }
+
+ fn add(&mut self, s: Shape) {
+ self.ink.push(s);
+ }
+
+ /// A filled outline with a halo around it.
+ fn poly(&mut self, pts: Vec<Pos2>, fill: Color32) {
+ self.halo(Shape::closed_line(pts.clone(), Stroke::new(3.0, HALO)));
+ self.add(Shape::convex_polygon(pts.clone(), fill, Stroke::NONE));
+ self.add(Shape::closed_line(pts, Stroke::new(1.0, INK)));
+ }
+
+ /// A haloed stroke.
+ fn line(&mut self, a: Pos2, b: Pos2) {
+ self.halo(Shape::line_segment([a, b], Stroke::new(3.0, HALO)));
+ self.add(Shape::line_segment([a, b], Stroke::new(1.2, INK)));
+ }
+
+ fn into_shapes(self) -> Vec<Shape> {
+ let mut out = self.halo;
+ out.extend(self.ink);
+ out
+ }
+}
+
+fn at(o: Pos2, pts: &[(f32, f32)]) -> Vec<Pos2> {
+ pts.iter().map(|&(x, y)| o + vec2(x, y)).collect()
+}
+
+/// The pointer arrow, tip at `o`: ink-filled (Selection) or hollow (Direct Selection).
+fn arrow(ink: &mut Ink, o: Pos2, hollow: bool) {
+ let pts = at(o, &[(0.0, 0.0), (0.0, 15.0), (3.8, 11.4), (6.4, 17.0), (8.6, 16.0), (6.1, 10.6), (11.0, 10.6)]);
+ ink.halo(Shape::closed_line(pts.clone(), Stroke::new(3.0, HALO)));
+ // The arrow is concave: fill it as two convex parts, then outline it.
+ let fill = if hollow { HALO } else { INK };
+ let part = |idx: &[usize]| idx.iter().filter_map(|&i| pts.get(i).copied()).collect::<Vec<_>>();
+ ink.add(Shape::convex_polygon(part(&[0, 1, 2, 5, 6]), fill, Stroke::NONE));
+ ink.add(Shape::convex_polygon(part(&[2, 3, 4, 5]), fill, Stroke::NONE));
+ ink.add(Shape::closed_line(pts, Stroke::new(1.0, INK)));
+}
+
+/// What the pen badge says a click does.
+#[derive(Clone, Copy)]
+enum Badge {
+ None,
+ Add,
+ Delete,
+ Close,
+ Convert,
++ Continue,
+}
+
+/// The pen nib, tip at `o` (top left), with a badge below right.
+fn pen(ink: &mut Ink, o: Pos2, badge: Badge) {
+ ink.poly(at(o, &[(0.0, 0.0), (4.0, 12.0), (8.0, 16.0), (16.0, 8.0), (12.0, 4.0)]), INK);
+ // The nib's slit and breather hole.
+ ink.add(Shape::line_segment([o + vec2(1.0, 1.0), o + vec2(5.5, 5.5)], Stroke::new(1.0, HALO)));
+ ink.add(Shape::circle_filled(o + vec2(6.5, 6.5), 1.4, HALO));
+ ink.line(o + vec2(10.0, 14.0), o + vec2(14.0, 18.0));
+ let b = o + vec2(16.0, 14.0);
+ match badge {
+ Badge::None => {}
+ Badge::Add => {
+ ink.line(b + vec2(0.0, 3.0), b + vec2(6.0, 3.0));
+ ink.line(b + vec2(3.0, 0.0), b + vec2(3.0, 6.0));
+ }
+ Badge::Delete => ink.line(b + vec2(0.0, 3.0), b + vec2(6.0, 3.0)),
+ Badge::Close => {
+ ink.halo(Shape::circle_stroke(b + vec2(3.0, 3.0), 3.0, Stroke::new(3.0, HALO)));
+ ink.add(Shape::circle_stroke(b + vec2(3.0, 3.0), 3.0, Stroke::new(1.2, INK)));
+ }
+ Badge::Convert => {
+ ink.line(b + vec2(0.0, 6.0), b + vec2(3.0, 0.0));
+ ink.line(b + vec2(3.0, 0.0), b + vec2(6.0, 6.0));
+ }
++ Badge::Continue => ink.line(b + vec2(1.0, 6.0), b + vec2(5.0, 0.0)),
+ }
+}
+
+/// A curved double arrow over the hotspot: an arc bowing up, an arrowhead at each end pointing on
+/// along the arc.
+fn rotate(ink: &mut Ink, o: Pos2) {
+ const R: f32 = 8.0;
+ let (a0, a1) = (std::f32::consts::PI * 0.12, std::f32::consts::PI * 0.88);
+ let on = |a: f32| o + vec2(a.cos() * R, -a.sin() * R);
+ let pts: Vec<Pos2> = (0..=12).map(|i| on(a0 + (a1 - a0) * i as f32 / 12.0)).collect();
+ ink.halo(Shape::line(pts.clone(), Stroke::new(3.2, HALO)));
+ ink.add(Shape::line(pts, Stroke::new(1.3, INK)));
+ for (a, away) in [(a0, -1.0f32), (a1, 1.0)] {
+ let t = vec2(-a.sin(), -a.cos()) * away;
+ let n = vec2(-t.y, t.x);
+ let (end, tip) = (on(a) - t * 1.5, on(a) + t * 4.5);
+ ink.poly(vec![tip, end + n * 1.8, end - n * 1.8], INK);
+ }
+}
+
+/// The shapes of cursor `c` with its hotspot at `p`, in points; `None` for system cursors.
+fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> {
+ let mut ink = Ink::default();
+ match c {
+ Cursor::Arrow => arrow(&mut ink, p, false),
+ Cursor::ArrowHollow => arrow(&mut ink, p, true),
+ Cursor::Pen => pen(&mut ink, p, Badge::None),
+ Cursor::PenAdd => pen(&mut ink, p, Badge::Add),
+ Cursor::PenDelete => pen(&mut ink, p, Badge::Delete),
+ Cursor::PenClose => pen(&mut ink, p, Badge::Close),
+ Cursor::PenConvert => pen(&mut ink, p, Badge::Convert),
++ Cursor::PenContinue => pen(&mut ink, p, Badge::Continue),
+ Cursor::Rotate => rotate(&mut ink, p),
+ _ => return None,
+ }
+ Some(ink.into_shapes())
+}
+
+/// The cursor bitmaps handed to the OS, by (cursor, pixels per point). Each glyph is rasterized
+/// once; handing the same `Arc` every frame lets the integration keep its OS cursor.
+#[derive(Default)]
+pub struct Images(Vec<(Cursor, f32, CustomCursorImage)>);
+
+impl Images {
+ /// Cursor `c` for `ppp` physical pixels per point; `None` for cursors without a glyph.
+ pub fn get(&mut self, c: Cursor, ppp: f32) -> Option<CustomCursorImage> {
+ if let Some((.., image)) = self.0.iter().find(|(k, s, _)| *k == c && *s == ppp) {
+ return Some(image.clone());
+ }
+ let image = rasterize(c, ppp)?;
+ // A few glyphs at the scales of the displays the window visited.
+ if self.0.len() >= 128 {
+ self.0.clear();
+ }
+ self.0.push((c, ppp, image.clone()));
+ Some(image)
+ }
+}
+
+/// The largest side of a cursor bitmap, in pixels (the glyphs span under 30 points).
+const MAX_SIDE: f32 = 256.0;
+
+/// Cursor `c` as a straight-alpha RGBA bitmap at `ppp` pixels per point, tessellated
+/// (anti-aliased) as egui would paint it, the hotspot on a pixel corner.
+pub(crate) fn rasterize(c: Cursor, ppp: f32) -> Option<CustomCursorImage> {
+ if !(ppp.is_finite() && ppp > 0.0) {
+ return None;
+ }
+ let shapes = glyph(c, Pos2::ZERO)?;
+ let mut tessellator = Tessellator::new(ppp, TessellationOptions::default(), [1, 1], vec![]);
+ let mut mesh = Mesh::default();
+ for shape in shapes {
+ tessellator.tessellate_shape(shape, &mut mesh);
+ }
+ let bounds = mesh.calc_bounds();
+ // The hotspot must lie inside the bitmap.
+ let min = (bounds.min.to_vec2() * ppp).floor().min(Vec2::ZERO);
+ let max = (bounds.max.to_vec2() * ppp).ceil().max(Vec2::splat(1.0));
+ let size = max - min;
+ if !(size.x <= MAX_SIDE && size.y <= MAX_SIDE) {
+ return None;
+ }
+ let (w, h) = (size.x as usize, size.y as usize);
+ let mut px = vec![[0.0; 4]; w * h];
+ let corner = |v: &Vertex| (v.pos.to_vec2() * ppp - min, v.color);
+ for &[i, j, k] in mesh.indices.as_chunks::<3>().0 {
+ if let (Some(a), Some(b), Some(c)) = (mesh.vertices.get(i as usize), mesh.vertices.get(j as usize), mesh.vertices.get(k as usize)) {
+ fill_triangle(&mut px, w, [corner(a), corner(b), corner(c)]);
+ }
+ }
+ let rgba: Vec<u8> = px
+ .iter()
+ .flat_map(|&[r, g, b, a]| {
+ let k = if a > 0.0 { 1.0 / a } else { 0.0 };
+ [r * k, g * k, b * k, a].map(|x| (x * 255.0).round().clamp(0.0, 255.0) as u8)
+ })
+ .collect();
+ Some(CustomCursorImage { rgba: rgba.into(), size: [w as u16, h as u16], hotspot: [-min.x as u16, -min.y as u16] })
+}
+
+/// Blend triangle `t` (pixel positions and premultiplied colours, interpolated across it) over `px`
+/// (premultiplied RGBA, `w` pixels a row) at the pixel centres it covers, as the GPU blends egui's
+/// meshes. A centre on an edge goes to one of the two triangles sharing it, so seams aren't doubled.
+fn fill_triangle(px: &mut [[f32; 4]], w: usize, t: [(Vec2, Color32); 3]) {
+ let edge = |a: Vec2, b: Vec2, p: Vec2| (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
+ let [a, mut b, mut c] = t;
+ let mut area = edge(a.0, b.0, c.0);
+ if area < 0.0 {
+ std::mem::swap(&mut b, &mut c);
+ area = -area;
+ }
+ if area.is_nan() || area <= 1e-6 || w == 0 {
+ return;
+ }
+ // Of the two triangles sharing an edge (walking it in opposite directions), one owns it.
+ let owns = |u: Vec2, v: Vec2| v.y > u.y || (v.y == u.y && v.x > u.x);
+ let h = px.len() / w;
+ let lo = a.0.min(b.0).min(c.0).max(Vec2::ZERO);
+ let hi = a.0.max(b.0).max(c.0).min(vec2(w as f32, h as f32));
+ for y in lo.y.floor() as usize..hi.y.ceil() as usize {
+ for x in lo.x.floor() as usize..hi.x.ceil() as usize {
+ let p = pos2(x as f32 + 0.5, y as f32 + 0.5).to_vec2();
+ let weights = [(b.0, c.0), (c.0, a.0), (a.0, b.0)].map(|(u, v)| (edge(u, v, p), owns(u, v)));
+ if !weights.iter().all(|&(e, own)| e > 0.0 || (e == 0.0 && own)) {
+ continue;
+ }
+ let Some(dst) = px.get_mut(y * w + x) else { continue };
+ let [wa, wb, wc] = weights.map(|(e, _)| e / area);
+ let src: [f32; 4] = std::array::from_fn(|i| {
+ let channel = |col: Color32| f32::from(col.to_array()[i]);
+ (wa * channel(a.1) + wb * channel(b.1) + wc * channel(c.1)) / 255.0
+ });
+ let keep = 1.0 - src[3];
+ *dst = std::array::from_fn(|i| src[i] + dst[i] * keep);
+ }
+ }
+}
+
+/// The system cursor for `c`: shown where the window has no glyph for it, or no bitmap cursors.
+pub fn system(c: Cursor) -> egui::CursorIcon {
+ use egui::CursorIcon as C;
+ match c {
+ Cursor::Arrow | Cursor::ArrowHollow => C::Default,
+ Cursor::Move => C::Move,
+ Cursor::Crosshair => C::Crosshair,
+ Cursor::ResizeH => C::ResizeHorizontal,
+ Cursor::ResizeV => C::ResizeVertical,
+ Cursor::ResizeNwSe => C::ResizeNwSe,
+ Cursor::ResizeNeSw => C::ResizeNeSw,
+ Cursor::Rotate => C::Alias,
- Cursor::Pen | Cursor::PenAdd | Cursor::PenDelete | Cursor::PenClose | Cursor::PenConvert => C::Crosshair,
++ Cursor::Pen | Cursor::PenAdd | Cursor::PenDelete | Cursor::PenClose | Cursor::PenConvert | Cursor::PenContinue => C::Crosshair,
++ Cursor::PathBracket => C::ResizeColumn,
+ Cursor::Text => C::Text,
+ Cursor::Hand => C::Grab,
+ Cursor::HandGrab => C::Grabbing,
+ Cursor::ZoomIn => C::ZoomIn,
+ Cursor::ZoomOut => C::ZoomOut,
+ Cursor::Eyedropper => C::Crosshair,
+ Cursor::LoadedText | Cursor::LoadedGraphic => C::Copy,
++ Cursor::ThreadLink => C::Alias,
++ Cursor::Unthread => C::NoDrop,
+ Cursor::NotAllowed => C::NotAllowed,
+ }
+}
+
+/// Show cursor `c` with the pointer at `hover` (screen points): set the OS cursor bitmap or paint
+/// the glyph per [`MODE`], and return the cursor icon to set.
+pub fn show(ctx: &egui::Context, images: &mut Images, c: Cursor, hover: Pos2) -> egui::CursorIcon {
+ match MODE {
+ Mode::Os => {
+ // The glyphs keep the system cursors' size whatever the interface scale.
+ let ppp = ctx.pixels_per_point() / ctx.zoom_factor().max(0.01);
+ ctx.set_cursor_image(images.get(c, ppp));
+ system(c)
+ }
+ Mode::Painted => {
+ let layer = egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("tool-cursor"));
+ // Divide by the zoom factor so the glyph keeps its size in physical pixels.
+ let scale = 1.0 / ctx.zoom_factor().max(0.01);
+ let painter = ctx.layer_painter(layer);
+ match glyph(c, Pos2::ZERO) {
+ Some(shapes) => {
+ let place = egui::emath::TSTransform::new(hover.to_vec2(), scale);
+ painter.extend(shapes.into_iter().map(|mut s| {
+ s.transform(place);
+ s
+ }));
+ egui::CursorIcon::None
+ }
+ None => system(c),
+ }
+ }
+ Mode::System => system(c),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Every cursor with a glyph.
- const GLYPHS: [Cursor; 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/lib.rs
index 824cbf527,4b5c63f98..3d890f14a
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -511,8 -529,27 +530,29 @@@ pub struct DesignApp
last_time: f64,
/// When recovery data was last written (seconds, egui time).
pub last_recovery: f64,
+ /// The tool cursor bitmaps handed to the OS.
+ pub cursors: cursors::Images,
+ /// The egui context (set by the first frame): copied text goes to the system clipboard through it.
+ egui_ctx: Option<egui::Context>,
+ /// A control-channel request is being handled: commands it runs never read or write the
+ /// user's system clipboard (a control client must not see or replace it).
+ pub(crate) in_control: bool,
+ /// The system clipboard's text that stands for the last object copy: what that copy put there
+ /// (no native menu: without it the paste keys produce no paste event), or what it held then
+ /// (native menu). It is never pasted as text: Paste with it pastes the copied objects.
+ object_clip_text: Option<String>,
+ /// Quit was chosen: close the window on the next frame, as its close button does.
+ quit_requested: bool,
+ /// Close the window without asking about unsaved changes (the control channel's `app.quit`).
+ pub(crate) quit_without_asking: bool,
+ /// No document is discarded until every unsaved document has an up-to-date approval.
+ quitting: Option<QuitState>,
+ }
+
+ struct QuitState {
+ original_active: Option<u64>,
+ accepted: HashMap<u64, u64>,
+ pending: Option<u64>,
}
impl DesignApp {
@@@ -550,7 -590,12 +593,13 @@@
native_shortcuts: Default::default(),
last_time: 0.0,
last_recovery: 0.0,
+ cursors: cursors::Images::default(),
+ egui_ctx: None,
+ in_control: false,
+ object_clip_text: None,
+ quit_requested: false,
+ quit_without_asking: false,
+ quitting: None,
}
}