Select the current query when refocusing search fields (#4533)

* Search field receives a focus request

* Find keeps an IME composition when the find field already has the keyboard

Selecting the query on Find made the next IME update replace the whole
query when the field was composing: egui replaces the selected range,
and only egui can end a composition from inside the field. The query is
now selected only when the field takes the keyboard from elsewhere, in
one helper for the find bar and the Search panel.

* Test that the Search panel keeps an IME composition when asked for the keyboard again

* A repeated Find selects the query while the field has the keyboard

`owns_ime_events` is only `has_focus` on the pinned egui, so a second Find
while the find field (or the Search panel field) still had the keyboard
kept the caret and typing appended to the old query. Follow the IME
composition from the field's own events and cursor instead: a non-empty
pre-edit starts it, a commit or empty pre-edit ends it, and any other edit,
click or loss of focus ends it too. Only a live composition keeps the
selection; every other Find selects all of the query.

Tests: a repeated Find with the keyboard still in the field, for both
fields, and a Find after a committed composition.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
This commit is contained in:
Francesco UrbaniandFredApps authored and GitHub committed 2026-11-16 10:00:37 +01:00
1 parent 799fdd14b9
commit 90d847ce17
5 files changed
+162 -8

No files matched your search

+1 -4
View File
@@ -300,10 +300,7 @@ pub(super) fn find_bar(view: &mut DocView, pages: usize, area: Rect, editing: bo
.desired_width(220.0)
.frame(egui::Frame::NONE);
let r = ui.add(edit).accessible_name(tl!("Find text"));
if find.focus {
r.request_focus();
find.focus = false;
}
widgets::focus_selecting_all(ui, &r, &find.query, &mut find.focus);
if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
step = Some(!ui.input(|i| i.modifiers.shift));
r.request_focus();
+1 -4
View File
@@ -22,10 +22,7 @@ pub(crate) fn panel(ui: &mut egui::Ui, t: &Tokens, view: &mut DocView, pages: us
.add(crate::widgets::line(&mut find.query).id(egui::Id::unique("search-panel-input")).hint_text(tl!("Search")).desired_width(f32::INFINITY))
.accessible_name(tl!("Search"))
.labelled_by(l.id);
if find.focus {
r.request_focus();
find.focus = false;
}
widgets::focus_selecting_all(ui, &r, &find.query, &mut find.focus);
ui.horizontal(|ui| {
// Outlined boxes (the panel and the check-box fill are alike), as in dialogs.
let w = &mut ui.visuals_mut().widgets;
+59
View File
@@ -85,6 +85,65 @@ pub fn line(text: &mut dyn egui::TextBuffer) -> egui::TextEdit<'_> {
egui::TextEdit::singleline(text).margin(FIELD_MARGIN).min_size(vec2(0.0, FIELD_MIN_HEIGHT))
}
/// Give the field `r` the keyboard with all of `text` selected when `request` is set, so typing
/// replaces it, and clear `request`. Call it on every pass, right after adding the field.
///
/// A field in the middle of an IME composition keeps its selection: the composition's next
/// update replaces the selected range, and egui ends a composition only from inside the field.
/// egui keeps that state private (`Memory::owns_ime_events` is only `has_focus`), so
/// `ime_composing` follows it from the field's events. Any other request, including a repeated
/// one while the field already has the keyboard, selects all of `text`.
pub fn focus_selecting_all(ui: &egui::Ui, r: &egui::Response, text: &str, request: &mut bool) {
let composing = ime_composing(ui, r);
if !std::mem::take(request) {
return;
}
r.request_focus();
if composing {
return;
}
let mut state = egui::TextEdit::load_state(ui.ctx(), r.id).unwrap_or_default();
state.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(text)));
state.store(ui.ctx(), r.id);
}
/// Whether the field `r` holds an IME composition after this pass's events.
///
/// A non-empty pre-edit starts one, and a commit or an empty pre-edit ends it. Anything else that
/// ends it inside the `TextEdit` (typing, a mutating key, a paste, a click) also moves its cursor
/// off the range the last IME event left, and losing the keyboard ends it too.
fn ime_composing(ui: &egui::Ui, r: &egui::Response) -> bool {
type Composition = Option<egui::text::CCursorRange>;
let key = r.id.with("ime_composition");
let cursor = egui::TextEdit::load_state(ui.ctx(), r.id).and_then(|s| s.cursor.char_range());
let mut composition: Composition = if r.has_focus() { ui.data(|d| d.get_temp::<Composition>(key)).flatten() } else { None };
let mut saw_ime = false;
if r.has_focus() {
ui.input(|i| {
for event in &i.events {
if let egui::Event::Ime(ime) = event {
saw_ime = true;
match ime {
egui::ImeEvent::Preedit { text, .. } if text.is_empty() => composition = None,
egui::ImeEvent::Preedit { text, .. } if text != "\n" && text != "\r" => composition = cursor,
egui::ImeEvent::Commit(_) => composition = None,
_ => {}
}
}
}
});
}
if let Some(range) = composition {
if saw_ime {
composition = cursor.or(Some(range));
} else if cursor != Some(range) {
composition = None;
}
}
ui.data_mut(|d| d.insert_temp(key, composition));
composition.is_some()
}
/// A multiline field with the same horizontal inset as [`line()`].
pub fn block(text: &mut dyn egui::TextBuffer) -> egui::TextEdit<'_> {
egui::TextEdit::multiline(text).margin(egui::Margin::symmetric(10, 6))
+100
View File
@@ -0,0 +1,100 @@
//! Find (⌘F) gives the find field the keyboard with the query selected, so typing replaces it,
//! also when the field already has the keyboard, and asking again while the field is composing
//! with an IME leaves the composition alone (the find bar and the Search panel).
use egui_kittest::Harness;
use pdfcraft_ui_egui::PdfCraftApp;
fn harness() -> Harness<'static, PdfCraftApp> {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
let mut app = PdfCraftApp::new();
app.run_inline = true;
app.set_option("language", "en").unwrap();
app.open_bytes("form.pdf", None, include_bytes!("../data/form.pdf").to_vec()).unwrap();
app.set_option("left", "closed").unwrap();
app
});
h.run_steps(4);
h
}
fn query(h: &Harness<'static, PdfCraftApp>) -> String {
h.state().views[0].find.as_ref().unwrap().query.clone()
}
#[test]
fn find_selects_the_query_when_the_field_takes_the_keyboard() {
let mut h = harness();
h.state_mut().views[0].open_find();
h.run_steps(2);
h.event(egui::Event::Text("cat".into()));
h.run_steps(2);
let id = h.state().views[0].find_input_id();
h.ctx.memory_mut(|m| m.surrender_focus(id));
h.run_steps(2);
h.state_mut().views[0].open_find();
h.run_steps(2);
assert!(h.ctx.memory(|m| m.has_focus(id)));
h.event(egui::Event::Text("dog".into()));
h.run_steps(2);
assert_eq!(query(&h), "dog", "typing replaces the selected query");
}
type Open = dyn Fn(&mut Harness<'static, PdfCraftApp>);
/// The find bar (⌘F) and the Search panel (Advanced Search) share the focus request.
fn fields() -> [(&'static str, Box<Open>); 2] {
[
("find bar", Box::new(|h| h.state_mut().views[0].open_find())),
("Search panel", Box::new(|h| assert!(h.state_mut().execute("edit.advanced_search")))),
]
}
/// A second Find while the field still has the keyboard (no IME composition) selects the query
/// again, so typing replaces it instead of appending.
#[test]
fn find_again_while_the_field_has_the_keyboard_selects_the_query() {
for (field, open) in fields() {
let mut h = harness();
open(&mut h);
h.run_steps(2);
h.event(egui::Event::Text("cat".into()));
h.run_steps(2);
assert_eq!(query(&h), "cat", "{field}");
open(&mut h);
h.run_steps(2);
h.event(egui::Event::Text("dog".into()));
h.run_steps(2);
assert_eq!(query(&h), "dog", "{field}: typing replaces the selected query");
}
}
#[test]
fn find_again_while_composing_keeps_the_query() {
for (field, open) in fields() {
let mut h = harness();
open(&mut h);
h.run_steps(2);
h.event(egui::Event::Text("cat".into()));
h.run_steps(2);
h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "ka".into(), active_range_chars: Some(0..2) }));
h.run_steps(2);
assert_eq!(query(&h), "catka", "{field}");
// Selecting the query here would make the commit replace all of it.
open(&mut h);
h.run_steps(2);
h.event(egui::Event::Ime(egui::ImeEvent::Commit("か".into())));
h.run_steps(2);
assert_eq!(query(&h), "catか", "{field}");
// The commit ended the composition, so the next Find selects the query again.
open(&mut h);
h.run_steps(2);
h.event(egui::Event::Text("dog".into()));
h.run_steps(2);
assert_eq!(query(&h), "dog", "{field}: typing after the composition replaces the query");
}
}
+1
View File
@@ -45,6 +45,7 @@ mod editor_taps;
mod export;
mod field_triggers;
mod fill_sign;
mod find_focus;
mod find_replace;
mod folders;
mod fonts;