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 was = input.edit.selection();
307 let keyed = keyed.unwrap_or_else(|| {
308 input.upstream = None;
310 input.goal = None;
311 input.edit.key(event, !input.password)
312 });
313 let selected = input
315 .edit
316 .selection()
317 .filter(|now| keyed == Keyed::Moved && Some(now) != was.as_ref() && !input.password);
318 let primary = selected.and_then(|range| input.edit.text.get(range).map(str::to_owned));
319 let accept = keyed == Keyed::Accept;
320 let typed = match keyed {
321 Keyed::Unused => return None,
322 Keyed::Moved => Typed::Moved,
323 Keyed::Edited => Typed::Edited(input.signal, input.edit.text.clone(), None),
324 Keyed::Copy(text) => Typed::Clipboard(Clipboard::Copy(text)),
325 Keyed::Cut(text) => Typed::Edited(
326 input.signal,
327 input.edit.text.clone(),
328 Some(Clipboard::Copy(text)),
329 ),
330 Keyed::Paste => Typed::Clipboard(Clipboard::Paste),
331 Keyed::Accept => {
332 let handler = untrack(|| input.on_accept.try_with(Option::clone)).flatten();
333 let text = input.edit.text.clone();
334 let node = self.node(id)?;
335 Typed::Accept(AcceptCall {
337 cx: node.cx.clone(),
338 path: Rc::clone(&node.path),
339 handler: handler?,
340 text,
341 })
342 }
343 };
344 if !accept {
345 self.update_input(id, |input| {
346 input.refresh();
347 });
348 }
349 if let Some(text) = primary {
350 self.primary = Some(Clipboard::Copy(text));
351 }
352 Some(typed)
353 }
354
355 fn page_height(&self, id: NodeId) -> Option<f32> {
358 self
359 .path_to(id)
360 .into_iter()
361 .rev()
362 .find_map(|at| match &self.node(at)?.kind {
363 NodeKind::Scroll(scroll) => scroll
364 .active()
365 .iter()
366 .find(|axis| !axis.horizontal)
367 .map(|axis| axis.length),
368 _ => None,
369 })
370 }
371
372 fn focusable(&self) -> Vec<(NodeId, Option<usize>)> {
376 let mut found = Vec::new();
377 let mut pending = vec![self.root];
378 while let Some(id) = pending.pop() {
379 if self.node(id).is_some_and(|node| !node.visible) {
381 continue;
382 }
383 match self.node(id).map(|node| &node.kind) {
384 Some(NodeKind::Button(button)) if button.enabled => found.push((id, None)),
385 Some(NodeKind::Input(_)) => found.push((id, None)),
386 Some(NodeKind::Text(text)) => {
387 found.extend(text.link_stops().into_iter().map(|link| (id, Some(link))));
388 }
389 _ => {}
390 }
391 let mut children = self.taffy.children(id).unwrap_or_default();
392 children.reverse();
393 pending.extend(children);
394 }
395 found
396 }
397
398 fn focused_key_call(&self) -> Option<KeyCall> {
399 let id = self.keyboard.focused?;
400 let node = self.node(id)?;
401 let NodeKind::Button(button) = &node.kind else {
402 return None;
403 };
404 let handler = untrack(|| button.handlers.try_with(|handlers| handlers.key.clone()))??;
406 Some(KeyCall {
407 cx: node.cx.clone(),
408 path: Rc::clone(&node.path),
409 handler,
410 })
411 }
412
413 fn window_key_call(&self) -> Option<KeyCall> {
414 let node = self.node(self.root)?;
415 Some(KeyCall {
416 cx: node.cx.clone(),
417 path: Rc::clone(&node.path),
418 handler: self.keyboard.handler.clone()?,
419 })
420 }
421
422 fn default_key(&mut self, event: &KeyEvent) -> Option<crate::input::Call> {
425 match event.key {
426 Key::Tab => {
427 let buttons = self.focusable();
428 let at = self.keyboard.focused.and_then(|id| {
429 let link = self.keyboard.link;
430 buttons.iter().position(|&stop| stop == (id, link))
431 });
432 let count = buttons.len();
433 let next = match (at, event.modifiers.shift) {
434 _ if count == 0 => None,
435 (None, false) => Some(0),
436 (None, true) => Some(count - 1),
437 (Some(at), false) => Some((at + 1) % count),
438 (Some(at), true) => Some((at + count - 1) % count),
439 };
440 let (id, link) = next.map_or((None, None), |next| {
441 (Some(buttons[next].0), buttons[next].1)
442 });
443 self.focus_link(id, link);
444 None
445 }
446 Key::Enter | Key::Character(' ') => {
447 let id = self.keyboard.focused?;
448 match self.keyboard.link {
449 Some(link) => self.link_call(id, link),
450 None => self.click(id),
451 }
452 }
453 _ => None,
454 }
455 }
456}
457
458enum Typed {
460 Edited(Signal<String>, String, Option<Clipboard>),
462 Clipboard(Clipboard),
464 Moved,
466 Accept(AcceptCall),
468}
469
470struct AcceptCall {
472 cx: Cx,
473 path: Rc<str>,
474 handler: AcceptHandler,
475 text: String,
476}
477
478impl AcceptCall {
479 fn run(self) {
480 run_isolated(&self.path, "on_accept", self.handler, |f| {
481 f(&self.cx, &self.text)
482 });
483 }
484}
485
486struct KeyCall {
488 cx: Cx,
489 path: Rc<str>,
490 handler: KeyHandler,
491}
492
493impl KeyCall {
494 fn run(self, event: &KeyEvent) -> bool {
496 run_isolated(&self.path, "on_key", self.handler, |f| f(&self.cx, event)).unwrap_or(false)
497 }
498}