diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index d6fedcd9fa..64d4fec82e 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -4,6 +4,7 @@ use egui::{Align2, CornerRadius, Key, KeyboardShortcut, Modifiers, Rect, Sense, Stroke, Ui, pos2, vec2}; use serde_json::{Value, json}; +use crate::inuse::{Late, Pane}; use crate::mapview::Toast; use crate::theme::{Tokens, regular, semibold}; use crate::widgets::{row_button, selectable_menu_row, small, text_w, why_disabled}; @@ -883,13 +884,7 @@ fn parse_scale(text: &str) -> Option { /// Global keyboard shortcuts. pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { - if app.ui.command_search.is_some() { - return; - } - // Behind a dialog (Save changes?, Recover unsaved work?, Command Search…) the keys are the - // dialog's: Escape answers it rather than switching tools, and Ctrl+N can't start what it - // asks about. - if crate::saveprompt::waiting(app) || ctx.memory(|m| m.top_modal_layer()).is_some() || app.ui.shortcut_editor.capturing() { + if behind_a_dialog(app, ctx) { return; } // The repeat-use form is not modal: another pane or an unfinished sketch keeps Escape. @@ -915,22 +910,17 @@ pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { app.ui.history_jump = None; } crate::modelbuilder::shortcuts(app, ctx); - // The search box (or a table cell, or the Script pane's find bar) had the focus until egui - // took it away on Escape: that Escape clears the box (leaves the cell as it was, closes the - // bar), not the tool. An open list (a clause's Functions) keeps the same keys as a box, those - // without Ctrl (⌘): Escape closes it. - let pass = ctx.cumulative_pass_nr(); - let typing = ctx.egui_wants_keyboard_input() - || crate::completion::menu_is_open(ctx) - || crate::crspicker::list_is_open(ctx) - || crate::searchbox::had_focus(&app.ui.search, pass) - || crate::table::had_focus(&app.table, pass) - || app.workflow.script_find.had_focus(pass); + let typing = typing(app, ctx); // A text field focused, not any widget (a button reached with Tab): it has an undo of its own. let text_field = ctx.text_edit_focused(); // An element selected in the open layout, for the layout's own keys. let element = app.session.active_layout.is_some() && app.layout.selected.is_some(); - let mut run: Vec<(String, Value)> = Vec::new(); + // The pane the user last pressed or scrolled in: Delete and Rename act on it. + let pane = crate::inuse::pane(app); + // What to run now, each with the pane that was in use as its key went down, and what to run + // once the panes are drawn ([`late_keys`]). + let mut run: Vec<(String, Value, Pane)> = Vec::new(); + let mut late: Vec = Vec::new(); let keymap = &app.ui.keymap; ctx.input_mut(|i| { for b in keymap.match_order() { @@ -938,8 +928,7 @@ pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { // which type text, and undo and redo, whatever they're bound to (#685), as ModelBuilder // leaves them. // Pause unmodified shortcuts during first-person movement, retaining the existing Escape, Home and Delete controls. - if (typing && !b.chord.command) - || (text_field && b.chord.is_text_undo()) + if text_takes(Some(b.chord), typing, text_field) || (app.session.map().view.first_person && !b.chord.command && !b.chord.alt @@ -958,14 +947,36 @@ pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { if element && !b.chord.command && matches!(b.chord.key, Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown) { continue; } + // The press that the shortcut takes, if it isn't only a held key's repeats. + let press = crate::inuse::press(app, b.chord.key, Some(b.chord.modifiers())); if i.consume_shortcut(&KeyboardShortcut::new(b.chord.modifiers(), b.chord.key)) { - run.push((b.command.clone(), b.params.clone())); + let (id, params) = (b.command.clone(), b.params.clone()); + match press { + None if follows_click(&id) && repeat_stops(app, b.chord.key, pane) => {} + None => run.push((id, params, pane)), + // A key that acts on what a click picks waits for the click to be taken. + Some(press) if press.after_click && follows_click(&id) => { + late.push(Late { id, params, pane: press.pane, chord: Some(b.chord) }); + } + Some(press) => run.push((id, params, press.pane)), + } } } if !typing { - // A Mac keyboard's delete key is Backspace: it deletes a layout element too. - if element && i.consume_key(Modifiers::NONE, Key::Backspace) { - run.push(("edit.delete".into(), Value::Null)); + // A Mac keyboard's delete key is Backspace: it deletes a layout element too, and + // removes the layers picked in the layer list. There it is the key alone, pressed + // once: `consume_key` takes Shift and Alt with it, and a held key's repeats. + let press = crate::inuse::press(app, Key::Backspace, None); + let key_pane = press.map_or(pane, |press| press.pane); + // In the layer list only that press counts; for a layout's element, a repeat does too. + let takes = if key_pane == Pane::Layers { press.is_some() } else { element }; + if takes && i.consume_key(Modifiers::NONE, Key::Backspace) { + let (id, params) = ("edit.delete".to_string(), Value::Null); + if press.is_some_and(|press| press.after_click) { + late.push(Late { id, params, pane: key_pane, chord: None }); + } else if press.is_some() || !repeat_stops(app, Key::Backspace, key_pane) { + run.push((id, params, key_pane)); + } } // Arrow keys nudge the selected layout element, further with Shift; held, it keeps // going. Shift first: a plain arrow's pattern takes Shift-arrows too. @@ -976,7 +987,7 @@ pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { { for (m, step) in [(Modifiers::SHIFT, NUDGE_FAST_MM), (Modifiers::NONE, NUDGE_MM)] { for _ in 0..i.count_and_consume_key(m, key) { - run.push(("ui.layoutNudge".into(), json!({"dx": dx * step, "dy": dy * step}))); + run.push(("ui.layoutNudge".into(), json!({"dx": dx * step, "dy": dy * step}), pane)); } } } @@ -984,16 +995,107 @@ pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { // Clipboard keys arrive as events, not key presses. for e in &i.events { match e { - egui::Event::Copy => run.push(("ui.copy".into(), Value::Null)), - egui::Event::Cut => run.push(("ui.cut".into(), Value::Null)), - egui::Event::Paste(text) => run.push(("edit.paste".into(), json!({"text": text}))), + egui::Event::Copy => run.push(("ui.copy".into(), Value::Null, pane)), + egui::Event::Cut => run.push(("ui.cut".into(), Value::Null, pane)), + egui::Event::Paste(text) => run.push(("edit.paste".into(), json!({"text": text}), pane)), _ => {} } } } }); - for (id, p) in &run { - let (id, p) = (id.as_str(), p.clone()); + let dialogs = dialogs_up(app); + crate::inuse::keep_late(app, late, dialogs); + run_keys(app, ctx, &run); +} + +/// Whether the keys are a dialog's (Save changes?, Recover unsaved work?, Command Search…): +/// Escape answers it rather than switching tools, and Ctrl+N can't start what it asks about. +fn behind_a_dialog(app: &RustGisApp, ctx: &egui::Context) -> bool { + app.ui.command_search.is_some() + || crate::saveprompt::waiting(app) + || ctx.memory(|m| m.top_modal_layer()).is_some() + || app.ui.shortcut_editor.capturing() +} + +/// The dialogs and questions that are up, whether the File menu's backstage covers the window, and +/// the project, as one number: it differs once a click (or a key of the same frame) has opened or +/// answered one, or another project has taken this one's place. (egui says a modal dialog is up +/// only from the frame after it first shows.) +fn dialogs_up(app: &RustGisApp) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + let asked = (app.map.deleting.is_some(), app.mb.asking(), crate::saveprompt::waiting(app)); + (app.dialogs.open, asked, app.ui.command_search.is_some(), app.ui.backstage, app.session.opened).hash(&mut hasher); + hasher.finish() +} + +/// Whether a held key's repeat of a command that acts on what a click picks ([`follows_click`]) +/// does nothing, with `pane` in use. In the layer list, each removal makes the next layer the +/// active one, so a held Delete would take the list from there down. A key held since another +/// pane was in use stays that pane's (Delete held in the layer list, then the wheel turned over +/// the map, must not reach the map's features). And while a click is under way, the key's first +/// press didn't act either. +fn repeat_stops(app: &RustGisApp, key: Key, pane: Pane) -> bool { + pane == Pane::Layers || crate::inuse::clicking(app) || crate::inuse::held_in(app, key).is_some_and(|pressed_in| pressed_in != pane) +} + +/// Whether text is being typed. The search box (or a table cell, or the Script pane's find bar) +/// had the focus until egui took it away on Escape: that Escape clears the box (leaves the cell as +/// it was, closes the bar), not the tool. An open list (a clause's Functions) keeps the same keys +/// as a box, those without Ctrl (⌘): Escape closes it. +fn typing(app: &RustGisApp, ctx: &egui::Context) -> bool { + let pass = ctx.cumulative_pass_nr(); + ctx.egui_wants_keyboard_input() + || crate::completion::menu_is_open(ctx) + || crate::crspicker::list_is_open(ctx) + || crate::searchbox::had_focus(&app.ui.search, pass) + || crate::table::had_focus(&app.table, pass) + || app.workflow.script_find.had_focus(pass) +} + +/// Whether a text field keeps a key for itself (`chord`: the shortcut, or `None` for a key that +/// is none): while one has the focus it keeps the keys it acts on, those without Ctrl (⌘), which +/// type text, and undo and redo, whatever they're bound to (#685), as ModelBuilder leaves them. +fn text_takes(chord: Option, typing: bool, text_field: bool) -> bool { + match chord { + Some(chord) => (typing && !chord.command) || (text_field && chord.is_text_undo()), + None => typing, + } +} + +/// Whether command `id` acts on what a click picks (the layer, the tab, the features). A frame +/// reads its keys before it draws the panes, where a click is taken, so on a slow frame a layer +/// clicked and Delete pressed would remove the layer picked before: the key of such a command, +/// pressed while a click is under way, runs in [`late_keys`]. +fn follows_click(id: &str) -> bool { + matches!(id, "edit.delete" | "layer.rename") +} + +/// Runs the keys [`shortcuts`] left for the end of the frame, now that the panes have taken its +/// click and the dialogs it opened are up. A key pressed while a button is still down came +/// before anyone could know what the click picks: it is dropped, as is one that a text field +/// takes when the click put the cursor in one, and one whose click opened or answered a dialog +/// (Delete Layout?), which the key was not for. +pub fn late_keys(app: &mut RustGisApp, ctx: &egui::Context) { + let (late, dialogs) = crate::inuse::take_late(app); + if late.is_empty() || crate::inuse::down(app) || behind_a_dialog(app, ctx) || dialogs != dialogs_up(app) { + return; + } + let (typing, text_field) = (typing(app, ctx), ctx.text_edit_focused()); + let run: Vec<(String, Value, Pane)> = + late.into_iter().filter(|key| !text_takes(key.chord, typing, text_field)).map(|key| (key.id, key.params, key.pane)).collect(); + // The panes and dialogs were drawn before these keys run: another frame shows what they did. + if !run.is_empty() { + ctx.request_repaint(); + } + run_keys(app, ctx, &run); +} + +/// Runs the commands of the keys pressed, each with the pane that was in use as its key went +/// down: what a key does depends on the tool, the view and the pane. +fn run_keys(app: &mut RustGisApp, ctx: &egui::Context, run: &[(String, Value, Pane)]) { + for (id, p, pane) in run { + let (id, p, pane) = (id.as_str(), p.clone(), *pane); if id == "tool.set" { app.map.cancel_sketch(); app.layout.cancel_tool(); @@ -1038,6 +1140,22 @@ pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { crate::circleedit::cancel(app); continue; } + // In the layer list, Delete removes the layers picked there, never the features selected + // on the map, a layout's element or a vertex (#2945). + if id == "edit.delete" && pane == Pane::Layers { + remove_picked_layers(app); + continue; + } + // On the tabs, and in a layout, Rename (F2) is for the map or layout in view, as a + // double-click on its tab is; elsewhere it renames the active layer (below). + if id == "layer.rename" + && p.get("name").is_none() + && p.get("layer").is_none() + && let Some(dialog) = renames_view(app, pane) + { + let _ = app.run("ui.dialog", json!({"name": dialog})); + continue; + } // With Edit Vertices, Delete removes the chosen vertex rather than the feature. if id == "edit.delete" && app.session.active_layout.is_none() @@ -1056,19 +1174,16 @@ pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { .selected .is_some_and(|el| app.session.project.layouts.get(li).is_some_and(|l| l.locked_in_removal(el).is_some())); if kept { - let text = crate::i18n::fmt( - "{command}: {reason}", - &[("command", tl_raw!("Delete Element")), ("reason", crate::layoutview::locked_delete())], - ); - if !app.map.toasts.iter().any(|t| t.text == text) { - app.session.notify(text, true); - } + cannot_run(app, tl_raw!("Delete Element"), crate::layoutview::locked_delete()); } else if let Some(el) = app.layout.selected.take() { let _ = app.run("layout.removeElement", json!({"layout": li, "element": el})); + } else { + cannot_run(app, tl_raw!("Delete Element"), tl_raw!("no element is selected")); } continue; } - if matches!(id, "edit.delete" | "ui.copy" | "ui.cut") && app.session.map().selection_count() == 0 { + // Copy and Cut with nothing selected do nothing. Delete says so (below). + if matches!(id, "ui.copy" | "ui.cut") && app.session.map().selection_count() == 0 { continue; } // Pasting text that isn't features (a stray copy from elsewhere) does nothing. @@ -1086,11 +1201,7 @@ pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { && let Some(why) = why_disabled(app, id) { let label = app.session.registry.get(id).map_or(id, |s| s.label); - let text = crate::i18n::fmt("{command}: {reason}", &[("command", tl_raw!(label)), ("reason", tl_raw!(why))]); - // Once while it shows: a held key repeats, and each repeat comes here. - if !app.map.toasts.iter().any(|t| t.text == text) { - app.session.notify(text, true); - } + cannot_run(app, tl_raw!(label), tl_raw!(why)); continue; } // Rename with no name given (F2) opens the Rename dialog for the active layer, as Command @@ -1104,6 +1215,42 @@ pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { } } +/// Says why a key's command (`label`, translated, as `reason` is) can't run now. Once while the +/// notice shows: a held key repeats, and each repeat comes here. +fn cannot_run(app: &mut RustGisApp, label: &str, reason: &str) { + let text = crate::i18n::fmt("{command}: {reason}", &[("command", label), ("reason", reason)]); + if !app.map.toasts.iter().any(|t| t.text == text) { + app.session.notify(text, true); + } +} + +/// Delete in the layer list: removes what is picked there, as its menu's Remove does (one Undo +/// step, no question asked). That is the tile layer picked, else the layers picked together; +/// with neither, it says so. +fn remove_picked_layers(app: &mut RustGisApp) { + if let Some(i) = app.session.selected_tile() { + let _ = app.run("map.removeTiles", json!({"index": i})); + } else if let Some(why) = why_disabled(app, "layer.remove") { + cannot_run(app, tl_raw!("Remove"), tl_raw!(why)); + } else { + let _ = app.run("layer.remove", Value::Null); + } +} + +/// The dialog Rename (F2) opens for the map or layout in view, when `pane` is one where the key +/// is about it rather than the active layer: the tabs, or a layout. `None` elsewhere, and with +/// ModelBuilder in view (a model is named in its own toolbar). +fn renames_view(app: &RustGisApp, pane: Pane) -> Option<&'static str> { + if app.mb.shown() { + return None; + } + match (pane, app.session.active_layout.is_some()) { + (Pane::Tabs | Pane::View, true) => Some("renameLayout"), + (Pane::Tabs, false) => Some("renameMap"), + _ => None, + } +} + /// Whether a UI command is available on the current platform. pub(crate) fn command_available(id: &str, web: bool) -> bool { !web || !matches!( diff --git a/crates/ui-egui/src/inuse.rs b/crates/ui-egui/src/inuse.rs new file mode 100644 index 0000000000..4cba32e2d4 --- /dev/null +++ b/crates/ui-egui/src/inuse.rs @@ -0,0 +1,640 @@ +//! The pane in use: the part of the window the user last pressed, dragged or scrolled in. A few +//! keys mean different things in different panes (Delete removes a layer in the Layers pane and +//! features on the map), and [`crate::chrome::shortcuts`] routes them by it (#2945). +//! +//! Hovering doesn't count. A dialog over the panes is none of them, and a menu or a pop-up leaves +//! the pane it was opened from in use. + +use egui::{Key, LayerId, Modifiers, Order, PointerButton, Pos2, Rect}; +use serde_json::Value; + +use crate::keymap::Chord; +use crate::{LeftPane, RustGisApp}; + +/// A part of the window a key can act on. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Pane { + /// The map, layout or ModelBuilder canvas in view. Also before anything was pressed, and in a + /// shell that draws its own interface: the keys act as they do on the map. + #[default] + View, + /// The tabs of the maps and layouts, above the view. + Tabs, + /// The layer list (the Layers pane, under its title). + Layers, + /// The attribute table. + Table, + /// The rest: the ribbon, the status bar, any other pane. + Other, +} + +/// A key pressed on this frame (not a held key's repeat), and what was so as it went down. +#[derive(Clone, Copy)] +pub struct Press { + key: Key, + modifiers: Modifiers, + /// The pane in use then: a press or a wheel turn later on the frame doesn't change whose key + /// it was. + pub pane: Pane, + /// Whether a click was under way: a mouse button was down as the frame began, or went down or + /// up earlier on it. The panes take a click only as they are drawn, after the keys are read. + pub after_click: bool, +} + +/// A key's command kept until the frame's panes and dialogs are drawn +/// ([`crate::chrome::late_keys`]). +pub struct Late { + pub id: String, + pub params: Value, + /// The pane in use as the key went down. + pub pane: Pane, + /// The shortcut pressed, or `None` for a key that is no shortcut (Backspace). + pub chord: Option, +} + +/// Which pane is in use, and where the panes were drawn. +#[derive(Default)] +pub struct InUse { + pane: Pane, + /// Where each pane was drawn on the last frame, and on which layer, in drawing order: a pane + /// drawn inside another comes after it. + drawn: Vec<(Pane, Rect, LayerId)>, + /// The project the pane was pressed in ([`rustgis_engine::Session::opened`]). + project: u64, + /// Where the pointer was when the last frame ended. + pointer: Option, + /// The mouse buttons that are down by this frame's events, a bit each (a finger is the first). + down: u8, + /// Whether a click was under way at some point of this frame: a button was down as it began, + /// or went down or up on it. + clicking: bool, + /// The keys pressed on this frame, in order. + presses: Vec, + /// The keys that are down, each with the pane that was in use as it went down: a held key's + /// repeats are that pane's. + held: Vec<(Key, Pane)>, + /// This frame's keys kept until its panes are drawn, and the dialogs that were up as they + /// were pressed (a number that differs when they do). + late: Vec, + late_dialogs: u64, +} + +impl InUse { + /// Records where `pane` is drawn this frame, and on which layer (`Ui::layer_id`). + pub fn drawn(&mut self, pane: Pane, layer: LayerId, rect: Rect) { + self.drawn.push((pane, rect, layer)); + } +} + +/// A mouse button's bit in [`InUse::down`]. +fn bit(button: PointerButton) -> u8 { + match button { + PointerButton::Primary => 1, + PointerButton::Secondary => 2, + PointerButton::Middle => 4, + PointerButton::Extra1 => 8, + PointerButton::Extra2 => 16, + } +} + +/// Takes this frame's presses and scrolling: the pane under the pointer at each is the one in use +/// from there on, for the keys that follow it on the frame too. Called once a frame, before the +/// keys are read and the panes are drawn. +pub fn follow(app: &mut RustGisApp, ctx: &egui::Context) { + let drawn = std::mem::take(&mut app.ui.in_use.drawn); + let in_use = &mut app.ui.in_use; + // Another project is nothing the user has worked in yet: Delete must not remove a layer of it + // because the last project's layer list was in use. + if in_use.project != app.session.opened { + in_use.project = app.session.opened; + in_use.pane = Pane::default(); + } + // A pane closed (by a key or a command, with no press elsewhere) is no longer in use, and + // isn't again when it is opened. Nor is one pressed where it was drawn as it closed. And no + // pane is drawn behind the File menu's backstage, which a command can open with no press. + let open = |pane: Pane| { + !app.ui.backstage + && match pane { + Pane::Layers => app.ui.left == Some(LeftPane::Contents), + Pane::Table => app.session.table_layer.is_some() || app.session.table_standalone.is_some(), + _ => true, + } + }; + if !open(in_use.pane) { + in_use.pane = Pane::Other; + } + // Where the pointer was at each press, wheel turn and zoom (not where it is by the end of the + // frame), and for each key how many of them came before it. + let mut pointer = in_use.pointer; + let mut down = in_use.down; + let mut clicked = down != 0; + let mut worked: Vec = Vec::new(); + // Each key going down (with its modifiers, how many of them came before and whether a click + // was under way) or up (`None`), in order. + let mut keys: Vec<(Key, Option<(Modifiers, usize, bool)>)> = Vec::new(); + ctx.input(|i| { + for e in &i.events { + match e { + egui::Event::PointerMoved(pos) => pointer = Some(*pos), + egui::Event::PointerButton { pos, button, pressed, .. } => { + pointer = Some(*pos); + clicked = true; + if *pressed { + down |= bit(*button); + worked.push(*pos); + } else { + down &= !bit(*button); + } + } + egui::Event::MouseWheel { .. } | egui::Event::Zoom(_) => worked.extend(pointer), + egui::Event::PointerGone => pointer = None, + // The system took the touch away, or the window lost the keyboard (a release + // elsewhere isn't told): no release will come. + egui::Event::Touch { phase: egui::TouchPhase::Cancel, .. } | egui::Event::WindowFocused(false) => down = 0, + egui::Event::Key { key, pressed: true, repeat: false, modifiers, .. } => { + keys.push((*key, Some((*modifiers, worked.len(), clicked)))); + } + egui::Event::Key { key, pressed: false, .. } => keys.push((*key, None)), + _ => {} + } + } + }); + in_use.pointer = pointer; + in_use.down = down; + in_use.clicking = clicked; + // The pane after each of them, in turn. + let modal = ctx.memory(|m| m.top_modal_layer()); + let mut panes = vec![in_use.pane]; + for at in worked { + // What floats there over the window's own layer (a dialog, a menu, a pop-up), if anything. + let over = ctx.layer_id_at(at); + let hit = drawn + .iter() + .rev() + .find(|(pane, rect, layer)| open(*pane) && rect.contains(at) && over.is_none_or(|o| o == *layer)) + .map(|(pane, ..)| *pane); + let before = panes.last().copied().unwrap_or_default(); + panes.push(match hit { + Some(pane) => pane, + // A modal dialog (Command Search), wherever in the window the press lands. + None if over.is_some() && over == modal => Pane::Other, + // A menu or a pop-up that no pane says is its own: the pane it was opened from stays. + None if over.is_some_and(|o| matches!(o.order, Order::Foreground | Order::Tooltip | Order::Debug)) => before, + None => Pane::Other, + }); + } + in_use.pane = panes.last().copied().unwrap_or_default(); + in_use.presses.clear(); + for (key, pressed) in keys { + in_use.held.retain(|(held, _)| *held != key); + if let Some((modifiers, worked, after_click)) = pressed { + let pane = panes.get(worked).copied().unwrap_or(in_use.pane); + in_use.presses.push(Press { key, modifiers, pane, after_click }); + in_use.held.push((key, pane)); + } + } +} + +/// The pane in use. +pub fn pane(app: &RustGisApp) -> Pane { + app.ui.in_use.pane +} + +/// Whether a mouse button or a finger is down, by this frame's events. +pub fn down(app: &RustGisApp) -> bool { + app.ui.in_use.down != 0 +} + +/// Whether a click was under way at some point of this frame. +pub fn clicking(app: &RustGisApp) -> bool { + app.ui.in_use.clicking +} + +/// The pane that was in use as `key`, still down, was pressed. +pub fn held_in(app: &RustGisApp, key: Key) -> Option { + app.ui.in_use.held.iter().find(|(held, _)| *held == key).map(|(_, pane)| *pane) +} + +/// The first press of `key` on this frame that isn't a held key's repeat: with modifiers that +/// match `chord` as a shortcut's do (Shift and Alt may be held besides), or with none at all for +/// `None`. The one event says both whether a shortcut was pressed anew and when. +pub fn press(app: &RustGisApp, key: Key, chord: Option) -> Option { + let matches = |p: &&Press| p.key == key && chord.map_or(p.modifiers.is_none(), |chord| p.modifiers.matches_logically(chord)); + app.ui.in_use.presses.iter().find(matches).copied() +} + +/// Keeps this frame's keys that run after its panes are drawn ([`crate::chrome::late_keys`]), +/// with `dialogs`, a number for the dialogs that are up now. +pub fn keep_late(app: &mut RustGisApp, late: Vec, dialogs: u64) { + app.ui.in_use.late = late; + app.ui.in_use.late_dialogs = dialogs; +} + +/// The keys kept by [`keep_late`], once, and its `dialogs`. +pub fn take_late(app: &mut RustGisApp) -> (Vec, u64) { + (std::mem::take(&mut app.ui.in_use.late), app.ui.in_use.late_dialogs) +} + +#[cfg(test)] +mod tests { + use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, vec2}; + use egui_kittest::kittest::Queryable; + use serde_json::{Value, json}; + + use super::*; + + type Window = egui_kittest::Harness<'static, RustGisApp>; + + /// The whole app as its window runs it, so the panes say where they are and the keys are + /// read from where a frame reads them. No right pane: a layer's name is only in the list. + /// Frames a quarter of a second long, so two clicks on a layer are never a double-click. + fn window(mut app: RustGisApp) -> Window { + app.ui.right_open.clear(); + app.ui.right = None; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 900.0)).with_max_steps(64).with_step_dt(0.25).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(6); + h + } + + /// Where `pane` was drawn on the last frame. + fn rect(h: &Window, pane: Pane) -> Rect { + h.state().ui.in_use.drawn.iter().find(|d| d.0 == pane).map(|d| d.1).unwrap() + } + + fn button(pos: Pos2, pressed: bool) -> Event { + Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE } + } + + /// A press and release of the mouse at `pos`. + fn press(h: &mut Window, pos: Pos2) { + h.event(Event::PointerMoved(pos)); + h.step(); + h.event(button(pos, true)); + h.step(); + h.event(button(pos, false)); + h.run_steps(2); + } + + /// Events that all arrive in one frame, as on a slow one (the harness otherwise gives each + /// event a frame of its own); only that frame is run. + fn one_frame(h: &mut Window, events: impl IntoIterator) { + h.input_mut().events.extend(events); + h.step(); + } + + /// [`one_frame`], and the frames after it in which what it started ends. + fn in_one_frame(h: &mut Window, events: impl IntoIterator) { + one_frame(h, events); + h.run_steps(2); + } + + /// The Delete key going down, or up. + fn delete(pressed: bool) -> Event { + Event::Key { key: Key::Delete, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE } + } + + /// A turn of the mouse wheel. + fn wheel() -> Event { + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + modifiers: Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + } + } + + /// A key pressed and let go. + fn key(h: &mut Window, key: Key) { + h.key_press(key); + h.run_steps(2); + } + + fn layer_names(h: &Window) -> Vec { + h.state().session.map().layers.iter().map(|l| l.name.clone()).collect() + } + + fn cities(h: &Window) -> (usize, usize) { + let l = h.state().session.map().layer_by_name("Cities").unwrap(); + (l.dataset.features.len(), l.selection.len()) + } + + /// Whether a notice with exactly this text shows. + fn says(h: &Window, text: &str) -> bool { + h.state().map.toasts.iter().any(|t| t.text == text) + } + + /// Features selected, then a layer clicked in the list: Delete (and Backspace) removes that + /// layer in one Undo step and leaves the features. Once the map is scrolled, Delete is for the + /// features again (#2945). + #[test] + fn delete_removes_layers_in_the_layer_list_and_features_on_the_map() { + let mut app = RustGisApp::with_sample(); + app.run("edit.enable", json!({"on": true})).unwrap(); + app.run("select.all", json!({"layer": "Cities"})).unwrap(); + let mut h = window(app); + let (before, all) = (layer_names(&h), cities(&h)); + assert!(all.0 > 0 && all.0 == all.1, "every city is selected: {all:?}"); + assert_eq!(pane(h.state()), Pane::View, "nothing pressed yet"); + + for delete in [Key::Delete, Key::Backspace] { + h.get_by_label("Rivers").click(); + h.run_steps(2); + assert_eq!(pane(h.state()), Pane::Layers); + key(&mut h, delete); + assert!(!layer_names(&h).contains(&"Rivers".to_string()), "{delete:?} removed the layer clicked"); + assert_eq!(layer_names(&h).len(), before.len() - 1, "and only that one"); + assert_eq!(cities(&h), all, "the selected features stay"); + h.state_mut().run("edit.undo", Value::Null).unwrap(); + h.run_steps(2); + assert_eq!(layer_names(&h), before, "one Undo brings the layer back"); + } + + // The key held: its repeats remove nothing more, though the next layer is now the active + // one. Shift+Backspace is another key. + h.get_by_label("Rivers").click(); + h.run_steps(2); + h.key_down(Key::Delete); + h.run_steps(2); + assert_eq!(layer_names(&h).len(), before.len() - 1); + // Down again with no release between: a repeat, as a held key sends. + h.key_down(Key::Delete); + h.run_steps(2); + // Still held, and the wheel turned over the map: the key stays the layer list's, and its + // repeats don't reach the map's selected features. + let map = rect(&h, Pane::View).center(); + in_one_frame(&mut h, [Event::PointerMoved(map), wheel()]); + h.key_down(Key::Delete); + h.run_steps(2); + assert_eq!(cities(&h), all, "a key held since the layer list was in use deletes no features"); + h.key_up(Key::Delete); + h.get_by_label("Cities").click(); + h.run_steps(2); + h.key_press_modifiers(Modifiers::SHIFT, Key::Backspace); + h.run_steps(2); + assert_eq!(layer_names(&h).len(), before.len() - 1, "one press removes one layer: {:?}", layer_names(&h)); + h.state_mut().run("edit.undo", Value::Null).unwrap(); + h.run_steps(2); + + // A click and Delete in one frame: the key waits for the click, and removes the layer it + // picked, not the one picked before. + h.get_by_label("Cities").click(); + h.run_steps(2); + let rivers = h.get_by_label("Rivers").rect().center(); + let only_rivers_went = |h: &mut Window, when: &str| { + assert!( + !layer_names(h).contains(&"Rivers".to_string()) && layer_names(h).len() == before.len() - 1, + "{when}: {:?}", + layer_names(h) + ); + assert_eq!(cities(h), all, "{when}: the selected features stay"); + h.state_mut().run("edit.undo", Value::Null).unwrap(); + h.run_steps(2); + assert_eq!(layer_names(h), before); + h.get_by_label("Cities").click(); + h.run_steps(2); + }; + let click_and_delete = [Event::PointerMoved(rivers), button(rivers, true), button(rivers, false), delete(true), delete(false)]; + in_one_frame(&mut h, click_and_delete.clone()); + only_rivers_went(&mut h, "clicked and pressed in one frame"); + // Another layer clicked on the very next frame: the key was for the first click. + let cities_row = h.get_by_label("Cities").rect().center(); + one_frame(&mut h, click_and_delete); + in_one_frame(&mut h, [Event::PointerMoved(cities_row), button(cities_row, true), button(cities_row, false)]); + only_rivers_went(&mut h, "another layer clicked on the next frame"); + // The key first, then the click, in one frame: the key was for the layer picked before. + in_one_frame(&mut h, [delete(true), delete(false), Event::PointerMoved(rivers), button(rivers, true), button(rivers, false)]); + assert!(!layer_names(&h).contains(&"Cities".to_string()) && layer_names(&h).len() == before.len() - 1, "{:?}", layer_names(&h)); + h.state_mut().run("edit.undo", Value::Null).unwrap(); + h.run_steps(2); + h.get_by_label("Cities").click(); + h.run_steps(2); + // The button still down when the key comes: what the click picks isn't known yet, so the + // key is dropped, and nothing goes once the button is let go either. + one_frame(&mut h, [Event::PointerMoved(rivers), button(rivers, true)]); + // Another button pressed and let go meanwhile leaves the first one down. + let middle = |pressed| Event::PointerButton { pos: rivers, button: PointerButton::Middle, pressed, modifiers: Modifiers::NONE }; + one_frame(&mut h, [middle(true), middle(false)]); + in_one_frame(&mut h, [delete(true), delete(false)]); + assert_eq!(layer_names(&h), before, "nothing is removed while the button is down"); + h.event(button(rivers, false)); + h.run_steps(3); + assert_eq!(layer_names(&h), before, "nor once it is let go"); + // A touch the system took away: no release comes, and the keys run as before. + let cancel = Event::Touch { + device_id: egui::TouchDeviceId(0), + id: egui::TouchId(0), + phase: egui::TouchPhase::Cancel, + pos: rivers, + force: None, + }; + in_one_frame(&mut h, [Event::PointerMoved(rivers), button(rivers, true), cancel, Event::PointerGone]); + key(&mut h, Key::Delete); + assert_eq!(layer_names(&h).len(), before.len() - 1, "the key runs though no release came: {:?}", layer_names(&h)); + h.state_mut().run("edit.undo", Value::Null).unwrap(); + h.run_steps(2); + h.get_by_label("Cities").click(); + h.run_steps(2); + // A click that puts the cursor in the filter box: the key that came with it is the box's. + let filter = rect(&h, Pane::Layers).center_top() + vec2(0.0, 20.0); + in_one_frame(&mut h, [Event::PointerMoved(filter), button(filter, true), button(filter, false), delete(true), delete(false)]); + assert!(h.ctx.egui_wants_keyboard_input(), "the click is in the filter box"); + assert_eq!(layer_names(&h), before, "Delete in a text field removes no layer"); + h.key_press(Key::Escape); + h.run_steps(2); + + // The wheel over the map: the map is in use, with the layer list's click still the last. + h.get_by_label("Cities").click(); + h.run_steps(2); + let at = rect(&h, Pane::View).center(); + h.event(Event::PointerMoved(at)); + h.step(); + h.event(wheel()); + h.run_steps(2); + assert_eq!(pane(h.state()), Pane::View); + // Delete, then a layer clicked, in one frame: the key was pressed on the map. + in_one_frame(&mut h, [delete(true), delete(false), Event::PointerMoved(rivers), button(rivers, true), button(rivers, false)]); + assert_eq!(pane(h.state()), Pane::Layers); + assert_eq!(layer_names(&h), before, "Delete on the map removes no layer"); + assert_eq!(cities(&h), (0, 0), "it deletes the selected features"); + } + + /// F2 renames what the pane in use shows: the map or layout on the tabs and in a layout, the + /// active layer in the layer list and on the map. + #[test] + fn f2_renames_the_map_or_layout_on_its_tab_and_the_layer_elsewhere() { + let mut app = RustGisApp::with_sample(); + app.run("layout.new", json!({"name": "Sheet"})).unwrap(); + app.run("layout.close", Value::Null).unwrap(); + let map = app.session.map().name.clone(); + let mut h = window(app); + // What F2 opens, and the name it offers; the dialog is closed again. + let f2 = |h: &mut Window| { + key(h, Key::F2); + let asked = (h.state().dialogs.open, h.state().dialogs.text.clone()); + h.state_mut().dialogs.open = None; + h.run_steps(2); + asked + }; + + // The first tab is the map in view. + let tabs = rect(&h, Pane::Tabs); + press(&mut h, tabs.left_center() + vec2(40.0, 0.0)); + assert_eq!(pane(h.state()), Pane::Tabs); + assert_eq!(f2(&mut h), (Some("renameMap"), map)); + + h.state_mut().run("layout.activate", json!({"name": "Sheet"})).unwrap(); + h.run_steps(2); + assert_eq!(f2(&mut h), (Some("renameLayout"), "Sheet".to_string()), "on the tabs, with a layout in view"); + let view = rect(&h, Pane::View); + press(&mut h, view.left_top() + vec2(12.0, 12.0)); + assert_eq!(pane(h.state()), Pane::View); + assert_eq!(f2(&mut h), (Some("renameLayout"), "Sheet".to_string()), "in the layout"); + + h.get_by_label("Rivers").click(); + h.run_steps(2); + assert_eq!(f2(&mut h), (Some("renameLayer"), "Rivers".to_string()), "in the layer list, with a layout in view"); + + h.state_mut().run("layout.close", Value::Null).unwrap(); + h.run_steps(2); + let view = rect(&h, Pane::View); + press(&mut h, view.left_top() + vec2(12.0, 12.0)); + assert_eq!(pane(h.state()), Pane::View); + assert_eq!(f2(&mut h), (Some("renameLayer"), "Rivers".to_string()), "on the map"); + } + + /// Delete with nothing to act on says why, in each pane, and not twice while the notice shows. + #[test] + fn delete_with_nothing_to_act_on_says_why() { + let mut app = RustGisApp::with_sample(); + app.run("edit.enable", json!({"on": false})).unwrap(); + let mut h = window(app); + key(&mut h, Key::Delete); + assert!( + says(&h, "Delete: editing is turned off (Edit › Edit)"), + "{:?}", + h.state().map.toasts.iter().map(|t| &t.text).collect::>() + ); + + h.state_mut().run("edit.enable", json!({"on": true})).unwrap(); + key(&mut h, Key::Delete); + key(&mut h, Key::Delete); + assert_eq!(h.state().map.toasts.iter().filter(|t| t.text == "Delete: nothing is selected").count(), 1); + + // The layer list in use, with no layer picked in it. + h.get_by_label("Rivers").click(); + h.run_steps(2); + h.state_mut().session.active_layer = None; + key(&mut h, Key::Backspace); + assert!(says(&h, "Remove: select a layer in the Layers pane first")); + + h.state_mut().run("layout.new", json!({"name": "Sheet"})).unwrap(); + h.state_mut().layout.selected = None; + h.run_steps(2); + let view = rect(&h, Pane::View); + press(&mut h, view.left_top() + vec2(12.0, 12.0)); + h.state_mut().layout.selected = None; + key(&mut h, Key::Delete); + assert!(says(&h, "Delete Element: no element is selected")); + } + + /// A click that asks a question (a layout tab's close button: Delete Layout?) and Delete in + /// the same frame: the key is behind the question, and the layout's selected element stays. + #[test] + fn delete_with_the_click_that_asks_a_question_is_dropped() { + let mut app = RustGisApp::with_sample(); + app.run("layout.new", json!({"name": "Sheet"})).unwrap(); + let li = app.session.active_layout.unwrap(); + let title = app.session.project.layouts[li].elements.iter().find(|e| e.name == "Title").unwrap().id; + app.layout.selected = Some(title); + let mut h = window(app); + assert_eq!(h.state().layout.selected, Some(title)); + let close = h.get_by_label("Delete Layout").rect().center(); + in_one_frame(&mut h, [Event::PointerMoved(close), button(close, true), button(close, false), delete(true), delete(false)]); + assert!(h.state().map.deleting.is_some(), "the click asked whether to delete the layout"); + assert!(h.state().session.project.layouts[li].element(title).is_some(), "Delete didn't reach the element behind the question"); + } + + /// What ends the layer list's turn without a press in another pane, and what doesn't: its + /// own menu keeps it; a dialog, another project and the pane closing end it. + #[test] + fn the_layer_list_stays_in_use_only_while_the_user_is_in_it() { + let mut h = window(RustGisApp::with_sample()); + let list = |h: &mut Window| { + h.get_by_label("Rivers").click(); + h.run_steps(2); + assert_eq!(pane(h.state()), Pane::Layers); + }; + + // A row of the layer's own menu, wherever the menu reaches. + list(&mut h); + h.get_by_label("Rivers").click_secondary(); + h.run_steps(3); + h.get_by_label("Zoom To Layer").click(); + h.run_steps(3); + assert_eq!(pane(h.state()), Pane::Layers, "a menu is its pane's"); + + // A dialog's button. + h.state_mut().run("ui.dialog", json!({"name": "renameLayer"})).unwrap(); + h.run_steps(3); + h.get_by_label("Cancel").click(); + h.run_steps(3); + assert_eq!(pane(h.state()), Pane::Other, "a dialog is no pane"); + + // A press says where it was, though the pointer is over the list by the end of the frame. + list(&mut h); + let (map, layers) = (rect(&h, Pane::View).center(), rect(&h, Pane::Layers).center()); + in_one_frame(&mut h, [Event::PointerMoved(map), button(map, true), button(map, false), Event::PointerMoved(layers)]); + assert_eq!(pane(h.state()), Pane::View, "pressed on the map, then moved over the list"); + + // Command Search closed by a click beside it: a dialog, though the click is over the map. + list(&mut h); + h.state_mut().run("ui.commandSearch", Value::Null).unwrap(); + h.run_steps(3); + press(&mut h, map); + h.state_mut().ui.command_search = None; + h.run_steps(2); + assert_eq!(pane(h.state()), Pane::Other, "a modal dialog is no pane"); + + list(&mut h); + h.state_mut().run("project.new", Value::Null).unwrap(); + h.run_steps(2); + assert_eq!(pane(h.state()), Pane::View, "another project starts on the map"); + + h.state_mut().run("project.sample", Value::Null).unwrap(); + h.run_steps(3); + list(&mut h); + // The File menu's backstage opened by a command, with no press: it covers the list. + h.state_mut().run("ui.backstage", json!({"open": true})).unwrap(); + h.run_steps(2); + assert_eq!(pane(h.state()), Pane::Other, "the layer list is behind the backstage"); + h.state_mut().run("ui.backstage", json!({"open": false})).unwrap(); + h.run_steps(2); + // So are the tabs: F2 must not rename the map behind it. + let tabs = rect(&h, Pane::Tabs); + press(&mut h, tabs.left_center() + vec2(40.0, 0.0)); + assert_eq!(pane(h.state()), Pane::Tabs); + h.state_mut().run("ui.backstage", json!({"open": true})).unwrap(); + h.run_steps(2); + assert_eq!(pane(h.state()), Pane::Other, "the tabs are behind the backstage"); + h.state_mut().run("ui.backstage", json!({"open": false})).unwrap(); + h.run_steps(2); + list(&mut h); + // The wheel turned where the pane was drawn as it closed: it isn't there any more. + h.state_mut().ui.left = None; + one_frame(&mut h, [Event::PointerMoved(layers), wheel()]); + assert_eq!(pane(h.state()), Pane::Other, "the Layers pane closed"); + h.run_steps(2); + assert_eq!(pane(h.state()), Pane::Other); + h.state_mut().ui.left = Some(LeftPane::Contents); + h.run_steps(2); + assert_eq!(pane(h.state()), Pane::Other, "and open again, with no press in it"); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 403d4daad5..8966523c7b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -62,6 +62,7 @@ mod geometrycalc; mod globe_drape; mod graphicformat; pub mod icons; +mod inuse; mod keymap; mod labelfonts; mod labelpane; @@ -1014,6 +1015,8 @@ pub struct UiState { pub tab_strip_rect: Option, /// Where the left and right panes were drawn on the last frame, while they show. pub pane_rects: [Option; 2], + /// The pane the user is working in, for the keys that act on it. + pub(crate) in_use: inuse::InUse, /// Tabs hidden from the ribbon (Settings › Customize › Ribbon). pub hidden_tabs: Vec, /// Extra Quick Access Toolbar commands. @@ -1276,6 +1279,7 @@ impl Default for UiState { shortcut_preferences_full: false, tab_strip_rect: None, pane_rects: [None; 2], + in_use: inuse::InUse::default(), copy_out: None, open_url: None, copy_image: None, @@ -7551,6 +7555,8 @@ impl RustGisApp { let t = theme::Tokens::get(&ctx); // Before the shortcuts and the fields: the row picked in a text field's menu, as its keys. fieldmenu::play(self, &ctx); + // Before the shortcuts: a key acts on the pane this frame's press is in. + inuse::follow(self, &ctx); chrome::shortcuts(self, &ctx); panes::follow_layer_filter(self); // A Zarr summary or point series, a trend, a workflow, an export or a read running on its thread lands @@ -7606,6 +7612,9 @@ impl RustGisApp { chrome::about(self, &ctx); #[cfg(not(target_arch = "wasm32"))] agentthreads::windows(self, &ctx); + // The keys that follow a click of this frame, now that the panes have taken it and the + // dialogs it opened are up. Before the notices, which a key that can't run adds to. + chrome::late_keys(self, &ctx); chrome::notices(self, &ctx); // After every field is drawn: one right-clicked opens its menu. fieldmenu::show(self, &ctx); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 7f322f1daf..e47afb3909 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -856,6 +856,7 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { if app.chrome.is_none() { view_tabs(app, ui, &t); } + app.ui.in_use.drawn(crate::inuse::Pane::View, ui.layer_id(), ui.available_rect_before_wrap()); crate::vertexedit::cancel_stale_drag(app); crate::vertexedit::say_unplaced(app); if app.mb.shown() { @@ -4451,6 +4452,7 @@ fn popup(app: &mut RustGisApp, ui: &mut Ui, rect: Rect) { // Keyed by the feature: egui remembers an area's (and a scroll area's and grid's) size, and // the next popup mustn't start from the last one's. let key = (&layer, &title, attrs.len()); + let mut drawn = None; egui::Area::new(egui::Id::unique(("identify_popup", key))).fixed_pos(pos).order(egui::Order::Foreground).show(ui.ctx(), |ui| { let frame = egui::Frame::NONE .fill(t.menu) @@ -4636,7 +4638,12 @@ fn popup(app: &mut RustGisApp, ui: &mut Ui, rect: Rect) { new_limit = Some(vec2(limit.x + d.x, r.height() + d.y).clamp(vec2(240.0, 120.0), space)); } ui.ctx().data_mut(|d| d.insert_temp(shown_id, r.height())); + drawn = Some((ui.layer_id(), r)); }); + // The pop-up is the map's: a press in it leaves the layer list, as one on the map does. + if let Some((layer, r)) = drawn { + app.ui.in_use.drawn(crate::inuse::Pane::View, layer, r); + } if let Some(l) = new_limit { ui.ctx().data_mut(|d| d.insert_temp(limit_id, l)); } @@ -4815,6 +4822,7 @@ fn next_view_tab(ui: &mut Ui, w: f32) -> Rect { /// is always in sight. fn view_tabs(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::hover()); + app.ui.in_use.drawn(crate::inuse::Pane::Tabs, ui.layer_id(), r); ui.painter().rect_filled(r, 0.0, t.tab_strip); ui.painter().line_segment([pos2(r.min.x, r.max.y - 0.5), pos2(r.max.x, r.max.y - 0.5)], Stroke::new(1.0, t.border)); // The tabs take the strip but the New Map button's room and the gaps around it. diff --git a/crates/ui-egui/src/modelbuilder.rs b/crates/ui-egui/src/modelbuilder.rs index f557772f8a..0356ed15e8 100644 --- a/crates/ui-egui/src/modelbuilder.rs +++ b/crates/ui-egui/src/modelbuilder.rs @@ -115,6 +115,11 @@ impl ModelBuilder { self.open && self.active } + /// Whether a question about unsaved changes is up, or about to be drawn. + pub fn asking(&self) -> bool { + self.confirm.is_some() + } + /// Whether the canvas has changes not saved to the project. pub fn dirty(&self) -> bool { self.graph != self.saved || self.saved_as.as_deref().is_some_and(|s| s != self.name.trim()) @@ -587,19 +592,29 @@ fn request(app: &mut RustGisApp, p: Pending) { } /// ModelBuilder's keys, before the app's own: Delete (or Backspace) deletes the selection, -/// Ctrl+D duplicates the selected node, Ctrl+Z and Ctrl+Y undo and redo canvas edits. +/// Ctrl+D duplicates the selected node, Ctrl+Z and Ctrl+Y undo and redo canvas edits. With the +/// layer list in use, Delete and Backspace are left for it. pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { if !app.mb.shown() || ctx.egui_wants_keyboard_input() { return; } let cmd = egui::Modifiers::COMMAND; + // The pane in use as the key went down: the wheel turned over the canvas after it doesn't + // make the key the canvas's, on the same frame or while the key is held (its repeats are the + // pane's it was pressed in, as in `chrome::shortcuts`). + let layers = |key| { + let pressed_in = crate::inuse::press(app, key, None).map(|press| press.pane).or_else(|| crate::inuse::held_in(app, key)); + pressed_in.unwrap_or_else(|| crate::inuse::pane(app)) == crate::inuse::Pane::Layers + }; let (mut del, mut dup, mut undo, mut redo) = (false, false, false, false); ctx.input_mut(|i| { undo = i.consume_shortcut(&egui::KeyboardShortcut::new(cmd, egui::Key::Z)); redo = i.consume_shortcut(&egui::KeyboardShortcut::new(cmd | egui::Modifiers::SHIFT, egui::Key::Z)) || i.consume_shortcut(&egui::KeyboardShortcut::new(cmd, egui::Key::Y)); - if app.mb.selected.is_some() || app.mb.selected_edge.is_some() { - del = i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) || i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace); + // Nothing is deleted while a mouse button is down, as with the app's own Delete. + if (app.mb.selected.is_some() || app.mb.selected_edge.is_some()) && !crate::inuse::down(app) { + del = + [egui::Key::Delete, egui::Key::Backspace].into_iter().any(|key| !layers(key) && i.consume_key(egui::Modifiers::NONE, key)); } if app.mb.selected.is_some() { dup = i.consume_shortcut(&egui::KeyboardShortcut::new(cmd, egui::Key::D)); @@ -2120,6 +2135,55 @@ mod tests { assert_eq!(h.state().mb.graph.nodes.len(), 3, "the canvas is kept"); } + /// A layer clicked in the list with a node selected on the canvas: Delete is the list's. It + /// removes that layer and leaves the node (#2945). + #[test] + fn delete_is_the_layer_lists_while_it_is_in_use() { + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.ui.right_open.clear(); + app.ui.right = None; + app.run("ui.modelBuilder", Value::Null).unwrap(); + let node = app.mb.add(&Add::Input, pos2(0.0, 0.0)); + app.mb.selected = Some(node); + let layers = app.session.map().layers.len(); + // The whole window: the layer list beside the canvas. + let mut h = egui_kittest::Harness::builder().with_size(vec2(1300.0, 900.0)).with_max_steps(64).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(6); + assert!(h.state().mb.shown()); + h.get_by_label("Rivers").click(); + h.run_steps(2); + h.event(Event::Key { key: Key::Delete, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_eq!(h.state().mb.graph.nodes.len(), 1, "the node stays"); + assert_eq!(h.state().session.map().layers.len(), layers - 1); + assert!(h.state().session.map().layer_by_name("Rivers").is_none(), "Delete removed the layer clicked in the list"); + // The key still held, and the wheel turned over the canvas: its repeats stay the layer + // list's, and the node stays. + let canvas = pos2(800.0, 500.0); + h.event(Event::PointerMoved(canvas)); + h.step(); + h.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + modifiers: Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + }); + h.run_steps(2); + h.event(Event::Key { key: Key::Delete, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_eq!(h.state().mb.graph.nodes.len(), 1, "a held Delete's repeat on the canvas leaves the node"); + assert_eq!(h.state().session.map().layers.len(), layers - 1); + } + /// Closing with unsaved changes asks first; Discard closes, Cancel keeps the model open. #[test] fn closing_asks_about_unsaved_changes() { diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 6af05246b3..d1698c553e 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -49,7 +49,10 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { let rect = ui.available_rect_before_wrap(); let mut body = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(*ui.layout())); match left { - LeftPane::Contents => contents(app, &mut body, &t), + LeftPane::Contents => { + app.ui.in_use.drawn(crate::inuse::Pane::Layers, body.layer_id(), rect); + contents(app, &mut body, &t); + } LeftPane::Catalog => catalog(app, &mut body, &t), LeftPane::Sources => crate::sourcespane::show(app, &mut body, &t), } diff --git a/crates/ui-egui/src/table.rs b/crates/ui-egui/src/table.rs index 4154e44a96..377eea06ac 100644 --- a/crates/ui-egui/src/table.rs +++ b/crates/ui-egui/src/table.rs @@ -374,7 +374,8 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { } let t = Tokens::get(ui.ctx()); let pass = ui.ctx().cumulative_pass_nr(); - egui::Panel::bottom("attribute_table") + let layer = ui.layer_id(); + let panel = egui::Panel::bottom("attribute_table") .resizable(true) .default_size(250.0) .size_range(120.0..=600.0) @@ -800,6 +801,7 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { } } }); + app.ui.in_use.drawn(crate::inuse::Pane::Table, layer, panel.response.rect); statistics_window(app, ui.ctx()); } diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index 886ac80128..0c150a118d 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -546,14 +546,19 @@ with `{"layer":"parcels"}`. | ++ctrl+equal++ / ++ctrl+minus++ | Zoom in / out | | ++home++ | Full extent | | ++esc++ | Back to Explore; cancel a sketch | -| ++delete++ | Delete selected features; with Edit Vertices, the chosen vertex; in a layout, the selected element | +| ++delete++ | Delete selected features; with Edit Vertices, the chosen vertex; in a layout, the selected element; in the layer list, remove the selected layers (++backspace++ too) | | ++ctrl+d++ | Duplicate the selected layout element | | Arrow keys / ++shift++ + arrow keys | Nudge the selected layout element / nudge it further | | ++alt+shift+right++ / ++alt+shift+left++ | Indent the active layer into the group above it / outdent it out of its group | | ++alt+shift+up++ / ++alt+shift+down++ | Move the active layer up / down one step in the Layers pane | -| ++f2++ | Rename the active layer | +| ++f2++ | Rename the active layer; on the map and layout tabs, and in a layout, the map or layout in view | | ++ctrl+c++ / ++ctrl+x++ / ++ctrl+v++ | Copy / Cut / Paste features | On macOS, ++cmd++ takes the place of ++ctrl++. **Help › Shortcuts** lists them all in the app, from the same table the app runs them from. While you type in a text field, undo and redo take back its typing, not the project's last change. + +++delete++ and ++f2++ act on the part of the window you last clicked, dragged or scrolled in. +Click a layer in the Layers pane and ++delete++ removes it (Undo brings it back), whatever is +selected on the map; click or scroll the map and it deletes the selected features again. When +++delete++ has nothing to act on, a notice says why.