DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge PR #1090: Canvas: Enter and Tab in a panel field no longer reach the selected text
aiongg0c972f724fec
diff --cc crates/ui-egui/src/canvas.rsindex 16604d001,5a691fde5..32226b655--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -1351,6 -1192,34 +1351,19 @@@ fn draw_text_selection}}-/// Where the text caret stood on screen last frame: the OS puts its input-method window there.-fn ime_caret_id() -> egui::Id {- egui::Id::new("canvas_ime_caret")-}-+ /// A text field had keyboard focus when this frame began, per window: egui keeps one focus per+ /// viewport, so a field focused in the main window must not mute the second window's canvas.+ fn field_focused_id(ctx: &egui::Context) -> egui::Id {+ egui::Id::new("canvas_field_focused").with(ctx.viewport_id())+ }++ /// Called before the panels draw. A panel field gives up focus on Enter or Tab while it draws,+ /// before the canvas: without this the canvas would take that same key for the text.+ pub fn begin_frame(ctx: &egui::Context) {+ let (id, focused) = (field_focused_id(ctx), ctx.text_edit_focused());+ ctx.data_mut(|d| d.insert_temp(id, focused));+ }+-/// The input method is composing text (sent to `text.compose`) that it hasn't committed.-fn ime_composing_id() -> egui::Id {- egui::Id::new("canvas_ime_composing")-}--/// Remembers the caret at `p0`–`p1` for the input method's window.-fn remember_ime_caret(painter: &egui::Painter, p0: egui::Pos2, p1: egui::Pos2) {- painter.ctx().data_mut(|d| d.insert_temp(ime_caret_id(), egui::Rect::from_two_pos(p0, p1)));-}-/// Caret / text highlight inside a table cell (the cell's lines are offset by the cell origin).#[allow(clippy::too_many_arguments)]fn draw_cell_selection(@@@ -2242,29 -1857,47 +2255,31 @@@ fn handle_input(app: &mut DesignApp, uiif resp.clicked() || resp.drag_started() {resp.request_focus();}- // Both split panes show the same document, but only the focused pane dispatches its keys.+ // 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));- // Keyboard for the active tool.- if menu_open || (ui.ctx().text_edit_focused() && !resp.has_focus()) || !keyboard_pane(app) {++ // Keyboard for the active tool. A field focused when the frame began keeps this frame's keys.+ let field_id = field_focused_id(ui.ctx());+ let field = ui.ctx().text_edit_focused() || ui.data(|d| d.get_temp::<bool>(field_id)).unwrap_or(false);- if app.pane != app.focus_pane || (field && !resp.has_focus()) {++ if menu_open || (field && !resp.has_focus()) || !keyboard_pane(app) {return;}- // The engine drops composed text when something else edits or the caret moves; the input- // method must forget it too, or the next key would finish an accent that is gone.- let composing = ui.data(|d| d.get_temp::<bool>(ime_composing_id())).unwrap_or(false);- let interrupt = composing && app.session.composition().is_none();- if interrupt || !wants_text {- ui.data_mut(|d| d.remove::<bool>(ime_composing_id()));- }- if wants_text {- // Turn the OS input method on: macOS composes dead keys (⌥E then I types í) and- // Japanese/Chinese input only for a window that asks for it. Without it ⌥E typed "e".- let cursor_rect = ui.data(|d| d.get_temp(ime_caret_id())).unwrap_or(egui::Rect::from_min_size(rect.min, egui::Vec2::ZERO));- ui.ctx().output_mut(|o| {- o.ime = Some(egui::output::IMEOutput { purpose: egui::IMEPurpose::Normal, rect, cursor_rect, should_interrupt_composition: interrupt });- });- }+ // 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}));}- // What is composed shows in the story, in the text's own format, until it commits.- egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) if wants_text => {- let on = !text.is_empty();- if app.run("text.compose", json!({"text": text})).is_ok() {- ui.data_mut(|d| d.insert_temp(ime_composing_id(), on));- }- }- egui::Event::Ime(egui::ImeEvent::Commit(t)) if wants_text => {- ui.data_mut(|d| d.remove::<bool>(ime_composing_id()));- let _ = app.run("text.compose", json!({"text": ""}));- if !t.is_empty() {- 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.@@@ -4244,63 -2681,34 +4259,89 @@@ mod testsassert_eq!(lines(f64::NAN, 12.0, 792.0), [0.0; 0]);assert_eq!(baseline_grid_lines(0.0, 12.0, f64::INFINITY).count(), MAX_BASELINES);}++ #[test]+ fn enter_or_tab_in_a_panel_field_leave_the_selected_text_alone() {+ for key in [egui::Key::Enter, egui::Key::Tab] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let f = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Hello"})).unwrap();+ app.select_tool("type");+ app.run("text.select", json!({"story": f["story"], "anchor": 1, "focus": 4})).unwrap();+ assert!(app.session.wants_text());+ let mut h = harness(app);+ let size = h.get_all_by_role(egui::accesskit::Role::TextInput).find(|n| n.value().as_deref() == Some("12 pt")).unwrap();+ size.focus();+ h.run_steps(1);+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);+ h.run_steps(1);+ h.event(egui::Event::Text("18".into()));+ h.run_steps(1);+ h.key_press(key);+ h.run_steps(3);+ let text = h.state_mut().session.execute("story.get", &json!({"story": f["story"]})).unwrap()["text"].clone();+ assert_eq!(text, "Hello", "{key:?} confirms the field and leaves the story alone");+ let size = crate::panels::text_attrs(h.state_mut()).unwrap()["chars"]["size"].clone();+ assert_eq!(size, 18.0, "{key:?} applies the typed size");+ }+ }}+#[cfg(test)]+mod pencil_preview_tests {+ use egui::{Pos2, pos2, vec2};++ /// Lines painted in `color` (egui paths) and the points they pass through.+ fn lines_in(h: &egui_kittest::Harness<'static, crate::test_window::Window>, color: egui::Color32) -> Vec<Vec<Pos2>> {+ fn walk(s: &egui::Shape, color: egui::Color32, out: &mut Vec<Vec<Pos2>>) {+ match s {+ egui::Shape::Path(p) if p.stroke.color == egui::epaint::ColorMode::Solid(color) && p.points.len() >= 2 => out.push(p.points.clone()),+ egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, color, out)),+ _ => {}+ }+ }+ let mut out = vec![];+ h.output().shapes.iter().for_each(|s| walk(&s.shape, color, &mut out));+ out+ }++ #[test]+ fn the_pencil_stroke_shows_while_drawing() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", serde_json::json!({})).unwrap();+ app.run("tool.select", serde_json::json!({"tool": "pencil"})).unwrap();+ let mut h = crate::test_window::open(app, vec2(1400.0, 900.0));+ let doc = &h.state().app.session.doc().unwrap().doc;+ let layer = doc.layers[0].color;+ let color = egui::Color32::from_rgb(layer[0], layer[1], layer[2]);+ let items = |h: &egui_kittest::Harness<'static, crate::test_window::Window>| h.state().app.session.doc().unwrap().doc.spreads[0].items.len();+ let before = items(&h);+ // Press on the page and drag, without letting go.+ let start = pos2(520.0, 380.0);+ h.hover_at(start);+ h.drag_at(start);+ h.run_steps(2);+ let path: Vec<Pos2> = (1..=12).map(|i| start + vec2(i as f32 * 12.0, (i as f32 * 0.6).sin() * 30.0)).collect();+ for p in &path {+ h.hover_at(*p);+ h.run_steps(1);+ }+ let drawn = lines_in(&h, color);+ let stroke = drawn.iter().max_by_key(|l| l.len()).expect("the stroke is painted while the button is down");+ let near = |a: Pos2, b: Pos2| (a - b).length() < 2.0;+ assert!(near(stroke[0], start), "it starts where the press was: {:?}", stroke[0]);+ assert!(path.iter().all(|p| stroke.iter().any(|q| near(*p, *q))), "it follows the pointer: {stroke:?}");+ assert_eq!(items(&h), before, "nothing is made before the release");+ // Letting go makes the path and ends the preview.+ h.drop_at(*path.last().unwrap());+ h.run_steps(3);+ assert_eq!(items(&h), before + 1);+ let app = &mut h.state_mut().app;+ let view = app.view_info();+ assert!(app.session.overlays(view).is_empty(), "the preview is gone");+ }+}+#[cfg(test)]mod scrollbar_tests {use egui::{Event, Modifiers, PointerButton};