Merge pull request #452 from ludovic111/fix/classic-text-fields

World screens' text fields: move the cursor, select, click and drag
This commit is contained in:
Ludovic Marie
2026-10-16 07:36:56 +02:00
committed by GitHub
6 changed files with 366 additions and 107 deletions
+21 -1
View File
@@ -9124,6 +9124,7 @@ impl ApplicationHandler for Game<'_> {
&& !horizon_client::ui_theme::horizon()
{
title.drag(self.cursor, (b.width, b.height));
title.drag_field(&self.res.atlas, self.cursor.0);
}
if self.dragging && self.screen == Screen::Options {
let _ = b;
@@ -9213,6 +9214,7 @@ impl ApplicationHandler for Game<'_> {
} if self.title.is_some() && self.screen != Screen::Options => {
if let Some(title) = &mut self.title {
title.release();
title.release_field();
}
}
WindowEvent::MouseInput {
@@ -9227,6 +9229,7 @@ impl ApplicationHandler for Game<'_> {
.unwrap_or([1, 1]);
let mut b = HudBatch::new(size);
let atlas = &self.res.atlas;
let shift = self.has_shift_down();
let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| {
if horizon_client::ui_theme::horizon() {
(
@@ -9234,7 +9237,10 @@ impl ApplicationHandler for Game<'_> {
false,
)
} else {
t.click(self.cursor.0, self.cursor.1, (b.width, b.height))
let clicked =
t.click(self.cursor.0, self.cursor.1, (b.width, b.height));
t.press_field(atlas, self.cursor, (b.width, b.height), shift);
clicked
}
});
if sound {
@@ -9445,6 +9451,20 @@ impl ApplicationHandler for Game<'_> {
t.confirm_edit();
}
}
PhysicalKey::Code(
key @ (KeyCode::Backspace
| KeyCode::Delete
| KeyCode::ArrowLeft
| KeyCode::ArrowRight
| KeyCode::Home
| KeyCode::End),
) if self.title.as_mut().is_some_and(|t| t.has_caret_field()) => {
let (ctrl, shift) =
(self.has_control_down(), self.has_shift_down());
if let Some(t) = self.title.as_mut() {
t.field_key(key, ctrl, shift);
}
}
PhysicalKey::Code(KeyCode::Backspace) => self.title_edit(None, true),
PhysicalKey::Code(KeyCode::Tab) => {
if let Some(t) = self.title.as_mut() {
+9 -5
View File
@@ -46,6 +46,9 @@ impl Game<'_> {
let Some(title) = self.title.as_mut() else {
return;
};
if title.has_caret_field() {
return title.field_shortcut(shortcut, &mut self.clipboard);
}
if let Some((id, value, max)) = title.focused_field() {
let changed = Self::append_shortcut(
&mut self.text_selection,
@@ -60,15 +63,16 @@ impl Game<'_> {
}
}
}
/// Typing or a backspace in an append-only field of the title screens:
/// Select All's selection is replaced first.
/// Typing or a backspace in a field of the title screens: in the server
/// screens' append-only fields Select All's selection is replaced first.
pub(super) fn title_edit(&mut self, typed: Option<&str>, backspace: bool) {
let Some(title) = self.title.as_mut() else {
return;
};
let cleared = title
.focused_field()
.is_some_and(|(id, value, _)| self.text_selection.take(id, value));
let cleared = !title.has_caret_field()
&& title
.focused_field()
.is_some_and(|(id, value, _)| self.text_selection.take(id, value));
if cleared {
title.search_changed();
}
+124 -83
View File
@@ -129,6 +129,8 @@ pub struct Title {
pub started: std::time::Instant,
search: String,
search_focused: bool,
/// The focused text field's cursor, selection and scroll.
caret: RefCell<crate::ui::Caret>,
scroll: Cell<crate::ui::Scroll>,
create_return_to_main: bool,
message_lines: Cell<usize>,
@@ -233,6 +235,7 @@ impl Title {
started: now,
search: String::new(),
search_focused: false,
caret: RefCell::default(),
scroll: Cell::default(),
create_return_to_main: false,
message_lines: Cell::new(1),
@@ -808,14 +811,13 @@ impl Title {
Mode::Select { worlds, selected } => {
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
centered(atlas, batch, "Select World", 8.0, u32::MAX);
text_field(
atlas,
self.caret.borrow_mut().draw(
batch,
((w / 2.0).floor() - 100.0, 21.0),
&self.search,
atlas,
(SEARCH, &self.search, 50),
[(w / 2.0).floor() - 100.0, 21.0, 200.0, 20.0],
self.search_focused,
!self.search.is_empty()
&& (self.started.elapsed().as_millis() / 300).is_multiple_of(2),
self.started,
);
if self.search.is_empty() {
batch.text(
@@ -973,13 +975,13 @@ impl Title {
rgba(160, 160, 160, 255),
true,
);
text_field(
atlas,
self.caret.borrow_mut().draw(
batch,
((w / 2.0).floor() - 100.0, top + 39.0),
name,
atlas,
(EDIT_NAME, name, 32),
[(w / 2.0).floor() - 100.0, top + 39.0, 200.0, 20.0],
*focused,
(self.started.elapsed().as_millis() / 300).is_multiple_of(2),
self.started,
);
}
Mode::Delete { world } => {
@@ -1348,40 +1350,99 @@ impl Title {
pub fn focused_field(&mut self) -> Option<(crate::clipboard::FieldId, &mut String, usize)> {
match &mut self.mode {
Mode::Multiplayer(screen) => screen.focused_text(),
Mode::Select { .. } if self.search_focused => {
Some((("world.search", 0), &mut self.search, 50))
}
Mode::Edit {
name,
focused: true,
..
} => Some((("world.edit-name", 0), name, 32)),
Mode::Create {
name, seed, focus, ..
} => match focus {
0 => Some((("world.name", 0), name, 32)),
1 => Some((("world.seed", 0), seed, 32)),
_ => None,
},
mode => caret_field(mode, self.search_focused, &mut self.search),
}
}
/// Whether the focused field edits at its cursor (every field but the
/// server screens', which still append).
pub fn has_caret_field(&mut self) -> bool {
caret_field(&mut self.mode, self.search_focused, &mut self.search).is_some()
}
/// Edit the focused field through its `EditBox`; false when there is none.
fn edit_field(&mut self, f: impl FnOnce(&mut crate::ui::EditBox)) -> bool {
let Some((id, value, max)) =
caret_field(&mut self.mode, self.search_focused, &mut self.search)
else {
return false;
};
let before = value.clone();
self.caret.get_mut().edit(id, value, max, f);
if *value != before {
self.search_changed();
}
true
}
/// EditBox.charTyped / insertText at the cursor.
pub fn type_text(&mut self, text: &str) {
if let Mode::Multiplayer(screen) = &mut self.mode {
return screen.type_text(text);
}
self.edit_field(|edit| edit.insert_text(text));
}
pub fn backspace(&mut self) {
if let Mode::Multiplayer(screen) = &mut self.mode {
return screen.backspace();
}
self.field_key(winit::keyboard::KeyCode::Backspace, false, false);
}
/// EditBox.keyPressed: moving and deleting in the focused field.
pub fn field_key(&mut self, key: winit::keyboard::KeyCode, ctrl: bool, shift: bool) -> bool {
let mut handled = false;
self.edit_field(|edit| handled = edit.key(key, ctrl, shift));
handled
}
/// Ctrl+A/C/V/X in the focused field.
pub fn field_shortcut(
&mut self,
shortcut: crate::clipboard::EditShortcut,
board: &mut dyn crate::clipboard::Clipboard,
) {
self.edit_field(|edit| {
edit.shortcut(shortcut, board);
});
}
/// The focused field's box on screen.
fn focused_rect(&self, (w, h): (f32, f32)) -> Option<[f32; 4]> {
let x = (w / 2.0).floor() - 100.0;
match &self.mode {
Mode::Select { .. } if self.search_focused => Some([x, 21.0, 200.0, 20.0]),
Mode::Edit { focused: true, .. } => Some([x, edit_top(h) + 39.0, 200.0, 20.0]),
Mode::Create { focus, options, .. } => create_world::field_rect(w, h, options.tab)
.filter(|(id, _)| id == focus)
.map(|(_, rect)| rect),
_ => None,
}
}
pub fn type_text(&mut self, text: &str) {
if let Some((_, field, max)) = self.focused_field() {
for c in text.chars().filter(|c| !c.is_control()) {
if field.chars().count() < max {
field.push(c);
}
}
self.search_changed();
/// A left press after `click` focused a field: the cursor goes under the
/// pointer (`EditBox.onClick`).
pub fn press_field(
&mut self,
atlas: &HudAtlas,
(x, y): (f32, f32),
size: (f32, f32),
shift: bool,
) {
let (w, h) = (size.0.ceil(), size.1.ceil());
let Some(rect @ [fx, fy, fw, fh]) = self.focused_rect((w, h)) else {
return;
};
if !crate::ui::hovered((x, y), fx, fy, fw, fh) {
return;
}
if let Some(field) = caret_field(&mut self.mode, self.search_focused, &mut self.search) {
self.caret.get_mut().press(atlas, field, rect, x, shift);
}
}
pub fn backspace(&mut self) {
if let Some((_, field, _)) = self.focused_field() {
field.pop();
self.search_changed();
/// The pointer moved with the button held (`EditBox.onDrag`).
pub fn drag_field(&mut self, atlas: &HudAtlas, x: f32) {
if let Some(field) = caret_field(&mut self.mode, self.search_focused, &mut self.search) {
self.caret.get_mut().drag(atlas, field, x);
}
}
/// The button was released: drags stop selecting.
pub fn release_field(&mut self) {
self.caret.get_mut().release();
}
/// Clipboard replacements also invalidate a selection in the filtered list.
pub fn search_changed(&mut self) {
if self.search_focused
@@ -1503,52 +1564,32 @@ fn wrapped(atlas: &HudAtlas, text: &str, width: f32) -> Vec<String> {
.map(|t| t.plain())
.collect()
}
fn text_field(
atlas: &HudAtlas,
batch: &mut HudBatch,
pos: (f32, f32),
value: &str,
focused: bool,
blink: bool,
) {
let (x, y) = pos;
crate::widgets::target_as([x, y, 200.0, 20.0], crate::widgets::Kind::Field);
batch.fill(
atlas,
x,
y,
200.0,
20.0,
if focused {
u32::MAX
} else {
rgba(160, 160, 160, 255)
const SEARCH: crate::clipboard::FieldId = ("world.search", 0);
const EDIT_NAME: crate::clipboard::FieldId = ("world.edit-name", 0);
const WORLD_NAME: crate::clipboard::FieldId = ("world.name", 0);
const WORLD_SEED: crate::clipboard::FieldId = ("world.seed", 0);
/// The focused field of the world screens: the list's search, the world
/// name being edited, or Create New World's name or seed.
fn caret_field<'a>(
mode: &'a mut Mode,
search_focused: bool,
search: &'a mut String,
) -> Option<(crate::clipboard::FieldId, &'a mut String, usize)> {
match mode {
Mode::Select { .. } if search_focused => Some((SEARCH, search, 50)),
Mode::Edit {
name,
focused: true,
..
} => Some((EDIT_NAME, name, 32)),
Mode::Create {
name, seed, focus, ..
} => match focus {
0 => Some((WORLD_NAME, name, 32)),
1 => Some((WORLD_SEED, seed, 32)),
_ => None,
},
);
batch.fill(atlas, x + 1.0, y + 1.0, 198.0, 18.0, rgba(0, 0, 0, 255));
let count = atlas.font.fit_reverse(value, 188.0);
let start = value
.char_indices()
.nth(value.chars().count().saturating_sub(count))
.map_or(value.len(), |(i, _)| i);
let value = &value[start..];
batch.text(
atlas,
value,
x + 4.0,
y + 6.0,
rgba(224, 224, 224, 255),
true,
);
if focused && blink {
batch.text(
atlas,
"_",
x + 4.0 + HudBatch::text_width(atlas, value),
y + 6.0,
rgba(224, 224, 224, 255),
true,
);
_ => None,
}
}
/// `yyyy/MM/dd HH:mm` (UTC) for a modification time in Unix seconds.
+18 -16
View File
@@ -145,15 +145,20 @@ fn grid(w: f32, h: f32, tab: usize) -> (f32, f32) {
TAB_BAR + ((area - gh) * 0.166_666_67).trunc(),
)
}
/// The text box under the pointer: 0 the name, 1 the seed.
pub(super) fn field_at(w: f32, h: f32, tab: usize, (x, y): (f32, f32)) -> Option<u8> {
/// The text box of `tab`: 0 the name (Game tab), 1 the seed (World tab).
pub(super) fn field_rect(w: f32, h: f32, tab: usize) -> Option<(u8, [f32; 4])> {
let (gx, gy) = grid(w, h, tab);
match tab {
0 => ui::hovered((x, y), gx + 1.0, gy + 13.0, 208.0, 20.0).then_some(0),
1 => ui::hovered((x, y), gx, gy + 41.0, 308.0, 20.0).then_some(1),
0 => Some((0, [gx + 1.0, gy + 13.0, 208.0, 20.0])),
1 => Some((1, [gx, gy + 41.0, 308.0, 20.0])),
_ => None,
}
}
/// The text box under the pointer: 0 the name, 1 the seed.
pub(super) fn field_at(w: f32, h: f32, tab: usize, (x, y): (f32, f32)) -> Option<u8> {
let (id, [fx, fy, fw, fh]) = field_rect(w, h, tab)?;
ui::hovered((x, y), fx, fy, fw, fh).then_some(id)
}
fn tr(key: &str) -> String {
Text::translate(key, &[]).plain()
@@ -390,7 +395,7 @@ impl Title {
self.create_field(
atlas,
batch,
name,
(super::WORLD_NAME, name, 32),
[gx + 1.0, gy + 13.0, 208.0],
focus == 0,
None,
@@ -401,7 +406,7 @@ impl Title {
self.create_field(
atlas,
batch,
seed,
(super::WORLD_SEED, seed, 32),
[gx, gy + 41.0, 308.0],
focus == 1,
Some("selectWorld.seedInfo"),
@@ -425,24 +430,21 @@ impl Title {
u32::MAX,
);
}
/// An EditBox with its cursor at the end; `hint` shows while it is empty
/// and unfocused.
/// An EditBox; `hint` shows while it is empty and unfocused.
fn create_field(
&self,
atlas: &HudAtlas,
batch: &mut HudBatch,
value: &str,
(id, value, max): (crate::clipboard::FieldId, &str, usize),
[x, y, width]: [f32; 3],
focused: bool,
hint: Option<&str>,
) {
let mut field = ui::EditBox::new(x, y, width, 20.0);
field.value = value.to_owned();
field.cursor = ui::char_len(value);
field.highlight = field.cursor;
field.focused = focused;
field.focused_since(self.started);
field.draw(batch, atlas, None);
let rect = [x, y, width, 20.0];
self.caret
.borrow_mut()
.draw(batch, atlas, (id, value, max), rect, focused, self.started);
let field = ui::EditBox::new(x, y, width, 20.0);
if let Some(hint) = hint
&& value.is_empty()
&& !focused
+25
View File
@@ -704,3 +704,28 @@ fn new_world_generation_settings_round_trip() {
Some("minecraft:flat")
);
}
#[test]
fn world_fields_edit_at_their_cursor() {
use winit::keyboard::KeyCode;
let mut f = Fixture::new();
f.world("World", "World");
f.title.enter_singleplayer();
// The search box takes the focus.
f.title.click(240.0, 30.0, (480.0, 262.0));
f.title.type_text("hello world");
for _ in 0..5 {
assert!(f.title.field_key(KeyCode::ArrowLeft, false, false));
}
f.title.type_text("X");
assert_eq!(f.title.search, "hello Xworld");
// Shift+Home selects back to the start; typing replaces the selection.
f.title.field_key(KeyCode::Home, false, true);
f.title.type_text("Y");
assert_eq!(f.title.search, "Yworld");
// Ctrl+Left jumps a word; Backspace deletes before the cursor.
f.title.field_key(KeyCode::ArrowLeft, true, false);
f.title.field_key(KeyCode::ArrowRight, false, false);
f.title.field_key(KeyCode::Backspace, false, false);
assert_eq!(f.title.search, "world");
}
+169 -2
View File
@@ -598,6 +598,122 @@ pub struct EditBox {
pub suggestion: Option<String>,
pub text_color: u32,
}
/// The focused text field of a screen that keeps its values as `String`s
/// (the world list's search, world names, seeds): the `EditBox` state that
/// outlives a frame, its cursor, selection and scroll.
#[derive(Clone, Debug)]
pub struct Caret {
field: Option<crate::clipboard::FieldId>,
edit: EditBox,
/// The last click's time and field, for double clicks.
last_click: Option<(Instant, crate::clipboard::FieldId)>,
/// The button is held since a press on the field (`onDrag`).
held: bool,
}
impl Default for Caret {
fn default() -> Self {
Self {
field: None,
edit: EditBox::new(0.0, 0.0, 200.0, 20.0),
last_click: None,
held: false,
}
}
}
impl Caret {
/// The box for field `id` holding `value`. A field newly focused, or
/// whose value changed elsewhere, starts with its cursor at the end.
fn sync(&mut self, id: crate::clipboard::FieldId, value: &str, max: usize) -> &mut EditBox {
self.edit.max_length = max;
if self.field != Some(id) || self.edit.value != value {
self.edit.value = value.to_owned();
self.edit.move_cursor_to_end(false);
if self.field != Some(id) {
self.edit.display = 0;
self.field = Some(id);
}
}
&mut self.edit
}
/// Edit field `id`'s `value` through its box; the value is written back.
pub fn edit<R>(
&mut self,
id: crate::clipboard::FieldId,
value: &mut String,
max: usize,
f: impl FnOnce(&mut EditBox) -> R,
) -> R {
let edit = self.sync(id, value, max);
let result = f(edit);
value.clone_from(&edit.value);
result
}
/// A press on field `id` at GUI `x` (`EditBox.onClick`): a second press
/// within 250 ms is a double click (`MouseHandler`).
pub fn press(
&mut self,
atlas: &HudAtlas,
(id, value, max): (crate::clipboard::FieldId, &mut String, usize),
rect: [f32; 4],
x: f32,
shift: bool,
) {
let now = Instant::now();
let double = self
.last_click
.is_some_and(|(at, field)| field == id && now.duration_since(at).as_millis() < 250);
self.last_click = Some((now, id));
self.held = true;
self.edit(id, value, max, |edit| {
[edit.x, edit.y, edit.width, edit.height] = rect;
edit.click(atlas, x, shift, double);
});
}
/// The pointer moved with the button held after a press on field `id`.
pub fn drag(
&mut self,
atlas: &HudAtlas,
(id, value, max): (crate::clipboard::FieldId, &mut String, usize),
x: f32,
) {
if self.held && self.last_click.is_some_and(|(_, field)| field == id) {
self.edit(id, value, max, |edit| edit.drag_to(atlas, x));
}
}
/// The button was released: drags no longer select.
pub fn release(&mut self) {
self.held = false;
}
/// Draw field `id` at `rect`: the focused one with its caret, the others
/// showing the end of their text.
#[allow(clippy::too_many_arguments)]
pub fn draw(
&mut self,
batch: &mut HudBatch,
atlas: &HudAtlas,
(id, value, max): (crate::clipboard::FieldId, &str, usize),
rect: [f32; 4],
focused: bool,
focused_at: Instant,
) {
let mut idle;
let edit = if focused {
self.sync(id, value, max)
} else {
idle = EditBox::new(0.0, 0.0, 0.0, 0.0);
idle.max_length = max;
idle.set_value(value);
&mut idle
};
[edit.x, edit.y, edit.width, edit.height] = rect;
edit.focused = focused;
if edit.focused_at < focused_at {
edit.focused_at = focused_at;
}
edit.draw(batch, atlas, None);
}
}
/// `EditBox.extractWidgetRenderState` for Horizon's append-only fields,
/// unbordered and with the cursor at the end: the text from (x, y), the
/// highlight when Select All covers the value (`invert_text` as
@@ -740,10 +856,14 @@ impl EditBox {
self.value.replace_range(ba..bb, "");
self.set_cursor(a, false);
}
/// EditBox.getWordPosition.
/// EditBox.getWordPosition from the cursor.
pub fn word_position(&self, dir: isize) -> usize {
self.word_position_from(dir, self.cursor)
}
/// EditBox.getWordPosition(dir, from).
fn word_position_from(&self, dir: isize, from: usize) -> usize {
let chars: Vec<char> = self.value.chars().collect();
let mut pos = self.cursor;
let mut pos = from.min(chars.len());
if dir < 0 {
while pos > 0 && chars[pos - 1] == ' ' {
pos -= 1;
@@ -773,6 +893,33 @@ impl EditBox {
pub fn move_cursor_to_end(&mut self, select: bool) {
self.set_cursor(char_len(&self.value), select);
}
/// EditBox.findClickedPositionInText: the character boundary under GUI `x`.
pub fn position_at(&mut self, atlas: &HudAtlas, x: f32) -> usize {
self.layout(atlas);
let room = (x.floor() - self.text_x()).min(self.inner_width());
let rest: String = self.value.chars().skip(self.display).collect();
self.display + atlas.font.fit(&rest, room)
}
/// EditBox.onClick: the cursor to the pointer, extending the selection
/// with Shift; a double click selects the word under it (`selectWord`).
pub fn click(&mut self, atlas: &HudAtlas, x: f32, shift: bool, double: bool) {
let pos = self.position_at(atlas, x);
if double {
let (start, end) = (
self.word_position_from(-1, pos),
self.word_position_from(1, pos),
);
self.set_cursor(start, false);
self.set_cursor(end, true);
} else {
self.set_cursor(pos, shift);
}
}
/// EditBox.onDrag: the selection follows the pointer.
pub fn drag_to(&mut self, atlas: &HudAtlas, x: f32) {
let pos = self.position_at(atlas, x);
self.set_cursor(pos, true);
}
fn scroll_to(&mut self, pos: usize) {
// EditBox.scrollTo without font access is completed in `layout`.
self.display = self.display.min(char_len(&self.value));
@@ -1086,6 +1233,26 @@ mod tests {
assert_eq!(s.amount, 36.0);
}
#[test]
fn edit_box_clicks_place_the_cursor_and_select() {
let atlas = HudAtlas::build(Path::new("/nonexistent/horizon-test-assets")).unwrap();
let mut e = EditBox::new(10.0, 0.0, 200.0, 20.0);
e.set_value("hello world");
let at = |e: &EditBox, s: &str| e.text_x() + atlas.font.width(s);
// findClickedPositionInText: the characters left of the pointer.
e.click(&atlas, at(&e, "hello "), false, false);
assert_eq!((e.cursor, e.highlight), (6, 6));
// Shift extends the selection from the anchor.
e.click(&atlas, at(&e, "hello wor"), true, false);
assert_eq!(e.selected_text(), "wor");
// selectWord: the word and the spaces after it.
e.click(&atlas, at(&e, "he"), false, true);
assert_eq!(e.selected_text(), "hello ");
// onDrag from a click: left of the text is its start.
e.click(&atlas, at(&e, "hello "), false, false);
e.drag_to(&atlas, e.text_x() - 5.0);
assert_eq!((e.cursor, e.highlight), (0, 6));
}
#[test]
fn edit_box_editing() {
let mut e = EditBox::new(0.0, 0.0, 100.0, 20.0);
e.max_length = 10;