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