DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Threading: load text from a port and click to thread
aiongg786129723795
diff --git a/ROADMAP.md b/ROADMAP.mdindex ec17b7119..6da50141b 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -29,6 +29,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope- Crash recovery: unsaved documents are written to the recovery folder every 30 s and reopened (unsaved, remembering their files) after a crash; File › Revert and Save a Copy…; `file.recovery.*`, `file.revert`, `file.saveACopy`.- Edit › Paste Into (copied objects become a frame's content, clipped by it; rendered, PDF and IDML both ways — verified in InDesign 2026); Polygon Settings (sides, star inset; double-click the Polygon tool).- Color panel (fill/stroke proxy, CMYK/RGB/Lab sliders with channel ramps, tint slider for swatches, spectrum ramp, Add to Swatches) and Color Picker (double-click the proxy); mixed colours are unnamed (not listed in Swatches until added); `object.color`, `swatch.addToSwatches`, `swatch.addUnnamed`.+- Threading: click a selected text frame's in or out port (overset or not) to load the text cursor, then click a frame to thread it (stories merge), click empty space for a column-wide frame down to the bottom margin, or drag a frame; Shift-click autoflows, Alt-click stays loaded; click the linked frame or double-click a port to break the thread; Esc unloads. Link and unthread cursors show where a click threads or unthreads. `text.thread`, `text.unthread`, `text.removeFromThread`.- Place text files: Word (.docx: styles by name with their attributes, bold/italic/underline/size/font, footnotes, tables, tabs, breaks), RTF and plain text, into the insertion point, the selected frame or a new frame; autoflow adds pages and threaded frames until the text fits; Remove Styles option (`designcraft-textimport`).- Gradient Feather (⇧G tool, `object.gradientFeather`): objects fade along a linear or radial opacity gradient, on screen and as a soft mask in PDF.- Script Label (`object.label`, `object.findByLabel`), alt text (`object.altText`), Isolate Blending / Knockout Group (`object.transparencyGroup`; on screen, PDF isolates), Table ▸ Sort (`table.sortRows`, numeric-aware, header/footer fixed).diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 8b4e7713e..feafdb441 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -538,6 +538,45 @@ fn commands_take_non_object_params_without_panicking() {}}+/// Load the text from a frame's out port with the Selection tool and click on the pasteboard:+/// a new frame is threaded there and the overset text flows into it.+#[test]+fn threading_with_the_loaded_text_cursor_on_the_sample() {+ use designcraft_tools::{PointerEvent, PointerKind};+ let mut s = Session::new();+ s.execute("file.newSample", &json!({})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ let (sid, first) = d.stories.values().find(|st| st.frames.len() >= 2).map(|st| (st.id, st.frames[0])).expect("a threaded story");+ // Break the thread so the first frame is overset, and select it.+ s.execute("text.unthread", &json!({"frame": first.0})).unwrap();+ assert!(s.cache.get(&s.doc().unwrap().doc, sid, None).is_overset());+ s.execute("selection.set", &json!({"ids": [first.0]})).unwrap();+ s.set_tool("selection");+ let v = ViewInfo::at_zoom(1.0);+ let layout = s.layout();+ let port = designcraft_tools::thread::port_center(&s.doc().unwrap().doc, &layout, first, true, v.zoom).unwrap();+ let ev = |k, p: designcraft_geom::Point| PointerEvent::new(k, p.x, p.y);+ s.pointer(&ev(PointerKind::Down, port), v).unwrap();+ s.pointer(&ev(PointerKind::Up, port), v).unwrap();+ assert_eq!(s.cursor(port + designcraft_geom::Vec2::new(-2000.0, 0.0), Default::default(), v), designcraft_tools::Cursor::LoadedText);+ // On the pasteboard left of the first spread.+ let b = layout.slots[0].bounds;+ let at = designcraft_geom::Point::new(b.x0 - 300.0, b.y0 + 100.0);+ let undo = s.doc().unwrap().history.undo.len();+ s.pointer(&ev(PointerKind::Down, at), v).unwrap();+ s.pointer(&ev(PointerKind::Up, at), v).unwrap();+ let st = s.doc().unwrap();+ assert_eq!(st.history.undo.len(), undo + 1, "one undo step");+ let frames = st.doc.story(sid).unwrap().frames.clone();+ assert_eq!(frames.len(), 2);+ let new = frames[1];+ assert_eq!(st.selection.items, [new]);+ let cs = s.cache.get(&s.doc().unwrap().doc, sid, None);+ assert!(cs.frames.iter().any(|f| f.frame == new && !f.range.is_empty()), "the text flows into the new frame");+ let nb = s.doc().unwrap().doc.item(new).unwrap().bounds();+ assert!((nb.y0 - layout.to_spread(designcraft_doc::SpreadRef::Doc(0), at).y).abs() < 1e-6, "{nb:?}");+}+/// Drag a selection handle of item 0 on spread 0 from the edge point `at` by `by` (canvas units).fn drag_handle(s: &mut Session, at: designcraft_geom::Point, by: designcraft_geom::Vec2, v: ViewInfo) {use designcraft_tools::{PointerEvent, PointerKind};diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rsindex 016df8783..cdeaee792 100644--- a/crates/tools/src/lib.rs+++ b/crates/tools/src/lib.rs@@ -20,6 +20,7 @@ mod pencil;pub mod select;pub mod snap;mod text;+pub mod thread;mod xform;use designcraft_compose::Cache;@@ -354,6 +355,10 @@ pub enum Cursor {ZoomOut,Eyedropper,LoadedText,+ /// Loaded text over a frame a click threads to.+ ThreadLink,+ /// Loaded text over the frame a click unthreads from.+ Unthread,LoadedGraphic,NotAllowed,}diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rsindex 457625fc6..84e12d3b3 100644--- a/crates/tools/src/select.rs+++ b/crates/tools/src/select.rs@@ -3,11 +3,13 @@//! Click selects the frontmost item (Shift toggles), drag moves (Alt duplicates, Shift constrains),//! the 8 bounding-box handles resize (Shift keeps proportions, Alt from centre, Cmd scales content),//! empty-canvas drags make a marquee, double-clicking a text frame switches to the Type tool.+//! A click on a selected text frame's in or out port loads the text cursor (see [`crate::thread`]).use designcraft_doc::{ItemId, SpreadRef};use designcraft_geom::{Affine, Point, Rect, Vec2};use serde_json::{Value, json};+use crate::thread::Loaded;use crate::{Action, Cursor, Gesture, Mods, Overlay, PointerEvent, PointerKind, SnapRequest, Tool, ToolContext, ToolKey, rect_json, spread_json};#[derive(Clone, Debug)]@@ -38,6 +40,11 @@ enum Drag {start: Point,cur: Point,},+ /// A press with the loaded text cursor.+ Place {+ start: Point,+ cur: Point,+ },Anchor {id: u64,si: usize,@@ -100,11 +107,58 @@ pub struct SelectionTool {guides: Vec<Overlay>,/// Selected item to toggle if this Shift press never becomes a drag.shift_release: Option<u64>,+ /// The loaded text cursor.+ loaded: Option<Loaded>,}impl SelectionTool {pub fn new(direct: bool) -> Self {- Self { direct, drag: Drag::None, hover_handle: None, guides: vec![], shift_release: None }+ Self { direct, drag: Drag::None, hover_handle: None, guides: vec![], shift_release: None, loaded: None }+ }++ /// Ports and the loaded text cursor. None: not a threading event.+ fn thread_pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option<Vec<Action>> {+ let p = ev.pos;+ let exec = |c: Option<(&'static str, Value)>| c.map(|(id, params)| Action::Exec(id.into(), params)).into_iter().collect::<Vec<_>>();+ // A double click: sent as such, or the canvas's second press.+ if matches!(ev.kind, PointerKind::Down | PointerKind::DoubleClick)+ && ev.click_count() == 2+ && let Some((frame, out)) = crate::thread::port_at(cx, p)+ {+ self.loaded = None;+ self.drag = Drag::None;+ return Some(exec(crate::thread::unthread_at_port(cx.doc, frame, out)));+ }+ self.loaded = self.loaded.and_then(|l| l.resolve(cx.doc));+ match (ev.kind, self.loaded) {+ (PointerKind::Down | PointerKind::DoubleClick, _) if let Some((frame, out)) = crate::thread::port_at(cx, p) => {+ self.loaded = Some(Loaded { frame, out, advance: false });+ self.drag = Drag::None;+ Some(vec![])+ }+ (PointerKind::Down | PointerKind::DoubleClick, Some(_)) => {+ self.drag = Drag::Place { start: p, cur: p };+ Some(vec![])+ }+ (PointerKind::Drag, Some(_)) => {+ if let Drag::Place { start, .. } = self.drag {+ self.drag = Drag::Place { start, cur: p };+ }+ Some(vec![])+ }+ (PointerKind::Up, Some(l)) => {+ let Drag::Place { start, .. } = std::mem::replace(&mut self.drag, Drag::None) else { return Some(vec![]) };+ let cmd = l.click(cx, start, p, ev.mods);+ // Alt (semi-autoflow) stays loaded with what is left; an invalid target keeps the load.+ if cmd.is_some() {+ self.loaded = (ev.mods.alt && !ev.mods.shift && cmd.as_ref().is_some_and(|c| c.0 == "text.thread"))+ .then_some(Loaded { advance: true, ..l });+ }+ Some(exec(cmd))+ }+ (PointerKind::Move, Some(_)) => Some(vec![]),+ _ => None,+ }}}@@ -371,6 +425,11 @@ impl Tool for SelectionTool {fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {let p = ev.pos;+ if !self.direct+ && let Some(actions) = self.thread_pointer(cx, ev)+ {+ return actions;+ }// The second press of a double click on a text frame: edit its text.if matches!(ev.kind, PointerKind::Down | PointerKind::DoubleClick)&& ev.click_count() == 2@@ -600,6 +659,7 @@ impl Tool for SelectionTool {self.drag = Drag::Marquee { start, cur: p };vec![]}+ Drag::Place { .. } => vec![],Drag::Rotate { center, start_angle, start_rotation } => {let mut a = ((p - center).atan2() - start_angle).to_degrees();self.guides.clear();@@ -711,7 +771,7 @@ impl Tool for SelectionTool {}vec![Action::Exec("selection.set".into(), json!({"ids": ids, "add": ev.mods.shift}))]}- Drag::None => vec![],+ Drag::None | Drag::Place { .. } => vec![],}}PointerKind::DoubleClick => vec![],@@ -719,6 +779,11 @@ impl Tool for SelectionTool {}fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec<Action> {+ if key == ToolKey::Escape && self.loaded.take().is_some() {+ // Unload; the selection stays. Cancel (no interaction runs) marks the key handled.+ self.drag = Drag::None;+ return vec![Action::Cancel];+ }let inc = cx.doc.settings.keyboard_increment * if mods.shift { 10.0 } else { 1.0 };let mv = |dx: f64, dy: f64| vec![Action::Exec("transform.move".into(), json!({"dx": dx, "dy": dy, "copy": mods.alt}))];if cx.selection.items.is_empty() {@@ -737,7 +802,7 @@ impl Tool for SelectionTool {fn overlays(&self, _cx: &ToolContext) -> Vec<Overlay> {match &self.drag {- Drag::Marquee { start, cur } => vec![Overlay::Marquee(Rect::from_points(*start, *cur))],+ Drag::Marquee { start, cur } | Drag::Place { start, cur } => vec![Overlay::Marquee(Rect::from_points(*start, *cur))],Drag::Move { .. } | Drag::Resize { .. } | Drag::Rotate { .. } | Drag::Anchor { .. } => self.guides.clone(),_ => vec![],}@@ -747,6 +812,9 @@ impl Tool for SelectionTool {if self.direct {return Cursor::ArrowHollow;}+ if let Some(l) = self.loaded.and_then(|l| l.resolve(cx.doc)) {+ return if crate::thread::port_at(cx, p).is_some() { Cursor::LoadedText } else { l.cursor(cx, p) };+ }match self.drag {Drag::Move { .. } => return Cursor::Move,Drag::Resize { handle, .. } => return handle_cursor(handle),diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rsindex 902c44949..f898755bf 100644--- a/crates/tools/src/tests.rs+++ b/crates/tools/src/tests.rs@@ -706,6 +706,205 @@ 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 alt_click_stays_loaded() {+ 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 alt = Mods { alt: true, ..Default::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);+}++#[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());diff --git a/crates/tools/src/thread.rs b/crates/tools/src/thread.rsnew file mode 100644index 000000000..7e6500fbb--- /dev/null+++ b/crates/tools/src/thread.rs@@ -0,0 +1,199 @@+//! Text threads with the Selection tool: the in and out ports of selected text frames, and the+//! loaded text cursor a click on a port gives.+//!+//! Loaded from an out port, a click threads the clicked frame after the port's frame; loaded+//! from an in port, in front of it. A click on empty space makes a frame the width of the column+//! there, a drag makes one of the dragged size. Clicking the frame on the other side of an+//! existing link breaks the thread there. Shift autoflows, Alt stays loaded with the rest.++use designcraft_doc::{Document, Item, ItemId, SpreadRef};+use designcraft_geom::{Point, Rect};+use serde_json::{Value, json};++use crate::{CanvasLayout, Cursor, Mods, ToolContext, rect_json, spread_json};++/// Port square size, in screen pixels.+pub const PORT_SIZE_PX: f64 = 8.5;+/// The in port sits this far below the top-left corner, the out port this far above the+/// bottom-right corner (screen pixels along the frame edge).+const IN_PORT_PX: f64 = 14.5;+const OUT_PORT_PX: f64 = 12.0;+/// Screen pixels around a port that still hit it.+const PORT_SLOP_PX: f64 = 2.0;+/// A click frame shorter than this (the click was at or below the bottom margin) gets+/// [`CLICK_FRAME_HEIGHT`] instead.+const MIN_CLICK_FRAME_HEIGHT: f64 = 12.0;+const CLICK_FRAME_HEIGHT: f64 = 72.0;++/// Canvas centre of a text frame's in port (on its left edge below the top-left corner) or out+/// port (on its right edge above the bottom-right corner), at `zoom` screen pixels per point.+pub fn port_center(doc: &Document, layout: &CanvasLayout, id: ItemId, out: bool, zoom: f64) -> Option<Point> {+ let it = doc.item(id)?;+ let loc = doc.find(id)?;+ let m = layout.xf(loc.spread) * doc.parent_xf(&loc) * it.xf;+ let r = it.inner_bounds();+ let (corner, toward) = if out { (Point::new(r.x1, r.y1), Point::new(r.x1, r.y0)) } else { (Point::new(r.x0, r.y0), Point::new(r.x0, r.y1)) };+ let c = m * corner;+ let edge = (m * toward) - c;+ let len = edge.hypot();+ let step = (if out { OUT_PORT_PX } else { IN_PORT_PX }) / zoom.max(1e-9);+ if !(len.is_finite() && len > 1e-9 && step.is_finite()) {+ return Some(c);+ }+ // Along the edge, never past its middle on a tiny frame.+ Some(c + edge * (step.min(len / 2.0) / len))+}++/// The port of a selected text frame under `p` (canvas): (frame, out port?).+pub fn port_at(cx: &ToolContext, p: Point) -> Option<(ItemId, bool)> {+ let half = cx.tol(PORT_SIZE_PX / 2.0 + PORT_SLOP_PX);+ for id in &cx.selection.items {+ if !cx.doc.item(*id).is_some_and(Item::is_text_frame) {+ continue;+ }+ for out in [true, false] {+ if let Some(c) = port_center(cx.doc, cx.layout, *id, out, cx.zoom)+ && (c.x - p.x).abs() <= half+ && (c.y - p.y).abs() <= half+ {+ return Some((*id, out));+ }+ }+ }+ None+}++/// The frame a click with the loaded cursor makes on empty space (spread coordinates): the width+/// of the column under the click (the nearest column of the nearest page), from the click down+/// to the bottom margin. Off the page's columns it starts at the click, a column wide.+pub fn click_frame_rect(doc: &Document, sr: SpreadRef, p: Point) -> Option<Rect> {+ let sp = doc.spread(sr)?;+ let page = sp.pages.get(sp.page_at_x(p.x)?)?;+ let cols = page.column_rects();+ let dist = |c: &Rect| {+ if p.x < c.x0 {+ c.x0 - p.x+ } else if p.x > c.x1 {+ p.x - c.x1+ } else {+ 0.0+ }+ };+ let col = cols.iter().min_by(|a, b| dist(a).total_cmp(&dist(b)))?;+ let on_page = p.x >= page.x && p.x <= page.x + page.width;+ let (x0, x1) = if on_page { (col.x0, col.x1) } else { (p.x, p.x + col.width()) };+ let y1 = if col.y1 - p.y >= MIN_CLICK_FRAME_HEIGHT { col.y1 } else { p.y + CLICK_FRAME_HEIGHT };+ let r = Rect::new(x0, p.y, x1.max(x0 + 1.0), y1);+ [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()).then_some(r)+}++/// The loaded text cursor.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct Loaded {+ /// The frame whose port was clicked.+ pub frame: ItemId,+ /// Loaded from the out port (thread after `frame`) or the in port (in front of it).+ pub out: bool,+ /// Semi-autoflow: the frame just threaded on that side takes over once the document has it.+ pub advance: bool,+}++/// What a click with the loaded cursor does at a point.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum Target {+ /// Nothing there: a new frame.+ Empty,+ /// A frame that can join the thread.+ Thread(ItemId),+ /// The frame on the other side of the port's link: break the thread there.+ Unthread,+ /// A frame that can't join (the loaded frame itself, a picture, a frame text flows into…).+ Invalid,+}++impl Loaded {+ /// The loaded frame now (an advancing load moves on to the frame threaded last), or None+ /// when that frame is gone (undo, delete).+ pub fn resolve(self, doc: &Document) -> Option<Loaded> {+ let frame = if self.advance { self.neighbour(doc).unwrap_or(self.frame) } else { self.frame };+ doc.item(frame).filter(|i| i.is_text_frame()).map(|_| Loaded { frame, out: self.out, advance: false })+ }++ /// The next frame from an out port, the previous one from an in port.+ fn neighbour(self, doc: &Document) -> Option<ItemId> {+ if self.out { doc.next_frame(self.frame) } else { doc.prev_frame(self.frame) }+ }++ /// `text.thread` `from`/`to` for joining frame `t` (None: a new frame) on this side.+ fn pair(self, doc: &Document, t: Option<ItemId>) -> (Option<ItemId>, Option<ItemId>) {+ match (self.out, doc.prev_frame(self.frame)) {+ (true, _) => (Some(self.frame), t),+ (false, Some(prev)) => (Some(prev), t),+ (false, None) => (t, Some(self.frame)),+ }+ }++ pub fn target(self, cx: &ToolContext, p: Point) -> Target {+ let Some((_, id)) = cx.hit(p) else { return Target::Empty };+ if Some(id) == self.neighbour(cx.doc) {+ return Target::Unthread;+ }+ match self.pair(cx.doc, Some(id)) {+ (Some(from), Some(to)) if cx.doc.check_thread(from, to).is_ok() => Target::Thread(id),+ _ => Target::Invalid,+ }+ }++ pub fn cursor(self, cx: &ToolContext, p: Point) -> Cursor {+ match self.target(cx, p) {+ Target::Empty => Cursor::LoadedText,+ Target::Thread(_) => Cursor::ThreadLink,+ Target::Unthread => Cursor::Unthread,+ Target::Invalid if cx.hit(p).is_some_and(|(_, id)| id == self.frame) => Cursor::LoadedText,+ Target::Invalid => Cursor::NotAllowed,+ }+ }++ /// The command for a click at `p`, or a drag from `start` to `p` (canvas). None: nothing to do.+ pub fn click(self, cx: &ToolContext, start: Point, p: Point, mods: Mods) -> Option<(&'static str, Value)> {+ let dragged = (p - start).hypot() >= cx.tol(3.0);+ let (pair, new_rect) = if dragged {+ let (sr, a) = cx.layout.spread_at(start)?;+ (self.pair(cx.doc, None), Some((sr, Rect::from_points(a, cx.layout.to_spread(sr, p)))))+ } else {+ match self.target(cx, p) {+ Target::Unthread => {+ let side = if self.out { "after" } else { "before" };+ return Some(("text.unthread", json!({"frame": self.frame.0, "side": side})));+ }+ Target::Invalid => return None,+ Target::Thread(t) => (self.pair(cx.doc, Some(t)), None),+ Target::Empty => {+ let (sr, sp) = cx.layout.spread_at(p)?;+ (self.pair(cx.doc, None), Some((sr, click_frame_rect(cx.doc, sr, sp)?)))+ }+ }+ };+ let mut params = serde_json::Map::new();+ if let Some(f) = pair.0 {+ params.insert("from".into(), json!(f.0));+ }+ if let Some(t) = pair.1 {+ params.insert("to".into(), json!(t.0));+ }+ if let Some((sr, r)) = new_rect {+ params.insert("rect".into(), rect_json(r));+ params.insert("spread".into(), spread_json(sr));+ }+ if mods.shift {+ params.insert("autoflow".into(), json!(true));+ }+ Some(("text.thread", Value::Object(params)))+ }+}++/// Double-click on a port: break the link it shows, if it has one.+pub(crate) fn unthread_at_port(doc: &Document, frame: ItemId, out: bool) -> Option<(&'static str, Value)> {+ let linked = if out { doc.next_frame(frame).is_some() } else { doc.prev_frame(frame).is_some() };+ linked.then(|| ("text.unthread", json!({"frame": frame.0, "side": if out { "after" } else { "before" }})))+}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 22b833cd1..164e953f5 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -330,6 +330,36 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {let space = ui.input(|i| i.key_down(egui::Key::Space)) && !app.session.wants_text();let c = if space { Cursor::Hand } 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));+ 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);+ }+ }}}@@ -352,6 +382,8 @@ fn cursor_icon(c: Cursor) -> egui::CursorIcon {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,}}@@ -801,7 +833,7 @@ fn draw_selection(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Documunion = Some(union.map_or(b, |u| u.union(b)));// Text frame ports.if let Content::Text(tf) = &it.content {- draw_ports(app, painter, xf, doc, layout, it, tf.story, a, color);+ draw_ports(app, painter, xf, doc, layout, it, tf.story, color);}if let Content::Graphic(g) = &it.content&& sel.content@@ -894,7 +926,6 @@ fn draw_ports(layout: &CanvasLayout,it: &Item,sid: designcraft_doc::StoryId,- a: Affine,color: Color32,) {let Some(story) = doc.story(sid) else { return };@@ -902,14 +933,11 @@ fn draw_ports(let is_last = pos + 1 == story.frames.len();let cs = app.session.cache.get(doc, sid, None);let overset = is_last && cs.is_overset();- let s = 8.5;- let _ = layout;- let r = it.inner_bounds();- let m = a * it.xf;+ let s = designcraft_tools::thread::PORT_SIZE_PX as f32;// In port on the left edge below the top-left corner; out port on the right edge above the- // bottom-right corner (screen-space offsets).- let inp = xf.to_screen(m * Point::new(r.x0, r.y0)) + vec2(0.0, 14.5);- let outp = xf.to_screen(m * Point::new(r.x1, r.y1)) - vec2(0.0, 12.0);+ // bottom-right corner. The Selection tool hit-tests the same places.+ let port = |out: bool| designcraft_tools::thread::port_center(doc, layout, it.id, out, xf.zoom).map(|c| xf.to_screen(c));+ let (Some(inp), Some(outp)) = (port(false), port(true)) else { return };for (c, has_link, is_out) in [(inp, pos > 0, false), (outp, !is_last, true)] {let pr = Rect::from_center_size(c, vec2(s, s));painter.rect_filled(pr, 0.0, Color32::WHITE);diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex 9afde404e..a8d386775 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -126,6 +126,7 @@ pub fn handle(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) ->let base_mods: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default();let view = app.view_info();let xf = app.canvas_rect.zip(app.view().copied()).map(|(rect, v)| Xf::new(rect, &v));+ let mut last = None;for e in events {let kind = match e.get("kind").and_then(Value::as_str).unwrap_or("") {"down" => PointerKind::Down,@@ -151,9 +152,14 @@ pub fn handle(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) ->return err(e);}app.after_engine();+ last = Some((pos, mods));}ctx.request_repaint();- wrap(app.run("document.inspect", json!({})).map(|d| json!({"selection": d["selection"], "tool": app.session.tool_id()})))+ // The tool's cursor where the last event was.+ let cursor = last.map(|(pos, mods)| app.session.cursor(pos, mods, view));+ wrap(+ app.run("document.inspect", json!({})).map(|d| json!({"selection": d["selection"], "tool": app.session.tool_id(), "cursor": cursor})),+ )}"ui.key" => {let Some(k) = s("key").and_then(key_from) else { return err("unknown or missing `key`") };diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 86364b50c..76c9308c9 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -16,7 +16,7 @@ Start the app with `--control <port>` (or `DESIGNCRAFT_CONTROL_PORT`). The serve| `ui.inspect` | — | Tool, UI state, view (zoom/origin), canvas rect, perf || `ui.menu.list` / `ui.tool.list` | — | Menu tree / Tools panel groups || `ui.tool.select` | `{tool}` | Select a tool (`selection`, `type`, `rectangleFrame`, …) |-| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick, x, y, space?: "screen"\|"canvas", clicks?}], mods?}` | Drive the active tool through the same code path as the mouse; `clicks` on a `down` is the press count (3 = triple click) |+| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick, x, y, space?: "screen"\|"canvas", clicks?}], mods?}` | Drive the active tool through the same code path as the mouse; `clicks` on a `down` is the press count (3 = triple click); returns the selection, the tool and its cursor at the last event (e.g. `LoadedText`, `ThreadLink`, `Unthread`) || `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | Synthetic keyboard input (typing into a text frame) || `ui.move` / `ui.click` / `ui.drag` | screen points | Real egui pointer input — reaches every widget, menu and panel || `ui.set` | `{brightness?, panel?, rulers?, guides?, frameEdges?, baselineGrid?, textThreads?, screenMode?, zoom?, page?, fit?}` | UI state |