Skip to main content

hypersig_desktop/
os.rs

1//! What the application's handlers ask of the operating system.
2
3use std::fmt;
4use std::path::PathBuf;
5#[cfg(feature = "testing")]
6use std::sync::{Arc, Mutex, PoisonError};
7
8use hypersig::{SafeUrl, Url};
9use tao::event_loop::EventLoopProxy;
10use tao::window::WindowId;
11use tokio::sync::{broadcast, oneshot};
12
13use crate::arrange::{Arrange, Layer, Placement};
14use crate::clipboard;
15use crate::error::Error;
16use crate::handoff::{Launch, Launches};
17use crate::menu::Menu;
18use crate::message::{Answer, Message};
19use crate::notification::{Notification, Notified};
20use crate::run::Event;
21use crate::shortcut::{Presses, Shortcut};
22#[cfg(feature = "testing")]
23use crate::testing::Fake;
24use crate::tray::Tray;
25
26/// The operating system's windows and services, for the application's handlers.
27///
28/// [`App::run`](crate::App::run) gives it to the setup closure, which puts it
29/// in the router's state, so a handler reaches it as `state.os`. A test gives
30/// the handlers `testing::FakeOs::os` instead, with the
31/// `testing` feature.
32#[derive(Clone)]
33pub struct Os {
34    inner: Inner,
35    launches: broadcast::Sender<Launch>,
36    /// The identifier [`App::new`](crate::App::new) named.
37    id: &'static str,
38}
39
40#[derive(Clone)]
41enum Inner {
42    System(EventLoopProxy<Event>),
43    #[cfg(feature = "testing")]
44    Fake(Arc<Mutex<Fake>>),
45}
46
47impl fmt::Debug for Os {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        f.debug_struct("Os").finish_non_exhaustive()
50    }
51}
52
53impl Os {
54    pub(crate) fn new(
55        proxy: EventLoopProxy<Event>,
56        launches: broadcast::Sender<Launch>,
57        id: &'static str,
58    ) -> Self {
59        Self {
60            inner: Inner::System(proxy),
61            launches,
62            id,
63        }
64    }
65
66    #[cfg(feature = "testing")]
67    pub(crate) fn fake(fake: Arc<Mutex<Fake>>) -> Self {
68        let launches = lock(&fake).launches.clone();
69        Self {
70            inner: Inner::Fake(fake),
71            launches,
72            id: "dev.hypersig.fake",
73        }
74    }
75
76    /// The launches of the application that start while it runs.
77    ///
78    /// A start of the application while this copy runs hands its command
79    /// line and working directory over and exits, and the copy that runs
80    /// brings a window forward. On macOS a file or a link the person opens
81    /// with the application, which the system hands the copy running
82    /// rather than starting another, arrives here too, with each file as
83    /// its path and each link as its text in [`Launch::args`]. Each
84    /// [`Launches`] gets the launches handed over after it was made, so a
85    /// setup that takes one before it returns the router misses none.
86    #[must_use]
87    pub fn launches(&self) -> Launches {
88        Launches::new(self.launches.subscribe())
89    }
90
91    /// Shows `notification` among the system's notifications.
92    ///
93    /// The returned [`Notified`] tells whether the person clicked it. On
94    /// macOS, the notification comes from the application installed with
95    /// the identifier [`App::new`](crate::App::new) names; a run outside
96    /// such a bundle shows it under another application's name.
97    ///
98    /// # Errors
99    ///
100    /// Fails with [`ErrorKind::Notification`](crate::ErrorKind::Notification)
101    /// when the system does not show it, as on Linux without a notification
102    /// server.
103    pub async fn notify(&self, notification: Notification) -> Result<Notified, Error> {
104        match &self.inner {
105            Inner::System(_) => {
106                tokio::task::spawn_blocking(move || crate::notification::show(&notification))
107                    .await
108                    .map_err(Error::notification)?
109            }
110            #[cfg(feature = "testing")]
111            Inner::Fake(fake) => {
112                let (clicked, heard) = oneshot::channel();
113                lock(fake).notifications.push((notification, Some(clicked)));
114                Ok(Notified { clicked: heard })
115            }
116        }
117    }
118
119    /// Registers `shortcut` for the rest of the run, so the application
120    /// hears it while another application has focus.
121    ///
122    /// Each call returns its own [`Presses`] of the presses and releases
123    /// after it, and a shortcut asked for again is not registered twice. On
124    /// Linux, the shortcut is grabbed from the X server, so a Wayland session
125    /// delivers it only while an X11 window has focus, and none at all
126    /// without Xwayland, where registering still returns `Ok`.
127    ///
128    /// # Errors
129    ///
130    /// Fails with [`ErrorKind::Shortcut`](crate::ErrorKind::Shortcut) when
131    /// the system does not register it, as when another application holds
132    /// it, and when the application is closing.
133    pub async fn shortcut(&self, shortcut: Shortcut) -> Result<Presses, Error> {
134        match &self.inner {
135            Inner::System(proxy) => {
136                let (answer, answered) = oneshot::channel();
137                Os::send(proxy, Event::Shortcut { shortcut, answer })?;
138                answered.await.map_err(|_closed| Error::closed())?
139            }
140            #[cfg(feature = "testing")]
141            Inner::Fake(fake) => Ok(Presses::new(
142                lock(fake)
143                    .shortcuts
144                    .entry(shortcut)
145                    .or_insert_with(crate::shortcut::channel)
146                    .subscribe(),
147            )),
148        }
149    }
150
151    /// Shows `tray` in the system tray, in place of the tray shown before.
152    ///
153    /// While a tray is shown, closing the last window leaves the
154    /// application running, and the tray's Quit item ends it.
155    ///
156    /// # Errors
157    ///
158    /// Fails with [`ErrorKind::Tray`](crate::ErrorKind::Tray) when the
159    /// tray's icon is not a PNG or the system has no tray, and when the
160    /// application is closing.
161    pub async fn tray(&self, tray: Tray) -> Result<(), Error> {
162        match &self.inner {
163            Inner::System(proxy) => {
164                let (answer, answered) = oneshot::channel();
165                Os::send(proxy, Event::Tray { tray, answer })?;
166                answered.await.map_err(|_closed| Error::closed())?
167            }
168            #[cfg(feature = "testing")]
169            Inner::Fake(fake) => {
170                lock(fake).tray = Some(tray);
171                Ok(())
172            }
173        }
174    }
175
176    /// Puts `menus` in the menu bar, in place of the menus put there before.
177    ///
178    /// On macOS they go between the Edit and Window menus of the
179    /// application's menu bar, and on Linux in a bar at the top of every
180    /// window, opened then or later. Windows shows no menu bar of
181    /// this crate's, since muda puts one in a window only through an
182    /// `unsafe` call, which this crate forbids; there the menus are
183    /// recorded and nothing is shown.
184    ///
185    /// # Errors
186    ///
187    /// Fails when the application is closing.
188    pub fn menus(&self, menus: impl IntoIterator<Item = Menu>) -> Result<(), Error> {
189        let menus = menus.into_iter().collect();
190        match &self.inner {
191            Inner::System(proxy) => Os::send(proxy, Event::Menus(menus)),
192            #[cfg(feature = "testing")]
193            Inner::Fake(fake) => {
194                lock(fake).menus = menus;
195                Ok(())
196            }
197        }
198    }
199
200    /// Shows `count` on the application's icon, or clears it at 0.
201    ///
202    /// macOS writes the number on the Dock icon. Linux sets it on the
203    /// launcher entry of `<program>.desktop`, the desktop file of the
204    /// packages cargo-packager builds, which Ubuntu's dock shows. Windows
205    /// puts a red dot on each window's taskbar button, since a button has
206    /// no room for a number.
207    ///
208    /// # Errors
209    ///
210    /// Fails when the application is closing.
211    pub fn badge(&self, count: u32) -> Result<(), Error> {
212        match &self.inner {
213            Inner::System(proxy) => Os::send(proxy, Event::Badge(count)),
214            #[cfg(feature = "testing")]
215            Inner::Fake(fake) => {
216                lock(fake).badge = count;
217                Ok(())
218            }
219        }
220    }
221
222    /// The application's windows.
223    #[must_use]
224    pub fn windows(&self) -> Windows<'_> {
225        Windows { os: self }
226    }
227
228    /// A file dialog, to be given a title and filters before it is shown.
229    pub fn dialog(&self) -> Dialog {
230        Dialog {
231            #[cfg(feature = "testing")]
232            os: self.clone(),
233            title: None,
234            filters: Vec::new(),
235            directory: None,
236            file_name: None,
237        }
238    }
239
240    /// Shows `message` in the system's message box, with an OK button,
241    /// and waits for the person to close it.
242    pub async fn tell(&self, message: Message) {
243        match &self.inner {
244            Inner::System(_) => {
245                message.system(rfd::MessageButtons::Ok).show().await;
246            }
247            #[cfg(feature = "testing")]
248            Inner::Fake(fake) => lock(fake).tell(message),
249        }
250    }
251
252    /// Shows `message` with OK and Cancel buttons, and returns whether the
253    /// person chose OK. Closing the box counts as Cancel.
254    pub async fn confirm(&self, message: Message) -> bool {
255        match &self.inner {
256            Inner::System(_) => {
257                let chosen = message.system(rfd::MessageButtons::OkCancel).show().await;
258                chosen == rfd::MessageDialogResult::Ok
259            }
260            #[cfg(feature = "testing")]
261            Inner::Fake(fake) => lock(fake).confirm(message),
262        }
263    }
264
265    /// Shows `message` with Yes, No, and Cancel buttons, and returns the
266    /// one the person chose. Closing the box counts as Cancel.
267    pub async fn ask(&self, message: Message) -> Answer {
268        match &self.inner {
269            Inner::System(_) => {
270                let chosen = message
271                    .system(rfd::MessageButtons::YesNoCancel)
272                    .show()
273                    .await;
274                Answer::from_system(&chosen)
275            }
276            #[cfg(feature = "testing")]
277            Inner::Fake(fake) => lock(fake).ask(message),
278        }
279    }
280
281    /// Whether the system starts the application when the person logs in.
282    #[must_use]
283    pub fn autostart(&self) -> Autostart<'_> {
284        Autostart { os: self }
285    }
286
287    /// The system clipboard.
288    #[must_use]
289    pub fn clipboard(&self) -> Clipboard<'_> {
290        Clipboard { os: self }
291    }
292
293    /// Opens `url` in the person's web browser, or their mail program for a
294    /// `mailto:` URL.
295    ///
296    /// # Errors
297    ///
298    /// Fails with [`ErrorKind::NotExternal`](crate::ErrorKind::NotExternal)
299    /// when `url` names no scheme, as `/notes` does, since the system would
300    /// open such a path as a file, and fails when the system cannot open it.
301    pub fn open_external(&self, url: &SafeUrl) -> Result<(), Error> {
302        if !is_external(url.as_str()) {
303            return Err(Error::not_external());
304        }
305        match &self.inner {
306            Inner::System(_) => open::that_detached(url.as_str()).map_err(Error::from),
307            #[cfg(feature = "testing")]
308            Inner::Fake(fake) => {
309                lock(fake).external.push(url.clone());
310                Ok(())
311            }
312        }
313    }
314
315    /// Sends `event` to the event loop.
316    fn send(proxy: &EventLoopProxy<Event>, event: Event) -> Result<(), Error> {
317        proxy.send_event(event).map_err(|_closed| Error::closed())
318    }
319}
320
321/// Whether `url` is one the system opens in another program: an absolute
322/// `http`, `https`, or `mailto` URL. A [`SafeUrl`] has one of these schemes
323/// or none.
324pub(crate) fn is_external(url: &str) -> bool {
325    ["http://", "https://", "mailto:"].iter().any(|scheme| {
326        url.get(..scheme.len())
327            .is_some_and(|start| start.eq_ignore_ascii_case(scheme))
328    })
329}
330
331#[cfg(feature = "testing")]
332fn lock(fake: &Mutex<Fake>) -> std::sync::MutexGuard<'_, Fake> {
333    fake.lock().unwrap_or_else(PoisonError::into_inner)
334}
335
336/// The application's windows, from [`Os::windows`].
337#[derive(Debug, Clone, Copy)]
338pub struct Windows<'a> {
339    os: &'a Os,
340}
341
342impl Windows<'_> {
343    /// Opens `page` in a new window, shown once the page has loaded.
344    ///
345    /// # Errors
346    ///
347    /// Fails when the window or its web view cannot be made, and when the
348    /// application is closing.
349    pub async fn open(&self, page: &Url) -> Result<Window, Error> {
350        let key = match &self.os.inner {
351            Inner::System(proxy) => {
352                let (answer, answered) = oneshot::channel();
353                Os::send(
354                    proxy,
355                    Event::Open {
356                        url: page.as_str().to_owned(),
357                        answer: Some(answer),
358                    },
359                )?;
360                Key::System(answered.await.map_err(|_closed| Error::closed())??)
361            }
362            #[cfg(feature = "testing")]
363            Inner::Fake(fake) => {
364                let mut fake = lock(fake);
365                fake.windows.push(Some(page.clone()));
366                let index = fake.windows.len() - 1;
367                // A system window comes to the front when it is shown.
368                fake.focused = Some(index);
369                Key::Fake(index)
370            }
371        };
372        Ok(Window {
373            key,
374            os: self.os.clone(),
375        })
376    }
377
378    /// The window that had the keyboard last, while it is open.
379    ///
380    /// A window has the keyboard while the person types or clicks in it,
381    /// so a handler of a click in a page finds that page's window here,
382    /// and it stays the one found while another application has focus.
383    /// The first window counts as soon as it is shown.
384    ///
385    /// # Errors
386    ///
387    /// Fails when the application is closing.
388    pub async fn focused(&self) -> Result<Option<Window>, Error> {
389        let key = match &self.os.inner {
390            Inner::System(proxy) => {
391                let (answer, answered) = oneshot::channel();
392                Os::send(proxy, Event::Focused(answer))?;
393                answered
394                    .await
395                    .map_err(|_closed| Error::closed())?
396                    .map(Key::System)
397            }
398            #[cfg(feature = "testing")]
399            Inner::Fake(fake) => {
400                let fake = lock(fake);
401                fake.focused
402                    .filter(|&index| fake.windows.get(index).is_some_and(Option::is_some))
403                    .map(Key::Fake)
404            }
405        };
406        Ok(key.map(|key| Window {
407            key,
408            os: self.os.clone(),
409        }))
410    }
411}
412
413/// A window [`Windows::open`] opened.
414#[derive(Debug, Clone)]
415pub struct Window {
416    key: Key,
417    os: Os,
418}
419
420#[derive(Debug, Clone, Copy, PartialEq, Eq)]
421enum Key {
422    System(WindowId),
423    #[cfg(feature = "testing")]
424    Fake(usize),
425}
426
427impl Window {
428    /// Closes the window, as its close button does.
429    ///
430    /// On a window that is already closed, it does nothing and returns
431    /// `Ok(())`.
432    ///
433    /// # Errors
434    ///
435    /// Fails when the application is closing.
436    pub fn close(&self) -> Result<(), Error> {
437        match (&self.os.inner, self.key) {
438            (Inner::System(proxy), Key::System(id)) => Os::send(proxy, Event::Close(id)),
439            #[cfg(feature = "testing")]
440            (Inner::Fake(fake), Key::Fake(index)) => {
441                if let Some(window) = lock(fake).windows.get_mut(index) {
442                    *window = None;
443                }
444                Ok(())
445            }
446            #[cfg(feature = "testing")]
447            _ => Ok(()),
448        }
449    }
450
451    /// Brings the window to the front and gives it the keyboard.
452    ///
453    /// On a window that is already closed, it does nothing and returns
454    /// `Ok(())`.
455    ///
456    /// # Errors
457    ///
458    /// Fails when the application is closing.
459    pub fn focus(&self) -> Result<(), Error> {
460        match (&self.os.inner, self.key) {
461            (Inner::System(proxy), Key::System(id)) => Os::send(proxy, Event::Focus(id)),
462            #[cfg(feature = "testing")]
463            (Inner::Fake(fake), Key::Fake(index)) => {
464                let mut fake = lock(fake);
465                if fake.windows.get(index).is_some_and(Option::is_some) {
466                    fake.focused = Some(index);
467                }
468                Ok(())
469            }
470            #[cfg(feature = "testing")]
471            _ => Ok(()),
472        }
473    }
474}
475
476impl Window {
477    /// Maximizes, minimizes, or makes the window fullscreen, or returns it
478    /// to [`Placement::Normal`].
479    ///
480    /// On a window that is already closed, it does nothing and returns
481    /// `Ok(())`, as each method below does.
482    ///
483    /// # Errors
484    ///
485    /// Fails when the application is closing, as each method below does.
486    pub fn place(&self, placement: Placement) -> Result<(), Error> {
487        self.arrange(Arrange::Place(placement))
488    }
489
490    /// Keeps the window above the windows of every other application, or
491    /// returns it among them.
492    ///
493    /// # Errors
494    ///
495    /// Fails when the application is closing.
496    pub fn layer(&self, layer: Layer) -> Result<(), Error> {
497        self.arrange(Arrange::Layer(layer))
498    }
499
500    /// Moves the window's top-left corner to `x`, `y` logical pixels from
501    /// the top left of the primary screen.
502    ///
503    /// Wayland lets no application place its windows, so on Linux under
504    /// Wayland the window stays where the compositor put it.
505    ///
506    /// # Errors
507    ///
508    /// Fails when the application is closing.
509    pub fn move_to(&self, x: i32, y: i32) -> Result<(), Error> {
510        self.arrange(Arrange::Move(x, y))
511    }
512
513    /// Makes the window's page area `width` by `height` logical pixels,
514    /// within [`App::min_size`](crate::App::min_size).
515    ///
516    /// # Errors
517    ///
518    /// Fails when the application is closing.
519    pub fn resize(&self, width: u32, height: u32) -> Result<(), Error> {
520        self.arrange(Arrange::Resize(width, height))
521    }
522
523    fn arrange(&self, change: Arrange) -> Result<(), Error> {
524        match (&self.os.inner, self.key) {
525            (Inner::System(proxy), Key::System(id)) => Os::send(proxy, Event::Arrange(id, change)),
526            #[cfg(feature = "testing")]
527            (Inner::Fake(fake), Key::Fake(index)) => {
528                lock(fake).arrange(index, change);
529                Ok(())
530            }
531            #[cfg(feature = "testing")]
532            _ => Ok(()),
533        }
534    }
535
536    /// Which window of a fake system this is, for `FakeOs`.
537    #[cfg(feature = "testing")]
538    pub(crate) fn fake_index(&self) -> Option<usize> {
539        match self.key {
540            Key::Fake(index) => Some(index),
541            Key::System(_) => None,
542        }
543    }
544}
545
546impl PartialEq for Window {
547    fn eq(&self, other: &Self) -> bool {
548        self.key == other.key
549    }
550}
551
552impl Eq for Window {}
553
554/// A file dialog, from [`Os::dialog`], shown by one of its async methods.
555#[derive(Debug, Clone)]
556#[must_use = "a dialog shows only when one of its async methods is awaited"]
557pub struct Dialog {
558    /// Only a fake system answers in place of the system's own dialog.
559    #[cfg(feature = "testing")]
560    os: Os,
561    title: Option<String>,
562    filters: Vec<(String, Vec<String>)>,
563    directory: Option<PathBuf>,
564    file_name: Option<String>,
565}
566
567impl Dialog {
568    /// Titles the dialog's window.
569    pub fn title(mut self, title: impl Into<String>) -> Self {
570        self.title = Some(title.into());
571        self
572    }
573
574    /// Offers the files whose extension is one of `extensions`, as `name`.
575    pub fn filter(mut self, name: impl Into<String>, extensions: &[&str]) -> Self {
576        self.filters.push((
577            name.into(),
578            extensions
579                .iter()
580                .map(|&extension| extension.to_owned())
581                .collect(),
582        ));
583        self
584    }
585
586    /// Opens the dialog in `directory`.
587    pub fn directory(mut self, directory: impl Into<PathBuf>) -> Self {
588        self.directory = Some(directory.into());
589        self
590    }
591
592    /// Fills in `name` as the file to save.
593    pub fn file_name(mut self, name: impl Into<String>) -> Self {
594        self.file_name = Some(name.into());
595        self
596    }
597
598    /// The file the person chose, or `None` when they cancelled.
599    pub async fn open_file(self) -> Option<PathBuf> {
600        #[cfg(feature = "testing")]
601        if let Some(paths) = self.fake_answer(crate::testing::DialogKind::OpenFile) {
602            return paths?.into_iter().next();
603        }
604        self.system()
605            .pick_file()
606            .await
607            .map(|file| file.path().to_owned())
608    }
609
610    /// The files the person chose, or `None` when they cancelled.
611    pub async fn open_files(self) -> Option<Vec<PathBuf>> {
612        #[cfg(feature = "testing")]
613        if let Some(paths) = self.fake_answer(crate::testing::DialogKind::OpenFiles) {
614            return paths;
615        }
616        self.system()
617            .pick_files()
618            .await
619            .map(|files| files.iter().map(|file| file.path().to_owned()).collect())
620    }
621
622    /// The folder the person chose, or `None` when they cancelled.
623    pub async fn pick_folder(self) -> Option<PathBuf> {
624        #[cfg(feature = "testing")]
625        if let Some(paths) = self.fake_answer(crate::testing::DialogKind::PickFolder) {
626            return paths?.into_iter().next();
627        }
628        self.system()
629            .pick_folder()
630            .await
631            .map(|folder| folder.path().to_owned())
632    }
633
634    /// Where the person chose to save, or `None` when they cancelled. The
635    /// file is not written.
636    pub async fn save_file(self) -> Option<PathBuf> {
637        #[cfg(feature = "testing")]
638        if let Some(paths) = self.fake_answer(crate::testing::DialogKind::SaveFile) {
639            return paths?.into_iter().next();
640        }
641        self.system()
642            .save_file()
643            .await
644            .map(|file| file.path().to_owned())
645    }
646
647    /// The answer a test gave a fake system for this dialog: the paths, or
648    /// `None` for a cancelled dialog. The outer `None` means the system's
649    /// own dialog answers.
650    #[cfg(feature = "testing")]
651    #[expect(
652        clippy::option_option,
653        reason = "the outer layer is who answers and the inner one is the answer"
654    )]
655    fn fake_answer(&self, kind: crate::testing::DialogKind) -> Option<Option<Vec<PathBuf>>> {
656        match &self.os.inner {
657            Inner::System(_) => None,
658            Inner::Fake(fake) => Some(lock(fake).answer_dialog(crate::testing::ShownDialog {
659                kind,
660                title: self.title.clone(),
661                filters: self.filters.clone(),
662                directory: self.directory.clone(),
663                file_name: self.file_name.clone(),
664            })),
665        }
666    }
667
668    fn system(self) -> rfd::AsyncFileDialog {
669        let mut dialog = rfd::AsyncFileDialog::new();
670        if let Some(title) = self.title {
671            dialog = dialog.set_title(title);
672        }
673        for (name, extensions) in self.filters {
674            dialog = dialog.add_filter(name, &extensions);
675        }
676        if let Some(directory) = self.directory {
677            dialog = dialog.set_directory(directory);
678        }
679        if let Some(name) = self.file_name {
680            dialog = dialog.set_file_name(name);
681        }
682        dialog
683    }
684}
685
686/// Whether the application starts at login, from [`Os::autostart`].
687///
688/// The entry is written under the identifier [`App::new`](crate::App::new)
689/// names and starts the program running now: on Linux the `AppImage` the
690/// person installed, and elsewhere the running binary, so a run from
691/// `cargo run` writes an entry for the binary under `target`.
692#[derive(Debug, Clone, Copy)]
693pub struct Autostart<'a> {
694    os: &'a Os,
695}
696
697impl Autostart<'_> {
698    /// Has the system start the application each time the person logs in.
699    ///
700    /// # Errors
701    ///
702    /// Fails with [`ErrorKind::Autostart`](crate::ErrorKind::Autostart)
703    /// when the entry cannot be written.
704    pub async fn enable(&self) -> Result<(), Error> {
705        match &self.os.inner {
706            Inner::System(_) => {
707                crate::autostart::with_entry(self.os.id, auto_launch::AutoLaunch::enable).await
708            }
709            #[cfg(feature = "testing")]
710            Inner::Fake(fake) => {
711                lock(fake).autostart = true;
712                Ok(())
713            }
714        }
715    }
716
717    /// Stops the system from starting the application at login.
718    ///
719    /// # Errors
720    ///
721    /// Fails with [`ErrorKind::Autostart`](crate::ErrorKind::Autostart)
722    /// when the entry cannot be removed.
723    pub async fn disable(&self) -> Result<(), Error> {
724        match &self.os.inner {
725            Inner::System(_) => {
726                crate::autostart::with_entry(self.os.id, auto_launch::AutoLaunch::disable).await
727            }
728            #[cfg(feature = "testing")]
729            Inner::Fake(fake) => {
730                lock(fake).autostart = false;
731                Ok(())
732            }
733        }
734    }
735
736    /// Whether the system starts the application at login.
737    ///
738    /// # Errors
739    ///
740    /// Fails with [`ErrorKind::Autostart`](crate::ErrorKind::Autostart)
741    /// when the entry cannot be read.
742    pub async fn is_enabled(&self) -> Result<bool, Error> {
743        match &self.os.inner {
744            Inner::System(_) => {
745                crate::autostart::with_entry(self.os.id, auto_launch::AutoLaunch::is_enabled).await
746            }
747            #[cfg(feature = "testing")]
748            Inner::Fake(fake) => Ok(lock(fake).autostart),
749        }
750    }
751}
752
753/// The system clipboard, from [`Os::clipboard`].
754#[derive(Debug, Clone, Copy)]
755pub struct Clipboard<'a> {
756    os: &'a Os,
757}
758
759impl Clipboard<'_> {
760    /// The text on the clipboard, or `None` when it holds no text.
761    ///
762    /// # Errors
763    ///
764    /// Fails when the system clipboard cannot be read.
765    pub async fn read_text(&self) -> Result<Option<String>, Error> {
766        match &self.os.inner {
767            Inner::System(_) => clipboard::read().await,
768            #[cfg(feature = "testing")]
769            Inner::Fake(fake) => Ok(lock(fake).clipboard.clone()),
770        }
771    }
772
773    /// Puts `text` on the clipboard.
774    ///
775    /// # Errors
776    ///
777    /// Fails when the system clipboard cannot be written.
778    pub async fn write_text(&self, text: impl Into<String>) -> Result<(), Error> {
779        match &self.os.inner {
780            Inner::System(_) => clipboard::write(text.into()).await,
781            #[cfg(feature = "testing")]
782            Inner::Fake(fake) => {
783                lock(fake).clipboard = Some(text.into());
784                Ok(())
785            }
786        }
787    }
788}
789
790#[cfg(test)]
791mod tests {
792    use super::is_external;
793
794    #[test]
795    fn only_an_absolute_url_is_external() {
796        for url in [
797            "https://example.com",
798            "HTTP://example.com/a",
799            "mailto:a@example.com",
800        ] {
801            assert!(is_external(url), "{url}");
802        }
803        for url in ["/notes", "notes", "//example.com", "file:///etc", ""] {
804            assert!(!is_external(url), "{url}");
805        }
806    }
807}