Skip to main content

day_core/
status.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The app's presence outside its windows (docs/status-item.md): status items, progress on the
5//! Dock or taskbar icon, the macOS Dock icon itself, and whether the app keeps running when its
6//! last window closes.
7
8use std::cell::{Cell, RefCell};
9use std::collections::HashMap;
10
11use day_spec::{AppProgress, StatusItemSpec};
12
13/// Whether the app keeps running when its last window closes (docs/windows.md "Keeping the app
14/// running"), set with [`set_keep_running`].
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16pub enum KeepRunning {
17    /// Keep running while the app shows a status item, so a tray app's menu stays usable with
18    /// every window closed; otherwise follow the platform's rule.
19    #[default]
20    Automatic,
21    /// Keep running with no window open, status item or not: a background helper, an app that
22    /// reopens its window from the Dock or a global shortcut. The app ends when it calls
23    /// `day::quit()` or the user quits from a menu.
24    Always,
25    /// End the app when its last window closes, on every platform, macOS included.
26    Never,
27}
28
29day_reactive::tls_slots! {
30    status;
31    static POLICY: Cell<KeepRunning> = const { Cell::new(KeepRunning::Automatic) };
32    /// The status items, in the order the app first added them, each with the dispatch ids its
33    /// menu and click hold (swept when the item changes or goes).
34    static ITEMS: RefCell<Vec<(StatusItemSpec, Vec<u64>)>> = const { RefCell::new(Vec::new()) };
35    /// What the toolkit was last told about keeping the process alive.
36    static TOLD_KEEP: Cell<Option<bool>> = const { Cell::new(None) };
37    static TRACKING: RefCell<HashMap<String, Tracking>> = RefCell::new(HashMap::new());
38    static NEXT_TRACKING: Cell<u64> = const { Cell::new(1) };
39}
40
41struct Tracking {
42    token: u64,
43    pending: Option<StatusItemSpec>,
44}
45
46/// Backend hook: freeze a status item's installed model and handlers during native menu
47/// tracking. Updates are coalesced until [`end_menu_tracking`]. The token prevents a delayed
48/// close callback from ending a later session (including removal and recreation of the id).
49#[must_use]
50pub fn begin_menu_tracking(id: &str) -> u64 {
51    let token = NEXT_TRACKING.with(|next| {
52        let token = next.get();
53        next.set(token.wrapping_add(1).max(1));
54        token
55    });
56    TRACKING.with(|tracking| {
57        let mut tracking = tracking.borrow_mut();
58        let pending = tracking.remove(id).and_then(|old| old.pending);
59        tracking.insert(id.to_owned(), Tracking { token, pending });
60    });
61    token
62}
63
64/// Backend hook: finish tracking *after* the native selection has dispatched, then install
65/// the most recent pending update. AppKit calls this on the next main-loop turn because
66/// `menuDidClose:` precedes the selected item's action.
67pub fn end_menu_tracking(id: &str, token: u64) {
68    let pending = TRACKING.with(|tracking| {
69        let mut tracking = tracking.borrow_mut();
70        if tracking.get(id).is_some_and(|t| t.token == token) {
71            tracking.remove(id).and_then(|t| t.pending)
72        } else {
73            None
74        }
75    });
76    if let Some(spec) = pending {
77        set_status_item(spec);
78    }
79}
80
81/// Choose whether the app keeps running when its last window closes (docs/windows.md).
82pub fn set_keep_running(policy: KeepRunning) {
83    POLICY.with(|p| p.set(policy));
84    sync_keep_running();
85}
86
87/// The policy as set (default [`KeepRunning::Automatic`]).
88#[must_use]
89pub fn keep_running_policy() -> KeepRunning {
90    POLICY.with(std::cell::Cell::get)
91}
92
93/// Whether closing the last window should leave the app running right now.
94pub(crate) fn keeps_running() -> bool {
95    match keep_running_policy() {
96        KeepRunning::Always => true,
97        KeepRunning::Never => false,
98        KeepRunning::Automatic => ITEMS.with(|i| !i.borrow().is_empty()),
99    }
100}
101
102/// Tell the toolkit when the answer changes, so it stops (or resumes) ending the app on its own.
103fn sync_keep_running() {
104    let keep = keeps_running();
105    if TOLD_KEEP.with(|t| t.replace(Some(keep))) != Some(keep) && crate::tree::has_tree() {
106        crate::with_tree(|t| t.set_keep_running(keep));
107    }
108}
109
110/// Re-send the keep-running answer: the backend that boots after the app set its policy (a
111/// `set_keep_running` in `root()` runs before the tree exists on some paths).
112pub(crate) fn boot_sync() {
113    TOLD_KEEP.with(|t| t.set(None));
114    if keeps_running() {
115        sync_keep_running();
116    }
117}
118
119fn action_ids(spec: &StatusItemSpec) -> Vec<u64> {
120    let mut ids = crate::menu::collect_ids(&spec.menu);
121    if spec.activate != 0 {
122        ids.push(spec.activate);
123    }
124    ids
125}
126
127/// Show `spec`, or update the shown item with the same id (docs/status-item.md). Replacing an
128/// item drops the closures its previous menu and click held. While a backend is tracking the
129/// menu, keep the installed snapshot and coalesce updates until selection has finished.
130#[expect(
131    clippy::missing_panics_doc,
132    reason = "each `unwrap` reads the `Option` this function filled and has not yet taken"
133)]
134pub fn set_status_item(spec: StatusItemSpec) {
135    let mut spec = Some(spec);
136    let superseded = TRACKING.with(|tracking| {
137        let mut tracking = tracking.borrow_mut();
138        let active = tracking.get_mut(&spec.as_ref().unwrap().id)?;
139        active.pending.replace(spec.take().unwrap())
140    });
141    if spec.is_none() {
142        if let Some(old) = superseded {
143            // A discarded intermediate update is never shown. Release only its own actions;
144            // installed and latest-pending specs may explicitly reuse the same ids.
145            let mut keep = ITEMS.with(|items| {
146                items
147                    .borrow()
148                    .iter()
149                    .find(|(s, _)| s.id == old.id)
150                    .map_or_default(|(_, ids)| ids.clone())
151            });
152            TRACKING.with(|tracking| {
153                if let Some(next) = tracking
154                    .borrow()
155                    .get(&old.id)
156                    .and_then(|t| t.pending.as_ref())
157                {
158                    keep.extend(action_ids(next));
159                }
160            });
161            let stale: Vec<_> = action_ids(&old)
162                .into_iter()
163                .filter(|id| !keep.contains(id))
164                .collect();
165            crate::menu::forget_actions(&stale);
166        }
167        return;
168    }
169    let spec = spec.unwrap();
170    let ids = action_ids(&spec);
171    let stale = ITEMS.with(|items| {
172        let mut items = items.borrow_mut();
173        if let Some((s, old)) = items.iter_mut().find(|(s, _)| s.id == spec.id) {
174            let stale: Vec<u64> = old.iter().copied().filter(|i| !ids.contains(i)).collect();
175            *s = spec;
176            *old = ids;
177            stale
178        } else {
179            items.push((spec, ids));
180            Vec::new()
181        }
182    });
183    crate::menu::forget_actions(&stale);
184    send_items();
185}
186
187/// Remove the status item `id`, if shown.
188pub fn remove_status_item(id: &str) {
189    let pending =
190        TRACKING.with(|tracking| tracking.borrow_mut().remove(id).and_then(|t| t.pending));
191    if let Some(pending) = pending {
192        crate::menu::forget_actions(&action_ids(&pending));
193    }
194    let stale = ITEMS.with(|items| {
195        let mut items = items.borrow_mut();
196        let i = items.iter().position(|(s, _)| s.id == id)?;
197        Some(items.remove(i).1)
198    });
199    if let Some(stale) = stale {
200        crate::menu::forget_actions(&stale);
201        send_items();
202    }
203}
204
205/// The status items currently shown, in order.
206#[must_use]
207pub fn status_items() -> Vec<StatusItemSpec> {
208    ITEMS.with(|i| i.borrow().iter().map(|(s, _)| s.clone()).collect())
209}
210
211fn send_items() {
212    let items = status_items();
213    crate::with_tree(|t| t.set_status_items(&items));
214    sync_keep_running();
215}
216
217/// Show `progress` on the app's Dock or taskbar icon (`Cap::AppProgress`, docs/status-item.md).
218pub fn set_app_progress(progress: AppProgress) {
219    crate::with_tree(|t| t.set_app_progress(progress));
220}
221
222/// Show or hide the app's Dock icon while it runs (`Cap::DockVisibility`, macOS). A menu-bar
223/// app hides it and lives in its status item; `[app.macos] dock = false` in Day.toml hides it
224/// from launch, before the first frame.
225pub fn set_dock_visible(visible: bool) {
226    crate::with_tree(|t| t.set_dock_visible(visible));
227}
228
229/// Forget everything (tests; pairs with `uninstall_tree`).
230pub fn reset_status() {
231    TRACKING.with(|tracking| tracking.borrow_mut().clear());
232    ITEMS.with(|i| i.borrow_mut().clear());
233    POLICY.with(|p| p.set(KeepRunning::Automatic));
234    TOLD_KEEP.with(|t| t.set(None));
235}