Skip to main content

nsh_core/element/
desktop.rs

1//! Desktop windows and menus for Rust components, using the platform's
2//! native chrome (TS: `nsh/desktop`'s `Window`, `currentWindow()` and
3//! `Menu`).
4//!
5//! Every window of the app renders from its one engine. [`window`] declares
6//! a window of the app's own in the tree, controlled as a dialog is: open
7//! while [`Window::open`] holds, its content in the same reactive graph as
8//! the rest of the app. [`current_window`] is the window the calling code
9//! renders in (the app root's ref outside a window): a [`WindowRef`]
10//! whose [`WindowRef::set`] changes its attributes and whose requests
11//! ([`WindowRef::set_mode`], [`WindowRef::minimize`], ...) the
12//! platform carries out, reporting what happened in
13//! [`WindowRef::state`]. [`quit`], [`restart`], [`launch_at_login`] and
14//! [`set_launch_at_login`] are `Application`'s.
15//!
16//! A custom title bar hides the system's (`TitleBarOptions` with
17//! [`TitleBarStyle::Hidden`](crate::desktop::TitleBarStyle::Hidden)),
18//! marks its background with [`Interactive::window_drag`], and reserves the
19//! left and right edges reported by [`title_bar`]. The application menu
20//! ([`set_application_menu`]) and context menus ([`popup_menu`]) are
21//! [`MenuItem`]s whose [`MenuItem::on_select`] runs when the user chooses
22//! the item, by a click or its shortcut.
23//!
24//! An app that opens its window as the user left it saves
25//! [`WindowState::placement`] when it changes and gives it back to
26//! [`WindowRef::set_placement`], which fits it on the displays there
27//! are now; a [`window`] with [`Window::restore_bounds`] has the core do
28//! both.
29//!
30//! ```ignore
31//! let window = current_window(); // in a window's content
32//! if let Some(saved) = Storage::get_item("window")
33//!     .and_then(|json| serde_json::from_str::<WindowPlacement>(&json).ok())
34//! {
35//!     window.set_placement(saved);
36//! }
37//! effect(move || {
38//!     if let Some(state) = window.state() {
39//!         let json = serde_json::to_string(&state.placement).unwrap();
40//!         let _ = Storage::set_item("window", json);
41//!     }
42//! });
43//! ```
44//!
45//! On platforms without desktop windows these have no effect.
46//!
47//! [`Interactive::window_drag`]: super::Interactive::window_drag
48
49use std::{cell::RefCell, fmt, rc::Rc};
50
51use super::{
52    AnyElement, Element, ElementRef, ImageSrc, IntoElement, IntoElements, IntoReactive, Owner,
53    ParentElement, Signal, cleanup, menus::MenuHandler, task::Answer,
54};
55use crate::{
56    Command, EventKind, EventPayload,
57    desktop::{
58        self, CloseReason, DesktopCommand, Display, DisplayId, LaunchAtLoginError, MenuAction,
59        MenuBarMode, MenuRole, Shortcut, TrayTitlePlacement, TrayTitleRun, WindowAttributes,
60        WindowCloseCause, WindowEvent, WindowFrame, WindowKind, WindowMode, WindowOptions,
61        WindowPlacement, WindowPosition, WindowRequest, WindowState,
62    },
63    geometry::{Bounds, Edges, Point, Points, Size},
64    keymap::When,
65    platform::Os,
66};
67
68/// The current window's ([`current_window`]) custom title bar: its height
69/// (`top`) and the widths its native window controls occupy (`left` and
70/// `right`), in points (TS: `titleBar()`). Reading subscribes to changes,
71/// including entering and leaving full screen. In macOS full screen the
72/// height stays and `left` is the traffic lights' width only while the
73/// system shows them (pointer at the top of the screen). These are zero
74/// with a system title bar and on platforms without desktop windows.
75pub fn title_bar() -> Edges<Points> {
76    if !super::os().is_desktop() || super::idiom() == crate::platform::Idiom::Terminal {
77        return Edges::default();
78    }
79    current_window().title_bar()
80}
81
82/// When the menu bar shows on Windows and Linux where the window draws the
83/// application menu as a bar above the app (the GPUI backend):
84/// [`MenuBarMode::Shown`] (the default) always; [`MenuBarMode::AutoHide`]
85/// only after Alt is pressed and released alone, until Alt alone hides it
86/// again. F10 and Alt with a menu's initial open a menu either way, and the
87/// bar shows while it is open. macOS's menu bar is the system's (TS:
88/// `Menu.setMenuBar`).
89pub fn set_menu_bar(mode: MenuBarMode) {
90    super::desktop_command(DesktopCommand::SetMenuBar(mode));
91}
92
93/// The current window's state (TS: `windowState()`):
94/// [`WindowRef::state`] of [`current_window`]; `None` off the desktops,
95/// where there is no window.
96pub fn window_state() -> Option<WindowState> {
97    if !super::os().is_desktop() || super::idiom() == crate::platform::Idiom::Terminal {
98        return None;
99    }
100    current_window().state()
101}
102
103/// The displays (TS: `displays()`): their bounds and the parts of them
104/// windows use, in screen coordinates. Reading subscribes: plugging in a
105/// display, unplugging one or arranging them again changes them. Empty
106/// off desktops.
107pub fn displays() -> Vec<Display> {
108    super::ambient::displays()
109}
110
111/// The display with `id`, of [`displays`] (reading subscribes).
112pub fn display(id: DisplayId) -> Option<Display> {
113    displays().into_iter().find(|d| d.id == id)
114}
115
116// --- Windows ---------------------------------------------------------------------------
117
118/// Where a [`WindowRef`]'s commands go.
119#[derive(Clone, Copy)]
120enum Target {
121    /// The app root (the invisible host's ref), not a user window.
122    Main,
123    /// A window of the app's own: the dialog root carrying the ref.
124    Own(ElementRef),
125}
126
127/// A window (TS: `WindowRef`): the app root's ref ([`main_window`], the
128/// invisible host, not a user window) or a window of the app's own
129/// ([`window`]), as [`current_window`] gives it. Setting its attributes and
130/// its requests are commands that go out with the commit; the platform may
131/// decline or adjust a request, and [`Self::state`] reports what happened.
132/// Commands to a closed window do nothing.
133#[derive(Clone)]
134pub struct WindowRef {
135    id: Rc<str>,
136    target: Target,
137    /// The state of a window of the app's own (the app root's is the
138    /// environment's).
139    state: Option<Signal<Option<WindowState>>>,
140    /// The hidden title bar's area of a window of the app's own (the app
141    /// root's is the environment's).
142    title_bar: Option<Signal<Edges<Points>>>,
143    /// Closes a window of the app's own as its element does
144    /// ([`WindowRef::close`]).
145    close: Option<Rc<dyn Fn(WindowCloseCause)>>,
146    /// The close presses of a window of the app's own: how many, and the
147    /// last one's reason (the app root's are the environment's).
148    close_press: Option<Signal<(u64, CloseReason)>>,
149    /// What a window of the app's own was set to and asked for before its
150    /// element was mounted (its content's first render): opened with it.
151    early: Option<Signal<Early>>,
152}
153
154/// What a window's ref was given before its element was mounted.
155#[derive(Clone, Default, PartialEq)]
156struct Early {
157    /// Joins the options it opens with.
158    attributes: WindowAttributes,
159    /// Sent after it opens, in order (`focus()`, `set_mode()`, ...).
160    commands: Vec<DesktopCommand>,
161    /// It closed: nothing more is kept.
162    closed: bool,
163}
164
165impl fmt::Debug for WindowRef {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        f.debug_struct("WindowRef")
168            .field("id", &self.id)
169            .finish_non_exhaustive()
170    }
171}
172
173impl PartialEq for WindowRef {
174    fn eq(&self, other: &Self) -> bool {
175        self.id == other.id
176    }
177}
178
179/// The app root's ref, for commands about the application host: it is not a
180/// user window and has no visible window in window model v2. A desktop app
181/// declares its UI with [`window`]; off the desktops [`window`] shows its
182/// content in the app's one surface. Its window requests (`show`, `hide`,
183/// `focus`, `close`, `minimize`, `restore`, modes and bounds) do nothing: the
184/// host never shows and is not a window to close; [`WindowRef::request_attention`]
185/// still reaches the platform: the app's Dock icon bounces or its launcher
186/// entry turns urgent (the hidden host has no taskbar button on Windows). Use
187/// [`quit`] (or `Application.quit`) to end the app.
188pub fn main_window() -> WindowRef {
189    WindowRef {
190        id: Rc::from("main"),
191        target: Target::Main,
192        state: None,
193        title_bar: None,
194        close: None,
195        close_press: None,
196        early: None,
197    }
198}
199
200/// The window the calling code renders in (TS: `currentWindow()`): the
201/// nearest [`window`] around it. Never the focused window. Call it while
202/// rendering and keep the handle: listeners and tasks find no window
203/// around them. Outside every window it is [`main_window`]: the app root's
204/// ref, which a released app's plain root renders in (not a user window on
205/// the desktops).
206pub fn current_window() -> WindowRef {
207    super::use_context::<WindowRef>().unwrap_or_else(main_window)
208}
209
210/// The ref of a window JS opened (`<Window>` of `nsh/desktop`) at node
211/// `node`, under its own owner, for the Rust components rendered inside it:
212/// [`current_window`] finds it as it finds a [`window`]'s, with the state
213/// and title bar area `reported` gives and [`WindowRef::report`] keeps.
214/// Commands go to the node; JS keeps its own handle of the window.
215pub(crate) fn js_window(
216    id: &str,
217    node: crate::NodeId,
218    executor: &Rc<super::Executor>,
219    reported: (Option<WindowState>, Edges<Points>),
220) -> (Owner, WindowRef) {
221    Owner::detached().run(|| {
222        super::create_root(|| {
223            let element = ElementRef::new(executor);
224            if let Some(target) = element.target() {
225                target.attach(node);
226            }
227            let this = WindowRef {
228                id: Rc::from(id),
229                target: Target::Own(element),
230                state: Some(super::signal(reported.0)),
231                title_bar: Some(super::signal(reported.1)),
232                close: None,
233                close_press: None,
234                early: None,
235            };
236            super::provide_context(this.clone());
237            this
238        })
239    })
240}
241
242impl WindowRef {
243    /// Its id: the app's (`"main"` is a conventional first-window id, with
244    /// no special behavior).
245    pub fn id(&self) -> &str {
246        &self.id
247    }
248
249    /// Whether its id is `"main"` (a conventional first-window id; there
250    /// is no privileged window).
251    pub fn is_main(&self) -> bool {
252        self.id.as_ref() == "main"
253    }
254
255    /// The ref on a window of the app's own's dialog root (its node is the
256    /// window's root node); `None` for the app root's ref.
257    pub(crate) fn dialog_root(&self) -> Option<super::ElementRef> {
258        match &self.target {
259            Target::Main => None,
260            Target::Own(element) => Some(*element),
261        }
262    }
263
264    fn command(&self, command: DesktopCommand) {
265        match self.target {
266            Target::Main => {
267                // The host is not a user window: a request would act on the
268                // hidden host, and minimize/restore/mode can present it on
269                // Linux or Windows. Attributes keep the app-root defaults.
270                // Attention is the app's (its Dock icon or launcher entry),
271                // so it passes like the attributes do.
272                if matches!(
273                    command,
274                    DesktopCommand::SetAttributes(_)
275                        | DesktopCommand::Request(WindowRequest::RequestAttention { .. })
276                ) {
277                    super::ambient::desktop_command(command);
278                }
279            }
280            // Not mounted yet (`open_window`, or set while it first
281            // renders): the attributes join the options it opens with, and
282            // the other commands follow its opening, in order.
283            Target::Own(element) => match self.early {
284                Some(early) if element.node().is_none() => {
285                    if !early.is_live() {
286                        return;
287                    }
288                    early.update(|e| match command {
289                        _ if e.closed => {}
290                        DesktopCommand::SetAttributes(attributes) => {
291                            e.attributes.merge(&attributes)
292                        }
293                        command => e.commands.push(command),
294                    });
295                }
296                _ => element.send(Command::Desktop(Box::new(command))),
297            },
298        }
299    }
300
301    /// What the platform reports of it (reading subscribes): its mode,
302    /// bounds, display, whether it is focused, minimized or visible.
303    /// `None` off desktops, while it is not open, and once it closed.
304    pub fn state(&self) -> Option<WindowState> {
305        match self.state {
306            None => super::ambient::window_state(),
307            Some(state) => state.try_get().flatten(),
308        }
309    }
310
311    /// Changes the attributes `attributes` sets (TS: `set(partial)`); the
312    /// others keep their values. One command per window and commit carries
313    /// what changed. An attribute the app's capabilities do not grant is
314    /// left as it is, with a warning.
315    pub fn set(&self, attributes: WindowAttributes) {
316        if attributes.is_empty() {
317            return;
318        }
319        self.command(DesktopCommand::SetAttributes(Box::new(attributes)));
320    }
321
322    /// Shows it, restoring it when minimized. The app root's ref never
323    /// shows: the host is invisible in window model v2.
324    pub fn show(&self) {
325        if matches!(self.target, Target::Main) {
326            return;
327        }
328        self.command(DesktopCommand::Request(WindowRequest::Show));
329    }
330
331    /// Hides it.
332    pub fn hide(&self) {
333        self.command(DesktopCommand::Request(WindowRequest::Hide));
334    }
335
336    /// Shows it, brings it to the front of its level and focuses it. The app
337    /// root's ref never shows or takes focus.
338    pub fn focus(&self) {
339        if matches!(self.target, Target::Main) {
340            return;
341        }
342        self.command(DesktopCommand::Request(WindowRequest::Focus));
343    }
344
345    /// Closes it, whatever `close_on_press` says. A [`window`] reports it
346    /// to [`Window::on_open_change`] with [`WindowCloseCause::Close`], so
347    /// the app's `open` state follows. Only this window closes; the app's
348    /// last-window policy decides whether the app ends (an embedding host
349    /// decides).
350    pub fn close(&self) {
351        match &self.close {
352            Some(close) => close(WindowCloseCause::Close),
353            None => self.command(DesktopCommand::Request(WindowRequest::Close)),
354        }
355    }
356
357    /// What the platform reported of a window JS opened
358    /// ([`js_window`]): its state and title bar area follow.
359    pub(crate) fn report(&self, event: &WindowEvent) {
360        match event {
361            WindowEvent::State(next) => {
362                if let Some(state) = self.state {
363                    state.try_set(Some(**next));
364                }
365            }
366            WindowEvent::TitleBar(area) => {
367                if let Some(title_bar) = self.title_bar {
368                    title_bar.try_set(*area);
369                }
370            }
371            _ => {}
372        }
373    }
374
375    /// Its hidden title bar's area (reading subscribes): the bar's height
376    /// (`top`) and the widths its window controls take (`left`, `right`),
377    /// as [`title_bar`] gives the main window's.
378    pub fn title_bar(&self) -> Edges<Points> {
379        match self.title_bar {
380            Some(area) => area.try_get().unwrap_or_default(),
381            None => super::title_bar(),
382        }
383    }
384
385    /// Minimizes it.
386    pub fn minimize(&self) {
387        self.command(DesktopCommand::Request(WindowRequest::Minimize));
388    }
389
390    /// Brings it back from being minimized, in the mode it had.
391    pub fn restore(&self) {
392        self.command(DesktopCommand::Request(WindowRequest::Restore));
393    }
394
395    /// Puts it in `mode`; doing it again changes nothing.
396    pub fn set_mode(&self, mode: WindowMode) {
397        self.command(DesktopCommand::Request(WindowRequest::SetMode(mode)));
398    }
399
400    /// Moves and sizes it in points, in screen coordinates; fields left out
401    /// keep their values. Widths and heights take positive finite numbers,
402    /// `x` and `y` finite ones: other values keep the field's value.
403    pub fn set_bounds(&self, frame: WindowFrame) {
404        self.command(DesktopCommand::Request(WindowRequest::SetBounds(
405            WindowFrame {
406                x: frame.x.filter(|v| v.is_finite()),
407                y: frame.y.filter(|v| v.is_finite()),
408                width: frame.width.filter(|v| v.is_finite() && v.0 > 0.0),
409                height: frame.height.filter(|v| v.is_finite() && v.0 > 0.0),
410                animated: frame.animated,
411            },
412        )));
413    }
414
415    /// Restores a placement saved earlier ([`WindowState::placement`]):
416    /// restored to its bounds, then maximized or in full screen when its
417    /// mode says so. The bounds are first fitted on the displays there are
418    /// now: unchanged when at least 100 × 20 points of the window's top 40
419    /// points are on a display's visible bounds, where the user can take
420    /// it by its title bar; otherwise centered on the primary display's
421    /// visible bounds, no larger than them.
422    pub fn set_placement(&self, placement: WindowPlacement) {
423        self.command(DesktopCommand::Request(WindowRequest::SetPlacement(
424            placement,
425        )));
426    }
427
428    /// Centers it on `display` (its own with `None`).
429    pub fn center(&self, display: Option<DisplayId>) {
430        self.command(DesktopCommand::Request(WindowRequest::Center { display }));
431    }
432
433    /// Asks for the user's attention: the Dock's icon bounces, the taskbar
434    /// button flashes; `critical` until the user activates the app.
435    pub fn request_attention(&self, critical: bool) {
436        self.command(DesktopCommand::Request(WindowRequest::RequestAttention {
437            critical,
438        }));
439    }
440
441    /// Runs `f` with what changed whenever `changed` finds a change between
442    /// two states, under the current owner.
443    fn on_change<T: 'static>(
444        &self,
445        changed: impl Fn(Option<&WindowState>, &WindowState) -> Option<T> + 'static,
446        f: impl Fn(T) + 'static,
447    ) {
448        let this = self.clone();
449        let last = super::stored(None::<WindowState>);
450        super::effect(move || {
451            let Some(next) = this.state() else { return };
452            let previous = last.replace(Some(next));
453            if let Some(change) = changed(previous.as_ref(), &next) {
454                super::untracked(|| f(change));
455            }
456        });
457    }
458
459    /// Runs `f` with the reason each time the user asks to close it (its
460    /// close button, a shortcut, a menu, the taskbar, the system), under
461    /// the current owner (TS: `on("closePress", …)`). With
462    /// `close_on_press: false` it stays open: save or ask, then
463    /// [`Self::close`].
464    pub fn on_close_press(&self, f: impl Fn(CloseReason) + 'static) {
465        let signal = self
466            .close_press
467            .unwrap_or_else(super::ambient::main_close_press_signal);
468        let seen = super::stored(signal.with_untracked(|(count, _)| *count));
469        super::effect(move || {
470            let (count, reason) = signal.get();
471            if seen.replace(count) != count {
472                super::untracked(|| f(reason));
473            }
474        });
475    }
476
477    /// Runs `f` with `focused` when it gains or loses the focus.
478    pub fn on_focus_change(&self, f: impl Fn(bool) + 'static) {
479        self.on_change(
480            |old, new| (old.is_some_and(|o| o.focused != new.focused)).then_some(new.focused),
481            f,
482        );
483    }
484
485    /// Runs `f` with its mode and whether it is minimized when either
486    /// changes.
487    pub fn on_mode_change(&self, f: impl Fn(WindowMode, bool) + 'static) {
488        self.on_change(
489            |old, new| {
490                old.is_some_and(|o| o.mode != new.mode || o.minimized != new.minimized)
491                    .then_some((new.mode, new.minimized))
492            },
493            move |(mode, minimized)| f(mode, minimized),
494        );
495    }
496
497    /// Runs `f` with its bounds once a move or a resize settles.
498    pub fn on_bounds_change(&self, f: impl Fn(Bounds<Points>) + 'static) {
499        self.on_change(
500            |old, new| (old.is_some_and(|o| o.bounds != new.bounds)).then_some(new.bounds),
501            f,
502        );
503    }
504
505    /// Runs `f` with the display it moved to.
506    pub fn on_display_change(&self, f: impl Fn(DisplayId) + 'static) {
507        self.on_change(
508            |old, new| {
509                (old.is_some_and(|o| o.display != new.display))
510                    .then_some(new.display)
511                    .flatten()
512            },
513            f,
514        );
515    }
516}
517
518/// Why a [`window`] closed ([`Window::on_open_change`]).
519#[non_exhaustive]
520#[derive(Debug, Clone, Copy, PartialEq, Default)]
521pub struct OpenChange {
522    /// Whether it is open now (always `false`: the app opens windows).
523    pub open: bool,
524    /// What closed it.
525    pub reason: WindowCloseCause,
526}
527
528type OpenChangeFn = Rc<dyn Fn(&OpenChange)>;
529type ClosePressFn = Rc<dyn Fn(CloseReason)>;
530type BindFn = Rc<dyn Fn(&mut WindowAttributes)>;
531type ContentFn = Rc<dyn Fn() -> Vec<AnyElement>>;
532
533/// A window of the app's own in the tree (TS: `<Window>`), made by
534/// [`window`]: open while [`Self::open`] holds and the user has not closed
535/// it, its content made each time it opens.
536pub struct Window {
537    options: WindowOptions,
538    bound: Vec<BindFn>,
539    reactive: Vec<super::Reactive<WindowAttributes>>,
540    open: Option<super::Reactive<bool>>,
541    content: Option<ContentFn>,
542    on_open_change: Option<OpenChangeFn>,
543    on_close_press: Option<ClosePressFn>,
544    /// Its ref, made before it opens ([`open_window`]).
545    opened: Option<WindowRef>,
546}
547
548/// A window of the app's own (TS: `<Window>`): a window the platform shows
549/// its content in, rendered from the app's one engine, so it shares the
550/// app's signals, context and theme. Give it an [`Window::id`] (one window
551/// per id), its [`Window::kind`] and its content; it opens while
552/// [`Window::open`] holds (always, without it) and closes when it leaves
553/// the tree.
554///
555/// ```ignore
556/// window()
557///     .id("inspector")
558///     .kind(WindowKind::Panel)
559///     .title("Inspector")
560///     .default_size(size(px(320.), px(560.)))
561///     .open(inspector)
562///     .on_open_change(move |e| inspector.set(e.open))
563///     .content(inspector_panel)
564/// ```
565///
566/// Off the desktops it shows its content in the app's one surface.
567pub fn window() -> Window {
568    Window {
569        options: WindowOptions::default(),
570        bound: Vec::new(),
571        reactive: Vec::new(),
572        open: None,
573        content: None,
574        on_open_change: None,
575        on_close_press: None,
576        opened: None,
577    }
578}
579
580impl Window {
581    /// The app's id for it: one window per id, and the key of its kept
582    /// placement ([`Self::restore_bounds`]).
583    pub fn id(mut self, id: impl Into<String>) -> Self {
584        self.options.id = id.into();
585        self
586    }
587
588    /// What it is for: its attributes' defaults.
589    pub fn kind(mut self, kind: WindowKind) -> Self {
590        self.options.kind = kind;
591        self
592    }
593
594    /// The id of the window that owns it (`"main"` is a conventional id).
595    pub fn parent(mut self, id: impl Into<String>) -> Self {
596        self.options.parent = Some(id.into());
597        self
598    }
599
600    /// Its parent takes no input while it is open (dialogs).
601    pub fn modal(mut self, modal: bool) -> Self {
602        self.options.modal = modal;
603        self
604    }
605
606    /// Its content size when it opens.
607    pub fn default_size(mut self, size: Size<Points>) -> Self {
608        self.options.default_size = Some(size);
609        self
610    }
611
612    /// Where it opens.
613    pub fn default_position(mut self, position: WindowPosition) -> Self {
614        self.options.default_position = Some(position);
615        self
616    }
617
618    /// The display it opens on.
619    pub fn display(mut self, display: DisplayId) -> Self {
620        self.options.display = Some(display);
621        self
622    }
623
624    /// The mode it opens in.
625    pub fn default_mode(mut self, mode: WindowMode) -> Self {
626        self.options.default_mode = Some(mode);
627        self
628    }
629
630    /// Opens where the user left it: the core keeps its placement under its
631    /// id and fits it on the displays there are when it opens again.
632    pub fn restore_bounds(mut self, restore: bool) -> Self {
633        self.options.restore_bounds = restore;
634        self
635    }
636
637    /// Its title (a value, a signal or a closure).
638    pub fn title(mut self, title: impl IntoReactive<String>) -> Self {
639        match title.into_reactive() {
640            super::Reactive::Static(title) => self.options.attributes.title = Some(title),
641            reactive => {
642                let reactive = Rc::new(reactive);
643                self.bound.push(Rc::new(move |a: &mut WindowAttributes| {
644                    a.title = Some(reactive.get());
645                }));
646            }
647        }
648        self
649    }
650
651    /// Any of its attributes (a value, a signal or a closure): the fields
652    /// set, over its kind's defaults; given again, the later fields win.
653    pub fn attributes(mut self, attributes: impl IntoReactive<WindowAttributes>) -> Self {
654        match attributes.into_reactive() {
655            super::Reactive::Static(a) => self.options.attributes.merge(&a),
656            reactive => self.reactive.push(reactive),
657        }
658        self
659    }
660
661    /// Whether it is open (a value, a signal or a closure).
662    pub fn open(mut self, open: impl IntoReactive<bool>) -> Self {
663        self.open = Some(open.into_reactive());
664        self
665    }
666
667    /// Runs `f` when the window closed while `open` held (the user's close
668    /// press with `close_on_press`, Escape, losing the focus, its parent
669    /// closing, [`WindowRef::close`]): the app sets its `open` state
670    /// from it.
671    pub fn on_open_change(mut self, f: impl Fn(&OpenChange) + 'static) -> Self {
672        self.on_open_change = Some(Rc::new(f));
673        self
674    }
675
676    /// Runs `f` when the user asks to close it (its close button, the
677    /// close key), whether or not `close_on_press` lets it close.
678    pub fn on_close_press(mut self, f: impl Fn(CloseReason) + 'static) -> Self {
679        self.on_close_press = Some(Rc::new(f));
680        self
681    }
682
683    /// What it shows, made each time it opens; [`current_window`] in it is
684    /// this window.
685    pub fn content<E: IntoElements>(mut self, content: impl Fn() -> E + 'static) -> Self {
686        self.content = Some(Rc::new(move || content().into_elements()));
687        self
688    }
689}
690
691impl IntoElement for Window {
692    fn into_element(self) -> AnyElement {
693        // Off the desktops, and in a terminal, the app has one surface: the
694        // window's content is the app's screen while `open`, as TSX's
695        // `<Window>` does.
696        if !super::os().is_desktop() || super::idiom() == crate::platform::Idiom::Terminal {
697            let open = self.open.unwrap_or(super::Reactive::Static(true));
698            return match self.content {
699                Some(content) => super::when(move || open.get(), move || content()).into_element(),
700                None => super::when(false, Vec::<AnyElement>::new).into_element(),
701            };
702        }
703        let Window {
704            options,
705            bound,
706            reactive,
707            open,
708            content,
709            on_open_change,
710            on_close_press,
711            opened,
712        } = self;
713        let open = open.unwrap_or(super::Reactive::Static(true));
714        // Closed by the user while `open` stayed true: hidden until the app
715        // follows (then `open` opens it again).
716        let closed = super::signal(false);
717        let open = Rc::new(open);
718        let is_open = {
719            let open = open.clone();
720            move || {
721                let open = open.get();
722                if !open {
723                    super::untracked(|| closed.set(false));
724                }
725                open && !closed.get()
726            }
727        };
728        let options = Rc::new(options);
729        let bound = Rc::new(bound);
730        let reactive = Rc::new(reactive);
731        super::when(is_open, move || {
732            let (element, state, title_bar, close_press, early) = match &opened {
733                Some(WindowRef {
734                    target: Target::Own(element),
735                    state: Some(state),
736                    title_bar: Some(title_bar),
737                    close_press: Some(close_press),
738                    early: Some(early),
739                    ..
740                }) => (*element, *state, *title_bar, *close_press, *early),
741                _ => (
742                    super::element_ref(),
743                    super::signal(None::<WindowState>),
744                    super::signal(Edges::<Points>::default()),
745                    super::signal((0u64, CloseReason::default())),
746                    super::signal(Early::default()),
747                ),
748            };
749            // Closed, its ref reaches nothing: what it is asked for then is
750            // not kept for a later opening.
751            super::cleanup(move || {
752                early.try_set(Early {
753                    closed: true,
754                    ..Early::default()
755                });
756            });
757            let close: Rc<dyn Fn(WindowCloseCause)> = {
758                let on_open_change = on_open_change.clone();
759                Rc::new(move |cause: WindowCloseCause| {
760                    closed.set(true);
761                    if let Some(f) = &on_open_change {
762                        f(&OpenChange {
763                            open: false,
764                            reason: cause,
765                        });
766                    }
767                })
768            };
769            let this = WindowRef {
770                id: Rc::from(options.id.as_str()),
771                target: Target::Own(element),
772                state: Some(state),
773                title_bar: Some(title_bar),
774                close: Some(close.clone()),
775                close_press: Some(close_press),
776                early: Some(early),
777            };
778            LiveWindows::add(this.clone());
779            super::provide_context(this);
780            let mut modal = super::modal().element_ref(&element);
781            {
782                let node = modal.node();
783                let options = options.clone();
784                let bound = bound.clone();
785                let reactive = reactive.clone();
786                let resolve = move || {
787                    let mut o = (*options).clone();
788                    for b in bound.iter() {
789                        b(&mut o.attributes);
790                    }
791                    for r in reactive.iter() {
792                        o.attributes.merge(&r.get());
793                    }
794                    let commands = early.with(|e| {
795                        o.attributes.merge(&e.attributes);
796                        e.commands.clone()
797                    });
798                    (o, commands)
799                };
800                let apply = |attrs: &mut super::Attrs, (o, commands): (WindowOptions, _)| {
801                    let rare = attrs.rare_mut();
802                    rare.window = Some(Box::new(o));
803                    rare.window_commands = commands;
804                };
805                // Bound even with static options: what its content sets
806                // while it first renders (`early`) joins them.
807                node.bind_attr(super::Reactive::Bound(Rc::new(resolve)), apply);
808                let on_close_press = on_close_press.clone();
809                let close_on_dismiss = close.clone();
810                node.handlers.push((
811                    EventKind::Window,
812                    super::Listener::from(move |payload: &EventPayload| {
813                        let EventPayload::Window(event) = payload else {
814                            return;
815                        };
816                        match event.as_ref() {
817                            WindowEvent::State(next) => {
818                                state.try_set(Some(**next));
819                            }
820                            WindowEvent::TitleBar(area) => {
821                                title_bar.try_set(*area);
822                            }
823                            WindowEvent::ClosePress { reason } => {
824                                if let Some(f) = &on_close_press {
825                                    f(*reason);
826                                }
827                                if close_press.is_live() {
828                                    close_press.update(|(count, last)| {
829                                        *count += 1;
830                                        *last = *reason;
831                                    });
832                                }
833                            }
834                            WindowEvent::Closed { cause } => close(*cause),
835                            // The root's ([`Core`](crate::Core) hears them).
836                            WindowEvent::QuitRequest | WindowEvent::Reopen => {}
837                        }
838                    }),
839                ));
840                // The platforms that close windows themselves report it so.
841                node.handlers.push((
842                    EventKind::Dismiss,
843                    super::Listener::from(move |_: &EventPayload| {
844                        close_on_dismiss(WindowCloseCause::ClosePress)
845                    }),
846                ));
847            }
848            if let Some(content) = &content {
849                modal = modal.children(content());
850            }
851            modal
852        })
853        .into_element()
854    }
855}
856
857/// Every window of the app's own that is open now (the app root's ref
858/// aside), however it opened: a [`window`] in the tree or [`open_window`].
859#[derive(Default, Clone)]
860struct LiveWindows(Vec<WindowRef>);
861
862impl LiveWindows {
863    /// Lists `window` until the owner rendering it is disposed (it closes).
864    fn add(window: WindowRef) {
865        let live = super::global::<Self>();
866        let id = window.id.clone();
867        live.update(|l| l.0.push(window));
868        super::cleanup(move || {
869            if live.is_live() {
870                live.update(|l| l.0.retain(|w| !Rc::ptr_eq(&w.id, &id)));
871            }
872        });
873    }
874
875    /// The open window with `id`.
876    fn get(id: &str) -> Option<WindowRef> {
877        super::global::<Self>().with_untracked(|l| l.0.iter().find(|w| &*w.id == id).cloned())
878    }
879
880    fn count() -> usize {
881        super::global::<Self>().with_untracked(|l| l.0.len())
882    }
883}
884
885/// What the app may open, as the core checks it ([`crate::Core::set_access`]).
886#[derive(Default, Clone)]
887pub(crate) struct WindowAccess(pub(crate) Option<std::sync::Arc<crate::access::Access>>);
888
889/// The windows [`open_window`] opened, in the order they opened.
890#[derive(Default, Clone)]
891struct OpenedWindows(Vec<Opened>);
892
893/// A window [`open_window`] opened: its id, its [`Window`] until it
894/// renders, and the owner of its ref's signals (disposed once it closes).
895#[derive(Clone)]
896struct Opened {
897    id: Rc<str>,
898    window: Rc<RefCell<Option<Window>>>,
899    owner: Owner,
900}
901
902impl PartialEq for Opened {
903    fn eq(&self, other: &Self) -> bool {
904        Rc::ptr_eq(&self.window, &other.window)
905    }
906}
907
908/// Opens `window` (made with [`window`]) from anywhere: an event handler, a
909/// menu item, a task (TS: `Window.open`; GPUI: `cx.open_window`). It
910/// renders from the app's one engine, so it shares the app's signals,
911/// context and theme, and stays open until it closes (the user, its
912/// [`WindowRef::close`]). One window per id: with the id of a window that
913/// is open, however it opened, it focuses that window and returns its ref
914/// (a document window per document: `.id(format!("doc:{id}"))`). Without
915/// an id it gets a new one.
916///
917/// `None`, with a warning in the log, where TS `Window.open` throws: off
918/// the desktops (`ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`) and when the app's
919/// capabilities do not grant the window (`ERR_ACCESS_DENIED`).
920/// [`Window::open`] does not apply here: the window opens now.
921///
922/// ```ignore
923/// let Some(inspector) = open_window(
924///     window()
925///         .id("inspector")
926///         .kind(WindowKind::Panel)
927///         .title("Inspector")
928///         .content(inspector_panel),
929/// ) else {
930///     return;
931/// };
932/// inspector.set_mode(WindowMode::Normal);
933/// ```
934pub fn open_window(mut window: Window) -> Option<WindowRef> {
935    if !super::os().is_desktop() || super::idiom() == crate::platform::Idiom::Terminal {
936        log::warn!("open_window: windows of the app's own open on the desktops only");
937        return None;
938    }
939    if window.open.is_some() {
940        log::warn!("open_window: `Window::open` is ignored, the window opens now");
941    }
942    let opened = super::global::<OpenedWindows>();
943    if window.options.id.is_empty() {
944        thread_local!(static NEXT: std::cell::Cell<u64> = const { std::cell::Cell::new(0) });
945        let n = NEXT.with(|n| {
946            n.set(n.get() + 1);
947            n.get()
948        });
949        window.options.id = format!("window-{n}");
950    }
951    let id: Rc<str> = Rc::from(window.options.id.as_str());
952    // Open already: rendered (any way in), or opened and not yet rendered.
953    let open = LiveWindows::get(&id).or_else(|| {
954        opened.with_untracked(|o| {
955            o.0.iter()
956                .find(|w| w.id == id)
957                .and_then(|w| w.window.borrow().as_ref().and_then(|w| w.opened.clone()))
958        })
959    });
960    if let Some(open) = open {
961        open.focus();
962        return Some(open);
963    }
964    let access = super::global::<WindowAccess>().get_untracked().0;
965    if let Some(access) = access {
966        let pending = opened.with_untracked(|o| {
967            o.0.iter()
968                .filter(|w| LiveWindows::get(&w.id).is_none())
969                .count()
970        });
971        if let Err(message) = access.check_window(
972            window.options.kind,
973            &window.options.attributes,
974            LiveWindows::count() + pending,
975        ) {
976            log::warn!("open_window: {message}: the window does not open");
977            return None;
978        }
979    }
980    let user = window.on_open_change.take();
981    let on_open_change: OpenChangeFn = {
982        let id = id.clone();
983        Rc::new(move |change: &OpenChange| {
984            opened.update(|o| o.0.retain(|w| w.id != id));
985            if let Some(f) = &user {
986                f(change);
987            }
988        })
989    };
990    let (owner, this) = Owner::detached().run(|| {
991        super::create_root(|| WindowRef {
992            id: id.clone(),
993            target: Target::Own(super::element_ref()),
994            state: Some(super::signal(None)),
995            title_bar: Some(super::signal(Edges::default())),
996            close: Some({
997                let on_open_change = on_open_change.clone();
998                Rc::new(move |reason| {
999                    on_open_change(&OpenChange {
1000                        open: false,
1001                        reason,
1002                    })
1003                })
1004            }),
1005            close_press: Some(super::signal((0, CloseReason::default()))),
1006            early: Some(super::signal(Early::default())),
1007        })
1008    });
1009    window.on_open_change = Some(on_open_change);
1010    window.open = None;
1011    window.opened = Some(this.clone());
1012    opened.update(|o| {
1013        o.0.push(Opened {
1014            id,
1015            window: Rc::new(RefCell::new(Some(window))),
1016            owner,
1017        })
1018    });
1019    Some(this)
1020}
1021
1022/// The windows [`open_window`] opened: the core renders it beside the
1023/// app's root.
1024pub(crate) struct OpenedWindowsHost;
1025
1026impl super::Component for OpenedWindowsHost {
1027    type Props = ();
1028    type Event = super::NoEvent;
1029
1030    fn view(_: (), _: super::Scope<super::NoEvent>) -> impl IntoElement {
1031        super::each(
1032            move || super::global::<OpenedWindows>().get().0,
1033            |w: &Opened| w.id.clone(),
1034            |w, _| {
1035                let w = w.get_untracked();
1036                // The ref's signals go once the window closes (its row goes).
1037                let owner = w.owner;
1038                super::cleanup(move || owner.dispose());
1039                let window = w.window.borrow().as_ref().map(|w| Window {
1040                    options: w.options.clone(),
1041                    bound: w.bound.clone(),
1042                    reactive: Vec::new(),
1043                    open: None,
1044                    content: w.content.clone(),
1045                    on_open_change: w.on_open_change.clone(),
1046                    on_close_press: w.on_close_press.clone(),
1047                    opened: w.opened.clone(),
1048                });
1049                let reactive = w
1050                    .window
1051                    .borrow_mut()
1052                    .as_mut()
1053                    .map(|w| std::mem::take(&mut w.reactive))
1054                    .unwrap_or_default();
1055                window.map(|mut window| {
1056                    window.reactive = reactive;
1057                    window
1058                })
1059            },
1060        )
1061    }
1062}
1063
1064/// Quits the app, as the application menu's Quit item
1065/// ([`MenuRole::Quit`]) and the platform's quit key do (TS: `Application.quit`):
1066/// the engine stops as when the last window closes (an embedding app's close
1067/// handling runs as it does for the Quit item), then the app's run ends, also
1068/// when closing the window alone would leave it running (a window kept hidden
1069/// for the Dock, a tray icon). It is not a per-window close path: windows'
1070/// `on_open_change` may not run. It quits
1071/// whether or not the app listens to quit requests ([`on_quit_request`]):
1072/// that is how an app that asks first quits once it is ready; a GPUI host
1073/// that owns the window is asked first and quits when it is ready. For a
1074/// menu item or a button of
1075/// the app's own that quits, and for restarting after an update. A view
1076/// embedded in another app leaves the app's lifecycle to that app. On the
1077/// web, called while a quit request listener runs, it lets the page leave
1078/// without a question ([`on_quit_request`]); the app ends as the page goes.
1079/// On platforms without desktop windows this has no effect.
1080pub fn quit() {
1081    super::desktop_command(DesktopCommand::Quit);
1082}
1083
1084/// Sets when closing the app's last window quits it (TS:
1085/// `Application.setQuitMode`; nsh.json's `application.quitMode`):
1086/// [`desktop::QuitMode::Platform`] (the default) follows the platform
1087/// (macOS stays in the Dock; Windows and Linux quit),
1088/// [`desktop::QuitMode::LastWindowClosed`] quits on every platform, and
1089/// [`desktop::QuitMode::Explicit`] leaves the app running so it can open
1090/// another window, show a tray menu or call [`quit`]. The app root stays
1091/// alive while no window is open. A view embedded in another app leaves
1092/// the app's lifecycle to that app; on platforms without desktop windows
1093/// this has no effect.
1094pub fn set_quit_mode(mode: desktop::QuitMode) {
1095    super::desktop_command(DesktopCommand::SetQuitMode(mode));
1096}
1097
1098/// Sets which additional requests go to [`on_quit_request`] on standalone
1099/// apps (TS: `Application.setQuitRequestOptions`): system requests on macOS
1100/// and Windows, main-window closes on macOS. Both options default to false;
1101/// each call replaces them. Without a listener the app
1102/// still quits as before. Changing the options cancels a pending request.
1103/// Replacing the app cancels its request and restores the default options.
1104/// Other platforms and embedded views ignore it.
1105pub fn set_quit_request_options(options: desktop::QuitRequestOptions) {
1106    super::desktop_command(DesktopCommand::SetQuitRequestOptions(options));
1107}
1108
1109/// Cancels the pending quit request on standalone macOS, Windows and Linux apps
1110/// (TS: `Application.cancelQuitRequest`). For an intercepted system
1111/// request, this cancels logout or shutdown too (on Windows, the user can
1112/// still end the session anyway). Call [`quit`] to approve instead.
1113/// Repeated requests share the pending confirmation until answered.
1114/// System requests left unanswered are cancelled after 110 seconds (on
1115/// macOS, before AppKit's logout timeout). Removing the last listener also
1116/// cancels them.
1117/// Nothing happens without a pending request or on other platforms.
1118pub fn cancel_quit_request() {
1119    super::desktop_command(DesktopCommand::CancelQuitRequest);
1120}
1121
1122/// The application menu as a window's menu bar shows it on Windows and Linux
1123/// (TS: `MenuBar` from `nsh/base` draws it): what
1124/// [`set_application_menu`] set, completed with the standard menus (an Edit
1125/// menu, Quit) and titled in the app's language. Empty while none is set
1126/// and on macOS, whose menu bar is the system's. Reactive: a component
1127/// reading it follows the menu. Choose an item with
1128/// [`choose_application_menu_item`].
1129pub fn application_menu() -> Vec<desktop::MenuItem> {
1130    if !desktop_os() || super::os() == Os::MacOs {
1131        return Vec::new();
1132    }
1133    let menu = super::menus::app_menu(&super::view_menus()).get();
1134    let Some(items) = menu.items else {
1135        return Vec::new();
1136    };
1137    let mut bar = desktop::menu_bar(&items, false);
1138    menu.labels.title_menus(&mut bar);
1139    // A role's item shows the label and shortcut the platform gives it.
1140    fn roles(items: &mut [desktop::MenuItem], labels: &desktop::MenuLabels) {
1141        for item in items {
1142            match item {
1143                desktop::MenuItem::Action(action) => {
1144                    if let Some(role) = action.role {
1145                        if action.label.is_empty() {
1146                            action.label = labels.label(role).to_owned();
1147                        }
1148                        if action.shortcut.is_none() {
1149                            action.shortcut = role.shortcut(false);
1150                        }
1151                    }
1152                }
1153                desktop::MenuItem::Submenu { items, .. } => roles(items, labels),
1154                desktop::MenuItem::Separator => {}
1155            }
1156        }
1157    }
1158    roles(&mut bar, &menu.labels);
1159    bar
1160}
1161
1162/// Chooses `item` of [`application_menu`], as the platform's menu bar does:
1163/// its role ([`perform_menu_role`]) or its handler (the app's `onSelect`,
1164/// in Rust or JS).
1165pub fn choose_application_menu_item(item: &desktop::MenuAction) {
1166    match item.role {
1167        Some(role) => perform_menu_role(role),
1168        None if item.id != 0 => super::act(super::task::Action::ChooseMenuItem(item.id)),
1169        None => {}
1170    }
1171}
1172
1173/// Performs `role` as the application menu's item of that role does: copy,
1174/// paste and the other edit roles act on the focused view, window roles on
1175/// the focused window, `quit` asks as the Quit item does (TS:
1176/// `Menu.perform`). For menus the app draws itself (`MenuBar`). Standalone
1177/// apps on macOS, Windows and Linux; elsewhere it does nothing.
1178pub fn perform_menu_role(role: crate::desktop::MenuRole) {
1179    if desktop_os() {
1180        super::desktop_command(DesktopCommand::PerformMenuRole(role));
1181    }
1182}
1183
1184pub use super::quit::QUIT_TIMEOUT;
1185
1186/// Runs `f` as the app quits, for its cleanup (TS: `Application.on("quit",
1187/// …)`), as GPUI's `App::on_app_quit`: saving what it keeps, closing a
1188/// connection. It cannot keep the app running; an app that asks first
1189/// listens to quit requests ([`on_quit_request`]). It runs when the app
1190/// stops: its Quit
1191/// item and [`quit`], its last window closing, the system ending it
1192/// (logging out), a host app removing its view, on the web the page going
1193/// (its tab closed, a reload, another site), once, however the user left
1194/// it; a page the browser keeps to come back to keeps the app running.
1195/// The engine waits for the
1196/// futures it returns [`QUIT_TIMEOUT`] at most, together, and while it
1197/// waits the platform does: keep it short. Removed with the current owner.
1198///
1199/// ```ignore
1200/// on_app_quit(move || {
1201///     let draft = draft.get_untracked();
1202///     async move { save_draft(draft).await }
1203/// });
1204/// ```
1205pub fn on_app_quit<F>(f: impl FnMut() -> F + 'static)
1206where
1207    F: std::future::Future<Output = ()> + 'static,
1208{
1209    let owner = Owner::current();
1210    let f = RefCell::new(f);
1211    let listener: super::quit::QuitListener = Rc::new(move || {
1212        let future = owner.run(|| (f.borrow_mut())());
1213        super::ambient::owned(owner, future)
1214    });
1215    let subscription = add_quit_listener(listener);
1216    cleanup(move || drop(subscription));
1217}
1218
1219/// Runs `f` each time the user asks to quit the app (TS:
1220/// `Application.on("quitRequest", …)`), as AppKit's
1221/// `applicationShouldTerminate:`: while one is registered, the app's Quit
1222/// item and the platform's quit key (Command-Q, Ctrl+Q) no longer quit, and
1223/// the app decides: it asks the user, saves, or waits for work to finish,
1224/// then calls [`quit`]. Without one they quit as before. The system ending
1225/// the app (logging out, shutting down) runs [`on_app_quit`] without asking
1226/// by default. On macOS, Windows and Linux (with a session manager), [`set_quit_request_options`] can
1227/// include system requests (and main-window closes on macOS); answer with
1228/// [`quit`] or [`cancel_quit_request`]. Standalone apps on macOS, Windows and Linux;
1229/// a view embedded in another app leaves the app's lifecycle to that app. On the web, the
1230/// user leaving the page (closing its tab, reloading) is the request: `f`
1231/// runs then, and a [`quit`] it calls at once lets the page go without a
1232/// question; otherwise the browser asks the user whether to leave. The
1233/// [`on_app_quit`] listeners run once the page is gone. Removed with the
1234/// current owner.
1235///
1236/// ```ignore
1237/// on_quit_request(move || {
1238///     if busy.get_untracked() {
1239///         confirm_quit.set(true);
1240///     } else {
1241///         quit();
1242///     }
1243/// });
1244/// ```
1245pub fn on_quit_request(f: impl Fn() + 'static) {
1246    let owner = Owner::current();
1247    let listener: super::quit::QuitRequestListener = Rc::new(move || owner.run(&f));
1248    let subscription = add_quit_request_listener(listener);
1249    cleanup(move || drop(subscription));
1250}
1251
1252/// Runs `f` each time the OS asks the app to show itself (TS:
1253/// `Application.on("reopen", …)`): a macOS Dock or Finder reopen, or a
1254/// later launch on Windows and Linux. The app opens or focuses the window
1255/// it wants; nothing shows implicitly. Removed with the current owner.
1256pub fn on_reopen(f: impl Fn() + 'static) {
1257    let owner = Owner::current();
1258    let listener: super::quit::ReopenListener = Rc::new(move || owner.run(&f));
1259    let subscription = add_reopen_listener(listener);
1260    cleanup(move || drop(subscription));
1261}
1262
1263/// Runs `f` when the app's last window closes (TS:
1264/// `Application.on("lastWindowClosed", …)`), after the window's own close
1265/// path. The quit mode is decided at that close; a JS listener runs in a
1266/// later commit, after the decision, so an app that stays alive with no
1267/// windows sets `quitMode: "explicit"` before the last close.
1268/// Removed with the current owner.
1269pub fn on_last_window_closed(f: impl Fn() + 'static) {
1270    let owner = Owner::current();
1271    let listener: super::quit::LastWindowClosedListener = Rc::new(move || owner.run(&f));
1272    let subscription = add_last_window_closed_listener(listener);
1273    cleanup(move || drop(subscription));
1274}
1275
1276/// Adds `listener` to what hears the user ask to quit, until the
1277/// subscription drops (`Application.on("quitRequest")` keeps one per JS
1278/// listener).
1279pub(crate) fn add_quit_request_listener(
1280    listener: super::quit::QuitRequestListener,
1281) -> super::quit::Subscription<super::quit::QuitRequestListener> {
1282    let requests = &super::ambient::executor().quit_requests;
1283    let id = requests.borrow_mut().add(listener);
1284    super::quit::Subscription::new(requests, id)
1285}
1286
1287/// Adds `listener` to what hears the OS ask the app to show itself
1288/// (`Application.on("reopen")` keeps one per JS listener).
1289pub(crate) fn add_reopen_listener(
1290    listener: super::quit::ReopenListener,
1291) -> super::quit::Subscription<super::quit::ReopenListener> {
1292    let reopens = &super::ambient::executor().reopens;
1293    let id = reopens.borrow_mut().add(listener);
1294    super::quit::Subscription::new(reopens, id)
1295}
1296
1297/// Adds `listener` to what hears the app's last window close
1298/// (`Application.on("lastWindowClosed")` keeps one per JS listener).
1299pub(crate) fn add_last_window_closed_listener(
1300    listener: super::quit::LastWindowClosedListener,
1301) -> super::quit::Subscription<super::quit::LastWindowClosedListener> {
1302    let closed = &super::ambient::executor().last_window_closed;
1303    let id = closed.borrow_mut().add(listener);
1304    super::quit::Subscription::new(closed, id)
1305}
1306
1307/// Adds `listener` to what runs as the app quits, until the subscription
1308/// drops (`Application.on("quit")` keeps one while the VM lasts).
1309pub(crate) fn add_quit_listener(
1310    listener: super::quit::QuitListener,
1311) -> super::quit::QuitSubscription {
1312    let quit = &super::ambient::executor().quit;
1313    let id = quit.borrow_mut().add(listener);
1314    super::quit::QuitSubscription::new(quit, id)
1315}
1316
1317/// Restarts the app (TS: `Application.restart`): it quits as [`quit`]
1318/// does, and once this process has exited the platform starts the same
1319/// program again with the arguments it was started with. For a setting
1320/// that takes effect at the next start (the app's language, say): the app
1321/// asks the user first, then calls this. Standalone apps on macOS, Windows
1322/// and Linux; a view embedded in another app leaves the app's lifecycle to
1323/// that app, and on other platforms this has no effect.
1324pub fn restart() {
1325    super::desktop_command(DesktopCommand::Restart);
1326}
1327
1328/// Whether the system opens the app when the user logs in (TS:
1329/// `Application.launchAtLogin()`), as the system has it now: ask again when
1330/// the app shows it, as the user may change it in the system's settings.
1331/// To await in a task. `false` wherever the app cannot launch at login (a
1332/// view embedded in another app, `nsh run`, iOS, Android, the web), while
1333/// macOS waits for the user to approve it in Login Items, and when the
1334/// system cannot be read (logged). On macOS it is the app's bundle id's, the
1335/// same for every copy of the app; on Windows and Linux it is this copy's.
1336pub fn launch_at_login() -> impl Future<Output = bool> + 'static {
1337    let answer = super::login_item_request(None);
1338    async move {
1339        answer.await.unwrap_or_else(|error| {
1340            log::warn!("{error}");
1341            false
1342        })
1343    }
1344}
1345
1346/// Turns launching at login on or off (TS:
1347/// `Application.setLaunchAtLogin(enabled)`): turning on what is on and off
1348/// what is off succeed. Call it when the user turns the app's own setting on
1349/// or off, never on the app's own (at every start, say): what the user
1350/// chose in the system's settings stands. The changes run in the order the
1351/// app makes them. On macOS the system may then wait for the user's
1352/// approval, and [`launch_at_login`] reads `false` until they give it.
1353/// Fails with [`LaunchAtLoginError::Unavailable`] where the app cannot
1354/// launch at login and with the system's error when it refuses.
1355pub fn set_launch_at_login(
1356    enabled: bool,
1357) -> impl Future<Output = Result<(), LaunchAtLoginError>> + 'static {
1358    // Asked now, so the changes keep the order of the calls.
1359    let answer = super::login_item_request(Some(enabled));
1360    async move { answer.await.map(|_| ()) }
1361}
1362
1363/// An item of a menu (TS: `nsh/desktop`'s `MenuItem`): an item that runs
1364/// its [`on_select`](Self::on_select) or carries out its
1365/// [`role`](Self::role), a separator, or a submenu.
1366///
1367/// ```ignore
1368/// MenuItem::submenu("File", [
1369///     MenuItem::new("New").shortcut("mod+n").on_select(new_document),
1370///     MenuItem::separator(),
1371///     MenuItem::role(MenuRole::Quit),
1372/// ])
1373/// ```
1374#[derive(Clone)]
1375pub struct MenuItem {
1376    kind: Kind,
1377    label: String,
1378    role: Option<MenuRole>,
1379    /// The keystroke as written, checked.
1380    shortcut: Option<Rc<str>>,
1381    when: When,
1382    enabled: bool,
1383    checked: Option<bool>,
1384    icon: Option<ImageSrc>,
1385    /// An SF Symbol name for iOS header menus; see [`Self::symbol`].
1386    symbol: Option<String>,
1387    /// Destructive on iOS; ignored on the desktops; see [`Self::destructive`].
1388    destructive: bool,
1389    /// Inline section when this is a submenu; see [`Self::inline`].
1390    inline: bool,
1391    on_select: Option<MenuHandler>,
1392}
1393
1394#[derive(Clone)]
1395enum Kind {
1396    Action,
1397    Separator,
1398    Submenu(Vec<MenuItem>),
1399}
1400
1401impl MenuItem {
1402    fn of(kind: Kind, label: String) -> Self {
1403        MenuItem {
1404            kind,
1405            label,
1406            role: None,
1407            shortcut: None,
1408            when: When::Always,
1409            enabled: true,
1410            checked: None,
1411            icon: None,
1412            symbol: None,
1413            destructive: false,
1414            inline: false,
1415            on_select: None,
1416        }
1417    }
1418
1419    /// An item showing `label`.
1420    pub fn new(label: impl Into<String>) -> Self {
1421        Self::of(Kind::Action, label.into())
1422    }
1423
1424    /// A standard item the platform carries out, with the platform's label
1425    /// and shortcut unless it is given its own.
1426    pub fn role(role: MenuRole) -> Self {
1427        MenuItem {
1428            role: Some(role),
1429            ..Self::of(Kind::Action, String::new())
1430        }
1431    }
1432
1433    /// A line between groups of items.
1434    pub fn separator() -> Self {
1435        Self::of(Kind::Separator, String::new())
1436    }
1437
1438    /// An item opening a menu of `items` (the top-level menus of the
1439    /// application menu: `File`, `Edit`, ...).
1440    pub fn submenu(label: impl Into<String>, items: impl IntoIterator<Item = MenuItem>) -> Self {
1441        Self::of(Kind::Submenu(items.into_iter().collect()), label.into())
1442    }
1443
1444    /// What it shows, in place of its role's label.
1445    pub fn label(mut self, label: impl Into<String>) -> Self {
1446        self.label = label.into();
1447        self
1448    }
1449
1450    /// Its keyboard shortcut, as `nsh/keymap` writes keystrokes: `"mod+n"`,
1451    /// `"mod+shift+z"`, `"alt+f4"`, `"f11"` (`mod` is Command on macOS and
1452    /// Control elsewhere; [`Shortcut::parse`]).
1453    ///
1454    /// # Panics
1455    ///
1456    /// On a keystroke that is not one, as TS's menus throw.
1457    #[track_caller]
1458    pub fn shortcut(mut self, keystroke: &str) -> Self {
1459        if let Err(e) = Shortcut::parse(keystroke, false) {
1460            panic!("MenuItem::shortcut: {e}");
1461        }
1462        self.shortcut = Some(keystroke.into());
1463        self
1464    }
1465
1466    /// When its shortcut chooses it while a text field has the keyboard
1467    /// focus ([`When::Always`] by default), on the GPUI backend.
1468    pub fn shortcut_when(mut self, when: When) -> Self {
1469        self.when = when;
1470        self
1471    }
1472
1473    /// It cannot be chosen (or opened): shown dimmed.
1474    pub fn disabled(mut self, disabled: bool) -> Self {
1475        self.enabled = !disabled;
1476        self
1477    }
1478
1479    /// A check mark: makes it a checkable item, checked or not.
1480    pub fn checked(mut self, checked: bool) -> Self {
1481        self.checked = Some(checked);
1482        self
1483    }
1484
1485    /// The image beside its label, or beside a submenu's (the top-level
1486    /// menus of a menu bar show their titles alone): a URL or an
1487    /// [`asset!`](crate::asset)'s image, as [`image`](crate::element::image)
1488    /// takes, fitted in the menu's icon size for the screen. An SVG takes
1489    /// the color of the menu's text; a bitmap keeps its colors. It loads
1490    /// off the main thread and shows once it has (one that fails to load
1491    /// leaves the item without an icon, with a warning). GTK's menus show
1492    /// no icons beside labels, and a terminal shows no images. For an SF
1493    /// Symbol name for iOS header menus, use [`Self::symbol`] instead.
1494    pub fn icon(mut self, src: impl Into<ImageSrc>) -> Self {
1495        self.icon = Some(src.into());
1496        self
1497    }
1498
1499    /// An SF Symbol name beside its label in iOS header menus; ignored
1500    /// elsewhere (including macOS). Takes the place of [`Self::icon`] when
1501    /// both are set.
1502    pub fn symbol(mut self, name: impl Into<String>) -> Self {
1503        self.symbol = Some(name.into());
1504        self
1505    }
1506
1507    /// Marks the action destructive: iOS draws it red; the desktops ignore
1508    /// it.
1509    pub fn destructive(mut self, destructive: bool) -> Self {
1510        self.destructive = destructive;
1511        self
1512    }
1513
1514    /// An inline section when this is a submenu ([`Self::submenu`]): on
1515    /// iOS, `UIMenuOptions.displayInline` with the label as the section
1516    /// title; on the desktops, its items between separators, its label
1517    /// not shown.
1518    pub fn inline(mut self, inline: bool) -> Self {
1519        self.inline = inline;
1520        self
1521    }
1522
1523    /// Runs `f` when it is chosen, by a click or its shortcut, under the
1524    /// owner that showed the menu.
1525    pub fn on_select(mut self, f: impl Fn() + 'static) -> Self {
1526        self.on_select = Some(Rc::new(f));
1527        self
1528    }
1529}
1530
1531impl fmt::Debug for MenuItem {
1532    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1533        match &self.kind {
1534            Kind::Separator => f.write_str("Separator"),
1535            Kind::Submenu(items) => f
1536                .debug_struct("Submenu")
1537                .field("label", &self.label)
1538                .field("items", items)
1539                .finish_non_exhaustive(),
1540            Kind::Action => f
1541                .debug_struct("MenuItem")
1542                .field("label", &self.label)
1543                .field("role", &self.role)
1544                .field("shortcut", &self.shortcut)
1545                .finish_non_exhaustive(),
1546        }
1547    }
1548}
1549
1550/// Makes the platform's items of `items`, keeping their handlers (run
1551/// under `owner`) in `handlers` with the ids it gives them.
1552pub(crate) fn decode_for_header(
1553    items: Vec<MenuItem>,
1554    mac: bool,
1555    owner: &Owner,
1556    handlers: &mut Vec<(u32, MenuHandler)>,
1557) -> Vec<desktop::MenuItem> {
1558    decode(items, mac, owner, handlers)
1559}
1560
1561/// Makes the platform's items of `items`, keeping their handlers (run
1562/// under `owner`) in `handlers` with the ids it gives them.
1563fn decode(
1564    items: Vec<MenuItem>,
1565    mac: bool,
1566    owner: &Owner,
1567    handlers: &mut Vec<(u32, MenuHandler)>,
1568) -> Vec<desktop::MenuItem> {
1569    let menus = super::view_menus();
1570    items
1571        .into_iter()
1572        .map(|item| match item.kind {
1573            Kind::Separator => desktop::MenuItem::Separator,
1574            Kind::Submenu(items) => desktop::MenuItem::Submenu {
1575                label: item.label,
1576                enabled: item.enabled,
1577                items: decode(items, mac, owner, handlers),
1578                icon: item.icon.as_ref().and_then(ImageSrc::menu_icon),
1579                symbol: item.symbol,
1580                inline: item.inline,
1581            },
1582            Kind::Action => {
1583                let id = match item.on_select {
1584                    Some(f) => {
1585                        let id = menus.borrow_mut().next_id();
1586                        let owner = *owner;
1587                        handlers.push((id, Rc::new(move || owner.run(&*f))));
1588                        id
1589                    }
1590                    None => 0,
1591                };
1592                let shortcut = match item.shortcut {
1593                    // Checked when it was given.
1594                    Some(text) => Shortcut::parse(&text, mac).ok(),
1595                    None => item.role.and_then(|r| r.shortcut(mac)),
1596                };
1597                desktop::MenuItem::Action(MenuAction {
1598                    id,
1599                    label: item.label,
1600                    shortcut,
1601                    enabled: item.enabled,
1602                    checked: item.checked,
1603                    role: item.role,
1604                    when: item.when,
1605                    icon: item.icon.as_ref().and_then(ImageSrc::menu_icon),
1606                    symbol: item.symbol,
1607                    destructive: item.destructive,
1608                })
1609            }
1610        })
1611        .collect()
1612}
1613
1614/// Decodes the items of a selectable view's selection menu
1615/// ([`super::Element::selection_menu`]), keeping their handlers under a
1616/// generation that a cleanup drops when the binding is replaced or the
1617/// owner goes. Shown on every OS, not the desktops alone.
1618pub(crate) fn register_selection_menu(items: Vec<MenuItem>) -> Vec<desktop::MenuItem> {
1619    let menus = super::view_menus();
1620    let owner = Owner::current();
1621    let mut handlers = Vec::new();
1622    let items = decode(items, super::os() == Os::MacOs, &owner, &mut handlers);
1623    let generation = menus.borrow_mut().push_header(handlers);
1624    let weak = Rc::downgrade(&menus);
1625    cleanup(move || {
1626        if let Some(menus) = weak.upgrade() {
1627            menus.borrow_mut().take_header(generation);
1628        }
1629    });
1630    items
1631}
1632
1633/// Whether the app runs on a desktop OS, where menus show (as TS's).
1634fn desktop_os() -> bool {
1635    super::os().is_desktop()
1636}
1637
1638/// Sets the application menu, a submenu per top-level item (`File`,
1639/// `Edit`, ...), or with `None` restores the platform's default (TS:
1640/// `Menu.setApplicationMenu`). On macOS it is the menu bar, whose first
1641/// menu is the app menu (titled with the app's name); on Windows the menu
1642/// bar of each normal [`window`], not shown while its title bar is hidden
1643/// (its shortcuts still work: a title bar of the app's own shows its menus
1644/// with [`popup_menu`]), whose window roles act on that window. Linux does
1645/// not show it yet: it belongs to the hidden app host. Call it again to change it; in an [`effect`] it follows
1646/// the signals it reads. The items' handlers run while the current owner
1647/// lives: the menu stays after it, inert, until it is set again.
1648///
1649/// [`effect`]: super::effect
1650pub fn set_application_menu(items: impl Into<Option<Vec<MenuItem>>>) {
1651    if !desktop_os() {
1652        return;
1653    }
1654    let menus = super::view_menus();
1655    let Some(items) = items.into() else {
1656        let mut m = menus.borrow_mut();
1657        m.app_generation += 1;
1658        let old = std::mem::take(&mut m.app);
1659        drop(m);
1660        drop(old);
1661        super::desktop_command(DesktopCommand::SetMenu(None));
1662        return;
1663    };
1664    let owner = Owner::current();
1665    let mut handlers = Vec::new();
1666    let items = desktop::MenuItem::with_inline_expanded(&decode(
1667        items,
1668        super::os() == Os::MacOs,
1669        &owner,
1670        &mut handlers,
1671    ));
1672    let generation = {
1673        let mut m = menus.borrow_mut();
1674        m.app_generation += 1;
1675        let old = std::mem::replace(&mut m.app, handlers);
1676        let generation = m.app_generation;
1677        drop(m);
1678        drop(old);
1679        generation
1680    };
1681    let weak = Rc::downgrade(&menus);
1682    cleanup(move || {
1683        if let Some(menus) = weak.upgrade() {
1684            let mut m = menus.borrow_mut();
1685            if m.app_generation == generation {
1686                let old = std::mem::take(&mut m.app);
1687                drop(m);
1688                drop(old);
1689            }
1690        }
1691    });
1692    super::desktop_command(DesktopCommand::SetMenu(Some(items.into())));
1693}
1694
1695/// Shows a context menu of `items` at the pointer (TS: `Menu.popup`). The
1696/// chosen item's [`MenuItem::on_select`] runs under the current owner. The
1697/// answer comes once the menu closes, chosen or dismissed (at once off
1698/// desktops), so a button that opened it can look pressed until then; it
1699/// need not be awaited.
1700pub fn popup_menu(items: Vec<MenuItem>) -> Answer<()> {
1701    popup(items, None)
1702}
1703
1704/// As [`popup_menu`], with the menu's top left corner at `at` (the
1705/// window's coordinates, in points: an
1706/// [`on_context_menu`](super::Interactive::on_context_menu)'s
1707/// `page_position`; TS: `Menu.popup(items, at)`).
1708pub fn popup_menu_at(items: Vec<MenuItem>, at: Point<Points>) -> Answer<()> {
1709    popup(items, Some(at))
1710}
1711
1712fn popup(items: Vec<MenuItem>, at: Option<Point<Points>>) -> Answer<()> {
1713    let (answer, slot) = Answer::new();
1714    if !desktop_os() {
1715        slot.borrow_mut().deliver(());
1716        return answer;
1717    }
1718    let menus = super::view_menus();
1719    let owner = Owner::current();
1720    let mut handlers = Vec::new();
1721    let items = desktop::MenuItem::with_inline_expanded(&decode(
1722        items,
1723        super::os() == Os::MacOs,
1724        &owner,
1725        &mut handlers,
1726    ));
1727    let generation = {
1728        let mut m = menus.borrow_mut();
1729        // One context menu at a time: one shown before is closed by now.
1730        m.settle_popup();
1731        m.closed = Some(slot);
1732        m.popup_generation += 1;
1733        let old = std::mem::replace(&mut m.popup, handlers);
1734        let generation = m.popup_generation;
1735        drop(m);
1736        drop(old);
1737        generation
1738    };
1739    let weak = Rc::downgrade(&menus);
1740    cleanup(move || {
1741        if let Some(menus) = weak.upgrade() {
1742            let mut m = menus.borrow_mut();
1743            if m.popup_generation == generation {
1744                let old = std::mem::take(&mut m.popup);
1745                drop(m);
1746                drop(old);
1747            }
1748        }
1749    });
1750    super::desktop_command(DesktopCommand::PopupMenu {
1751        items: items.into(),
1752        at,
1753    });
1754    answer
1755}
1756
1757/// A click on the tray's icon ([`Tray::on_click`]; TS: `TrayClickEvent`).
1758#[derive(Debug, Clone, Copy, PartialEq)]
1759#[non_exhaustive]
1760pub struct TrayClickEvent {
1761    /// The icon's frame on the screen, in points, in the coordinates of
1762    /// [`displays`] and [`WindowRef::set_bounds`]: where to place a window
1763    /// beside it. `None` when the system does not say where the icon is
1764    /// (always on Linux).
1765    pub bounds: Option<Bounds<Points>>,
1766}
1767
1768/// The app's icon in the system tray, for [`set_tray`] (TS:
1769/// `TrayOptions`): the notification area on Windows, the menu bar's right
1770/// side on macOS, a StatusNotifierItem on Linux.
1771#[derive(Default)]
1772#[must_use = "a tray shows nothing until given to set_tray"]
1773pub struct Tray {
1774    icon: Option<ImageSrc>,
1775    tooltip: String,
1776    title: Vec<TrayTitleRun>,
1777    title_placement: TrayTitlePlacement,
1778    menu: Vec<MenuItem>,
1779    on_click: Option<TrayClick>,
1780}
1781
1782type TrayClick = Rc<dyn Fn(&TrayClickEvent)>;
1783
1784/// A tray icon to give to [`set_tray`]: the app's icon, its name as the
1785/// tooltip, no menu.
1786pub fn tray() -> Tray {
1787    Tray::default()
1788}
1789
1790impl Tray {
1791    /// The icon (as [`Image`](super::Image)'s source). Keep it simple and
1792    /// square: panels draw it at 16 to 24 pixels. An SVG is a template on
1793    /// macOS, drawn in the menu bar's text color; elsewhere it keeps its
1794    /// colors. Without one, the app's icon where the system has one.
1795    pub fn icon(mut self, src: impl Into<ImageSrc>) -> Self {
1796        self.icon = Some(src.into());
1797        self
1798    }
1799
1800    /// Shown when the pointer rests on the icon (the app's name without
1801    /// it).
1802    pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
1803        self.tooltip = tooltip.into();
1804        self
1805    }
1806
1807    /// Text beside the icon, in runs each of its own color: what the app
1808    /// keeps in sight (a price, a count). macOS's menu bar shows it in its
1809    /// font; Linux's panels that show AppIndicator labels show its text
1810    /// right of the icon; Windows' notification area shows the icon alone.
1811    ///
1812    /// ```ignore
1813    /// tray().title([
1814    ///     TrayTitleRun::new("AAPL 228.00 "),
1815    ///     TrayTitleRun::new("+1.33%").color(rgb(0xd92d20)),
1816    /// ])
1817    /// ```
1818    pub fn title(mut self, runs: impl IntoIterator<Item = TrayTitleRun>) -> Self {
1819        self.title = runs.into_iter().collect();
1820        self
1821    }
1822
1823    /// Which side of the icon the title shows on (macOS; Linux's panels
1824    /// draw it right of the icon).
1825    pub fn title_placement(mut self, placement: TrayTitlePlacement) -> Self {
1826        self.title_placement = placement;
1827        self
1828    }
1829
1830    /// Its menu, opened by a secondary click (and a primary one without
1831    /// [`Tray::on_click`]).
1832    pub fn menu(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
1833        self.menu = items.into_iter().collect();
1834        self
1835    }
1836
1837    /// Runs when the icon is clicked with the primary button (on Windows,
1838    /// Enter or Space on the icon too), with where the icon is.
1839    pub fn on_click(mut self, f: impl Fn(&TrayClickEvent) + 'static) -> Self {
1840        self.on_click = Some(Rc::new(f));
1841        self
1842    }
1843}
1844
1845impl fmt::Debug for Tray {
1846    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1847        f.debug_struct("Tray")
1848            .field("tooltip", &self.tooltip)
1849            .field("title", &self.title)
1850            .field("title_placement", &self.title_placement)
1851            .field("menu", &self.menu)
1852            .field("on_click", &self.on_click.is_some())
1853            .finish_non_exhaustive()
1854    }
1855}
1856
1857/// Shows the app's icon in the system tray, or changes it; `None` removes
1858/// it (TS: `Tray.set`). One per app, shared with TS: the last set wins.
1859/// Call it again to change it; in an [`effect`] it follows the signals it
1860/// reads. Its menu's and click's handlers run while the current owner
1861/// lives: the icon stays after it, inert, until it is set again. Nothing
1862/// happens off desktops.
1863///
1864/// ```ignore
1865/// set_tray(
1866///     tray()
1867///         .icon("tray.svg")
1868///         .tooltip("Player")
1869///         .menu([MenuItem::new("Quit").on_select(quit)])
1870///         .on_click(|e| show_popover(e.bounds)),
1871/// );
1872/// ```
1873///
1874/// [`effect`]: super::effect
1875pub fn set_tray(tray: impl Into<Option<Tray>>) {
1876    if !desktop_os() {
1877        return;
1878    }
1879    let menus = super::view_menus();
1880    let Some(tray) = tray.into() else {
1881        let mut m = menus.borrow_mut();
1882        m.tray_generation += 1;
1883        let old = (std::mem::take(&mut m.tray), m.tray_click.take());
1884        drop(m);
1885        drop(old);
1886        super::desktop_command(DesktopCommand::SetTray(None));
1887        return;
1888    };
1889    let owner = Owner::current();
1890    let mut handlers = Vec::new();
1891    let items = decode(tray.menu, super::os() == Os::MacOs, &owner, &mut handlers);
1892    let click = tray.on_click.map(|f| {
1893        let id = menus.borrow_mut().next_id();
1894        let handler: super::menus::TrayClickHandler =
1895            Rc::new(move |bounds| owner.run(|| f(&TrayClickEvent { bounds })));
1896        (id, handler)
1897    });
1898    let command = desktop::Tray {
1899        icon: tray.icon.as_ref().and_then(ImageSrc::menu_icon),
1900        tooltip: tray.tooltip,
1901        title: tray.title,
1902        title_placement: tray.title_placement,
1903        menu: items.into(),
1904        click: click.as_ref().map_or(0, |(id, _)| *id),
1905    };
1906    let generation = {
1907        let mut m = menus.borrow_mut();
1908        m.tray_generation += 1;
1909        let old = (
1910            std::mem::replace(&mut m.tray, handlers),
1911            std::mem::replace(&mut m.tray_click, click),
1912        );
1913        let generation = m.tray_generation;
1914        drop(m);
1915        drop(old);
1916        generation
1917    };
1918    let weak = Rc::downgrade(&menus);
1919    cleanup(move || {
1920        if let Some(menus) = weak.upgrade() {
1921            let mut m = menus.borrow_mut();
1922            if m.tray_generation == generation {
1923                let old = (std::mem::take(&mut m.tray), m.tray_click.take());
1924                drop(m);
1925                drop(old);
1926            }
1927        }
1928    });
1929    super::desktop_command(DesktopCommand::SetTray(Some(command)));
1930}
1931
1932/// Registers `keystroke` system-wide, heard whichever app has the keyboard
1933/// (TS: `GlobalShortcut.register`): `on_press` runs at each press, under
1934/// the current owner, until [`unregister_global_shortcut`] or the owner
1935/// goes. The keystroke is written as a [`MenuItem::shortcut`]'s
1936/// (`"mod+shift+k"`). The answer is whether the system took it: `false`
1937/// when another app holds it, when the keystroke is not one (a warning
1938/// names why in the log, and the component goes on — keystrokes often
1939/// come from user settings, where a typo must not end it), or off
1940/// desktops; it need not be awaited. Registering a keystroke again
1941/// replaces its function.
1942///
1943/// On Linux it goes through the desktop portal
1944/// (`org.freedesktop.portal.GlobalShortcuts`): the desktop may ask the
1945/// user to confirm it or let them pick another keystroke, and Hyprland
1946/// binds it in its own configuration
1947/// (`bind = …, global, <app id>:<shortcut>`).
1948pub fn register_global_shortcut(keystroke: &str, on_press: impl Fn() + 'static) -> Answer<bool> {
1949    let shortcut = match Shortcut::parse(keystroke, super::os() == Os::MacOs) {
1950        Ok(shortcut) => shortcut,
1951        Err(e) => {
1952            log::warn!("register_global_shortcut: {e}");
1953            let (answer, slot) = Answer::new();
1954            slot.borrow_mut().deliver(false);
1955            return answer;
1956        }
1957    };
1958    let (answer, slot) = Answer::new();
1959    if !desktop_os() {
1960        slot.borrow_mut().deliver(false);
1961        return answer;
1962    }
1963    unregister_where(|g| g.shortcut == shortcut);
1964    let menus = super::view_menus();
1965    let owner = Owner::current();
1966    let id = {
1967        let mut m = menus.borrow_mut();
1968        let id = m.next_id();
1969        m.globals.push(super::menus::Global {
1970            id,
1971            shortcut,
1972            on_press: Rc::new(move || owner.run(&on_press)),
1973            registered: Some(slot),
1974        });
1975        id
1976    };
1977    cleanup(move || unregister_where(|g| g.id == id));
1978    super::desktop_command(DesktopCommand::RegisterGlobalShortcut { id, shortcut });
1979    answer
1980}
1981
1982/// Gives back `keystroke`, registered with [`register_global_shortcut`]
1983/// (TS: `GlobalShortcut.unregister`). A keystroke that is not one, or not
1984/// registered, does nothing.
1985pub fn unregister_global_shortcut(keystroke: &str) {
1986    if let Ok(shortcut) = Shortcut::parse(keystroke, super::os() == Os::MacOs) {
1987        unregister_where(|g| g.shortcut == shortcut);
1988    }
1989}
1990
1991/// Gives back every shortcut registered with [`register_global_shortcut`]
1992/// (TS: `GlobalShortcut.unregisterAll`).
1993pub fn unregister_all_global_shortcuts() {
1994    unregister_where(|_| true);
1995}
1996
1997fn unregister_where(remove: impl Fn(&super::menus::Global) -> bool) {
1998    let menus = super::view_menus();
1999    let removed: Vec<super::menus::Global> = {
2000        let mut m = menus.borrow_mut();
2001        let (removed, kept) = std::mem::take(&mut m.globals)
2002            .into_iter()
2003            .partition(&remove);
2004        m.globals = kept;
2005        removed
2006    };
2007    for g in removed {
2008        if let Some(slot) = g.registered {
2009            slot.borrow_mut().deliver(false);
2010        }
2011        super::desktop_command(DesktopCommand::UnregisterGlobalShortcut(g.id));
2012    }
2013}
2014
2015#[cfg(test)]
2016mod tests {
2017    use super::*;
2018
2019    /// A keystroke that is not one answers `false` where the call was
2020    /// made, instead of ending the component that took it from user
2021    /// settings (#2758): the answer is already there to poll.
2022    #[test]
2023    fn a_keystroke_that_is_not_one_answers_false() {
2024        let runtime = crate::element::Runtime::default();
2025        runtime.set_environment(crate::element::Environment::default());
2026        let _entered = runtime.enter();
2027        let answer = register_global_shortcut("ctrl+alt+notakey", || {});
2028        let waker = std::task::Waker::noop();
2029        let mut cx = std::task::Context::from_waker(waker);
2030        match std::pin::pin!(answer).poll(&mut cx) {
2031            std::task::Poll::Ready(taken) => assert!(!taken),
2032            std::task::Poll::Pending => panic!("the answer was to be delivered at once"),
2033        }
2034    }
2035}