diff --git a/crates/engine/src/keys.rs b/crates/engine/src/keys.rs index 0501a0299..c28430043 100644 --- a/crates/engine/src/keys.rs +++ b/crates/engine/src/keys.rs @@ -293,6 +293,14 @@ impl Session { Ok(true) } + /// Whether Tab has something to do here: text is being edited (it indents, types a tab or goes to the next table + /// cell), or the slide has an object after the selected one. Past the last object it has nothing left to select. + pub fn tab_has_work(&self) -> bool { + let Some(st) = self.active() else { return false }; + let last = st.shapes().iter().rev().find(|s| !s.hidden).map(|s| s.id); + st.selection.text.is_some() || (last.is_some() && st.selection.shapes.first().copied() != last) + } + fn cycle_selection(&mut self, forward: bool) -> Result<()> { let st = self.doc()?; let ids: Vec<_> = st.shapes().iter().filter(|s| !s.hidden).map(|s| s.id).collect(); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d6f385d57..845f591f1 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -13,6 +13,7 @@ use super::{ mod clipboard; mod commands; mod control; +mod document_focus; pub(crate) mod files; mod frame; mod ime; @@ -22,6 +23,7 @@ mod playback; #[cfg(test)] pub(crate) use clipboard::{OBJECTS_MARKER, system_clipboard_text}; +pub(crate) use document_focus::DocumentFocus; #[cfg(test)] pub(crate) use files::web_image_files; pub use keys::key_name; @@ -69,6 +71,7 @@ impl SlideApp { synthetic_generation: 0, synthetic_target: None, synthetic_focus: None, + document_focus: DocumentFocus::default(), synthetic_injected_time: None, ribbon_scroll: HashMap::new(), show_instance: 0, @@ -287,8 +290,7 @@ impl SlideApp { let ctx = ui.ctx().clone(); self.ime_frame_viewport = Some(ctx.viewport_id()); self.ime_pending = None; - // Every pass, discarded ones included: the runtime routes the next frame's keys by the last pass's canvas. - crate::framework::host_canvas(&ctx); + let document_before = self.document_focus.drawn.take(); if !self.ui_setup(&ctx) { // This pass is discarded for the new fonts. The input events were already consumed // by egui, so keep them queued for the next frame instead of silently losing them. @@ -352,6 +354,7 @@ impl SlideApp { } } }); + self.finish_document(&ctx, document_before); toast::note_missing_fonts(self); toast::show(self, &ctx); dialogs::show(self, &ctx); diff --git a/crates/ui-egui/src/app/document_focus.rs b/crates/ui-egui/src/app/document_focus.rs new file mode 100644 index 000000000..74b2f1e67 --- /dev/null +++ b/crates/ui-egui/src/app/document_focus.rs @@ -0,0 +1,87 @@ +//! The document window (the slide canvas, the slide sorter or the notes page) as the window's one document canvas: its +//! widget, its Tab stop and when it takes the keyboard focus. + +use craft_ui::runtime::overlay::{self, OpenFilter}; + +use super::{SlideApp, ViewMode}; +use crate::framework::{document_id, focus_document, focused_widget, host_canvas}; + +/// What the document window's focus depends on from pass to pass. +#[derive(Default)] +pub(crate) struct DocumentFocus { + /// The presentation (its uid) whose document window the pass drew; `None` on the start screen, the File tab and in + /// a slide show. + pub(super) drawn: Option, + /// A presentation opened or became active and has yet to ask for the focus. + wanted: bool, +} + +impl SlideApp { + /// Draws the document window's widget over `rect` and declares it as the window's canvas. A press in it gives it + /// the focus. Real presses only: with the document focused, egui makes Enter and Space clicks of it. + pub(crate) fn document_widget(&mut self, ui: &egui::Ui, rect: egui::Rect, sense: egui::Sense) -> egui::Response { + let resp = ui.interact(rect, document_id(), sense); + self.document_focus.drawn = self.session.active().map(|d| d.uid); + host_canvas(ui.ctx(), self.document_keeps_tab(ui.ctx())); + if resp.is_pointer_button_down_on() && ui.input(|i| i.pointer.any_pressed()) { + focus_document(ui.ctx()); + } + resp + } + + /// Whether the focused document keeps Tab: on the slide, while the session has something for it to do. A modal + /// dialog, a menu or a popup that is up gets it instead. + fn document_keeps_tab(&self, ctx: &egui::Context) -> bool { + matches!(self.ui.view, ViewMode::Normal | ViewMode::Outline | ViewMode::Reading) && self.session.tab_has_work() && !self.overlay_open(ctx) + } + + /// Whether a modal dialog, DeckCraft's or the framework's, the palette, the opening overlay, or an egui menu or + /// popup is up. + pub(super) fn overlay_open(&self, ctx: &egui::Context) -> bool { + self.dialog.as_ref().is_some_and(|d| d.modal()) + || self.palette.is_some() + || self.opening.is_some() + || ctx.any_popup_open() + || egui::Popup::is_any_open(ctx) + || overlay::any_open(ctx, OpenFilter::Modal) + } + + /// Ends the document window's pass, after the views; `before` is the presentation the last pass drew. The pass's + /// input has changed what Tab has to do, so the document is declared again. One that opened or became active asks + /// for the focus. It waits for a modal dialog, menu or popup to close, and leaves the focus with a text field and + /// with a widget of another layer. + pub(super) fn finish_document(&mut self, ctx: &egui::Context, before: Option) { + let drawn = self.document_focus.drawn; + if drawn.is_none() { + self.document_focus.wanted = false; + return; + } + host_canvas(ctx, self.document_keeps_tab(ctx)); + self.document_focus.wanted |= drawn != before; + if !self.document_focus.wanted || self.overlay_open(ctx) { + return; + } + self.document_focus.wanted = false; + let layer = |id| ctx.read_response(id).map(|widget| widget.layer_id); + if !ctx.text_edit_focused() && focused_widget(ctx).is_none_or(|id| layer(id) == layer(document_id())) { + focus_document(ctx); + } + } + + /// While slide text is being edited, the text owns the keyboard (#93): a stray focus on an ordinary widget (the + /// window's drag handle, a ribbon button) would swallow every later key and end text entry, and with nothing + /// focused Tab would leave the text. The document takes the focus back; a text field or an open menu keeps its keys. + pub(super) fn edited_text_takes_focus(&self, ctx: &egui::Context) { + let editing = self.session.active().is_some_and(|d| d.selection.text.is_some()); + if !editing || ctx.text_edit_focused() || self.overlay_open(ctx) { + return; + } + if ctx.read_response(document_id()).is_some() { + if !ctx.memory(|m| m.has_focus(document_id())) { + focus_document(ctx); + } + } else if let Some(id) = ctx.memory(|m| m.focused()) { + ctx.memory_mut(|m| m.surrender_focus(id)); + } + } +} diff --git a/crates/ui-egui/src/app/ime.rs b/crates/ui-egui/src/app/ime.rs index 3632b368f..4aaa6d031 100644 --- a/crates/ui-egui/src/app/ime.rs +++ b/crates/ui-egui/src/app/ime.rs @@ -145,7 +145,7 @@ impl SlideApp { && ctx.input(|i| i.viewport().focused.unwrap_or(true)) && ctx.input(|i| i.viewport().visible() != Some(false)) && !ctx.input(|i| i.viewport().close_requested()) - && ctx.memory(|m| m.focused().is_none()) + && !crate::framework::widget_has_keyboard(ctx) && self.dialog.as_ref().is_none_or(|d| !d.modal()) && self.palette.is_none() && self.backstage.is_none() diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index c50601712..701f08f32 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -140,7 +140,7 @@ impl SlideApp { return; } let current = self.input_target(); - let focus = ctx.memory(|m| m.focused()); + let focus = crate::framework::focused_widget(ctx); if self.synthetic_target == Some(current) && focus == self.synthetic_focus { return; } @@ -210,7 +210,7 @@ impl SlideApp { Err(e) => self.set_status(e), } } - let focus = ctx.memory(|m| m.focused()); + let focus = crate::framework::focused_widget(ctx); if self.synthetic_pending { let current = self.input_target(); if self.synthetic_target != Some(current) || focus != self.synthetic_focus { diff --git a/crates/ui-egui/src/app/keys.rs b/crates/ui-egui/src/app/keys.rs index cab80571a..4c2769e6d 100644 --- a/crates/ui-egui/src/app/keys.rs +++ b/crates/ui-egui/src/app/keys.rs @@ -1,5 +1,6 @@ use super::clipboard::OBJECTS_MARKER; use super::{Mods, SlideApp, Value, backstage, json, menus}; +use crate::framework::widget_has_keyboard; impl SlideApp { /// The app shortcuts that still make sense on the empty File/start screen: create, open, @@ -47,7 +48,7 @@ impl SlideApp { } } - /// Keyboard and clipboard for the slide (when no text field has focus). + /// Keyboard and clipboard for the slide (with nothing or the document window focused). pub(super) fn keyboard(&mut self, ctx: &egui::Context) { let mut events = ctx.input(|i| i.events.clone()); if crate::framework::window_escape(ctx) { @@ -79,26 +80,15 @@ impl SlideApp { // File-tab navigation and document-free shortcuts remain available. self.suspend_ime_reset(viewport); self.route_ime_controls_only(ctx, &events); - if self.palette.is_none() && self.dialog.as_ref().is_none_or(|d| !d.modal()) && ctx.memory(|m| m.focused().is_none()) { + if self.palette.is_none() && self.dialog.as_ref().is_none_or(|d| !d.modal()) && !widget_has_keyboard(ctx) { self.route_backstage_keys(events); } self.drain_requests(); return; } let modal = self.dialog.as_ref().is_some_and(|d| d.modal()) || self.palette.is_some(); - // While slide text is being edited, the text owns the keyboard (#93). Tab and the arrow - // keys move egui's keyboard focus onto ordinary widgets (the window's drag handle, ribbon - // buttons), and that stray focus would swallow every later key and end text entry. Let it - // go; a real text field or an open menu keeps its keys. - if !modal - && self.session.active().is_some_and(|d| d.selection.text.is_some()) - && !ctx.text_edit_focused() - && !ctx.any_popup_open() - && let Some(id) = ctx.memory(|m| m.focused()) - { - ctx.memory_mut(|m| m.surrender_focus(id)); - } - if ctx.memory(|m| m.focused().is_some()) || modal { + self.edited_text_takes_focus(ctx); + if widget_has_keyboard(ctx) || modal { // A stock field/modal/palette owns input now. Retire the custom fence, then visit // controls in raw order; stock text/key events are left for the stock widgets. self.suspend_ime_reset(viewport); @@ -180,12 +170,6 @@ impl SlideApp { } } egui::Event::Key { key, pressed: true, modifiers, .. } => { - if key == egui::Key::Tab { - // The slide has the keyboard, so Tab is ours (indent, tab character, next - // shape). Left to egui it would also focus the first ribbon widget, and - // every key after it would go there instead of the slide (#78). - ctx.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); - } if key == egui::Key::Escape && self.anim_preview.is_some() && !modifiers.command && !modifiers.ctrl && !modifiers.alt { self.anim_preview = None; continue; diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 526d046cd..9a2768d0f 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -112,9 +112,11 @@ fn wheel_navigation(app: &mut SlideApp, ui: &mut Ui, carry_id: egui::Id, doc_uid } fn empty_deck_prompt(app: &mut SlideApp, ui: &mut Ui, avail: Rect, t: &Tokens) { - let resp = ui.allocate_rect(avail, Sense::click()); + ui.advance_cursor_after_rect(avail); + let resp = app.document_widget(ui, avail, Sense::click()); ui.painter().text(avail.center(), Align2::CENTER_CENTER, "Click to add first slide", theme::font(22.0), t.text_dim); - if resp.clicked() { + // Enter on the focused document is the session's New Slide, not a click of the prompt. + if resp.clicked_by(egui::PointerButton::Primary) || ui.input(|i| i.has_accesskit_action_request(resp.id, egui::accesskit::Action::Click)) { let _ = app.run("slide.new", json!({"layout": "title"})); } } @@ -172,7 +174,8 @@ pub fn show(app: &mut SlideApp, ui: &mut Ui) { let last_id = scroll_id.with("last"); let mut offset: egui::Vec2 = ui.data_mut(|d| d.get_temp(scroll_id).unwrap_or_default()); let last: Option<(Rect, f32)> = ui.data_mut(|d| d.get_temp(last_id)); - let resp = ui.allocate_rect(avail, Sense::click_and_drag()); + ui.advance_cursor_after_rect(avail); + let resp = app.document_widget(ui, avail, Sense::click_and_drag()); let (wheel, zoom_delta, hover) = ui.input(|i| (i.smooth_scroll_delta, i.zoom_delta(), i.pointer.hover_pos())); let zooming = resp.hovered() && (zoom_delta - 1.0).abs() > 1e-3; if zooming { diff --git a/crates/ui-egui/src/canvas/ime.rs b/crates/ui-egui/src/canvas/ime.rs index 61f47bc14..12253a12e 100644 --- a/crates/ui-egui/src/canvas/ime.rs +++ b/crates/ui-egui/src/canvas/ime.rs @@ -34,7 +34,7 @@ pub fn ime_area(app: &SlideApp, xf: Xf) -> Option { /// has settled. pub(super) fn ime_output(app: &mut SlideApp, ui: &Ui, xf: Xf) { let ctx = ui.ctx(); - if ctx.memory(|m| m.focused().is_some()) || app.dialog.as_ref().is_some_and(|d| d.modal()) || app.palette.is_some() || app.backstage_open() { + if crate::framework::widget_has_keyboard(ctx) || app.dialog.as_ref().is_some_and(|d| d.modal()) || app.palette.is_some() || app.backstage_open() { return; } let Some(r) = ime_area(app, xf) else { return }; diff --git a/crates/ui-egui/src/document_focus_tests.rs b/crates/ui-egui/src/document_focus_tests.rs new file mode 100644 index 000000000..40afeaf17 --- /dev/null +++ b/crates/ui-egui/src/document_focus_tests.rs @@ -0,0 +1,133 @@ +//! The document window as the window's one canvas stop: Tab, real presses and its keys. + +use deckcraft_engine::Session; +use egui::{Event, Id, Key, Modifiers, PointerButton, Role, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; + +use crate::framework::document_id; +use crate::state::ViewMode; +use crate::{Services, SlideApp}; + +fn harness() -> Harness<'static, SlideApp> { + let mut session = Session::with_new(); + session.prefs.autocorrect = false; + let mut app = SlideApp::new(session, Services::default()); + app.ui.notes = false; + let mut h = Harness::builder().with_context_setup(crate::framework::install_headless).with_size(vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut SlideApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h +} + +fn focused(h: &Harness<'_, SlideApp>) -> Option { + h.ctx.memory(|m| m.focused()) +} + +fn press(h: &mut Harness<'_, SlideApp>, modifiers: Modifiers, key: Key) { + h.key_press_modifiers(modifiers, key); + h.run_steps(2); +} + +fn tab(h: &mut Harness<'_, SlideApp>) { + press(h, Modifiers::NONE, Key::Tab); +} + +fn selected(h: &Harness<'_, SlideApp>) -> Vec { + h.state().session.active().unwrap().selection.shapes.clone() +} + +#[test] +fn tab_selects_the_slides_objects_then_moves_on_and_shift_tab_walks_back() { + let mut h = harness(); + assert_eq!(focused(&h), Some(document_id()), "an opened presentation has the keyboard"); + let objects: Vec<_> = h.state().session.active().unwrap().shapes().iter().map(|s| s.id).collect(); + assert!(objects.len() > 1); + for object in &objects { + tab(&mut h); + assert_eq!((selected(&h), focused(&h)), (vec![*object], Some(document_id()))); + } + press(&mut h, Modifiers::SHIFT, Key::Tab); + let before = focused(&h); + assert!(before.is_some() && before != Some(document_id()), "with the last object selected, Shift+Tab leaves the slide"); + tab(&mut h); + assert_eq!(focused(&h), Some(document_id()), "Tab from the stop before it stops at the slide"); + tab(&mut h); + let after = focused(&h); + assert!(after.is_some() && after != Some(document_id()) && after != before, "past the last object, Tab moves on"); + press(&mut h, Modifiers::SHIFT, Key::Tab); + assert_eq!(focused(&h), Some(document_id()), "Shift+Tab walks back to the slide"); + assert_eq!(selected(&h), objects[objects.len() - 1..]); +} + +#[test] +fn a_press_on_the_slide_takes_the_keyboard_from_a_focused_button() { + let mut h = harness(); + h.get_by_role_and_label(Role::Button, "File").focus(); + h.run_steps(2); + assert!(h.get_by_role_and_label(Role::Button, "File").is_focused()); + let pos = h.state().canvas_rect.unwrap().right_bottom() - vec2(10.0, 10.0); + h.hover_at(pos); + h.run_steps(1); + for pressed in [true, false] { + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + assert_eq!(focused(&h), Some(document_id())); + press(&mut h, Modifiers::NONE, Key::Enter); + assert!(!h.state().backstage_open(), "the File button isn't activated"); + assert_eq!(h.state().session.active().unwrap().doc.slides.len(), 2, "Enter adds a slide"); +} + +#[test] +fn the_focused_slide_takes_arrows_escape_typing_and_tab() { + let mut h = harness(); + let left = |h: &Harness<'_, SlideApp>| { + let st = h.state().session.active().unwrap(); + deckcraft_engine::cmd::xfrm_of(&st.doc, &st.selection, &st.shapes()[0]).x + }; + tab(&mut h); + let x = left(&h); + press(&mut h, Modifiers::NONE, Key::ArrowRight); + assert!(left(&h) > x, "the arrow moves the object, not the focus"); + press(&mut h, Modifiers::NONE, Key::Escape); + assert!(selected(&h).is_empty()); + assert_eq!(focused(&h), Some(document_id()), "Escape leaves the focus on the slide"); + tab(&mut h); + h.event(Event::Text("ab".into())); + h.run_steps(2); + tab(&mut h); + h.event(Event::Text("c".into())); + h.run_steps(2); + let st = h.state().session.active().unwrap(); + assert_eq!(st.shapes()[0].text.as_ref().unwrap().text(), "ab\tc"); + assert!(st.selection.text.is_some()); + press(&mut h, Modifiers::NONE, Key::Escape); + assert!(h.state().session.active().unwrap().selection.text.is_none(), "Escape ends text editing"); + assert_eq!(focused(&h), Some(document_id())); +} + +#[test] +fn every_view_draws_the_document_and_the_file_tab_takes_its_focus() { + let mut h = harness(); + for view in [ViewMode::Outline, ViewMode::Reading, ViewMode::NotesPage, ViewMode::Sorter] { + h.state_mut().ui.view = view; + h.run_steps(3); + assert_eq!(focused(&h), Some(document_id()), "the focus stays in the document window"); + } + tab(&mut h); + assert!(focused(&h).is_some_and(|id| id != document_id()), "Tab has no work in the slide sorter"); + h.state_mut().ui.view = ViewMode::Normal; + h.state_mut().open_backstage(crate::backstage::Page::Home); + h.run_steps(3); + assert!(h.state().backstage_open()); + h.key_press(Key::Escape); + h.run_steps(3); + assert!(!h.state().backstage_open(), "Escape leaves the File tab"); + assert_eq!(focused(&h), Some(document_id()), "and the slide has the keyboard again"); +} diff --git a/crates/ui-egui/src/framework.rs b/crates/ui-egui/src/framework.rs index 228121475..812d76108 100644 --- a/crates/ui-egui/src/framework.rs +++ b/crates/ui-egui/src/framework.rs @@ -5,18 +5,18 @@ //! //! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of DeckCraft's own egui //! widgets has the keyboard. The window's Escape is read with [`escape_pressed`] or [`take_window_cancel`]; the -//! document window is declared to the runtime with [`host_canvas`] each pass, which keeps Tab, the edit chords and -//! the clipboard events in egui's input for DeckCraft's own key routing (`SlideApp::keyboard`). +//! document window is declared to the runtime with [`host_canvas`] each pass that draws it, which keeps the edit chords +//! and the clipboard events, and Tab while it has the focus and Tab has work, in egui's input for DeckCraft's own key +//! routing (`SlideApp::keyboard`). That routing has the keyboard unless [`widget_has_keyboard`]. -use std::sync::{Arc, OnceLock}; +use std::sync::Arc; use craft_host::target::ShellInfo; use craft_host::{AppInfo, Host}; -use craft_keymap::{Chord, Key, Mods, Overrides}; +use craft_keymap::{Chord, Key, Mods}; use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts}; -use craft_ui::runtime::commands::{CommandInput, CommandSet, NavCommand}; use craft_ui::runtime::env::{RootEnv, Scale}; -use craft_ui::runtime::focus::{EditSet, KeepKeys, KeyUse}; +use craft_ui::runtime::focus::{self, EditSet, FocusTarget, KeepKeys, KeyUse}; use craft_ui::runtime::frame::{FrameInput, FrameOutput}; use craft_ui::runtime::keys::{Intent, with_window_intents}; use craft_ui::shell::embed::{self, CloseDecision}; @@ -72,21 +72,6 @@ pub(crate) fn host() -> Arc { ) } -/// F6 and Shift+F6 move between framework panes by default. DeckCraft has none: the only stop is its document window -/// ([`host_canvas`]), and focusing it would turn its arrows and clipboard events into framework intents that -/// DeckCraft's key routing does not read. Overrides are keyed by command id, which the command set gives. -fn command_overrides() -> Arc { - static OVERRIDES: OnceLock> = OnceLock::new(); - OVERRIDES - .get_or_init(|| { - let mut overrides = Overrides::new(); - overrides.insert(NavCommand::NextPane.id(), Vec::new()); - overrides.insert(NavCommand::PreviousPane.id(), Vec::new()); - Arc::new(overrides) - }) - .clone() -} - impl SlideApp { /// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime /// gathered since the last frame and gives the coming passes the root values (theme mode, interface scale). @@ -101,7 +86,7 @@ impl SlideApp { let mode = if self.ui.brightness == crate::theme::Brightness::Dark { craft_theme::Mode::Dark } else { craft_theme::Mode::Light }; // The slide show and the canvas read Ctrl/Cmd+wheel themselves, so a smooth Ctrl+wheel stays a wheel event. let root = RootEnv::new().mode(mode).scale(Scale::new(self.ui.ui_scale.clamp(0.5, 3.0))).ctrl_wheel_pinch(false); - FrameInput::new(root).commands(CommandInput::new().overrides(command_overrides())).host(Arc::clone(&self.framework_host)) + FrameInput::new(root).host(Arc::clone(&self.framework_host)) } /// The framework's part of `App::logic`, after DeckCraft's own: the root window's close path. With unsaved @@ -135,16 +120,38 @@ const QUICK_ACCESS_KEYS: [Chord; 9] = [ Chord::new(Mods::ALT, Key::Num9), ]; -/// The keys DeckCraft's document window keeps while it is the window's key target: Tab (indent, next shape), -/// every clipboard event and edit chord, and the Quick Access Toolbar's Alt+digits, which `SlideApp::keyboard` -/// routes itself. -const DOCUMENT_KEYS: KeyUse = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL).with_claims(&QUICK_ACCESS_KEYS); +/// The keys DeckCraft's document window keeps while it has the focus or is the window's key target: every clipboard +/// event and edit chord, and the Quick Access Toolbar's Alt+digits, which `SlideApp::keyboard` routes itself. +const DOCUMENT_KEYS: KeyUse = KeyUse::CANVAS.with_edits(EditSet::ALL).with_claims(&QUICK_ACCESS_KEYS); + +/// The document window's widget: the slide canvas, the slide sorter or the notes page, whichever the view draws. +pub(crate) fn document_id() -> egui::Id { + egui::Id::unique("deckcraft_document") +} /// Declares DeckCraft's document window, drawn in this pass, as the window's canvas. With nothing focused it is the -/// window's key target, so Tab, the edit chords, the clipboard events and the claimed Alt+digits stay in egui's input -/// for DeckCraft. -pub(crate) fn host_canvas(ctx: &egui::Context) { - craft_ui::runtime::focus::host_canvas(ctx, egui::Id::unique("deckcraft_document"), DOCUMENT_KEYS); +/// window's key target: the edit chords, the clipboard events and the claimed Alt+digits stay in egui's input for +/// DeckCraft. Tab and Shift+Tab stop at it; with `keeps_tab` the focused document keeps them in egui's input, else they +/// move on from it. +pub(crate) fn host_canvas(ctx: &egui::Context, keeps_tab: bool) { + let keys = if keeps_tab { DOCUMENT_KEYS.with_keep(KeepKeys::Tab) } else { DOCUMENT_KEYS }; + focus::host_canvas(ctx, document_id(), keys); +} + +/// Gives the document window the keyboard focus. It is the runtime's focus, which an Escape does not take away. +pub(crate) fn focus_document(ctx: &egui::Context) { + focus::request(ctx, FocusTarget::Id(document_id())); +} + +/// The widget that has the keyboard, the document window left out: a focused document leaves the keyboard to +/// DeckCraft's own key routing, as with nothing focused. +pub(crate) fn focused_widget(ctx: &egui::Context) -> Option { + ctx.memory(|m| m.focused()).filter(|id| *id != document_id()) +} + +/// Whether a widget other than the document window 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 DeckCraft's own widgets or popups has the keyboard, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0211e2e94..f866144f4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -268,8 +268,11 @@ pub struct SlideApp { synthetic_generation: u64, /// Document/slide/canvas identity the queued/injected batch belongs to. synthetic_target: Option, - /// Focus identity the pending batch was injected with; a focus change retracts it. + /// Focus identity the pending batch was injected with (the document window counts as none); a focus change + /// retracts it. synthetic_focus: Option, + /// The document window as a Tab stop, and when it takes the keyboard focus. + document_focus: app::DocumentFocus, /// `RawInput::time` of the pass the batch was injected into. A logic-only callback leaves /// `InputState` from the previous pass; comparing this value keeps retraction from draining /// an unrelated batch out of that stale input. @@ -460,6 +463,8 @@ mod browsetheme_tests; #[cfg(test)] mod compare_tests; #[cfg(test)] +mod document_focus_tests; +#[cfg(test)] mod eyedropper_tests; #[cfg(test)] mod field_frame_tests; diff --git a/crates/ui-egui/src/panels/smartart.rs b/crates/ui-egui/src/panels/smartart.rs index a50f95070..6f098a57f 100644 --- a/crates/ui-egui/src/panels/smartart.rs +++ b/crates/ui-egui/src/panels/smartart.rs @@ -8,7 +8,7 @@ pub(super) fn smartart(app: &mut SlideApp, ui: &mut Ui) { return; }; let texts: Vec = d.nodes.iter().map(|n| n.text.clone()).collect(); - let focused_any = ui.ctx().memory(|m| m.focused().is_some()) || app.ui.smartart_focus.is_some(); + let focused_any = crate::framework::widget_has_keyboard(ui.ctx()) || app.ui.smartart_focus.is_some(); if app.ui.smartart_drafts.0 != gid.0 || app.ui.smartart_drafts.1.len() != texts.len() || !focused_any { app.ui.smartart_drafts = (gid.0, texts.clone()); } @@ -24,7 +24,8 @@ pub(super) fn smartart(app: &mut SlideApp, ui: &mut Ui) { ui.horizontal(|ui| { ui.add_space(16.0 * node.level as f32); ui.label("•"); - let te = egui::TextEdit::singleline(draft).id(id).hint_text("Diagram text").desired_width(f32::INFINITY); + // The line keeps Tab for its own command; Escape leaves it. + let te = egui::TextEdit::singleline(draft).id(id).hint_text("Diagram text").desired_width(f32::INFINITY).lock_focus(true); let r = ui.add(te); if app.ui.smartart_focus == Some(i) { r.request_focus(); @@ -39,13 +40,15 @@ pub(super) fn smartart(app: &mut SlideApp, ui: &mut Ui) { action = Some(("smartArt.removeNode", json!({"index": i}))); focus_row = Some(i.saturating_sub(1)); } - } - if r.lost_focus() { let (tab, shift) = ui.input(|inp| (inp.key_pressed(egui::Key::Tab), inp.modifiers.shift)); if tab { action = Some((if shift { "smartArt.promote" } else { "smartArt.demote" }, json!({"index": i}))); focus_row = Some(i); - } else if ui.input(|inp| inp.key_pressed(egui::Key::Enter)) { + commit = Some(i); + } + } + if r.lost_focus() { + if ui.input(|inp| inp.key_pressed(egui::Key::Enter)) { action = Some(("smartArt.addNode", json!({"index": i, "position": "after"}))); focus_row = Some(i + 1); } diff --git a/crates/ui-egui/src/sorter.rs b/crates/ui-egui/src/sorter.rs index 3cbd6f3f9..0ea7adb53 100644 --- a/crates/ui-egui/src/sorter.rs +++ b/crates/ui-egui/src/sorter.rs @@ -278,6 +278,8 @@ pub fn show(app: &mut SlideApp, ui: &mut Ui) { let multi = st.selection.slides.clone(); let zoom = app.ui.sorter_zoom.clamp(0.5, 3.0); let grouped = groups(&doc); + // Behind the thumbnails, which take the presses: the document's Tab stop and key target. + app.document_widget(ui, ui.available_rect_before_wrap(), Sense::focusable_noninteractive()); egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { ui.add_space(12.0); ui.horizontal(|ui| { @@ -363,6 +365,9 @@ pub fn notes_page(app: &mut SlideApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let avail = ui.available_rect_before_wrap(); ui.painter().rect_filled(avail, CornerRadius::ZERO, t.canvas); + if app.session.active().is_some() { + app.document_widget(ui, avail, Sense::click()); + } let Some(st) = app.session.active() else { return }; let doc = st.doc.clone(); let idx = st.selection.slide;