diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index f21e99a852..dbd38b7646 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -130,7 +130,8 @@ impl egui::DroppedFile for DroppedPath { } /// The viewport facts a frame reports: a window-focus event also sets the root viewport's focus fact, as a host -/// reports both, and the fact stays until the next such event. Before any event the focus is unknown. +/// reports both, and the fact stays until the next such event. Before any event the focus is unknown. The root's input +/// reports the same focus (`RawInput::focused`), a window with focus while it is unknown. fn window_focus_facts(ctx: &Context, events: &[Event], native_pixels_per_point: Option) -> egui::ViewportIdMap { let last = events.iter().rev().find_map(|event| if let Event::WindowFocused(focused) = event { Some(*focused) } else { None }); let focused = Service::::run(ctx, |state| { @@ -251,6 +252,7 @@ pub(crate) fn run_frame( let dropped_files = files.dropped.iter().map(|name| Arc::new(DroppedPath(name.into())) as egui::DroppedFileHandle).collect(); Service::::run(ctx, |resets| resets.input(viewport, &mut events)); let mut viewports = window_focus_facts(ctx, &events, native_pixels_per_point); + let focused = viewport != egui::ViewportId::ROOT || viewports.get(&egui::ViewportId::ROOT).and_then(|info| info.focused).unwrap_or(true); let children = open_children(ctx, viewport); for child in &children { viewports @@ -260,6 +262,7 @@ pub(crate) fn run_frame( screen_rect: Some(screen), time: Some(time), viewport_id: viewport, + focused, events, hovered_files, dropped_files, diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 300e08ea4c..bd082ac7a5 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -236,7 +236,10 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) let content = placed.union(output.response.rect).union(text_rect); super::widgets::note_scroll_region(ui.ctx(), rect.intersect(ui.clip_rect()), content); } - let focused = output.response.has_focus(); + // The widget's key focus, whether or not the window has the system's: switching to another app is no focus move, + // so the typing run, caret and selection carry on (egui's `Response::has_focus` is false while the window is in + // the background). + let focused = ui.memory(|memory| memory.has_focus(id)); let caret = output.cursor_range.map(|range| { let at = output.galley.pos_from_cursor(range.primary); at.translate(output.galley_pos.to_vec2()) diff --git a/crates/ui-widgets/tests/it/text/edit_run.rs b/crates/ui-widgets/tests/it/text/edit_run.rs new file mode 100644 index 0000000000..e56000c38d --- /dev/null +++ b/crates/ui-widgets/tests/it/text/edit_run.rs @@ -0,0 +1,118 @@ +//! A text field's typing run across focus changes: switching to another app carries the run on. + +use craft_behavior::{CancelReason, EditEvent}; +use craft_ui::contract::{Bind, Show as _}; +use craft_ui::testing::{Fixture, pointer, trial}; +use craft_ui::text::TextField; +use egui::{Event, Id, Key, Modifiers, Pos2}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +/// How a pass of the field ended a typing run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Ended { + Commit, + Cancel(CancelReason), +} + +/// A text field named "City" bound to `text`, alone in a window. +struct Rig { + fixture: Fixture, + text: Rc>, + field: Rc>, + ended: Rc>>, +} + +fn rig(text: &str, select_on_focus: bool) -> Rig { + let text = Rc::new(RefCell::new(text.to_owned())); + let field = Rc::new(Cell::new(Id::NULL)); + let ended = Rc::new(RefCell::new(Vec::new())); + let (held, id, log) = (text.clone(), field.clone(), ended.clone()); + let mut fixture = Fixture::new(move |ui| { + let mut text = held.borrow_mut(); + let mut field = TextField::new("City", Bind::bound(&mut *text)); + if select_on_focus { + field = field.select_on_focus(); + } + let out = field.show(ui); + id.set(out.response.id); + log.borrow_mut().extend(out.events.iter().filter_map(|event| match event { + EditEvent::Commit { .. } => Some(Ended::Commit), + EditEvent::Cancel { reason, .. } => Some(Ended::Cancel(*reason)), + _ => None, + })); + }); + fixture.settle(); + Rig { fixture, text, field, ended } +} + +impl Rig { + fn text(&self) -> String { + self.text.borrow().clone() + } + + fn ended(&self) -> Vec { + self.ended.borrow().clone() + } + + fn focused(&self) -> bool { + self.fixture.focused_stop().map(|(id, _)| id) == Some(self.field.get()) + } + + fn at(&self) -> Pos2 { + self.fixture.by_label("City").expect("the field").center() + } + + /// A click in the middle of the field, well after any other: two clicks never make a double click. + fn click(&mut self) { + self.fixture.advance(1.0); + let at = self.at(); + self.fixture.click_at(at); + self.fixture.settle(); + } + + fn select_all(&mut self) { + self.fixture.key(Key::A, Modifiers::COMMAND); + self.fixture.settle(); + } + + fn type_text(&mut self, text: &str) { + self.fixture.type_text(text); + self.fixture.settle(); + } + + fn escape(&mut self) { + self.fixture.key(Key::Escape, Modifiers::NONE); + self.fixture.settle(); + } + + /// Clicks into the field and retypes its whole text as `text`. + fn retype(&mut self, text: &str) { + self.click(); + self.select_all(); + self.type_text(text); + } +} + +/// Switching to another app and back is no focus move: the field keeps the focus and its run, the selection it had +/// carries on, and nothing commits or cancels; Escape afterwards still gives back the text from before the run. +#[trial] +fn switching_apps_carries_on_with_the_typing_run() { + let mut rig = rig("Lisbon", false); + rig.retype("Rome"); + rig.select_all(); + rig.fixture.frame(vec![pointer::window_blurred()]); + rig.fixture.idle(4); + assert!(rig.focused(), "the field keeps the focus while the window is in the background"); + assert_eq!(rig.ended(), [], "the window losing focus ends nothing"); + rig.fixture.frame(vec![Event::WindowFocused(true)]); + rig.fixture.settle(); + assert!(rig.focused(), "the field has the focus when the window is back"); + assert_eq!(rig.ended(), [], "the window coming back ends nothing"); + rig.type_text("Porto"); + assert_eq!(rig.text(), "Porto", "the selection carried on: typing replaced it"); + rig.escape(); + assert_eq!(rig.text(), "Lisbon", "Escape gives back the text from before the run"); + assert_eq!(rig.ended(), [Ended::Cancel(CancelReason::Escape)]); +} + diff --git a/crates/ui-widgets/tests/it/text/mod.rs b/crates/ui-widgets/tests/it/text/mod.rs index 42f14bd0e2..b8ed3ebfbb 100644 --- a/crates/ui-widgets/tests/it/text/mod.rs +++ b/crates/ui-widgets/tests/it/text/mod.rs @@ -2,6 +2,7 @@ pub(crate) mod access; pub(crate) mod alt_text; pub(crate) mod chips; pub(crate) mod edit_menu; +pub(crate) mod edit_run; pub(crate) mod fields; pub(crate) mod hex; mod kit;