Skip to main content

hypersig_desktop/
app.rs

1//! The application: its identifier, its first window, and the router it serves.
2
3use std::env;
4use std::error::Error as StdError;
5use std::path::PathBuf;
6
7use axum::Router;
8
9use crate::error::Error;
10
11/// A desktop application, named by a reverse domain name.
12///
13/// The identifier decides where [`App::data_dir`] is, and so where the
14/// application keeps its port and its lock. On Windows and Linux the web
15/// views keep their cookies and `localStorage` there too; on macOS,
16/// `WKWebView` keeps them in `~/Library/WebKit`.
17///
18/// `U` is `()`, or [`Updates`](crate::Updates) once
19/// [`App::updates`] has named where new versions are found, and then
20/// [`App::run`] hands the setup an [`Updater`](crate::Updater) too.
21#[derive(Debug, Clone, Copy)]
22pub struct App<U = ()> {
23    pub(crate) id: &'static str,
24    pub(crate) size: (u32, u32),
25    pub(crate) min_size: Option<(u32, u32)>,
26    pub(crate) resizable: bool,
27    pub(crate) frame: crate::Frame,
28    pub(crate) devices: crate::device::Devices,
29    #[cfg_attr(
30        not(feature = "updater"),
31        expect(dead_code, reason = "only the `run` of `App<Updates>` reads it")
32    )]
33    pub(crate) updates: U,
34}
35
36impl App {
37    /// An application named by `id`, such as `dev.example.notes`.
38    ///
39    /// # Panics
40    ///
41    /// Panics unless `id` is two or more parts joined by dots, each of ASCII
42    /// letters, digits, and hyphens. In a `const`, that is a compile error.
43    #[must_use]
44    pub const fn new(id: &'static str) -> Self {
45        assert!(
46            is_identifier(id),
47            "an application identifier is a reverse domain name such as `dev.example.notes`: two or more parts joined by dots, each of ASCII letters, digits, and hyphens"
48        );
49        Self {
50            id,
51            size: (1024, 768),
52            min_size: None,
53            resizable: true,
54            frame: crate::Frame::System,
55            devices: crate::device::Devices::NONE,
56            updates: (),
57        }
58    }
59
60    /// Finds the application's new versions where `updates` says, with the
61    /// [`Updater`](crate::Updater) [`App::run`] hands the setup.
62    #[cfg(feature = "updater")]
63    #[must_use]
64    pub const fn updates(self, updates: crate::Updates) -> App<crate::Updates> {
65        App {
66            id: self.id,
67            size: self.size,
68            min_size: self.min_size,
69            resizable: self.resizable,
70            frame: self.frame,
71            devices: self.devices,
72            updates,
73        }
74    }
75}
76
77impl<U> App<U> {
78    /// Opens the window `width` by `height` logical pixels large.
79    ///
80    /// # Panics
81    ///
82    /// Panics when the size is narrower or shorter than
83    /// [`min_size`](Self::min_size). In a `const`, that is a compile error.
84    ///
85    /// ```compile_fail,E0080
86    /// use hypersig_desktop::App;
87    ///
88    /// const APP: App = App::new("dev.example.notes").min_size(800, 600).size(640, 480);
89    /// # let _ = APP;
90    /// ```
91    #[must_use]
92    pub const fn size(mut self, width: u32, height: u32) -> Self {
93        self.size = (width, height);
94        self.check_sizes();
95        self
96    }
97
98    /// Keeps the window at least `width` by `height` logical pixels large.
99    ///
100    /// # Panics
101    ///
102    /// Panics when [`size`](Self::size) is narrower or shorter than this. In
103    /// a `const`, that is a compile error.
104    #[must_use]
105    pub const fn min_size(mut self, width: u32, height: u32) -> Self {
106        self.min_size = Some((width, height));
107        self.check_sizes();
108        self
109    }
110
111    /// Checks that the window opens no smaller than it may become.
112    const fn check_sizes(&self) {
113        if let Some((width, height)) = self.min_size {
114            assert!(
115                self.size.0 >= width && self.size.1 >= height,
116                "the window's `size` is at least its `min_size` in both width and height"
117            );
118        }
119    }
120
121    /// Whether the person can resize the window, which they can by default.
122    #[must_use]
123    pub const fn resizable(mut self, resizable: bool) -> Self {
124        self.resizable = resizable;
125        self
126    }
127
128    /// Draws `frame` around each window, which is the system's by default.
129    ///
130    /// With [`Frame::None`](crate::Frame::None), the page draws the title
131    /// bar: [`MovesWindow::moves_window`](crate::MovesWindow::moves_window)
132    /// marks the part the person drags the window by, and
133    /// [`Window::close`](crate::Window::close) and
134    /// [`Window::place`](crate::Window::place) answer its buttons. On macOS
135    /// the window then has no close, minimize, and zoom buttons of its own,
136    /// and on Linux no shadow where the window manager draws it with the
137    /// border.
138    #[must_use]
139    pub const fn frame(mut self, frame: crate::Frame) -> Self {
140        self.frame = frame;
141        self
142    }
143
144    /// Lets the pages use `device` through `getUserMedia`.
145    ///
146    /// The web view grants a page only the devices named here, without
147    /// asking the person, and refuses the others. The system still asks the
148    /// person once whether the application may use the device. On macOS, the
149    /// web view offers no `navigator.mediaDevices` unless the bundle's
150    /// `Info.plist` has `NSMicrophoneUsageDescription` for the microphone and
151    /// `NSCameraUsageDescription` for the camera, which a run outside a
152    /// bundle lacks.
153    ///
154    /// `WebView2`, on Windows, keeps a grant in the web view's data, so a
155    /// later version that no longer names the device is still granted it
156    /// until that data is removed.
157    #[must_use]
158    pub const fn allow(mut self, device: crate::Device) -> Self {
159        self.devices = self.devices.with(device);
160        self
161    }
162
163    /// The directory where this application keeps its files.
164    ///
165    /// It is `~/Library/Application Support/<id>` on macOS,
166    /// `%LOCALAPPDATA%\<id>` on Windows, and `$XDG_DATA_HOME/<id>` or
167    /// `~/.local/share/<id>` elsewhere. [`App::run`] creates it before it
168    /// polls the future that builds the router, so that future can open a
169    /// file inside it.
170    ///
171    /// # Errors
172    ///
173    /// Fails with [`ErrorKind::NoDataDir`](crate::ErrorKind::NoDataDir) when
174    /// the environment variable the directory is found from is unset or not
175    /// an absolute path.
176    pub fn data_dir(&self) -> Result<PathBuf, Error> {
177        base_dir()
178            .map(|base| base.join(self.id))
179            .ok_or_else(Error::no_data_dir)
180    }
181}
182
183/// What the future given to [`App::run`] returns: a router, or why there is none.
184pub trait IntoRouter {
185    /// The router to serve, or why there is none.
186    ///
187    /// # Errors
188    ///
189    /// Fails with the error the application's setup returned.
190    fn into_router(self) -> Result<Router, Box<dyn StdError + Send + Sync>>;
191}
192
193impl IntoRouter for Router {
194    fn into_router(self) -> Result<Router, Box<dyn StdError + Send + Sync>> {
195        Ok(self)
196    }
197}
198
199impl<E: Into<Box<dyn StdError + Send + Sync>>> IntoRouter for Result<Router, E> {
200    fn into_router(self) -> Result<Router, Box<dyn StdError + Send + Sync>> {
201        self.map_err(Into::into)
202    }
203}
204
205/// Whether `id` is two or more non-empty parts joined by dots, each of ASCII
206/// letters, digits, and hyphens, which every file system accepts as a
207/// directory name.
208const fn is_identifier(id: &str) -> bool {
209    let bytes = id.as_bytes();
210    let mut parts = 1;
211    let mut part_len = 0;
212    let mut i = 0;
213    while i < bytes.len() {
214        let byte = bytes[i];
215        if byte == b'.' {
216            if part_len == 0 {
217                return false;
218            }
219            parts += 1;
220            part_len = 0;
221        } else if byte.is_ascii_alphanumeric() || byte == b'-' {
222            part_len += 1;
223        } else {
224            return false;
225        }
226        i += 1;
227    }
228    parts >= 2 && part_len > 0
229}
230
231/// The directory each application's own directory is made in.
232#[cfg(target_os = "macos")]
233fn base_dir() -> Option<PathBuf> {
234    absolute_var("HOME").map(|home| home.join("Library").join("Application Support"))
235}
236
237/// The directory each application's own directory is made in.
238#[cfg(windows)]
239fn base_dir() -> Option<PathBuf> {
240    absolute_var("LOCALAPPDATA")
241}
242
243/// The directory each application's own directory is made in.
244#[cfg(not(any(target_os = "macos", windows)))]
245fn base_dir() -> Option<PathBuf> {
246    absolute_var("XDG_DATA_HOME")
247        .or_else(|| absolute_var("HOME").map(|home| home.join(".local").join("share")))
248}
249
250/// The value of the environment variable `name`, when it is an absolute path.
251fn absolute_var(name: &str) -> Option<PathBuf> {
252    env::var_os(name)
253        .map(PathBuf::from)
254        .filter(|path| path.is_absolute())
255}
256
257#[cfg(test)]
258mod tests {
259    use super::{App, is_identifier};
260
261    #[test]
262    fn a_reverse_domain_name_is_an_identifier() {
263        assert!(is_identifier("dev.example.notes"));
264        assert!(is_identifier("com.my-company.app2"));
265    }
266
267    #[test]
268    fn other_text_is_not() {
269        for id in [
270            "",
271            "notes",
272            ".notes",
273            "notes.",
274            "dev..notes",
275            "dev.ex ample",
276            "dev/notes",
277            "dev.γƒŽγƒΌγƒˆ",
278        ] {
279            assert!(!is_identifier(id), "{id}");
280        }
281    }
282
283    #[test]
284    fn a_size_at_least_the_minimum_is_kept() {
285        let app = App::new("dev.example.notes")
286            .min_size(400, 300)
287            .size(400, 500);
288        assert_eq!((app.size, app.min_size), ((400, 500), Some((400, 300))));
289    }
290
291    #[test]
292    #[should_panic(expected = "at least its `min_size`")]
293    fn a_minimum_wider_than_the_size_panics() {
294        let _ = App::new("dev.example.notes")
295            .size(640, 480)
296            .min_size(800, 300);
297    }
298}