Skip to content

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

Merge canvas-focus-lock: Canvas: arrow keys and Tab keep keyboard focus on the canvas

aionggbf2708e8cf02
diff --cc crates/ui-egui/src/canvas.rs
index 576fddc57,1935d6de0..d48c67d3d
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@@ -1938,24 -1443,21 +1938,29 @@@ fn handle_input(app: &mut DesignApp, ui
if resp.clicked() || resp.drag_started() {
resp.request_focus();
}
+ // Arrow keys, Tab and Escape belong to the canvas (caret, nudge, tab character, deselect).
+ // Without the lock egui moves focus to a neighbouring widget, and the next Space or Return
+ // clicks it while typing still reaches the text.
+ let lock = egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true };
+ ui.memory_mut(|m| m.set_focus_lock_filter(resp.id, lock));
- // Both split panes show the same document, but only the focused pane dispatches its keys.
- if app.pane != app.focus_pane || (ui.ctx().text_edit_focused() && !resp.has_focus()) {
+ // Keyboard for the active tool.
+ if menu_open || (ui.ctx().text_edit_focused() && !resp.has_focus()) || !keyboard_pane(app) {
return;
}
+ // Keys of a frame that began composing are the IME's too (a Backspace that empties the marked
+ // text must not delete the character before it).
+ let composing_at_start = app.session.tool_composing();
let evs = ui.input(|i| i.events.clone());
for e in evs {
+ let composing = composing_at_start || app.session.tool_composing();
match e {
- egui::Event::Text(t) if wants_text => {
+ egui::Event::Ime(ime) if wants_text => ime_event(app, ime, vi),
+ // Keys the IME passes through come as text only while nothing is marked.
+ egui::Event::Text(t) if wants_text && !composing => {
let _ = app.run("text.insert", json!({"text": t}));
}
+ // The IME owns the keyboard until it commits: no typing, clipboard or editing keys.
+ egui::Event::Text(_) | egui::Event::Paste(_) | egui::Event::Copy | egui::Event::Cut | egui::Event::Key { .. } if composing => {}
egui::Event::Paste(t) if wants_text => {
// Formatted when the system clipboard still holds what was copied here;
// Shift (⇧⌘V) pastes without formatting.
@@@ -2626,487 -1803,46 +2631,527 @@@ mod tests
}
}
+ /// The live-corner widget draws on a selected rectangle frame; clicking it draws the diamonds.
+ #[test]
+ fn live_corner_widget_and_diamonds_draw() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ app.run("frame.create", json!({"rect": [100, 100, 300, 250], "content": "graphic"})).unwrap();
+ let id = app.session.doc().unwrap().doc.spreads[0].items[0].id;
+ app.run("selection.set", json!({"ids": [id.0]})).unwrap();
+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_pixels_per_point(1.0).wgpu().build_ui_state(
+ |ui, app: &mut DesignApp| {
+ let ctx = ui.ctx().clone();
+ app.logic(&ctx);
+ app.ui(ui);
+ },
+ app,
+ );
+ h.run_steps(4);
+ let screen = |h: &Harness<'_, DesignApp>, x: f64, y: f64| {
+ let app = h.state();
+ let layout = CanvasLayout::new(&app.session.doc().unwrap().doc, false);
+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
+ xf.to_screen(layout.to_canvas(SpreadRef::Doc(0), Point::new(x, y)))
+ };
+ let widget = screen(&h, 300.0, 100.0) + vec2(0.0, 11.5);
+ let diamond = screen(&h, 100.0, 100.0) + vec2(12.0, 0.0);
+ let yellow = |h: &mut Harness<'_, DesignApp>, p: Pos2| -> Option<bool> {
+ let img = match h.render() {
+ Ok(img) => img,
+ Err(e) => {
+ eprintln!("skipped: no offscreen renderer ({e})");
+ return None;
+ }
+ };
+ let px = img.get_pixel(p.x.round() as u32, p.y.round() as u32).0;
+ Some(px[0] > 200 && px[1] > 180 && px[2] < 100)
+ };
+ let Some(w) = yellow(&mut h, widget) else { return };
+ assert!(w, "no widget at {widget:?}");
+ assert_eq!(yellow(&mut h, diamond), Some(false));
+ h.hover_at(widget);
+ h.step();
+ for pressed in [true, false] {
+ h.event(egui::Event::PointerButton { pos: widget, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
+ h.step();
+ }
+ h.run_steps(3);
+ assert_eq!(yellow(&mut h, diamond), Some(true), "no diamond at {diamond:?}");
+ assert_eq!(yellow(&mut h, widget), Some(false));
+ }
+
+ /// A harness whose frames are 1 ms apart, so two clicks make a double-click.
+ fn fast_harness(app: DesignApp) -> Harness<'static, DesignApp> {
+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(0.001).build_ui_state(
+ |ui, app: &mut DesignApp| {
+ let ctx = ui.ctx().clone();
+ app.logic(&ctx);
+ app.ui(ui);
+ },
+ app,
+ );
+ h.run_steps(4);
+ h
+ }
+
+ fn primary(h: &mut Harness<'_, DesignApp>, pos: Pos2, pressed: bool) {
+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
+ h.run_steps(2);
+ }
+
+ fn corner_drag(h: &mut Harness<'_, DesignApp>, from: Pos2, to: Pos2) {
+ h.hover_at(from);
+ h.step();
+ primary(h, from, true);
+ h.event(egui::Event::PointerMoved(from + (to - from) / 2.0));
+ h.run_steps(2);
+ h.event(egui::Event::PointerMoved(to));
+ h.run_steps(2);
+ primary(h, to, false);
+ }
+
+ fn corner_click(h: &mut Harness<'_, DesignApp>, p: Pos2) {
+ h.hover_at(p);
+ h.step();
+ primary(h, p, true);
+ primary(h, p, false);
+ }
+
+ /// Where the rulers measure from (canvas coordinates): the document's zero point on the
+ /// spread in view (its first page, for a page origin).
+ fn ruler_zero(app: &DesignApp, doc: &Document, layout: &CanvasLayout) -> Option<Point> {
+ ruler_pieces(app, doc, layout, doc.zero_point()).first().map(|p| p.2)
+ }
+
+ fn zero_point(h: &Harness<'_, DesignApp>) -> [f64; 2] {
+ h.state().session.doc().unwrap().doc.settings.zero_point
+ }
+
+ #[test]
+ fn the_ruler_corner_drags_resets_and_locks_the_zero_point() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"pages": 3})).unwrap();
+ let mut h = fast_harness(app);
+ let rect = h.state().canvas_rect.unwrap();
+ let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0);
+ // A click that stays in the corner leaves the zero point.
+ corner_click(&mut h, corner);
+ assert_eq!(zero_point(&h), [0.0, 0.0]);
+ // Dragged out, it lands where released, measured from the spread in view.
+ let dest = rect.min + vec2(80.0, 50.0);
+ let expected = {
+ let app = h.state();
+ let st = app.session.active().unwrap();
+ let layout = CanvasLayout::new(&st.doc, false);
+ let slot = layout.slots[current_slot(app, &layout).unwrap()];
+ let sp = slot.to_spread(Xf::new(rect, app.view().unwrap()).to_canvas(dest));
+ let b = st.doc.spread(slot.spread).unwrap().bounds();
+ [sp.x - b.x0, sp.y - b.y0]
+ };
+ corner_drag(&mut h, corner, dest);
+ let zp = zero_point(&h);
+ assert!((zp[0] - expected[0]).abs() < 0.5 && (zp[1] - expected[1]).abs() < 0.5, "{zp:?} vs {expected:?}");
+ assert!(zp[0].abs() > 1.0 && zp[1].abs() > 1.0, "moved: {zp:?}");
+ // The rulers measure from the point it was dropped on.
+ {
+ let app = h.state();
+ let st = app.session.active().unwrap();
+ let layout = CanvasLayout::new(&st.doc, false);
+ let o = ruler_zero(app, &st.doc, &layout).unwrap();
+ let on_screen = Xf::new(rect, app.view().unwrap()).to_screen(o);
+ assert!((on_screen - dest).length() < 0.5, "{on_screen:?} vs {dest:?}");
+ }
+ // A double-click resets it.
+ corner_click(&mut h, corner);
+ corner_click(&mut h, corner);
+ assert_eq!(zero_point(&h), [0.0, 0.0]);
+ // Locked from the corner's context menu, the corner ignores drags and double-clicks.
+ right_click(&mut h, corner);
+ h.get_by_label("Lock Zero Point").click();
+ h.run_steps(3);
+ assert!(h.state().session.doc().unwrap().doc.settings.zero_point_locked);
+ corner_drag(&mut h, corner, dest);
+ assert_eq!(zero_point(&h), [0.0, 0.0]);
+ // Unlocked again from the same menu.
+ right_click(&mut h, corner);
+ h.get_by_label("Unlock Zero Point").click();
+ h.run_steps(3);
+ corner_drag(&mut h, corner, dest);
+ assert_ne!(zero_point(&h), [0.0, 0.0]);
+ h.state_mut().run("view.lockZeroPoint", json!({"on": true})).unwrap();
+ corner_click(&mut h, corner);
+ corner_click(&mut h, corner);
+ assert_ne!(zero_point(&h), [0.0, 0.0], "a locked zero point isn't reset");
+ }
+
+ #[test]
+ fn cmd_dragging_the_ruler_corner_makes_a_guide_each_way() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let mut h = harness(app);
+ let rect = h.state().canvas_rect.unwrap();
+ let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0);
+ let dest = rect.min + vec2(120.0, 90.0);
+ let (r, at) = {
+ let app = h.state();
+ let st = app.session.active().unwrap();
+ CanvasLayout::new(&st.doc, false).spread_at(Xf::new(rect, app.view().unwrap()).to_canvas(dest)).unwrap()
+ };
+ h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND));
+ h.step();
+ corner_drag(&mut h, corner, dest);
+ h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
+ h.step();
+ let doc = h.state().session.doc().unwrap().doc.clone();
+ let guides: Vec<_> = doc.spread(r).unwrap().pages.iter().flat_map(|p| p.guides.clone()).collect();
+ assert_eq!(guides.len(), 2, "{guides:?}");
+ let pos = |o: designcraft_doc::Orientation| guides.iter().find(|g| g.orientation == o).map(|g| g.position).unwrap();
+ assert!((pos(designcraft_doc::Orientation::Horizontal) - at.y).abs() < 0.5);
+ assert!((pos(designcraft_doc::Orientation::Vertical) - at.x).abs() < 0.5);
+ assert!(guides.iter().all(|g| g.spread));
+ assert_eq!(doc.settings.zero_point, [0.0, 0.0], "the zero point stays");
+ }
+
+ #[test]
+ fn rulers_and_xy_fields_measure_from_the_zero_point_on_every_spread() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ // Spread 0: page 1; spread 1: pages 2 and 3.
+ app.run("file.new", json!({"pages": 3})).unwrap();
+ app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap();
+ app.session.prefs.dimensions_include_stroke = false;
+ let mut h = harness(app);
+ let rect = h.state().canvas_rect.unwrap();
+ for (spread, x0) in [(0usize, 136.0), (1, 736.0)] {
+ let app = h.state_mut();
+ let id = app.run("frame.create", json!({"spread": spread, "rect": [x0, 70, x0 + 50.0, 120]})).unwrap()["id"].clone();
+ app.run("selection.set", json!({"ids": [id]})).unwrap();
+ // X/Y (Control, Properties and Info panels).
+ let r = crate::panels::sel_info(app).unwrap().page_rect;
+ assert!((r.x0 - (x0 - 100.0)).abs() < 1e-6 && (r.y0 - 20.0).abs() < 1e-6, "spread {spread}: {r:?}");
+ // The rulers, with that spread in view.
+ let layout = CanvasLayout::new(&app.session.active().unwrap().doc, false);
+ let slot = layout.slots[spread];
+ let v = app.view_mut().unwrap();
+ let zoom = v.zoom;
+ let c = slot.bounds.center();
+ v.origin = Point::new(c.x - rect.width() as f64 / 2.0 / zoom, c.y - rect.height() as f64 / 2.0 / zoom);
+ h.run_steps(2);
+ let app = h.state();
+ let doc = app.session.active().unwrap().doc.clone();
+ assert_eq!(current_slot(app, &layout), Some(spread));
+ let o = ruler_zero(app, &doc, &layout).unwrap();
+ assert!((o.x - slot.bounds.x0 - 100.0).abs() < 1e-6 && (o.y - slot.bounds.y0 - 50.0).abs() < 1e-6, "spread {spread}: {o:?}");
+ }
+ }
+
+ /// Screen position of spread 0's point (x, y).
+ fn screen_of(h: &Harness<'_, DesignApp>, x: f64, y: f64) -> Pos2 {
+ let app = h.state();
+ let st = app.session.active().unwrap();
+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
+ xf.to_screen(CanvasLayout::new(&st.doc, st.editing_parents).xf(SpreadRef::Doc(0)) * Point::new(x, y))
+ }
+
+ /// A menu row: a button that isn't a toggle, named by its label, then its shortcut if it has
+ /// one. Toggle buttons with the same name (the Task Bar's icons) don't match.
+ fn menu_row<'h>(h: &'h Harness<'_, DesignApp>, label: &'h str) -> Option<egui_kittest::Node<'h>> {
+ h.query_by(move |n| {
+ n.role() == egui::accesskit::Role::Button
+ && n.toggled().is_none()
+ && n.label().is_some_and(|l| l == label || l.strip_prefix(label).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.contains(' ')))
+ })
+ }
+
+ fn enabled(h: &Harness<'_, DesignApp>, label: &str) -> bool {
+ use egui_kittest::kittest::NodeT;
+ !menu_row(h, label).unwrap_or_else(|| panic!("no menu row {label}")).accesskit_node().is_disabled()
+ }
+
+ fn spread_items(h: &Harness<'_, DesignApp>) -> Vec<u64> {
+ h.state().session.doc().unwrap().doc.spreads[0].items.iter().map(|i| i.id.0).collect()
+ }
+
+ fn selected(h: &Harness<'_, DesignApp>) -> Vec<u64> {
+ h.state().session.doc().unwrap().selection.items.iter().map(|i| i.0).collect()
+ }
+
+ #[test]
+ fn right_clicking_an_object_selects_it_and_its_menu_arranges_it() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();
+ let b = app.run("frame.create", json!({"rect": [150, 150, 300, 300]})).unwrap()["id"].as_u64().unwrap();
+ let mut h = harness(app);
+ assert_eq!(selected(&h), [b]);
+ let on_a = screen_of(&h, 60.0, 60.0);
+ right_click(&mut h, on_a);
+ assert_eq!(selected(&h), [a], "the object under the pointer is selected first");
+ // An empty frame's menu: Content, but no Fitting (nothing to fit) and no text frame entries.
+ assert!(menu_row(&h, "Content").is_some());
+ assert!(menu_row(&h, "Fitting").is_none() && menu_row(&h, "Text Frame Options…").is_none());
+ // Paste is available with nothing copied here: the system clipboard may hold another app's text.
+ assert!(enabled(&h, "Copy") && enabled(&h, "Paste"));
+ menu_row(&h, "Arrange").unwrap().click();
+ h.run_steps(3);
+ menu_row(&h, "Bring to Front").unwrap().click();
+ h.run_steps(3);
+ assert_eq!(spread_items(&h), [b, a]);
+ assert!(menu_row(&h, "Arrange").is_none(), "choosing an entry closes the menu");
+ }
+
+ #[test]
+ fn right_clicking_empty_canvas_offers_paste_after_a_copy() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();
+ app.run("edit.copy", json!({})).unwrap();
+ app.select_tool("rectangleFrame");
+ let mut h = harness(app);
+ let empty = screen_of(&h, 400.0, 500.0);
+ right_click(&mut h, empty);
+ assert_eq!(selected(&h), [a], "a right-click on nothing keeps the selection");
+ assert!(menu_row(&h, "Arrange").is_none(), "the page menu, not the object menu");
+ assert!(enabled(&h, "Paste in Place"));
+ assert!(menu_row(&h, "✓ Show/Hide Rulers").is_some(), "toggles show their state");
+ // Escape closes the menu and does nothing else: the tool would deselect, the shortcuts
+ // would switch to the Selection tool.
+ h.key_press(egui::Key::Escape);
+ h.run_steps(3);
+ assert!(menu_row(&h, "Paste in Place").is_none());
+ assert_eq!((h.state().session.tool_id(), selected(&h)), ("rectangleFrame", vec![a]));
+ right_click(&mut h, empty);
+ menu_row(&h, "Paste").unwrap().click();
+ h.run_steps(3);
+ assert_eq!(spread_items(&h).len(), 2);
+ }
+
+ #[test]
+ fn right_clicking_another_object_while_the_menu_is_open_reopens_it_there() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();
+ let b = app.run("frame.create", json!({"rect": [36, 600, 200, 760]})).unwrap()["id"].as_u64().unwrap();
+ let mut h = harness(app);
+ // The menu opens down from A, with the pointer on its first row (no submenu open); B is below it.
+ let (on_a, on_b) = (screen_of(&h, 60.0, 60.0), screen_of(&h, 50.0, 700.0));
+ right_click(&mut h, on_a);
+ assert_eq!(selected(&h), [a]);
+ assert!(menu_row(&h, "Arrange").is_some());
+ right_click(&mut h, on_b);
+ assert_eq!(selected(&h), [b]);
+ assert!(menu_row(&h, "Arrange").is_some(), "the menu reopens at the new click");
+ }
+
+ #[test]
+ fn a_context_menu_in_one_pane_keeps_the_keys_from_the_other() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let a = app.run("frame.create", json!({"rect": [36, 36, 100, 100]})).unwrap()["id"].as_u64().unwrap();
+ app.select_tool("rectangleFrame");
+ app.split = true;
+ let mut h = harness(app);
+ // The focused pane is the left one; this point is near its right edge, away from the frame.
+ let left = h.state().canvas_rect.unwrap();
+ right_click(&mut h, pos2(left.max.x - 40.0, left.center().y));
+ assert!(menu_row(&h, "Paste in Place").is_some());
+ // Escape closes the left pane's menu before the right pane handles the keys.
+ h.key_press(egui::Key::Escape);
+ h.run_steps(3);
+ assert!(menu_row(&h, "Paste in Place").is_none());
+ assert_eq!((h.state().session.tool_id(), selected(&h)), ("rectangleFrame", vec![a]));
+ }
+
+ #[test]
+ fn right_clicking_text_keeps_the_selected_text_or_places_the_caret() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ app.run("frame.create", json!({"rect": [36, 36, 400, 200], "content": "text"})).unwrap();
+ app.select_tool("type");
+ app.run("text.insert", json!({"text": "Hello world"})).unwrap();
+ let sid = *app.session.doc().unwrap().doc.stories.keys().next().unwrap();
+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 5})).unwrap();
+ let mut h = harness(app);
+ let text_sel = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().selection.text.as_ref().map(|t| (t.anchor, t.focus));
+ // Inside "Hello": the selection stays.
+ let inside = screen_of(&h, 45.0, 44.0);
+ right_click(&mut h, inside);
+ assert_eq!(text_sel(&h), Some((0, 5)));
+ assert!(menu_row(&h, "Paste without Formatting").is_some(), "the text menu");
+ h.key_press(egui::Key::Escape);
+ h.run_steps(3);
+ // Past the end of the line: the caret goes there.
+ let past_end = screen_of(&h, 300.0, 44.0);
+ right_click(&mut h, past_end);
+ assert_eq!(text_sel(&h), Some((11, 11)));
+ assert!(menu_row(&h, "Paste without Formatting").is_some());
+ }
+
+ #[test]
+ fn rows_hidden_in_the_menu_bar_are_hidden_in_context_menus() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap();
+ app.ui.hidden_menu_items.push(crate::menus::menu_key("Object/Arrange", "Bring to Front"));
+ let mut h = harness(app);
+ let on_frame = screen_of(&h, 60.0, 60.0);
+ right_click(&mut h, on_frame);
+ menu_row(&h, "Arrange").unwrap().click();
+ h.run_steps(3);
+ assert!(menu_row(&h, "Bring to Front").is_none());
+ assert!(menu_row(&h, "Send to Back").is_some());
+ assert!(h.query_by_label("Show All Menu Items").is_some());
+ }
+
+ #[test]
+ fn a_secondary_drag_neither_moves_marquees_nor_draws() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();
+ let mut h = harness(app);
+ // A secondary-button drag between spread points.
+ let drag = |h: &mut Harness<'_, DesignApp>, from: (f64, f64), to: (f64, f64)| {
+ let (from, to) = (screen_of(h, from.0, from.1), screen_of(h, to.0, to.1));
+ h.hover_at(from);
+ h.step();
+ h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
+ h.step();
+ for t in [0.25, 0.5, 0.75, 1.0] {
+ h.event(egui::Event::PointerMoved(from + (to - from) * t));
+ h.step();
+ }
+ h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
+ h.run_steps(3);
+ };
+ let xf = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.item(designcraft_doc::ItemId(a)).unwrap().xf;
+ let before = xf(&h);
+ // Selection tool: on the object (no move), and from empty page across it (no marquee).
+ drag(&mut h, (100.0, 100.0), (300.0, 300.0));
+ assert_eq!(xf(&h), before);
+ h.state_mut().run("edit.deselectAll", json!({})).unwrap();
+ drag(&mut h, (400.0, 400.0), (20.0, 20.0));
+ assert!(selected(&h).is_empty());
+ // Rectangle Frame tool: no frame.
+ h.state_mut().select_tool("rectangleFrame");
+ drag(&mut h, (300.0, 300.0), (500.0, 500.0));
+ assert_eq!(spread_items(&h), [a]);
+ }
+
+ #[test]
+ fn tools_show_their_own_cursors_over_the_page() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let mut h = harness(app);
+ let p = h.state().canvas_rect.unwrap().center();
+ let mut shown = |tool: &str| {
+ h.state_mut().run("tool.select", json!({"tool": tool})).unwrap();
+ h.hover_at(p);
+ h.run_steps(2);
+ let out = &h.output().platform_output;
+ (out.cursor_icon, out.cursor_image.clone())
+ };
+ let (pen, direct, text) = (shown("pen"), shown("directSelection"), shown("type"));
+ let ppp = h.ctx.pixels_per_point();
+ let images = &mut h.state_mut().cursors;
+ match crate::cursors::MODE {
+ crate::cursors::Mode::Os => {
+ assert_eq!(pen.1, images.get(Cursor::Pen, ppp), "Pen");
+ assert_eq!(direct.1, images.get(Cursor::ArrowHollow, ppp), "Direct Selection");
+ assert_eq!(text, (egui::CursorIcon::Text, None), "the I-beam stays a system cursor");
+ }
+ crate::cursors::Mode::Painted => assert_eq!((pen.0, direct.0), (egui::CursorIcon::None, egui::CursorIcon::None)),
+ crate::cursors::Mode::System => assert_eq!(pen, (egui::CursorIcon::Crosshair, None)),
+ }
+ }
+
+ #[test]
+ fn document_grid_is_drawn_where_points_snap_to_it() {
+ use designcraft_tools::{SnapView, ToolContext};
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let doc = app.session.active().unwrap().doc.clone();
+ let layout = CanvasLayout::new(&doc, false);
+ let sr = SpreadRef::Doc(0);
+ // Where the grid snaps a point in the first page (72 pt / 8 subdivisions = 9 pt).
+ let page = doc.spreads[0].pages[0].bounds();
+ let sel = Selection::default();
+ let cx = ToolContext {
+ doc: &doc,
+ selection: &sel,
+ cache: &app.session.cache,
+ layout: &layout,
+ zoom: 1.0,
+ layer: doc.layers[0].id,
+ snap: SnapView { snap_to_document_grid: true, zone_px: 20.0, ..SnapView::OFF },
+ unit: Unit::Points,
+ };
+ let (snapped, _) = designcraft_tools::snap::snap_point(&cx, sr, Point::new(page.x0 + 31.3, page.y0 + 47.9));
+ assert_eq!((snapped.x - page.x0, snapped.y - page.y0), (27.0, 45.0));
+ // Render 40 × 40 pt around it at 4 px/pt.
+ let scale = 4.0;
+ let corner = layout.xf(sr) * Point::new(snapped.x - 20.0, snapped.y - 20.0);
+ let view = Affine::scale(scale) * Affine::translate((-corner.x, -corner.y));
+ let placed: Vec<_> = layout.slots.iter().map(|s| designcraft_render::Placed { spread: s.spread, xf: s.xf }).collect();
+ let render = |app: &DesignApp| {
+ let opts = screen_options(app, &layout, false, 1.0);
+ designcraft_render::Renderer::new().render(&doc, &app.session.cache, &placed, 160, 160, view, &opts)
+ };
+ // The snapped point is at pixel (80, 80); halfway to the next line is 18 px further.
+ let darkest = |img: &designcraft_render::Rendered, xs: [u32; 2], ys: [u32; 2]| {
+ (xs[0]..xs[1]).flat_map(|x| (ys[0]..ys[1]).map(move |y| (x, y))).map(|(x, y)| img.pixel(x, y)[0]).min().unwrap()
+ };
+ let off = render(&app);
+ assert_eq!(darkest(&off, [78, 82], [60, 64]), 255, "no grid while it is hidden");
+ app.run("view.documentGrid", json!({})).unwrap();
+ let on = render(&app);
+ assert!(darkest(&on, [79, 81], [60, 64]) < 250, "a vertical line at the snapped x");
+ assert!(darkest(&on, [60, 64], [79, 81]) < 250, "a horizontal line at the snapped y");
+ assert_eq!(darkest(&on, [96, 100], [96, 100]), 255, "nothing between lines");
+ // Preview hides it.
+ app.ui.screen_mode = ScreenMode::Preview;
+ assert!(screen_options(&app, &layout, true, 1.0).document_grid.is_empty());
+ }
+
+ /// egui moves keyboard focus on a plain arrow key or Tab, and Space/Return then clicks the
+ /// focused widget (e.g. the status bar's spread buttons) while typing still reaches the text.
+ #[test]
+ fn arrow_keys_and_tab_keep_keyboard_focus_on_the_canvas() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"pages": 3})).unwrap();
+ let f = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Hello"})).unwrap();
+ app.select_tool("type");
+ let mut h = harness(app);
+ let p = {
+ let app = h.state();
+ let st = app.session.active().unwrap();
+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);
+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
+ xf.to_screen(layout.xf(SpreadRef::Doc(0)) * Point::new(100.0, 60.0))
+ };
+ h.hover_at(p);
+ h.step();
+ for pressed in [true, false] {
+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
+ h.step();
+ }
+ h.run_steps(2);
+ let focus = h.ctx.memory(|m| m.focused());
+ assert!(focus.is_some(), "a click on the canvas takes keyboard focus");
+ let view = *h.state().view().unwrap();
+ for key in [egui::Key::ArrowDown, egui::Key::Space, egui::Key::ArrowRight, egui::Key::Enter, egui::Key::Tab, egui::Key::Escape] {
+ h.key_press(key);
+ if key == egui::Key::Space {
+ h.event(egui::Event::Text(" ".into()));
+ }
+ h.run_steps(2);
+ assert_eq!(h.ctx.memory(|m| m.focused()), focus, "{key:?} keeps keyboard focus on the canvas");
+ }
+ let v = *h.state().view().unwrap();
+ assert_eq!((v.origin, v.zoom), (view.origin, view.zoom), "the view stays where it was");
+ let text = h.state_mut().session.execute("story.get", &json!({"story": f["story"]})).unwrap()["text"].clone();
+ assert_eq!(text, "Hello \n\t", "Space, Return and Tab reach the text");
+ }
+
#[test]
fn rulers_open_no_units_menu_without_a_document() {
let mut h = harness(DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()));