diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index e7efb8b9..4719071d 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -186,7 +186,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { /// rename, a number field) keeps the key for itself, and the key is left alone over other panels. fn select_all_layers(app: &mut TextureCraftApp, ui: &Ui) { let ctx = ui.ctx(); - if ctx.egui_wants_keyboard_input() || !ui.ui_contains_pointer() { + if crate::framework::widget_has_keyboard(ctx) || !ui.ui_contains_pointer() { return; } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index e7bb9497..6d827113 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -451,17 +451,6 @@ fn refresh_specs(app: &mut TextureCraftApp) { // --------------------------------------------------------------------------------------------- // Drawing -/// The viewport's id as the window's document canvas. -fn viewport_canvas_id() -> egui::Id { - egui::Id::unique("texturecraft-viewport-canvas") -} - -/// Declares the viewport, drawn in this pass, as the window's document canvas (the dock's canvas -/// group, or the whole window with the UI hidden). -pub(crate) fn host_viewport_canvas(ctx: &egui::Context) { - crate::framework::host_canvas(ctx, viewport_canvas_id()); -} - /// From a panel's left edge to its contents' text (an empty panel's note) pub(crate) const HEADER_TITLE_LEFT: f32 = 12.0; @@ -610,13 +599,12 @@ impl DockPanels for Panels<'_> { } } - /// The viewport, edge to edge in its group, as the window's document canvas. + /// The viewport, edge to edge in its group. fn group_view(&mut self, panels: &[Panel], _: usize, ui: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { let GroupAt::Show(rect) = at else { return None }; if !panels.contains(&Panel::Viewport) { return None; } - host_viewport_canvas(ui.ctx()); crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect()); ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport); crate::viewport::central(self.app, ui); diff --git a/crates/ui-egui/src/framework.rs b/crates/ui-egui/src/framework.rs index 28a3bcbf..78637b68 100644 --- a/crates/ui-egui/src/framework.rs +++ b/crates/ui-egui/src/framework.rs @@ -6,10 +6,10 @@ //! //! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of TextureCraft's own egui //! widgets has the keyboard. The window's Escape is read with [`escape_pressed`] and taken with -//! [`take_window_cancel`], its plain Enter taken with [`take_window_submit`]; the 3D/2D viewport is declared to the runtime with [`host_canvas`], which keeps the edit -//! chords and the clipboard events in egui's input for TextureCraft's shortcuts. A bare Tab with nothing focused -//! toggles the window's chrome in the runtime ([`RootEnv::tab_toggles_chrome`]), which `frame_input` turns into Hide UI; -//! with the viewport focused, Tab stays in egui for the shortcut table's `ui.hideUi`. +//! [`take_window_cancel`], its plain Enter taken with [`take_window_submit`]; the 3D and 2D views are declared to the runtime with [`host_canvas`], which keeps the edit +//! chords and the clipboard events in egui's input for TextureCraft's shortcuts. A bare Tab with nothing or a view +//! focused toggles the window's chrome in the runtime ([`RootEnv::tab_toggles_chrome`]), which `frame_input` turns into +//! Hide UI. A focused view leaves the keyboard to the shortcuts ([`widget_has_keyboard`]). use std::sync::{Arc, OnceLock}; @@ -19,7 +19,7 @@ use craft_keymap::Overrides; use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts}; use craft_ui::runtime::commands::{ChromeCommand, CommandInput, CommandSet as _, NavCommand, QuitCommand}; use craft_ui::runtime::env::{RootEnv, Scale}; -use craft_ui::runtime::focus::{EditSet, KeepKeys, KeyUse}; +use craft_ui::runtime::focus::{EditSet, KeyUse}; use craft_ui::runtime::frame::{ChromeToggle, FrameInput, FrameOutput}; use craft_ui::runtime::keys::{Intent, with_window_intents}; use craft_ui::shell::embed::{self, CloseDecision}; @@ -105,11 +105,11 @@ impl TextureCraftApp { } /// The root values of this frame. TextureCraft registers no commands with the runtime (its own shortcut table - /// runs every key, [`command_overrides`]). The runtime toggles the chrome on a bare Tab with nothing focused - /// (`tab_toggles_chrome`, the viewport being the registered canvas), and each panels toggle it recorded for the - /// root window flips Hide UI, as the `ui.hideUi` command does; with the viewport focused, Tab stays in egui for - /// that command ([`host_canvas`]), so one Tab flips Hide UI once. While one of TextureCraft's own egui modals - /// shows in the root window, the runtime blocks the panels floated into windows of their own. + /// runs every key, [`command_overrides`]). The runtime toggles the chrome on a bare Tab with nothing or a + /// view focused (`tab_toggles_chrome`, the views being the registered canvases) and takes it out of egui's input, and + /// each panels toggle it recorded for the root window flips Hide UI, as the `ui.hideUi` command does. While one of + /// TextureCraft's own egui modals shows in the root window, the runtime blocks the panels floated into windows of + /// their own. pub(crate) fn frame_input(&mut self, ctx: &egui::Context, output: FrameOutput, scale: f32) -> FrameInput { for (viewport, toggle) in &output.chrome_toggles { if *viewport == ViewportId::ROOT && *toggle == ChromeToggle::Panels { @@ -135,15 +135,27 @@ impl TextureCraftApp { } } -/// Declares the viewport `id`, drawn in this pass, as the window's document canvas. With nothing focused it is the -/// window's key target: the edit chords and the clipboard events stay in egui's input for TextureCraft's shortcuts. -/// A bare Tab with nothing focused is the runtime's chrome toggle (`frame_input`); with the viewport focused, the -/// canvas keeps Tab in egui for the shortcut table's Hide UI. +/// Declares the view `id`, an egui widget drawn in this pass, as a document canvas of the window. With nothing or the +/// view focused, the edit chords and the clipboard events stay in egui's input for TextureCraft's shortcuts, and a bare +/// Tab is the runtime's chrome toggle (`frame_input`). Tab and Shift+Tab stop at the view, Shift+Tab moves on from it, +/// and a click gives it no focus. pub(crate) fn host_canvas(ctx: &egui::Context, id: egui::Id) { - const KEYS: KeyUse = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL); + const KEYS: KeyUse = KeyUse::CANVAS.with_edits(EditSet::ALL); craft_ui::runtime::focus::host_canvas(ctx, id, KEYS); } +/// The widget that has the keyboard, the 3D and 2D views left out: a focused view leaves the keyboard to +/// TextureCraft's shortcuts, as with nothing focused. +pub(crate) fn focused_widget(ctx: &egui::Context) -> Option { + use crate::viewport::{view_2d_id, view_3d_id}; + ctx.memory(|memory| memory.focused()).filter(|focused| ![view_3d_id(), view_2d_id()].contains(focused)) +} + +/// Whether a widget other than the 3D and 2D views has the keyboard. +pub(crate) fn widget_has_keyboard(ctx: &egui::Context) -> bool { + focused_widget(ctx).is_some() +} + /// Whether Escape was pressed in this pass: from egui while one of TextureCraft's own widgets or popups has the /// keyboard, otherwise the window's cancel, which the runtime routes to no component. Leaves it for later readers. pub(crate) fn escape_pressed(ctx: &egui::Context) -> bool { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1466a2f1..844a8b36 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1204,7 +1204,6 @@ impl eframe::App for TextureCraftApp { let panel_frame = if hide_ui { egui::Frame::NONE.fill(tokens.viewport) } else { egui::Frame::NONE.fill(tokens.chrome).inner_margin(theme::GUTTER) }; egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| { if hide_ui { - docking::host_viewport_canvas(ui.ctx()); viewport::central(self, ui); } else { docking::show(self, ui); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 46e02bdc..b2282360 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -447,9 +447,9 @@ fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { } } -/// Runs the commands bound to the keys pressed this frame, outside text fields and key capture +/// Runs the commands bound to the keys pressed this frame, with no widget but the viewport focused, outside key capture pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { - if crate::keymap::capturing(ctx) || (ctx.memory(|memory| memory.focused().is_some()) && ctx.egui_wants_keyboard_input()) { + if crate::keymap::capturing(ctx) || crate::framework::widget_has_keyboard(ctx) { return; } @@ -487,9 +487,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { let popup_open = egui::Popup::is_any_open(ctx) || app.ui.export.pending_drop.is_some(); let picker_open = crate::color_picker::open_window(ctx).is_some(); - let no_widget_focused = ctx.memory(|memory| memory.focused().is_none()); - #[cfg(not(target_arch = "wasm32"))] - let nothing_focused = ctx.memory(|memory| memory.focused().is_none()); + let nothing_focused = !crate::framework::widget_has_keyboard(ctx); let log_copies = crate::log_panel::takes_copy(app, ctx); let commands_to_invoke = ctx.input_mut(|input| { // egui's label selection copies on these events at the end of the frame @@ -501,7 +499,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Escape and Enter answer the Reset UI question first, even when a shortcut binds them let confirming_reset = app.ui.windows.confirm_reset_ui; if confirming_reset && !popup_open { - crate::windows::reset_ui_keys(app, input, no_widget_focused); + crate::windows::reset_ui_keys(app, input, nothing_focused); } // F2 renames the selected template on Output templates, before its 3D view binding diff --git a/crates/ui-egui/src/property_sheet/color_bar.rs b/crates/ui-egui/src/property_sheet/color_bar.rs index c83ff515..bf295906 100644 --- a/crates/ui-egui/src/property_sheet/color_bar.rs +++ b/crates/ui-egui/src/property_sheet/color_bar.rs @@ -286,7 +286,7 @@ impl PropertySheet<'_> { // Escape ends hex editing first even when egui has already dropped the field's focus let escape = - crate::framework::escape_pressed(&ctx) && ctx.memory(|memory| memory.focused().is_none_or(|focused| focused == bar.id)) && !hex_took_escape(&ctx); + crate::framework::escape_pressed(&ctx) && crate::framework::focused_widget(&ctx).is_none_or(|focused| focused == bar.id) && !hex_took_escape(&ctx); if closed || (!list_open && !waiting && (pressed_outside || escape)) { state.open = false; crate::color_picker::forget_window(&ctx); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 95f05acf..4e7634d4 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -60,6 +60,24 @@ fn aux_view(app: &TextureCraftApp) -> Option { } } +/// The 3D view's widget: the same in the dock and with the UI hidden, so it keeps the focus when Tab hides the UI +pub fn view_3d_id() -> egui::Id { + egui::Id::unique("texturecraft-view3d") +} + +/// The 2D view's widget, as [`view_3d_id`] +pub fn view_2d_id() -> egui::Id { + egui::Id::unique("texturecraft-view2d") +} + +/// Draw the widget of a view and declare it as a document canvas of the window. In a split view both are, so the keys +/// are the same in either. +fn view_widget(ui: &Ui, rect: Rect, id: egui::Id, sense: Sense) -> egui::Response { + let response = ui.interact(rect, id, sense); + crate::framework::host_canvas(ui.ctx(), id); + response +} + /// The viewport dock tab: the paint bar, then the 3D and 2D views in the chosen layout with the mode's overlays pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let mode = app.ui.mode; @@ -183,6 +201,8 @@ fn empty_views(app: &mut TextureCraftApp, ui: &mut Ui) { }; for (rect, id) in regions { + // Nothing to click or drag, but still the window's canvas: Tab hides and shows the UI + view_widget(ui, rect, if id == "v2d" { view_2d_id() } else { view_3d_id() }, Sense::focusable_noninteractive()); ui.painter().rect_filled(rect, 0.0, tokens.viewport); view_header(app, ui, rect, id); } @@ -732,7 +752,7 @@ pub(crate) fn orbit(app: &mut TextureCraftApp, delta: egui::Vec2) { } fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { - let response = ui.interact(rect, ui.scope_id().with("view3d"), Sense::click_and_drag()); + let response = view_widget(ui, rect, view_3d_id(), Sense::click_and_drag()); app.viewport_rect = rect; let size = rect.size(); app.session.viewport = Vec2::new(size.x.max(MIN_CAMERA_VIEWPORT), size.y.max(MIN_CAMERA_VIEWPORT)); @@ -747,7 +767,8 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Navigation; S + drag moves the projection stencil instead, below let delta = ui.input(|input| input.pointer.delta()); - let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(STENCIL_KEY)) && !ui.ctx().egui_wants_keyboard_input(); + let s_held = + app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(STENCIL_KEY)) && !crate::framework::widget_has_keyboard(ui.ctx()); // Only an equipped Projection tool that can act moves its stencil: it isn't drawn otherwise let stencil_moves = tool_acts(app) && app.session.tool.tool == Tool::Projection; @@ -1209,7 +1230,7 @@ fn path_keys(app: &mut TextureCraftApp, ui: &Ui) { return; } - if !tool_acts(app) || app.session.tool.tool != Tool::Path || app.session.tool.path.points.is_empty() || ui.ctx().egui_wants_keyboard_input() { + if !tool_acts(app) || app.session.tool.tool != Tool::Path || app.session.tool.path.points.is_empty() || crate::framework::widget_has_keyboard(ui.ctx()) { return; } @@ -1686,7 +1707,10 @@ fn uv_fill_box_corners(view: crate::uv_view_map::UvViewMap, [origin, opposite]: /// V held with the Clone tool in painting mode: clicks set the clone source fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool { - tool_acts(app) && app.session.tool.tool == Tool::Clone && ui.input(|input| input.key_down(CLONE_SOURCE_KEY)) && !ui.ctx().egui_wants_keyboard_input() + tool_acts(app) + && app.session.tool.tool == Tool::Clone + && ui.input(|input| input.key_down(CLONE_SOURCE_KEY)) + && !crate::framework::widget_has_keyboard(ui.ctx()) } /// Crosshair where the Clone tool reads from. @@ -2069,7 +2093,7 @@ fn framed_tile_view(set: &texturecraft_engine::core::TextureSet, size: egui::Vec /// The 2D (UV) view: navigation, painting in texture coordinates and the overlays drawn over the texture. fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { let tokens = Tokens::get(ui.ctx()); - let response = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); + let response = view_widget(ui, rect, view_2d_id(), Sense::click_and_drag()); let size = rect.size(); let (alt, shift, snap) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift, input.modifiers.shift && input.modifiers.command)); let ctrl = ui.input(|input| input.modifiers.ctrl); diff --git a/crates/ui-egui/tests/it/fill_material_rows.rs b/crates/ui-egui/tests/it/fill_material_rows.rs index 7aae83bf..fe0091a1 100644 --- a/crates/ui-egui/tests/it/fill_material_rows.rs +++ b/crates/ui-egui/tests/it/fill_material_rows.rs @@ -503,6 +503,14 @@ fn the_picker_is_a_window_beside_the_panel_that_its_title_drags_and_its_close_or harness.run_steps(SETTLE_FRAMES); assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "Escape closes it"); + + click(&mut harness, Role::Button, "Base color"); + harness.ctx.memory_mut(|memory| memory.request_focus(texturecraft_ui_egui::viewport::view_3d_id())); + harness.run_steps(SETTLE_FRAMES); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "Escape closes it with the viewport focused"); } #[test] diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 44cc994a..f3b4fd5a 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -102,6 +102,7 @@ mod user_smart_mask; mod view2d_navigation; mod view2d_tiles; mod view_mode_picker; +mod viewport_focus; mod window_menu_684; mod filter_card; diff --git a/crates/ui-egui/tests/it/viewport_focus.rs b/crates/ui-egui/tests/it/viewport_focus.rs new file mode 100644 index 00000000..20eca85c --- /dev/null +++ b/crates/ui-egui/tests/it/viewport_focus.rs @@ -0,0 +1,228 @@ +//! The 3D and 2D views as Tab stops: they keep the focus Tab gives them, Tab on one hides and shows the UI, Shift+Tab +//! moves on from it, and the keys of the viewport work as with nothing focused. + +use craft_ui::runtime::focus::{FocusTarget, request}; +use egui::{Event, Id, Key, Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; +use serde_json::json; +use texturecraft_engine::{Session, Tool, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; +use texturecraft_ui_egui::viewport::{view_2d_id, view_3d_id}; + +type AppHarness = Harness<'static, TextureCraftApp>; + +fn harness(session: Session, layout: ViewLayout) -> AppHarness { + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.state_mut().ui.layout = layout; + h.run_steps(4); + h +} + +fn sample() -> Session { + texturecraft_engine::sample_session(256, 64).unwrap() +} + +fn focused(h: &AppHarness) -> Option { + h.ctx.memory(|memory| memory.focused()) +} + +/// Focus `view` as Tab does +fn focus(h: &mut AppHarness, view: Id) { + request(&h.ctx, FocusTarget::Id(view)); + h.run_steps(2); + assert_eq!(focused(h), Some(view)); +} + +fn press(h: &mut AppHarness, modifiers: Modifiers, key: Key) { + h.key_press_modifiers(modifiers, key); + h.run_steps(3); +} + +fn hidden(h: &AppHarness) -> bool { + h.state().ui.hide_ui +} + +/// The views each layout draws +const DRAWN: [(ViewLayout, bool, bool); 3] = [(ViewLayout::Only3D, true, false), (ViewLayout::Only2D, false, true), (ViewLayout::Split, true, true)]; + +#[test] +fn shift_tab_walks_over_the_views_and_tab_on_one_toggles_the_ui_once() { + let mut h = harness(sample(), ViewLayout::Split); + let mut walked = Vec::new(); + while focused(&h) != Some(view_3d_id()) { + press(&mut h, Modifiers::SHIFT, Key::Tab); + assert!(focused(&h).is_some(), "Shift+Tab {} keeps a focus", walked.len()); + walked.push(focused(&h).unwrap()); + assert!(walked.len() < 400, "Shift+Tab reaches the 3D view"); + } + assert!(walked.iter().position(|stop| *stop == view_2d_id()).is_some_and(|at| at > 0), "it passes the stops after the views, then the 2D view"); + + press(&mut h, Modifiers::SHIFT, Key::Tab); + let before = focused(&h).expect("Shift+Tab moves on from the view"); + assert!(!walked.contains(&before)); + press(&mut h, Modifiers::NONE, Key::Tab); + assert_eq!(focused(&h), Some(view_3d_id()), "Tab from the stop before the view stops at it"); + assert!(!hidden(&h)); + + press(&mut h, Modifiers::NONE, Key::Tab); + assert!(hidden(&h), "Tab on the focused view hides the UI"); + assert_eq!(focused(&h), Some(view_3d_id()), "which keeps the focus"); + press(&mut h, Modifiers::NONE, Key::Tab); + assert!(!hidden(&h), "the next Tab shows it"); + press(&mut h, Modifiers::SHIFT, Key::Tab); + assert_eq!(focused(&h), Some(before), "Shift+Tab leaves the view backward"); +} + +#[test] +fn every_drawn_view_holds_the_focus_and_toggles_the_ui_with_and_without_a_project() { + for (layout, in_3d, in_2d) in DRAWN { + for project in [true, false] { + for view in [view_3d_id(), view_2d_id()].into_iter().zip([in_3d, in_2d]).filter_map(|(view, drawn)| drawn.then_some(view)) { + let mut h = harness(if project { sample() } else { Session::closed().unwrap() }, layout); + for focus_view in [false, true] { + if focus_view { + focus(&mut h, view); + } + for shown_next in [false, true] { + press(&mut h, Modifiers::NONE, Key::Tab); + assert_eq!(hidden(&h), !shown_next, "project {project}, focused {focus_view}"); + assert_eq!(focused(&h), focus_view.then_some(view), "project {project}"); + } + } + } + } + } +} + +#[test] +fn a_click_in_either_view_leaves_tab_to_the_ui_toggle() { + for (clicked, with_focus) in [(view_3d_id(), view_3d_id()), (view_2d_id(), view_2d_id()), (view_2d_id(), view_3d_id())] { + let mut h = harness(sample(), ViewLayout::Split); + focus(&mut h, with_focus); + let at = h.ctx.read_response(clicked).unwrap().rect.center(); + for pressed in [true, false] { + h.hover_at(at); + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(3); + } + press(&mut h, Modifiers::NONE, Key::Tab); + assert!(hidden(&h)); + press(&mut h, Modifiers::NONE, Key::Tab); + assert!(!hidden(&h)); + } +} + +#[test] +fn shortcuts_run_with_a_view_focused() { + for view in [view_3d_id(), view_2d_id()] { + let mut h = harness(sample(), ViewLayout::Split); + let name = h.state().session.doc.project.layers[&h.state().session.selected_layer().unwrap()].name.clone(); + let row = h.get_by_label(&name).rect().center(); + focus(&mut h, view); + let layers = |h: &AppHarness| h.state().session.doc.project.layers.len(); + let before = layers(&h); + h.event(Event::Copy); + h.run_steps(3); + assert!(h.state().session.clipboard.is_some(), "Ctrl+C copies the layer"); + h.event(Event::Paste("Layer".into())); + h.run_steps(3); + assert!(layers(&h) > before, "Ctrl+V pastes it"); + press(&mut h, Modifiers::COMMAND, Key::Z); + assert_eq!(layers(&h), before, "Ctrl+Z takes it back"); + + let size = h.state().session.tool.brush.size; + press(&mut h, Modifiers::NONE, Key::CloseBracket); + assert!(h.state().session.tool.brush.size > size, "] grows the brush"); + + h.hover_at(row); + h.run_steps(1); + press(&mut h, Modifiers::COMMAND, Key::A); + let session = &h.state().session; + let every_row = texturecraft_engine::layer_selection::stack_rows(&session.doc.project, 0, true); + assert_eq!(session.selected_layers().len(), every_row.len(), "Ctrl+A over the Layers panel selects every row"); + assert_eq!(focused(&h), Some(view)); + } +} + +#[test] +fn the_path_keys_work_with_the_view_focused() { + let mut session = sample(); + execute(&mut session, "layer.add.paint", &json!(null)).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + let mut h = harness(session, ViewLayout::Only2D); + let place = |h: &mut AppHarness| { + execute(&mut h.state_mut().session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.5], [0.8, 0.5]], "commit": false})).unwrap(); + h.run_steps(3); + }; + let points = |h: &AppHarness| h.state().session.tool.path.points.len(); + focus(&mut h, view_2d_id()); + + place(&mut h); + press(&mut h, Modifiers::NONE, Key::Backspace); + assert_eq!(points(&h), 2, "Backspace removes one point"); + let (effect, index) = h.state().session.tool.path.editing.unwrap(); + press(&mut h, Modifiers::NONE, Key::Enter); + assert!(points(&h) == 0 && h.state().session.paths(effect).is_some_and(|paths| paths.get(index).is_some()), "Enter applies the path"); + + place(&mut h); + assert_eq!(points(&h), 3); + press(&mut h, Modifiers::NONE, Key::Escape); + assert_eq!(points(&h), 0, "Escape cancels the next one"); + assert_eq!(focused(&h), Some(view_2d_id())); +} + +#[test] +fn held_keys_work_with_the_view_focused() { + let mut session = sample(); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let image = session.import_resource_bytes("logo.png", png).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": image})).unwrap(); + session.tool.tool = Tool::Projection; + let mut h = harness(session, ViewLayout::Only3D); + focus(&mut h, view_3d_id()); + + let scale = |h: &AppHarness| h.state().session.tool.stencil.as_ref().unwrap().scale; + let (before, yaw) = (scale(&h), h.state().session.camera.yaw); + hold_and_right_drag(&mut h, Key::S); + assert_ne!(scale(&h), before, "S + right drag scales the stencil"); + assert_eq!(h.state().session.camera.yaw, yaw, "instead of turning the camera"); + assert_eq!(focused(&h), Some(view_3d_id())); +} + +fn hold_and_right_drag(h: &mut AppHarness, key: Key) { + let from = h.state().viewport_rect.center(); + let button = |h: &mut AppHarness, pos: Pos2, pressed| { + h.event(Event::PointerButton { pos, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); + }; + h.event(Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.hover_at(from); + button(h, from, true); + h.run_steps(2); + for step in 1..=4 { + h.hover_at(from + egui::vec2(15.0 * step as f32, 0.0)); + h.run_steps(1); + } + button(h, from + egui::vec2(60.0, 0.0), false); + h.event(Event::Key { key, physical_key: Some(key), pressed: false, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(3); +} + +#[test] +fn escape_and_enter_answer_a_question_with_a_view_focused() { + for (key, reset) in [(Key::Escape, false), (Key::Enter, true)] { + let mut h = harness(sample(), ViewLayout::Only3D); + h.state_mut().ui.windows.confirm_reset_ui = true; + h.run_steps(3); + focus(&mut h, view_3d_id()); + press(&mut h, Modifiers::NONE, key); + assert!(!h.state().ui.windows.confirm_reset_ui, "{key:?} answers the question"); + assert_eq!(h.state().ui.layout == ViewLayout::Split, reset, "only Enter resets the layout"); + } +}