Skip to main content

day_core/
toolbar.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Toolbar contributions (docs/toolbars.md). The model ([`day_spec::ToolbarItem`]) is
5//! toolkit-neutral and carries only ids for its commands; the closures live here, keyed by
6//! id, the same shape as [`crate::menu`] and the same id space, so one closure can
7//! back both a toolbar button and its menu-bar twin.
8//!
9//! Any piece can declare items. Where it sits decides which chrome carries them (the window's
10//! own, or one navigation page's), and its scope decides how long they stay: a contribution is
11//! withdrawn when the piece that registered it is disposed, so a command leaves with the content
12//! it acts on. Several pieces may contribute to one chrome; this module merges them in
13//! registration order and hands the result to the toolkit as one model.
14
15use 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
23/// A toolbar item's value callback: what a search field's text or a toggle's state runs.
24type ValueAction = Rc<dyn Fn(&ToolbarValue)>;
25
26/// Which chrome a contribution lands on.
27///
28/// Not a placement; [`day_spec::ToolbarPlacement`] says where on a chrome an item sits. This
29/// says which chrome, and it is never written by an app: it follows from the piece that declared
30/// the items, which is what the design is built around (docs/toolbars.md).
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32pub enum Chrome {
33    /// The window's own chrome, shown on every page of that window.
34    Window(RNode),
35    /// One navigation page's chrome. Which surface draws it follows from the page's
36    /// [`day_spec::props::Pane`].
37    Page(RNode),
38}
39
40/// One navigation page being built: the node contributions land on, whether it is on screen, and
41/// which column of the window it is.
42struct PageFrame {
43    page: RNode,
44    active: Option<Rc<dyn Fn() -> bool>>,
45    column: day_spec::ToolbarColumn,
46    /// The window this page belongs to, captured when its host was built. A destination page is
47    /// built lazily, on the first selection, long after its window's build has returned, and
48    /// `window_being_built()` then answers the primary window, so a second window's pages
49    /// would contribute to the first one's bar.
50    window: RNode,
51}
52
53/// One piece's declared items, alive as long as that piece is.
54struct Contribution {
55    chrome: Chrome,
56    /// Registration order within its chrome. Stable across an update, so re-deriving a list does
57    /// not move it past a neighbor that was declared later.
58    seq: u64,
59    items: Vec<ToolbarItem>,
60    /// The window this contribution's chrome belongs to.
61    window: RNode,
62    document_window: Option<DocumentWindow>,
63    /// Whether the page carrying it is on screen. One bar serves the window, so a pane that is
64    /// collapsed or a destination that is not the one showing must not leave its commands on it;
65    /// that is what made a sidebar row's chrome look one level out of step (docs/toolbars.md).
66    /// `None` for a window's items, which are always showing.
67    active: Option<Rc<dyn Fn() -> bool>>,
68}
69
70/// A resident document's mutable presentation window. Contributions inherit this
71/// context so moving the document also moves its commands without rebuilding them.
72#[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    /// Value callbacks (search text, toggle state) by dispatch id. Plain buttons don't appear
95    /// here; they register with [`crate::menu::register_menu_action`] and arrive as
96    /// `Event::MenuAction`.
97    static VALUE_ACTIONS: RefCell<HashMap<u64, ValueAction>> = RefCell::new(HashMap::new());
98    /// Live contributions by token.
99    static CONTRIBUTIONS: RefCell<HashMap<u64, Contribution>> = RefCell::new(HashMap::new());
100    /// Each chrome's merged model as last lowered; dayscript resolves an item's action here,
101    /// and a recompose compares against it to skip an install that would change nothing. Items
102    /// carry slot ids here, never closure ids (the toolbar slot model).
103    static MODELS: RefCell<Vec<(Chrome, Vec<ToolbarItem>)>> = const { RefCell::new(Vec::new()) };
104    /// Each window's dispatch slots: (window, item key) → the id the toolkit holds for that item
105    /// (the toolbar slot model).
106    static SLOT_IDS: RefCell<HashMap<(RNode, String), u64>> = RefCell::new(HashMap::new());
107    /// Slot id → the closure id it dispatches to right now.
108    static SLOT_TARGETS: RefCell<HashMap<u64, u64>> = RefCell::new(HashMap::new());
109    /// Each window's bar as its toolkit holds it: what an edit is computed against. Separate
110    /// from [`MODELS`], which is the bar the window should carry (and what dayscript reads), so
111    /// an edit the toolkit never received is not mistaken for one it did: the next recompose
112    /// sends it again, the way a whole-bar install used to heal on the next change.
113    static DELIVERED: RefCell<HashMap<RNode, Vec<ToolbarItem>>> = RefCell::new(HashMap::new());
114    /// A recompose is owed at the end of this turn ([`schedule_recompose`]).
115    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    /// Next contribution token, and the registration counter behind `Contribution::seq`.
119    static NEXT_TOKEN: Cell<u64> = const { Cell::new(1) };
120    /// The window whose content is being built right now (see [`with_window`]).
121    static BUILDING: Cell<Option<RNode>> = const { Cell::new(None) };
122    /// The navigation pages this build is inside, innermost last, each with the predicate that
123    /// says whether it is on screen. A contribution registered with a non-empty stack belongs to
124    /// the innermost page; one registered with an empty stack belongs to the window.
125    static PAGE_STACK: RefCell<Vec<PageFrame>> = RefCell::new(Vec::new());
126}
127
128/// Run `f` with `root` as the window contributions inside it belong to. day-core wraps each
129/// window's content build in this, and a presented cover wraps its content, so a navigation
130/// stack inside the cover puts its toolbar on the cover's own bar; nesting restores the
131/// previous window on the way out.
132pub fn with_window<R>(root: RNode, f: impl FnOnce() -> R) -> R {
133    // Restored on unwind too (the anim.rs `Restore` rule): a contained panic during a
134    // secondary window's build would otherwise leave `BUILDING` pointing at a dead window,
135    // silently redirecting every later contribution.
136    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
146/// Run `f` with `page` as the navigation page contributions inside it belong to. The pieces layer
147/// wraps each destination, sidebar and content-list build in this.
148pub 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
158/// [`with_page_gated`] naming the window explicitly. Callers that build pages lazily (every
159/// navigation host) pass the window they were built in.
160pub 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
187/// [`with_page`] with the predicate that says whether this page is on screen (a collapsed
188/// content-list pane, a destination that is not the one showing, a page covered by a push). The
189/// window's one bar carries only the chromes that predicate admits (docs/toolbars.md).
190pub 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
199/// The window the page being built belongs to, else the one being built.
200pub 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
206/// The predicate for the page being built, if it has one.
207pub 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
211/// Which column the page being built is; [`day_spec::ToolbarColumn::Window`] at the window root.
212pub 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
221/// The window being built, else the primary root. Shared with the ambient environment lookup, which scopes
222/// the same way for the same reason: an app's one `size_class()` call inside a shared
223/// `build_shell` must mean "this window".
224pub fn window_being_built() -> RNode {
225    BUILDING
226        .with(|b| b.get())
227        .unwrap_or_else(|| with_tree(|t| t.root_node()))
228}
229
230/// The chrome a contribution registered right now belongs to: the innermost navigation page
231/// being built, else the window being built, else the primary window.
232///
233/// Captured once, at registration. A derived contribution re-runs long after its build, when
234/// neither stack says anything, so reading this later would send its items to the primary
235/// window's chrome.
236pub 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
243/// Register a value callback for a search or toggle item and return its dispatch id (nonzero).
244/// The id comes from the menu action counter, so toolbar and menu ids never collide.
245pub 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
251/// Run the value callback registered for `action` (no-op if none). Called by the event pump on
252/// `Event::ToolbarChanged`, inside a reactive batch so multiple signal writes coalesce. `action`
253/// is the slot id the toolkit holds (the toolbar slot model); a raw closure id works too.
254pub 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
263/// Synthetic input to a bar item (dayscript's `toolbar:` step): paint the widget the way an app
264/// write would, then dispatch the value as the native control would. Both halves are needed, as
265/// for a text field (`crate::synthesize_text`): a real keystroke reaches Day with the field
266/// already showing it, so the dispatch alone records the text without touching the widget, and a
267/// synthesized one left the field empty while the app acted on the query.
268pub 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
292/// The closure id a toolkit-held slot id dispatches to now; any other id is returned as is.
293/// The menu rail resolves through here too, since toolbar buttons ride it.
294pub(crate) fn resolve_slot(id: u64) -> u64 {
295    SLOT_TARGETS.with(|m| m.borrow().get(&id).copied().unwrap_or(id))
296}
297
298/// Add one piece's items to `chrome` and return the token that owns them. The caller withdraws
299/// them with [`unregister_contribution`], normally from its own scope cleanup.
300pub fn register_contribution(chrome: Chrome, items: Vec<ToolbarItem>) -> u64 {
301    register_contribution_gated(chrome, items, None)
302}
303
304/// [`register_contribution`] for a page, with the predicate that says whether that page is on
305/// screen. The caller also re-reads it inside an effect, which is what re-composes the bar when
306/// a pane collapses or the destination changes.
307pub 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
336/// One window's whole bar for a toolkit that draws only one: its items, then every page
337/// chrome on screen under it, in registration order (docs/toolbars.md).
338fn 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
357/// Replace one contribution's items in place, keeping its position among its neighbors.
358pub 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
370/// Give a contribution's items new labels and tooltips, one `(label, tooltip)` per item in
371/// order, keeping everything else as it now stands (actions, a search field's typed text): a
372/// language change relabeling a fixed toolbar (docs/toolbars.md).
373pub 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
385/// Withdraw a contribution. Its items leave the chrome, and the closures only it owned go with
386/// them.
387pub 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
395/// Drop the closures `items` registered that no live contribution still carries, so a page
396/// visited a hundred times does not hold a hundred generations of its commands.
397///
398/// Only the item-level ids: a button's or a toggle's own closure, registered fresh by each
399/// lowering. A pull-down's entries can name Day's standing dispatchers (a new-window item), so
400/// they stay registered, as they did before.
401fn 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
422/// The order the buckets draw in, leading to trailing. `Bottom` sorts with `Secondary`: a chrome
423/// with no bottom bar draws it there, and one with a bottom bar takes it out of this list before
424/// ordering matters.
425fn 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
436/// Record a value the user put into a live item, without touching the widget that reported it.
437///
438/// The widget already shows it; what is stale is Day's copy. Both copies (the owning
439/// contribution's, which a re-compose merges from, and the window's model, which the toolkit
440/// drew and dayscript reads) must learn it, or the next rebuild seeds the item with whatever Day
441/// last pushed. That is how a search field typed into came back empty after a page change, with
442/// the list still filtered by the text it had lost, and how clearing it afterwards reported
443/// nothing new (the field held the stale seed already).
444fn mirror_value(action: u64, value: &ToolbarValue) {
445    // A page's own bar (a phone's navigation item) is a model of its own; the desktops merge
446    // the showing page into the window's. Either way the item's chrome is where Day's copy lives.
447    // A window's bar first: where a page merges into it, that is the bar the toolkit drew.
448    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        // A submission leaves the field's text as the last `Text` set it.
473        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
493/// Owe the windows a recompose, paid once when the current turn settles.
494///
495/// Every change to what a bar carries lands here: a contribution registered, re-derived or
496/// withdrawn, a page gate flipping. A single user action makes several of them. Swapping the
497/// page withdraws the old page's items and contributes the new page's, and handing each step to
498/// the toolkit rebuilt the bar twice, through an intermediate bar nobody should see, when the
499/// bar before and after was the same. Deferring to the end of the turn composes only the settled
500/// result, and [`recompose_windows`] then finds nothing to install. Outside a turn (a window's
501/// first build) it runs right away.
502fn schedule_recompose() {
503    if RECOMPOSE_PENDING.with(|p| p.replace(true)) {
504        return;
505    }
506    day_reactive::at_turn_end(recompose_windows);
507}
508
509/// Hand every window whose composed bar changed its new model, and nothing to the rest.
510///
511/// A bar is re-installed only when something the toolkit draws changed: an item added,
512/// removed or reordered, a label, an icon, a kind. What changes on every derivation, the
513/// closures, never reaches the model: each item is handed to the toolkit under a stable slot
514/// id (the toolbar slot model), so a page re-built with the same commands composes a model equal to
515/// the installed one. Values the user or the app change (search text, a toggle) reach the model
516/// through the same patches that update the widget, so they never differ either.
517fn recompose_windows() {
518    recompose_serially(recompose_windows_inner);
519}
520
521// Native toolbar edits can enqueue layout/focus events. `with_tree` drains those events
522// before returning, and their handlers can request another toolbar composition. Finish
523// recording DELIVERED first: nested diffs against the old baseline insert an item twice,
524// which raises an Objective-C exception in NSToolbar.
525fn 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        // A window whose last contribution left still has a bar to take down.
553        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        // Recorded as the toolkit's only once it has the edit. A window whose root has no native
582        // handle yet takes none; its bar goes out whole on the next recompose instead.
583        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
594/// The order backends rely on (`Toolkit::edit_toolbar`): every removal, then the insertions in
595/// ascending position.
596fn 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
612/// Record a value the toolkit already shows (a patch it took, or input it reported) in its copy
613/// of the bar, so the next edit is computed against what is on screen.
614fn 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
622/// The bar without the items whose id an earlier one already has.
623///
624/// An id is an item's identity on the bar (the native identifier, the key an edit and a patch
625/// address), so it must be unique, and two showing pages declaring the same one is an app bug.
626/// Keeping the first, and saying so once, leaves the bar coherent rather than editing two
627/// natives under one name.
628fn 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
646/// The edit that turns bar `prev` into bar `next`, and the value patches for the items it keeps
647/// (docs/toolbars.md).
648///
649/// Items are matched by id. One the toolkit already draws is kept when it is drawn the same way
650/// (everything but its values: words, search text, prompt and completions, toggle state, selection,
651/// enablement) and when keeping it does not reorder it past another kept item; the kept set is
652/// the longest run of matched items already in order, so a reshuffle costs the fewest items.
653/// Everything else is removed and inserted. A kept item whose values moved gets the patches that
654/// bring it current, the same patches a bound signal would have sent.
655fn diff_bar(
656    prev: &[ToolbarItem],
657    next: &[ToolbarItem],
658) -> (Vec<day_spec::ToolbarOp>, Vec<ToolbarPatch>) {
659    use day_spec::ToolbarOp;
660    // For each item of `next`, the position of its unchanged counterpart in `prev`.
661    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
692/// The indices into `seq` of a longest strictly increasing subsequence of its `Some` values.
693fn longest_increasing(seq: &[Option<usize>]) -> Vec<usize> {
694    // Patience sorting: `tails[k]` is the index of the smallest tail of an increasing run of
695    // length k + 1, and `back` links each element to its predecessor in the run.
696    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
718/// The patches that bring a kept item's values from `was` to `now`.
719fn 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
783/// Swap each item's closure id for the window's stable slot id for that item, and point the
784/// slot at the closure.
785///
786/// An item's identity is its id, so the same command on the next page, or the same page built
787/// again, gets the slot it had. The toolkit keeps dispatching the id it was given, and the id keeps reaching the
788/// current closure: no install to repoint it, and nothing for a toolkit to diff. A pull-down's
789/// entries get slots the same way, by their path under the item.
790fn 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    // Slots this window no longer shows dispatch nothing; the ids stay reserved for the item's
800    // return.
801    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
828/// The slot for `key` in `root`'s bar, now dispatching to `target`. `0` stays `0`: an item with
829/// nothing to run has nothing to address.
830fn 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
844/// The pieces layer, after a change to what is on screen (a push, a pop, a tab switch), so a
845/// one-bar-per-window toolkit is handed the showing pages' items. No-op where every page has a
846/// bar of its own.
847pub fn chrome_changed() {
848    schedule_recompose();
849}
850
851/// Apply a targeted item update wherever the item lives: the path a bound signal writes through,
852/// so a search field keeps its focus and its insertion point.
853pub 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
865/// [`patch_toolbar`] against an explicit chrome. Also updates the retained model, so a later
866/// full replace does not resurrect the stale value.
867pub fn patch_chrome(chrome: Chrome, patch: ToolbarPatch) {
868    // The contribution that owns the item keeps its own copy, so a later re-compose rebuilds
869    // from the current value rather than the one the item was declared with.
870    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    // …and so does the window's model, which is the one the toolkit draws and dayscript reads.
882    //
883    // A page's chrome has no model of its own: everything is composed into the window's before
884    // it crosses (see `lower`). Patching a per-chrome copy left the drawn bar carrying the value
885    // the item was built with, which is how a page command declared while nothing was selected
886    // stayed disabled on a window that never re-composed afterwards, and did nothing when tapped.
887    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
899/// Mirror a patch into the retained model.
900fn apply_to_model(items: &mut [ToolbarItem], patch: &ToolbarPatch) {
901    patch.apply_to(items);
902}
903
904/// An item as the toolkit draws it: everything but its values, which travel as patches, and its
905/// action, whose slot id never changes while the item is on the bar.
906fn shape_of(item: &ToolbarItem) -> ToolbarItem {
907    use day_spec::ToolbarItemKind as K;
908    let mut i = item.clone();
909    i.enabled = true;
910    // Words are values too: a language change patches them on the live item.
911    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
930/// Every live item, across every chrome. dayscript's `toolbar:` step walks it to resolve an
931/// item's dispatch id, and an app has one bar per window at a time, so a duplicate id across two
932/// chromes would be an app bug rather than an ambiguity to resolve here.
933pub fn toolbar_model() -> Vec<ToolbarItem> {
934    MODELS.with(|m| m.borrow().iter().flat_map(|(_, i)| i.clone()).collect())
935}
936
937/// Show/hide the sidebar pane of the navigation host `host`: the behavior behind the sidebar
938/// affordance a nav host contributes for itself (`day_spec::SIDEBAR_TOGGLE_ID`). `false` when
939/// the toolkit has no pane to toggle there. The item's action makes this call, and dayscript's
940/// `toolbar:` step presses the item like any other, so a walkthrough drives the same path a
941/// click does (docs/toolbars.md).
942pub fn toggle_sidebar(host: RNode) -> bool {
943    with_tree(|t| t.toggle_sidebar(host))
944}
945
946/// Drop a closed window's contributions, chrome model and the value closures only they owned.
947///
948/// Called before the window's scope is disposed. Disposal runs every contribution's cleanup,
949/// and each one re-composes the window it belonged to, a merge that asks the other
950/// contributions' gates whether their page is showing, through signals the same disposal has
951/// already dropped. Withdrawing the whole window here first leaves those cleanups nothing to
952/// re-compose (a token that is already gone is a no-op), so a closed window never merges its
953/// own dying bar.
954pub(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
988/// Reset every chrome's toolbar state (tests; pairs with `uninstall_tree`).
989pub 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
1001/// Focus the active window's search control, revealing a collapsed desktop search item.
1002/// Returns false when the active window has no toolbar search contribution.
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                // Simulate a native edit draining an event before the caller records delivery.
1035                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    /// Apply the diff the way a backend does and compare with the target.
1066    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        // Removals first, then insertions in ascending position: the contract backends rely on.
1073        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        // `d` moves; `a`, `b` and `c` stay put.
1126        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}