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 pub fn new(root: RNode) -> Self {
76 Self(Rc::new(Cell::new(root)))
77 }
78 pub fn set(&self, root: RNode) {
79 if self.0.replace(root) != root {
80 schedule_recompose();
81 }
82 }
83}
84impl Contribution {
85 fn window(&self) -> RNode {
86 self.document_window
87 .as_ref()
88 .map_or(self.window, |w| w.0.get())
89 }
90}
91
92day_reactive::tls_slots! {
93 toolbar;
94 static VALUE_ACTIONS: RefCell<HashMap<u64, ValueAction>> = RefCell::new(HashMap::new());
98 static CONTRIBUTIONS: RefCell<HashMap<u64, Contribution>> = RefCell::new(HashMap::new());
100 static MODELS: RefCell<Vec<(Chrome, Vec<ToolbarItem>)>> = const { RefCell::new(Vec::new()) };
104 static SLOT_IDS: RefCell<HashMap<(RNode, String), u64>> = RefCell::new(HashMap::new());
107 static SLOT_TARGETS: RefCell<HashMap<u64, u64>> = RefCell::new(HashMap::new());
109 static DELIVERED: RefCell<HashMap<RNode, Vec<ToolbarItem>>> = RefCell::new(HashMap::new());
114 static RECOMPOSE_PENDING: Cell<bool> = const { Cell::new(false) };
116 static RECOMPOSING: Cell<bool> = const { Cell::new(false) };
117 static RECOMPOSE_AGAIN: Cell<bool> = const { Cell::new(false) };
118 static NEXT_TOKEN: Cell<u64> = const { Cell::new(1) };
120 static BUILDING: Cell<Option<RNode>> = const { Cell::new(None) };
122 static PAGE_STACK: RefCell<Vec<PageFrame>> = RefCell::new(Vec::new());
126}
127
128pub fn with_window<R>(root: RNode, f: impl FnOnce() -> R) -> R {
133 struct Restore(Option<RNode>);
137 impl Drop for Restore {
138 fn drop(&mut self) {
139 BUILDING.with(|b| b.set(self.0));
140 }
141 }
142 let _restore = Restore(BUILDING.with(|b| b.replace(Some(root))));
143 f()
144}
145
146pub fn with_page<R>(page: RNode, f: impl FnOnce() -> R) -> R {
149 with_page_in(
150 page,
151 None,
152 day_spec::ToolbarColumn::Detail,
153 window_being_built(),
154 f,
155 )
156}
157
158pub fn with_page_in<R>(
161 page: RNode,
162 active: Option<Rc<dyn Fn() -> bool>>,
163 column: day_spec::ToolbarColumn,
164 window: RNode,
165 f: impl FnOnce() -> R,
166) -> R {
167 struct Restore;
168 impl Drop for Restore {
169 fn drop(&mut self) {
170 PAGE_STACK.with(|s| {
171 s.borrow_mut().pop();
172 });
173 }
174 }
175 PAGE_STACK.with(|s| {
176 s.borrow_mut().push(PageFrame {
177 page,
178 active,
179 column,
180 window,
181 })
182 });
183 let _restore = Restore;
184 f()
185}
186
187pub fn with_page_gated<R>(
191 page: RNode,
192 active: Option<Rc<dyn Fn() -> bool>>,
193 column: day_spec::ToolbarColumn,
194 f: impl FnOnce() -> R,
195) -> R {
196 with_page_in(page, active, column, window_being_built(), f)
197}
198
199pub fn current_page_window() -> RNode {
201 PAGE_STACK
202 .with(|s| s.borrow().last().map(|f| f.window))
203 .unwrap_or_else(window_being_built)
204}
205
206pub fn current_page_gate() -> Option<Rc<dyn Fn() -> bool>> {
208 PAGE_STACK.with(|s| s.borrow().last().and_then(|f| f.active.clone()))
209}
210
211pub fn current_page_column() -> day_spec::ToolbarColumn {
213 PAGE_STACK.with(|s| {
214 s.borrow()
215 .last()
216 .map(|f| f.column)
217 .unwrap_or(day_spec::ToolbarColumn::Window)
218 })
219}
220
221pub fn window_being_built() -> RNode {
225 BUILDING
226 .with(|b| b.get())
227 .unwrap_or_else(|| with_tree(|t| t.root_node()))
228}
229
230pub fn current_chrome() -> Chrome {
237 match PAGE_STACK.with(|s| s.borrow().last().map(|f| f.page)) {
238 Some(page) => Chrome::Page(page),
239 None => Chrome::Window(window_being_built()),
240 }
241}
242
243pub fn register_toolbar_value(f: Rc<dyn Fn(&ToolbarValue)>) -> u64 {
246 let id = crate::menu::next_action_id();
247 VALUE_ACTIONS.with(|m| m.borrow_mut().insert(id, f));
248 id
249}
250
251pub fn dispatch_toolbar_value(action: u64, value: &ToolbarValue) {
255 mirror_value(action, value);
256 let target = resolve_slot(action);
257 let f = VALUE_ACTIONS.with(|m| m.borrow().get(&target).cloned());
258 if let Some(f) = f {
259 day_reactive::batch(|| f(value));
260 }
261}
262
263pub fn synthesize_toolbar_value(action: u64, value: &ToolbarValue) {
269 if let ToolbarValue::Text(text) = value {
270 let target = MODELS.with(|m| {
271 m.borrow().iter().find_map(|(c, items)| match c {
272 Chrome::Window(root) => items
273 .iter()
274 .find(|i| i.action == action)
275 .map(|i| (*root, i.id.clone())),
276 Chrome::Page(_) => None,
277 })
278 });
279 if let Some((root, item)) = target {
280 let patch = ToolbarPatch::Text {
281 item,
282 text: text.clone(),
283 };
284 if with_tree(|t| t.patch_window_toolbar(root, patch.clone())) {
285 deliver_value(root, &patch);
286 }
287 }
288 }
289 dispatch_toolbar_value(action, value);
290}
291
292pub(crate) fn resolve_slot(id: u64) -> u64 {
295 SLOT_TARGETS.with(|m| m.borrow().get(&id).copied().unwrap_or(id))
296}
297
298pub fn register_contribution(chrome: Chrome, items: Vec<ToolbarItem>) -> u64 {
301 register_contribution_gated(chrome, items, None)
302}
303
304pub fn register_contribution_gated(
308 chrome: Chrome,
309 items: Vec<ToolbarItem>,
310 active: Option<Rc<dyn Fn() -> bool>>,
311) -> u64 {
312 let token = NEXT_TOKEN.with(|n| {
313 let t = n.get();
314 n.set(t + 1);
315 t
316 });
317 let window = current_page_window();
318 CONTRIBUTIONS.with(|m| {
319 m.borrow_mut().insert(
320 token,
321 Contribution {
322 chrome,
323 seq: token,
324 items,
325 window,
326 document_window: day_reactive::Scope::current().use_context::<DocumentWindow>(),
327 active,
328 },
329 )
330 });
331 let _ = chrome;
332 schedule_recompose();
333 token
334}
335
336fn merged_window(root: RNode) -> Vec<ToolbarItem> {
339 let mut live: Vec<(u64, Vec<ToolbarItem>)> = CONTRIBUTIONS.with(|m| {
340 m.borrow()
341 .values()
342 .filter(|c| c.window() == root)
343 .filter(|c| {
344 c.active
345 .as_ref()
346 .is_none_or(|f| day_reactive::untrack(|| f()))
347 })
348 .map(|c| (c.seq, c.items.clone()))
349 .collect()
350 });
351 live.sort_by_key(|(seq, _)| *seq);
352 let mut out: Vec<ToolbarItem> = live.into_iter().flat_map(|(_, items)| items).collect();
353 out.sort_by_key(|i| placement_rank(i.placement));
354 out
355}
356
357pub fn update_contribution(token: u64, items: Vec<ToolbarItem>) {
359 let old = CONTRIBUTIONS.with(|m| {
360 let mut m = m.borrow_mut();
361 let c = m.get_mut(&token)?;
362 Some(std::mem::replace(&mut c.items, items))
363 });
364 if let Some(old) = old {
365 forget_closures(&old);
366 schedule_recompose();
367 }
368}
369
370pub fn relabel_contribution(token: u64, texts: &[(String, Option<String>)]) {
374 let Some(mut items) = CONTRIBUTIONS.with(|m| m.borrow().get(&token).map(|c| c.items.clone()))
375 else {
376 return;
377 };
378 for (item, (label, tooltip)) in items.iter_mut().zip(texts) {
379 item.label = label.clone();
380 item.tooltip = tooltip.clone();
381 }
382 update_contribution(token, items);
383}
384
385pub fn unregister_contribution(token: u64) {
388 let old = CONTRIBUTIONS.with(|m| m.borrow_mut().remove(&token).map(|c| c.items));
389 if let Some(old) = old {
390 forget_closures(&old);
391 schedule_recompose();
392 }
393}
394
395fn forget_closures(items: &[ToolbarItem]) {
402 let live: std::collections::HashSet<u64> = CONTRIBUTIONS.with(|m| {
403 m.borrow()
404 .values()
405 .flat_map(|c| c.items.iter().map(|i| i.action))
406 .collect()
407 });
408 for item in items
409 .iter()
410 .filter(|i| i.action != 0 && !live.contains(&i.action))
411 {
412 VALUE_ACTIONS.with(|m| m.borrow_mut().remove(&item.action));
413 if matches!(
414 item.kind,
415 day_spec::ToolbarItemKind::Button | day_spec::ToolbarItemKind::Menu { .. }
416 ) {
417 crate::menu::forget_action(item.action);
418 }
419 }
420}
421
422fn placement_rank(p: day_spec::ToolbarPlacement) -> u8 {
426 use day_spec::ToolbarPlacement as P;
427 match p {
428 P::Navigation => 0,
429 P::Principal => 1,
430 P::Automatic => 2,
431 P::Primary => 3,
432 P::Secondary | P::Bottom => 4,
433 }
434}
435
436fn mirror_value(action: u64, value: &ToolbarValue) {
445 let Some((chrome, id)) = MODELS.with(|m| {
449 let m = m.borrow();
450 let found = |window: bool| {
451 m.iter().find_map(|(c, items)| {
452 (matches!(c, Chrome::Window(_)) == window)
453 .then(|| items.iter().find(|i| i.action == action))
454 .flatten()
455 .map(|i| (*c, i.id.clone()))
456 })
457 };
458 found(true).or_else(|| found(false))
459 }) else {
460 return;
461 };
462 let patch = match value {
463 ToolbarValue::Text(text) => ToolbarPatch::Text {
464 item: id,
465 text: text.clone(),
466 },
467 ToolbarValue::On(on) => ToolbarPatch::On { item: id, on: *on },
468 ToolbarValue::Selected(index) => ToolbarPatch::Selected {
469 item: id,
470 index: *index,
471 },
472 ToolbarValue::Submit(_) => return,
474 };
475 CONTRIBUTIONS.with(|m| {
476 for c in m.borrow_mut().values_mut().filter(|c| match chrome {
477 Chrome::Window(root) => c.window() == root,
478 Chrome::Page(_) => c.chrome == chrome,
479 }) {
480 apply_to_model(&mut c.items, &patch);
481 }
482 });
483 MODELS.with(|m| {
484 if let Some((_, items)) = m.borrow_mut().iter_mut().find(|(c, _)| *c == chrome) {
485 apply_to_model(items, &patch);
486 }
487 });
488 if let Chrome::Window(root) = chrome {
489 deliver_value(root, &patch);
490 }
491}
492
493fn schedule_recompose() {
503 if RECOMPOSE_PENDING.with(|p| p.replace(true)) {
504 return;
505 }
506 day_reactive::at_turn_end(recompose_windows);
507}
508
509fn recompose_windows() {
518 recompose_serially(recompose_windows_inner);
519}
520
521fn recompose_serially(mut apply: impl FnMut()) {
526 if RECOMPOSING.with(|busy| busy.replace(true)) {
527 RECOMPOSE_AGAIN.with(|again| again.set(true));
528 return;
529 }
530 struct Reset;
531 impl Drop for Reset {
532 fn drop(&mut self) {
533 RECOMPOSING.with(|busy| busy.set(false));
534 RECOMPOSE_AGAIN.with(|again| again.set(false));
535 }
536 }
537 let _reset = Reset;
538 loop {
539 RECOMPOSE_AGAIN.with(|again| again.set(false));
540 apply();
541 if !RECOMPOSE_AGAIN.with(|again| again.get()) {
542 break;
543 }
544 }
545}
546
547fn recompose_windows_inner() {
548 RECOMPOSE_PENDING.with(|p| p.set(false));
549 let roots: Vec<RNode> = {
550 let mut v: Vec<RNode> =
551 CONTRIBUTIONS.with(|m| m.borrow().values().map(|c| c.window()).collect());
552 v.extend(MODELS.with(|m| {
554 m.borrow()
555 .iter()
556 .filter_map(|(c, _)| match c {
557 Chrome::Window(r) => Some(*r),
558 Chrome::Page(_) => None,
559 })
560 .collect::<Vec<_>>()
561 }));
562 v.sort();
563 v.dedup();
564 v
565 };
566 for root in roots {
567 let items = slot_model(root, unique_ids(merged_window(root)));
568 MODELS.with(|m| {
569 let mut m = m.borrow_mut();
570 match m.iter_mut().find(|(c, _)| *c == Chrome::Window(root)) {
571 Some(entry) => entry.1 = items.clone(),
572 None => m.push((Chrome::Window(root), items.clone())),
573 }
574 });
575 let prev = DELIVERED.with(|d| d.borrow().get(&root).cloned().unwrap_or_default());
576 let (ops, patches) = diff_bar(&prev, &items);
577 if ops.is_empty() && patches.is_empty() {
578 continue;
579 }
580 debug_assert!(edit_is_ordered(&ops), "toolbar edit out of order: {ops:?}");
581 let delivered = ops.is_empty() || with_tree(|t| t.edit_window_toolbar(root, ops));
584 if !delivered {
585 continue;
586 }
587 for patch in patches {
588 with_tree(|t| t.patch_window_toolbar(root, patch));
589 }
590 DELIVERED.with(|d| d.borrow_mut().insert(root, items));
591 }
592}
593
594fn edit_is_ordered(ops: &[day_spec::ToolbarOp]) -> bool {
597 use day_spec::ToolbarOp as O;
598 let first_insert = ops
599 .iter()
600 .position(|o| matches!(o, O::Insert { .. }))
601 .unwrap_or(ops.len());
602 let inserts: Vec<usize> = ops[first_insert..]
603 .iter()
604 .filter_map(|o| match o {
605 O::Insert { index, .. } => Some(*index),
606 O::Remove { .. } => None,
607 })
608 .collect();
609 inserts.len() == ops.len() - first_insert && inserts.windows(2).all(|w| w[0] < w[1])
610}
611
612fn deliver_value(root: RNode, patch: &ToolbarPatch) {
615 DELIVERED.with(|d| {
616 if let Some(items) = d.borrow_mut().get_mut(&root) {
617 patch.apply_to(items);
618 }
619 });
620}
621
622fn unique_ids(items: Vec<ToolbarItem>) -> Vec<ToolbarItem> {
629 let mut seen = std::collections::HashSet::new();
630 items
631 .into_iter()
632 .filter(|i| {
633 let fresh = seen.insert(i.id.clone());
634 if !fresh {
635 log::warn!(
636 "toolbar item id {:?} appears twice in one window's bar; only the first is \
637 shown (docs/toolbars.md: ids are unique within a bar)",
638 i.id
639 );
640 }
641 fresh
642 })
643 .collect()
644}
645
646fn diff_bar(
656 prev: &[ToolbarItem],
657 next: &[ToolbarItem],
658) -> (Vec<day_spec::ToolbarOp>, Vec<ToolbarPatch>) {
659 use day_spec::ToolbarOp;
660 let matched: Vec<Option<usize>> = next
662 .iter()
663 .map(|n| {
664 prev.iter()
665 .position(|p| p.id == n.id)
666 .filter(|&at| shape_of(&prev[at]) == shape_of(n))
667 })
668 .collect();
669 let kept = longest_increasing(&matched);
670
671 let mut ops: Vec<ToolbarOp> = prev
672 .iter()
673 .enumerate()
674 .filter(|(at, _)| !kept.iter().any(|&k| matched[k] == Some(*at)))
675 .map(|(_, p)| ToolbarOp::Remove { id: p.id.clone() })
676 .collect();
677 let mut patches = Vec::new();
678 for (index, item) in next.iter().enumerate() {
679 if kept.contains(&index) {
680 let before = &prev[matched[index].unwrap_or_default()];
681 patches.extend(value_patches(before, item));
682 } else {
683 ops.push(ToolbarOp::Insert {
684 index,
685 item: item.clone(),
686 });
687 }
688 }
689 (ops, patches)
690}
691
692fn longest_increasing(seq: &[Option<usize>]) -> Vec<usize> {
694 let mut tails: Vec<usize> = Vec::new();
697 let mut back: Vec<Option<usize>> = vec![None; seq.len()];
698 for (i, v) in seq.iter().enumerate() {
699 let Some(v) = *v else { continue };
700 let k = tails.partition_point(|&t| seq[t].unwrap_or_default() < v);
701 back[i] = k.checked_sub(1).map(|p| tails[p]);
702 if k == tails.len() {
703 tails.push(i);
704 } else {
705 tails[k] = i;
706 }
707 }
708 let mut out = Vec::new();
709 let mut at = tails.last().copied();
710 while let Some(i) = at {
711 out.push(i);
712 at = back[i];
713 }
714 out.reverse();
715 out
716}
717
718fn value_patches(was: &ToolbarItem, now: &ToolbarItem) -> Vec<ToolbarPatch> {
720 use day_spec::ToolbarItemKind as K;
721 let item = now.id.clone();
722 let mut out = Vec::new();
723 match (&was.kind, &now.kind) {
724 (
725 K::Search {
726 text: t0,
727 suggestions: s0,
728 placeholder: p0,
729 },
730 K::Search {
731 text: t1,
732 suggestions: s1,
733 placeholder: p1,
734 },
735 ) => {
736 if t0 != t1 {
737 out.push(ToolbarPatch::Text {
738 item: item.clone(),
739 text: t1.clone(),
740 });
741 }
742 if s0 != s1 {
743 out.push(ToolbarPatch::Suggestions {
744 item: item.clone(),
745 list: s1.clone(),
746 });
747 }
748 if p0 != p1 {
749 out.push(ToolbarPatch::Placeholder {
750 item: item.clone(),
751 text: p1.clone(),
752 });
753 }
754 }
755 (K::Toggle { on: a }, K::Toggle { on: b }) if a != b => out.push(ToolbarPatch::On {
756 item: item.clone(),
757 on: *b,
758 }),
759 (K::Segmented { selected: a, .. }, K::Segmented { selected: b, .. }) if a != b => {
760 out.push(ToolbarPatch::Selected {
761 item: item.clone(),
762 index: *b,
763 })
764 }
765 _ => {}
766 }
767 if was.label != now.label || was.tooltip != now.tooltip {
768 out.push(ToolbarPatch::Label {
769 item: item.clone(),
770 label: now.label.clone(),
771 tooltip: now.tooltip.clone(),
772 });
773 }
774 if was.enabled != now.enabled {
775 out.push(ToolbarPatch::Enabled {
776 item,
777 on: now.enabled,
778 });
779 }
780 out
781}
782
783fn slot_model(root: RNode, mut items: Vec<ToolbarItem>) -> Vec<ToolbarItem> {
791 let mut live: Vec<u64> = Vec::new();
792 for item in &mut items {
793 let key = item.id.clone();
794 item.action = slot_for(root, &key, item.action, &mut live);
795 if let day_spec::ToolbarItemKind::Menu { items: entries } = &mut item.kind {
796 slot_menu(root, &key, entries, &mut live);
797 }
798 }
799 let keep: std::collections::HashSet<u64> = live.into_iter().collect();
802 SLOT_IDS.with(|ids| {
803 SLOT_TARGETS.with(|t| {
804 let mut t = t.borrow_mut();
805 for ((r, _), slot) in ids.borrow().iter() {
806 if *r == root && !keep.contains(slot) {
807 t.remove(slot);
808 }
809 }
810 })
811 });
812 items
813}
814
815fn slot_menu(root: RNode, parent: &str, entries: &mut [day_spec::MenuItem], live: &mut Vec<u64>) {
816 for (i, entry) in entries.iter_mut().enumerate() {
817 let key = format!("{parent}/{i}");
818 match entry {
819 day_spec::MenuItem::Action { action, .. } => {
820 *action = slot_for(root, &key, *action, live);
821 }
822 day_spec::MenuItem::Submenu { items, .. } => slot_menu(root, &key, items, live),
823 day_spec::MenuItem::Separator => {}
824 }
825 }
826}
827
828fn slot_for(root: RNode, key: &str, target: u64, live: &mut Vec<u64>) -> u64 {
831 if target == 0 {
832 return 0;
833 }
834 let slot = SLOT_IDS.with(|ids| {
835 *ids.borrow_mut()
836 .entry((root, key.to_string()))
837 .or_insert_with(crate::menu::next_action_id)
838 });
839 SLOT_TARGETS.with(|t| t.borrow_mut().insert(slot, target));
840 live.push(slot);
841 slot
842}
843
844pub fn chrome_changed() {
848 schedule_recompose();
849}
850
851pub fn patch_toolbar(patch: ToolbarPatch) {
854 let owner = MODELS.with(|m| {
855 m.borrow()
856 .iter()
857 .find(|(_, items)| items.iter().any(|i| i.id == patch.item()))
858 .map(|(c, _)| *c)
859 });
860 if let Some(chrome) = owner {
861 patch_chrome(chrome, patch);
862 }
863}
864
865pub fn patch_chrome(chrome: Chrome, patch: ToolbarPatch) {
868 let window = CONTRIBUTIONS.with(|m| {
871 let mut m = m.borrow_mut();
872 let mut window = None;
873 for c in m.values_mut() {
874 if c.chrome == chrome {
875 apply_to_model(&mut c.items, &patch);
876 window = Some(c.window());
877 }
878 }
879 window
880 });
881 let Some(root) = window else { return };
888 MODELS.with(|m| {
889 let mut m = m.borrow_mut();
890 if let Some((_, items)) = m.iter_mut().find(|(c, _)| *c == Chrome::Window(root)) {
891 apply_to_model(items, &patch);
892 }
893 });
894 if with_tree(|t| t.patch_window_toolbar(root, patch.clone())) {
895 deliver_value(root, &patch);
896 }
897}
898
899fn apply_to_model(items: &mut [ToolbarItem], patch: &ToolbarPatch) {
901 patch.apply_to(items);
902}
903
904fn shape_of(item: &ToolbarItem) -> ToolbarItem {
907 use day_spec::ToolbarItemKind as K;
908 let mut i = item.clone();
909 i.enabled = true;
910 i.label.clear();
912 i.tooltip = None;
913 match &mut i.kind {
914 K::Search {
915 text,
916 suggestions,
917 placeholder,
918 } => {
919 text.clear();
920 suggestions.clear();
921 placeholder.clear();
922 }
923 K::Toggle { on } => *on = false,
924 K::Segmented { selected, .. } => *selected = 0,
925 _ => {}
926 }
927 i
928}
929
930pub fn toolbar_model() -> Vec<ToolbarItem> {
934 MODELS.with(|m| m.borrow().iter().flat_map(|(_, i)| i.clone()).collect())
935}
936
937pub fn toggle_sidebar(host: RNode) -> bool {
943 with_tree(|t| t.toggle_sidebar(host))
944}
945
946pub(crate) fn forget_window(root: RNode) {
955 let gone: Vec<ToolbarItem> = CONTRIBUTIONS.with(|m| {
956 let mut m = m.borrow_mut();
957 let mut gone = Vec::new();
958 m.retain(|_, c| {
959 let mine = c.window() == root;
960 if mine {
961 gone.extend(c.items.clone());
962 }
963 !mine
964 });
965 gone
966 });
967 forget_closures(&gone);
968 MODELS.with(|m| {
969 m.borrow_mut()
970 .retain(|(c, _)| !matches!(c, Chrome::Window(r) if *r == root))
971 });
972 DELIVERED.with(|d| {
973 d.borrow_mut().remove(&root);
974 });
975 SLOT_IDS.with(|ids| {
976 SLOT_TARGETS.with(|t| {
977 let mut t = t.borrow_mut();
978 ids.borrow_mut().retain(|(r, _), slot| {
979 if *r == root {
980 t.remove(slot);
981 }
982 *r != root
983 });
984 })
985 });
986}
987
988pub fn reset_toolbars() {
990 MODELS.with(|m| m.borrow_mut().clear());
991 CONTRIBUTIONS.with(|m| m.borrow_mut().clear());
992 VALUE_ACTIONS.with(|m| m.borrow_mut().clear());
993 SLOT_IDS.with(|m| m.borrow_mut().clear());
994 SLOT_TARGETS.with(|m| m.borrow_mut().clear());
995 DELIVERED.with(|m| m.borrow_mut().clear());
996 RECOMPOSE_PENDING.with(|p| p.set(false));
997 PAGE_STACK.with(|s| s.borrow_mut().clear());
998 BUILDING.with(|b| b.set(None));
999}
1000
1001pub 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!(check(&bar, &bar).is_empty());
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!(ops.is_empty());
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!(longest_increasing(&[None, None]).is_empty());
1149 }
1150}