DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge table-border-drag: Tables: drag row and column borders with the Type tool
aiongga5fbf5d8d4ff
diff --cc ROADMAP.mdindex c1d16dd7e,2023bbaba..5546b77cf--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -128,62 -129,12 +128,63 @@@ list) · [roadmap.md](docs/roadmap.md)Newest first.+ - **2026-10-12** · With the Type tool, dragging a table's column or row border resizes it (the double-arrow cursor shows over a border): later columns and rows move along, Shift keeps the table size, and Shift on the right or bottom edge scales every column or row. A dragged row becomes At Least; one undo step per drag, Esc cancels; works in rotated frames and turned spreads. Scripts use `table.resizeBorder`. No readiness percentage change.+- **2026-10-12** · The Tools panel's Fill/Stroke keys work: D (default fill and stroke), X (fill or stroke in front), Shift+X (swap per object, tints included) and / (Apply None), as `color.*` commands; swap and default are one undo step (`object.swapFillStroke`, `object.defaultFillStroke`); the Color panel follows the proxy's fill/stroke choice. No readiness percentage change.+- **2026-10-12** · With a placed graphic selected (Direct Selection), the Transform values act on the graphic inside its frame, as in InDesign: a tilted frame's image can be straightened to 0°. No readiness percentage change.+- **2026-10-11** · Font menu laid out like InDesign's: filters (classification, favourites,+ recently added), families opening to their styles, the selected text as the sample in three+ sizes, Recently Used fonts, Show Similar Fonts and each font's format.+- **2026-10-12** · The Effects panel shows the level its settings apply to ("Group: Color Dodge 100%") and, as in InDesign, Isolate Blending and Knockout Group for a selected group. No readiness percentage change.+- **2026-10-12** · Edit › Step and Repeat has its InDesign dialog: Repeat (Count, or Rows and Columns with Create as a grid), Offset (Vertical, Horizontal, in ruler units) and Preview, which shows the copies while the dialog is open; Cancel takes them away and OK makes them as one undo step. No readiness percentage change.+- **2026-10-12** · Load Styles: the Paragraph Styles and Character Styles panels load styles from another DesignCraft document or an IDML file, with the styles, swatches and lists they name; a dialog picks the styles and what happens to one the document defines differently (`style.load`). No readiness percentage change.+- **2026-10-12** · On screen, blend modes blend with the objects below and not with the paper, as in InDesign and in PDF export: a Color Dodge or Screen object over blank paper shows as it is. No readiness percentage change.+- **2026-10-12** · Text threads by hand: click a selected text frame's in or out port to load+ the text cursor, then click a frame to thread it, click empty space for a column-wide frame or+ drag one (it snaps like frame drawing); Shift-click autoflows, Alt-click stays loaded on the+ frame just added; click the linked frame or double-click a port to break the thread.+ `text.thread`, `text.unthread`, `text.removeFromThread` with undo; locked frames and layers+ refuse threads. The alpha gate now waits only on the Primary Text Frame page fixes (#165). No+ readiness percentage change.+- **2026-10-12** · Properties › Transform shows rotation, shear and X/Y scale, and Rotate 90° and Flip Horizontal/Vertical buttons, as InDesign's does. No readiness percentage change.+- **2026-10-12** · Underlines and strikethroughs are drawn as one bar per stretch of text on screen, as in PDF export: a bar per letter left faint seams between the letters. No readiness percentage change.+- **2026-10-12** · The section marker character shows its section's marker text on document pages (nothing when the section has none) instead of the word "Section", which stays on parent pages; editing the marker recomposes (#556). No readiness percentage change.+- **2026-10-12** · IDML import keeps a font family name exactly as written, trailing spaces included, and font lookup falls back to the name without surrounding spaces; `FontStyle="Nothing"` leaves the style to the paragraph (#558). No readiness percentage change.+- **2026-10-12** · Clipping paths saved with images in IDML (Detect Edges, Alpha Channel, Photoshop Path, User-Modified Path, inverted or not) clip the image on screen and in PDF and survive IDML export; `object.clippingPathOptions` reports, inverts or removes one (#450). No readiness percentage change.+- **2026-10-12** · Anchored objects with text wrap push text aside: other stories' text under them and the lines of their own story after the anchor's line (#557). No readiness percentage change.+- **2026-10-12** · Hyphenation Zone applies to the Single-line Composer only, as in InDesign. With the default Paragraph Composer, ragged text hyphenates where InDesign does (aper-natem), giving the same line breaks. No readiness percentage change.- **2026-10-12** · Words in capitals hyphenate like capitalized words (FERRUM COM-MODI), as in InDesign; Hyphenate Capitalized Words off keeps them whole. No readiness percentage change.+- **2026-10-12** · Load Swatches refuses an `.ase` file with more than 100,000 colors, and `swatch.load` merges a file of 100,000 colors in under 0.1 s (it took 9.6 s of CPU in a test build). No readiness percentage change.+- **2026-10-11 (printing):** `file.printers` and `file.print` use craft-libs/craft-print for CUPS and Windows. DesignCraft retains PDF export, page selection, spreads, marks and bleed; dry runs create no temporary PDF or print job. Windows selects matching or default driver paper and shrinks oversized sheets without enlarging smaller ones; queue duplex defaults are preserved. Headless tests exercise exported bytes, job settings, dry runs and refusals; shared native Windows CI passes, including paused-queue submission and cleanup. PostScript, production print controls and physical output validation remain open. No readiness percentage change.+- **2026-10-11** · The View menu follows InDesign's: proofing first, then zoom, Rotate Spread, Screen Mode, Display Performance, rulers, Extras, Grids & Guides and Structure; the view items that sat at the end of the Type menu moved there. No readiness percentage change.+- **2026-10-11** · Properties › Appearance's Fill and Stroke menus gain InDesign's Tint field and, for a text frame, Apply To: Frame / Text. No readiness percentage change.+- **2026-10-11** · `story.replaceRange`, `story.setText`, notes, footnotes, endnotes, type on a path and table cells read `\r` and `\r\n` as paragraph returns, as `frame.create` and `text.insert` already did. No readiness percentage change.+- **2026-10-11** · Corner Options keep curved sides curved and round every corner point, including where an arc meets a line (a Pathfinder quarter circle with rounded corners stayed a triangle). No readiness percentage change.+- **2026-10-11:** Type › Justification… (Cmd+Alt+Shift+J, also in the Paragraph panel menu) sets word and letter spacing, glyph scaling and the composer on the selected paragraphs, sharing the Paragraph Style Options section (#531). No readiness percentage change.+- **2026-10-11** · Properties gains InDesign's Pathfinder section (Add, Subtract, Intersect, Exclude Overlap, Minus Back) with several objects selected; section titles and icon buttons have accessible names. No readiness percentage change.- **2026-10-11** · `transform.move {copy}`, Edit › Duplicate and Step and Repeat return the copies' ids, so a script can go on with them. No readiness percentage change.- **2026-10-11** · `object.fill` and `object.stroke` refuse a swatch name the document doesn't have (it painted nothing) and suggest the name meant (`Paper` → `[Paper]`). No readiness percentage change.-- **2026-10-11 (printing):** `file.printers` and `file.print` use craft-libs/craft-print for CUPS and Windows. DesignCraft retains PDF export, page selection, spreads, marks and bleed; dry runs create no temporary PDF or print job. Windows selects matching or default driver paper and shrinks oversized sheets without enlarging smaller ones; queue duplex defaults are preserved. Headless tests exercise exported bytes, job settings, dry runs and refusals; shared native Windows CI passes, including paused-queue submission and cleanup. PostScript, production print controls and physical output validation remain open. No readiness percentage change.-+- **2026-10-11** · Japanese captions now cover print ranges, imported style handling and table+ row/column movement, including row-height distribution. Existing translation and RTL helpers+ handle the display; command IDs, stored option values and user-defined style names are unchanged.+- **2026-10-11** · Moving a sheared and rotated text frame no longer leaves trails of text behind: canvas repaints cover the frame's whole text box, not just its outline. No readiness percentage change.+- **2026-10-11** · Live corners: the yellow widget on a selected rectangle frame shows corner+ diamonds; dragging one rounds the corners, Alt-click steps the corner shape (#186).+- **2026-10-11** · Optical kerning (#181): pairs are spaced from their outlines (ink gap per band,+ pulled towards the font's stem gap, bounded) instead of silently using the font's kern pairs.+- **2026-10-11** · New Document laid out like InDesign's (#325): Recent, Saved, Print, Web and+ Mobile preset tabs beside the preset's details; saved document presets live in the engine+ (`file.savePreset`, `file.deletePreset`, `file.new {preset}`); `file.new` takes intent, units,+ start page and per-edge bleed and slug.+- **2026-10-11** · macOS: fonts that font services and managers activate (Adobe Fonts,+ RightFont) are listed, read from the files CoreText has available (#261, #327).+- **2026-10-11:** Document pages take their parent page's margins and columns (left or right parent page by side) and follow its changes unless they have their own; parent ruler guides draw and snap on the pages based on it. IDML import marks a page margin preference that differs from its parent as the page's own. No readiness percentage change.+- **2026-10-11** · Document Setup laid out like InDesign's: Page Size, Margins (new: every+ page's, `layout.documentSetup {margins}`), Bleed and Slug with links, Adjust Layout.+- **2026-10-11** · IDML reads and writes a spread's view rotation (Rotate Spread) as the+ rotation part of the spread transform (#484).+- **2026-10-11** · The document grid is drawn (View ▸ Grids & Guides ▸ Show/Hide Document Grid,+ ⌘'), on the lines Snap to Document Grid uses, behind or in front of page items (#530).+- **2026-10-12** · Double-clicking the Fill or Stroke box in the Tools panel opens the Color Picker with the selection's colour, as in InDesign (it opened the Swatches panel). No readiness percentage change.- **2026-10-10 (UI.4–UI.5):** Panel tabs can move into other groups, split the dock, float, resize and return to their saved locations through shared docking transactions. Layouts persist in custom workspaces; UI and control commands share the same validated action path. Shared pane geometry and widget-state theme application retain all five palettes and local fonts. Split panes send keyboard input only to the focused canvas and scope contextual toolbar IDs per pane. No readiness percentage change.- **2026-10-10** · Version 0.6.0; releases add a Linux riscv64 tar.gz (cross-compiled, CLIsmoke-tested under QEMU).diff --cc crates/compose/src/lib.rsindex 113d5ef32,225b6ceac..ef44533e6--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -46,10 -38,9 +46,10 @@@ use designcraft_geom::{Affine, Point, Ruse crate::breaker::{Break, Spacing};pub use crate::cache::Cache;use crate::notes::Notes;-pub use crate::notes::{find_note, hit_note, note_caret};+pub use crate::notes::{find_note, hit_note, hit_note_with, note_caret};+use crate::parabox::ParaBox;use crate::shape::{Glyph, StyleTable, SubstCtx};- pub use crate::table::{PlacedCell, StrokeSeg, TableFrag, cell_caret, find_cell, hit_cell, hit_cell_with};-pub use crate::table::{BorderHit, PlacedCell, StrokeSeg, TableFrag, cell_caret, find_cell, hit_border, hit_cell};++pub use crate::table::{BorderHit, PlacedCell, StrokeSeg, TableFrag, cell_caret, find_cell, hit_border, hit_cell, hit_cell_with};/// Character appearance shared by many glyphs (indexed from [`PlacedGlyph::style`]).#[derive(Clone, Debug, PartialEq)]diff --cc crates/engine/src/cmd/table.rsindex fc2f60398,96c2d0484..c1c313554--- a/crates/engine/src/cmd/table.rs+++ b/crates/engine/src/cmd/table.rs@@@ -200,17 -200,17 +200,26 @@@ fn table_specs() -> Vec<CommandSpec>in_table,set_cell),+ cmd!(+ query "table.getCellStroke",+ "Get Cell Stroke",+ [],+ None,+ "{story?, table?, rows?, cols?, edges?} → {weight, color, tint, type, gapColor, gapTint, fill, fillTint, edges: count} of the chosen edges of the target cells; a value that differs between them is null",+ in_table_or_ids,+ get_cell_stroke+ ),cmd!("table.setRowHeight", "Row Height", [], None, "{height, mode?: atLeast|exactly}", in_table, set_row_height),cmd!("table.setColumnWidth", "Column Width", [], None, "{width}", in_table, set_col_width),+ cmd!(+ "table.resizeBorder",+ "Resize Row or Column",+ [],+ None,+ "{story?, table?, frame?, axis: column|row, index, delta? | size?, keepTableSize?: bool} — moves the border after column/row `index` by `delta` (or makes that column/row `size` wide/high); later columns/rows move along. The last index is the table's end/bottom edge. keepTableSize: on an inner border the next column/row gives or takes the change; on the edge all columns/rows scale proportionally. A dragged row becomes At Least. Refuses a locked `frame`",+ in_table_or_ids,+ resize_border+ ),cmd!("table.distributeColumns", "Distribute Columns Evenly", ["Table"], None, "{}", in_table, distribute_cols),cmd!("table.distributeRows",diff --cc crates/tools/src/tests.rsindex e5a860704,4b0bb837a..6aaa12ce6--- a/crates/tools/src/tests.rs+++ b/crates/tools/src/tests.rs@@@ -742,592 -706,56 +742,646 @@@ 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:?}");+ }+ }diff --cc crates/tools/src/text.rsindex 625d998f3,d1486e47b..d495d7cf3--- a/crates/tools/src/text.rs+++ b/crates/tools/src/text.rs@@@ -1,27 -1,13 +1,28 @@@//! Type tool (T): click in a frame to place the caret, drag in a frame to select text, drag on//! empty canvas to draw a new text frame. Keys move the caret / delete; typing goes through- //! `text.insert` (sent by the UI as text input).+ //! `text.insert` (sent by the UI as text input). Dragging a table's row or column border resizes+ //! it (`table.resizeBorder`).+//!+//! IME: the marked text of a composition is a preview of `text.insert` at the caret (so it lays+//! out in place like typed text), underlined, until the IME commits it (one `text.insert`, one+//! undo step) or clears it (the preview goes, leaving no undo step).-use designcraft_compose::BorderHit;-use designcraft_geom::{Affine, Point};+use std::ops::Range;++use designcraft_compose as compose;+use designcraft_doc::{ItemId, TextSel};+use designcraft_geom::{Affine, Point, Vec2};use serde_json::json;-use crate::{Action, Cursor, Mods, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, frame::drag_rect, rect_json, spread_json};+use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, frame::snapped_drag_rect, rect_json, spread_json};++/// IME marked text shown at the caret through a preview of `text.insert`, not yet typed.+#[derive(Clone, Debug, PartialEq)]+struct Preedit {+ text: String,+ /// The clause being converted (empty: the IME's cursor), in bytes of `text`.+ active: Option<Range<usize>>,+}#[derive(Default)]pub struct TypeTool {@@@ -33,11 -19,86 +34,91 @@@/// A press on a table whose whole rows or columns are selected: (frame, press point in/// spread space) — a drag moves them, a click places the caret.cell_drag: Option<(u64, Point)>,+ /// Snap guides while drawing a frame.+ guides: Vec<Overlay>,+ /// The press selected a word, line, paragraph or story (several clicks): drags keep it.+ unit_selected: bool,+ preedit: Option<Preedit>,+ /// A press on a table row or column border: a drag resizes it.+ border: Option<BorderDrag>,+ }++ /// A table border under the pointer, and the frame's canvas → inner-space mapping.+ #[derive(Clone, Copy)]+ struct BorderDrag {+ frame: u64,+ story: u64,- hit: BorderHit,++ hit: compose::BorderHit,+ /// Canvas → frame inner space (through rotations, scaling and turned spreads).+ inv: Affine,+ /// Press point in frame inner space.+ start: Point,+ begun: bool,+ /// The border runs vertically on the canvas (column borders on an unrotated frame).+ horizontal_drag: bool,+ }++ /// The row or column border of a table near canvas point `pos`, in an unlocked text frame.+ fn border_at(cx: &ToolContext, pos: Point) -> Option<BorderDrag> {+ let (_, id) = cx.hit(pos)?;+ let it = cx.doc.item(id)?;+ if it.locked {+ return None;+ }+ let sid = it.text_frame()?.story;+ let story = cx.doc.story(sid)?;+ if story.tables.is_empty() {+ return None;+ }+ let xf = cx.item_canvas_xf(id)? * cx.doc.text_xf(it);+ let det = xf.determinant().abs();+ if !(det.is_finite() && det > 1e-12) {+ return None;+ }+ let inv = xf.inverse();+ let start = inv * pos;+ let cs = cx.cache.get(cx.doc, sid, None);+ let fi = cs.frames.iter().position(|f| f.frame == id)?;- let hit = designcraft_compose::hit_border(&cs, fi, &story.tables, start, cx.tol(4.0) / det.sqrt())?;++ let hit = compose::hit_border(&cs, fi, &story.tables, start, cx.tol(4.0) / det.sqrt())?;+ let axis = if hit.column { Point::new(1.0, 0.0) } else { Point::new(0.0, 1.0) };+ let v = (xf * axis) - (xf * Point::ORIGIN);+ Some(BorderDrag { frame: id.0, story: sid.0, hit, inv, start, begun: false, horizontal_drag: v.x.abs() >= v.y.abs() })+ }++ impl BorderDrag {+ fn cursor(&self) -> Cursor {+ if self.horizontal_drag { Cursor::ResizeH } else { Cursor::ResizeV }+ }++ /// Begin (once) and preview the resize for the pointer at canvas `pos`.+ fn drag(&mut self, pos: Point, keep: bool) -> Vec<Action> {+ let d = (self.inv * pos) - self.start;+ let mut delta = if self.hit.column { d.x } else { d.y };+ if self.hit.mirrored {+ delta = -delta;+ }+ if !delta.is_finite() {+ return vec![];+ }+ let mut out = vec![];+ if !self.begun {+ self.begun = true;+ out.push(Action::Begin(if self.hit.column { "Resize Column" } else { "Resize Row" }.into()));+ }+ out.push(Action::Preview(+ "table.resizeBorder".into(),+ json!({+ "frame": self.frame,+ "story": self.story,+ "table": self.hit.table,+ "axis": if self.hit.column { "column" } else { "row" },+ "index": self.hit.index,+ "delta": delta,+ "keepTableSize": keep,+ }),+ ));+ out+ }}/// Are whole rows or whole columns of a table selected?@@@ -138,7 -127,13 +219,14 @@@ impl Tool for TypeToolself.drawing = false;self.selecting = None;self.cell_drag = None;+ self.unit_selected = false;+ self.border = None;+ if ev.kind == PointerKind::Down+ && let Some(b) = border_at(cx, ev.pos)+ {+ self.border = Some(b);+ return vec![];+ }if let Some((_, id)) = cx.hit(ev.pos)&& let Some(it) = cx.doc.item(id)&& !matches!(it.content, designcraft_doc::Content::Graphic(_) | designcraft_doc::Content::Group { .. })@@@ -170,7 -158,14 +258,14 @@@}PointerKind::Drag => {let Some(a) = self.start else { return vec![] };+ if let Some(b) = self.border.as_mut() {+ // A click with a little wobble must not resize.+ if !b.begun && (ev.pos - a).hypot() < cx.tol(3.0) {+ return vec![];+ }+ return b.drag(ev.pos, ev.mods.shift);+ }- if self.cell_drag.is_some() {+ if self.cell_drag.is_some() || self.unit_selected {return vec![];}if let Some(fid) = self.selecting {@@@ -197,8 -189,10 +292,11 @@@out}PointerKind::Up => {+ self.guides.clear();let start = self.start.take();+ if let Some(b) = self.border.take() {+ return if b.begun { vec![Action::Commit] } else { vec![] };+ }if let Some((fid, from)) = self.cell_drag.take() {let sp = cx.layout.spread_at(ev.pos).map(|(_, p)| p).unwrap_or(ev.pos);let moved = start.is_some_and(|a| (ev.pos - a).hypot() >= cx.tol(3.0));@@@ -228,8 -222,13 +326,14 @@@}fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec<Action> {+ if key == ToolKey::Escape+ && let Some(b) = self.border.take()+ {+ self.start = None;+ return if b.begun { vec![Action::Cancel] } else { vec![] };+ }- if cx.selection.text.is_none() {+ // The IME owns the keys while it composes (the UI holds them back; this is a guard).+ if cx.selection.text.is_none() || self.preedit.is_some() {return vec![];}let mv = |dir: &str| {@@@ -251,36 -250,11 +355,36 @@@}}+ fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {+ if self.drawing {+ return self.guides.clone();+ }+ let (Some(p), Some(ts)) = (&self.preedit, cx.selection.text) else { return vec![] };+ // Marked text: a thin underline, a thick one under the clause being converted.+ let start = marked_start(cx, ts, p);+ let line = |(a, b): (Point, Point)| Overlay::Line { a, b, color: [0, 0, 0], dashed: false };+ let mut o: Vec<Overlay> = underlines(cx, ts, start..start + p.text.len()).into_iter().map(line).collect();+ match &p.active {+ Some(r) if !r.is_empty() => {+ for (a, b) in underlines(cx, ts, start + r.start..start + r.end) {+ // A second line a pixel further from the text.+ let d = b - a;+ let n = Vec2::new(-d.y, d.x) * (cx.tol(1.0) / d.hypot().max(1e-9));+ o.push(line((a + n, b + n)));+ }+ }+ // The IME's cursor inside the marked text (the text caret stays at its end).+ Some(r) if r.start < p.text.len() => o.extend(caret_line(cx, ts, start + r.start).map(line)),+ _ => {}+ }+ o+ }+fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor {- match cx.hit(p) {- Some((_, id)) if cx.doc.item(id).is_some_and(|i| i.is_text_frame()) => Cursor::Text,- _ => Cursor::Text,+ if let Some(b) = self.border.as_ref().copied().or_else(|| if self.start.is_none() { border_at(cx, p) } else { None }) {+ return b.cursor();}+ Cursor::Text}fn busy(&self) -> bool {diff --cc docs/target-app-parity.mdindex 9c838827b,ceee73976..1b4582215--- a/docs/target-app-parity.md+++ b/docs/target-app-parity.md@@@ -265,18 -265,18 +265,18 @@@ The inventory below was the "Working toIt is evidence of breadth: each item exists. It is not a claim of InDesign-level depth.- Document model: facing/non-facing spreads, parent pages with page-number markers, sections, layers, frames (text / graphic / unassigned), threaded stories, paragraph/character/object styles with based-on, swatches (process/spot/tints/gradients), corner options, text wrap, drop shadow, opacity/blend.-- Text engine: Knuth–Plass paragraph composer and single-line composer, dictionary hyphenation (public-domain Moby list + our own trained Liang patterns), justification with word/letter/glyph-scaling ranges, keep options (keep with next, keep lines together, widows/orphans), balance ragged lines, optical margin alignment, hyphenation zone/limit, columns, threading across frames and spreads, tabs, bullets/numbering, rules, shading, baseline grid, first-baseline options, vertical justification, wrap exclusions, overset detection, caret/hit testing.+- Text engine: Knuth–Plass paragraph composer and single-line composer, dictionary hyphenation (public-domain Moby list + our own trained Liang patterns), justification with word/letter/glyph-scaling ranges, keep options (keep with next, keep lines together — at start/end of paragraph by default, as in InDesign — widows/orphans), balance ragged lines, optical margin alignment, hyphenation zone/limit, columns, threading across frames and spreads, tabs, bullets/numbering, rules, shading, baseline grid, first-baseline options, vertical justification, wrap exclusions, overset detection, caret/hit testing.- FID2: IDML underline/strikethrough Text Color resets survive style inheritance and roundtrip. Raster and PDF paint underlines behind glyphs, retain strikethrough above, and center rules on their offsets; synthetic overlap tests cover both backends.- Rendering: vello_cpu (SIMD, multithreaded) — pages, items, images with mip levels, gradients, composed text.-- UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts, document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches, Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document and Preferences dialogs, Quick Apply (⌘Return), 4 brightness themes.-- Pen tool, Direct Selection anchor/handle editing, rotate from corners, Rotate/Scale/Shear tools, Eyedropper, snapping & smart guides, Align/Distribute, Find/Change (text + GREP), Story Editor, Paragraph Style Options, Effects panel, hidden characters, native macOS menu bar, measured InDesign 2026 look (Medium Dark): Properties sections per selection state, 21 pt spinner fields with arithmetic, Contextual Task Bar, inverse (black) text selection, Pages panel with drag-and-drop reorder / parent apply, Layers panel with per-object rows.+- UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts and the Fill/Stroke proxy (D, X, Shift+X, / as `color.*` commands), document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), document grid (View ▸ Grids & Guides, ⌘', on the snap positions, behind or in front of items), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches, Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document and Preferences dialogs, Quick Apply (⌘Return), 4 brightness themes.+- Pen tool, Direct Selection anchor/handle editing, rotate from corners, Rotate/Scale/Shear tools, Eyedropper, snapping & smart guides, Align/Distribute, Find/Change (text + GREP), Story Editor, Paragraph Style Options, Effects panel, hidden characters, native macOS menu bar, measured InDesign 2026 look (Medium Dark): Properties sections per selection state, 21 pt spinner fields with arithmetic, Contextual Task Bar, inverse (black) text selection, Pages panel with drag-and-drop reorder / parent apply, Layers panel with per-object rows, expandable groups and drag-and-drop reorder of layers and objects (the selection square moves the selection to another layer).- Tools: Selection (click, marquee, move, Alt-duplicate, resize handles), Direct Selection, Type (draw frame, click caret, select, type), Rectangle/Ellipse/Polygon (+ frame variants), Line, Hand, Zoom.- PDF export (krilla): real selectable text with embedded font subsets, DeviceCMYK/RGB + spot Separations, bleed boxes, crop/bleed marks + page info, pages or spreads, PDF/A-2b (PDF/X-4 output intent pending) — `file.exportPdf`, File › Export PDF…, `designcraft-cli run --export out.pdf`. File › Export PDF… now opens an "Export PDF" options dialog (General / Compression / Marks and Bleeds / Advanced) and remembers the last-used settings across exports and sessions.-- IDML interchange (`designcraft-idml`): export and import of swatches, styles, fonts, preferences, parent spreads, spreads/pages, frames, groups, images (embedded or linked), formatted threaded stories — opens in InDesign 2026 and round-trips InDesign-exported files (`file.exportIdml`, `file.openIdml`, File → Export IDML…, CLI `--in x.idml` / `--export x.idml`).+- IDML interchange (`designcraft-idml`): export and import of swatches, styles, fonts, preferences, parent spreads, spreads/pages, frames, groups, images (embedded or linked), formatted threaded stories; attributes a file leaves unset take InDesign's defaults (Keep Lines Together at start/end of paragraph, 12 pt corners, paragraph rules in Text Color, auto-sizing from the centre, numbered lists restarting in each story, alternating table fills Black 20 % / None; a tint of −1 is the colour's own; frames take the fill, stroke, corners and Text Frame Options they don't write from their object style chain, then [None]) — opens in InDesign 2026 and round-trips InDesign-exported files (`file.exportIdml`, `file.openIdml`, File → Export IDML…, CLI `--in x.idml` / `--export x.idml`).- - Tables (M8): tables anchored in stories (header/footer/body rows, merged cells, per-edge strokes, fills + alternating fills, insets, vertical justification, at-least/exact row heights); composed into the text column (columns scale to fit, rows break across columns/frames with repeating headers/footers, overset); rendered, exported to PDF (real text) and IDML (export + import); Table menu, Table panel, Create Table dialog, caret/typing/Tab navigation and cell selection in cells; `table.*` commands.+ - Tables (M8): tables anchored in stories (header/footer/body rows, merged cells, per-edge strokes, fills + alternating fills, insets, vertical justification, at-least/exact row heights); composed into the text column (columns scale to fit, rows break across columns/frames with repeating headers/footers, overset); rendered, exported to PDF (real text) and IDML (export + import); Table menu, Table panel, Create Table dialog, caret/typing/Tab navigation and cell selection in cells; Type tool drags of row and column borders (Shift keeps the table size, or scales every row/column on the outer edge; `table.resizeBorder`); `table.*` commands.- Hyperlinks (text or frames → URL / e-mail / page) and bookmarks, exported as PDF link annotations and outline.- EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`).-- Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid), snippets, object styles, Numbering & Section Options.+- Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid, with a previewing dialog), snippets, object styles, Numbering & Section Options.- Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands.- Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in Type › Paragraph Rules…, the Paragraph panel menu and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named.- Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands.