1use std::any::Any;
13use std::cell::RefCell;
14use std::collections::HashMap;
15use std::fmt::Write as _;
16use std::rc::Rc;
17
18use day_spec::props::*;
19use day_spec::*;
20
21type NativeEvent = (Rc<dyn Fn(NodeId, Event)>, NodeId, Event);
35type VisibleRows = Rc<dyn Fn(&std::collections::HashSet<u64>) -> Vec<u64>>;
37
38thread_local! {
39 static VIEWPORT_ROWS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
41 static VIEWPORTS: RefCell<HashMap<u64, Viewport>> = RefCell::new(HashMap::new());
42 static CELL_HEIGHTS: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
46 static NATIVE_EVENTS: RefCell<Vec<NativeEvent>> = RefCell::new(Vec::new());
49 static MOCK_WINDOW: std::cell::Cell<Size> = const { std::cell::Cell::new(Size::new(0.0, 0.0)) };
51}
52
53struct Viewport {
54 visible: VisibleRows,
57 bind_row: Rc<dyn Fn(u64, RawHandle)>,
58 recycle: Rc<dyn Fn(RawHandle)>,
59 cell_height: Option<Rc<dyn Fn(RawHandle) -> f64>>,
61 expanded: std::collections::HashSet<u64>,
63 start: usize,
65 to_end: bool,
67 bound: usize,
69 dirty: bool,
70}
71
72fn viewport_cell(host: u64, slot: usize) -> RawHandle {
74 ((1u64 << 40) + host * 4096 + slot as u64) as RawHandle
75}
76
77fn viewport_slot(cell: u64) -> Option<(u64, usize)> {
79 let offset = cell.checked_sub(1u64 << 40)?;
80 Some((offset / 4096, (offset % 4096) as usize))
81}
82
83fn viewport_cell_top(cell: u64) -> f64 {
85 let Some((host, slot)) = viewport_slot(cell) else {
86 return 0.0;
87 };
88 CELL_HEIGHTS.with(|h| {
89 let h = h.borrow();
90 (0..slot)
91 .map(|s| {
92 h.get(&(viewport_cell(host, s) as u64))
93 .copied()
94 .unwrap_or(0.0)
95 })
96 .sum()
97 })
98}
99
100fn window_frame(s: &MockState, id: u64) -> Rect {
103 let Some(w) = s.widgets.get(&id) else {
104 return Rect::default();
105 };
106 let mut frame = w.frame;
107 let mut current = id;
108 for _ in 0..4096 {
110 let next = match s.widgets.get(¤t) {
111 Some(w) if w.kind == kinds::LIST_CELL => viewport_slot(current).map(|(host, _)| {
112 frame.origin.y += viewport_cell_top(current);
113 host
114 }),
115 _ => s
116 .widgets
117 .iter()
118 .find(|(_, p)| p.children.contains(¤t))
119 .map(|(k, _)| *k),
120 };
121 let Some(parent) = next else {
122 break;
123 };
124 if let Some(p) = s.widgets.get(&parent) {
125 frame.origin.x += p.frame.origin.x;
126 frame.origin.y += p.frame.origin.y;
127 }
128 current = parent;
129 }
130 frame
131}
132
133fn viewport_touch(host: u64, f: impl FnOnce(&mut Viewport)) {
134 VIEWPORTS.with(|v| {
135 if let Some(port) = v.borrow_mut().get_mut(&host) {
136 f(port);
137 port.dirty = true;
138 }
139 });
140}
141
142fn viewport_flush() {
144 let rows = VIEWPORT_ROWS.with(std::cell::Cell::get);
145 if rows == 0 {
146 return;
147 }
148 let events = NATIVE_EVENTS.with(|q| std::mem::take(&mut *q.borrow_mut()));
149 for (sink, node, event) in events {
150 sink(node, event);
151 }
152 let dirty: Vec<u64> = VIEWPORTS.with(|v| {
153 v.borrow()
154 .iter()
155 .filter(|(_, p)| p.dirty)
156 .map(|(h, _)| *h)
157 .collect()
158 });
159 for host in dirty {
160 let Some((visible, bind_row, recycle, cell_height, expanded, start, to_end, bound)) =
161 VIEWPORTS.with(|v| {
162 let mut v = v.borrow_mut();
163 let p = v.get_mut(&host)?;
164 p.dirty = false;
165 Some((
166 p.visible.clone(),
167 p.bind_row.clone(),
168 p.recycle.clone(),
169 p.cell_height.clone(),
170 p.expanded.clone(),
171 p.start,
172 p.to_end,
173 p.bound,
174 ))
175 })
176 else {
177 continue;
178 };
179 let rows_now = visible(&expanded);
180 let total = rows_now.len();
181 let start = if to_end {
182 total.saturating_sub(rows)
183 } else {
184 start.min(total.saturating_sub(rows))
185 };
186 let count = rows.min(total - start.min(total));
187 for slot in 0..count {
188 let cell = viewport_cell(host, slot);
189 bind_row(rows_now[start + slot], cell);
190 if let Some(height) = &cell_height {
192 let laid = height(cell);
193 CELL_HEIGHTS.with(|h| h.borrow_mut().insert(cell as u64, laid));
194 }
195 }
196 for slot in count..bound {
198 recycle(viewport_cell(host, slot));
199 }
200 VIEWPORTS.with(|v| {
201 if let Some(p) = v.borrow_mut().get_mut(&host) {
202 p.start = start;
203 p.to_end = false;
204 p.bound = count;
205 }
206 });
207 }
208}
209
210#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
211pub struct MockHandle(pub u64);
212
213#[derive(Default, Debug, Clone)]
214pub struct MockWidget {
215 pub kind: &'static str,
216 pub node: u64,
217 pub text: String,
218 pub placeholder: String,
219 pub selection: Option<day_spec::props::TextSelection>,
222 pub value: f64,
223 pub flag: bool,
224 pub half: bool,
227 pub enabled: bool,
228 pub selected: bool,
230 pub editable: bool,
232 pub selectable: bool,
233 pub spellcheck: bool,
234 pub input_traits: Option<day_spec::InputTraits>,
237 pub cursor: Option<day_spec::Cursor>,
239 pub children: Vec<u64>,
240 pub frame: Rect,
241 pub a11y: A11yProps,
242 pub scroll_content: Size,
243 pub scroll_offset: Point,
246 pub ops: Vec<DrawOp>,
247 pub background: Option<Color>,
249 pub corner_radius: f64,
250 pub clips: bool,
251 pub surface_role: Option<day_spec::SurfaceRole>,
253 pub font: Option<day_spec::FontSpec>,
255 pub runs: Vec<day_spec::TextRun>,
259 pub focused: bool,
261 pub opacity: Option<f64>,
263 pub transform: Option<day_spec::Transform>,
265 pub last_anim: Option<AnimSpec>,
268 pub presentation: Option<day_spec::props::NavPresentation>,
272 pub selected_page: Option<usize>,
276 pub nav_depth: usize,
279 pub nav_guarded: bool,
282}
283
284#[derive(Clone, Debug)]
287pub struct MockWindow {
288 pub handle: u64,
290 pub node: NodeId,
292 pub title: String,
293 pub size: Size,
294 pub kind: String,
296 pub tabbing: day_spec::WindowTabbing,
298 pub open: bool,
299 pub focused: bool,
300 pub fit_size: Option<Size>,
304}
305
306#[derive(Default)]
307pub struct MockState {
308 pub system_colors: Option<[day_spec::Color; 5]>,
310 pub ui_busy: bool,
312 next: u64,
313 pub widgets: HashMap<u64, MockWidget>,
314 pub log: Vec<String>,
315 pub sink: Option<Rc<dyn Fn(NodeId, Event)>>,
324 pub bitmaps: HashMap<u64, day_spec::BitmapInfo>,
328 pub measure_calls: usize,
330 pub scroll_bar_inset: f64,
333 pub list_sources: HashMap<u64, ListSource>,
336 pub tree_sources: HashMap<u64, day_spec::TreeSource>,
339 pub emulated_trees: bool,
341 pub app_menu: Vec<String>,
343 pub dock_menu: Vec<String>,
345 pub drag_regions: std::collections::HashSet<u64>,
347 pub status_items: Vec<day_spec::StatusItemSpec>,
349 pub app_progress: day_spec::AppProgress,
351 pub dock_visible: Option<bool>,
353 pub keep_running: bool,
355 pub launcher_shortcuts: Vec<day_spec::LauncherShortcut>,
357 pub window_changes: Vec<(u64, day_spec::WindowChange)>,
360 pub window_states: HashMap<u64, day_spec::WindowState>,
362 pub decline_window_states: bool,
365 pub toolbar_edits: Vec<Vec<day_spec::ToolbarOp>>,
368 pub toolbar: day_spec::ToolbarMirror,
370 pub no_toolbar_search: bool,
373 pub decline_toolbar_edits: bool,
375 pub toolbar_patches: Vec<day_spec::ToolbarPatch>,
377 pub context_menus: HashMap<u64, Vec<String>>,
379 pub context_menu_providers: HashMap<u64, day_spec::ContextMenuFn>,
381 pub button_menus: HashMap<u64, day_spec::ContextMenuFn>,
384 pub shares: Vec<(day_spec::share::ShareSpec, Option<u64>)>,
387 pub system_back: bool,
390 pub windows: Vec<MockWindow>,
392 pub no_multi_window: bool,
394 pub defer_window_close: bool,
396 pub native_window_tabs: bool,
398 pub native_list_items: bool,
401 pub window_tab_groups: Vec<Vec<NodeId>>,
403 pub announcements: Vec<(String, bool)>,
405 pub reduce_motion: bool,
409 pub secure_class_swap: bool,
413 pub nav_split: bool,
416 pub no_nav_tabs: bool,
421 pub no_nav_reorder: bool,
423 pub native_nav_reorder: bool,
427 pub desktop_idiom: bool,
431 pub nav_content_list: Support,
435 pub pending_windows: bool,
438 pub pending_opens: Vec<(NodeId, String, String)>,
440 #[allow(clippy::type_complexity)]
442 pub describers: Vec<Box<dyn Fn(&dyn Any) -> Option<String>>>,
443}
444
445impl MockState {
446 fn log(&mut self, s: String) {
447 self.log.push(s);
448 }
449}
450
451pub struct MockToolkit {
454 pub state: Rc<RefCell<MockState>>,
455}
456
457#[derive(Clone)]
458pub struct MockProbe {
459 pub state: Rc<RefCell<MockState>>,
460}
461
462impl MockToolkit {
463 #[must_use]
464 pub fn new() -> (Self, MockProbe) {
465 VIEWPORT_ROWS.with(|r| r.set(0));
467 VIEWPORTS.with(|v| v.borrow_mut().clear());
468 NATIVE_EVENTS.with(|q| q.borrow_mut().clear());
469 day_async::set_blocking_inline(true);
472 let state = Rc::new(RefCell::new(MockState::default()));
473 (
474 MockToolkit {
475 state: state.clone(),
476 },
477 MockProbe { state },
478 )
479 }
480}
481
482impl MockProbe {
483 #[must_use]
484 pub fn log(&self) -> Vec<String> {
485 self.state.borrow().log.clone()
486 }
487 pub fn clear_log(&self) {
488 let mut s = self.state.borrow_mut();
489 s.log.clear();
490 s.measure_calls = 0;
491 }
492 pub fn measure_calls(&self) -> usize {
493 self.state.borrow().measure_calls
494 }
495 pub fn describe_patch<T: 'static>(&self, f: impl Fn(&T) -> String + 'static) {
508 self.state
509 .borrow_mut()
510 .describers
511 .push(Box::new(move |any| any.downcast_ref::<T>().map(&f)));
512 }
513 #[must_use]
515 pub fn mutations(&self) -> Vec<String> {
516 self.state
517 .borrow()
518 .log
519 .iter()
520 .filter(|l| !l.starts_with("measure"))
521 .cloned()
522 .collect()
523 }
524 #[must_use]
525 pub fn widget(&self, h: MockHandle) -> MockWidget {
526 self.state
527 .borrow()
528 .widgets
529 .get(&h.0)
530 .cloned()
531 .unwrap_or_default()
532 }
533 #[must_use]
534 pub fn find_by_kind(&self, kind: &str) -> Vec<(MockHandle, MockWidget)> {
535 let mut v: Vec<_> = self
536 .state
537 .borrow()
538 .widgets
539 .iter()
540 .filter(|(_, w)| w.kind == kind)
541 .map(|(k, w)| (MockHandle(*k), w.clone()))
542 .collect();
543 v.sort_by_key(|(h, _)| h.0);
544 v
545 }
546 pub fn list_first_visible(&self, host: MockHandle, index: usize) {
548 let callback = self
549 .state
550 .borrow()
551 .list_sources
552 .get(&host.0)
553 .and_then(|source| source.first_visible.clone());
554 if let Some(callback) = callback {
555 callback(index);
556 }
557 }
558
559 #[must_use]
561 pub fn list_len(&self, host: MockHandle) -> usize {
562 let f = self
563 .state
564 .borrow()
565 .list_sources
566 .get(&host.0)
567 .map(|s| s.len.clone());
568 f.map_or(0, |f| f())
569 }
570
571 pub fn list_bind(&self, host: MockHandle, index: usize, cell: MockHandle) {
576 let f = self
577 .state
578 .borrow()
579 .list_sources
580 .get(&host.0)
581 .map(|s| s.bind_row.clone());
582 if let Some(f) = f {
583 f(index, cell.0 as RawHandle);
584 }
585 }
586
587 pub fn list_bind_pinned(&self, host: MockHandle, index: usize, cell: MockHandle) {
590 let f = self
591 .state
592 .borrow()
593 .list_sources
594 .get(&host.0)
595 .map(|s| s.bind_pinned.clone());
596 if let Some(f) = f {
597 f(index, cell.0 as RawHandle);
598 }
599 }
600
601 pub fn set_native_behavior(&self, viewport_rows: usize) {
611 VIEWPORT_ROWS.with(|r| r.set(viewport_rows));
612 }
613
614 pub fn list_recycle(&self, host: MockHandle, cell: MockHandle) {
615 let f = self
616 .state
617 .borrow()
618 .list_sources
619 .get(&host.0)
620 .map(|s| s.recycle.clone());
621 if let Some(f) = f {
622 f(cell.0 as RawHandle);
623 }
624 }
625
626 pub fn list_release(&self, host: MockHandle, cell: MockHandle) {
631 let f = self
632 .state
633 .borrow()
634 .list_sources
635 .get(&host.0)
636 .map(|s| s.release.clone());
637 if let Some(f) = f {
638 f(cell.0 as RawHandle);
639 }
640 }
641
642 #[must_use]
646 pub fn list_can_move(&self, host: MockHandle, from: usize, to: usize) -> i64 {
647 let f = self
648 .state
649 .borrow()
650 .list_sources
651 .get(&host.0)
652 .and_then(|s| s.reorder.as_ref().map(|r| r.can_move.clone()));
653 f.map_or(i64::MIN, |f| f(from, to))
654 }
655
656 #[must_use]
660 pub fn list_can_delete(&self, host: MockHandle, index: usize) -> Option<bool> {
661 let f = self
662 .state
663 .borrow()
664 .list_sources
665 .get(&host.0)
666 .and_then(|s| s.delete.as_ref().map(|d| d.can_delete.clone()));
667 f.map(|f| f(index))
668 }
669
670 #[must_use]
674 pub fn list_delete(&self, host: MockHandle, index: usize) -> bool {
675 let d = self
676 .state
677 .borrow()
678 .list_sources
679 .get(&host.0)
680 .and_then(|s| s.delete.clone());
681 let Some(d) = d else {
682 self.state
683 .borrow_mut()
684 .log(format!("list delete unsupported {index}"));
685 return false;
686 };
687 if !(d.can_delete)(index) {
688 self.state
689 .borrow_mut()
690 .log(format!("list delete denied {index}"));
691 return false;
692 }
693 (d.delete_row)(index);
694 true
695 }
696
697 #[must_use]
701 pub fn list_swipe_actions(
702 &self,
703 host: MockHandle,
704 index: usize,
705 edge: SwipeEdge,
706 ) -> Option<Vec<ListSwipeAction>> {
707 let f = self
708 .state
709 .borrow()
710 .list_sources
711 .get(&host.0)
712 .and_then(|s| s.swipe.as_ref().map(|sw| sw.actions_at.clone()));
713 f.map(|f| f(index, edge))
714 }
715
716 #[must_use]
721 pub fn list_swipe(
722 &self,
723 host: MockHandle,
724 index: usize,
725 edge: SwipeEdge,
726 action: usize,
727 ) -> bool {
728 let sw = self
729 .state
730 .borrow()
731 .list_sources
732 .get(&host.0)
733 .and_then(|s| s.swipe.clone());
734 let Some(sw) = sw else {
735 self.state
736 .borrow_mut()
737 .log(format!("list swipe unsupported {index}"));
738 return false;
739 };
740 if (sw.actions_at)(index, edge).len() <= action {
741 self.state
742 .borrow_mut()
743 .log(format!("list swipe no action {index}"));
744 return false;
745 }
746 (sw.perform)(index, edge, action);
747 true
748 }
749
750 #[must_use]
754 pub fn list_move(&self, host: MockHandle, from: usize, to: usize) -> bool {
755 let r = self
756 .state
757 .borrow()
758 .list_sources
759 .get(&host.0)
760 .and_then(|s| s.reorder.clone());
761 let Some(r) = r else {
762 self.state
763 .borrow_mut()
764 .log(format!("list move unsupported {from}->{to}"));
765 return false;
766 };
767 let accepted = (r.can_move)(from, to);
768 if accepted < 0 {
769 self.state
770 .borrow_mut()
771 .log(format!("list move denied {from}->{to}"));
772 return false;
773 }
774 (r.move_row)(from, accepted as usize);
775 self.state
776 .borrow_mut()
777 .log(format!("list move {from}->{accepted}"));
778 true
779 }
780
781 #[must_use]
784 pub fn tree_children(&self, host: MockHandle, parent: Option<u64>) -> Vec<u64> {
785 let fns = self
786 .state
787 .borrow()
788 .tree_sources
789 .get(&host.0)
790 .map(|s| (s.children_len.clone(), s.child_token.clone()));
791 let Some((len, tok)) = fns else {
792 return Vec::new();
793 };
794 (0..len(parent)).map(|i| tok(parent, i)).collect()
795 }
796
797 #[must_use]
799 pub fn tree_expandable(&self, host: MockHandle, token: u64) -> bool {
800 let f = self
801 .state
802 .borrow()
803 .tree_sources
804 .get(&host.0)
805 .map(|s| s.expandable.clone());
806 f.is_some_and(|f| f(token))
807 }
808
809 #[must_use]
811 pub fn tree_type_text(&self, host: MockHandle, token: u64) -> String {
812 let f = self
813 .state
814 .borrow()
815 .tree_sources
816 .get(&host.0)
817 .map(|s| s.type_select_text.clone());
818 f.map_or_default(|f| f(token))
819 }
820
821 pub fn tree_bind(&self, host: MockHandle, token: u64, cell: MockHandle) {
825 let f = self
826 .state
827 .borrow()
828 .tree_sources
829 .get(&host.0)
830 .map(|s| s.bind_row.clone());
831 if let Some(f) = f {
832 f(token, cell.0 as RawHandle);
833 }
834 }
835
836 #[must_use]
839 pub fn tree_can_move(
840 &self,
841 host: MockHandle,
842 token: u64,
843 parent: Option<u64>,
844 index: Option<usize>,
845 ) -> Option<day_spec::MoveVerdict> {
846 let f = self
847 .state
848 .borrow()
849 .tree_sources
850 .get(&host.0)
851 .and_then(|s| s.moves.as_ref().map(|m| m.can_move.clone()));
852 f.map(|f| f(token, parent, index))
853 }
854
855 #[must_use]
858 pub fn tree_move(
859 &self,
860 host: MockHandle,
861 token: u64,
862 parent: Option<u64>,
863 index: Option<usize>,
864 ) -> bool {
865 let m = self
866 .state
867 .borrow()
868 .tree_sources
869 .get(&host.0)
870 .and_then(|s| s.moves.clone());
871 let Some(m) = m else {
872 self.state
873 .borrow_mut()
874 .log(format!("tree move unsupported {token}"));
875 return false;
876 };
877 if (m.can_move)(token, parent, index) == day_spec::MoveVerdict::Deny {
878 self.state
879 .borrow_mut()
880 .log(format!("tree move denied {token}"));
881 return false;
882 }
883 (m.move_node)(token, parent, index);
884 self.state
885 .borrow_mut()
886 .log(format!("tree move {token} -> {parent:?}@{index:?}"));
887 true
888 }
889
890 pub fn emit(&self, node: NodeId, event: Event) {
896 let sink = self.state.borrow().sink.clone();
897 match sink {
898 Some(sink) => sink(node, event),
899 None => panic!("day-mock: no event sink installed"),
900 }
901 }
902
903 #[must_use]
908 pub fn press_menu_button(&self, button: u64) -> Option<Vec<day_spec::MenuItem>> {
909 let provider = self.state.borrow().button_menus.get(&button).cloned()?;
910 day_spec::resolve_button_menu(&provider, || {
911 self.state.borrow().button_menus.contains_key(&button)
912 })
913 }
914
915 #[must_use]
917 pub fn shares(&self) -> Vec<(day_spec::share::ShareSpec, Option<u64>)> {
918 self.state.borrow().shares.clone()
919 }
920
921 #[must_use]
924 pub fn system_back_armed(&self) -> bool {
925 self.state.borrow().system_back
926 }
927
928 #[must_use]
931 pub fn choose_share_action(&self, index: usize) -> bool {
932 let id = self
933 .state
934 .borrow()
935 .shares
936 .last()
937 .and_then(|(spec, _)| spec.actions.get(index))
938 .map(|a| a.id);
939 match id {
940 Some(id) => {
941 self.emit(day_spec::WINDOW_NODE, day_spec::Event::MenuAction(id));
942 true
943 }
944 None => false,
945 }
946 }
947
948 pub fn set_no_toolbar_search(&self, v: bool) {
952 self.state.borrow_mut().no_toolbar_search = v;
953 }
954
955 pub fn set_native_list_items(&self, v: bool) {
957 self.state.borrow_mut().native_list_items = v;
958 }
959
960 pub fn set_decline_toolbar_edits(&self, v: bool) {
962 self.state.borrow_mut().decline_toolbar_edits = v;
963 }
964
965 #[must_use]
967 pub fn toolbar_edits(&self) -> Vec<Vec<day_spec::ToolbarOp>> {
968 self.state.borrow().toolbar_edits.clone()
969 }
970
971 #[must_use]
973 pub fn toolbar_items(&self) -> Vec<day_spec::ToolbarItem> {
974 self.state.borrow().toolbar.items().to_vec()
975 }
976
977 #[must_use]
979 pub fn toolbar_patches(&self) -> Vec<day_spec::ToolbarPatch> {
980 self.state.borrow().toolbar_patches.clone()
981 }
982
983 #[must_use]
985 pub fn windows(&self) -> Vec<MockWindow> {
986 self.state.borrow().windows.clone()
987 }
988
989 #[must_use]
991 pub fn dock_menu(&self) -> Vec<String> {
992 self.state.borrow().dock_menu.clone()
993 }
994
995 #[must_use]
997 pub fn window_changes(&self) -> Vec<(u64, day_spec::WindowChange)> {
998 self.state.borrow().window_changes.clone()
999 }
1000
1001 #[must_use]
1003 pub fn status_items(&self) -> Vec<day_spec::StatusItemSpec> {
1004 self.state.borrow().status_items.clone()
1005 }
1006
1007 #[must_use]
1009 pub fn keep_running(&self) -> bool {
1010 self.state.borrow().keep_running
1011 }
1012
1013 #[must_use]
1015 pub fn is_drag_region(&self, handle: u64) -> bool {
1016 self.state.borrow().drag_regions.contains(&handle)
1017 }
1018
1019 pub fn set_decline_window_states(&self, v: bool) {
1021 self.state.borrow_mut().decline_window_states = v;
1022 }
1023
1024 pub fn set_reduce_motion(&self, v: bool) {
1027 self.state.borrow_mut().reduce_motion = v;
1028 }
1029
1030 pub fn set_secure_class_swap(&self, v: bool) {
1033 self.state.borrow_mut().secure_class_swap = v;
1034 }
1035
1036 pub fn set_no_multi_window(&self, v: bool) {
1038 self.state.borrow_mut().no_multi_window = v;
1039 }
1040
1041 pub fn set_nav_split(&self, v: bool) {
1045 self.state.borrow_mut().nav_split = v;
1046 }
1047
1048 pub fn set_no_nav_reorder(&self, v: bool) {
1050 self.state.borrow_mut().no_nav_reorder = v;
1051 }
1052
1053 pub fn set_native_nav_reorder(&self, v: bool) {
1055 self.state.borrow_mut().native_nav_reorder = v;
1056 }
1057
1058 pub fn set_no_nav_tabs(&self, v: bool) {
1060 self.state.borrow_mut().no_nav_tabs = v;
1061 }
1062
1063 pub fn set_desktop_idiom(&self, v: bool) {
1068 self.state.borrow_mut().desktop_idiom = v;
1069 }
1070
1071 pub fn set_nav_content_list(&self, v: day_spec::Support) {
1075 self.state.borrow_mut().nav_content_list = v;
1076 }
1077
1078 pub fn set_pending_windows(&self, v: bool) {
1081 self.state.borrow_mut().pending_windows = v;
1082 }
1083
1084 #[must_use]
1089 pub fn complete_window(&self, node: NodeId, size: Size) -> Option<day_spec::RawHandle> {
1090 let mut s = self.state.borrow_mut();
1091 let i = s.pending_opens.iter().position(|(n, _, _)| *n == node)?;
1092 let (node, title, kind) = s.pending_opens.remove(i);
1093 s.next += 1;
1094 let h = s.next;
1095 s.widgets.insert(
1096 h,
1097 MockWidget {
1098 kind: kinds::CONTAINER,
1099 node: node.0,
1100 enabled: true,
1101 ..Default::default()
1102 },
1103 );
1104 s.windows.push(MockWindow {
1105 handle: h,
1106 node,
1107 title,
1108 size,
1109 kind,
1110 tabbing: day_spec::WindowTabbing::Automatic,
1111 open: true,
1112 focused: false,
1113 fit_size: None,
1114 });
1115 s.log(format!("window_ready #{h} {}", fmt_size(size)));
1116 Some(h as day_spec::RawHandle)
1117 }
1118
1119 pub fn resize_window(&self, node: NodeId, size: Size) {
1122 {
1123 let mut s = self.state.borrow_mut();
1124 if let Some(w) = s.windows.iter_mut().find(|w| w.node == node) {
1125 w.size = size;
1126 }
1127 }
1128 self.emit(node, Event::WindowResized(size));
1129 }
1130
1131 pub fn set_defer_window_close(&self, defer: bool) {
1134 self.state.borrow_mut().defer_window_close = defer;
1135 }
1136
1137 pub fn close_window_natively(&self, node: NodeId) {
1140 {
1141 let mut s = self.state.borrow_mut();
1142 if let Some(w) = s.windows.iter_mut().find(|w| w.node == node) {
1143 w.open = false;
1144 }
1145 }
1146 self.emit(node, Event::WindowClosed);
1147 }
1148
1149 #[must_use]
1151 pub fn log_len(&self) -> usize {
1152 self.state.borrow().log.len()
1153 }
1154
1155 #[must_use]
1157 pub fn log_since(&self, mark: usize) -> Vec<String> {
1158 self.state.borrow().log[mark..].to_vec()
1159 }
1160}
1161
1162fn fmt_size(s: Size) -> String {
1163 format!("{}x{}", s.width, s.height)
1164}
1165fn fmt_rect(r: Rect) -> String {
1166 format!(
1167 "({},{} {}x{})",
1168 r.origin.x, r.origin.y, r.size.width, r.size.height
1169 )
1170}
1171
1172pub const MOCK_LINE_H: f64 = 16.0;
1175
1176pub const MOCK_IMAGE_W: f64 = 64.0;
1180pub const MOCK_IMAGE_H: f64 = 48.0;
1181pub const MOCK_ENCODE_FORMATS: [day_spec::ImageFormat; 2] =
1184 [day_spec::ImageFormat::Png, day_spec::ImageFormat::Jpeg];
1185
1186fn describe_image_source(source: &day_spec::ImageSource) -> String {
1189 match source {
1190 day_spec::ImageSource::Named(name) => name.clone(),
1191 day_spec::ImageSource::Bytes(b) => format!("bytes:{}", b.len()),
1192 day_spec::ImageSource::Decoded(id) => format!("bitmap:{}", id.0),
1193 }
1194}
1195
1196pub fn text_size(text: &str, proposal: Proposal, wraps: bool, scale: f64) -> Size {
1197 let needed = 8.0 * scale * text.chars().count() as f64;
1198 let line = MOCK_LINE_H * scale;
1199 match (proposal.width, wraps) {
1200 (Some(w), true) if needed > w && w > 0.0 => {
1201 let lines = (needed / w).ceil();
1202 Size::new(w, line * lines)
1203 }
1204 _ => Size::new(needed, line),
1205 }
1206}
1207
1208#[must_use]
1212pub fn font_scale(style: Font) -> f64 {
1213 let points = match style {
1214 Font::LargeTitle => 34.0,
1215 Font::Title => 28.0,
1216 Font::Title2 => 22.0,
1217 Font::Title3 => 20.0,
1218 Font::Headline | Font::Body => 17.0,
1219 Font::Subheadline => 15.0,
1220 Font::Callout => 16.0,
1221 Font::Footnote => 13.0,
1222 Font::Caption => 12.0,
1223 Font::Caption2 => 11.0,
1224 Font::System(pt) | Font::Custom(_, pt) => pt,
1225 };
1226 points / 17.0
1227}
1228
1229impl MockToolkit {
1230 fn raise(&self, event: Event) {
1237 let sink = self.state.borrow().sink.clone();
1238 match sink {
1239 Some(sink) => sink(NodeId(0), event),
1240 None => self
1241 .state
1242 .borrow_mut()
1243 .log(format!("dropped {event:?}: no event sink installed")),
1244 }
1245 }
1246}
1247
1248impl Toolkit for MockToolkit {
1249 fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
1250 let colors = self.state.borrow().system_colors;
1251 colors.map_or_else(
1252 || role.fallback(self.dark_mode()),
1253 |colors| colors[role as usize],
1254 )
1255 }
1256
1257 type Handle = MockHandle;
1258
1259 #[expect(
1260 clippy::match_same_arms,
1261 reason = "each capability keeps its own arm, with a comment saying why the mock answers it"
1262 )]
1263 fn capability(&self, cap: Cap) -> Support {
1264 match cap {
1265 Cap::Snapshot => Support::Native,
1266 Cap::Toolbar | Cap::Dialogs if VIEWPORT_ROWS.with(std::cell::Cell::get) > 0 => {
1271 Support::Native
1272 }
1273 Cap::ListRecycling if VIEWPORT_ROWS.with(std::cell::Cell::get) > 0 => Support::Native,
1275 Cap::ToolbarSearch => {
1278 if self.state.borrow().no_toolbar_search {
1279 Support::Unsupported
1280 } else {
1281 Support::Native
1282 }
1283 }
1284 Cap::ImageDecode | Cap::ImageEncode => Support::Native,
1290 Cap::CanvasBitmap => Support::Native,
1294 Cap::Cursor => Support::Native,
1296 Cap::ListItem => {
1302 if self.state.borrow().native_list_items {
1303 Support::Native
1304 } else {
1305 Support::Unsupported
1306 }
1307 }
1308 Cap::WindowTabbing => {
1309 if self.state.borrow().native_window_tabs {
1310 Support::Native
1311 } else {
1312 Support::Unsupported
1313 }
1314 }
1315 Cap::WindowStates
1316 | Cap::WindowFullscreen
1317 | Cap::ContentProtection
1318 | Cap::DockMenu
1319 | Cap::DragRegion
1320 | Cap::StatusItem
1321 | Cap::AppProgress
1322 | Cap::DockVisibility
1323 | Cap::Monitors
1324 | Cap::DynamicShortcuts
1325 | Cap::WindowGeometry
1326 | Cap::WindowPosition
1327 | Cap::WindowLevel
1328 | Cap::WindowAppearance
1329 | Cap::RequestAttention => Support::Native,
1330 Cap::FontList => Support::Emulated,
1332 Cap::Announce => Support::Native,
1333 Cap::ReduceMotion => Support::Native,
1334 Cap::BaselineAlignment => Support::Native,
1336 Cap::TextEditable | Cap::TextSelectable | Cap::TextSpellCheck => Support::Native,
1338 Cap::TextRuns => Support::Native,
1343 Cap::Animation => Support::Native,
1345 Cap::Cover => Support::Native,
1348 Cap::StatusBarHidden => Support::Native,
1350 Cap::ListReorder => Support::Native,
1353 Cap::NavReorder => {
1354 let s = self.state.borrow();
1355 if s.no_nav_reorder {
1356 Support::Unsupported
1357 } else if s.native_nav_reorder {
1358 Support::Native
1359 } else {
1360 Support::Emulated
1361 }
1362 }
1363 Cap::Tree | Cap::TreeSections if self.state.borrow().emulated_trees => {
1365 Support::Emulated
1366 }
1367 Cap::Tree | Cap::TreeSections | Cap::TreeMove => Support::Native,
1368 Cap::NavSplit | Cap::NavRepresent => {
1372 if self.state.borrow().nav_split {
1373 Support::Native
1374 } else {
1375 Support::Unsupported
1376 }
1377 }
1378 Cap::NavContentList => self.state.borrow().nav_content_list,
1381 Cap::NavTabs => {
1385 if self.state.borrow().no_nav_tabs {
1386 Support::Unsupported
1387 } else {
1388 Support::Native
1389 }
1390 }
1391 Cap::NavTabsAdaptive => {
1393 let st = self.state.borrow();
1394 if st.no_nav_tabs || st.desktop_idiom {
1395 Support::Unsupported
1396 } else {
1397 Support::Native
1398 }
1399 }
1400 Cap::MultiWindow => {
1402 if self.state.borrow().no_multi_window {
1403 Support::Unsupported
1404 } else {
1405 Support::Native
1406 }
1407 }
1408 _ => Support::Unsupported,
1409 }
1410 }
1411
1412 fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> MockHandle {
1413 let mut s = self.state.borrow_mut();
1414 s.next += 1;
1415 let h = s.next;
1416 let mut w = MockWidget {
1417 kind,
1418 node: id.0,
1419 enabled: true,
1420 ..Default::default()
1421 };
1422 let mut detail = String::new();
1423 if let Some(p) = props.downcast_ref::<CoverProps>() {
1424 w.half = p.half;
1425 detail = format!(" sheet={} half={}", p.sheet, p.half);
1426 } else if let Some(p) = props.downcast_ref::<ListItemProps>() {
1427 w.text.clone_from(&p.title);
1428 w.flag = p.checked;
1429 detail = format!(
1430 " title={:?} subtitle={:?} detail={:?} icon={:?} checked={}",
1431 p.title, p.subtitle, p.detail, p.icon, p.checked
1432 );
1433 } else if let Some(p) = props.downcast_ref::<LabelProps>() {
1434 w.text.clone_from(&p.text);
1435 w.flag = p.wraps;
1436 w.font = Some(p.font);
1437 w.runs.clone_from(&p.runs);
1438 detail = format!(" text={:?}", p.text);
1439 } else if let Some(p) = props.downcast_ref::<ButtonProps>() {
1440 w.text.clone_from(&p.title);
1441 w.enabled = p.enabled;
1442 w.selected = p.selected;
1443 detail = format!(" title={:?}", p.title);
1444 } else if let Some(p) = props.downcast_ref::<ToggleProps>() {
1445 w.flag = p.on;
1446 w.enabled = p.enabled;
1447 } else if let Some(p) = props.downcast_ref::<SliderProps>() {
1448 w.value = p.value;
1449 w.enabled = p.enabled;
1450 } else if let Some(p) = props.downcast_ref::<TextFieldProps>() {
1451 w.text.clone_from(&p.text);
1452 w.placeholder.clone_from(&p.placeholder);
1453 w.enabled = p.enabled;
1454 } else if let Some(p) = props.downcast_ref::<CanvasProps>() {
1455 w.ops.clone_from(&p.ops);
1456 } else if let Some(p) = props.downcast_ref::<ContainerProps>() {
1457 w.background = p.background;
1458 w.corner_radius = p.corner_radius;
1459 w.clips = p.clips;
1460 w.surface_role = p.role;
1461 if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
1462 detail = format!(
1463 " bg={:?} radius={} clips={}",
1464 p.background, p.corner_radius, p.clips
1465 );
1466 }
1467 } else if let Some(p) = props.downcast_ref::<ImageProps>() {
1468 w.text = describe_image_source(&p.source);
1471 w.flag = p.template;
1473 detail = format!(" source={}", w.text);
1474 } else if let Some(p) = props.downcast_ref::<ProgressProps>() {
1475 w.flag = p.value.is_none();
1477 w.value = p.value.unwrap_or(0.0);
1478 detail = format!(" value={:?}", p.value);
1479 } else if let Some(p) = props.downcast_ref::<NavProps>() {
1480 w.text.clone_from(&p.title);
1481 w.flag = p.presentation.is_split();
1482 w.presentation = Some(p.presentation);
1483 detail = match p.list_width {
1486 Some(w) => format!(
1487 " title={:?} presentation={:?} list_width={w} list_visible={}",
1488 p.title, p.presentation, p.list_visible
1489 ),
1490 None => format!(" title={:?} presentation={:?}", p.title, p.presentation),
1491 };
1492 } else if let Some(p) = props.downcast_ref::<NavPageProps>() {
1493 w.text.clone_from(&p.title);
1494 w.flag = p.pane == day_spec::props::Pane::Sidebar;
1497 detail = format!(" title={:?} pane={:?}", p.title, p.pane);
1498 } else if let Some(p) = props.downcast_ref::<NavMenuProps>() {
1499 w.text = p.items.join("|");
1500 w.value = p.selected.map_or(-1.0, |i| i as f64);
1501 detail = format!(
1502 " items={:?} selected={:?} movable={:?}",
1503 p.items, p.selected, p.movable
1504 );
1505 if p.regroup {
1507 let _ = write!(detail, " regroup sorted={:?}", p.sorted);
1508 }
1509 } else if let Some(p) = props.downcast_ref::<PickerProps>() {
1510 w.text = p.options.join("|");
1511 w.value = p.selected as f64;
1512 w.enabled = p.enabled;
1513 detail = format!(" options={:?} selected={}", p.options, p.selected);
1514 } else if let Some(p) = props.downcast_ref::<TextAreaProps>() {
1515 w.text.clone_from(&p.text);
1516 w.placeholder.clone_from(&p.placeholder);
1517 w.editable = p.editable;
1518 w.selectable = p.selectable;
1519 w.spellcheck = p.spellcheck;
1520 detail = format!(
1521 " lines={}..{} editable={} selectable={} spellcheck={}",
1522 p.min_lines, p.max_lines, p.editable, p.selectable, p.spellcheck
1523 );
1524 }
1525 s.log(format!("realize {kind} #{h}{detail}"));
1526 s.widgets.insert(h, w);
1527 MockHandle(h)
1528 }
1529
1530 fn update(
1531 &mut self,
1532 h: &MockHandle,
1533 kind: PieceKind,
1534 patch: &dyn Any,
1535 anim: Option<&AnimSpec>,
1536 ) {
1537 let mut s = self.state.borrow_mut();
1538 let described = s.describers.iter().find_map(|d| d(patch));
1541 let detail;
1542 let mut cover_shown: Option<(u64, bool, bool)> = None;
1545 {
1546 let w = s.widgets.get_mut(&h.0).expect("update on unknown widget");
1547 if anim.is_some() {
1548 w.last_anim = anim.copied();
1549 }
1550 detail = if let Some(p) = patch.downcast_ref::<ImagePatch>() {
1551 match p {
1552 ImagePatch::Source(s) => {
1555 w.text = describe_image_source(s);
1556 format!("source={}", w.text)
1557 }
1558 ImagePatch::Tint(c) => format!("tint={c:?}"),
1559 }
1560 } else if let Some(p) = patch.downcast_ref::<LabelPatch>() {
1561 match p {
1562 LabelPatch::Text(t) => {
1563 w.text.clone_from(t);
1564 format!("text={t:?}")
1565 }
1566 LabelPatch::Color(_) => "color".into(),
1567 LabelPatch::Font(f) => {
1568 w.font = Some(*f);
1569 "font".into()
1570 }
1571 LabelPatch::Runs(text, runs) => {
1572 w.text.clone_from(text);
1573 w.runs.clone_from(runs);
1574 format!("runs={}", runs.len())
1575 }
1576 }
1577 } else if let Some(p) = patch.downcast_ref::<ButtonPatch>() {
1578 match p {
1579 ButtonPatch::Content(c) => {
1580 w.text.clone_from(&c.title);
1581 format!("content={c:?}")
1582 }
1583 ButtonPatch::Title(t) => {
1584 w.text.clone_from(t);
1585 format!("title={t:?}")
1586 }
1587 ButtonPatch::Enabled(e) => {
1588 w.enabled = *e;
1589 format!("enabled={e}")
1590 }
1591 ButtonPatch::Selected(on) => {
1592 w.selected = *on;
1593 format!("selected={on}")
1594 }
1595 ButtonPatch::Style(s) => format!("style={s:?}"),
1598 }
1599 } else if let Some(p) = patch.downcast_ref::<TogglePatch>() {
1600 match p {
1601 TogglePatch::On(v) => {
1602 w.flag = *v;
1603 format!("on={v}")
1604 }
1605 TogglePatch::Enabled(e) => {
1606 w.enabled = *e;
1607 format!("enabled={e}")
1608 }
1609 }
1610 } else if let Some(p) = patch.downcast_ref::<SliderPatch>() {
1611 match p {
1612 SliderPatch::Value(v) => {
1613 w.value = *v;
1614 format!("value={v}")
1615 }
1616 SliderPatch::Enabled(e) => {
1617 w.enabled = *e;
1618 format!("enabled={e}")
1619 }
1620 }
1621 } else if let Some(p) = patch.downcast_ref::<TextFieldPatch>() {
1622 match p {
1623 TextFieldPatch::Text { text, from_native } => {
1624 if !*from_native {
1625 w.text.clone_from(text);
1626 }
1627 format!("text={text:?} from_native={from_native}")
1628 }
1629 TextFieldPatch::Placeholder(t) => {
1630 w.placeholder.clone_from(t);
1631 format!("placeholder={t:?}")
1632 }
1633 TextFieldPatch::Enabled(e) => {
1634 w.enabled = *e;
1635 format!("enabled={e}")
1636 }
1637 TextFieldPatch::Select(r) => {
1638 let r = r.clamped(&w.text);
1639 w.selection = Some(r);
1640 format!("select={}..{}", r.start, r.end)
1641 }
1642 }
1643 } else if let Some(p) = patch.downcast_ref::<CanvasProps>() {
1644 w.ops.clone_from(&p.ops);
1645 format!("canvas ops={}", w.ops.len())
1646 } else if let Some(ProgressPatch::Value(v)) = patch.downcast_ref::<ProgressPatch>() {
1647 w.flag = v.is_none();
1648 w.value = v.unwrap_or(0.0);
1649 format!("value={v:?}")
1650 } else if let Some(pp) = patch.downcast_ref::<PickerPatch>() {
1651 let Some(w) = s.widgets.get_mut(&h.0) else {
1652 return;
1653 };
1654 match pp {
1655 PickerPatch::Selected(i) => {
1656 w.value = *i as f64;
1657 format!("picker.selected {i}")
1658 }
1659 PickerPatch::Options(opts) => {
1660 w.text = opts.join("|");
1661 format!("picker.options {opts:?}")
1662 }
1663 PickerPatch::Enabled(e) => {
1664 w.enabled = *e;
1665 format!("picker.enabled {e}")
1666 }
1667 }
1668 } else if let Some(tp) = patch.downcast_ref::<TextAreaPatch>() {
1669 if let Some(w) = s.widgets.get_mut(&h.0) {
1670 match tp {
1671 TextAreaPatch::SetText(t) => w.text.clone_from(t),
1672 TextAreaPatch::SetEditable(v) => w.editable = *v,
1673 TextAreaPatch::SetSelectable(v) => w.selectable = *v,
1674 TextAreaPatch::SetSpellCheck(v) => w.spellcheck = *v,
1675 }
1676 }
1677 format!("textarea.patch {tp:?}")
1678 } else if let Some(p) = patch.downcast_ref::<ListItemPatch>() {
1679 match p {
1680 ListItemPatch::Title(t) => w.text.clone_from(t),
1681 ListItemPatch::Checked(on) => w.flag = *on,
1682 _ => {}
1683 }
1684 format!("list_item {p:?}")
1685 } else if let Some(p) = patch.downcast_ref::<NavMenuPatch>() {
1686 match p {
1687 NavMenuPatch::IconProgress(values) => format!("menu icon_progress={values:?}"),
1688 NavMenuPatch::Selected(sel) => {
1689 w.value = sel.map_or(-1.0, |i| i as f64);
1690 format!("menu selected={sel:?}")
1691 }
1692 NavMenuPatch::Items {
1694 items,
1695 selected,
1696 badges,
1697 rows_changed,
1698 movable,
1699 sorted,
1700 ..
1701 } => {
1702 w.text = items.join("|");
1703 w.value = selected.map_or(-1.0, |i| i as f64);
1704 let mut line = format!(
1705 "menu items={items:?} selected={selected:?} badges={badges:?} \
1706 rows_changed={rows_changed:?} movable={movable:?}"
1707 );
1708 if !sorted.is_empty() {
1709 let _ = write!(line, " sorted={sorted:?}");
1710 }
1711 line
1712 }
1713 }
1714 } else if let Some(p) = patch.downcast_ref::<NavPatch>() {
1715 match p {
1716 NavPatch::Pushed { title, .. } => {
1717 w.text.clone_from(title);
1718 w.nav_depth += 1;
1719 format!("nav pushed title={title:?}")
1720 }
1721 NavPatch::Popped => {
1722 w.nav_depth = w.nav_depth.saturating_sub(1);
1723 "nav popped".into()
1724 }
1725 NavPatch::Title(t) => {
1726 w.text.clone_from(t);
1727 format!("nav title={t:?}")
1728 }
1729 NavPatch::GuardTop(on) => {
1731 w.flag = *on;
1732 w.nav_guarded = *on;
1733 format!("nav guard={on}")
1734 }
1735 NavPatch::Presentation(p) => {
1740 w.flag = p.is_split();
1741 w.presentation = Some(*p);
1742 format!("nav presentation={p:?}")
1743 }
1744 NavPatch::Select(i) => {
1748 w.selected_page = Some(*i);
1749 w.value = *i as f64;
1750 format!("nav select={i}")
1751 }
1752 NavPatch::ListVisible(v) => format!("nav list visible={v}"),
1756 NavPatch::Reorder(order) => format!("nav reorder {order:?}"),
1757 NavPatch::ListInStack(v) => format!("nav list in-stack={v}"),
1758 }
1759 } else if let Some(p) = patch.downcast_ref::<CoverPatch>() {
1760 match p {
1763 CoverPatch::Present {
1764 background,
1765 dismiss_disabled,
1766 } => {
1767 w.flag = true;
1768 w.background = *background;
1769 cover_shown = Some((w.node, true, w.half));
1770 format!(
1771 "cover present bg={background:?} dismiss_disabled={dismiss_disabled}"
1772 )
1773 }
1774 CoverPatch::DismissDisabled(d) => format!("cover dismiss_disabled={d}"),
1775 CoverPatch::Dismiss => {
1776 w.flag = false;
1777 cover_shown = Some((w.node, false, w.half));
1778 "cover dismiss".into()
1779 }
1780 }
1781 } else if let Some(ContainerPatch::Background(c)) =
1782 patch.downcast_ref::<ContainerPatch>()
1783 {
1784 w.background = *c;
1785 format!("bg={c:?}")
1786 } else if let Some(p) = patch.downcast_ref::<ListPatch>() {
1787 match p {
1788 ListPatch::Reload => {
1789 viewport_touch(h.0, |_| {});
1790 "list reload".into()
1791 }
1792 ListPatch::Splice(deltas) => {
1793 viewport_touch(h.0, |_| {});
1794 format!("list splice {deltas:?}")
1795 }
1796 ListPatch::RowSizeInvalidated { cell, height } => {
1797 CELL_HEIGHTS.with(|h| h.borrow_mut().insert(*cell as u64, *height));
1798 format!("list row-size-invalidated {height}")
1799 }
1800 ListPatch::ScrollToEnd => {
1801 w.flag = true;
1803 viewport_touch(h.0, |p| p.to_end = true);
1804 "list scroll-to-end".into()
1805 }
1806 ListPatch::ScrollToRow(row) => {
1807 let rows = VIEWPORT_ROWS.with(std::cell::Cell::get);
1808 viewport_touch(h.0, |p| p.start = row.saturating_sub(rows / 2));
1809 format!("list scroll-to-row {row}")
1810 }
1811 ListPatch::Selected(rows) => format!("list selected {rows:?}"),
1812 ListPatch::Editing(on) => format!("list editing {on}"),
1813 }
1814 } else if let Some(p) = patch.downcast_ref::<TreePatch>() {
1815 match p {
1816 TreePatch::Reload => {
1817 viewport_touch(h.0, |_| {});
1818 "tree reload".into()
1819 }
1820 TreePatch::Expand(tok, on) => {
1821 let (tok, on) = (*tok, *on);
1822 viewport_touch(h.0, |p| {
1823 if on {
1824 p.expanded.insert(tok);
1825 } else {
1826 p.expanded.remove(&tok);
1827 }
1828 });
1829 format!("tree expand {tok} {on}")
1830 }
1831 TreePatch::Selected(toks) => format!("tree selected {toks:?}"),
1832 TreePatch::Reveal(tok) => format!("tree reveal {tok}"),
1833 }
1834 } else {
1835 described.unwrap_or_else(|| "?".into())
1836 };
1837 }
1838 s.log(format!("update {kind} #{} {detail}", h.0));
1839 if let (Some((node, shown, half)), Some(sink)) = (cover_shown, s.sink.clone())
1842 && VIEWPORT_ROWS.with(std::cell::Cell::get) > 0
1843 {
1844 let event = if shown {
1845 let mut size = MOCK_WINDOW.with(std::cell::Cell::get);
1847 if half {
1848 size.height = (size.height * 0.5).floor();
1849 }
1850 Event::FrameChanged(size)
1851 } else {
1852 Event::CoverHidden
1853 };
1854 NATIVE_EVENTS.with(|q| q.borrow_mut().push((sink, NodeId(node), event)));
1855 }
1856 }
1857
1858 fn release(&mut self, h: MockHandle) {
1859 VIEWPORTS.with(|v| v.borrow_mut().remove(&h.0));
1860 let mut s = self.state.borrow_mut();
1861 s.widgets.remove(&h.0);
1862 s.context_menu_providers.remove(&h.0);
1863 s.button_menus.remove(&h.0);
1864 s.log(format!("release #{}", h.0));
1865 }
1866
1867 fn insert(&mut self, parent: &MockHandle, child: &MockHandle, index: usize) {
1868 let mut s = self.state.borrow_mut();
1869 {
1870 let p = s
1871 .widgets
1872 .get_mut(&parent.0)
1873 .expect("insert into unknown parent");
1874 let idx = index.min(p.children.len());
1875 p.children.insert(idx, child.0);
1876 }
1877 s.log(format!(
1878 "insert #{} into #{} at {}",
1879 child.0, parent.0, index
1880 ));
1881 }
1882
1883 fn remove(&mut self, parent: &MockHandle, child: &MockHandle) {
1884 let mut s = self.state.borrow_mut();
1885 {
1886 let p = s
1887 .widgets
1888 .get_mut(&parent.0)
1889 .expect("remove from unknown parent");
1890 p.children.retain(|&c| c != child.0);
1891 }
1892 s.log(format!("remove #{} from #{}", child.0, parent.0));
1893 }
1894
1895 fn move_child(&mut self, parent: &MockHandle, child: &MockHandle, to: usize) {
1896 let mut s = self.state.borrow_mut();
1897 {
1898 let p = s
1899 .widgets
1900 .get_mut(&parent.0)
1901 .expect("move in unknown parent");
1902 p.children.retain(|&c| c != child.0);
1903 let idx = to.min(p.children.len());
1904 p.children.insert(idx, child.0);
1905 }
1906 s.log(format!("move #{} in #{} to {}", child.0, parent.0, to));
1907 }
1908
1909 fn measure(&mut self, h: &MockHandle, kind: PieceKind, p: Proposal) -> Size {
1910 let mut s = self.state.borrow_mut();
1911 s.measure_calls += 1;
1912 let w = s.widgets.get(&h.0).cloned().unwrap_or_default();
1913 let size = match kind {
1914 kinds::LABEL => {
1915 let scale = w.font.map_or(1.0, |f| font_scale(f.style));
1916 let s = text_size(&w.text, p, w.flag, scale);
1917 Size::new(s.width.min(p.width.unwrap_or(s.width)), s.height)
1918 }
1919 kinds::BUTTON => {
1920 let t = text_size(&w.text, Proposal::UNCONSTRAINED, false, 1.0);
1921 Size::new(t.width + 16.0, 24.0)
1922 }
1923 kinds::TOGGLE => Size::new(51.0, 31.0),
1924 kinds::SLIDER | kinds::TEXT_FIELD | kinds::LIST_ITEM => {
1925 Size::new(p.width.unwrap_or(200.0), 24.0)
1926 }
1927 kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 1.0),
1928 kinds::IMAGE => Size::new(32.0, 32.0),
1929 kinds::PROGRESS if w.flag => Size::new(20.0, 20.0),
1931 kinds::PROGRESS => Size::new(p.width.unwrap_or(200.0), 4.0),
1932 _ => Size::new(p.width.unwrap_or(10.0), p.height.unwrap_or(10.0)),
1933 };
1934 s.log(format!(
1935 "measure {kind} #{} {:?} -> {}",
1936 h.0,
1937 p.cache_key(),
1938 fmt_size(size)
1939 ));
1940 size
1941 }
1942
1943 fn first_baseline(&mut self, h: &MockHandle, kind: PieceKind, size: Size) -> Option<f64> {
1949 const ASCENT: f64 = 12.0;
1950 let framed_inset = |box_h: f64| (box_h - MOCK_LINE_H) / 2.0 + ASCENT;
1951 let s = self.state.borrow();
1952 let w = s.widgets.get(&h.0).cloned().unwrap_or_default();
1953 match kind {
1954 kinds::LABEL => (!w.text.is_empty() || size.height > 0.0).then_some(ASCENT),
1955 kinds::BUTTON | kinds::TEXT_FIELD | kinds::TEXT_AREA => Some(framed_inset(size.height)),
1956 _ => None,
1958 }
1959 }
1960
1961 fn set_frame(&mut self, h: &MockHandle, frame: Rect, anim: Option<&AnimSpec>) {
1962 let mut s = self.state.borrow_mut();
1963 if let Some(w) = s.widgets.get_mut(&h.0) {
1964 w.frame = frame;
1965 if anim.is_some() {
1966 w.last_anim = anim.copied();
1967 }
1968 }
1969 let a = if anim.is_some() { " animated" } else { "" };
1970 s.log(format!("set_frame #{} {}{}", h.0, fmt_rect(frame), a));
1971 }
1972
1973 fn set_opacity(&mut self, h: &MockHandle, opacity: f64, anim: Option<&AnimSpec>) {
1974 let mut s = self.state.borrow_mut();
1975 if let Some(w) = s.widgets.get_mut(&h.0) {
1976 w.opacity = Some(opacity);
1977 if anim.is_some() {
1978 w.last_anim = anim.copied();
1979 }
1980 }
1981 let a = if anim.is_some() { " animated" } else { "" };
1982 s.log(format!("set_opacity #{} {:.3}{}", h.0, opacity, a));
1983 }
1984
1985 fn set_transform(
1986 &mut self,
1987 h: &MockHandle,
1988 t: day_spec::Transform,
1989 _size: day_spec::Size,
1990 anim: Option<&AnimSpec>,
1991 ) {
1992 let mut s = self.state.borrow_mut();
1993 if let Some(w) = s.widgets.get_mut(&h.0) {
1994 w.transform = Some(t);
1995 if anim.is_some() {
1996 w.last_anim = anim.copied();
1997 }
1998 }
1999 let a = if anim.is_some() { " animated" } else { "" };
2000 s.log(format!(
2001 "set_transform #{} tx={:.1},ty={:.1},sx={:.2},sy={:.2},rot={:.1}{}",
2002 h.0, t.tx, t.ty, t.sx, t.sy, t.rotate_deg, a
2003 ));
2004 }
2005
2006 fn set_selectable(&mut self, h: &MockHandle, selectable: bool) -> Option<MockHandle> {
2007 let mut s = self.state.borrow_mut();
2008 if let Some(w) = s.widgets.get_mut(&h.0) {
2009 w.selectable = selectable;
2010 }
2011 s.log(format!("set_selectable #{} {}", h.0, selectable));
2012 None
2013 }
2014
2015 fn set_input_traits(
2016 &mut self,
2017 h: &MockHandle,
2018 traits: &day_spec::InputTraits,
2019 ) -> Option<MockHandle> {
2020 let mut s = self.state.borrow_mut();
2021 s.log(format!(
2022 "set_input_traits #{} secure={} read_only={} purpose={:?} submit={:?} max={:?}",
2023 h.0,
2024 traits.secure,
2025 traits.read_only,
2026 traits.purpose,
2027 traits.submit_label,
2028 traits.max_length
2029 ));
2030 let was_secure = s
2031 .widgets
2032 .get(&h.0)
2033 .and_then(|w| w.input_traits.as_ref())
2034 .is_some_and(|t| t.secure);
2035 if s.secure_class_swap && was_secure != traits.secure {
2036 let mut w = s.widgets.remove(&h.0)?;
2039 w.input_traits = Some(traits.clone());
2040 s.next += 1;
2041 let new = s.next;
2042 for parent in s.widgets.values_mut() {
2043 for child in parent.children.iter_mut().filter(|c| **c == h.0) {
2044 *child = new;
2045 }
2046 }
2047 s.widgets.insert(new, w);
2048 s.log(format!("swap #{} for #{}", h.0, new));
2049 return Some(MockHandle(new));
2050 }
2051 if let Some(w) = s.widgets.get_mut(&h.0) {
2052 w.input_traits = Some(traits.clone());
2053 }
2054 None
2055 }
2056
2057 fn set_cursor(&mut self, h: &MockHandle, cursor: day_spec::Cursor) {
2058 let mut s = self.state.borrow_mut();
2059 if let Some(w) = s.widgets.get_mut(&h.0) {
2060 w.cursor = Some(cursor.clone());
2061 }
2062 s.log(format!("set_cursor #{} {}", h.0, cursor.css_name()));
2063 }
2064
2065 fn scroll_bar_inset(&mut self, _h: &MockHandle, _vertical: bool) -> f64 {
2066 self.state.borrow().scroll_bar_inset
2067 }
2068
2069 fn set_scroll_content(&mut self, h: &MockHandle, content: Size) {
2070 let mut s = self.state.borrow_mut();
2071 if let Some(w) = s.widgets.get_mut(&h.0) {
2072 w.scroll_content = content;
2073 }
2074 s.log(format!("set_scroll_content #{} {}", h.0, fmt_size(content)));
2075 }
2076
2077 fn scroll_to(&mut self, h: &MockHandle, target: Rect, _animated: bool) {
2078 let mut s = self.state.borrow_mut();
2079 if let Some(w) = s.widgets.get_mut(&h.0) {
2080 let (vw, vh) = (w.frame.size.width, w.frame.size.height);
2082 let (cw, ch) = (w.scroll_content.width, w.scroll_content.height);
2083 let clamp = |cur: f64, lo: f64, hi_edge: f64, view: f64, content: f64| -> f64 {
2084 let mut o = cur;
2085 if hi_edge > o + view {
2086 o = hi_edge - view;
2087 }
2088 if lo < o {
2089 o = lo;
2090 }
2091 o.clamp(0.0, (content - view).max(0.0))
2092 };
2093 let o = w.scroll_offset;
2094 w.scroll_offset = Point::new(
2095 clamp(
2096 o.x,
2097 target.origin.x,
2098 target.origin.x + target.size.width,
2099 vw,
2100 cw,
2101 ),
2102 clamp(
2103 o.y,
2104 target.origin.y,
2105 target.origin.y + target.size.height,
2106 vh,
2107 ch,
2108 ),
2109 );
2110 }
2111 s.log(format!("scroll_to #{} {}", h.0, fmt_rect(target)));
2112 }
2113
2114 fn scroll_offset(&mut self, h: &MockHandle) -> Point {
2115 self.state
2116 .borrow()
2117 .widgets
2118 .get(&h.0)
2119 .map_or(Point::ZERO, |w| w.scroll_offset)
2120 }
2121
2122 fn enable_gesture(&mut self, h: &MockHandle, _node: NodeId, kind: GestureKind) {
2123 self.state
2124 .borrow_mut()
2125 .log(format!("enable_gesture #{} {:?}", h.0, kind));
2126 }
2127
2128 fn focus(&mut self, h: &MockHandle, node: NodeId, focused: bool) {
2129 let sink = {
2130 let mut st = self.state.borrow_mut();
2131 st.log(format!("focus #{} {}", h.0, focused));
2132 if let Some(w) = st.widgets.get_mut(&h.0) {
2133 w.focused = focused;
2134 }
2135 st.sink.clone()
2136 };
2137 if let Some(sink) = sink {
2140 sink(node, Event::FocusChanged(focused));
2141 }
2142 }
2143
2144 fn set_event_sink(&mut self, sink: EventSink) {
2145 self.state.borrow_mut().sink = Some(Rc::from(sink));
2146 }
2147
2148 fn attach_tree(&mut self, host: &MockHandle, source: day_spec::TreeSource) {
2149 if VIEWPORT_ROWS.with(std::cell::Cell::get) > 0 {
2150 let (children_len, child_token) =
2151 (source.children_len.clone(), source.child_token.clone());
2152 let visible = move |open: &std::collections::HashSet<u64>| {
2154 fn walk(
2155 parent: Option<u64>,
2156 open: &std::collections::HashSet<u64>,
2157 len: &dyn Fn(Option<u64>) -> usize,
2158 tok: &dyn Fn(Option<u64>, usize) -> u64,
2159 out: &mut Vec<u64>,
2160 ) {
2161 for i in 0..len(parent) {
2162 let t = tok(parent, i);
2163 out.push(t);
2164 if open.contains(&t) {
2165 walk(Some(t), open, len, tok, out);
2166 }
2167 }
2168 }
2169 let mut out = Vec::new();
2170 walk(None, open, &*children_len, &*child_token, &mut out);
2171 out
2172 };
2173 VIEWPORTS.with(|v| {
2174 v.borrow_mut().insert(
2175 host.0,
2176 Viewport {
2177 visible: Rc::new(visible),
2178 bind_row: source.bind_row.clone(),
2179 recycle: source.recycle.clone(),
2180 cell_height: None,
2181 expanded: std::collections::HashSet::default(),
2182 start: 0,
2183 to_end: false,
2184 bound: 0,
2185 dirty: true,
2186 },
2187 )
2188 });
2189 }
2190 let mut s = self.state.borrow_mut();
2191 s.tree_sources.insert(host.0, source);
2192 s.log(format!("attach_tree #{}", host.0));
2193 }
2194
2195 fn attach_list(&mut self, host: &MockHandle, source: ListSource) {
2196 if VIEWPORT_ROWS.with(std::cell::Cell::get) > 0 {
2197 VIEWPORTS.with(|v| {
2198 v.borrow_mut().insert(
2199 host.0,
2200 Viewport {
2201 visible: {
2202 let len = source.len.clone();
2203 Rc::new(move |_| (0..len() as u64).collect())
2204 },
2205 bind_row: {
2206 let bind = source.bind_row.clone();
2207 Rc::new(move |row, cell| bind(row as usize, cell))
2208 },
2209 recycle: source.recycle.clone(),
2210 cell_height: Some(source.cell_height.clone()),
2211 expanded: std::collections::HashSet::default(),
2212 start: 0,
2213 to_end: false,
2214 bound: 0,
2215 dirty: true,
2216 },
2217 )
2218 });
2219 }
2220 let mut s = self.state.borrow_mut();
2221 s.list_sources.insert(host.0, source);
2222 s.log(format!("attach_list #{}", host.0));
2223 }
2224
2225 fn adopt(&mut self, raw: RawHandle) -> MockHandle {
2226 let h = raw as u64;
2228 let mut s = self.state.borrow_mut();
2229 s.widgets.entry(h).or_insert_with(|| MockWidget {
2230 kind: kinds::LIST_CELL,
2231 node: h,
2232 enabled: true,
2233 ..Default::default()
2234 });
2235 MockHandle(h)
2236 }
2237
2238 fn reduce_motion(&mut self) -> bool {
2239 self.state.borrow().reduce_motion
2240 }
2241
2242 fn announce(&mut self, text: &str, urgent: bool) {
2243 let mut s = self.state.borrow_mut();
2244 s.announcements.push((text.to_string(), urgent));
2245 s.log(format!("announce {text:?} urgent={urgent}"));
2246 }
2247
2248 fn set_a11y(&mut self, h: &MockHandle, a11y: &A11yProps) {
2249 let mut s = self.state.borrow_mut();
2250 if let Some(w) = s.widgets.get_mut(&h.0) {
2251 w.a11y = a11y.clone();
2252 }
2253 s.log(format!("a11y #{} id={:?}", h.0, a11y.identifier));
2254 }
2255
2256 fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
2263 let format = day_spec::ImageFormat::sniff(bytes);
2264 let mut s = self.state.borrow_mut();
2265 s.log(format!(
2266 "decode_image #{} {} bytes {:?}",
2267 id.0,
2268 bytes.len(),
2269 format
2270 ));
2271 let event = match format {
2272 Some(format) => {
2273 let info = day_spec::BitmapInfo {
2274 pixels: Size::new(MOCK_IMAGE_W, MOCK_IMAGE_H),
2277 scale: 1.0,
2278 format: Some(format),
2279 has_alpha: format == day_spec::ImageFormat::Png,
2280 };
2281 s.bitmaps.insert(id.0, info);
2282 Event::ImageDecoded {
2283 req,
2284 result: Ok(info),
2285 }
2286 }
2287 None => Event::ImageDecoded {
2288 req,
2289 result: Err(day_spec::ImageError::Decode),
2290 },
2291 };
2292 drop(s);
2293 self.raise(event);
2294 }
2295
2296 fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
2297 self.state.borrow().bitmaps.get(&id.0).copied()
2298 }
2299
2300 fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
2301 let mut s = self.state.borrow_mut();
2302 s.log(format!("encode_image #{} {:?}", id.0, spec.format));
2303 let known = s.bitmaps.contains_key(&id.0);
2304 let result = if !known {
2305 Err(day_spec::ImageError::Gone)
2306 } else if !MOCK_ENCODE_FORMATS.contains(&spec.format) {
2307 Err(day_spec::ImageError::Encode)
2308 } else {
2309 Ok(match spec.format {
2312 day_spec::ImageFormat::Jpeg => vec![0xff, 0xd8, 0xff, 0xe0],
2313 _ => vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
2314 })
2315 };
2316 drop(s);
2317 self.raise(Event::ImageEncoded { req, result });
2318 }
2319
2320 fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
2321 MOCK_ENCODE_FORMATS.to_vec()
2322 }
2323
2324 fn release_image(&mut self, id: day_spec::BitmapId) {
2325 let mut s = self.state.borrow_mut();
2326 s.bitmaps.remove(&id.0);
2327 s.log(format!("release_image #{}", id.0));
2328 }
2329
2330 fn render_bitmap(
2333 &mut self,
2334 req: u64,
2335 id: day_spec::BitmapId,
2336 ops: &[DrawOp],
2337 size: Size,
2338 scale: f64,
2339 ) {
2340 let (w, h) = day_spec::export_pixels(size, scale);
2341 let info = day_spec::BitmapInfo {
2342 pixels: Size::new(f64::from(w), f64::from(h)),
2343 scale,
2344 format: None,
2345 has_alpha: true,
2346 };
2347 let mut s = self.state.borrow_mut();
2348 s.log(format!(
2349 "render_bitmap #{} {} ops {} @{scale}",
2350 id.0,
2351 ops.len(),
2352 fmt_size(size)
2353 ));
2354 s.bitmaps.insert(id.0, info);
2355 drop(s);
2356 self.raise(Event::BitmapRendered {
2357 req,
2358 result: Ok(info),
2359 });
2360 }
2361
2362 fn replay(&mut self, h: &MockHandle, ops: &[DrawOp], size: Size) {
2363 let mut s = self.state.borrow_mut();
2364 if let Some(w) = s.widgets.get_mut(&h.0) {
2365 w.ops = ops.to_vec();
2366 }
2367 s.log(format!(
2368 "replay #{} {} ops in {}",
2369 h.0,
2370 ops.len(),
2371 fmt_size(size)
2372 ));
2373 }
2374
2375 fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
2377 use day_spec::FontWeight::{Bold, Regular};
2378 self.state.borrow_mut().log("font_families".to_string());
2379 let face = |name: &str, weight: day_spec::FontWeight, italic: bool| day_spec::FontFace {
2380 name: name.to_string(),
2381 weight,
2382 italic,
2383 };
2384 vec![
2385 day_spec::FontFamilyInfo {
2386 family: "Day Sans".to_string(),
2387 faces: vec![
2388 face("Regular", Regular, false),
2389 face("Bold", Bold, false),
2390 face("Italic", Regular, true),
2391 face("Bold Italic", Bold, true),
2392 ],
2393 },
2394 day_spec::FontFamilyInfo {
2395 family: "Day Mono".to_string(),
2396 faces: vec![face("Regular", Regular, false)],
2397 },
2398 ]
2399 }
2400
2401 fn measure_text(
2403 &mut self,
2404 text: &str,
2405 size: f64,
2406 _font: &day_spec::CanvasFont,
2407 ) -> Option<day_spec::TextMetrics> {
2408 self.state
2409 .borrow_mut()
2410 .log(format!("measure_text {text:?} {size}"));
2411 Some(day_spec::TextMetrics::approximate(text, size))
2412 }
2413
2414 fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
2415 Ok(vec![0x89, b'P', b'N', b'G'])
2416 }
2417
2418 fn fit_window(&mut self, host: &MockHandle, size: Size) {
2419 let mut st = self.state.borrow_mut();
2420 if let Some(w) = st.windows.iter_mut().find(|w| w.handle == host.0) {
2421 w.fit_size = Some(size);
2422 w.size = size;
2423 }
2424 st.log(format!("fit_window {} {size:?}", host.0));
2425 }
2426
2427 fn native_window_tabs(&self) -> bool {
2428 self.state.borrow().native_window_tabs
2429 }
2430 fn native_document_tabs(&self) -> bool {
2431 true
2432 }
2433 fn group_windows(&mut self, hosts: &[MockHandle]) {
2434 let mut state = self.state.borrow_mut();
2435 let ids: Vec<_> = hosts
2436 .iter()
2437 .filter_map(|h| {
2438 state
2439 .windows
2440 .iter()
2441 .find(|w| w.handle == h.0 && w.open)
2442 .map(|w| w.node)
2443 })
2444 .collect();
2445 for group in &mut state.window_tab_groups {
2446 group.retain(|id| !ids.contains(id));
2447 }
2448 state.window_tab_groups.retain(|group| !group.is_empty());
2449 if !ids.is_empty() {
2450 state.window_tab_groups.push(ids);
2451 }
2452 state.log(format!("group_windows {hosts:?}"));
2453 }
2454 fn window_tab_order(&self, host: &MockHandle) -> Vec<NodeId> {
2455 let state = self.state.borrow();
2456 let Some(window) = state.windows.iter().find(|w| w.handle == host.0 && w.open) else {
2457 return Vec::new();
2458 };
2459 state
2460 .window_tab_groups
2461 .iter()
2462 .find(|group| group.contains(&window.node))
2463 .map_or_default(|group| {
2464 group
2465 .iter()
2466 .copied()
2467 .filter(|id| state.windows.iter().any(|w| w.node == *id && w.open))
2468 .collect()
2469 })
2470 }
2471 fn open_window(
2472 &mut self,
2473 id: NodeId,
2474 options: &day_spec::WindowOptions,
2475 kind: day_spec::WindowKind,
2476 ) -> day_spec::WindowOpenReply<MockHandle> {
2477 let kind_s = match kind {
2478 day_spec::WindowKind::Normal => "normal",
2479 day_spec::WindowKind::Preferences => "preferences",
2480 day_spec::WindowKind::About => "about",
2481 };
2482 let mut s = self.state.borrow_mut();
2483 if s.no_multi_window {
2484 s.log(format!("open_window unsupported kind={kind_s}"));
2485 return day_spec::WindowOpenReply::Unsupported;
2486 }
2487 if s.pending_windows {
2488 s.log(format!("open_window pending {:?} kind={kind_s}", id.0));
2489 s.pending_opens
2490 .push((id, options.title.clone(), kind_s.into()));
2491 return day_spec::WindowOpenReply::Pending;
2492 }
2493 s.next += 1;
2494 let h = s.next;
2495 s.widgets.insert(
2496 h,
2497 MockWidget {
2498 kind: kinds::CONTAINER,
2499 node: id.0,
2500 enabled: true,
2501 ..Default::default()
2502 },
2503 );
2504 s.windows.push(MockWindow {
2505 handle: h,
2506 node: id,
2507 title: options.title.clone(),
2508 size: options.size,
2509 kind: kind_s.into(),
2510 tabbing: options.tabbing.clone(),
2511 open: true,
2512 focused: false,
2513 fit_size: None,
2514 });
2515 s.log(format!(
2516 "open_window #{h} {:?} {} kind={kind_s}",
2517 options.title,
2518 fmt_size(options.size)
2519 ));
2520 day_spec::WindowOpenReply::Open(MockHandle(h))
2521 }
2522
2523 fn quit_app(&mut self) {
2524 self.state.borrow_mut().log("quit_app".to_string());
2527 }
2528
2529 fn close_window(&mut self, host: &MockHandle) {
2530 let mut s = self.state.borrow_mut();
2533 let Some(w) = s.windows.iter_mut().find(|w| w.handle == host.0 && w.open) else {
2534 return;
2535 };
2536 let node = w.node;
2537 s.log(format!("close_window #{}", host.0));
2538 if s.defer_window_close {
2539 return;
2540 }
2541 s.windows.iter_mut().find(|w| w.node == node).unwrap().open = false;
2542 let sink = s.sink.clone();
2543 drop(s);
2544 if let Some(sink) = sink {
2545 sink(node, Event::WindowClosed);
2546 }
2547 }
2548
2549 fn focus_window(&mut self, host: &MockHandle) {
2550 let mut s = self.state.borrow_mut();
2551 let Some(node) = s
2552 .windows
2553 .iter()
2554 .find(|w| w.handle == host.0 && w.open)
2555 .map(|w| w.node)
2556 else {
2557 return;
2558 };
2559 let prev = s.windows.iter().find(|w| w.focused).map(|w| w.node);
2560 for w in &mut s.windows {
2561 w.focused = w.handle == host.0;
2562 }
2563 s.log(format!("focus_window #{}", host.0));
2564 let sink = s.sink.clone();
2565 drop(s);
2566 if let Some(sink) = sink {
2567 if let Some(p) = prev
2568 && p != node
2569 {
2570 sink(p, Event::WindowFocused(false));
2571 }
2572 sink(node, Event::WindowFocused(true));
2573 }
2574 }
2575
2576 fn set_window_title(&mut self, host: &MockHandle, title: &str) {
2577 let mut s = self.state.borrow_mut();
2578 if let Some(w) = s.windows.iter_mut().find(|w| w.handle == host.0) {
2579 w.title = title.to_string();
2580 }
2581 s.log(format!("set_window_title #{} {title:?}", host.0));
2582 }
2583
2584 fn snapshot_window_of(&mut self, host: &MockHandle) -> Result<Vec<u8>, String> {
2585 Ok(vec![0x89, b'P', b'N', b'G', host.0 as u8])
2588 }
2589
2590 fn present(&mut self, req: u64, spec: &day_spec::present::PresentSpec) {
2591 self.state
2594 .borrow_mut()
2595 .log(format!("present req={req} title={:?}", spec.title()));
2596 }
2597
2598 fn dismiss(&mut self, req: u64) {
2599 self.state.borrow_mut().log(format!("dismiss req={req}"));
2600 }
2601
2602 fn share_support(&self) -> day_spec::Support {
2603 day_spec::Support::Native
2604 }
2605
2606 fn share(&mut self, spec: &day_spec::share::ShareSpec, anchor: Option<&Self::Handle>) -> bool {
2607 let anchor = anchor.map(|h| h.0);
2610 self.state.borrow_mut().shares.push((spec.clone(), anchor));
2611 true
2612 }
2613
2614 fn open_url(&mut self, url: &str) {
2615 self.state.borrow_mut().log(format!("open_url {url}"));
2617 }
2618
2619 fn defer_system_gestures(&mut self, edges: day_spec::Edges) {
2620 self.state
2622 .borrow_mut()
2623 .log(format!("defer_system_gestures edges={:#06b}", edges.0));
2624 }
2625
2626 fn set_status_bar_hidden(&mut self, hidden: bool) {
2627 self.state
2629 .borrow_mut()
2630 .log(format!("set_status_bar_hidden {hidden}"));
2631 }
2632
2633 fn edit_toolbar(&mut self, _h: &MockHandle, ops: &[day_spec::ToolbarOp]) -> bool {
2637 let mut s = self.state.borrow_mut();
2638 if s.decline_toolbar_edits {
2639 return false;
2640 }
2641 for op in ops {
2642 s.toolbar.apply(op);
2643 }
2644 s.toolbar_edits.push(ops.to_vec());
2645 s.log(format!("edit_toolbar [{} ops]", ops.len()));
2646 true
2647 }
2648
2649 fn update_toolbar(&mut self, _h: &MockHandle, patch: &day_spec::ToolbarPatch) {
2650 let mut s = self.state.borrow_mut();
2651 s.toolbar.patch(patch);
2652 s.toolbar_patches.push(patch.clone());
2653 }
2654
2655 fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
2656 let mut s = self.state.borrow_mut();
2657 s.app_menu = items.iter().map(menu_title).collect();
2658 s.log(format!("set_app_menu [{} items]", items.len()));
2659 }
2660
2661 fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
2662 let mut s = self.state.borrow_mut();
2663 s.status_items = items.to_vec();
2664 s.log(format!("set_status_items [{} items]", items.len()));
2665 }
2666
2667 fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
2668 let mut s = self.state.borrow_mut();
2669 s.app_progress = progress;
2670 s.log(format!("set_app_progress {progress:?}"));
2671 }
2672
2673 fn set_dock_visible(&mut self, visible: bool) {
2674 let mut s = self.state.borrow_mut();
2675 s.dock_visible = Some(visible);
2676 s.log(format!("set_dock_visible {visible}"));
2677 }
2678
2679 fn set_keep_running(&mut self, keep: bool) {
2680 let mut s = self.state.borrow_mut();
2681 s.keep_running = keep;
2682 s.log(format!("set_keep_running {keep}"));
2683 }
2684
2685 fn monitors(&self) -> Vec<day_spec::Monitor> {
2686 let frame = day_spec::Rect::new(0.0, 0.0, 1440.0, 900.0);
2688 vec![day_spec::Monitor {
2689 id: "mock-0".into(),
2690 name: "Mock Display".into(),
2691 frame,
2692 work_area: day_spec::Rect::new(0.0, 25.0, 1440.0, 875.0),
2693 scale: 2.0,
2694 primary: true,
2695 }]
2696 }
2697
2698 fn window_frame(&self, host: &MockHandle) -> Option<day_spec::Rect> {
2699 let s = self.state.borrow();
2701 s.window_changes.iter().rev().find_map(|(h, c)| match c {
2702 day_spec::WindowChange::Frame {
2703 origin: Some(o),
2704 size: Some(z),
2705 } if *h == host.0 => Some(day_spec::Rect::new(o.x, o.y, z.width, z.height)),
2706 _ => None,
2707 })
2708 }
2709
2710 fn set_launcher_shortcuts(&mut self, shortcuts: &[day_spec::LauncherShortcut]) {
2711 let mut s = self.state.borrow_mut();
2712 s.launcher_shortcuts = shortcuts.to_vec();
2713 s.log(format!(
2714 "set_launcher_shortcuts [{} items]",
2715 shortcuts.len()
2716 ));
2717 }
2718
2719 fn set_drag_region(&mut self, h: &MockHandle, drag: bool) {
2720 let mut s = self.state.borrow_mut();
2721 if drag {
2722 s.drag_regions.insert(h.0);
2723 } else {
2724 s.drag_regions.remove(&h.0);
2725 }
2726 s.log(format!("set_drag_region #{} {drag}", h.0));
2727 }
2728
2729 fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
2730 let mut s = self.state.borrow_mut();
2731 s.dock_menu = items.iter().map(menu_title).collect();
2732 s.log(format!("set_dock_menu [{} items]", items.len()));
2733 }
2734
2735 fn apply_window(&mut self, host: &MockHandle, change: &day_spec::WindowChange) {
2736 let mut s = self.state.borrow_mut();
2740 s.log(format!("apply_window #{} {change:?}", host.0));
2741 s.window_changes.push((host.0, change.clone()));
2742 let day_spec::WindowChange::State(state) = change else {
2743 return;
2744 };
2745 if s.decline_window_states {
2746 return;
2747 }
2748 s.window_states.insert(host.0, *state);
2749 let node = s
2750 .windows
2751 .iter()
2752 .find(|w| w.handle == host.0)
2753 .map_or(day_spec::WINDOW_NODE, |w| w.node);
2754 let sink = s.sink.clone();
2755 drop(s);
2756 if let Some(sink) = sink {
2757 sink(node, Event::WindowStateChanged(*state));
2758 }
2759 }
2760
2761 fn set_context_menu(&mut self, h: &MockHandle, _node: NodeId, items: &[day_spec::MenuItem]) {
2762 let mut s = self.state.borrow_mut();
2763 if items.is_empty() {
2764 s.context_menus.remove(&h.0);
2765 } else {
2766 s.context_menus
2767 .insert(h.0, items.iter().map(menu_title).collect());
2768 }
2769 s.log(format!("set_context_menu #{} [{} items]", h.0, items.len()));
2770 }
2771
2772 fn set_context_menu_fn(&mut self, h: &MockHandle, _node: NodeId, f: day_spec::ContextMenuFn) {
2773 self.state
2774 .borrow_mut()
2775 .context_menu_providers
2776 .insert(h.0, f);
2777 }
2778
2779 fn set_button_menu(&mut self, h: &MockHandle, _node: NodeId, f: day_spec::ContextMenuFn) {
2780 let mut s = self.state.borrow_mut();
2781 s.button_menus.insert(h.0, f);
2782 s.log(format!("set_button_menu #{}", h.0));
2783 }
2784
2785 fn supports_lifecycle(&self, _phase: day_spec::Lifecycle) -> bool {
2786 true
2789 }
2790
2791 fn read_native(&self, h: &MockHandle) -> day_spec::NativeSnapshot {
2792 let s = self.state.borrow();
2795 let Some(w) = s.widgets.get(&h.0) else {
2796 return day_spec::NativeSnapshot::default();
2797 };
2798 let kind = w.kind;
2799 let texty = matches!(
2800 kind,
2801 "day.label" | "day.button" | "day.text_field" | "day.text_area"
2802 );
2803 let picked = (kind == "day.picker")
2805 .then(|| w.text.split('|').nth(w.value as usize).map(str::to_owned))
2806 .flatten();
2807 day_spec::NativeSnapshot {
2808 found: true,
2809 role: w.a11y.role,
2810 label: w.a11y.label.clone(),
2811 value: w.a11y.value.clone(),
2812 identifier: w.a11y.identifier.clone(),
2813 text: texty.then(|| w.text.clone()).or(picked),
2814 number: matches!(kind, "day.slider" | "day.progress").then_some(w.value),
2815 checked: match kind {
2817 "day.toggle" => Some(w.flag),
2818 "day.button" => Some(w.selected),
2819 _ => None,
2820 },
2821 enabled: Some(w.enabled),
2822 visible: None,
2823 frame: Some(window_frame(&s, h.0)),
2824 }
2825 }
2826
2827 fn set_system_back(&mut self, armed: bool) {
2828 let mut s = self.state.borrow_mut();
2829 s.system_back = armed;
2830 s.log(format!("system_back armed={armed}"));
2831 }
2832
2833 fn native_back(&mut self) -> bool {
2838 let target = {
2839 let mut s = self.state.borrow_mut();
2840 let Some(sink) = s.sink.clone() else {
2841 return false;
2842 };
2843 let cover = s
2844 .widgets
2845 .values()
2846 .filter(|w| w.kind == kinds::COVER && w.flag)
2847 .map(|w| w.node)
2848 .max();
2849 let host = s
2850 .widgets
2851 .iter()
2852 .filter(|(_, w)| w.nav_depth > 0)
2853 .max_by_key(|(_, w)| w.node)
2854 .map(|(h, _)| *h);
2855 let target = if let Some(node) = cover {
2856 Some((
2857 NodeId(node),
2858 Event::NavBack {
2859 already_popped: false,
2860 },
2861 ))
2862 } else if let Some(h) = host {
2863 let w = s.widgets.get_mut(&h).expect("host just found");
2864 let guarded = w.nav_guarded;
2865 if !guarded {
2866 w.nav_depth -= 1;
2867 }
2868 Some((
2869 NodeId(w.node),
2870 Event::NavBack {
2871 already_popped: !guarded,
2872 },
2873 ))
2874 } else if s.system_back {
2875 Some((
2876 day_spec::WINDOW_NODE,
2877 Event::NavBack {
2878 already_popped: false,
2879 },
2880 ))
2881 } else {
2882 None
2883 };
2884 if let Some((node, _)) = &target {
2885 s.log(format!("native_back -> {node:?}"));
2886 }
2887 target.map(|(node, ev)| (sink, node, ev))
2888 };
2889 match target {
2890 Some((sink, node, ev)) => {
2891 sink(node, ev);
2892 true
2893 }
2894 None => false,
2895 }
2896 }
2897
2898 fn ui_idle(&mut self) -> bool {
2899 self.state.borrow_mut().log("ui_idle".into());
2902 !self.state.borrow().ui_busy
2903 }
2904
2905 fn on_suspend(&mut self) {
2906 self.state.borrow_mut().log("on_suspend".into());
2907 }
2908
2909 fn on_resume(&mut self) {
2910 self.state.borrow_mut().log("on_resume".into());
2911 }
2912
2913 fn on_memory_warning(&mut self) {
2914 self.state.borrow_mut().log("on_memory_warning".into());
2915 }
2916}
2917
2918fn menu_title(item: &day_spec::MenuItem) -> String {
2920 match item {
2921 day_spec::MenuItem::Action { label, .. } | day_spec::MenuItem::Submenu { label, .. } => {
2922 label.clone()
2923 }
2924 day_spec::MenuItem::Separator => "—".into(),
2925 }
2926}
2927
2928impl Platform for MockToolkit {
2929 const TARGET: &'static str = "mock-mock";
2930 const TOOLKIT: &'static str = "mock";
2931 const RUN_ENDS_APP: bool = false;
2933
2934 fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, MockHandle, Size)>) {
2935 let root = self.realize(kinds::CONTAINER, &ContainerProps::default(), NodeId(0));
2938 MOCK_WINDOW.with(|w| w.set(options.size));
2939 ready(self, root, options.size);
2940 }
2941
2942 fn post(f: Box<dyn FnOnce() + Send>) {
2943 f();
2945 }
2946
2947 fn post_delayed(_ms: u32, f: Box<dyn FnOnce() + Send>) {
2948 viewport_flush();
2950 f();
2953 }
2954}