Skip to main content

unbanished_ui/input/
keyboard.rs

1//! The keyboard: keys and shortcuts, typing into an edit, committing an edit and the caret.
2
3use super::*;
4
5pub(super) fn byte_index(s: &str, cursor: usize) -> usize {
6    s.char_indices().nth(cursor).map_or(s.len(), |p| p.0)
7}
8
9/// `System::String::ToInteger`: an optional sign and the digits after it, 0 without.
10pub(super) fn to_integer(s: &str) -> i32 {
11    let s = s.trim_start();
12    let (sign, digits) = match s.strip_prefix('-') {
13        Some(rest) => (-1i64, rest),
14        None => (1, s.strip_prefix('+').unwrap_or(s)),
15    };
16    let mut v: i64 = 0;
17    for c in digits.chars().take_while(|c| c.is_ascii_digit()) {
18        v = (v * 10 + c as i64 - '0' as i64).min(i32::MAX as i64 + 1);
19    }
20    (sign * v).clamp(i32::MIN as i64, i32::MAX as i64) as i32
21}
22
23impl Ui {
24    /// Press a key. Returns whether the interface used it.
25    pub fn key(&mut self, root: NodeId, key: Key) -> bool {
26        let active = self.active_nodes(root);
27        if self.focus.is_some_and(|id| !active.contains(&id)) {
28            self.focus = None;
29        }
30        if matches!(key, Key::Tab | Key::BackTab) {
31            let focusable: Vec<_> = active
32                .iter()
33                .copied()
34                .filter(|&id| self.interactive(id))
35                .collect();
36            if focusable.is_empty() {
37                return false;
38            }
39            let current = self
40                .focus
41                .and_then(|id| focusable.iter().position(|&n| n == id));
42            let i = match (current, key) {
43                (Some(i), Key::BackTab) => (i + focusable.len() - 1) % focusable.len(),
44                (Some(i), _) => (i + 1) % focusable.len(),
45                (None, Key::BackTab) => focusable.len() - 1,
46                _ => 0,
47            };
48            self.focus = Some(focusable[i]);
49            return true;
50        }
51        if let Some(id) = self.focus {
52            // A combo's popup retains focus while arrows browse; Enter confirms and Escape
53            // closes it. These keys must not fall through to the asset browser's navigation.
54            let combo = active
55                .iter()
56                .find_map(|&parent| match self.nodes[parent].kind {
57                    Kind::Control(Control::Combo { list, .. }) if parent == id || list == id => {
58                        Some((parent, list))
59                    }
60                    _ => None,
61                });
62            if let Some((parent, list)) = combo {
63                if matches!(key, Key::Up | Key::Down | Key::Home | Key::End) {
64                    if let Kind::Control(Control::Combo { open, .. }) = &mut self.nodes[parent].kind
65                    {
66                        *open = true;
67                    }
68                    if let Kind::List(l) = &mut self.nodes[list].kind {
69                        if !l.items.is_empty() {
70                            let last = l.items.len() - 1;
71                            let i = match key {
72                                Key::Home => 0,
73                                Key::End => last,
74                                Key::Up => l.selected.unwrap_or(0).saturating_sub(1),
75                                _ => l.selected.map_or(0, |i| (i + 1).min(last)),
76                            };
77                            l.selected = Some(i);
78                            l.reveal = true;
79                        }
80                    }
81                    self.focus = Some(list);
82                    return true;
83                }
84                if key == Key::Escape {
85                    if let Kind::Control(Control::Combo { open, .. }) = &mut self.nodes[parent].kind
86                    {
87                        *open = false;
88                    }
89                    self.focus = Some(parent);
90                    return true;
91                }
92                if id == list && matches!(key, Key::Enter | Key::Space) {
93                    if let Kind::List(l) = &self.nodes[list].kind {
94                        if let Some(i) = l.selected {
95                            let event = self.route_event(root, Event::Selected(list, i));
96                            self.pending.push(event);
97                        }
98                    }
99                    self.focus = Some(parent);
100                    return true;
101                }
102            }
103            if let Kind::Control(Control::Edit(e)) = &mut self.nodes[id].kind {
104                let len = e.text.text.chars().count();
105                e.cursor = e.cursor.min(len);
106                let mut changed = false;
107                match key {
108                    Key::Left => e.cursor = e.cursor.saturating_sub(1),
109                    Key::Right => e.cursor = (e.cursor + 1).min(len),
110                    Key::Home => e.cursor = 0,
111                    Key::End => e.cursor = len,
112                    Key::Backspace if e.cursor > 0 => {
113                        let at = byte_index(&e.text.text, e.cursor);
114                        let prev = byte_index(&e.text.text, e.cursor - 1);
115                        e.text.text.replace_range(prev..at, "");
116                        e.cursor -= 1;
117                        changed = true;
118                    }
119                    Key::Delete if e.cursor < len => {
120                        let at = byte_index(&e.text.text, e.cursor);
121                        let next = byte_index(&e.text.text, e.cursor + 1);
122                        e.text.text.replace_range(at..next, "");
123                        changed = true;
124                    }
125                    // `EditElement::Update`: Enter or Escape gives up the focus.
126                    Key::Enter | Key::Escape => {
127                        self.commit_edit(id);
128                        return true;
129                    }
130                    Key::Character(_) | Key::Space => return false,
131                    _ => return true,
132                }
133                if changed {
134                    self.pending.push(Event::Changed(id));
135                }
136                return true;
137            }
138            if let Kind::Control(Control::Slider(s)) = &self.nodes[id].kind {
139                let step = s.step();
140                let value = match key {
141                    Key::Left | Key::Down => s.value - step,
142                    Key::Right | Key::Up => s.value + step,
143                    Key::Home => s.range[0],
144                    Key::End => s.range[1],
145                    _ => f32::NAN,
146                };
147                if value.is_finite() {
148                    self.set_value(id, value);
149                    self.pending.push(Event::Changed(id));
150                    return true;
151                }
152            }
153            if let Kind::List(l) = &mut self.nodes[id].kind {
154                let last = l.items.len().saturating_sub(1);
155                let current = l.selected.unwrap_or(0);
156                let selected = match key {
157                    Key::Up => Some(current.saturating_sub(1)),
158                    Key::Down => Some(l.selected.map_or(0, |i| (i + 1).min(last))),
159                    Key::Home => Some(0),
160                    Key::End => Some(last),
161                    Key::PageUp => Some(current.saturating_sub(10)),
162                    Key::PageDown => Some((current + 10).min(last)),
163                    _ => None,
164                };
165                if let Some(i) = selected.filter(|_| !l.items.is_empty()) {
166                    l.selected = Some(i);
167                    l.reveal = true;
168                    let e = self.route_event(root, Event::Selected(id, i));
169                    self.pending.push(e);
170                    return true;
171                }
172            }
173            if matches!(key, Key::Enter | Key::Space) {
174                if let Some(event) = self.activate(id) {
175                    let event = self.route_event(root, event);
176                    self.pending.push(event);
177                    return true;
178                }
179            }
180        }
181        if key == Key::Escape {
182            let mut closed = false;
183            for id in &active {
184                if let Kind::Control(Control::Combo { open, .. }) = &mut self.nodes[*id].kind {
185                    closed |= *open;
186                    *open = false;
187                }
188            }
189            if closed {
190                return true;
191            }
192        }
193        let code = match key {
194            Key::Enter => 13,
195            Key::Escape => 27,
196            Key::Space => 32,
197            Key::Character(c) => c.to_ascii_uppercase() as u32,
198            _ => 0,
199        };
200        if code != 0 {
201            if let Some(id) = active
202                .into_iter()
203                .find(|&id| self.nodes[id].shortcut == Some(code))
204            {
205                if let Some(e) = self.activate(id) {
206                    let e = self.route_event(root, e);
207                    self.pending.push(e);
208                    return true;
209                }
210            }
211        }
212        false
213    }
214
215    /// Type text into the focused edit box. Returns whether it was used.
216    pub fn text_input(&mut self, text: &str) -> bool {
217        let Some(id) = self.focus else {
218            return false;
219        };
220        let Kind::Control(Control::Edit(e)) = &mut self.nodes[id].kind else {
221            return false;
222        };
223        if e.max_length == 0 {
224            return false;
225        }
226        let mut changed = false;
227        // `EditElement::SelectCharacter`: the keys of a US keyboard give printable ASCII but
228        // `:` and `;`; each goes in while the text is shorter than its most and the edit
229        // takes it. Deviation: an edit whose allowed characters name `:` or `;` takes them (the
230        // Multiplayer window's relay address); the original's edits never name them.
231        for ch in text.chars() {
232            let typable =
233                (' '..='~').contains(&ch) && (!matches!(ch, ':' | ';') || e.allowed.contains(ch));
234            if !typable
235                || e.text.text.chars().count() >= e.max_length
236                || (!e.allowed.is_empty() && !e.allowed.contains(ch))
237            {
238                continue;
239            }
240            let at = byte_index(&e.text.text, e.cursor);
241            e.text.text.insert(at, ch);
242            e.cursor += 1;
243            changed = true;
244        }
245        if changed {
246            self.pending.push(Event::Changed(id));
247        }
248        true
249    }
250
251    /// `EditElement::Update` losing the focus (Enter, Escape or a press elsewhere): a
252    /// NumberEdit's text becomes its number within its range (`NumberEditElement::
253    /// FinalizeText`), and event `0x15` goes.
254    pub(crate) fn commit_edit(&mut self, id: NodeId) {
255        if let Kind::Control(Control::Edit(e)) = &mut self.nodes[id].kind {
256            if let Some(range) = e.range {
257                let value = to_integer(&e.text.text)
258                    .clamp(range[0].min(range[1]) as i32, range[0].max(range[1]) as i32);
259                e.text.text = value.to_string();
260                e.cursor = e.cursor.min(e.text.text.chars().count());
261            }
262            self.pending.push(Event::Submitted(id));
263        }
264        if self.focus == Some(id) {
265            self.focus = None;
266        }
267    }
268
269    /// The caret's blink: every half second while an edit has the focus.
270    pub(crate) fn update_caret(&mut self, dt: f32) {
271        let Some(id) = self.focus else { return };
272        if let Kind::Control(Control::Edit(e)) = &mut self.nodes[id].kind {
273            e.blink += dt;
274            if 0.5 < e.blink {
275                e.caret = !e.caret;
276                e.blink = 0.0;
277            }
278        }
279    }
280}