DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge PR #1000: Type tool: a drag after several clicks extends the selection by words, lines or paragraphs (#981)
aionggbb6f6e777dcb
diff --cc crates/engine/src/cmd/text.rsindex 2b17953d4,b238a599d..037688389--- a/crates/engine/src/cmd/text.rs+++ b/crates/engine/src/cmd/text.rs@@@ -458,6 -376,21 +466,21 @@@ fn select_at(s: &mut Session, p: &Valuelet frame = id_param(p, "frame").ok_or_else(|| bad(ID, "missing frame"))?;let pt = point_param(p, "point").ok_or_else(|| bad(ID, "missing point"))?;let (sid, b, cell) = hit_byte_with(s, frame, pt, compose::hit_char).ok_or_else(|| bad(ID, "not a text frame"))?;+ let (a, e) = unit_at(s, sid, cell, b, unit, ID)?;+ s.text_drag = false;+ s.typing_format = None;+ let sel = TextSel { story: sid, anchor: a, focus: e, frame: Some(frame), cell };+ s.text_unit = Some(sel);+ let st = s.doc_mut()?;+ st.selection = Selection::text(sel);+ // Explicit reselection invalidates the Find scope even when the range is unchanged.- st.revision = st.revision.wrapping_add(1);++ st.bump_revision();+ Ok(json!({"story": sid.0, "anchor": a, "focus": e}))+ }++ /// The `unit` (word, line, paragraph or story) around byte `b` of story `sid` (a cell's story+ /// with `cell`), as the multiple clicks select it.+ fn unit_at(s: &Session, sid: StoryId, cell: Option<CellAddr>, b: usize, unit: &str, cmd: &str) -> Result<(usize, usize)> {let st = s.doc()?;let story = st.doc.text_story(sid, cell).ok_or(designcraft_doc::DocError::NoStory(sid))?;let text = story.text.as_str();@@@ -543,6 -469,20 +559,20 @@@ fn place(s: &mut Session, p: &Value, exs.execute("object.content", &json!({"ids": [frame.0], "type": "text"}))?;}let (sid, b, cell) = hit_byte(s, frame, pt).ok_or_else(|| bad("text.placeCaret", "not a text frame"))?;+ // A drag after several clicks: whole units from the one first selected, in either direction.+ if extend+ && let Some(unit) = str_param(p, "unit")+ && let Some(u) = s.text_unit.filter(|u| u.story == sid && u.cell == cell)+ {+ let (ua, ue) = (u.anchor.min(u.focus), u.anchor.max(u.focus));+ let (na, ne) = unit_at(s, sid, cell, b, unit, "text.extendTo")?;+ let (anchor, focus) = if na < ua { (ue, na) } else { (ua, ne.max(ue)) };+ s.typing_format = None;+ let st = s.doc_mut()?;+ st.selection = Selection::text(TextSel { story: sid, anchor, focus, frame: Some(frame), cell });- st.revision = st.revision.wrapping_add(1);++ st.bump_revision();+ return Ok(json!({"story": sid.0, "anchor": anchor, "focus": focus}));+ }// Drag and drop: a press inside the selected text keeps it (to be dragged).if !extend {s.text_drag = s.doc()?.selection.text.is_some_and(|t| t.story == sid && t.cell == cell && !t.range().is_empty() && t.range().contains(&b));diff --cc crates/engine/src/lib.rsindex 959677650,85f592d6c..d3d0dfffe--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@@ -350,8 -293,14 +350,11 @@@ pub struct Sessionpub(crate) transforms: (Vec<(String, Value)>, Vec<designcraft_doc::ItemId>, bool),/// Drag and drop text editing: the press landed in the selected text.pub(crate) text_drag: bool,+ /// The word, line, paragraph or story the last `text.selectAt` selected: a drag that follows a+ /// double, triple or quadruple click extends from it by whole units (#981).+ pub(crate) text_unit: Option<designcraft_doc::TextSel>,/// Character formatting chosen at a bare caret, for the text typed there next.pub(crate) typing_format: Option<cmd::text::TypingFormat>,- /// Text an input method is composing (a dead key's accent), shown in the story as an- /// interaction preview until it commits: (document uid, byte length before the caret).- pub(crate) composition: Option<(u64, usize)>,/// The open Object Library (File › New / Open Library).pub library: Option<cmd::library::Library>,/// The open book (File › Open Book).@@@ -398,7 -337,9 +401,8 @@@ impl Sessionloaded: None,transforms: Default::default(),text_drag: false,+ text_unit: None,typing_format: None,- composition: None,library: None,conveyor: Vec::new(),book: None,diff --cc crates/tools/src/tests.rsindex ddbb070e0,9c838c4c2..57ef0e53c--- a/crates/tools/src/tests.rs+++ b/crates/tools/src/tests.rs@@@ -1062,526 -1028,20 +1062,536 @@@ fn clicks_in_a_row_edit_and_select_text}// 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());+ // Moving while pressed extends the selection by the unit the clicks chose (#981).+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x + 40.0, y));+ assert!(matches!(&a[..], [Action::Exec(id, p)] if id == "text.extendTo" && p["unit"] == "word" && p["frame"] == fid.0), "{a:?}");+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x + 40.0, y));+ t.pointer(&cx, &press(3));+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x + 40.0, y));+ assert!(matches!(&a[..], [Action::Exec(id, p)] if id == "text.extendTo" && p["unit"] == "line"), "{a:?}");+ // One click, then a drag: a character at a time, as before.+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x + 40.0, y));+ t.pointer(&cx, &press(1));+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x + 40.0, y));+ assert!(matches!(&a[..], [Action::Exec(id, p)] if id == "text.extendTo" && p.get("unit").is_none()), "{a:?}");}+/// 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:?}"),+ }+}++/// With text selected, the Eyedropper on a text frame picks up its text formatting instead of+/// copying the frame's fill and stroke onto the selection (InDesign's Eyedropper).+#[test]+fn eyedropper_with_text_selected_picks_up_text_formatting() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (head, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 300.0, 140.0), lid, "Header", ParaFormat::default()).unwrap();+ let (_, body) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 200.0, 300.0, 300.0), lid, "Body", ParaFormat::default()).unwrap();+ let s = Selection::text(designcraft_doc::TextSel { story: body, anchor: 0, focus: 4, frame: None, cell: None });+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));+ let off = l.xf(SpreadRef::Doc(0)).translation();+ let cx = ctx(&d, &s, &c, &l);+ let mut t = create("eyedropper");+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0 + off.x, 120.0 + off.y));+ assert_eq!(a, vec![Action::Exec("type.pickUpFormat".into(), serde_json::json!({"frame": head.0, "point": [150.0, 120.0]}))]);+}++#[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_moves_selected_content_and_the_frame_otherwise() {+ 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]);+ // With the content selected (the grabber, or a double-click), the pointer is a hand over it and+ // a drag anywhere on it moves it, as in InDesign (Dansky's Exclude Overlap tutorial, 7:13).+ let edge = spread_pt(&l, 115.0, 185.0);+ assert_eq!(t.cursor(&ctx(&d, &content, &c, &l), edge, Mods::default()), Cursor::Hand);+ 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::Begin("Move Content".into()));+ let p = preview_params(&a);+ assert_eq!((p["dx"].as_f64(), &p["content"]), (Some(30.0), &serde_json::json!(true)));+ t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Up, edge.x + 30.0, edge.y));+ // Shift keeps it on one axis; the content stays selected.+ let shift = Mods { shift: true, ..Default::default() };+ t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Down, edge.x, edge.y).with_mods(shift));+ let a = t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Drag, edge.x + 30.0, edge.y + 4.0).with_mods(shift));+ let p = preview_params(&a);+ assert_eq!((p["dx"].as_f64(), p["dy"].as_f64(), &p["content"]), (Some(30.0), Some(0.0), &serde_json::json!(true)));+ assert_eq!(+ t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Up, edge.x + 30.0, edge.y).with_mods(shift)),+ vec![Action::Commit]+ );+ // Off the content (the graphic overhangs the frame's sides only), a press selects as before.+ assert_eq!(t.cursor(&ctx(&d, &content, &c, &l), spread_pt(&l, 150.0, 250.0), Mods::default()), Cursor::Arrow);+ // With the frame selected, a drag away from the grabber moves the frame.+ t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Down, edge.x, edge.y));+ let a = t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Drag, edge.x, edge.y + 30.0));+ assert_eq!(a[0], Action::Begin("Move".into()));+ assert_eq!(preview_params(&a).get("content"), None);+}++#[test]+fn double_click_toggles_frame_and_content() {+ let mut d = Document::new(&NewDocument::default());+ let f = graphic_frame(&mut d);+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));+ let at = spread_pt(&l, 120.0, 180.0);+ let mut t = create("selection");+ let frame = Selection::items(vec![f]);+ let content = Selection { content: true, ..Selection::items(vec![f]) };+ let set = |content: bool| vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": content}))];+ // The canvas's presses in a row: the first selects the frame, the second its content.+ let a = t.pointer(&ctx(&d, &Selection::default(), &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y));+ assert_eq!(a, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": false}))]);+ t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Up, at.x, at.y));+ assert_eq!(t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y).with_clicks(2)), set(true));+ assert!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Up, at.x, at.y)).is_empty());+ // With the content selected, the first press keeps it and the second selects the frame.+ assert!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y)).is_empty());+ t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Up, at.x, at.y));+ assert_eq!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y).with_clicks(2)), set(false));+ // A double click sent as such (control channel) toggles too.+ let dbl = PointerEvent::new(PointerKind::DoubleClick, at.x, at.y);+ assert_eq!(t.pointer(&ctx(&d, &frame, &c, &l), &dbl), set(true));+ assert_eq!(t.pointer(&ctx(&d, &content, &c, &l), &dbl), set(false));+}++/// A 200 × 150 pt rectangle frame, selected.+fn live_corner_doc() -> (Document, ItemId) {+ let mut d = Document::new(&NewDocument::default());+ let id = add_rect(&mut d, Rect::new(100.0, 100.0, 300.0, 250.0));+ (d, id)+}++fn corner_preview(a: &[Action]) -> Vec<(String, f64)> {+ let p = match a {+ [Action::Preview(cmd, p)] | [Action::Exec(cmd, p)] if cmd == "object.cornerOptions" => p,+ other => panic!("{other:?}"),+ };+ p["corners"].as_array().unwrap().iter().map(|c| (c["shape"].as_str().unwrap().to_string(), c["size"].as_f64().unwrap())).collect()+}++fn diamonds(o: &[Overlay]) -> Vec<Point> {+ o.iter().filter_map(|o| if let Overlay::LiveCornerDiamond(p) = o { Some(*p) } else { None }).collect()+}++#[test]+fn live_corners_click_widget_then_drag_rounds_all_corners() {+ let (d, id) = live_corner_doc();+ let s = Selection { items: vec![id], ..Default::default() };+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));+ let cx = ctx(&d, &s, &c, &l);+ let at = |x, y| spread_pt(&l, x, y);+ let mut t = create("selection");+ // The widget sits on the right edge, a little below the top-right corner.+ let w = at(300.0, 111.5);+ assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::LiveCornerWidget(p) if near(*p, w))));+ assert!(diamonds(&t.overlays(&cx)).is_empty());+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y)), vec![Action::Handled]);+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y)).is_empty());+ // Without corner sizes the diamonds sit 12 px along the top and bottom edges.+ let want = [at(112.0, 100.0), at(288.0, 100.0), at(288.0, 250.0), at(112.0, 250.0)];+ let got = diamonds(&t.overlays(&cx));+ assert!(got.len() == 4 && got.iter().zip(want).all(|(g, w)| near(*g, w)), "{got:?}");+ assert!(!t.overlays(&cx).iter().any(|o| matches!(o, Overlay::LiveCornerWidget(_))));+ // Drag the top-left diamond 20 pt toward the centre.+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, want[0].x, want[0].y));+ assert_eq!(a, vec![Action::Begin("Corner Options".into())]);+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, want[0].x + 20.0, want[0].y + 3.0));+ assert_eq!(corner_preview(&a), vec![("rounded".to_string(), 20.0); 4]);+ // The size stops at half the shorter side.+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, want[0].x + 500.0, want[0].y));+ assert_eq!(corner_preview(&a), vec![("rounded".to_string(), 75.0); 4]);+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, want[0].x + 500.0, want[0].y)), vec![Action::Commit]);+}++#[test]+fn live_corners_shift_drag_and_alt_click_change_one_corner() {+ let (mut d, id) = live_corner_doc();+ d.item_mut(id).unwrap().corners = designcraft_geom::corners::CornerOptions::uniform(designcraft_geom::corners::CornerShape::Rounded, 30.0);+ let s = Selection { items: vec![id], ..Default::default() };+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));+ let cx = ctx(&d, &s, &c, &l);+ let at = |x, y| spread_pt(&l, x, y);+ let mut t = create("selection");+ let w = at(300.0, 111.5);+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y));+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y));+ // With 30 pt corners the diamonds sit 30 pt along the edges.+ let tr = at(270.0, 100.0);+ assert!(diamonds(&t.overlays(&cx)).iter().any(|p| near(*p, tr)));+ let shift = Mods { shift: true, ..Default::default() };+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, tr.x, tr.y).with_mods(shift));+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, tr.x - 10.0, tr.y).with_mods(shift));+ let r = |n: f64| ("rounded".to_string(), n);+ assert_eq!(corner_preview(&a), vec![r(30.0), r(40.0), r(30.0), r(30.0)]);+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, tr.x - 10.0, tr.y));+ // Alt-click steps the bottom-right corner's shape; Shift+Alt steps every corner.+ let br = at(270.0, 250.0);+ let alt = Mods { alt: true, ..Default::default() };+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, br.x, br.y).with_mods(alt));+ assert_eq!(corner_preview(&a), vec![r(30.0), r(30.0), ("inverseRounded".to_string(), 30.0), r(30.0)]);+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, br.x - 30.0, br.y).with_mods(alt)).is_empty());+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, br.x - 30.0, br.y)).is_empty());+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, br.x, br.y).with_mods(Mods { alt: true, shift: true, ..Default::default() }));+ assert_eq!(corner_preview(&a), vec![("inverseRounded".to_string(), 30.0); 4]);+}++#[test]+fn live_corners_end_on_escape_empty_click_and_other_selection() {+ let (mut d, id) = live_corner_doc();+ let other = add_rect(&mut d, Rect::new(400.0, 100.0, 500.0, 200.0));+ let s = Selection { items: vec![id], ..Default::default() };+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));+ let cx = ctx(&d, &s, &c, &l);+ let w = spread_pt(&l, 300.0, 111.5);+ let mut t = create("selection");+ let enter = |t: &mut Box<dyn Tool>| {+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y));+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y));+ assert_eq!(diamonds(&t.overlays(&cx)).len(), 4);+ };+ // Escape leaves corner editing and keeps the selection; the next Escape deselects.+ enter(&mut t);+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Handled]);+ assert!(diamonds(&t.overlays(&cx)).is_empty());+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": []}))]);+ // A click on empty canvas.+ enter(&mut t);+ let e = spread_pt(&l, 350.0, 400.0);+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, e.x, e.y));+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, e.x, e.y));+ assert!(diamonds(&t.overlays(&cx)).is_empty());+ // Another selection.+ enter(&mut t);+ let s2 = Selection { items: vec![other], ..Default::default() };+ let cx2 = ctx(&d, &s2, &c, &l);+ assert!(diamonds(&t.overlays(&cx2)).is_empty());+ t.pointer(&cx2, &PointerEvent::new(PointerKind::Move, 0.0, 0.0));+ assert!(diamonds(&t.overlays(&cx)).is_empty());+ // A frame too small on screen has no widget.+ let mut far = ctx(&d, &s, &c, &l);+ far.zoom = 0.1;+ assert!(!t.overlays(&far).iter().any(|o| matches!(o, Overlay::LiveCornerWidget(_))));+}++#[test]+fn live_corner_diamonds_follow_a_rotated_frame() {+ let mut d = Document::new(&NewDocument::default());+ let id = add_rotated(&mut d, Rect::new(100.0, 100.0, 300.0, 250.0), 30.0);+ let s = Selection { items: vec![id], ..Default::default() };+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));+ let cx = ctx(&d, &s, &c, &l);+ let m = l.xf(SpreadRef::Doc(0)) * d.item(id).unwrap().xf;+ let mut t = create("selection");+ // The widget: 11.5 pt from the top-right corner along the turned right edge.+ let w = m * Point::new(300.0, 111.5);+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y));+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y));+ let tl = m * Point::new(112.0, 100.0);+ assert!(diamonds(&t.overlays(&cx)).iter().any(|p| near(*p, tl)), "{:?}", t.overlays(&cx));+ // Dragging along the turned top edge sets the size.+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, tl.x, tl.y));+ let to = m * Point::new(137.0, 100.0);+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.x, to.y));+ let got = corner_preview(&a);+ assert!(got.iter().all(|(shape, size)| shape == "rounded" && (size - 25.0).abs() < 1e-6), "{got:?}");+}++#[test]+fn pen_cursor_shows_add_delete_and_close() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (fid, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 200.0, 200.0), lid, "", ParaFormat::default()).unwrap();+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));+ let selected = Selection::items(vec![fid]);+ let none = Selection::default();+ let off = l.xf(SpreadRef::Doc(0)).translation();+ let at = |x: f64, y: f64| Point::new(x + off.x, y + off.y);+ let mut t = create("pen");+ let m = Mods::default();++ let cx = ctx(&d, &selected, &c, &l);+ assert_eq!(t.cursor(&cx, at(200.0, 100.0), m), Cursor::PenDelete, "on a selected path's anchor");+ assert_eq!(t.cursor(&cx, at(150.0, 101.0), m), Cursor::PenAdd, "on a selected path's outline");+ assert_eq!(t.cursor(&cx, at(150.0, 150.0), m), Cursor::Pen, "inside, away from the outline");+ let click = |t: &mut Box<dyn Tool>, cx: &ToolContext, p: Point| {+ let down = t.pointer(cx, &PointerEvent::new(PointerKind::Down, p.x, p.y));+ let up = t.pointer(cx, &PointerEvent::new(PointerKind::Up, p.x, p.y));+ (down, up)+ };+ let (down, up) = click(&mut t, &cx, at(200.0, 100.0));+ assert_eq!(down, vec![Action::Exec("path.deleteAnchor".into(), serde_json::json!({"id": fid.0, "subpath": 0, "anchor": 1}))]);+ assert!(up.is_empty() && !t.busy(), "deleting starts no path");+ let (down, _) = click(&mut t, &cx, at(150.0, 101.0));+ assert!(matches!(&down[..], [Action::Exec(cmd, p)] if cmd == "path.addAnchor" && p["id"] == fid.0), "{down:?}");++ // Unselected paths are drawn over; the first anchor of the path being drawn closes it.+ let cx = ctx(&d, &none, &c, &l);+ assert_eq!(t.cursor(&cx, at(200.0, 100.0), m), Cursor::Pen, "unselected path");+ click(&mut t, &cx, at(300.0, 300.0));+ assert_eq!(t.cursor(&cx, at(300.0, 300.0), m), Cursor::Pen, "one anchor cannot close yet");+ click(&mut t, &cx, at(400.0, 300.0));+ assert_eq!(t.cursor(&cx, at(301.0, 301.0), m), Cursor::PenClose, "on the first anchor");+ assert_eq!(t.cursor(&cx, at(350.0, 350.0), m), Cursor::Pen, "elsewhere while drawing");+}++#[test]+fn anchor_tools_show_pen_state_cursors() {+ let d = Document::new(&NewDocument::default());+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));+ let cx = ctx(&d, &s, &c, &l);+ let p = Point::new(10.0, 10.0);+ let cursor = |id: &str| create(id).cursor(&cx, p, Mods::default());+ assert_eq!(cursor("addAnchor"), Cursor::PenAdd);+ assert_eq!(cursor("deleteAnchor"), Cursor::PenDelete);+ assert_eq!(cursor("convertDirection"), Cursor::PenConvert);+}++/// A text frame holding a 3×3 table of 80 pt columns, optionally rotated about its centre.+fn table_frame(degrees: f64) -> (Document, ItemId) {+ let mut d = Document::new(&NewDocument::default());+ let layer = d.default_layer();+ let (id, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 400.0, 400.0), layer, "", ParaFormat::default()).unwrap();+ let tid = d.alloc();+ d.story_mut(sid).unwrap().insert_table(0, designcraft_doc::Table::new(tid, 3, 3, 0, 0, 240.0));+ d.item_mut(id).unwrap().xf = designcraft_geom::Affine::rotate_about(degrees.to_radians(), Point::new(250.0, 250.0));+ (d, id)+}++#[test]+fn type_tool_drags_a_table_column_border() {+ for degrees in [0.0, 90.0] {+ let (d, id) = table_frame(degrees);+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));+ let cx = ctx(&d, &s, &c, &l);+ let it = d.item(id).unwrap();+ let sid = it.text_frame().unwrap().story;+ let cs = c.get(&d, sid, None);+ let cell = cs.frames[0].tables[0].cell(1, 0).unwrap();+ let xf = cx.item_canvas_xf(id).unwrap() * d.text_xf(it);+ let on_border = xf * Point::new(cell.rect.x1 + 1.0, (cell.rect.y0 + cell.rect.y1) / 2.0);+ let dragged = xf * Point::new(cell.rect.x1 + 21.0, (cell.rect.y0 + cell.rect.y1) / 2.0);+ let mut t = create("type");+ let expected = if degrees == 0.0 { Cursor::ResizeH } else { Cursor::ResizeV };+ assert_eq!(t.cursor(&cx, on_border, Mods::default()), expected);+ // A click with a 1 px wobble on the border changes nothing.+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on_border.x, on_border.y)).is_empty());+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, on_border.x + 1.0, on_border.y)).is_empty());+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, on_border.x + 1.0, on_border.y)).is_empty());+ // A press on the border starts a resize, not a text selection.+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on_border.x, on_border.y)).is_empty());+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, dragged.x, dragged.y));+ assert_eq!(a[0], Action::Begin("Resize Column".into()));+ let Action::Preview(cmd, p) = &a[1] else { panic!("{a:?}") };+ assert_eq!(+ (cmd.as_str(), &p["axis"], &p["index"], &p["frame"]),+ ("table.resizeBorder", &serde_json::json!("column"), &serde_json::json!(0), &serde_json::json!(id.0))+ );+ assert!((p["delta"].as_f64().unwrap() - 20.0).abs() < 1e-6, "{p}");+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, dragged.x, dragged.y)), vec![Action::Commit]);+ // Esc cancels a drag in progress.+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on_border.x, on_border.y));+ t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, dragged.x, dragged.y));+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, dragged.x, dragged.y)).is_empty());+ // Inside the cell the Type tool places the caret as usual.+ let inside = xf * Point::new(cell.rect.x0 + 20.0, (cell.rect.y0 + cell.rect.y1) / 2.0);+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, inside.x, inside.y));+ assert!(matches!(&a[..], [Action::Exec(cmd, _)] if cmd == "text.placeCaret"), "{a:?}");+ }+}++#[test]+fn eyedropper_samples_a_placed_image_and_matches_other_objects() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let photo = ItemId(d.alloc());+ let mut it = Item::new(photo, lid, Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)));+ it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {+ asset: designcraft_doc::AssetId(1),+ size: (100.0, 100.0),+ xf: designcraft_geom::Affine::translate((0.0, 0.0)),+ clip: None,+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [0.0; 4],+ wrap: Default::default(),+ });+ d.assets.insert(+ designcraft_doc::AssetId(1),+ std::sync::Arc::new(designcraft_doc::Asset {+ id: designcraft_doc::AssetId(1),+ name: "photo.png".into(),+ mime: "image/png".into(),+ link: None,+ data: std::sync::Arc::new(vec![]),+ pixels: Some((100, 100)),+ page: 0,+ pdf_crop: Default::default(),+ pdf_box: None,+ }),+ );+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ // An unfilled text frame over part of the photo lets it show through.+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(150.0, 150.0, 250.0, 250.0), lid, "x", ParaFormat::default()).unwrap();+ let swatch = add_rect(&mut d, Rect::new(300.0, 100.0, 350.0, 150.0));+ d.item_mut(swatch).unwrap().fill.swatch = "[Black]".into();+ let target = add_rect(&mut d, Rect::new(400.0, 100.0, 450.0, 150.0));+ // The photo's layer is locked: sampling it still works.+ d.layers.iter_mut().for_each(|l| l.locked = true);+ let s = Selection { items: vec![target], ..Default::default() };+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));+ let off = l.xf(SpreadRef::Doc(0)).translation();+ let cx = ctx(&d, &s, &c, &l);+ let mut t = create("eyedropper");+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));+ let sample = |x: f64, y: f64| Action::Exec("color.sample".into(), serde_json::json!({"at": [x, y], "spread": {"kind": "doc", "index": 0}}));+ assert_eq!(a, vec![sample(120.0, 130.0)]);+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 180.0 + off.x, 180.0 + off.y));+ assert_eq!(a, vec![sample(180.0, 180.0)], "through the text frame");+ // With the toolbox's Stroke box in front, the colour goes to the stroke (a line has no fill).+ let mut cx_stroke = ctx(&d, &s, &c, &l);+ cx_stroke.stroke_in_front = true;+ let a = t.pointer(&cx_stroke, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));+ assert_eq!(+ a,+ vec![Action::Exec(+ "color.sample".into(),+ serde_json::json!({"at": [120.0, 130.0], "spread": {"kind": "doc", "index": 0}, "target": "stroke"})+ )]+ );+ // A filled object is matched as before (here on a locked layer: not reachable, so nothing).+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 320.0 + off.x, 120.0 + off.y)).is_empty());+ let mut d2 = d.clone();+ d2.layers.iter_mut().for_each(|l| l.locked = false);+ let cx = ctx(&d2, &s, &c, &l);+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 320.0 + off.x, 120.0 + off.y));+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": swatch.0}))]);+ // An image the pointer can reach names its frame, whose attributes apply where no pixel shows.+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));+ let sampled = serde_json::json!({"at": [120.0, 130.0], "spread": {"kind": "doc", "index": 0}, "matchFrom": photo.0});+ assert_eq!(a, vec![Action::Exec("color.sample".into(), sampled)]);+ // Vector graphics and missing assets must retain the ordinary attribute-matching path.+ for mime in ["application/pdf", "application/postscript", "image/svg+xml", "application/octet-stream"] {+ std::sync::Arc::make_mut(d2.assets.get_mut(&designcraft_doc::AssetId(1)).unwrap()).mime = mime.into();+ let cx = ctx(&d2, &s, &c, &l);+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": photo.0}))], "{mime}");+ }+ d2.assets.clear();+ let cx = ctx(&d2, &s, &c, &l);+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": photo.0}))]);+}++#[test]+fn double_clicking_a_handle_fits_the_frame_to_its_content_along_that_side() {+ let mut d = Document::new(&NewDocument::default());+ let id = add_rect(&mut d, Rect::new(100.0, 100.0, 300.0, 200.0));+ let s = Selection { items: vec![id], ..Default::default() };+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));+ let off = l.xf(SpreadRef::Doc(0)).translation();+ let cx = ctx(&d, &s, &c, &l);+ let mut t = create("selection");+ for ((x, y), axis) in [((300.0, 200.0), "both"), ((200.0, 200.0), "height"), ((300.0, 150.0), "width")] {+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, x + off.x, y + off.y));+ assert_eq!(a, vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis}))], "{axis}");+ }+}++#[test]+fn fitting_handle_axes_follow_spread_and_frame_rotation() {+ for spread_turn in 0..4 {+ for frame_turn in 0..4 {+ let mut d = Document::new(&NewDocument::default());+ let id = add_rect(&mut d, Rect::new(100.0, 100.0, 300.0, 200.0));+ d.item_mut(id).unwrap().xf = designcraft_geom::Affine::rotate(f64::from(frame_turn) * std::f64::consts::FRAC_PI_2);+ Arc::make_mut(&mut d.spreads[0]).pages[0].view_rotation = spread_turn;+ let s = Selection { items: vec![id], ..Default::default() };+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));+ let cx = ctx(&d, &s, &c, &l);+ let b = cx.selection_bounds().unwrap();+ let mut t = create("selection");+ let swapped = (spread_turn + frame_turn) % 2 == 1;+ for (index, axis) in [(1, if swapped { "width" } else { "height" }), (3, if swapped { "height" } else { "width" }), (4, "both")] {+ let p = select::handles(b)[index];+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, p.x, p.y));+ assert_eq!(+ a,+ vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis}))],+ "spread={spread_turn}, frame={frame_turn}, handle={index}"+ );+ }+ }+ }+}+#[test]fn pen_continues_an_open_path_from_either_end_point() {let mut d = Document::new(&NewDocument::default());diff --cc crates/tools/src/text.rsindex 046853e01,f6ab646ba..56658f41e--- a/crates/tools/src/text.rs+++ b/crates/tools/src/text.rs@@@ -36,89 -19,9 +36,90 @@@ pub struct TypeToolcell_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,+ /// The press selected a word, line, paragraph or story (several clicks): a drag extends the+ /// selection by that unit (#981).+ unit: Option<&'static str>,+ 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: 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 = 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?@@@ -223,14 -50,7 +224,14 @@@ impl Tool for TypeToolself.drawing = false;self.selecting = None;self.cell_drag = None;- self.unit_selected = false;+ self.unit = None;+ self.border = None;+ if ev.kind == PointerKind::Down+ && let Some(b) = border_at(cx, ev.pos)+ {+ self.border = Some(b);+ return vec![];+ }// Text frames take the caret (locked ones too, as in InDesign); an empty frame// becomes one, unless it's locked: then the press draws a new text frame over it.if let Some((_, id)) = cx.hit(ev.pos)@@@ -265,14 -85,7 +266,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() || self.unit_selected {+ if self.cell_drag.is_some() {return vec![];}if let Some(fid) = self.selecting {