1use std::rc::Rc;
12
13use crabshell_reactive::{Signal, untrack};
14
15use crate::access::AccessEvent;
16use crate::cx::Cx;
17use crate::edit::Keyed;
18use crate::input::{Handler, run_isolated};
19use crate::select::copy_key;
20use crate::text_input::AcceptHandler;
21use crate::tree::{Change, NodeId, NodeKind, Tree, borrow};
22use crate::window::Window;
23
24#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct KeyEvent {
27 pub key: Key,
29 pub text: Option<String>,
32 pub modifiers: Modifiers,
34 pub repeat: bool,
36}
37
38#[derive(Clone, Debug, PartialEq, Eq)]
40pub enum Key {
41 Enter,
43 Escape,
45 Tab,
47 Backspace,
49 Delete,
51 Left,
53 Right,
55 Up,
57 Down,
59 Home,
61 End,
63 PageUp,
65 PageDown,
67 Function(u8),
69 Character(char),
72 Other(u32),
75}
76
77#[derive(Clone, Debug, PartialEq, Eq)]
79pub enum Clipboard {
80 Copy(String),
82 Paste,
85}
86
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
89pub struct Modifiers {
90 pub ctrl: bool,
92 pub alt: bool,
94 pub shift: bool,
96 pub logo: bool,
98}
99
100const PAGE_LINES: f32 = 10.0;
103
104pub(crate) type KeyHandler = Rc<Handler<dyn Fn(&Cx, &KeyEvent) -> bool>>;
105
106#[derive(Default)]
108pub(crate) struct Keyboard {
109 pub(crate) entered: bool,
111 pub(crate) focused: Option<NodeId>,
113 pub(crate) link: Option<usize>,
115 pub(crate) handler: Option<KeyHandler>,
117 pub(crate) modifiers: Modifiers,
119}
120
121impl Keyboard {
122 pub(crate) fn forget(&mut self, removed: &[NodeId]) {
124 if self.focused.is_some_and(|id| removed.contains(&id)) {
125 self.focused = None;
126 self.link = None;
127 }
128 }
129}
130
131impl Window {
132 pub fn keyboard_enter(&self) {
135 let mut tree = borrow(&self.tree);
136 if !std::mem::replace(&mut tree.keyboard.entered, true) {
137 let root = tree.root;
138 tree.node_event(root, |id| AccessEvent::Active(id, true));
139 }
140 let focused = tree.keyboard.focused;
141 tree.show_focus(focused, true);
142 }
143
144 pub fn keyboard_leave(&self) {
147 let mut tree = borrow(&self.tree);
148 let was = std::mem::replace(&mut tree.keyboard.entered, false);
149 let focused = tree.keyboard.focused;
150 tree.show_focus(focused, false);
151 if was {
152 let root = tree.root;
153 tree.node_event(root, |id| AccessEvent::Active(id, false));
154 }
155 }
156
157 pub fn set_modifiers(&self, modifiers: Modifiers) {
160 borrow(&self.tree).keyboard.modifiers = modifiers;
161 }
162
163 pub fn key(&self, event: &KeyEvent) -> Option<Clipboard> {
173 let typed = borrow(&self.tree).input_key(event);
174 match typed {
175 Some(Typed::Edited(signal, text, clipboard)) => {
176 signal.try_set(text);
178 return clipboard;
179 }
180 Some(Typed::Clipboard(clipboard)) => return Some(clipboard),
181 Some(Typed::Moved) => return None,
182 Some(Typed::Accept(call)) => {
183 call.run();
184 return None;
185 }
186 None => {}
187 }
188 let (button, window) = {
189 let tree = self.tree.borrow();
190 (tree.focused_key_call(), tree.window_key_call())
191 };
192 for call in [button, window].into_iter().flatten() {
193 if call.run(event) {
194 return None;
195 }
196 }
197 let click = borrow(&self.tree).default_key(event);
198 if let Some(click) = click {
199 click.run();
200 }
201 None
202 }
203
204 pub fn focused(&self) -> Option<String> {
206 let tree = self.tree.borrow();
207 let id = tree.keyboard.focused?;
208 tree.node(id).map(|node| node.path.to_string())
209 }
210}
211
212impl Tree {
213 fn show_focus(&mut self, id: Option<NodeId>, shown: bool) {
217 let Some(id) = id else {
218 return;
219 };
220 if let Some(NodeKind::Text(_)) = self.node(id).map(|node| &node.kind) {
222 let link = self.keyboard.link.filter(|_| shown);
223 self.light_link(id, true, link);
224 return;
225 }
226 let was = match self.node(id).map(|node| &node.kind) {
227 Some(NodeKind::Input(input)) => input.focused,
228 Some(NodeKind::Button(button)) => button.focused,
229 _ => return,
230 };
231 if was == shown {
232 return;
233 }
234 if matches!(
235 self.node(id).map(|node| &node.kind),
236 Some(NodeKind::Input(_))
237 ) {
238 self.update(id, |node| match &mut node.kind {
239 NodeKind::Input(input) => {
240 input.focused = shown;
241 Change::Paint
242 }
243 _ => Change::None,
244 });
245 } else {
246 self.update_button_style(id, |button| button.focused = shown);
247 }
248 self.node_event(id, |id| AccessEvent::Focused(id, shown));
249 }
250
251 pub(crate) fn focus(&mut self, id: Option<NodeId>) {
254 self.focus_link(id, None);
255 }
256
257 pub(crate) fn drop_stale_link_focus(&mut self, id: NodeId) {
260 let (Some(focused), Some(link)) = (self.keyboard.focused, self.keyboard.link) else {
261 return;
262 };
263 let still = match self.node(id).map(|node| &node.kind) {
264 Some(NodeKind::Text(text)) => text.spans.get(link).is_some_and(|span| span.link.is_some()),
265 _ => false,
266 };
267 if focused == id && !still {
268 self.focus(None);
269 }
270 }
271
272 fn focus_link(&mut self, id: Option<NodeId>, link: Option<usize>) {
274 if id.is_some_and(|id| !self.shown(id)) {
275 return;
276 }
277 if self.keyboard.focused == id {
278 if self.keyboard.link != link {
279 self.keyboard.link = link;
280 let entered = self.keyboard.entered;
281 self.show_focus(id, entered);
282 }
283 return;
284 }
285 let old = std::mem::replace(&mut self.keyboard.focused, id);
286 if let Some(old) = old
288 && matches!(self.node(old).map(|node| &node.kind), Some(NodeKind::Input(input)) if input.preedit.is_some())
289 {
290 self.update_input(old, |input| {
291 input.preedit = None;
292 input.refresh();
293 });
294 }
295 if let Some(old) = old {
296 self.drop_selection(old);
297 }
298 self.show_focus(old, false);
299 self.keyboard.link = link;
300 let entered = self.keyboard.entered;
301 self.show_focus(id, entered);
302 if let Some(id) = id {
304 self.update_input(id, |_| {});
305 }
306 }
307
308 fn input_key(&mut self, event: &KeyEvent) -> Option<Typed> {
311 let id = self.keyboard.focused?;
312 let view = self.page_height(id);
313 let before = self.field_before(id);
315 let input = match &mut self.node_mut(id)?.kind {
316 NodeKind::Input(input) => input,
317 NodeKind::Text(text) => return copy_key(text, event).map(Typed::Clipboard),
318 _ => return None,
319 };
320 let page = view.unwrap_or(PAGE_LINES * input.text.buffer.metrics().line_height);
321 let keyed = match input.edit.multiline {
322 true => input.line_key(event, page),
323 false => None,
324 };
325 let was = input.edit.selection();
326 let keyed = keyed.unwrap_or_else(|| {
327 input.upstream = None;
329 input.goal = None;
330 input.edit.key(event, !input.password)
331 });
332 let selected = input
334 .edit
335 .selection()
336 .filter(|now| keyed == Keyed::Moved && Some(now) != was.as_ref() && !input.password);
337 let primary = selected.and_then(|range| input.edit.text.get(range).map(str::to_owned));
338 let accept = keyed == Keyed::Accept;
339 let typed = match keyed {
340 Keyed::Unused => return None,
341 Keyed::Moved => Typed::Moved,
342 Keyed::Edited => Typed::Edited(input.signal, input.edit.text.clone(), None),
343 Keyed::Copy(text) => Typed::Clipboard(Clipboard::Copy(text)),
344 Keyed::Cut(text) => Typed::Edited(
345 input.signal,
346 input.edit.text.clone(),
347 Some(Clipboard::Copy(text)),
348 ),
349 Keyed::Paste => Typed::Clipboard(Clipboard::Paste),
350 Keyed::Accept => {
351 let handler = untrack(|| input.on_accept.try_with(Option::clone)).flatten();
352 let text = input.edit.text.clone();
353 let node = self.node(id)?;
354 Typed::Accept(AcceptCall {
356 cx: node.cx.clone(),
357 path: Rc::clone(&node.path),
358 handler: handler?,
359 text,
360 })
361 }
362 };
363 if !accept {
364 self.update_input(id, |input| {
365 input.refresh();
366 });
367 self.field_changed(id, before);
368 }
369 if let Some(text) = primary {
370 self.primary = Some(Clipboard::Copy(text));
371 }
372 Some(typed)
373 }
374
375 fn page_height(&self, id: NodeId) -> Option<f32> {
378 self
379 .path_to(id)
380 .into_iter()
381 .rev()
382 .find_map(|at| match &self.node(at)?.kind {
383 NodeKind::Scroll(scroll) => scroll
384 .active()
385 .iter()
386 .find(|axis| !axis.horizontal)
387 .map(|axis| axis.length),
388 _ => None,
389 })
390 }
391
392 fn focusable(&self) -> Vec<(NodeId, Option<usize>)> {
396 let mut found = Vec::new();
397 let mut pending = vec![self.root];
398 while let Some(id) = pending.pop() {
399 if self.node(id).is_some_and(|node| !node.visible) {
401 continue;
402 }
403 match self.node(id).map(|node| &node.kind) {
404 Some(NodeKind::Button(button)) if button.enabled => found.push((id, None)),
405 Some(NodeKind::Input(_)) => found.push((id, None)),
406 Some(NodeKind::Text(text)) => {
407 found.extend(text.link_stops().into_iter().map(|link| (id, Some(link))));
408 }
409 _ => {}
410 }
411 let mut children = self.taffy.children(id).unwrap_or_default();
412 children.reverse();
413 pending.extend(children);
414 }
415 found
416 }
417
418 fn focused_key_call(&self) -> Option<KeyCall> {
419 let id = self.keyboard.focused?;
420 let node = self.node(id)?;
421 let NodeKind::Button(button) = &node.kind else {
422 return None;
423 };
424 let handler = untrack(|| button.handlers.try_with(|handlers| handlers.key.clone()))??;
426 Some(KeyCall {
427 cx: node.cx.clone(),
428 path: Rc::clone(&node.path),
429 handler,
430 })
431 }
432
433 fn window_key_call(&self) -> Option<KeyCall> {
434 let node = self.node(self.root)?;
435 Some(KeyCall {
436 cx: node.cx.clone(),
437 path: Rc::clone(&node.path),
438 handler: self.keyboard.handler.clone()?,
439 })
440 }
441
442 fn default_key(&mut self, event: &KeyEvent) -> Option<crate::input::Call> {
445 match event.key {
446 Key::Tab => {
447 let buttons = self.focusable();
448 let at = self.keyboard.focused.and_then(|id| {
449 let link = self.keyboard.link;
450 buttons.iter().position(|&stop| stop == (id, link))
451 });
452 let count = buttons.len();
453 let next = match (at, event.modifiers.shift) {
454 _ if count == 0 => None,
455 (None, false) => Some(0),
456 (None, true) => Some(count - 1),
457 (Some(at), false) => Some((at + 1) % count),
458 (Some(at), true) => Some((at + count - 1) % count),
459 };
460 let (id, link) = next.map_or((None, None), |next| {
461 (Some(buttons[next].0), buttons[next].1)
462 });
463 self.focus_link(id, link);
464 None
465 }
466 Key::Enter | Key::Character(' ') => {
467 let id = self.keyboard.focused?;
468 match self.keyboard.link {
469 Some(link) => self.link_call(id, link),
470 None => self.click(id),
471 }
472 }
473 _ => None,
474 }
475 }
476}
477
478enum Typed {
480 Edited(Signal<String>, String, Option<Clipboard>),
482 Clipboard(Clipboard),
484 Moved,
486 Accept(AcceptCall),
488}
489
490struct AcceptCall {
492 cx: Cx,
493 path: Rc<str>,
494 handler: AcceptHandler,
495 text: String,
496}
497
498impl AcceptCall {
499 fn run(self) {
500 run_isolated(&self.path, "on_accept", self.handler, |f| {
501 f(&self.cx, &self.text)
502 });
503 }
504}
505
506struct KeyCall {
508 cx: Cx,
509 path: Rc<str>,
510 handler: KeyHandler,
511}
512
513impl KeyCall {
514 fn run(self, event: &KeyEvent) -> bool {
516 run_isolated(&self.path, "on_key", self.handler, |f| f(&self.cx, event)).unwrap_or(false)
517 }
518}