1use std::rc::Rc;
12
13use crabshell_reactive::{Signal, untrack};
14
15use crate::cx::Cx;
16use crate::edit::Keyed;
17use crate::input::{Handler, run_isolated};
18use crate::select::copy_key;
19use crate::text_input::AcceptHandler;
20use crate::tree::{Change, NodeId, NodeKind, Tree, borrow};
21use crate::window::Window;
22
23#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct KeyEvent {
26 pub key: Key,
28 pub text: Option<String>,
31 pub modifiers: Modifiers,
33 pub repeat: bool,
35}
36
37#[derive(Clone, Debug, PartialEq, Eq)]
39pub enum Key {
40 Enter,
42 Escape,
44 Tab,
46 Backspace,
48 Delete,
50 Left,
52 Right,
54 Up,
56 Down,
58 Home,
60 End,
62 PageUp,
64 PageDown,
66 Function(u8),
68 Character(char),
71 Other(u32),
74}
75
76#[derive(Clone, Debug, PartialEq, Eq)]
78pub enum Clipboard {
79 Copy(String),
81 Paste,
84}
85
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
88pub struct Modifiers {
89 pub ctrl: bool,
91 pub alt: bool,
93 pub shift: bool,
95 pub logo: bool,
97}
98
99const PAGE_LINES: f32 = 10.0;
102
103pub(crate) type KeyHandler = Rc<Handler<dyn Fn(&Cx, &KeyEvent) -> bool>>;
104
105#[derive(Default)]
107pub(crate) struct Keyboard {
108 pub(crate) entered: bool,
110 pub(crate) focused: Option<NodeId>,
112 pub(crate) link: Option<usize>,
114 pub(crate) handler: Option<KeyHandler>,
116 pub(crate) modifiers: Modifiers,
118}
119
120impl Keyboard {
121 pub(crate) fn forget(&mut self, removed: &[NodeId]) {
123 if self.focused.is_some_and(|id| removed.contains(&id)) {
124 self.focused = None;
125 self.link = None;
126 }
127 }
128}
129
130impl Window {
131 pub fn keyboard_enter(&self) {
134 let mut tree = borrow(&self.tree);
135 tree.keyboard.entered = true;
136 let focused = tree.keyboard.focused;
137 tree.show_focus(focused, true);
138 }
139
140 pub fn keyboard_leave(&self) {
143 let mut tree = borrow(&self.tree);
144 tree.keyboard.entered = false;
145 let focused = tree.keyboard.focused;
146 tree.show_focus(focused, false);
147 }
148
149 pub fn set_modifiers(&self, modifiers: Modifiers) {
152 borrow(&self.tree).keyboard.modifiers = modifiers;
153 }
154
155 pub fn key(&self, event: &KeyEvent) -> Option<Clipboard> {
165 let typed = borrow(&self.tree).input_key(event);
166 match typed {
167 Some(Typed::Edited(signal, text, clipboard)) => {
168 signal.try_set(text);
170 return clipboard;
171 }
172 Some(Typed::Clipboard(clipboard)) => return Some(clipboard),
173 Some(Typed::Moved) => return None,
174 Some(Typed::Accept(call)) => {
175 call.run();
176 return None;
177 }
178 None => {}
179 }
180 let (button, window) = {
181 let tree = self.tree.borrow();
182 (tree.focused_key_call(), tree.window_key_call())
183 };
184 for call in [button, window].into_iter().flatten() {
185 if call.run(event) {
186 return None;
187 }
188 }
189 let click = borrow(&self.tree).default_key(event);
190 if let Some(click) = click {
191 click.run();
192 }
193 None
194 }
195
196 pub fn focused(&self) -> Option<String> {
198 let tree = self.tree.borrow();
199 let id = tree.keyboard.focused?;
200 tree.node(id).map(|node| node.path.to_string())
201 }
202}
203
204impl Tree {
205 fn show_focus(&mut self, id: Option<NodeId>, shown: bool) {
209 let Some(id) = id else {
210 return;
211 };
212 if let Some(NodeKind::Text(_)) = self.node(id).map(|node| &node.kind) {
214 let link = self.keyboard.link.filter(|_| shown);
215 self.light_link(id, true, link);
216 return;
217 }
218 if matches!(
219 self.node(id).map(|node| &node.kind),
220 Some(NodeKind::Input(_))
221 ) {
222 self.update(id, |node| match &mut node.kind {
223 NodeKind::Input(input) if input.focused != shown => {
224 input.focused = shown;
225 Change::Paint
226 }
227 _ => Change::None,
228 });
229 } else {
230 self.update_button_style(id, |button| button.focused = shown);
231 }
232 }
233
234 pub(crate) fn focus(&mut self, id: Option<NodeId>) {
237 self.focus_link(id, None);
238 }
239
240 pub(crate) fn drop_stale_link_focus(&mut self, id: NodeId) {
243 let (Some(focused), Some(link)) = (self.keyboard.focused, self.keyboard.link) else {
244 return;
245 };
246 let still = match self.node(id).map(|node| &node.kind) {
247 Some(NodeKind::Text(text)) => text.spans.get(link).is_some_and(|span| span.link.is_some()),
248 _ => false,
249 };
250 if focused == id && !still {
251 self.focus(None);
252 }
253 }
254
255 fn focus_link(&mut self, id: Option<NodeId>, link: Option<usize>) {
257 if id.is_some_and(|id| !self.shown(id)) {
258 return;
259 }
260 if self.keyboard.focused == id {
261 if self.keyboard.link != link {
262 self.keyboard.link = link;
263 let entered = self.keyboard.entered;
264 self.show_focus(id, entered);
265 }
266 return;
267 }
268 let old = std::mem::replace(&mut self.keyboard.focused, id);
269 if let Some(old) = old
271 && matches!(self.node(old).map(|node| &node.kind), Some(NodeKind::Input(input)) if input.preedit.is_some())
272 {
273 self.update_input(old, |input| {
274 input.preedit = None;
275 input.refresh();
276 });
277 }
278 if let Some(old) = old {
279 self.drop_selection(old);
280 }
281 self.show_focus(old, false);
282 self.keyboard.link = link;
283 let entered = self.keyboard.entered;
284 self.show_focus(id, entered);
285 if let Some(id) = id {
287 self.update_input(id, |_| {});
288 }
289 }
290
291 fn input_key(&mut self, event: &KeyEvent) -> Option<Typed> {
294 let id = self.keyboard.focused?;
295 let view = self.page_height(id);
296 let input = match &mut self.node_mut(id)?.kind {
297 NodeKind::Input(input) => input,
298 NodeKind::Text(text) => return copy_key(text, event).map(Typed::Clipboard),
299 _ => return None,
300 };
301 let page = view.unwrap_or(PAGE_LINES * input.text.buffer.metrics().line_height);
302 let keyed = match input.edit.multiline {
303 true => input.line_key(event, page),
304 false => None,
305 };
306 let keyed = keyed.unwrap_or_else(|| {
307 input.upstream = None;
309 input.goal = None;
310 input.edit.key(event, !input.password)
311 });
312 let accept = keyed == Keyed::Accept;
313 let typed = match keyed {
314 Keyed::Unused => return None,
315 Keyed::Moved => Typed::Moved,
316 Keyed::Edited => Typed::Edited(input.signal, input.edit.text.clone(), None),
317 Keyed::Copy(text) => Typed::Clipboard(Clipboard::Copy(text)),
318 Keyed::Cut(text) => Typed::Edited(
319 input.signal,
320 input.edit.text.clone(),
321 Some(Clipboard::Copy(text)),
322 ),
323 Keyed::Paste => Typed::Clipboard(Clipboard::Paste),
324 Keyed::Accept => {
325 let handler = untrack(|| input.on_accept.try_with(Option::clone)).flatten();
326 let text = input.edit.text.clone();
327 let node = self.node(id)?;
328 Typed::Accept(AcceptCall {
330 cx: node.cx.clone(),
331 path: Rc::clone(&node.path),
332 handler: handler?,
333 text,
334 })
335 }
336 };
337 if !accept {
338 self.update_input(id, |input| {
339 input.refresh();
340 });
341 }
342 Some(typed)
343 }
344
345 fn page_height(&self, id: NodeId) -> Option<f32> {
348 self
349 .path_to(id)
350 .into_iter()
351 .rev()
352 .find_map(|at| match &self.node(at)?.kind {
353 NodeKind::Scroll(scroll) => scroll
354 .active()
355 .iter()
356 .find(|axis| !axis.horizontal)
357 .map(|axis| axis.length),
358 _ => None,
359 })
360 }
361
362 fn focusable(&self) -> Vec<(NodeId, Option<usize>)> {
366 let mut found = Vec::new();
367 let mut pending = vec![self.root];
368 while let Some(id) = pending.pop() {
369 if self.node(id).is_some_and(|node| !node.visible) {
371 continue;
372 }
373 match self.node(id).map(|node| &node.kind) {
374 Some(NodeKind::Button(button)) if button.enabled => found.push((id, None)),
375 Some(NodeKind::Input(_)) => found.push((id, None)),
376 Some(NodeKind::Text(text)) => {
377 found.extend(text.link_stops().into_iter().map(|link| (id, Some(link))));
378 }
379 _ => {}
380 }
381 let mut children = self.taffy.children(id).unwrap_or_default();
382 children.reverse();
383 pending.extend(children);
384 }
385 found
386 }
387
388 fn focused_key_call(&self) -> Option<KeyCall> {
389 let id = self.keyboard.focused?;
390 let node = self.node(id)?;
391 let NodeKind::Button(button) = &node.kind else {
392 return None;
393 };
394 let handler = untrack(|| button.handlers.try_with(|handlers| handlers.key.clone()))??;
396 Some(KeyCall {
397 cx: node.cx.clone(),
398 path: Rc::clone(&node.path),
399 handler,
400 })
401 }
402
403 fn window_key_call(&self) -> Option<KeyCall> {
404 let node = self.node(self.root)?;
405 Some(KeyCall {
406 cx: node.cx.clone(),
407 path: Rc::clone(&node.path),
408 handler: self.keyboard.handler.clone()?,
409 })
410 }
411
412 fn default_key(&mut self, event: &KeyEvent) -> Option<crate::input::Call> {
415 match event.key {
416 Key::Tab => {
417 let buttons = self.focusable();
418 let at = self.keyboard.focused.and_then(|id| {
419 let link = self.keyboard.link;
420 buttons.iter().position(|&stop| stop == (id, link))
421 });
422 let count = buttons.len();
423 let next = match (at, event.modifiers.shift) {
424 _ if count == 0 => None,
425 (None, false) => Some(0),
426 (None, true) => Some(count - 1),
427 (Some(at), false) => Some((at + 1) % count),
428 (Some(at), true) => Some((at + count - 1) % count),
429 };
430 let (id, link) = next.map_or((None, None), |next| {
431 (Some(buttons[next].0), buttons[next].1)
432 });
433 self.focus_link(id, link);
434 None
435 }
436 Key::Enter | Key::Character(' ') => {
437 let id = self.keyboard.focused?;
438 match self.keyboard.link {
439 Some(link) => self.link_call(id, link),
440 None => self.click(id),
441 }
442 }
443 _ => None,
444 }
445 }
446}
447
448enum Typed {
450 Edited(Signal<String>, String, Option<Clipboard>),
452 Clipboard(Clipboard),
454 Moved,
456 Accept(AcceptCall),
458}
459
460struct AcceptCall {
462 cx: Cx,
463 path: Rc<str>,
464 handler: AcceptHandler,
465 text: String,
466}
467
468impl AcceptCall {
469 fn run(self) {
470 run_isolated(&self.path, "on_accept", self.handler, |f| {
471 f(&self.cx, &self.text)
472 });
473 }
474}
475
476struct KeyCall {
478 cx: Cx,
479 path: Rc<str>,
480 handler: KeyHandler,
481}
482
483impl KeyCall {
484 fn run(self, event: &KeyEvent) -> bool {
486 run_isolated(&self.path, "on_key", self.handler, |f| f(&self.cx, event)).unwrap_or(false)
487 }
488}