1use crate::types::vecmap::VecMap;
164use std::collections::HashMap;
165use std::fmt;
166
167use smallvec::SmallVec;
168use uzor::input::core::cook::CookState;
169use uzor::input::driver::CoordinatorDriver;
170use uzor::input::text::selection::{char_at_point, SelectionLine, TextSelection};
171use uzor::input::{
172 InputCoordinator, InputState, KeyCode, KeyPress, ModifierKeys, MouseButton, TextAction,
173 TextFieldStore, WidgetKind,
174};
175use uzor::{Rect, WidgetId};
176
177use crate::types::bus::{
178 ClipboardResult, ImeInput, KeyInput, KeyState, PointerInput, WheelDelta, WheelInput,
179};
180use crate::types::ids::{Revision, ScopeId, Seconds, Ticket, WindowId};
181use crate::types::intent::TextIntent;
182use crate::types::ops::{
183 Capture, CookedPointer, FocusOp, InputEffect, InputOp, PointerTarget, ScopeOwner,
184};
185use crate::types::snapshot::InputView;
186
187pub type InputEffects = SmallVec<[InputEffect; 2]>;
189
190pub const INPUT_TICKET_BASE: u64 = 1 << 63;
193
194#[allow(dead_code)]
197pub const CARET_BLINK_INTERVAL: Seconds = Seconds(0.5);
198
199const CARET_BLINK_MS: u64 = 500;
200
201const WHEEL_PIXELS_PER_LINE: f64 = 20.0;
204
205#[derive(Clone, Debug, Default)]
212struct PointerAccum {
213 pos: Option<(f64, f64)>,
214 prev_pos: Option<(f64, f64)>,
215 button_down: Option<MouseButton>,
216 clicked: Option<MouseButton>,
217 context: Option<(f64, f64)>,
219 mods: ModifierKeys,
220 scroll: (f64, f64),
221 scroll_precise: bool,
223 scroll_touch: bool,
225}
226
227#[derive(Clone, Debug, PartialEq, Eq)]
229struct SavedFocus {
230 id: WidgetId,
231 engaged: bool,
233}
234
235#[derive(Clone, Debug)]
236struct FocusScope {
237 owner: ScopeOwner,
238 members: Vec<WidgetId>,
239 saved: Option<SavedFocus>,
240}
241
242#[derive(Clone, Debug)]
245struct SelectableText {
246 text: String,
247 lines: Vec<SelectionLine>,
248}
249
250#[derive(Clone, Debug, Default)]
254pub struct Selectables(HashMap<WidgetId, SelectableText>, HashMap<WidgetId, WidgetId>);
255
256impl Selectables {
257 pub fn report(&mut self, widget: impl Into<WidgetId>, text: impl Into<String>, lines: Vec<SelectionLine>) {
260 self.0.insert(widget.into(), SelectableText { text: text.into(), lines });
261 }
262 pub fn alias(&mut self, member: impl Into<WidgetId>, owner: impl Into<WidgetId>) {
266 self.1.insert(member.into(), owner.into());
267 }
268 fn contains_key(&self, w: &WidgetId) -> bool {
269 self.0.contains_key(w)
270 }
271}
272
273#[derive(Clone, Debug)]
275struct PressSel {
276 widget: WidgetId,
277 anchor: usize,
278}
279
280#[derive(Clone, Copy, Debug, PartialEq, Eq)]
282enum EscLevel {
283 Widget,
285 Panel,
287 Window,
289}
290
291#[derive(Clone, Debug, PartialEq, Eq)]
294struct CaretKey {
295 field: WidgetId,
296 engaged: bool,
297 text: String,
298 cursor: usize,
299 selection: Option<usize>,
300 preedit: String,
301 preedit_cursor: usize,
302}
303
304#[derive(Clone, Debug, PartialEq, Eq)]
306struct Focused {
307 id: WidgetId,
308 field: bool,
310}
311
312struct PerWindowInput {
313 coord: InputCoordinator,
314 states: uzor::app_context::StateRegistry,
318 cook: CookState,
319 pointer: PointerAccum,
320 capture: Option<Capture>,
321 scopes: Vec<FocusScope>,
322 focus: Option<Focused>,
323 hover: Option<WidgetId>,
324 pressed: Option<WidgetId>,
325 clicked: SmallVec<[(WidgetId, u8); 2]>,
326 os_focused: bool,
327 caret: Option<CaretKey>,
328 blink_anchor_ms: u64,
329 caret_visible: bool,
330 armed: Option<Seconds>,
331 ime_area: Option<Rect>,
332 ime_allowed: bool,
333 pending_paste: Option<(Ticket, Option<WidgetId>)>,
336 offer: Option<String>,
338 selectables: HashMap<WidgetId, SelectableText>,
342 sel_alias: HashMap<WidgetId, WidgetId>,
344 reported: Selectables,
345 selections: Vec<(WidgetId, TextSelection)>,
346 press_sel: Option<PressSel>,
347 drag_ended: bool,
348 escalation: Option<(WidgetId, EscLevel)>,
349 focus_visible: bool,
352 key_clicks: Vec<WidgetId>,
355 space_armed: Option<WidgetId>,
357}
358
359fn activation(kind: Option<WidgetKind>) -> (bool, bool) {
363 use WidgetKind as K;
364 match kind {
365 Some(K::Link) => (true, false),
366 Some(K::Checkbox | K::Radio | K::Toggle) => (false, true),
367 Some(K::Button | K::CloseButton | K::ChromeTab | K::DropdownTrigger | K::Item | K::ColorSwatch | K::Custom) | None => (true, true),
368 Some(_) => (false, false),
369 }
370}
371
372impl PerWindowInput {
373 fn new() -> Self {
374 Self {
375 coord: InputCoordinator::new(),
376 states: uzor::app_context::StateRegistry::new(),
377 cook: CookState::default(),
378 pointer: PointerAccum::default(),
379 capture: None,
380 scopes: Vec::new(),
381 focus: None,
382 hover: None,
383 pressed: None,
384 clicked: SmallVec::new(),
385 os_focused: true,
388 caret: None,
389 blink_anchor_ms: 0,
390 caret_visible: false,
391 armed: None,
392 ime_area: None,
393 ime_allowed: false,
394 pending_paste: None,
395 offer: None,
396 selectables: HashMap::new(),
397 sel_alias: HashMap::new(),
398 reported: Selectables::default(),
399 selections: Vec::new(),
400 press_sel: None,
401 drag_ended: false,
402 escalation: None,
403 focus_visible: false,
404 key_clicks: Vec::new(),
405 space_armed: None,
406 }
407 }
408
409 fn allowed(&self, id: &WidgetId) -> bool {
414 self.scopes.last().is_none_or(|s| s.members.contains(id))
415 }
416
417 fn focus_raw(&mut self, id: WidgetId) {
420 let field = self.coord.text_fields().has_field(&id);
421 if field && self.coord.text_fields().is_focused(&id) {
422 self.coord.set_focus(id.clone());
426 } else if field {
427 self.coord.focus_text_field(&id);
428 } else {
429 self.coord.set_focus(id.clone());
430 }
431 self.focus = Some(Focused { id, field });
432 }
433
434 fn clear_raw(&mut self) -> bool {
435 let had = self.focus.is_some() || self.coord.text_fields().focused().is_some();
436 self.coord.clear_focus();
437 self.focus = None;
438 had
439 }
440
441 fn focused_id(&self) -> Option<&WidgetId> {
442 self.focus.as_ref().map(|f| &f.id)
443 }
444
445 fn scoped_candidates(&self) -> Option<Vec<WidgetId>> {
448 let scope = self.scopes.last()?;
449 Some(
450 scope
451 .members
452 .iter()
453 .filter(|m| self.coord.widget_rect(m).is_some() && self.coord.tab_index(m) >= 0)
454 .cloned()
455 .collect(),
456 )
457 }
458
459 fn cycle(&mut self, forward: bool) -> Option<bool> {
461 let before = self.focus.clone();
462 match self.scoped_candidates() {
463 Some(list) => {
464 if list.is_empty() {
465 return None;
466 }
467 let n = list.len();
468 let at = self
469 .focused_id()
470 .and_then(|f| list.iter().position(|m| m == f));
471 let next = match (at, forward) {
472 (Some(i), true) => (i + 1) % n,
473 (None, true) => 0,
474 (Some(i), false) => (i + n - 1) % n,
475 (None, false) => n - 1,
476 };
477 if self.focused_id() != Some(&list[next]) {
478 self.focus_raw(list[next].clone());
479 }
480 }
481 None => {
482 if forward {
483 self.coord.focus_next();
484 } else {
485 self.coord.focus_prev();
486 }
487 let target = self.coord.focused_widget().cloned()?;
488 if self.focused_id() != Some(&target) || !self.store_matches_focus() {
489 self.focus_raw(target);
490 }
491 }
492 }
493 Some(self.focus != before)
494 }
495
496 fn store_matches_focus(&self) -> bool {
498 let store = self.coord.text_fields().focused();
499 match &self.focus {
500 Some(f) if f.field => store == Some(&f.id),
501 _ => store.is_none(),
502 }
503 }
504
505 fn focus_op(
506 &mut self,
507 win: WindowId,
508 op: FocusOp,
509 next_scope: &mut u64,
510 fx: &mut InputEffects,
511 ) -> bool {
512 match op {
513 FocusOp::Set(id) => {
514 if !self.allowed(&id) || self.focused_id() == Some(&id) {
515 return false;
516 }
517 self.focus_raw(id);
518 true
519 }
520 FocusOp::Clear => self.clear_raw(),
521 FocusOp::Next => self.cycle(true).unwrap_or(false),
522 FocusOp::Prev => self.cycle(false).unwrap_or(false),
523 FocusOp::PushScope { owner, members } => {
524 if self.scopes.iter().any(|s| s.owner == owner) {
525 return self.set_members(&owner, members);
526 }
527 let saved = self.focus.as_ref().map(|f| SavedFocus {
528 engaged: f.field && self.coord.text_fields().is_engaged(&f.id),
529 id: f.id.clone(),
530 });
531 self.clear_raw();
532 self.scopes.push(FocusScope {
533 owner: owner.clone(),
534 members,
535 saved,
536 });
537 *next_scope += 1;
538 fx.push(InputEffect::ScopePushed {
539 win,
540 owner,
541 scope: ScopeId(*next_scope),
542 });
543 true
544 }
545 FocusOp::SetMembers { owner, members } => self.set_members(&owner, members),
546 FocusOp::PopScope { owner, restore } => self.pop_scope(&owner, restore),
547 }
548 }
549
550 fn set_members(&mut self, owner: &ScopeOwner, members: Vec<WidgetId>) -> bool {
551 let Some(i) = self.scopes.iter().position(|s| &s.owner == owner) else {
552 return false;
553 };
554 if self.scopes[i].members == members {
555 return false;
556 }
557 self.scopes[i].members = members;
558 let active = i + 1 == self.scopes.len();
559 if active {
560 if let Some(f) = self.focused_id().cloned() {
561 if !self.allowed(&f) {
562 self.clear_raw();
563 }
564 }
565 }
566 true
567 }
568
569 fn pop_scope(&mut self, owner: &ScopeOwner, restore: bool) -> bool {
570 let Some(i) = self.scopes.iter().position(|s| &s.owner == owner) else {
571 return false;
572 };
573 let scope = self.scopes.remove(i);
574 if i < self.scopes.len() {
575 self.scopes[i].saved = scope.saved;
578 return true;
579 }
580 self.clear_raw();
581 if let (true, Some(saved)) = (restore, scope.saved) {
582 if self.allowed(&saved.id) {
583 self.focus_raw(saved.id.clone());
584 if saved.engaged {
585 self.coord.text_fields_mut().engage(&saved.id);
586 }
587 }
588 }
589 true
590 }
591
592 fn reconcile_focus(&mut self) -> bool {
595 let store = self.coord.text_fields().focused().cloned();
596 match (store, self.focus.clone()) {
597 (Some(s), Some(f)) if f.field && s == f.id => false,
598 (Some(s), _) if self.allowed(&s) => {
599 self.coord.set_focus(s.clone());
600 self.focus = Some(Focused { id: s, field: true });
601 true
602 }
603 (Some(_), prev) => {
604 self.coord.text_fields_mut().blur();
606 if let Some(f) = prev.filter(|f| f.field) {
607 let engaged = self.coord.text_fields().is_engaged(&f.id);
608 self.coord.focus_text_field(&f.id);
609 if engaged {
610 self.coord.text_fields_mut().engage(&f.id);
611 }
612 }
613 false
614 }
615 (None, Some(f)) if f.field => {
616 self.coord.clear_focus();
618 self.focus = None;
619 true
620 }
621 (None, _) => false,
622 }
623 }
624
625 fn set_capture(&mut self, capture: Option<Capture>) -> bool {
628 if self.capture == capture {
629 return false;
630 }
631 if let Some(Capture::Widget(_)) = &self.capture {
632 self.coord.release_pointer();
633 }
634 if let Some(Capture::Widget(id)) = &capture {
635 self.coord.grab_pointer(id.clone());
636 }
637 self.capture = capture;
638 true
639 }
640
641 fn cook(&mut self, win: WindowId, now: Seconds, input: PointerInput) -> (bool, CookedPointer) {
642 let t = now.get();
643 let target = match &self.capture {
644 Some(c) => PointerTarget::Captured(c.clone()),
645 None => PointerTarget::HitTest,
646 };
647 let mut drag_started = false;
648 let mut ended_drag = false;
649 let mut changed = false;
650 if matches!(input, PointerInput::Down { .. }) && self.focus_visible {
653 self.focus_visible = false;
654 changed = true;
655 }
656 match input {
657 PointerInput::Moved { pos, mods } => {
658 self.pointer.pos = Some((pos.x, pos.y));
659 self.pointer.mods = mods;
660 drag_started = self.cook.motion(pos.x, pos.y).drag_started;
661 }
662 PointerInput::Down { pos, button, mods } => {
663 self.pointer.pos = Some((pos.x, pos.y));
664 self.pointer.mods = mods;
665 if self.cook.press_origin.is_none() {
667 self.cook.press(pos.x, pos.y, button, t);
668 }
669 }
670 PointerInput::Up { pos, button, mods } => {
671 self.pointer.pos = Some((pos.x, pos.y));
672 self.pointer.mods = mods;
673 if self.cook.press_origin.map(|o| o.button) == Some(button) {
674 ended_drag = self.cook.release(pos.x, pos.y, button, t);
675 self.drag_ended |= ended_drag;
676 changed = self.set_capture(None);
677 }
678 }
679 PointerInput::Entered | PointerInput::RawDelta { .. } => {}
680 PointerInput::Left => self.pointer.pos = None,
681 PointerInput::Cancelled => {
682 if self.coord.text_fields().drag_active() {
684 self.coord.text_fields_mut().on_drag_end();
685 }
686 self.cook.press_origin = None;
687 self.cook.drag_armed = false;
688 self.pointer.button_down = None;
689 changed = self.set_capture(None);
690 changed |= self.pressed.take().is_some();
691 self.press_sel = None;
692 self.drag_ended = false;
693 }
694 }
695 if drag_started {
699 let grab = self
700 .pressed
701 .clone()
702 .filter(|id| self.coord.widget_sense(id).is_some_and(|s| s.drag));
703 if let Some(id) = grab {
704 changed = self.set_capture(Some(Capture::Widget(id)));
705 }
706 }
707 let cooked = CookedPointer {
708 win,
709 input,
710 click_count: self.cook.click_count,
711 drag_armed: self.cook.drag_armed,
712 drag_started,
713 ended_drag,
714 target,
715 };
716 (changed, cooked)
717 }
718
719 fn content_target(&self, pos: Option<(f64, f64)>) -> Option<WidgetId> {
722 if let Some(Capture::Widget(id)) = &self.capture {
723 return Some(id.clone());
724 }
725 let (x, y) = pos?;
726 self.coord.hit_test_now(x, y)
727 }
728
729 fn deliver(
730 &mut self,
731 win: WindowId,
732 input: PointerInput,
733 fx: &mut InputEffects,
734 ) -> (bool, Option<WidgetId>) {
735 match input {
736 PointerInput::Moved { pos, .. } => {
737 self.pointer.pos = Some((pos.x, pos.y));
738 let target = self.content_target(self.pointer.pos);
742 let mut changed = self.pointer.button_down.is_some() || target != self.hover;
743 if self.pointer.button_down == Some(MouseButton::Left)
746 && self.cook.drag_armed
747 && self.coord.text_fields().drag_active()
748 {
749 self.coord.text_fields_mut().on_drag_move_xy(pos.x, pos.y);
750 changed = true;
751 }
752 (changed, target)
753 }
754 PointerInput::Down { pos, button, .. } => {
755 self.pointer.pos = Some((pos.x, pos.y));
756 self.pointer.button_down = Some(button);
757 self.pointer.clicked = None;
761 let target = self.content_target(self.pointer.pos);
762 let changed = self.pressed != target;
763 self.pressed.clone_from(&target);
764 let t = target.as_ref().map(|t| self.sel_owner(t));
765 let sel_changed = self.press_down(win, t.as_ref(), pos.x, pos.y, fx);
766 if button == MouseButton::Left {
767 self.arm_text_drag(target.as_ref(), pos.x, pos.y);
768 } else if self.coord.text_fields().drag_active() {
769 self.coord.text_fields_mut().on_drag_end();
770 }
771 let blurred = self.blur_text_on_outside_press(target.as_ref());
772 (changed | sel_changed | blurred, target)
773 }
774 PointerInput::Up { pos, button, .. } => {
775 self.pointer.pos = Some((pos.x, pos.y));
776 self.pointer.button_down = None;
777 self.pointer.clicked = Some(button);
778 if button == MouseButton::Right {
779 self.pointer.context = Some((pos.x, pos.y));
780 }
781 let target = self.content_target(self.pointer.pos);
782 let _ = self.pressed.take();
783 let t = target.as_ref().map(|t| self.sel_owner(t));
784 let _ = self.release_select(win, t.as_ref(), fx);
785 if button == MouseButton::Left && self.coord.text_fields().drag_active() {
789 self.coord.text_fields_mut().on_drag_end();
790 }
791 (true, target)
794 }
795 PointerInput::Entered
796 | PointerInput::Left
797 | PointerInput::Cancelled
798 | PointerInput::RawDelta { .. } => (false, None),
799 }
800 }
801
802 fn arm_text_drag(&mut self, target: Option<&WidgetId>, x: f64, y: f64) {
808 let field = match target {
809 Some(id)
810 if self.coord.widget_sense(id).is_some_and(|s| s.text)
811 && self.coord.text_fields().has_field(id) =>
812 {
813 Some(id.clone())
814 }
815 _ => None,
816 };
817 if let Some(id) = field {
818 if self.cook.click_count <= 1 {
819 self.coord.text_fields_mut().begin_drag_at_xy(id, x, y);
820 return;
821 }
822 }
823 if self.coord.text_fields().drag_active() {
824 self.coord.text_fields_mut().on_drag_end();
825 }
826 }
827
828 fn blur_text_on_outside_press(&mut self, target: Option<&WidgetId>) -> bool {
832 let on_field = target.is_some_and(|id| {
833 self.coord.text_fields().has_field(id)
834 && self.coord.widget_sense(id).is_some_and(|s| s.text)
835 });
836 if on_field || self.coord.text_fields().focused().is_none() {
837 return false;
838 }
839 self.coord.clear_focus();
840 if self.focus.as_ref().is_some_and(|f| f.field) {
841 self.focus = None;
842 }
843 true
844 }
845
846 fn release_select(
850 &mut self,
851 win: WindowId,
852 target: Option<&WidgetId>,
853 fx: &mut InputEffects,
854 ) -> bool {
855 if self.drag_ended {
856 return false;
857 }
858 let Some(p) = self.press_sel.clone() else {
859 return false;
860 };
861 if target != Some(&p.widget) {
862 return false;
863 }
864 let Some(st) = self.selectables.get(&p.widget) else {
865 return false;
866 };
867 let sel = TextSelection::for_click_count(&st.text, p.anchor, self.cook.click_count.max(1));
868 let changed = self.set_selection(win, &p.widget, sel, fx);
869 self.escalation = Some((p.widget, EscLevel::Widget));
870 changed
871 }
872
873 fn wheel(&mut self, input: WheelInput) -> Option<WidgetId> {
874 let (dx, dy) = match input.delta {
875 WheelDelta::Lines { x, y } => (x, y),
876 WheelDelta::Pixels { x, y } => {
877 self.pointer.scroll_precise = true;
878 (x / WHEEL_PIXELS_PER_LINE, y / WHEEL_PIXELS_PER_LINE)
879 }
880 };
881 self.pointer.pos = Some((input.pos.x, input.pos.y));
882 self.pointer.mods = input.mods;
883 self.pointer.scroll.0 += dx;
884 self.pointer.scroll.1 += dy;
885 if let Some(Capture::Widget(id)) = &self.capture {
886 return Some(id.clone());
887 }
888 self.coord.process_scroll(input.pos.x, input.pos.y)
889 }
890
891 fn sel_owner(&self, w: &WidgetId) -> WidgetId {
895 self.sel_alias.get(w).unwrap_or(w).clone()
896 }
897
898 fn sel_get(&self, widget: &WidgetId) -> Option<TextSelection> {
899 self.selections
900 .iter()
901 .find(|(w, _)| w == widget)
902 .map(|(_, s)| *s)
903 }
904
905 fn sel_set(&mut self, widget: WidgetId, sel: TextSelection) -> bool {
906 if let Some(slot) = self.selections.iter_mut().find(|(w, _)| *w == widget) {
907 if slot.1 == sel {
908 return false;
909 }
910 slot.1 = sel;
911 return true;
912 }
913 self.selections.push((widget, sel));
914 true
915 }
916
917 fn sel_remove(&mut self, widget: &WidgetId) -> bool {
918 let before = self.selections.len();
919 self.selections.retain(|(w, _)| w != widget);
920 self.selections.len() != before
921 }
922
923 fn set_selection(
925 &mut self,
926 win: WindowId,
927 widget: &WidgetId,
928 sel: TextSelection,
929 fx: &mut InputEffects,
930 ) -> bool {
931 if !self.sel_set(widget.clone(), sel) {
932 return false;
933 }
934 fx.push(InputEffect::InvalidateField {
935 win,
936 rect: self.coord.widget_rect(widget),
937 });
938 true
939 }
940
941 fn clear_selections(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
943 if self.selections.is_empty() {
944 return false;
945 }
946 for (w, _) in &self.selections {
947 fx.push(InputEffect::InvalidateField {
948 win,
949 rect: self.coord.widget_rect(w),
950 });
951 }
952 self.selections.clear();
953 self.escalation = None;
954 true
955 }
956
957 fn selectable_ids_by_row(&self) -> Vec<WidgetId> {
960 let mut ids: Vec<(f64, f64, WidgetId)> = self
961 .selectables
962 .keys()
963 .map(|w| {
964 let r = self
965 .coord
966 .widget_rect(w)
967 .unwrap_or_else(|| Rect::new(0.0, 0.0, 0.0, 0.0));
968 (r.y, r.x, w.clone())
969 })
970 .collect();
971 uzor::sort::sort_by(&mut ids, |a, b| a.0.total_cmp(&b.0).then_with(|| a.1.total_cmp(&b.1)));
972 ids.into_iter().map(|(_, _, w)| w).collect()
973 }
974
975 fn selected_text_concat(&self) -> Option<String> {
978 if self.selections.is_empty() {
979 return None;
980 }
981 let mut parts: Vec<String> = Vec::new();
982 for w in self.selectable_ids_by_row() {
983 if let (Some(sel), Some(st)) = (self.sel_get(&w), self.selectables.get(&w)) {
984 let s = sel.selected_text(&st.text);
985 if !s.is_empty() {
986 parts.push(s.to_owned());
987 }
988 }
989 }
990 if parts.is_empty() {
991 None
992 } else {
993 Some(parts.join("\n"))
994 }
995 }
996
997 fn nearest_panel_rect(&self, widget: &WidgetId) -> Option<Rect> {
1000 let mut cur = self.coord.widget_parent(widget);
1001 while let Some(p) = cur {
1002 if matches!(
1003 self.coord.widget_kind(&p),
1004 Some(WidgetKind::Panel | WidgetKind::BlackboxPanel)
1005 ) {
1006 return self.coord.widget_rect(&p);
1007 }
1008 cur = self.coord.widget_parent(&p);
1009 }
1010 None
1011 }
1012
1013 fn select_in_rect(&mut self, win: WindowId, rect: &Rect, fx: &mut InputEffects) -> bool {
1015 let mut changed = false;
1016 for w in self.selectable_ids_by_row() {
1017 if let Some(r) = self.coord.widget_rect(&w) {
1018 let inside = r.x >= rect.x
1019 && r.y >= rect.y
1020 && r.x + r.width <= rect.x + rect.width
1021 && r.y + r.height <= rect.y + rect.height;
1022 if inside {
1023 if let Some(st) = self.selectables.get(&w) {
1024 let sel = TextSelection::all(&st.text);
1025 changed |= self.set_selection(win, &w, sel, fx);
1026 }
1027 }
1028 }
1029 }
1030 changed
1031 }
1032
1033 fn select_everything(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
1035 let mut changed = false;
1036 for w in self.selectable_ids_by_row() {
1037 if let Some(st) = self.selectables.get(&w) {
1038 let sel = TextSelection::all(&st.text);
1039 changed |= self.set_selection(win, &w, sel, fx);
1040 }
1041 }
1042 changed
1043 }
1044
1045 fn press_down(
1048 &mut self,
1049 win: WindowId,
1050 target: Option<&WidgetId>,
1051 x: f64,
1052 y: f64,
1053 fx: &mut InputEffects,
1054 ) -> bool {
1055 let mut changed = false;
1056 if !target.is_some_and(|t| self.sel_get(t).is_some()) {
1057 changed |= self.clear_selections(win, fx);
1058 }
1059 self.press_sel = None;
1060 if let Some(t) = target {
1061 if let Some(st) = self.selectables.get(t) {
1062 let anchor = char_at_point(&st.lines, x, y);
1063 self.press_sel = Some(PressSel {
1064 widget: t.clone(),
1065 anchor,
1066 });
1067 }
1068 }
1069 changed
1070 }
1071
1072 fn selection_frame(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
1075 let mut changed = false;
1076
1077 if let Some(p) = self.press_sel.clone() {
1081 if self.cook.drag_armed || self.drag_ended {
1082 if let (Some(st), Some((x, y))) =
1083 (self.selectables.get(&p.widget), self.pointer.pos)
1084 {
1085 let sel = TextSelection::new(p.anchor, char_at_point(&st.lines, x, y));
1086 changed |= self.set_selection(win, &p.widget, sel, fx);
1087 }
1088 }
1089 }
1090
1091 if self.pointer.button_down.is_none() {
1097 self.press_sel = None;
1098 self.drag_ended = false;
1099 }
1100
1101 let fresh = std::mem::take(&mut self.reported);
1104 let gone: Vec<WidgetId> = self
1105 .selections
1106 .iter()
1107 .map(|(w, _)| w.clone())
1108 .filter(|w| !fresh.contains_key(w))
1109 .collect();
1110 if !gone.is_empty() {
1111 for w in &gone {
1112 fx.push(InputEffect::InvalidateField {
1113 win,
1114 rect: self.coord.widget_rect(w),
1115 });
1116 self.sel_remove(w);
1117 }
1118 if let Some((w, _)) = &self.escalation {
1119 if gone.contains(w) {
1120 self.escalation = None;
1121 }
1122 }
1123 changed = true;
1124 }
1125 self.selectables = fresh.0;
1126 self.sel_alias = fresh.1;
1127
1128 changed
1129 }
1130
1131 fn ctrl_a(&mut self, win: WindowId, fx: &mut InputEffects) -> Option<bool> {
1135 if let Some((w, level)) = self.escalation.clone() {
1136 let next = match level {
1137 EscLevel::Widget => match self.nearest_panel_rect(&w) {
1138 Some(rect) => {
1139 self.select_in_rect(win, &rect, fx);
1140 EscLevel::Panel
1141 }
1142 None => {
1143 self.select_everything(win, fx);
1144 EscLevel::Window
1145 }
1146 },
1147 EscLevel::Panel => {
1148 self.select_everything(win, fx);
1149 EscLevel::Window
1150 }
1151 EscLevel::Window => return Some(false),
1152 };
1153 self.escalation = Some((w, next));
1154 return Some(true);
1155 }
1156 let start = self
1158 .hover
1159 .clone()
1160 .filter(|h| self.selectables.contains_key(h))
1161 .or_else(|| (self.selections.len() == 1).then(|| self.selections[0].0.clone()));
1162 let w = start?;
1163 let st = self.selectables.get(&w)?;
1164 let sel = TextSelection::all(&st.text);
1165 let changed = self.set_selection(win, &w, sel, fx);
1166 self.escalation = Some((w, EscLevel::Widget));
1167 Some(changed)
1168 }
1169
1170 fn begin_frame(&mut self, now: Seconds) -> bool {
1173 let mut state = InputState::new();
1174 state.pointer.pos = self.pointer.pos;
1175 state.pointer.prev_pos = self.pointer.prev_pos;
1176 state.pointer.button_down = self.pointer.button_down;
1177 state.pointer.clicked = self.pointer.clicked.take();
1178 state.modifiers = self.pointer.mods;
1179 state.scroll_delta = std::mem::take(&mut self.pointer.scroll);
1180 self.pointer.scroll_precise = false;
1181 self.pointer.scroll_touch = false;
1182 self.pointer.context = None;
1183 state.time = now.get();
1184 self.pointer.prev_pos = self.pointer.pos;
1185 self.coord.begin_frame(state);
1186 let had_clicks = !self.clicked.is_empty();
1187 self.clicked.clear();
1188 had_clicks
1189 }
1190
1191 fn end_frame(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
1192 let mut hover = None;
1193 let mut clicked = SmallVec::new();
1194 for (id, r) in self.coord.end_frame() {
1195 if r.hovered {
1196 hover = Some(id.clone());
1197 }
1198 if r.clicked {
1199 let count = if r.triple_clicked {
1200 3
1201 } else if r.double_clicked {
1202 2
1203 } else {
1204 1
1205 };
1206 clicked.push((id, count));
1207 }
1208 }
1209 for w in self.key_clicks.drain(..) {
1210 if !clicked.iter().any(|(c, _)| *c == w) {
1211 clicked.push((w, 1));
1212 }
1213 }
1214 let mut changed = hover != self.hover || clicked != self.clicked;
1215 self.hover = hover;
1216 self.clicked = clicked.clone();
1217 let clicked_focus = clicked
1220 .iter()
1221 .map(|(id, _)| id.clone())
1222 .find(|id| self.allowed(id) && self.coord.widget_sense(id).is_some_and(|s| s.focus));
1223 if let Some(id) = clicked_focus {
1224 if self.focused_id() != Some(&id) {
1225 self.focus_raw(id);
1226 changed = true;
1227 }
1228 }
1229 changed |= self.selection_frame(win, fx);
1230 changed |= self.reconcile_focus();
1231 changed
1232 }
1233
1234 fn text_focus(&self) -> Option<WidgetId> {
1238 let f = self.focus.as_ref().filter(|f| f.field)?;
1239 self.coord
1240 .text_fields()
1241 .is_focused(&f.id)
1242 .then(|| f.id.clone())
1243 }
1244
1245 fn key(
1246 &mut self,
1247 win: WindowId,
1248 input: KeyInput,
1249 next_ticket: &mut u64,
1250 fx: &mut InputEffects,
1251 ) -> bool {
1252 let m = input.mods;
1253 if input.code == KeyCode::Space && input.state == KeyState::Up {
1254 if let Some(w) = self.space_armed.take() {
1255 if self.focused_id() == Some(&w) {
1256 self.key_clicks.push(w);
1257 return true;
1258 }
1259 }
1260 }
1261 if input.state == KeyState::Up {
1262 fx.push(InputEffect::KeyPassed { win, key: input });
1263 return false;
1264 }
1265 if input.code != KeyCode::Unknown {
1266 self.focus_visible = true;
1267 }
1268 if matches!(input.code, KeyCode::Enter | KeyCode::Space) && !(m.ctrl || m.alt || m.meta) {
1270 if let Some(f) = self.focus.as_ref().filter(|f| !f.field).map(|f| f.id.clone()) {
1271 if self.coord.widget_sense(&f).is_some_and(|s| s.click) {
1272 let (enter, space) = activation(self.coord.widget_kind(&f));
1273 if input.code == KeyCode::Enter && enter {
1274 self.key_clicks.push(f);
1275 return true;
1276 }
1277 if input.code == KeyCode::Space && space {
1278 self.space_armed = Some(f);
1279 return false;
1280 }
1281 }
1282 }
1283 }
1284 if input.code == KeyCode::Tab && !(m.ctrl || m.alt || m.meta) {
1285 return match self.cycle(!m.shift) {
1286 Some(changed) => changed,
1287 None => {
1288 fx.push(InputEffect::KeyPassed { win, key: input });
1289 false
1290 }
1291 };
1292 }
1293 let field = self.text_focus();
1294 let mut edit = editing_chord(&input);
1295 if edit.is_none() && matches!(input.code, KeyCode::ArrowUp | KeyCode::ArrowDown) && !(m.ctrl || m.alt || m.meta) {
1297 if field.as_ref().is_some_and(|f| self.coord.text_fields().has_lines(f)) {
1298 edit = Some(Edit::Key(if input.code == KeyCode::ArrowUp { KeyPress::ArrowUp } else { KeyPress::ArrowDown }));
1299 }
1300 }
1301 let (field, edit) = match (field, edit) {
1302 (Some(f), Some(e)) => (f, e),
1303 (None, Some(Edit::Copy)) => {
1306 if let Some(text) = self.selected_text_concat() {
1307 fx.push(InputEffect::CopyText { win, text });
1308 } else {
1309 if let Some(text) = self.offer.clone() {
1312 fx.push(InputEffect::CopyText { win, text });
1313 }
1314 fx.push(InputEffect::KeyPassed { win, key: input });
1315 }
1316 return false;
1317 }
1318 (None, Some(Edit::Cut)) => {
1319 if let Some(text) = self.offer.clone() {
1320 fx.push(InputEffect::CopyText { win, text });
1321 }
1322 fx.push(InputEffect::KeyPassed { win, key: input });
1323 return false;
1324 }
1325 (None, Some(Edit::Paste)) => {
1326 let ticket = Ticket(INPUT_TICKET_BASE.saturating_add(*next_ticket));
1330 *next_ticket = next_ticket.saturating_add(1);
1331 self.pending_paste = Some((ticket, None));
1332 fx.push(InputEffect::NeedPaste { win, ticket });
1333 return false;
1334 }
1335 (None, Some(Edit::Key(KeyPress::SelectAll)))
1336 if self.focus.as_ref().is_some_and(|f| !f.field && self.coord.widget_kind(&f.id).is_some_and(|k| k.is_blackbox())) =>
1337 {
1338 fx.push(InputEffect::KeyPassed { win, key: input });
1340 return false;
1341 }
1342 (None, Some(Edit::Key(KeyPress::SelectAll))) => {
1343 return match self.ctrl_a(win, fx) {
1345 Some(changed) => changed,
1346 None => {
1347 fx.push(InputEffect::KeyPassed { win, key: input });
1348 false
1349 }
1350 };
1351 }
1352 _ => {
1353 fx.push(InputEffect::KeyPassed { win, key: input });
1354 return false;
1355 }
1356 };
1357 let text_before = self.coord.text_fields().text(&field).to_owned();
1358 let changed_text = |action: &TextAction| matches!(action, TextAction::TextChanged(_));
1359 let mut changed = false;
1360 let multiline = self.coord.text_fields().field_state(&field).is_some_and(|s| s.config.multiline);
1361 let edit = match edit {
1362 Edit::Newline if multiline => Edit::Key(KeyPress::Paste("\n".into())),
1363 Edit::Newline => Edit::Submit,
1364 e => e,
1365 };
1366 match edit {
1367 Edit::Newline => {}
1368 Edit::Key(kp) => changed = changed_text(&self.coord.on_key(kp)),
1369 Edit::Char(c) => changed = changed_text(&self.coord.on_char(c)),
1370 Edit::Text(s) => {
1371 for c in s.chars() {
1372 changed |= changed_text(&self.coord.on_char(c));
1373 }
1374 }
1375 Edit::Submit => {
1376 if let TextAction::Commit(_) = self.coord.on_char('\r') {
1377 fx.push(InputEffect::Text(TextIntent::Submitted {
1378 win,
1379 field: field.clone(),
1380 }));
1381 }
1382 }
1383 Edit::Copy => {
1384 let own = if self.masked(&field) { None } else { self.coord.text_fields().copy_selection().filter(|t| !t.is_empty()) };
1387 if let Some(text) = own.or_else(|| self.selected_text_concat()) {
1388 fx.push(InputEffect::CopyText { win, text });
1389 }
1390 }
1391 Edit::Cut => {
1392 if !self.masked(&field) {
1393 if let Some(text) = self.coord.text_fields_mut().cut_selection(&field) {
1394 fx.push(InputEffect::CopyText { win, text });
1395 }
1396 }
1397 }
1398 Edit::Paste => {
1399 let ticket = Ticket(INPUT_TICKET_BASE.saturating_add(*next_ticket));
1400 *next_ticket = next_ticket.saturating_add(1);
1401 self.pending_paste = Some((ticket, Some(field.clone())));
1402 fx.push(InputEffect::NeedPaste { win, ticket });
1403 }
1404 }
1405 if changed || self.coord.text_fields().text(&field) != text_before {
1406 fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
1407 }
1408 false
1410 }
1411
1412 fn masked(&self, field: &WidgetId) -> bool {
1413 self.coord
1414 .text_fields()
1415 .field_state(field)
1416 .is_some_and(|s| s.config.masked)
1417 }
1418
1419 fn ime(&mut self, win: WindowId, input: ImeInput, fx: &mut InputEffects) {
1420 let Some(field) = self.text_focus() else {
1421 return;
1422 };
1423 match input {
1424 ImeInput::Enabled => {}
1425 ImeInput::Preedit { text, cursor } => {
1426 let chars = |b: usize| text.get(..b).map(|s| s.chars().count());
1427 let at = cursor
1428 .and_then(|(b, _)| chars(b))
1429 .unwrap_or_else(|| text.chars().count());
1430 self.coord.text_fields_mut().preedit_set(&field, text, at);
1431 }
1432 ImeInput::Commit(text) => {
1433 let action = self.coord.text_fields_mut().ime_commit(&field, text);
1434 if let TextAction::TextChanged(_) = action {
1435 fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
1436 }
1437 }
1438 ImeInput::Disabled => {
1439 self.coord
1440 .text_fields_mut()
1441 .preedit_set(&field, String::new(), 0);
1442 }
1443 }
1444 }
1445
1446 fn clipboard(&mut self, win: WindowId, result: ClipboardResult, fx: &mut InputEffects) {
1447 let Some((ticket, field)) = self.pending_paste.clone() else {
1448 return;
1449 };
1450 if ticket != result.ticket {
1451 return;
1452 }
1453 self.pending_paste = None;
1454 let Some(text) = result.text.filter(|t| !t.is_empty()) else {
1455 return;
1456 };
1457 let Some(field) = field else {
1458 fx.push(InputEffect::Pasted { win, text });
1459 return;
1460 };
1461 let Some(focused) = self.text_focus() else {
1462 return;
1463 };
1464 if focused != field {
1465 return;
1466 }
1467 if let TextAction::TextChanged(_) = self.coord.on_key(KeyPress::Paste(text)) {
1468 fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
1469 }
1470 }
1471
1472 fn paste(&mut self, win: WindowId, text: String, fx: &mut InputEffects) {
1476 self.pending_paste = None;
1477 if text.is_empty() {
1478 return;
1479 }
1480 match self.text_focus() {
1481 Some(field) => {
1482 if let TextAction::TextChanged(_) = self.coord.on_key(KeyPress::Paste(text)) {
1483 fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
1484 }
1485 }
1486 None => fx.push(InputEffect::Pasted { win, text }),
1487 }
1488 }
1489
1490 fn caret_key(&self) -> Option<CaretKey> {
1493 let store = self.coord.text_fields();
1494 let field = store.focused()?;
1495 let s = store.field_state(field)?;
1496 Some(CaretKey {
1497 field: field.clone(),
1498 engaged: s.engaged,
1499 text: s.text.clone(),
1500 cursor: s.cursor,
1501 selection: s.selection_start,
1502 preedit: s.preedit.clone(),
1503 preedit_cursor: s.preedit_cursor,
1504 })
1505 }
1506
1507 fn field_rect(&self, field: &WidgetId) -> Option<Rect> {
1508 let (x, y, w, h) = self.coord.text_fields().field_state(field)?.last_rect?;
1509 Some(Rect::new(x, y, w, h))
1510 }
1511
1512 fn caret_rect(&self, field: &WidgetId) -> Option<Rect> {
1514 let s = self.coord.text_fields().field_state(field)?;
1515 let (x, y, _, h) = s.last_rect?;
1516 let cx = s.last_char_positions.get(s.cursor).copied().unwrap_or(x);
1517 Some(Rect::new(cx, y, 1.0, h))
1518 }
1519
1520 fn settle(&mut self, win: WindowId, now: Seconds, fx: &mut InputEffects) -> bool {
1523 let now_ms = millis(now);
1524 let key = self.caret_key();
1525 let key_changed = key != self.caret;
1526 if key_changed {
1527 if let Some(old) = &self.caret {
1528 if key.as_ref().map(|k| &k.field) != Some(&old.field) {
1529 fx.push(InputEffect::InvalidateField {
1530 win,
1531 rect: self.field_rect(&old.field),
1532 });
1533 }
1534 }
1535 self.caret = key;
1536 self.blink_anchor_ms = now_ms;
1537 }
1538 self.coord
1539 .text_fields_mut()
1540 .set_blink_time(self.blink_anchor_ms);
1541 let active = self.os_focused && self.caret.as_ref().is_some_and(|k| k.engaged);
1542 let visible = active && self.coord.text_fields().cursor_visible(now_ms);
1543 let visible_changed = visible != self.caret_visible;
1544 self.caret_visible = visible;
1545 if key_changed || visible_changed {
1546 if let Some(k) = &self.caret {
1547 fx.push(InputEffect::InvalidateField {
1548 win,
1549 rect: self.field_rect(&k.field),
1550 });
1551 }
1552 }
1553 let at = active.then(|| next_blink_edge(self.blink_anchor_ms, now_ms));
1554 if at != self.armed {
1555 self.armed = at;
1556 fx.push(InputEffect::CaretDeadline { win, at });
1557 }
1558 let field = self.caret.as_ref().map(|k| k.field.clone());
1559 let allowed = field.is_some();
1560 if allowed != self.ime_allowed {
1561 self.ime_allowed = allowed;
1562 fx.push(InputEffect::ImeAllowed { win, allowed });
1563 }
1564 let area = field.and_then(|f| self.caret_rect(&f));
1565 if area != self.ime_area {
1566 self.ime_area = area;
1567 if let Some(rect) = area {
1568 fx.push(InputEffect::ImeArea { win, rect });
1569 }
1570 }
1571 key_changed || visible_changed
1572 }
1573}
1574
1575fn millis(t: Seconds) -> u64 {
1578 (t.get() * 1000.0).round().max(0.0) as u64
1580}
1581
1582fn next_blink_edge(anchor_ms: u64, now_ms: u64) -> Seconds {
1585 let phases = now_ms.saturating_sub(anchor_ms) / CARET_BLINK_MS + 1;
1586 let edge = anchor_ms.saturating_add(phases.saturating_mul(CARET_BLINK_MS));
1587 Seconds(edge as f64 / 1000.0)
1588}
1589
1590#[derive(Clone, Debug, PartialEq, Eq)]
1592enum Edit {
1593 Key(KeyPress),
1594 Char(char),
1595 Text(String),
1596 Submit,
1597 Newline,
1599 Copy,
1600 Cut,
1601 Paste,
1602}
1603
1604fn editing_chord(input: &KeyInput) -> Option<Edit> {
1607 let m = input.mods;
1608 let cmd = m.ctrl || m.meta;
1609 let edit = match input.code {
1610 KeyCode::A if cmd => Edit::Key(KeyPress::SelectAll),
1611 KeyCode::Z if cmd && m.shift => Edit::Key(KeyPress::Redo),
1612 KeyCode::Z if cmd => Edit::Key(KeyPress::Undo),
1613 KeyCode::Y if m.ctrl && !m.alt => Edit::Key(KeyPress::Redo),
1614 KeyCode::C if cmd => Edit::Copy,
1615 KeyCode::X if cmd => Edit::Cut,
1616 KeyCode::V if cmd => Edit::Paste,
1617 KeyCode::ArrowLeft if cmd => Edit::Key(KeyPress::WordLeft),
1618 KeyCode::ArrowRight if cmd => Edit::Key(KeyPress::WordRight),
1619 KeyCode::Backspace if cmd => Edit::Key(KeyPress::DeleteWordBack),
1620 KeyCode::Delete if cmd => Edit::Key(KeyPress::DeleteWordForward),
1621 KeyCode::ArrowLeft if m.shift => Edit::Key(KeyPress::ShiftLeft),
1622 KeyCode::ArrowRight if m.shift => Edit::Key(KeyPress::ShiftRight),
1623 KeyCode::Home if m.shift => Edit::Key(KeyPress::ShiftHome),
1624 KeyCode::End if m.shift => Edit::Key(KeyPress::ShiftEnd),
1625 KeyCode::ArrowLeft => Edit::Key(KeyPress::ArrowLeft),
1626 KeyCode::ArrowRight => Edit::Key(KeyPress::ArrowRight),
1627 KeyCode::Home => Edit::Key(KeyPress::Home),
1628 KeyCode::End => Edit::Key(KeyPress::End),
1629 KeyCode::Backspace => Edit::Char('\x08'),
1630 KeyCode::Delete => Edit::Key(KeyPress::Delete),
1631 KeyCode::Enter if m.shift => Edit::Newline,
1632 KeyCode::Enter => Edit::Submit,
1633 _ if cmd && !(m.ctrl && m.alt) => return None,
1636 _ => {
1637 let text: String = input
1638 .text
1639 .as_deref()?
1640 .chars()
1641 .filter(|c| !c.is_control())
1642 .collect();
1643 if text.is_empty() {
1644 return None;
1645 }
1646 match text.chars().count() {
1647 1 => Edit::Char(text.chars().next()?),
1648 _ => Edit::Text(text),
1649 }
1650 }
1651 };
1652 Some(edit)
1653}
1654
1655#[derive(Default)]
1661pub struct InputEngine {
1662 windows: VecMap<WindowId, PerWindowInput>,
1663 next_scope: u64,
1664 next_ticket: u64,
1665 rev: Revision,
1666}
1667
1668impl fmt::Debug for InputEngine {
1669 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1670 f.debug_struct("InputEngine")
1671 .field("windows", &self.windows.keys().collect::<Vec<_>>())
1672 .field("rev", &self.rev)
1673 .finish()
1674 }
1675}
1676
1677impl InputEngine {
1678 pub fn new() -> Self {
1680 Self::default()
1681 }
1682
1683 pub fn apply(&mut self, op: InputOp) -> InputEffects {
1686 let mut fx = InputEffects::new();
1687 let Self {
1688 windows,
1689 next_scope,
1690 next_ticket,
1691 rev,
1692 } = self;
1693 let changed = match op {
1694 InputOp::Open(win) => match windows.entry(win) {
1695 crate::types::vecmap::Entry::Occupied(_) => false,
1696 crate::types::vecmap::Entry::Vacant(slot) => {
1697 slot.insert(PerWindowInput::new());
1698 true
1699 }
1700 },
1701 InputOp::Close(win) => windows.remove(&win).is_some(),
1702 InputOp::WindowFocus { win, focused, now } => match windows.get_mut(&win) {
1703 Some(w) => {
1704 w.os_focused = focused;
1705 w.settle(win, now, &mut fx)
1706 }
1707 None => false,
1708 },
1709 InputOp::Pointer { win, now, input } => match windows.get_mut(&win) {
1710 Some(w) => {
1711 let (changed, cooked) = w.cook(win, now, input);
1712 fx.push(InputEffect::Pointer(cooked));
1713 changed
1714 }
1715 None => false,
1716 },
1717 InputOp::Deliver { win, input } => match windows.get_mut(&win) {
1718 Some(w) => {
1719 let (changed, target) = w.deliver(win, input, &mut fx);
1720 fx.push(InputEffect::Content { win, target, changed });
1721 changed
1722 }
1723 None => false,
1724 },
1725 InputOp::Wheel { win, input, touch } => {
1726 if let Some(w) = windows.get_mut(&win) {
1727 w.pointer.scroll_touch |= touch;
1728 let target = w.wheel(input);
1729 let changed = target.is_some();
1730 fx.push(InputEffect::Content { win, target, changed });
1731 }
1732 false
1733 }
1734 InputOp::Key { win, now, input } => match windows.get_mut(&win) {
1735 Some(w) => {
1736 let changed = w.key(win, input, next_ticket, &mut fx);
1737 w.settle(win, now, &mut fx) | changed
1738 }
1739 None => false,
1740 },
1741 InputOp::Ime { win, now, input } => match windows.get_mut(&win) {
1742 Some(w) => {
1743 w.ime(win, input, &mut fx);
1744 w.settle(win, now, &mut fx)
1745 }
1746 None => false,
1747 },
1748 InputOp::Context { win, pos } => match windows.get_mut(&win) {
1749 Some(w) => {
1750 w.pointer.context = Some((pos.x, pos.y));
1751 true
1752 }
1753 None => false,
1754 },
1755 InputOp::Paste { win, now, text } => match windows.get_mut(&win) {
1756 Some(w) => {
1757 w.paste(win, text, &mut fx);
1758 w.settle(win, now, &mut fx)
1759 }
1760 None => false,
1761 },
1762 InputOp::Offer { win, text } => {
1763 if let Some(w) = windows.get_mut(&win) {
1764 w.offer = text;
1765 }
1766 false
1767 }
1768 InputOp::Clipboard { win, now, result } => match windows.get_mut(&win) {
1769 Some(w) => {
1770 w.clipboard(win, result, &mut fx);
1771 w.settle(win, now, &mut fx)
1772 }
1773 None => false,
1774 },
1775 InputOp::Focus { win, now, op } => match windows.get_mut(&win) {
1776 Some(w) => {
1777 let changed = w.focus_op(win, op, next_scope, &mut fx);
1778 w.settle(win, now, &mut fx) | changed
1779 }
1780 None => false,
1781 },
1782 InputOp::SetCapture { win, capture } => windows
1783 .get_mut(&win)
1784 .is_some_and(|w| w.set_capture(capture)),
1785 InputOp::BeginFrame { win, now } => {
1786 windows.get_mut(&win).is_some_and(|w| w.begin_frame(now))
1787 }
1788 InputOp::EndFrame { win, now } => match windows.get_mut(&win) {
1789 Some(w) => {
1790 let changed = w.end_frame(win, &mut fx);
1791 w.settle(win, now, &mut fx) | changed
1792 }
1793 None => false,
1794 },
1795 };
1796 if changed {
1797 rev.bump();
1798 }
1799 fx
1800 }
1801
1802 pub fn tick(&mut self, now: Seconds) -> InputEffects {
1807 let mut fx = InputEffects::new();
1808 let mut changed = false;
1809 for (win, w) in &mut self.windows {
1810 if w.armed.is_some_and(|at| at.get() <= now.get()) {
1811 changed |= w.settle(*win, now, &mut fx);
1812 }
1813 }
1814 if changed {
1815 self.rev.bump();
1816 }
1817 fx
1818 }
1819
1820 #[allow(dead_code)]
1827 pub fn registrar(&mut self, win: WindowId) -> Option<&mut InputCoordinator> {
1828 self.windows.get_mut(&win).map(|w| &mut w.coord)
1829 }
1830
1831 #[allow(dead_code)]
1836 pub fn states_mut(&mut self, win: WindowId) -> Option<&mut uzor::app_context::StateRegistry> {
1837 self.windows.get_mut(&win).map(|w| &mut w.states)
1838 }
1839
1840 pub fn compose_parts(
1844 &mut self,
1845 win: WindowId,
1846 ) -> Option<(&mut InputCoordinator, &mut uzor::app_context::StateRegistry, &mut Selectables)> {
1847 self.windows
1848 .get_mut(&win)
1849 .map(|w| (&mut w.coord, &mut w.states, &mut w.reported))
1850 }
1851
1852 #[allow(dead_code)]
1860 pub fn update_selectable(
1861 &mut self,
1862 win: WindowId,
1863 widget: WidgetId,
1864 text: impl Into<String>,
1865 lines: Vec<SelectionLine>,
1866 ) {
1867 if let Some(w) = self.windows.get_mut(&win) {
1868 w.reported.report(widget, text, lines);
1869 }
1870 }
1871
1872 #[allow(dead_code)]
1875 pub fn alias_selectable(&mut self, win: WindowId, member: WidgetId, owner: WidgetId) {
1876 if let Some(w) = self.windows.get_mut(&win) {
1877 w.reported.alias(member, owner);
1878 }
1879 }
1880
1881 pub fn revision(&self) -> Revision {
1883 self.rev
1884 }
1885
1886 pub fn view(&self) -> InputEngineView<'_> {
1888 InputEngineView { e: self }
1889 }
1890}
1891
1892#[derive(Clone, Copy, Debug)]
1894pub struct InputEngineView<'a> {
1895 e: &'a InputEngine,
1896}
1897
1898#[allow(dead_code)]
1900impl<'a> InputEngineView<'a> {
1901 fn w(&self, win: WindowId) -> Option<&'a PerWindowInput> {
1902 self.e.windows.get(&win)
1903 }
1904
1905 pub fn ids(&self) -> impl Iterator<Item = WindowId> + 'a {
1907 self.e.windows.keys().copied()
1908 }
1909
1910 pub fn window(&self, win: WindowId) -> Option<InputView> {
1912 self.w(win).map(|w| InputView {
1913 hovered: w.hover.clone(),
1914 pressed: w.pressed.clone(),
1915 focused: w.focused_id().cloned(),
1916 focus_visible: w.focus_visible,
1917 captured: w.capture.is_some(),
1918 scope_depth: w.scopes.len(),
1919 })
1920 }
1921
1922 pub fn focused(&self, win: WindowId) -> Option<&'a WidgetId> {
1924 self.w(win)?.focused_id()
1925 }
1926
1927 pub fn active_scope(&self, win: WindowId) -> Option<&'a ScopeOwner> {
1929 self.w(win)?.scopes.last().map(|s| &s.owner)
1930 }
1931
1932 pub fn capture(&self, win: WindowId) -> Option<&'a Capture> {
1934 self.w(win)?.capture.as_ref()
1935 }
1936
1937 pub fn cook(&self, win: WindowId) -> Option<&'a CookState> {
1939 self.w(win).map(|w| &w.cook)
1940 }
1941
1942 pub fn clicked(&self, win: WindowId) -> &'a [(WidgetId, u8)] {
1945 self.w(win).map_or(&[], |w| w.clicked.as_slice())
1946 }
1947
1948 pub fn caret_visible(&self, win: WindowId) -> bool {
1951 self.w(win).is_some_and(|w| w.caret_visible)
1952 }
1953
1954 pub fn caret_deadline(&self, win: WindowId) -> Option<Seconds> {
1956 self.w(win)?.armed
1957 }
1958
1959 pub fn text_fields(&self, win: WindowId) -> Option<&'a TextFieldStore> {
1961 self.w(win).map(|w| w.coord.text_fields())
1962 }
1963
1964 pub fn selections(&self, win: WindowId) -> Option<&'a [(WidgetId, TextSelection)]> {
1968 self.w(win).map(|w| w.selections.as_slice())
1969 }
1970
1971 pub fn coordinator(&self, win: WindowId) -> Option<&'a InputCoordinator> {
1973 self.w(win).map(|w| &w.coord)
1974 }
1975
1976 pub fn pending_scroll(&self, win: WindowId) -> (f64, f64) {
1980 self.w(win).map_or((0.0, 0.0), |w| w.pointer.scroll)
1981 }
1982
1983 pub fn pending_scroll_precise(&self, win: WindowId) -> bool {
1986 self.w(win).is_some_and(|w| w.pointer.scroll_precise)
1987 }
1988
1989 pub fn pending_scroll_touch(&self, win: WindowId) -> bool {
1991 self.w(win).is_some_and(|w| w.pointer.scroll_touch)
1992 }
1993
1994 pub fn context_click(&self, win: WindowId) -> Option<(f64, f64)> {
1998 self.w(win).and_then(|w| w.pointer.context)
1999 }
2000
2001 pub fn pointer(&self, win: WindowId) -> (Option<(f64, f64)>, bool) {
2002 self.w(win).map_or((None, false), |w| (w.pointer.pos, w.pointer.button_down.is_some()))
2003 }
2004
2005 pub fn press_origin(&self, win: WindowId) -> Option<(f64, f64)> {
2009 let w = self.w(win)?;
2010 w.pointer.button_down?;
2011 w.cook.press_origin.map(|o| (o.x, o.y))
2012 }
2013}
2014
2015#[cfg(test)]
2016mod tests;