Skip to main content

hypersig_desktop/
run.rs

1//! Starting the server and the windows side by side, and stopping both.
2
3use std::collections::HashMap;
4use std::fs;
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7
8use axum::http::HeaderMap;
9use hypersig::Url;
10use tao::event::{Event as TaoEvent, WindowEvent};
11use tao::event_loop::{ControlFlow, EventLoopBuilder, EventLoopProxy, EventLoopWindowTarget};
12use tao::platform::run_return::EventLoopExtRunReturn as _;
13use tao::window::{Window, WindowId};
14use tokio::net::TcpListener;
15use tokio::runtime::Runtime;
16use tokio::sync::oneshot;
17use wry::{WebContext, WebView};
18
19use crate::app::{App, IntoRouter};
20use crate::error::Error;
21use crate::guard::{self, Guard};
22use crate::os::Os;
23use crate::smoke::{Smoke, Step};
24use crate::{handoff, instance, port, window};
25
26/// How long the server is given to finish the requests it is answering
27/// once the last window closes, the same as `hypersig::serve` gives.
28const GRACE: Duration = Duration::from_secs(5);
29
30/// How long a hidden window waits for its page before it is shown anyway.
31const FIRST_LOAD: Duration = Duration::from_secs(10);
32
33/// How long a closing window stays, hidden, after its page leaves. The web
34/// view writes `localStorage` to disk a moment after a page sets it, and a
35/// value set just before the window closed was lost when the process ended
36/// as soon as the page had left; with this wait, it was kept in each of
37/// four runs in `WKWebView`.
38const LEAVE: Duration = Duration::from_secs(1);
39
40/// What the server's tasks, the web views, and [`Os`] tell the event loop.
41#[derive(Debug)]
42pub(crate) enum Event {
43    /// The setup failed, or the server stopped on an error.
44    Failed(Error),
45    /// The title of a window's page changed.
46    Title(WindowId, String),
47    /// A page of the application finished loading in a window.
48    Loaded(WindowId),
49    /// A window's page has not finished loading in [`FIRST_LOAD`].
50    Slow(WindowId),
51    /// A page asks to be opened in a new window, answered on `answer` with
52    /// the window, when [`Os`] asked.
53    Open {
54        url: String,
55        answer: Option<oneshot::Sender<Result<WindowId, Error>>>,
56    },
57    /// [`Os`] shows a tray icon, or replaces the one shown.
58    Tray {
59        tray: crate::Tray,
60        answer: oneshot::Sender<Result<(), Error>>,
61    },
62    /// [`Os`] registers a global shortcut, or listens to one registered.
63    Shortcut {
64        shortcut: crate::Shortcut,
65        answer: oneshot::Sender<Result<crate::Presses, Error>>,
66    },
67    /// A global shortcut went down or came up.
68    Pressed(u32, crate::Press),
69    /// [`Os`] puts these menus in the menu bar.
70    Menus(Vec<crate::Menu>),
71    /// An item of the menu bar or of the tray's menu was chosen.
72    Menu(tray_icon::menu::MenuId),
73    /// [`Os`] closes a window.
74    Close(WindowId),
75    /// [`Os`] brings a window to the front.
76    Focus(WindowId),
77    /// [`Os`] asks which window had the keyboard last.
78    Focused(oneshot::Sender<Option<WindowId>>),
79    /// [`Os`] moves, sizes, or places a window.
80    Arrange(WindowId, crate::arrange::Arrange),
81    /// The person pressed a part of a window's page that moves the window.
82    Drag(WindowId),
83    /// The person double-clicked such a part.
84    Zoom(WindowId),
85    /// The count to show on the application's icon.
86    Badge(u32),
87    /// [`LEAVE`] has passed since a window began to close, or, with no
88    /// window, the application is quitting.
89    Left(Option<WindowId>),
90    /// An update closes the application and installs its package after
91    /// the server has stopped.
92    #[cfg(feature = "updater")]
93    Install(Box<crate::Downloaded>),
94    /// Ctrl-C was pressed in the terminal, or Quit was chosen in the menu.
95    Quit,
96    /// A second copy handed its command line over.
97    Raise,
98    /// The first page's answer to what a smoke run asked, or `None` when
99    /// it is time to ask again.
100    Smoke(Option<String>),
101}
102
103#[cfg(feature = "updater")]
104impl App<crate::Updates> {
105    /// Serves the router `setup` builds and shows `first_page` in a window,
106    /// as [`App::run`](App::<()>::run) does.
107    ///
108    /// `setup` receives the [`Os`] and the [`Updater`](crate::Updater) that
109    /// finds new versions where [`App::updates`] says.
110    ///
111    /// # Errors
112    ///
113    /// Fails where [`App::run`](App::<()>::run) fails.
114    ///
115    /// # Panics
116    ///
117    /// Panics on macOS when it is not called on the main thread.
118    pub fn run<S, F>(self, first_page: &Url, setup: S) -> Result<(), Error>
119    where
120        S: FnOnce(Os, crate::Updater) -> F,
121        F: Future<Output: IntoRouter> + Send + 'static,
122    {
123        let updater = crate::Updater::system(self.updates);
124        let app = App {
125            id: self.id,
126            size: self.size,
127            min_size: self.min_size,
128            resizable: self.resizable,
129            frame: self.frame,
130            devices: self.devices,
131            updates: (),
132        };
133        app.run(first_page, move |os| setup(os, updater))
134    }
135}
136
137impl App {
138    /// Serves the router `setup` builds and shows `first_page` in a window.
139    ///
140    /// `setup` receives the [`Os`] the router's handlers open windows and
141    /// reach the operating system through, and returns the future that
142    /// builds the router. That future runs on a Tokio runtime this method
143    /// starts, while the first window and its web view are made, and the
144    /// window is shown once its page has loaded.
145    ///
146    /// When another copy of the application runs, this start opens no
147    /// window: it hands its command line to that copy, which hears of it
148    /// through [`Os::launches`] and brings a window forward, and returns
149    /// `Ok(())`.
150    ///
151    /// Closing the last window while no tray is shown, Quit in the menu or
152    /// in the tray's menu, or Ctrl-C in the terminal stops the server,
153    /// which is given five seconds to finish the requests it is answering,
154    /// and the method returns once it has stopped.
155    ///
156    /// The windows and their event loop take the thread that calls this,
157    /// which on macOS must be the main thread, so `main` is not
158    /// `#[tokio::main]`.
159    ///
160    /// # Errors
161    ///
162    /// Fails with [`ErrorKind::InRuntime`](crate::ErrorKind::InRuntime) when
163    /// called inside a Tokio runtime, as from a `#[tokio::main]` function.
164    /// Fails too when the application's directory cannot be made, when another
165    /// copy of the application runs and does not take this start's command
166    /// line, when the setup returns an error, and when a window, a web view,
167    /// or the server fails.
168    ///
169    /// # Panics
170    ///
171    /// Panics on macOS when it is not called on the main thread.
172    pub fn run<S, F>(self, first_page: &Url, setup: S) -> Result<(), Error>
173    where
174        S: FnOnce(Os) -> F,
175        F: Future<Output: IntoRouter> + Send + 'static,
176    {
177        // Inside a runtime, `block_on` below would panic with a message
178        // that names neither `run` nor `#[tokio::main]`.
179        if tokio::runtime::Handle::try_current().is_ok() {
180            return Err(Error::in_runtime());
181        }
182        let started = Instant::now();
183        #[cfg(target_os = "macos")]
184        crate::notification::name_application(self.id);
185        let own = self.data_dir()?.join("hypersig_desktop");
186        fs::create_dir_all(&own)?;
187        let lock = match instance::lock(&own) {
188            // The copy already running takes this start's command line, and
189            // brings a window forward.
190            Err(error) if error.kind() == crate::ErrorKind::AlreadyRunning => {
191                return if handoff::hand_over(&own) {
192                    Ok(())
193                } else {
194                    Err(error)
195                };
196            }
197            locked => locked?,
198        };
199
200        let runtime = tokio::runtime::Builder::new_multi_thread()
201            .enable_all()
202            .build()?;
203        let listener = runtime.block_on(port::listen(&own))?;
204        let port = listener.local_addr()?.port();
205        let launches = handoff::channel();
206        let (guard, tokens) = Guard::new(port, launches.clone())?;
207        handoff::write_token(&own, &tokens.handoff)?;
208        let start = tokens.start;
209
210        let mut event_loop = EventLoopBuilder::<Event>::with_user_event().build();
211        let proxy = event_loop.create_proxy();
212        let (stop, stopped) = oneshot::channel();
213        let setup = setup(Os::new(proxy.clone(), launches.clone(), self.id));
214        runtime.spawn(raise_on_launch(launches.subscribe(), proxy.clone()));
215        let server = runtime.spawn(serve(listener, guard, setup, proxy.clone(), stopped));
216        runtime.spawn(quit_on_ctrl_c(proxy.clone()));
217
218        forward_system_events(&proxy);
219        #[cfg(feature = "updater")]
220        crate::updates::event_loop(Some(proxy.clone()));
221        let mut run = Lifecycle {
222            app: self,
223            proxy: &proxy,
224            runtime: &runtime,
225            context: window::context(own.join("webview")),
226            base: format!("http://127.0.0.1:{port}"),
227            windows: HashMap::new(),
228            first: None,
229            launches,
230            focused: None,
231            waiting: Vec::new(),
232            started: false,
233            smoke: Smoke::from_env(started)?,
234            badge: 0,
235            tray: None,
236            hotkeys: None,
237            #[cfg(any(target_os = "macos", target_os = "linux"))]
238            bar: crate::menu::bar(&[])?,
239            menu_items: HashMap::new(),
240            #[cfg(feature = "updater")]
241            install: None,
242            shortcuts: HashMap::new(),
243            items: HashMap::new(),
244            quitting: false,
245            failure: None,
246        };
247        // The first page is asked for at once, while the event loop starts
248        // and the setup runs: the listener holds the request until the
249        // server answers it.
250        let mut headers = HeaderMap::new();
251        headers.insert(guard::START_HEADER, start);
252        let first = run.open(&event_loop, Some((first_page.as_str(), headers)))?;
253        run.first = Some(first);
254        event_loop.run_return(|event, target, flow| {
255            *flow = if run.handle(event, target) {
256                ControlFlow::Exit
257            } else {
258                ControlFlow::Wait
259            };
260        });
261        let failure = run.failure.take();
262        #[cfg(feature = "updater")]
263        let install = run.install.take();
264        #[cfg(feature = "updater")]
265        crate::updates::event_loop(None);
266        drop(run);
267
268        let _ = stop.send(());
269        runtime.block_on(async {
270            let _ = tokio::time::timeout(GRACE, server).await;
271        });
272        runtime.shutdown_timeout(GRACE);
273        drop(lock);
274        failure.map_or(Ok(()), Err)?;
275        #[cfg(feature = "updater")]
276        install_after_stop(install)?;
277        Ok(())
278    }
279}
280
281/// A window, its web view, and how far its page has come.
282struct Open {
283    window: Window,
284    web_view: WebView,
285    shown: bool,
286    leaving: bool,
287}
288
289/// A window a page or [`Os`] asked for, with where to answer.
290struct Asked {
291    url: String,
292    answer: Option<oneshot::Sender<Result<WindowId, Error>>>,
293}
294
295/// The windows and how far the run has come.
296struct Lifecycle<'a> {
297    app: App,
298    proxy: &'a EventLoopProxy<Event>,
299    runtime: &'a Runtime,
300    /// The web view data every window shares, cookies included.
301    context: WebContext,
302    /// `http://127.0.0.1:<port>`, which a page's path is joined to.
303    base: String,
304    windows: HashMap<WindowId, Open>,
305    /// The first window, whose first page trades the start token for the
306    /// session cookie.
307    first: Option<WindowId>,
308    /// Where an opened file or link goes, as a second start's command line does.
309    launches: tokio::sync::broadcast::Sender<handoff::Launch>,
310    /// The window that had the keyboard last.
311    focused: Option<WindowId>,
312    /// The windows made before the first page loaded, with the page each
313    /// loads once it has, since a page needs the cookie the first one
314    /// receives.
315    waiting: Vec<(WindowId, String)>,
316    /// Whether the first page has loaded.
317    started: bool,
318    smoke: Option<Smoke>,
319    /// The tray icon shown, which keeps the application running with no window.
320    tray: Option<tray_icon::TrayIcon>,
321    /// The package an update installs once the server has stopped.
322    #[cfg(feature = "updater")]
323    install: Option<crate::Downloaded>,
324    /// The menu bar, shown while it lives: on macOS the application's, and
325    /// on Linux one in every window.
326    #[cfg(any(target_os = "macos", target_os = "linux"))]
327    bar: muda::Menu,
328    /// Where each item of the menu bar reports its clicks.
329    menu_items: HashMap<tray_icon::menu::MenuId, tokio::sync::broadcast::Sender<()>>,
330    /// What registers the global shortcuts, made on this thread when the
331    /// first one is asked for, as macOS and Windows need.
332    hotkeys: Option<global_hotkey::GlobalHotKeyManager>,
333    /// Where each global shortcut, by its id, reports its presses.
334    shortcuts: HashMap<u32, tokio::sync::broadcast::Sender<crate::Press>>,
335    /// Where each item of the tray's menu reports its clicks.
336    items: HashMap<tray_icon::menu::MenuId, tokio::sync::broadcast::Sender<()>>,
337    /// The count on the application's icon, which a window opened later
338    /// shows too on Windows.
339    badge: u32,
340    quitting: bool,
341    failure: Option<Error>,
342}
343
344impl Lifecycle<'_> {
345    /// Answers one event, and returns whether the event loop is done.
346    /// Moves the window `id` with the pointer until the button comes up.
347    fn drag(&self, id: WindowId) {
348        if let Some(open) = self.windows.get(&id)
349            && let Err(error) = open.window.drag_window()
350        {
351            tracing::warn!(%error, "the window did not follow the pointer");
352        }
353    }
354
355    /// Maximizes the window `id`, or restores it if it is maximized.
356    fn zoom(&self, id: WindowId) {
357        if let Some(open) = self.windows.get(&id) {
358            open.window.set_maximized(!open.window.is_maximized());
359        }
360    }
361
362    fn handle(
363        &mut self,
364        event: TaoEvent<'_, Event>,
365        target: &EventLoopWindowTarget<Event>,
366    ) -> bool {
367        match event {
368            TaoEvent::UserEvent(Event::Failed(error)) => self.fail(error),
369            TaoEvent::UserEvent(Event::Title(id, title)) => {
370                if let Some(open) = self.windows.get(&id) {
371                    open.window.set_title(&title);
372                }
373            }
374            TaoEvent::UserEvent(Event::Loaded(id)) => self.loaded(id),
375            TaoEvent::UserEvent(Event::Slow(id)) => self.slow(id),
376            TaoEvent::UserEvent(Event::Open { url, answer }) => {
377                if self.started {
378                    self.answer(target, Asked { url, answer });
379                } else {
380                    self.wait(target, Asked { url, answer });
381                }
382            }
383            TaoEvent::UserEvent(Event::Close(id))
384            | TaoEvent::WindowEvent {
385                window_id: id,
386                event: WindowEvent::CloseRequested,
387                ..
388            } => self.leave(id),
389            TaoEvent::UserEvent(Event::Badge(count)) => {
390                self.badge = count;
391                let windows = self.windows.values().filter(|open| !open.leaving);
392                crate::badge::show(count, windows.map(|open| &open.window), target);
393            }
394            TaoEvent::UserEvent(Event::Focus(id)) => {
395                if let Some(open) = self.windows.get(&id) {
396                    open.window.set_focus();
397                }
398            }
399            TaoEvent::WindowEvent {
400                window_id: id,
401                event: WindowEvent::Focused(true),
402                ..
403            } => self.focused = Some(id),
404            TaoEvent::UserEvent(Event::Focused(answer)) => {
405                let open = self
406                    .focused
407                    .filter(|id| self.windows.get(id).is_some_and(|open| !open.leaving));
408                let _ = answer.send(open);
409            }
410            TaoEvent::UserEvent(Event::Arrange(id, change)) => {
411                if let Some(open) = self.windows.get(&id) {
412                    crate::arrange::apply(&open.window, change);
413                }
414            }
415            TaoEvent::UserEvent(Event::Drag(id)) => self.drag(id),
416            TaoEvent::UserEvent(Event::Zoom(id)) => self.zoom(id),
417            TaoEvent::UserEvent(Event::Left(id)) => {
418                if let Some(id) = id
419                    && self.windows.get(&id).is_some_and(|open| open.leaving)
420                {
421                    self.windows.remove(&id);
422                }
423                // A tray keeps the application running with no window,
424                // until its Quit item or another way to quit is chosen.
425                return self.windows.is_empty() && (self.tray.is_none() || self.quitting);
426            }
427            TaoEvent::UserEvent(Event::Quit) => self.quit(),
428            #[cfg(feature = "updater")]
429            TaoEvent::UserEvent(Event::Install(downloaded)) => {
430                self.install = Some(*downloaded);
431                self.quit();
432            }
433            TaoEvent::UserEvent(Event::Tray { tray, answer }) => {
434                let _ = answer.send(self.tray(&tray));
435            }
436            TaoEvent::UserEvent(Event::Menu(id)) => self.chosen(&id),
437            TaoEvent::UserEvent(Event::Menus(menus)) => self.menus(&menus),
438            TaoEvent::UserEvent(Event::Shortcut { shortcut, answer }) => {
439                let _ = answer.send(self.shortcut(shortcut));
440            }
441            TaoEvent::UserEvent(Event::Pressed(id, press)) => {
442                if let Some(presses) = self.shortcuts.get(&id) {
443                    let _ = presses.send(press);
444                }
445            }
446            TaoEvent::UserEvent(Event::Raise) => self.raise(),
447            // macOS opens a file or a link as an Apple event to the copy
448            // running, which tao reports here, where Windows and Linux
449            // start the program with it on the command line.
450            // Each file goes in the arguments as its path and each link as
451            // its text, as the command line carries them.
452            TaoEvent::Opened { urls } => {
453                let args = urls
454                    .iter()
455                    .map(|url| match url.to_file_path() {
456                        Ok(path) if url.scheme() == "file" => path.into_os_string(),
457                        _ => url.as_str().into(),
458                    })
459                    .collect();
460                let dir = std::env::current_dir().unwrap_or_default();
461                let _ = self.launches.send(handoff::Launch::new(dir, args));
462            }
463            TaoEvent::UserEvent(Event::Smoke(answer)) => self.smoke(answer.as_deref()),
464            _ => {}
465        }
466        false
467    }
468
469    /// Makes a hidden window with its web view, which loads `page`, a path
470    /// of the application or a URL of its origin, with the headers given.
471    fn open(
472        &mut self,
473        target: &EventLoopWindowTarget<Event>,
474        page: Option<(&str, HeaderMap)>,
475    ) -> Result<WindowId, Error> {
476        if self.quitting {
477            return Err(Error::closed());
478        }
479        let window = window::window(&self.app, target)?;
480        #[cfg(windows)]
481        crate::badge::on_taskbar(&window, self.badge);
482        let origin = format!("{}/", self.base);
483        let web_view =
484            window::web_view(&self.app, &window, &mut self.context, &origin, self.proxy)?;
485        #[cfg(target_os = "linux")]
486        crate::menu::attach(&self.bar, &window);
487        let id = window.id();
488        if let Some((url, headers)) = page {
489            self.load(id, &web_view, url, headers)?;
490        }
491        self.windows.insert(
492            id,
493            Open {
494                window,
495                web_view,
496                shown: false,
497                leaving: false,
498            },
499        );
500        Ok(id)
501    }
502
503    /// Has `web_view`, of the window `id`, load `url`, a path of the
504    /// application or a URL of its origin, and shows the window without its
505    /// page if the page has not loaded after [`FIRST_LOAD`].
506    fn load(
507        &self,
508        id: WindowId,
509        web_view: &WebView,
510        url: &str,
511        headers: HeaderMap,
512    ) -> Result<(), Error> {
513        let absolute = if url.starts_with('/') {
514            format!("{}{url}", self.base)
515        } else {
516            url.to_owned()
517        };
518        web_view
519            .load_url_with_headers(&absolute, headers)
520            .map_err(Error::window)?;
521        let slow = self.proxy.clone();
522        self.runtime.spawn(async move {
523            tokio::time::sleep(FIRST_LOAD).await;
524            let _ = slow.send_event(Event::Slow(id));
525        });
526        Ok(())
527    }
528
529    /// Makes the window `asked` for before the first page has loaded and
530    /// tells whoever asked, so a setup that awaits the window can return
531    /// the router the first page waits for. Its page loads once the first
532    /// page has.
533    fn wait(&mut self, target: &EventLoopWindowTarget<Event>, Asked { url, answer }: Asked) {
534        let made = self.open(target, None);
535        match &made {
536            Ok(id) => self.waiting.push((*id, url)),
537            Err(error) => tracing::error!(%error, %url, "a window could not be opened"),
538        }
539        if let Some(answer) = answer {
540            let _ = answer.send(made);
541        }
542    }
543
544    fn loaded(&mut self, id: WindowId) {
545        let Some(open) = self.windows.get_mut(&id) else {
546            return;
547        };
548        if open.leaving {
549            return;
550        }
551        // `slow` shows a window whose page is late, and the page can still
552        // load after that.
553        let late = open.shown;
554        if !late {
555            open.shown = true;
556            open.window.set_visible(true);
557            open.window.set_focus();
558            // The system may not report the focus of a window shown while
559            // another application is in front.
560            self.focused = Some(id);
561        }
562        if self.first == Some(id) {
563            if !late {
564                self.smoke(None);
565            }
566            // The first page brings the cookie the other windows need, so
567            // they open once it has loaded, late or not.
568            if !self.started {
569                self.started();
570            }
571        } else if !late
572            && let Some(smoke) = &self.smoke
573            && let Err(error) = smoke.other_window(&open.web_view)
574        {
575            self.fail(error);
576        }
577    }
578
579    /// Loads the pages of the windows made while the first page loaded,
580    /// now that the cookie they need is there.
581    fn started(&mut self) {
582        self.started = true;
583        for (id, url) in std::mem::take(&mut self.waiting) {
584            let Some(open) = self.windows.get(&id).filter(|open| !open.leaving) else {
585                continue;
586            };
587            if let Err(error) = self.load(id, &open.web_view, &url, HeaderMap::new()) {
588                tracing::error!(%error, %url, "a window could not load its page");
589                self.leave(id);
590            }
591        }
592    }
593
594    /// Opens the window `asked` for, and tells whoever asked.
595    fn answer(&mut self, target: &EventLoopWindowTarget<Event>, Asked { url, answer }: Asked) {
596        let opened = self.open(target, Some((&url, HeaderMap::new())));
597        if let Err(error) = &opened {
598            tracing::error!(%error, %url, "a window could not be opened");
599        }
600        if let Some(answer) = answer {
601            let _ = answer.send(opened);
602        }
603    }
604
605    fn slow(&mut self, id: WindowId) {
606        let Some(open) = self.windows.get_mut(&id) else {
607            return;
608        };
609        if open.shown || open.leaving {
610            return;
611        }
612        tracing::error!(
613            "a page did not finish loading in {} seconds, so its window is shown without it",
614            FIRST_LOAD.as_secs()
615        );
616        open.shown = true;
617        open.window.set_visible(true);
618        // The windows made meanwhile would load their pages without the
619        // cookie, so they close instead.
620        if self.first == Some(id) {
621            for (waiting, url) in std::mem::take(&mut self.waiting) {
622                tracing::error!(%url, "a window was closed, since the first page did not load");
623                self.leave(waiting);
624            }
625        }
626        if self.smoke.is_some() {
627            self.fail(Error::smoke("a page did not finish loading in time"));
628        }
629    }
630
631    /// Brings a shown window forward, the first one while it is open.
632    fn raise(&self) {
633        let shown = |open: &&Open| open.shown && !open.leaving;
634        let window = self
635            .first
636            .and_then(|id| self.windows.get(&id))
637            .filter(shown)
638            .or_else(|| self.windows.values().find(shown));
639        if let Some(open) = window {
640            open.window.set_focus();
641        }
642    }
643
644    /// Takes the smoke run's next step in the first window, if this is one.
645    fn smoke(&mut self, answer: Option<&str>) {
646        let Some(smoke) = &mut self.smoke else {
647            return;
648        };
649        let Some(open) = self.first.and_then(|id| self.windows.get(&id)) else {
650            return;
651        };
652        if open.leaving {
653            return;
654        }
655        match smoke.step(answer, &open.web_view, self.proxy, self.runtime) {
656            Ok(Step::Waiting) => {}
657            // A window opened at start can load its page before the first
658            // page has answered, and `loaded` ran the script in none then.
659            Ok(Step::Scripting) => {
660                let first = self.first;
661                let ran = self
662                    .windows
663                    .iter()
664                    .filter(|(id, open)| Some(**id) != first && open.shown && !open.leaving)
665                    .try_for_each(|(_, open)| smoke.other_window(&open.web_view));
666                if let Err(error) = ran {
667                    self.fail(error);
668                }
669            }
670            Ok(Step::Done) => self.quit(),
671            Err(error) => self.fail(error),
672        }
673    }
674
675    /// Keeps the first failure and closes every window.
676    fn fail(&mut self, error: Error) {
677        self.failure.get_or_insert(error);
678        self.quit();
679    }
680
681    fn quit(&mut self) {
682        self.quitting = true;
683        let ids: Vec<WindowId> = self.windows.keys().copied().collect();
684        if ids.is_empty() {
685            // Only a tray kept the application running, so no window's
686            // `Left` will end the event loop.
687            let _ = self.proxy.send_event(Event::Left(None));
688        }
689        for id in ids {
690            self.leave(id);
691        }
692    }
693
694    /// Shows `tray`, in place of the tray shown before.
695    fn tray(&mut self, tray: &crate::Tray) -> Result<(), Error> {
696        let icon = crate::tray::show(tray)?;
697        self.items = tray
698            .items
699            .iter()
700            .map(|item| (item.id.clone(), item.clicked.clone()))
701            .collect();
702        self.tray = Some(icon);
703        Ok(())
704    }
705
706    /// Registers `shortcut` for the rest of the run, or listens to it again
707    /// when it is registered already.
708    fn shortcut(&mut self, shortcut: crate::Shortcut) -> Result<crate::Presses, Error> {
709        let hotkey = shortcut.hotkey();
710        if let Some(presses) = self.shortcuts.get(&hotkey.id()) {
711            return Ok(crate::Presses::new(presses.subscribe()));
712        }
713        let hotkeys = match &mut self.hotkeys {
714            Some(hotkeys) => hotkeys,
715            empty => {
716                empty.insert(global_hotkey::GlobalHotKeyManager::new().map_err(Error::shortcut)?)
717            }
718        };
719        hotkeys.register(hotkey).map_err(Error::shortcut)?;
720        let presses = crate::shortcut::channel();
721        let heard = presses.subscribe();
722        self.shortcuts.insert(hotkey.id(), presses);
723        Ok(crate::Presses::new(heard))
724    }
725
726    /// Answers the item `id` of the menu bar or of the tray's menu.
727    fn chosen(&mut self, id: &tray_icon::menu::MenuId) {
728        if id.0 == crate::tray::QUIT || is_menu_quit(id) {
729            self.quit();
730        } else if let Some(clicked) = self.items.get(id).or_else(|| self.menu_items.get(id)) {
731            let _ = clicked.send(());
732        }
733    }
734
735    /// Puts `menus` in the menu bar, in place of the menus put there before.
736    fn menus(&mut self, menus: &[crate::Menu]) {
737        self.menu_items = menus
738            .iter()
739            .flat_map(crate::Menu::items)
740            .map(|item| (item.id.clone(), item.clicked.clone()))
741            .collect();
742        #[cfg(any(target_os = "macos", target_os = "linux"))]
743        match crate::menu::bar(menus) {
744            Ok(bar) => {
745                #[cfg(target_os = "linux")]
746                for open in self.windows.values() {
747                    crate::menu::detach(&self.bar, &open.window);
748                    crate::menu::attach(&bar, &open.window);
749                }
750                self.bar = bar;
751            }
752            Err(error) => tracing::error!(%error, "the menu bar was not changed"),
753        }
754    }
755
756    /// Hides the window `id` and sends its page to `about:blank`, which ends
757    /// the page's streams from the web view's side, so the server has no
758    /// open stream to wait for when it is asked to stop. The window goes on
759    /// [`Event::Left`], after [`LEAVE`].
760    fn leave(&mut self, id: WindowId) {
761        let Some(open) = self.windows.get_mut(&id) else {
762            return;
763        };
764        if open.leaving {
765            return;
766        }
767        open.leaving = true;
768        open.window.set_visible(false);
769        if let Err(error) = open.web_view.load_url("about:blank") {
770            tracing::error!(%error, "a closing window could not leave its page");
771        }
772        let left = self.proxy.clone();
773        self.runtime.spawn(async move {
774            tokio::time::sleep(LEAVE).await;
775            let _ = left.send_event(Event::Left(Some(id)));
776        });
777    }
778}
779
780/// Installs the package an update left for the end of the run. The
781/// installer replaces this program and, on Windows, ends the process, so it
782/// starts only after the server has stopped.
783#[cfg(feature = "updater")]
784fn install_after_stop(install: Option<crate::Downloaded>) -> Result<(), Error> {
785    install.map_or(Ok(()), crate::Downloaded::install_now)
786}
787
788/// Whether `id` is the Quit item of the macOS menu bar.
789#[cfg(target_os = "macos")]
790fn is_menu_quit(id: &tray_icon::menu::MenuId) -> bool {
791    id.0 == crate::menu::QUIT
792}
793
794/// Whether `id` is the Quit item of the macOS menu bar, which this system has none of.
795#[cfg(not(target_os = "macos"))]
796fn is_menu_quit(_id: &tray_icon::menu::MenuId) -> bool {
797    false
798}
799
800/// Sends the event loop each click on a menu's item and each press of a
801/// global shortcut, which their crates report from a handler of their own.
802fn forward_system_events(proxy: &EventLoopProxy<Event>) {
803    let chosen = proxy.clone();
804    tray_icon::menu::MenuEvent::set_event_handler(Some(
805        move |event: tray_icon::menu::MenuEvent| {
806            let _ = chosen.send_event(Event::Menu(event.id));
807        },
808    ));
809    let pressed = proxy.clone();
810    global_hotkey::GlobalHotKeyEvent::set_event_handler(Some(
811        move |event: global_hotkey::GlobalHotKeyEvent| {
812            let _ = pressed.send_event(Event::Pressed(event.id(), event.state().into()));
813        },
814    ));
815}
816
817/// Brings a window forward each time a second copy hands its command line over.
818async fn raise_on_launch(
819    mut launches: tokio::sync::broadcast::Receiver<handoff::Launch>,
820    proxy: EventLoopProxy<Event>,
821) {
822    use tokio::sync::broadcast::error::RecvError;
823    loop {
824        match launches.recv().await {
825            Ok(_) | Err(RecvError::Lagged(_)) => {
826                if proxy.send_event(Event::Raise).is_err() {
827                    return;
828                }
829            }
830            Err(RecvError::Closed) => return,
831        }
832    }
833}
834
835/// Builds the router, tells the event loop that the server is ready, and
836/// serves until `stopped` resolves.
837async fn serve<F>(
838    listener: TcpListener,
839    guard: Arc<Guard>,
840    setup: F,
841    proxy: EventLoopProxy<Event>,
842    stopped: oneshot::Receiver<()>,
843) where
844    F: Future<Output: IntoRouter>,
845{
846    let router = match setup.await.into_router() {
847        Ok(router) => router,
848        Err(error) => {
849            let _ = proxy.send_event(Event::Failed(Error::setup(error)));
850            return;
851        }
852    };
853    #[cfg(target_os = "linux")]
854    let router = crate::framing::wrap(router);
855    let app = guard::wrap(router, guard);
856    let served = axum::serve(listener, app)
857        .with_graceful_shutdown(async {
858            let _ = stopped.await;
859        })
860        .await;
861    if let Err(error) = served {
862        let _ = proxy.send_event(Event::Failed(error.into()));
863    }
864}
865
866async fn quit_on_ctrl_c(proxy: EventLoopProxy<Event>) {
867    if tokio::signal::ctrl_c().await.is_ok() {
868        let _ = proxy.send_event(Event::Quit);
869    }
870}