1use std::cell::{Cell, RefCell};
16use std::collections::HashMap;
17use std::rc::Rc;
18
19use day_spec::{ToolbarItem, ToolbarPatch, ToolbarValue};
20
21use crate::tree::{RNode, with_tree};
22
23type ValueAction = Rc<dyn Fn(&ToolbarValue)>;
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32pub enum Chrome {
33 Window(RNode),
35 Page(RNode),
38}
39
40struct PageFrame {
43 page: RNode,
44 active: Option<Rc<dyn Fn() -> bool>>,
45 column: day_spec::ToolbarColumn,
46 window: RNode,
51}
52
53struct Contribution {
55 chrome: Chrome,
56 seq: u64,
59 items: Vec<ToolbarItem>,
60 window: RNode,
62 document_window: Option<DocumentWindow>,
63 active: Option<Rc<dyn Fn() -> bool>>,
68}
69
70#[derive(Clone)]
73pub struct DocumentWindow(Rc<Cell<RNode>>);
74impl DocumentWindow {
75 #[must_use]
76 pub fn new(root: RNode) -> Self {
77 Self(Rc::new(Cell::new(root)))
78 }
79 pub fn set(&self, root: RNode) {
80 if self.0.replace(root) != root {
81 schedule_recompose();
82 }
83 }
84}
85impl Contribution {
86 fn window(&self) -> RNode {
87 self.document_window
88 .as_ref()
89 .map_or(self.window, |w| w.0.get())
90 }
91}
92
93day_reactive::tls_slots! {
94 toolbar;
95 static VALUE_ACTIONS: RefCell<HashMap<u64, ValueAction>> = RefCell::new(HashMap::new());
99 static CONTRIBUTIONS: RefCell<HashMap<u64, Contribution>> = RefCell::new(HashMap::new());
101 static MODELS: RefCell<Vec<(Chrome, Vec<ToolbarItem>)>> = const { RefCell::new(Vec::new()) };
105 static SLOT_IDS: RefCell<HashMap<(RNode, String), u64>> = RefCell::new(HashMap::new());
108 static SLOT_TARGETS: RefCell<HashMap<u64, u64>> = RefCell::new(HashMap::new());
110 static DELIVERED: RefCell<HashMap<RNode, Vec<ToolbarItem>>> = RefCell::new(HashMap::new());
115 static RECOMPOSE_PENDING: Cell<bool> = const { Cell::new(false) };
117 static RECOMPOSING: Cell<bool> = const { Cell::new(false) };
118 static RECOMPOSE_AGAIN: Cell<bool> = const { Cell::new(false) };
119 static NEXT_TOKEN: Cell<u64> = const { Cell::new(1) };
121 static BUILDING: Cell<Option<RNode>> = const { Cell::new(None) };
123 static PAGE_STACK: RefCell<Vec<PageFrame>> = RefCell::new(Vec::new());
127}
128
129pub fn with_window<R>(root: RNode, f: impl FnOnce() -> R) -> R {
134 let previous = BUILDING.with(|b| b.replace(Some(root)));
138 let _restore =
139 std::mem::DropGuard::new(previous, |previous| BUILDING.with(|b| b.set(previous)));
140 f()
141}
142
143pub fn with_page<R>(page: RNode, f: impl FnOnce() -> R) -> R {
146 with_page_in(
147 page,
148 None,
149 day_spec::ToolbarColumn::Detail,
150 window_being_built(),
151 f,
152 )
153}
154
155pub fn with_page_in<R>(
158 page: RNode,
159 active: Option<Rc<dyn Fn() -> bool>>,
160 column: day_spec::ToolbarColumn,
161 window: RNode,
162 f: impl FnOnce() -> R,
163) -> R {
164 PAGE_STACK.with(|s| {
165 s.borrow_mut().push(PageFrame {
166 page,
167 active,
168 column,
169 window,
170 });
171 });
172 let _restore = std::mem::DropGuard::new((), |()| {
173 PAGE_STACK.with(|s| {
174 s.borrow_mut().pop();
175 });
176 });
177 f()
178}
179
180pub fn with_page_gated<R>(
184 page: RNode,
185 active: Option<Rc<dyn Fn() -> bool>>,
186 column: day_spec::ToolbarColumn,
187 f: impl FnOnce() -> R,
188) -> R {
189 with_page_in(page, active, column, window_being_built(), f)
190}
191
192pub fn current_page_window() -> RNode {
194 PAGE_STACK
195 .with(|s| s.borrow().last().map(|f| f.window))
196 .unwrap_or_else(window_being_built)
197}
198
199#[must_use]
201pub fn current_page_gate() -> Option<Rc<dyn Fn() -> bool>> {
202 PAGE_STACK.with(|s| s.borrow().last().and_then(|f| f.active.clone()))
203}
204
205#[must_use]
207pub fn current_page_column() -> day_spec::ToolbarColumn {
208 PAGE_STACK.with(|s| {
209 s.borrow()
210 .last()
211 .map_or(day_spec::ToolbarColumn::Window, |f| f.column)
212 })
213}
214
215#[must_use]
219pub fn window_being_built() -> RNode {
220 BUILDING
221 .with(std::cell::Cell::get)
222 .unwrap_or_else(|| with_tree(|t| t.root_node()))
223}
224
225#[must_use]
232pub fn current_chrome() -> Chrome {
233 match PAGE_STACK.with(|s| s.borrow().last().map(|f| f.page)) {
234 Some(page) => Chrome::Page(page),
235 None => Chrome::Window(window_being_built()),
236 }
237}
238
239pub fn register_toolbar_value(f: Rc<dyn Fn(&ToolbarValue)>) -> u64 {
242 let id = crate::menu::next_action_id();
243 VALUE_ACTIONS.with(|m| m.borrow_mut().insert(id, f));
244 id
245}
246
247pub fn dispatch_toolbar_value(action: u64, value: &ToolbarValue) {
251 mirror_value(action, value);
252 let target = resolve_slot(action);
253 let f = VALUE_ACTIONS.with(|m| m.borrow().get(&target).cloned());
254 if let Some(f) = f {
255 day_reactive::batch(|| f(value));
256 }
257}
258
259pub fn synthesize_toolbar_value(action: u64, value: &ToolbarValue) {
265 if let ToolbarValue::Text(text) = value {
266 let target = MODELS.with(|m| {
267 m.borrow().iter().find_map(|(c, items)| match c {
268 Chrome::Window(root) => items
269 .iter()
270 .find(|i| i.action == action)
271 .map(|i| (*root, i.id.clone())),
272 Chrome::Page(_) => None,
273 })
274 });
275 if let Some((root, item)) = target {
276 let patch = ToolbarPatch::Text {
277 item,
278 text: text.clone(),
279 };
280 if with_tree(|t| t.patch_window_toolbar(root, patch.clone())) {
281 deliver_value(root, &patch);
282 }
283 }
284 }
285 dispatch_toolbar_value(action, value);
286}
287
288pub(crate) fn resolve_slot(id: u64) -> u64 {
291 SLOT_TARGETS.with(|m| m.borrow().get(&id).copied().unwrap_or(id))
292}
293
294#[must_use]
297pub fn register_contribution(chrome: Chrome, items: Vec<ToolbarItem>) -> u64 {
298 register_contribution_gated(chrome, items, None)
299}
300
301#[must_use]
305pub fn register_contribution_gated(
306 chrome: Chrome,
307 items: Vec<ToolbarItem>,
308 active: Option<Rc<dyn Fn() -> bool>>,
309) -> u64 {
310 let token = NEXT_TOKEN.with(|n| {
311 let t = n.get();
312 n.set(t + 1);
313 t
314 });
315 let window = current_page_window();
316 CONTRIBUTIONS.with(|m| {
317 m.borrow_mut().insert(
318 token,
319 Contribution {
320 chrome,
321 seq: token,
322 items,
323 window,
324 document_window: day_reactive::Scope::current().use_context::<DocumentWindow>(),
325 active,
326 },
327 )
328 });
329 let _ = chrome;
330 schedule_recompose();
331 token
332}
333
334fn merged_window(root: RNode) -> Vec<ToolbarItem> {
337 let mut live: Vec<(u64, Vec<ToolbarItem>)> = CONTRIBUTIONS.with(|m| {
338 m.borrow()
339 .values()
340 .filter(|c| c.window() == root)
341 .filter(|c| {
342 c.active
343 .as_ref()
344 .is_none_or(|f| day_reactive::untrack(|| f()))
345 })
346 .map(|c| (c.seq, c.items.clone()))
347 .collect()
348 });
349 live.sort_by_key(|(seq, _)| *seq);
350 let mut out: Vec<ToolbarItem> = live.into_iter().flat_map(|(_, items)| items).collect();
351 out.sort_by_key(|i| placement_rank(i.placement));
352 out
353}
354
355pub fn update_contribution(token: u64, items: Vec<ToolbarItem>) {
357 let old = CONTRIBUTIONS.with(|m| {
358 let mut m = m.borrow_mut();
359 let c = m.get_mut(&token)?;
360 Some(std::mem::replace(&mut c.items, items))
361 });
362 if let Some(old) = old {
363 forget_closures(&old);
364 schedule_recompose();
365 }
366}
367
368pub fn relabel_contribution(token: u64, texts: &[(String, Option<String>)]) {
372 let Some(mut items) = CONTRIBUTIONS.with(|m| m.borrow().get(&token).map(|c| c.items.clone()))
373 else {
374 return;
375 };
376 for (item, (label, tooltip)) in items.iter_mut().zip(texts) {
377 item.label.clone_from(label);
378 item.tooltip.clone_from(tooltip);
379 }
380 update_contribution(token, items);
381}
382
383pub fn unregister_contribution(token: u64) {
386 let old = CONTRIBUTIONS.with(|m| m.borrow_mut().remove(&token).map(|c| c.items));
387 if let Some(old) = old {
388 forget_closures(&old);
389 schedule_recompose();
390 }
391}
392
393fn forget_closures(items: &[ToolbarItem]) {
400 let live: std::collections::HashSet<u64> = CONTRIBUTIONS.with(|m| {
401 m.borrow()
402 .values()
403 .flat_map(|c| c.items.iter().map(|i| i.action))
404 .collect()
405 });
406 for item in items
407 .iter()
408 .filter(|i| i.action != 0 && !live.contains(&i.action))
409 {
410 VALUE_ACTIONS.with(|m| m.borrow_mut().remove(&item.action));
411 if matches!(
412 item.kind,
413 day_spec::ToolbarItemKind::Button | day_spec::ToolbarItemKind::Menu { .. }
414 ) {
415 crate::menu::forget_action(item.action);
416 }
417 }
418}
419
420fn placement_rank(p: day_spec::ToolbarPlacement) -> u8 {
424 use day_spec::ToolbarPlacement as P;
425 match p {
426 P::Navigation => 0,
427 P::Principal => 1,
428 P::Automatic => 2,
429 P::Primary => 3,
430 P::Secondary | P::Bottom => 4,
431 }
432}
433
434fn mirror_value(action: u64, value: &ToolbarValue) {
443 let Some((chrome, id)) = MODELS.with(|m| {
447 let m = m.borrow();
448 let found = |window: bool| {
449 m.iter().find_map(|(c, items)| {
450 (matches!(c, Chrome::Window(_)) == window)
451 .then(|| items.iter().find(|i| i.action == action))
452 .flatten()
453 .map(|i| (*c, i.id.clone()))
454 })
455 };
456 found(true).or_else(|| found(false))
457 }) else {
458 return;
459 };
460 let patch = match value {
461 ToolbarValue::Text(text) => ToolbarPatch::Text {
462 item: id,
463 text: text.clone(),
464 },
465 ToolbarValue::On(on) => ToolbarPatch::On { item: id, on: *on },
466 ToolbarValue::Selected(index) => ToolbarPatch::Selected {
467 item: id,
468 index: *index,
469 },
470 ToolbarValue::Submit(_) => return,
472 };
473 CONTRIBUTIONS.with(|m| {
474 for c in m.borrow_mut().values_mut().filter(|c| match chrome {
475 Chrome::Window(root) => c.window() == root,
476 Chrome::Page(_) => c.chrome == chrome,
477 }) {
478 apply_to_model(&mut c.items, &patch);
479 }
480 });
481 MODELS.with(|m| {
482 if let Some((_, items)) = m.borrow_mut().iter_mut().find(|(c, _)| *c == chrome) {
483 apply_to_model(items, &patch);
484 }
485 });
486 if let Chrome::Window(root) = chrome {
487 deliver_value(root, &patch);
488 }
489}
490
491fn schedule_recompose() {
501 if RECOMPOSE_PENDING.with(|p| p.replace(true)) {
502 return;
503 }
504 day_reactive::at_turn_end(recompose_windows);
505}
506
507fn recompose_windows() {
516 recompose_serially(recompose_windows_inner);
517}
518
519fn recompose_serially(mut apply: impl FnMut()) {
524 if RECOMPOSING.with(|busy| busy.replace(true)) {
525 RECOMPOSE_AGAIN.with(|again| again.set(true));
526 return;
527 }
528 let _reset = std::mem::DropGuard::new((), |()| {
529 RECOMPOSING.with(|busy| busy.set(false));
530 RECOMPOSE_AGAIN.with(|again| again.set(false));
531 });
532 loop {
533 RECOMPOSE_AGAIN.with(|again| again.set(false));
534 apply();
535 if !RECOMPOSE_AGAIN.with(std::cell::Cell::get) {
536 break;
537 }
538 }
539}
540
541fn recompose_windows_inner() {
542 RECOMPOSE_PENDING.with(|p| p.set(false));
543 let roots: Vec<RNode> = {
544 let mut v: Vec<RNode> =
545 CONTRIBUTIONS.with(|m| m.borrow().values().map(Contribution::window).collect());
546 v.extend(MODELS.with(|m| {
548 m.borrow()
549 .iter()
550 .filter_map(|(c, _)| match c {
551 Chrome::Window(r) => Some(*r),
552 Chrome::Page(_) => None,
553 })
554 .collect::<Vec<_>>()
555 }));
556 v.sort();
557 v.dedup();
558 v
559 };
560 for root in roots {
561 let items = slot_model(root, unique_ids(merged_window(root)));
562 MODELS.with(|m| {
563 let mut m = m.borrow_mut();
564 match m.iter_mut().find(|(c, _)| *c == Chrome::Window(root)) {
565 Some(entry) => entry.1.clone_from(&items),
566 None => m.push((Chrome::Window(root), items.clone())),
567 }
568 });
569 let prev = DELIVERED.with(|d| d.borrow().get(&root).cloned().unwrap_or_default());
570 let (ops, patches) = diff_bar(&prev, &items);
571 if ops.is_empty() && patches.is_empty() {
572 continue;
573 }
574 debug_assert!(edit_is_ordered(&ops), "toolbar edit out of order: {ops:?}");
575 let delivered = ops.is_empty() || with_tree(|t| t.edit_window_toolbar(root, ops));
578 if !delivered {
579 continue;
580 }
581 for patch in patches {
582 with_tree(|t| t.patch_window_toolbar(root, patch));
583 }
584 DELIVERED.with(|d| d.borrow_mut().insert(root, items));
585 }
586}
587
588fn edit_is_ordered(ops: &[day_spec::ToolbarOp]) -> bool {
591 use day_spec::ToolbarOp as O;
592 let first_insert = ops
593 .iter()
594 .position(|o| matches!(o, O::Insert { .. }))
595 .unwrap_or(ops.len());
596 let inserts: Vec<usize> = ops[first_insert..]
597 .iter()
598 .filter_map(|o| match o {
599 O::Insert { index, .. } => Some(*index),
600 O::Remove { .. } => None,
601 })
602 .collect();
603 inserts.len() == ops.len() - first_insert && inserts.windows(2).all(|w| w[0] < w[1])
604}
605
606fn deliver_value(root: RNode, patch: &ToolbarPatch) {
609 DELIVERED.with(|d| {
610 if let Some(items) = d.borrow_mut().get_mut(&root) {
611 patch.apply_to(items);
612 }
613 });
614}
615
616fn unique_ids(items: Vec<ToolbarItem>) -> Vec<ToolbarItem> {
623 let mut seen = std::collections::HashSet::new();
624 items
625 .into_iter()
626 .filter(|i| {
627 let fresh = seen.insert(i.id.clone());
628 if !fresh {
629 log::warn!(
630 "toolbar item id {:?} appears twice in one window's bar; only the first is \
631 shown (docs/toolbars.md: ids are unique within a bar)",
632 i.id
633 );
634 }
635 fresh
636 })
637 .collect()
638}
639
640fn diff_bar(
650 prev: &[ToolbarItem],
651 next: &[ToolbarItem],
652) -> (Vec<day_spec::ToolbarOp>, Vec<ToolbarPatch>) {
653 use day_spec::ToolbarOp;
654 let matched: Vec<Option<usize>> = next
656 .iter()
657 .map(|n| {
658 prev.iter()
659 .position(|p| p.id == n.id)
660 .filter(|&at| shape_of(&prev[at]) == shape_of(n))
661 })
662 .collect();
663 let kept = longest_increasing(&matched);
664
665 let mut ops: Vec<ToolbarOp> = prev
666 .iter()
667 .enumerate()
668 .filter(|(at, _)| !kept.iter().any(|&k| matched[k] == Some(*at)))
669 .map(|(_, p)| ToolbarOp::Remove { id: p.id.clone() })
670 .collect();
671 let mut patches = Vec::new();
672 for (index, item) in next.iter().enumerate() {
673 if kept.contains(&index) {
674 let before = &prev[matched[index].unwrap_or_default()];
675 patches.extend(value_patches(before, item));
676 } else {
677 ops.push(ToolbarOp::Insert {
678 index,
679 item: item.clone(),
680 });
681 }
682 }
683 (ops, patches)
684}
685
686fn longest_increasing(seq: &[Option<usize>]) -> Vec<usize> {
688 let mut tails: Vec<usize> = Vec::new();
691 let mut back: Vec<Option<usize>> = vec![None; seq.len()];
692 for (i, v) in seq.iter().enumerate() {
693 let Some(v) = *v else { continue };
694 let k = tails.partition_point(|&t| seq[t].unwrap_or_default() < v);
695 back[i] = k.checked_sub(1).map(|p| tails[p]);
696 if k == tails.len() {
697 tails.push(i);
698 } else {
699 tails[k] = i;
700 }
701 }
702 let mut out = Vec::new();
703 let mut at = tails.last().copied();
704 while let Some(i) = at {
705 out.push(i);
706 at = back[i];
707 }
708 out.reverse();
709 out
710}
711
712fn value_patches(was: &ToolbarItem, now: &ToolbarItem) -> Vec<ToolbarPatch> {
714 use day_spec::ToolbarItemKind as K;
715 let item = now.id.clone();
716 let mut out = Vec::new();
717 match (&was.kind, &now.kind) {
718 (
719 K::Search {
720 text: t0,
721 suggestions: s0,
722 placeholder: p0,
723 },
724 K::Search {
725 text: t1,
726 suggestions: s1,
727 placeholder: p1,
728 },
729 ) => {
730 if t0 != t1 {
731 out.push(ToolbarPatch::Text {
732 item: item.clone(),
733 text: t1.clone(),
734 });
735 }
736 if s0 != s1 {
737 out.push(ToolbarPatch::Suggestions {
738 item: item.clone(),
739 list: s1.clone(),
740 });
741 }
742 if p0 != p1 {
743 out.push(ToolbarPatch::Placeholder {
744 item: item.clone(),
745 text: p1.clone(),
746 });
747 }
748 }
749 (K::Toggle { on: a }, K::Toggle { on: b }) if a != b => out.push(ToolbarPatch::On {
750 item: item.clone(),
751 on: *b,
752 }),
753 (K::Segmented { selected: a, .. }, K::Segmented { selected: b, .. }) if a != b => {
754 out.push(ToolbarPatch::Selected {
755 item: item.clone(),
756 index: *b,
757 });
758 }
759 _ => {}
760 }
761 if was.label != now.label || was.tooltip != now.tooltip {
762 out.push(ToolbarPatch::Label {
763 item: item.clone(),
764 label: now.label.clone(),
765 tooltip: now.tooltip.clone(),
766 });
767 }
768 if was.enabled != now.enabled {
769 out.push(ToolbarPatch::Enabled {
770 item,
771 on: now.enabled,
772 });
773 }
774 out
775}
776
777fn slot_model(root: RNode, mut items: Vec<ToolbarItem>) -> Vec<ToolbarItem> {
785 let mut live: Vec<u64> = Vec::new();
786 for item in &mut items {
787 let key = item.id.clone();
788 item.action = slot_for(root, &key, item.action, &mut live);
789 if let day_spec::ToolbarItemKind::Menu { items: entries } = &mut item.kind {
790 slot_menu(root, &key, entries, &mut live);
791 }
792 }
793 let keep: std::collections::HashSet<u64> = live.into_iter().collect();
796 SLOT_IDS.with(|ids| {
797 SLOT_TARGETS.with(|t| {
798 let mut t = t.borrow_mut();
799 for ((r, _), slot) in ids.borrow().iter() {
800 if *r == root && !keep.contains(slot) {
801 t.remove(slot);
802 }
803 }
804 });
805 });
806 items
807}
808
809fn slot_menu(root: RNode, parent: &str, entries: &mut [day_spec::MenuItem], live: &mut Vec<u64>) {
810 for (i, entry) in entries.iter_mut().enumerate() {
811 let key = format!("{parent}/{i}");
812 match entry {
813 day_spec::MenuItem::Action { action, .. } => {
814 *action = slot_for(root, &key, *action, live);
815 }
816 day_spec::MenuItem::Submenu { items, .. } => slot_menu(root, &key, items, live),
817 day_spec::MenuItem::Separator => {}
818 }
819 }
820}
821
822fn slot_for(root: RNode, key: &str, target: u64, live: &mut Vec<u64>) -> u64 {
825 if target == 0 {
826 return 0;
827 }
828 let slot = SLOT_IDS.with(|ids| {
829 *ids.borrow_mut()
830 .entry((root, key.to_string()))
831 .or_insert_with(crate::menu::next_action_id)
832 });
833 SLOT_TARGETS.with(|t| t.borrow_mut().insert(slot, target));
834 live.push(slot);
835 slot
836}
837
838pub fn chrome_changed() {
842 schedule_recompose();
843}
844
845pub fn patch_toolbar(patch: ToolbarPatch) {
848 let owner = MODELS.with(|m| {
849 m.borrow()
850 .iter()
851 .find(|(_, items)| items.iter().any(|i| i.id == patch.item()))
852 .map(|(c, _)| *c)
853 });
854 if let Some(chrome) = owner {
855 patch_chrome(chrome, patch);
856 }
857}
858
859#[expect(
862 clippy::needless_pass_by_value,
863 reason = "public signature; callers build the patch at the call site"
864)]
865pub fn patch_chrome(chrome: Chrome, patch: ToolbarPatch) {
866 let window = CONTRIBUTIONS.with(|m| {
869 let mut m = m.borrow_mut();
870 let mut window = None;
871 for c in m.values_mut() {
872 if c.chrome == chrome {
873 apply_to_model(&mut c.items, &patch);
874 window = Some(c.window());
875 }
876 }
877 window
878 });
879 let Some(root) = window else { return };
886 MODELS.with(|m| {
887 let mut m = m.borrow_mut();
888 if let Some((_, items)) = m.iter_mut().find(|(c, _)| *c == Chrome::Window(root)) {
889 apply_to_model(items, &patch);
890 }
891 });
892 if with_tree(|t| t.patch_window_toolbar(root, patch.clone())) {
893 deliver_value(root, &patch);
894 }
895}
896
897fn apply_to_model(items: &mut [ToolbarItem], patch: &ToolbarPatch) {
899 patch.apply_to(items);
900}
901
902fn shape_of(item: &ToolbarItem) -> ToolbarItem {
905 use day_spec::ToolbarItemKind as K;
906 let mut i = item.clone();
907 i.enabled = true;
908 i.label.clear();
910 i.tooltip = None;
911 match &mut i.kind {
912 K::Search {
913 text,
914 suggestions,
915 placeholder,
916 } => {
917 text.clear();
918 suggestions.clear();
919 placeholder.clear();
920 }
921 K::Toggle { on } => *on = false,
922 K::Segmented { selected, .. } => *selected = 0,
923 _ => {}
924 }
925 i
926}
927
928#[must_use]
932pub fn toolbar_model() -> Vec<ToolbarItem> {
933 MODELS.with(|m| m.borrow().iter().flat_map(|(_, i)| i.clone()).collect())
934}
935
936pub fn toggle_sidebar(host: RNode) -> bool {
942 with_tree(|t| t.toggle_sidebar(host))
943}
944
945pub(crate) fn forget_window(root: RNode) {
954 let gone: Vec<ToolbarItem> = CONTRIBUTIONS.with(|m| {
955 let mut m = m.borrow_mut();
956 let mut gone = Vec::new();
957 m.retain(|_, c| {
958 let mine = c.window() == root;
959 if mine {
960 gone.extend(c.items.clone());
961 }
962 !mine
963 });
964 gone
965 });
966 forget_closures(&gone);
967 MODELS.with(|m| {
968 m.borrow_mut()
969 .retain(|(c, _)| !matches!(c, Chrome::Window(r) if *r == root));
970 });
971 DELIVERED.with(|d| {
972 d.borrow_mut().remove(&root);
973 });
974 SLOT_IDS.with(|ids| {
975 SLOT_TARGETS.with(|t| {
976 let mut t = t.borrow_mut();
977 ids.borrow_mut().retain(|(r, _), slot| {
978 if *r == root {
979 t.remove(slot);
980 }
981 *r != root
982 });
983 });
984 });
985}
986
987pub fn reset_toolbars() {
989 MODELS.with(|m| m.borrow_mut().clear());
990 CONTRIBUTIONS.with(|m| m.borrow_mut().clear());
991 VALUE_ACTIONS.with(|m| m.borrow_mut().clear());
992 SLOT_IDS.with(|m| m.borrow_mut().clear());
993 SLOT_TARGETS.with(|m| m.borrow_mut().clear());
994 DELIVERED.with(|m| m.borrow_mut().clear());
995 RECOMPOSE_PENDING.with(|p| p.set(false));
996 PAGE_STACK.with(|s| s.borrow_mut().clear());
997 BUILDING.with(|b| b.set(None));
998}
999
1000#[must_use]
1003pub fn focus_toolbar_search() -> bool {
1004 let root = crate::windows::focused_root();
1005 let has = MODELS.with(|models| {
1006 models.borrow().iter().any(|(chrome, items)| {
1007 *chrome == Chrome::Window(root)
1008 && items.iter().any(|item| item.id == day_spec::SEARCH_ITEM_ID)
1009 })
1010 });
1011 if has {
1012 with_tree(|t| {
1013 t.patch_window_toolbar(
1014 root,
1015 ToolbarPatch::Focus {
1016 item: day_spec::SEARCH_ITEM_ID.to_owned(),
1017 },
1018 )
1019 });
1020 }
1021 has
1022}
1023
1024#[cfg(test)]
1025mod tests {
1026
1027 #[test]
1028 fn native_events_recompose_after_the_delivered_baseline_is_recorded() {
1029 let passes = std::cell::Cell::new(0);
1030 let delivered = std::cell::Cell::new(false);
1031 super::recompose_serially(|| {
1032 passes.set(passes.get() + 1);
1033 if passes.get() == 1 {
1034 super::recompose_serially(|| panic!("must not diff the stale baseline"));
1036 super::recompose_serially(|| panic!("nested requests must coalesce"));
1037 delivered.set(true);
1038 } else {
1039 assert!(delivered.get());
1040 }
1041 });
1042 assert_eq!(passes.get(), 2);
1043 super::recompose_serially(|| passes.set(passes.get() + 1));
1044 assert_eq!(passes.get(), 3, "the guard releases after a settled update");
1045 }
1046 use super::*;
1047 use day_spec::{ToolbarItemKind as K, ToolbarMirror, ToolbarOp};
1048
1049 fn item(id: &str, label: &str) -> ToolbarItem {
1050 ToolbarItem {
1051 id: id.into(),
1052 kind: K::Button,
1053 label: label.into(),
1054 tooltip: None,
1055 icon: None,
1056 enabled: true,
1057 action: 0,
1058 placement: day_spec::ToolbarPlacement::Automatic,
1059 label_style: day_spec::LabelStyle::Automatic,
1060 prominent: false,
1061 column: day_spec::ToolbarColumn::Window,
1062 }
1063 }
1064
1065 fn check(prev: &[ToolbarItem], next: &[ToolbarItem]) -> Vec<ToolbarOp> {
1067 let (ops, patches) = diff_bar(prev, next);
1068 let mut mirror = ToolbarMirror::default();
1069 for (i, p) in prev.iter().enumerate() {
1070 mirror.insert(i, p.clone());
1071 }
1072 let first_insert = ops
1074 .iter()
1075 .position(|o| matches!(o, ToolbarOp::Insert { .. }))
1076 .unwrap_or(ops.len());
1077 assert!(
1078 ops[first_insert..]
1079 .iter()
1080 .all(|o| matches!(o, ToolbarOp::Insert { .. }))
1081 );
1082 for op in &ops {
1083 mirror.apply(op);
1084 }
1085 for p in &patches {
1086 mirror.patch(p);
1087 }
1088 assert_eq!(mirror.items(), next);
1089 ops
1090 }
1091
1092 #[test]
1093 fn identical_bars_need_no_edit() {
1094 let bar = vec![item("a", "A"), item("b", "B")];
1095 assert_eq!(check(&bar, &bar), [] as [day_spec::ToolbarOp; 0]);
1096 }
1097
1098 #[test]
1099 fn inserts_and_removes_touch_only_their_items() {
1100 let prev = vec![item("a", "A"), item("b", "B"), item("search", "S")];
1101 let next = vec![item("a", "A"), item("c", "C"), item("search", "S")];
1102 let ops = check(&prev, &next);
1103 assert_eq!(ops.len(), 2);
1104 assert!(ops.iter().all(|o| match o {
1105 ToolbarOp::Remove { id } => id == "b",
1106 ToolbarOp::Insert { item, index } => item.id == "c" && *index == 1,
1107 }));
1108 }
1109
1110 #[test]
1111 fn a_reorder_moves_the_fewest_items() {
1112 let prev = vec![
1113 item("a", "A"),
1114 item("b", "B"),
1115 item("c", "C"),
1116 item("d", "D"),
1117 ];
1118 let next = vec![
1119 item("d", "D"),
1120 item("a", "A"),
1121 item("b", "B"),
1122 item("c", "C"),
1123 ];
1124 let ops = check(&prev, &next);
1125 assert_eq!(ops.len(), 2, "{ops:?}");
1127 }
1128
1129 #[test]
1130 fn a_value_change_is_a_patch_and_a_label_change_an_edit() {
1131 let mut toggled = item("t", "T");
1132 toggled.kind = K::Toggle { on: false };
1133 let mut on = toggled.clone();
1134 on.kind = K::Toggle { on: true };
1135 on.enabled = false;
1136 let (ops, patches) = diff_bar(std::slice::from_ref(&toggled), std::slice::from_ref(&on));
1137 assert_eq!(ops, [] as [day_spec::ToolbarOp; 0]);
1138 assert_eq!(patches.len(), 2);
1139 check(&[item("x", "Old")], &[item("x", "New")]);
1140 }
1141
1142 #[test]
1143 fn longest_increasing_skips_unmatched() {
1144 assert_eq!(
1145 longest_increasing(&[Some(2), None, Some(0), Some(1), Some(3)]),
1146 vec![2, 3, 4]
1147 );
1148 assert_eq!(longest_increasing(&[None, None]), [] as [usize; 0]);
1149 }
1150}