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}
224
225#[derive(Clone, Debug, PartialEq, Eq)]
227struct SavedFocus {
228 id: WidgetId,
229 engaged: bool,
231}
232
233#[derive(Clone, Debug)]
234struct FocusScope {
235 owner: ScopeOwner,
236 members: Vec<WidgetId>,
237 saved: Option<SavedFocus>,
238}
239
240#[derive(Clone, Debug)]
243struct SelectableText {
244 text: String,
245 lines: Vec<SelectionLine>,
246}
247
248#[derive(Clone, Debug, Default)]
252pub struct Selectables(HashMap<WidgetId, SelectableText>, HashMap<WidgetId, WidgetId>);
253
254impl Selectables {
255 pub fn report(&mut self, widget: impl Into<WidgetId>, text: impl Into<String>, lines: Vec<SelectionLine>) {
258 self.0.insert(widget.into(), SelectableText { text: text.into(), lines });
259 }
260 pub fn alias(&mut self, member: impl Into<WidgetId>, owner: impl Into<WidgetId>) {
264 self.1.insert(member.into(), owner.into());
265 }
266 fn contains_key(&self, w: &WidgetId) -> bool {
267 self.0.contains_key(w)
268 }
269}
270
271#[derive(Clone, Debug)]
273struct PressSel {
274 widget: WidgetId,
275 anchor: usize,
276}
277
278#[derive(Clone, Copy, Debug, PartialEq, Eq)]
280enum EscLevel {
281 Widget,
283 Panel,
285 Window,
287}
288
289#[derive(Clone, Debug, PartialEq, Eq)]
292struct CaretKey {
293 field: WidgetId,
294 engaged: bool,
295 text: String,
296 cursor: usize,
297 selection: Option<usize>,
298 preedit: String,
299 preedit_cursor: usize,
300}
301
302#[derive(Clone, Debug, PartialEq, Eq)]
304struct Focused {
305 id: WidgetId,
306 field: bool,
308}
309
310struct PerWindowInput {
311 coord: InputCoordinator,
312 states: uzor::app_context::StateRegistry,
316 cook: CookState,
317 pointer: PointerAccum,
318 capture: Option<Capture>,
319 scopes: Vec<FocusScope>,
320 focus: Option<Focused>,
321 hover: Option<WidgetId>,
322 pressed: Option<WidgetId>,
323 clicked: SmallVec<[(WidgetId, u8); 2]>,
324 os_focused: bool,
325 caret: Option<CaretKey>,
326 blink_anchor_ms: u64,
327 caret_visible: bool,
328 armed: Option<Seconds>,
329 ime_area: Option<Rect>,
330 ime_allowed: bool,
331 pending_paste: Option<(Ticket, Option<WidgetId>)>,
334 offer: Option<String>,
336 selectables: HashMap<WidgetId, SelectableText>,
340 sel_alias: HashMap<WidgetId, WidgetId>,
342 reported: Selectables,
343 selections: Vec<(WidgetId, TextSelection)>,
344 press_sel: Option<PressSel>,
345 drag_ended: bool,
346 escalation: Option<(WidgetId, EscLevel)>,
347 focus_visible: bool,
350 key_clicks: Vec<WidgetId>,
353 space_armed: Option<WidgetId>,
355}
356
357fn activation(kind: Option<WidgetKind>) -> (bool, bool) {
361 use WidgetKind as K;
362 match kind {
363 Some(K::Link) => (true, false),
364 Some(K::Checkbox | K::Radio | K::Toggle) => (false, true),
365 Some(K::Button | K::CloseButton | K::ChromeTab | K::DropdownTrigger | K::Item | K::ColorSwatch | K::Custom) | None => (true, true),
366 Some(_) => (false, false),
367 }
368}
369
370impl PerWindowInput {
371 fn new() -> Self {
372 Self {
373 coord: InputCoordinator::new(),
374 states: uzor::app_context::StateRegistry::new(),
375 cook: CookState::default(),
376 pointer: PointerAccum::default(),
377 capture: None,
378 scopes: Vec::new(),
379 focus: None,
380 hover: None,
381 pressed: None,
382 clicked: SmallVec::new(),
383 os_focused: true,
386 caret: None,
387 blink_anchor_ms: 0,
388 caret_visible: false,
389 armed: None,
390 ime_area: None,
391 ime_allowed: false,
392 pending_paste: None,
393 offer: None,
394 selectables: HashMap::new(),
395 sel_alias: HashMap::new(),
396 reported: Selectables::default(),
397 selections: Vec::new(),
398 press_sel: None,
399 drag_ended: false,
400 escalation: None,
401 focus_visible: false,
402 key_clicks: Vec::new(),
403 space_armed: None,
404 }
405 }
406
407 fn allowed(&self, id: &WidgetId) -> bool {
412 self.scopes.last().is_none_or(|s| s.members.contains(id))
413 }
414
415 fn focus_raw(&mut self, id: WidgetId) {
418 let field = self.coord.text_fields().has_field(&id);
419 if field {
420 self.coord.focus_text_field(&id);
421 } else {
422 self.coord.set_focus(id.clone());
423 }
424 self.focus = Some(Focused { id, field });
425 }
426
427 fn clear_raw(&mut self) -> bool {
428 let had = self.focus.is_some() || self.coord.text_fields().focused().is_some();
429 self.coord.clear_focus();
430 self.focus = None;
431 had
432 }
433
434 fn focused_id(&self) -> Option<&WidgetId> {
435 self.focus.as_ref().map(|f| &f.id)
436 }
437
438 fn scoped_candidates(&self) -> Option<Vec<WidgetId>> {
441 let scope = self.scopes.last()?;
442 Some(
443 scope
444 .members
445 .iter()
446 .filter(|m| self.coord.widget_rect(m).is_some() && self.coord.tab_index(m) >= 0)
447 .cloned()
448 .collect(),
449 )
450 }
451
452 fn cycle(&mut self, forward: bool) -> Option<bool> {
454 let before = self.focus.clone();
455 match self.scoped_candidates() {
456 Some(list) => {
457 if list.is_empty() {
458 return None;
459 }
460 let n = list.len();
461 let at = self
462 .focused_id()
463 .and_then(|f| list.iter().position(|m| m == f));
464 let next = match (at, forward) {
465 (Some(i), true) => (i + 1) % n,
466 (None, true) => 0,
467 (Some(i), false) => (i + n - 1) % n,
468 (None, false) => n - 1,
469 };
470 if self.focused_id() != Some(&list[next]) {
471 self.focus_raw(list[next].clone());
472 }
473 }
474 None => {
475 if forward {
476 self.coord.focus_next();
477 } else {
478 self.coord.focus_prev();
479 }
480 let target = self.coord.focused_widget().cloned()?;
481 if self.focused_id() != Some(&target) || !self.store_matches_focus() {
482 self.focus_raw(target);
483 }
484 }
485 }
486 Some(self.focus != before)
487 }
488
489 fn store_matches_focus(&self) -> bool {
491 let store = self.coord.text_fields().focused();
492 match &self.focus {
493 Some(f) if f.field => store == Some(&f.id),
494 _ => store.is_none(),
495 }
496 }
497
498 fn focus_op(
499 &mut self,
500 win: WindowId,
501 op: FocusOp,
502 next_scope: &mut u64,
503 fx: &mut InputEffects,
504 ) -> bool {
505 match op {
506 FocusOp::Set(id) => {
507 if !self.allowed(&id) || self.focused_id() == Some(&id) {
508 return false;
509 }
510 self.focus_raw(id);
511 true
512 }
513 FocusOp::Clear => self.clear_raw(),
514 FocusOp::Next => self.cycle(true).unwrap_or(false),
515 FocusOp::Prev => self.cycle(false).unwrap_or(false),
516 FocusOp::PushScope { owner, members } => {
517 if self.scopes.iter().any(|s| s.owner == owner) {
518 return self.set_members(&owner, members);
519 }
520 let saved = self.focus.as_ref().map(|f| SavedFocus {
521 engaged: f.field && self.coord.text_fields().is_engaged(&f.id),
522 id: f.id.clone(),
523 });
524 self.clear_raw();
525 self.scopes.push(FocusScope {
526 owner: owner.clone(),
527 members,
528 saved,
529 });
530 *next_scope += 1;
531 fx.push(InputEffect::ScopePushed {
532 win,
533 owner,
534 scope: ScopeId(*next_scope),
535 });
536 true
537 }
538 FocusOp::SetMembers { owner, members } => self.set_members(&owner, members),
539 FocusOp::PopScope { owner, restore } => self.pop_scope(&owner, restore),
540 }
541 }
542
543 fn set_members(&mut self, owner: &ScopeOwner, members: Vec<WidgetId>) -> bool {
544 let Some(i) = self.scopes.iter().position(|s| &s.owner == owner) else {
545 return false;
546 };
547 if self.scopes[i].members == members {
548 return false;
549 }
550 self.scopes[i].members = members;
551 let active = i + 1 == self.scopes.len();
552 if active {
553 if let Some(f) = self.focused_id().cloned() {
554 if !self.allowed(&f) {
555 self.clear_raw();
556 }
557 }
558 }
559 true
560 }
561
562 fn pop_scope(&mut self, owner: &ScopeOwner, restore: bool) -> bool {
563 let Some(i) = self.scopes.iter().position(|s| &s.owner == owner) else {
564 return false;
565 };
566 let scope = self.scopes.remove(i);
567 if i < self.scopes.len() {
568 self.scopes[i].saved = scope.saved;
571 return true;
572 }
573 self.clear_raw();
574 if let (true, Some(saved)) = (restore, scope.saved) {
575 if self.allowed(&saved.id) {
576 self.focus_raw(saved.id.clone());
577 if saved.engaged {
578 self.coord.text_fields_mut().engage(&saved.id);
579 }
580 }
581 }
582 true
583 }
584
585 fn reconcile_focus(&mut self) -> bool {
588 let store = self.coord.text_fields().focused().cloned();
589 match (store, self.focus.clone()) {
590 (Some(s), Some(f)) if f.field && s == f.id => false,
591 (Some(s), _) if self.allowed(&s) => {
592 self.coord.set_focus(s.clone());
593 self.focus = Some(Focused { id: s, field: true });
594 true
595 }
596 (Some(_), prev) => {
597 self.coord.text_fields_mut().blur();
599 if let Some(f) = prev.filter(|f| f.field) {
600 let engaged = self.coord.text_fields().is_engaged(&f.id);
601 self.coord.focus_text_field(&f.id);
602 if engaged {
603 self.coord.text_fields_mut().engage(&f.id);
604 }
605 }
606 false
607 }
608 (None, Some(f)) if f.field => {
609 self.coord.clear_focus();
611 self.focus = None;
612 true
613 }
614 (None, _) => false,
615 }
616 }
617
618 fn set_capture(&mut self, capture: Option<Capture>) -> bool {
621 if self.capture == capture {
622 return false;
623 }
624 if let Some(Capture::Widget(_)) = &self.capture {
625 self.coord.release_pointer();
626 }
627 if let Some(Capture::Widget(id)) = &capture {
628 self.coord.grab_pointer(id.clone());
629 }
630 self.capture = capture;
631 true
632 }
633
634 fn cook(&mut self, win: WindowId, now: Seconds, input: PointerInput) -> (bool, CookedPointer) {
635 let t = now.get();
636 let target = match &self.capture {
637 Some(c) => PointerTarget::Captured(c.clone()),
638 None => PointerTarget::HitTest,
639 };
640 let mut drag_started = false;
641 let mut ended_drag = false;
642 let mut changed = false;
643 if matches!(input, PointerInput::Down { .. }) && self.focus_visible {
646 self.focus_visible = false;
647 changed = true;
648 }
649 match input {
650 PointerInput::Moved { pos, mods } => {
651 self.pointer.pos = Some((pos.x, pos.y));
652 self.pointer.mods = mods;
653 drag_started = self.cook.motion(pos.x, pos.y).drag_started;
654 }
655 PointerInput::Down { pos, button, mods } => {
656 self.pointer.pos = Some((pos.x, pos.y));
657 self.pointer.mods = mods;
658 if self.cook.press_origin.is_none() {
660 self.cook.press(pos.x, pos.y, button, t);
661 }
662 }
663 PointerInput::Up { pos, button, mods } => {
664 self.pointer.pos = Some((pos.x, pos.y));
665 self.pointer.mods = mods;
666 if self.cook.press_origin.map(|o| o.button) == Some(button) {
667 ended_drag = self.cook.release(pos.x, pos.y, button, t);
668 self.drag_ended |= ended_drag;
669 changed = self.set_capture(None);
670 }
671 }
672 PointerInput::Entered | PointerInput::RawDelta { .. } => {}
673 PointerInput::Left => self.pointer.pos = None,
674 PointerInput::Cancelled => {
675 self.cook.press_origin = None;
676 self.cook.drag_armed = false;
677 self.pointer.button_down = None;
678 changed = self.set_capture(None);
679 changed |= self.pressed.take().is_some();
680 self.press_sel = None;
681 self.drag_ended = false;
682 }
683 }
684 if drag_started {
688 let grab = self
689 .pressed
690 .clone()
691 .filter(|id| self.coord.widget_sense(id).is_some_and(|s| s.drag));
692 if let Some(id) = grab {
693 changed = self.set_capture(Some(Capture::Widget(id)));
694 }
695 }
696 let cooked = CookedPointer {
697 win,
698 input,
699 click_count: self.cook.click_count,
700 drag_armed: self.cook.drag_armed,
701 drag_started,
702 ended_drag,
703 target,
704 };
705 (changed, cooked)
706 }
707
708 fn content_target(&self, pos: Option<(f64, f64)>) -> Option<WidgetId> {
711 if let Some(Capture::Widget(id)) = &self.capture {
712 return Some(id.clone());
713 }
714 let (x, y) = pos?;
715 self.coord.hit_test_now(x, y)
716 }
717
718 fn deliver(
719 &mut self,
720 win: WindowId,
721 input: PointerInput,
722 fx: &mut InputEffects,
723 ) -> (bool, Option<WidgetId>) {
724 match input {
725 PointerInput::Moved { pos, .. } => {
726 self.pointer.pos = Some((pos.x, pos.y));
727 let target = self.content_target(self.pointer.pos);
731 let mut changed = self.pointer.button_down.is_some() || target != self.hover;
732 if self.pointer.button_down == Some(MouseButton::Left)
735 && self.cook.drag_armed
736 && self.coord.text_fields().drag_active()
737 {
738 self.coord.text_fields_mut().on_drag_move(pos.x);
739 changed = true;
740 }
741 (changed, target)
742 }
743 PointerInput::Down { pos, button, .. } => {
744 self.pointer.pos = Some((pos.x, pos.y));
745 self.pointer.button_down = Some(button);
746 self.pointer.clicked = None;
750 let target = self.content_target(self.pointer.pos);
751 let changed = self.pressed != target;
752 self.pressed.clone_from(&target);
753 let t = target.as_ref().map(|t| self.sel_owner(t));
754 let sel_changed = self.press_down(win, t.as_ref(), pos.x, pos.y, fx);
755 if button == MouseButton::Left {
756 self.arm_text_drag(target.as_ref(), pos.x);
757 } else if self.coord.text_fields().drag_active() {
758 self.coord.text_fields_mut().on_drag_end();
759 }
760 (changed | sel_changed, target)
761 }
762 PointerInput::Up { pos, button, .. } => {
763 self.pointer.pos = Some((pos.x, pos.y));
764 self.pointer.button_down = None;
765 self.pointer.clicked = Some(button);
766 if button == MouseButton::Right {
767 self.pointer.context = Some((pos.x, pos.y));
768 }
769 let target = self.content_target(self.pointer.pos);
770 let _ = self.pressed.take();
771 let t = target.as_ref().map(|t| self.sel_owner(t));
772 let _ = self.release_select(win, t.as_ref(), fx);
773 if button == MouseButton::Left && self.coord.text_fields().drag_active() {
777 self.coord.text_fields_mut().on_drag_end();
778 }
779 (true, target)
782 }
783 PointerInput::Entered
784 | PointerInput::Left
785 | PointerInput::Cancelled
786 | PointerInput::RawDelta { .. } => (false, None),
787 }
788 }
789
790 fn arm_text_drag(&mut self, target: Option<&WidgetId>, x: f64) {
796 let field = match target {
797 Some(id)
798 if self.coord.widget_sense(id).is_some_and(|s| s.text)
799 && self.coord.text_fields().has_field(id) =>
800 {
801 Some(id.clone())
802 }
803 _ => None,
804 };
805 if let Some(id) = field {
806 if self.cook.click_count <= 1 {
807 self.coord.text_fields_mut().begin_drag_at(id, x);
808 return;
809 }
810 }
811 if self.coord.text_fields().drag_active() {
812 self.coord.text_fields_mut().on_drag_end();
813 }
814 }
815
816 fn release_select(
820 &mut self,
821 win: WindowId,
822 target: Option<&WidgetId>,
823 fx: &mut InputEffects,
824 ) -> bool {
825 if self.drag_ended {
826 return false;
827 }
828 let Some(p) = self.press_sel.clone() else {
829 return false;
830 };
831 if target != Some(&p.widget) {
832 return false;
833 }
834 let Some(st) = self.selectables.get(&p.widget) else {
835 return false;
836 };
837 let sel = TextSelection::for_click_count(&st.text, p.anchor, self.cook.click_count.max(1));
838 let changed = self.set_selection(win, &p.widget, sel, fx);
839 self.escalation = Some((p.widget, EscLevel::Widget));
840 changed
841 }
842
843 fn wheel(&mut self, input: WheelInput) -> Option<WidgetId> {
844 let (dx, dy) = match input.delta {
845 WheelDelta::Lines { x, y } => (x, y),
846 WheelDelta::Pixels { x, y } => {
847 self.pointer.scroll_precise = true;
848 (x / WHEEL_PIXELS_PER_LINE, y / WHEEL_PIXELS_PER_LINE)
849 }
850 };
851 self.pointer.pos = Some((input.pos.x, input.pos.y));
852 self.pointer.mods = input.mods;
853 self.pointer.scroll.0 += dx;
854 self.pointer.scroll.1 += dy;
855 if let Some(Capture::Widget(id)) = &self.capture {
856 return Some(id.clone());
857 }
858 self.coord.process_scroll(input.pos.x, input.pos.y)
859 }
860
861 fn sel_owner(&self, w: &WidgetId) -> WidgetId {
865 self.sel_alias.get(w).unwrap_or(w).clone()
866 }
867
868 fn sel_get(&self, widget: &WidgetId) -> Option<TextSelection> {
869 self.selections
870 .iter()
871 .find(|(w, _)| w == widget)
872 .map(|(_, s)| *s)
873 }
874
875 fn sel_set(&mut self, widget: WidgetId, sel: TextSelection) -> bool {
876 if let Some(slot) = self.selections.iter_mut().find(|(w, _)| *w == widget) {
877 if slot.1 == sel {
878 return false;
879 }
880 slot.1 = sel;
881 return true;
882 }
883 self.selections.push((widget, sel));
884 true
885 }
886
887 fn sel_remove(&mut self, widget: &WidgetId) -> bool {
888 let before = self.selections.len();
889 self.selections.retain(|(w, _)| w != widget);
890 self.selections.len() != before
891 }
892
893 fn set_selection(
895 &mut self,
896 win: WindowId,
897 widget: &WidgetId,
898 sel: TextSelection,
899 fx: &mut InputEffects,
900 ) -> bool {
901 if !self.sel_set(widget.clone(), sel) {
902 return false;
903 }
904 fx.push(InputEffect::InvalidateField {
905 win,
906 rect: self.coord.widget_rect(widget),
907 });
908 true
909 }
910
911 fn clear_selections(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
913 if self.selections.is_empty() {
914 return false;
915 }
916 for (w, _) in &self.selections {
917 fx.push(InputEffect::InvalidateField {
918 win,
919 rect: self.coord.widget_rect(w),
920 });
921 }
922 self.selections.clear();
923 self.escalation = None;
924 true
925 }
926
927 fn selectable_ids_by_row(&self) -> Vec<WidgetId> {
930 let mut ids: Vec<(f64, f64, WidgetId)> = self
931 .selectables
932 .keys()
933 .map(|w| {
934 let r = self
935 .coord
936 .widget_rect(w)
937 .unwrap_or_else(|| Rect::new(0.0, 0.0, 0.0, 0.0));
938 (r.y, r.x, w.clone())
939 })
940 .collect();
941 uzor::sort::sort_by(&mut ids, |a, b| a.0.total_cmp(&b.0).then_with(|| a.1.total_cmp(&b.1)));
942 ids.into_iter().map(|(_, _, w)| w).collect()
943 }
944
945 fn selected_text_concat(&self) -> Option<String> {
948 if self.selections.is_empty() {
949 return None;
950 }
951 let mut parts: Vec<String> = Vec::new();
952 for w in self.selectable_ids_by_row() {
953 if let (Some(sel), Some(st)) = (self.sel_get(&w), self.selectables.get(&w)) {
954 let s = sel.selected_text(&st.text);
955 if !s.is_empty() {
956 parts.push(s.to_owned());
957 }
958 }
959 }
960 if parts.is_empty() {
961 None
962 } else {
963 Some(parts.join("\n"))
964 }
965 }
966
967 fn nearest_panel_rect(&self, widget: &WidgetId) -> Option<Rect> {
970 let mut cur = self.coord.widget_parent(widget);
971 while let Some(p) = cur {
972 if matches!(
973 self.coord.widget_kind(&p),
974 Some(WidgetKind::Panel | WidgetKind::BlackboxPanel)
975 ) {
976 return self.coord.widget_rect(&p);
977 }
978 cur = self.coord.widget_parent(&p);
979 }
980 None
981 }
982
983 fn select_in_rect(&mut self, win: WindowId, rect: &Rect, fx: &mut InputEffects) -> bool {
985 let mut changed = false;
986 for w in self.selectable_ids_by_row() {
987 if let Some(r) = self.coord.widget_rect(&w) {
988 let inside = r.x >= rect.x
989 && r.y >= rect.y
990 && r.x + r.width <= rect.x + rect.width
991 && r.y + r.height <= rect.y + rect.height;
992 if inside {
993 if let Some(st) = self.selectables.get(&w) {
994 let sel = TextSelection::all(&st.text);
995 changed |= self.set_selection(win, &w, sel, fx);
996 }
997 }
998 }
999 }
1000 changed
1001 }
1002
1003 fn select_everything(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
1005 let mut changed = false;
1006 for w in self.selectable_ids_by_row() {
1007 if let Some(st) = self.selectables.get(&w) {
1008 let sel = TextSelection::all(&st.text);
1009 changed |= self.set_selection(win, &w, sel, fx);
1010 }
1011 }
1012 changed
1013 }
1014
1015 fn press_down(
1018 &mut self,
1019 win: WindowId,
1020 target: Option<&WidgetId>,
1021 x: f64,
1022 y: f64,
1023 fx: &mut InputEffects,
1024 ) -> bool {
1025 let mut changed = false;
1026 if !target.is_some_and(|t| self.sel_get(t).is_some()) {
1027 changed |= self.clear_selections(win, fx);
1028 }
1029 self.press_sel = None;
1030 if let Some(t) = target {
1031 if let Some(st) = self.selectables.get(t) {
1032 let anchor = char_at_point(&st.lines, x, y);
1033 self.press_sel = Some(PressSel {
1034 widget: t.clone(),
1035 anchor,
1036 });
1037 }
1038 }
1039 changed
1040 }
1041
1042 fn selection_frame(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
1045 let mut changed = false;
1046
1047 if let Some(p) = self.press_sel.clone() {
1051 if self.cook.drag_armed || self.drag_ended {
1052 if let (Some(st), Some((x, y))) =
1053 (self.selectables.get(&p.widget), self.pointer.pos)
1054 {
1055 let sel = TextSelection::new(p.anchor, char_at_point(&st.lines, x, y));
1056 changed |= self.set_selection(win, &p.widget, sel, fx);
1057 }
1058 }
1059 }
1060
1061 if self.pointer.button_down.is_none() {
1067 self.press_sel = None;
1068 self.drag_ended = false;
1069 }
1070
1071 let fresh = std::mem::take(&mut self.reported);
1074 let gone: Vec<WidgetId> = self
1075 .selections
1076 .iter()
1077 .map(|(w, _)| w.clone())
1078 .filter(|w| !fresh.contains_key(w))
1079 .collect();
1080 if !gone.is_empty() {
1081 for w in &gone {
1082 fx.push(InputEffect::InvalidateField {
1083 win,
1084 rect: self.coord.widget_rect(w),
1085 });
1086 self.sel_remove(w);
1087 }
1088 if let Some((w, _)) = &self.escalation {
1089 if gone.contains(w) {
1090 self.escalation = None;
1091 }
1092 }
1093 changed = true;
1094 }
1095 self.selectables = fresh.0;
1096 self.sel_alias = fresh.1;
1097
1098 changed
1099 }
1100
1101 fn ctrl_a(&mut self, win: WindowId, fx: &mut InputEffects) -> Option<bool> {
1105 if let Some((w, level)) = self.escalation.clone() {
1106 let next = match level {
1107 EscLevel::Widget => match self.nearest_panel_rect(&w) {
1108 Some(rect) => {
1109 self.select_in_rect(win, &rect, fx);
1110 EscLevel::Panel
1111 }
1112 None => {
1113 self.select_everything(win, fx);
1114 EscLevel::Window
1115 }
1116 },
1117 EscLevel::Panel => {
1118 self.select_everything(win, fx);
1119 EscLevel::Window
1120 }
1121 EscLevel::Window => return Some(false),
1122 };
1123 self.escalation = Some((w, next));
1124 return Some(true);
1125 }
1126 let start = self
1128 .hover
1129 .clone()
1130 .filter(|h| self.selectables.contains_key(h))
1131 .or_else(|| (self.selections.len() == 1).then(|| self.selections[0].0.clone()));
1132 let w = start?;
1133 let st = self.selectables.get(&w)?;
1134 let sel = TextSelection::all(&st.text);
1135 let changed = self.set_selection(win, &w, sel, fx);
1136 self.escalation = Some((w, EscLevel::Widget));
1137 Some(changed)
1138 }
1139
1140 fn begin_frame(&mut self, now: Seconds) -> bool {
1143 let mut state = InputState::new();
1144 state.pointer.pos = self.pointer.pos;
1145 state.pointer.prev_pos = self.pointer.prev_pos;
1146 state.pointer.button_down = self.pointer.button_down;
1147 state.pointer.clicked = self.pointer.clicked.take();
1148 state.modifiers = self.pointer.mods;
1149 state.scroll_delta = std::mem::take(&mut self.pointer.scroll);
1150 self.pointer.scroll_precise = false;
1151 self.pointer.context = None;
1152 state.time = now.get();
1153 self.pointer.prev_pos = self.pointer.pos;
1154 self.coord.begin_frame(state);
1155 let had_clicks = !self.clicked.is_empty();
1156 self.clicked.clear();
1157 had_clicks
1158 }
1159
1160 fn end_frame(&mut self, win: WindowId, fx: &mut InputEffects) -> bool {
1161 let mut hover = None;
1162 let mut clicked = SmallVec::new();
1163 for (id, r) in self.coord.end_frame() {
1164 if r.hovered {
1165 hover = Some(id.clone());
1166 }
1167 if r.clicked {
1168 let count = if r.triple_clicked {
1169 3
1170 } else if r.double_clicked {
1171 2
1172 } else {
1173 1
1174 };
1175 clicked.push((id, count));
1176 }
1177 }
1178 for w in self.key_clicks.drain(..) {
1179 if !clicked.iter().any(|(c, _)| *c == w) {
1180 clicked.push((w, 1));
1181 }
1182 }
1183 let mut changed = hover != self.hover || clicked != self.clicked;
1184 self.hover = hover;
1185 self.clicked = clicked.clone();
1186 let clicked_focus = clicked
1189 .iter()
1190 .map(|(id, _)| id.clone())
1191 .find(|id| self.allowed(id) && self.coord.widget_sense(id).is_some_and(|s| s.focus));
1192 if let Some(id) = clicked_focus {
1193 if self.focused_id() != Some(&id) {
1194 self.focus_raw(id);
1195 changed = true;
1196 }
1197 }
1198 changed |= self.selection_frame(win, fx);
1199 changed |= self.reconcile_focus();
1200 changed
1201 }
1202
1203 fn text_focus(&self) -> Option<WidgetId> {
1207 let f = self.focus.as_ref().filter(|f| f.field)?;
1208 self.coord
1209 .text_fields()
1210 .is_focused(&f.id)
1211 .then(|| f.id.clone())
1212 }
1213
1214 fn key(
1215 &mut self,
1216 win: WindowId,
1217 input: KeyInput,
1218 next_ticket: &mut u64,
1219 fx: &mut InputEffects,
1220 ) -> bool {
1221 let m = input.mods;
1222 if input.code == KeyCode::Space && input.state == KeyState::Up {
1223 if let Some(w) = self.space_armed.take() {
1224 if self.focused_id() == Some(&w) {
1225 self.key_clicks.push(w);
1226 return true;
1227 }
1228 }
1229 }
1230 if input.state == KeyState::Up {
1231 fx.push(InputEffect::KeyPassed { win, key: input });
1232 return false;
1233 }
1234 if input.code != KeyCode::Unknown {
1235 self.focus_visible = true;
1236 }
1237 if matches!(input.code, KeyCode::Enter | KeyCode::Space) && !(m.ctrl || m.alt || m.meta) {
1239 if let Some(f) = self.focus.as_ref().filter(|f| !f.field).map(|f| f.id.clone()) {
1240 if self.coord.widget_sense(&f).is_some_and(|s| s.click) {
1241 let (enter, space) = activation(self.coord.widget_kind(&f));
1242 if input.code == KeyCode::Enter && enter {
1243 self.key_clicks.push(f);
1244 return true;
1245 }
1246 if input.code == KeyCode::Space && space {
1247 self.space_armed = Some(f);
1248 return false;
1249 }
1250 }
1251 }
1252 }
1253 if input.code == KeyCode::Tab && !(m.ctrl || m.alt || m.meta) {
1254 return match self.cycle(!m.shift) {
1255 Some(changed) => changed,
1256 None => {
1257 fx.push(InputEffect::KeyPassed { win, key: input });
1258 false
1259 }
1260 };
1261 }
1262 let field = self.text_focus();
1263 let edit = editing_chord(&input);
1264 let (field, edit) = match (field, edit) {
1265 (Some(f), Some(e)) => (f, e),
1266 (None, Some(Edit::Copy)) => {
1269 if let Some(text) = self.selected_text_concat() {
1270 fx.push(InputEffect::CopyText { win, text });
1271 } else {
1272 if let Some(text) = self.offer.clone() {
1275 fx.push(InputEffect::CopyText { win, text });
1276 }
1277 fx.push(InputEffect::KeyPassed { win, key: input });
1278 }
1279 return false;
1280 }
1281 (None, Some(Edit::Cut)) => {
1282 if let Some(text) = self.offer.clone() {
1283 fx.push(InputEffect::CopyText { win, text });
1284 }
1285 fx.push(InputEffect::KeyPassed { win, key: input });
1286 return false;
1287 }
1288 (None, Some(Edit::Paste)) => {
1289 let ticket = Ticket(INPUT_TICKET_BASE.saturating_add(*next_ticket));
1293 *next_ticket = next_ticket.saturating_add(1);
1294 self.pending_paste = Some((ticket, None));
1295 fx.push(InputEffect::NeedPaste { win, ticket });
1296 return false;
1297 }
1298 (None, Some(Edit::Key(KeyPress::SelectAll)))
1299 if self.focus.as_ref().is_some_and(|f| !f.field && self.coord.widget_kind(&f.id).is_some_and(|k| k.is_blackbox())) =>
1300 {
1301 fx.push(InputEffect::KeyPassed { win, key: input });
1303 return false;
1304 }
1305 (None, Some(Edit::Key(KeyPress::SelectAll))) => {
1306 return match self.ctrl_a(win, fx) {
1308 Some(changed) => changed,
1309 None => {
1310 fx.push(InputEffect::KeyPassed { win, key: input });
1311 false
1312 }
1313 };
1314 }
1315 _ => {
1316 fx.push(InputEffect::KeyPassed { win, key: input });
1317 return false;
1318 }
1319 };
1320 let text_before = self.coord.text_fields().text(&field).to_owned();
1321 let changed_text = |action: &TextAction| matches!(action, TextAction::TextChanged(_));
1322 let mut changed = false;
1323 let multiline = self.coord.text_fields().field_state(&field).is_some_and(|s| s.config.multiline);
1324 let edit = match edit {
1325 Edit::Newline if multiline => Edit::Key(KeyPress::Paste("\n".into())),
1326 Edit::Newline => Edit::Submit,
1327 e => e,
1328 };
1329 match edit {
1330 Edit::Newline => {}
1331 Edit::Key(kp) => changed = changed_text(&self.coord.on_key(kp)),
1332 Edit::Char(c) => changed = changed_text(&self.coord.on_char(c)),
1333 Edit::Text(s) => {
1334 for c in s.chars() {
1335 changed |= changed_text(&self.coord.on_char(c));
1336 }
1337 }
1338 Edit::Submit => {
1339 if let TextAction::Commit(_) = self.coord.on_char('\r') {
1340 fx.push(InputEffect::Text(TextIntent::Submitted {
1341 win,
1342 field: field.clone(),
1343 }));
1344 }
1345 }
1346 Edit::Copy => {
1347 let own = if self.masked(&field) { None } else { self.coord.text_fields().copy_selection().filter(|t| !t.is_empty()) };
1350 if let Some(text) = own.or_else(|| self.selected_text_concat()) {
1351 fx.push(InputEffect::CopyText { win, text });
1352 }
1353 }
1354 Edit::Cut => {
1355 if !self.masked(&field) {
1356 if let Some(text) = self.coord.text_fields_mut().cut_selection(&field) {
1357 fx.push(InputEffect::CopyText { win, text });
1358 }
1359 }
1360 }
1361 Edit::Paste => {
1362 let ticket = Ticket(INPUT_TICKET_BASE.saturating_add(*next_ticket));
1363 *next_ticket = next_ticket.saturating_add(1);
1364 self.pending_paste = Some((ticket, Some(field.clone())));
1365 fx.push(InputEffect::NeedPaste { win, ticket });
1366 }
1367 }
1368 if changed || self.coord.text_fields().text(&field) != text_before {
1369 fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
1370 }
1371 false
1373 }
1374
1375 fn masked(&self, field: &WidgetId) -> bool {
1376 self.coord
1377 .text_fields()
1378 .field_state(field)
1379 .is_some_and(|s| s.config.masked)
1380 }
1381
1382 fn ime(&mut self, win: WindowId, input: ImeInput, fx: &mut InputEffects) {
1383 let Some(field) = self.text_focus() else {
1384 return;
1385 };
1386 match input {
1387 ImeInput::Enabled => {}
1388 ImeInput::Preedit { text, cursor } => {
1389 let chars = |b: usize| text.get(..b).map(|s| s.chars().count());
1390 let at = cursor
1391 .and_then(|(b, _)| chars(b))
1392 .unwrap_or_else(|| text.chars().count());
1393 self.coord.text_fields_mut().preedit_set(&field, text, at);
1394 }
1395 ImeInput::Commit(text) => {
1396 let action = self.coord.text_fields_mut().ime_commit(&field, text);
1397 if let TextAction::TextChanged(_) = action {
1398 fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
1399 }
1400 }
1401 ImeInput::Disabled => {
1402 self.coord
1403 .text_fields_mut()
1404 .preedit_set(&field, String::new(), 0);
1405 }
1406 }
1407 }
1408
1409 fn clipboard(&mut self, win: WindowId, result: ClipboardResult, fx: &mut InputEffects) {
1410 let Some((ticket, field)) = self.pending_paste.clone() else {
1411 return;
1412 };
1413 if ticket != result.ticket {
1414 return;
1415 }
1416 self.pending_paste = None;
1417 let Some(text) = result.text.filter(|t| !t.is_empty()) else {
1418 return;
1419 };
1420 let Some(field) = field else {
1421 fx.push(InputEffect::Pasted { win, text });
1422 return;
1423 };
1424 let Some(focused) = self.text_focus() else {
1425 return;
1426 };
1427 if focused != field {
1428 return;
1429 }
1430 if let TextAction::TextChanged(_) = self.coord.on_key(KeyPress::Paste(text)) {
1431 fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
1432 }
1433 }
1434
1435 fn paste(&mut self, win: WindowId, text: String, fx: &mut InputEffects) {
1439 self.pending_paste = None;
1440 if text.is_empty() {
1441 return;
1442 }
1443 match self.text_focus() {
1444 Some(field) => {
1445 if let TextAction::TextChanged(_) = self.coord.on_key(KeyPress::Paste(text)) {
1446 fx.push(InputEffect::Text(TextIntent::Changed { win, field }));
1447 }
1448 }
1449 None => fx.push(InputEffect::Pasted { win, text }),
1450 }
1451 }
1452
1453 fn caret_key(&self) -> Option<CaretKey> {
1456 let store = self.coord.text_fields();
1457 let field = store.focused()?;
1458 let s = store.field_state(field)?;
1459 Some(CaretKey {
1460 field: field.clone(),
1461 engaged: s.engaged,
1462 text: s.text.clone(),
1463 cursor: s.cursor,
1464 selection: s.selection_start,
1465 preedit: s.preedit.clone(),
1466 preedit_cursor: s.preedit_cursor,
1467 })
1468 }
1469
1470 fn field_rect(&self, field: &WidgetId) -> Option<Rect> {
1471 let (x, y, w, h) = self.coord.text_fields().field_state(field)?.last_rect?;
1472 Some(Rect::new(x, y, w, h))
1473 }
1474
1475 fn caret_rect(&self, field: &WidgetId) -> Option<Rect> {
1477 let s = self.coord.text_fields().field_state(field)?;
1478 let (x, y, _, h) = s.last_rect?;
1479 let cx = s.last_char_positions.get(s.cursor).copied().unwrap_or(x);
1480 Some(Rect::new(cx, y, 1.0, h))
1481 }
1482
1483 fn settle(&mut self, win: WindowId, now: Seconds, fx: &mut InputEffects) -> bool {
1486 let now_ms = millis(now);
1487 let key = self.caret_key();
1488 let key_changed = key != self.caret;
1489 if key_changed {
1490 if let Some(old) = &self.caret {
1491 if key.as_ref().map(|k| &k.field) != Some(&old.field) {
1492 fx.push(InputEffect::InvalidateField {
1493 win,
1494 rect: self.field_rect(&old.field),
1495 });
1496 }
1497 }
1498 self.caret = key;
1499 self.blink_anchor_ms = now_ms;
1500 }
1501 self.coord
1502 .text_fields_mut()
1503 .set_blink_time(self.blink_anchor_ms);
1504 let active = self.os_focused && self.caret.as_ref().is_some_and(|k| k.engaged);
1505 let visible = active && self.coord.text_fields().cursor_visible(now_ms);
1506 let visible_changed = visible != self.caret_visible;
1507 self.caret_visible = visible;
1508 if key_changed || visible_changed {
1509 if let Some(k) = &self.caret {
1510 fx.push(InputEffect::InvalidateField {
1511 win,
1512 rect: self.field_rect(&k.field),
1513 });
1514 }
1515 }
1516 let at = active.then(|| next_blink_edge(self.blink_anchor_ms, now_ms));
1517 if at != self.armed {
1518 self.armed = at;
1519 fx.push(InputEffect::CaretDeadline { win, at });
1520 }
1521 let field = self.caret.as_ref().map(|k| k.field.clone());
1522 let allowed = field.is_some();
1523 if allowed != self.ime_allowed {
1524 self.ime_allowed = allowed;
1525 fx.push(InputEffect::ImeAllowed { win, allowed });
1526 }
1527 let area = field.and_then(|f| self.caret_rect(&f));
1528 if area != self.ime_area {
1529 self.ime_area = area;
1530 if let Some(rect) = area {
1531 fx.push(InputEffect::ImeArea { win, rect });
1532 }
1533 }
1534 key_changed || visible_changed
1535 }
1536}
1537
1538fn millis(t: Seconds) -> u64 {
1541 (t.get() * 1000.0).round().max(0.0) as u64
1543}
1544
1545fn next_blink_edge(anchor_ms: u64, now_ms: u64) -> Seconds {
1548 let phases = now_ms.saturating_sub(anchor_ms) / CARET_BLINK_MS + 1;
1549 let edge = anchor_ms.saturating_add(phases.saturating_mul(CARET_BLINK_MS));
1550 Seconds(edge as f64 / 1000.0)
1551}
1552
1553#[derive(Clone, Debug, PartialEq, Eq)]
1555enum Edit {
1556 Key(KeyPress),
1557 Char(char),
1558 Text(String),
1559 Submit,
1560 Newline,
1562 Copy,
1563 Cut,
1564 Paste,
1565}
1566
1567fn editing_chord(input: &KeyInput) -> Option<Edit> {
1570 let m = input.mods;
1571 let cmd = m.ctrl || m.meta;
1572 let edit = match input.code {
1573 KeyCode::A if cmd => Edit::Key(KeyPress::SelectAll),
1574 KeyCode::Z if cmd && m.shift => Edit::Key(KeyPress::Redo),
1575 KeyCode::Z if cmd => Edit::Key(KeyPress::Undo),
1576 KeyCode::Y if m.ctrl && !m.alt => Edit::Key(KeyPress::Redo),
1577 KeyCode::C if cmd => Edit::Copy,
1578 KeyCode::X if cmd => Edit::Cut,
1579 KeyCode::V if cmd => Edit::Paste,
1580 KeyCode::ArrowLeft if cmd => Edit::Key(KeyPress::WordLeft),
1581 KeyCode::ArrowRight if cmd => Edit::Key(KeyPress::WordRight),
1582 KeyCode::Backspace if cmd => Edit::Key(KeyPress::DeleteWordBack),
1583 KeyCode::Delete if cmd => Edit::Key(KeyPress::DeleteWordForward),
1584 KeyCode::ArrowLeft if m.shift => Edit::Key(KeyPress::ShiftLeft),
1585 KeyCode::ArrowRight if m.shift => Edit::Key(KeyPress::ShiftRight),
1586 KeyCode::Home if m.shift => Edit::Key(KeyPress::ShiftHome),
1587 KeyCode::End if m.shift => Edit::Key(KeyPress::ShiftEnd),
1588 KeyCode::ArrowLeft => Edit::Key(KeyPress::ArrowLeft),
1589 KeyCode::ArrowRight => Edit::Key(KeyPress::ArrowRight),
1590 KeyCode::Home => Edit::Key(KeyPress::Home),
1591 KeyCode::End => Edit::Key(KeyPress::End),
1592 KeyCode::Backspace => Edit::Char('\x08'),
1593 KeyCode::Delete => Edit::Key(KeyPress::Delete),
1594 KeyCode::Enter if m.shift => Edit::Newline,
1595 KeyCode::Enter => Edit::Submit,
1596 _ if cmd && !(m.ctrl && m.alt) => return None,
1599 _ => {
1600 let text: String = input
1601 .text
1602 .as_deref()?
1603 .chars()
1604 .filter(|c| !c.is_control())
1605 .collect();
1606 if text.is_empty() {
1607 return None;
1608 }
1609 match text.chars().count() {
1610 1 => Edit::Char(text.chars().next()?),
1611 _ => Edit::Text(text),
1612 }
1613 }
1614 };
1615 Some(edit)
1616}
1617
1618#[derive(Default)]
1624pub struct InputEngine {
1625 windows: VecMap<WindowId, PerWindowInput>,
1626 next_scope: u64,
1627 next_ticket: u64,
1628 rev: Revision,
1629}
1630
1631impl fmt::Debug for InputEngine {
1632 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1633 f.debug_struct("InputEngine")
1634 .field("windows", &self.windows.keys().collect::<Vec<_>>())
1635 .field("rev", &self.rev)
1636 .finish()
1637 }
1638}
1639
1640impl InputEngine {
1641 pub fn new() -> Self {
1643 Self::default()
1644 }
1645
1646 pub fn apply(&mut self, op: InputOp) -> InputEffects {
1649 let mut fx = InputEffects::new();
1650 let Self {
1651 windows,
1652 next_scope,
1653 next_ticket,
1654 rev,
1655 } = self;
1656 let changed = match op {
1657 InputOp::Open(win) => match windows.entry(win) {
1658 crate::types::vecmap::Entry::Occupied(_) => false,
1659 crate::types::vecmap::Entry::Vacant(slot) => {
1660 slot.insert(PerWindowInput::new());
1661 true
1662 }
1663 },
1664 InputOp::Close(win) => windows.remove(&win).is_some(),
1665 InputOp::WindowFocus { win, focused, now } => match windows.get_mut(&win) {
1666 Some(w) => {
1667 w.os_focused = focused;
1668 w.settle(win, now, &mut fx)
1669 }
1670 None => false,
1671 },
1672 InputOp::Pointer { win, now, input } => match windows.get_mut(&win) {
1673 Some(w) => {
1674 let (changed, cooked) = w.cook(win, now, input);
1675 fx.push(InputEffect::Pointer(cooked));
1676 changed
1677 }
1678 None => false,
1679 },
1680 InputOp::Deliver { win, input } => match windows.get_mut(&win) {
1681 Some(w) => {
1682 let (changed, target) = w.deliver(win, input, &mut fx);
1683 fx.push(InputEffect::Content { win, target, changed });
1684 changed
1685 }
1686 None => false,
1687 },
1688 InputOp::Wheel { win, input } => {
1689 if let Some(w) = windows.get_mut(&win) {
1690 let target = w.wheel(input);
1691 let changed = target.is_some();
1692 fx.push(InputEffect::Content { win, target, changed });
1693 }
1694 false
1695 }
1696 InputOp::Key { win, now, input } => match windows.get_mut(&win) {
1697 Some(w) => {
1698 let changed = w.key(win, input, next_ticket, &mut fx);
1699 w.settle(win, now, &mut fx) | changed
1700 }
1701 None => false,
1702 },
1703 InputOp::Ime { win, now, input } => match windows.get_mut(&win) {
1704 Some(w) => {
1705 w.ime(win, input, &mut fx);
1706 w.settle(win, now, &mut fx)
1707 }
1708 None => false,
1709 },
1710 InputOp::Paste { win, now, text } => match windows.get_mut(&win) {
1711 Some(w) => {
1712 w.paste(win, text, &mut fx);
1713 w.settle(win, now, &mut fx)
1714 }
1715 None => false,
1716 },
1717 InputOp::Offer { win, text } => {
1718 if let Some(w) = windows.get_mut(&win) {
1719 w.offer = text;
1720 }
1721 false
1722 }
1723 InputOp::Clipboard { win, now, result } => match windows.get_mut(&win) {
1724 Some(w) => {
1725 w.clipboard(win, result, &mut fx);
1726 w.settle(win, now, &mut fx)
1727 }
1728 None => false,
1729 },
1730 InputOp::Focus { win, now, op } => match windows.get_mut(&win) {
1731 Some(w) => {
1732 let changed = w.focus_op(win, op, next_scope, &mut fx);
1733 w.settle(win, now, &mut fx) | changed
1734 }
1735 None => false,
1736 },
1737 InputOp::SetCapture { win, capture } => windows
1738 .get_mut(&win)
1739 .is_some_and(|w| w.set_capture(capture)),
1740 InputOp::BeginFrame { win, now } => {
1741 windows.get_mut(&win).is_some_and(|w| w.begin_frame(now))
1742 }
1743 InputOp::EndFrame { win, now } => match windows.get_mut(&win) {
1744 Some(w) => {
1745 let changed = w.end_frame(win, &mut fx);
1746 w.settle(win, now, &mut fx) | changed
1747 }
1748 None => false,
1749 },
1750 };
1751 if changed {
1752 rev.bump();
1753 }
1754 fx
1755 }
1756
1757 pub fn tick(&mut self, now: Seconds) -> InputEffects {
1762 let mut fx = InputEffects::new();
1763 let mut changed = false;
1764 for (win, w) in &mut self.windows {
1765 if w.armed.is_some_and(|at| at.get() <= now.get()) {
1766 changed |= w.settle(*win, now, &mut fx);
1767 }
1768 }
1769 if changed {
1770 self.rev.bump();
1771 }
1772 fx
1773 }
1774
1775 #[allow(dead_code)]
1782 pub fn registrar(&mut self, win: WindowId) -> Option<&mut InputCoordinator> {
1783 self.windows.get_mut(&win).map(|w| &mut w.coord)
1784 }
1785
1786 #[allow(dead_code)]
1791 pub fn states_mut(&mut self, win: WindowId) -> Option<&mut uzor::app_context::StateRegistry> {
1792 self.windows.get_mut(&win).map(|w| &mut w.states)
1793 }
1794
1795 pub fn compose_parts(
1799 &mut self,
1800 win: WindowId,
1801 ) -> Option<(&mut InputCoordinator, &mut uzor::app_context::StateRegistry, &mut Selectables)> {
1802 self.windows
1803 .get_mut(&win)
1804 .map(|w| (&mut w.coord, &mut w.states, &mut w.reported))
1805 }
1806
1807 #[allow(dead_code)]
1815 pub fn update_selectable(
1816 &mut self,
1817 win: WindowId,
1818 widget: WidgetId,
1819 text: impl Into<String>,
1820 lines: Vec<SelectionLine>,
1821 ) {
1822 if let Some(w) = self.windows.get_mut(&win) {
1823 w.reported.report(widget, text, lines);
1824 }
1825 }
1826
1827 #[allow(dead_code)]
1830 pub fn alias_selectable(&mut self, win: WindowId, member: WidgetId, owner: WidgetId) {
1831 if let Some(w) = self.windows.get_mut(&win) {
1832 w.reported.alias(member, owner);
1833 }
1834 }
1835
1836 pub fn revision(&self) -> Revision {
1838 self.rev
1839 }
1840
1841 pub fn view(&self) -> InputEngineView<'_> {
1843 InputEngineView { e: self }
1844 }
1845}
1846
1847#[derive(Clone, Copy, Debug)]
1849pub struct InputEngineView<'a> {
1850 e: &'a InputEngine,
1851}
1852
1853#[allow(dead_code)]
1855impl<'a> InputEngineView<'a> {
1856 fn w(&self, win: WindowId) -> Option<&'a PerWindowInput> {
1857 self.e.windows.get(&win)
1858 }
1859
1860 pub fn ids(&self) -> impl Iterator<Item = WindowId> + 'a {
1862 self.e.windows.keys().copied()
1863 }
1864
1865 pub fn window(&self, win: WindowId) -> Option<InputView> {
1867 self.w(win).map(|w| InputView {
1868 hovered: w.hover.clone(),
1869 pressed: w.pressed.clone(),
1870 focused: w.focused_id().cloned(),
1871 focus_visible: w.focus_visible,
1872 captured: w.capture.is_some(),
1873 scope_depth: w.scopes.len(),
1874 })
1875 }
1876
1877 pub fn focused(&self, win: WindowId) -> Option<&'a WidgetId> {
1879 self.w(win)?.focused_id()
1880 }
1881
1882 pub fn active_scope(&self, win: WindowId) -> Option<&'a ScopeOwner> {
1884 self.w(win)?.scopes.last().map(|s| &s.owner)
1885 }
1886
1887 pub fn capture(&self, win: WindowId) -> Option<&'a Capture> {
1889 self.w(win)?.capture.as_ref()
1890 }
1891
1892 pub fn cook(&self, win: WindowId) -> Option<&'a CookState> {
1894 self.w(win).map(|w| &w.cook)
1895 }
1896
1897 pub fn clicked(&self, win: WindowId) -> &'a [(WidgetId, u8)] {
1900 self.w(win).map_or(&[], |w| w.clicked.as_slice())
1901 }
1902
1903 pub fn caret_visible(&self, win: WindowId) -> bool {
1906 self.w(win).is_some_and(|w| w.caret_visible)
1907 }
1908
1909 pub fn caret_deadline(&self, win: WindowId) -> Option<Seconds> {
1911 self.w(win)?.armed
1912 }
1913
1914 pub fn text_fields(&self, win: WindowId) -> Option<&'a TextFieldStore> {
1916 self.w(win).map(|w| w.coord.text_fields())
1917 }
1918
1919 pub fn selections(&self, win: WindowId) -> Option<&'a [(WidgetId, TextSelection)]> {
1923 self.w(win).map(|w| w.selections.as_slice())
1924 }
1925
1926 pub fn coordinator(&self, win: WindowId) -> Option<&'a InputCoordinator> {
1928 self.w(win).map(|w| &w.coord)
1929 }
1930
1931 pub fn pending_scroll(&self, win: WindowId) -> (f64, f64) {
1935 self.w(win).map_or((0.0, 0.0), |w| w.pointer.scroll)
1936 }
1937
1938 pub fn pending_scroll_precise(&self, win: WindowId) -> bool {
1941 self.w(win).is_some_and(|w| w.pointer.scroll_precise)
1942 }
1943
1944 pub fn context_click(&self, win: WindowId) -> Option<(f64, f64)> {
1948 self.w(win).and_then(|w| w.pointer.context)
1949 }
1950
1951 pub fn pointer(&self, win: WindowId) -> (Option<(f64, f64)>, bool) {
1952 self.w(win).map_or((None, false), |w| (w.pointer.pos, w.pointer.button_down.is_some()))
1953 }
1954
1955 pub fn press_origin(&self, win: WindowId) -> Option<(f64, f64)> {
1959 let w = self.w(win)?;
1960 w.pointer.button_down?;
1961 w.cook.press_origin.map(|o| (o.x, o.y))
1962 }
1963}
1964
1965#[cfg(test)]
1966mod tests;