ashlar-native 0.2.0

Native OS features behind one API: dialogs, menus, clipboard, power, notifications, secrets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Open, save and folder pickers (rfd).
//!
//! Describe the dialog with [`FileDialog`], then call a blocking picker ([`FileDialog::open_file`],
//! …) or its async twin ([`FileDialog::open_file_async`], …). A dismissed dialog is
//! [`NativeError::Cancelled`].
//!
//! Threads: on macOS the blocking pickers must run on the main thread (or on another thread while
//! the main thread is running its event loop); the async pickers run anywhere and are the right
//! choice inside an event loop. On the web only [`FileDialog::open_bytes_async`] exists (browsers
//! give the page a file's contents, never its path); everything else is `Unsupported`.
//!
//! Parent a dialog to a window with [`FileDialog::parent`]: it then opens over that window (a
//! sheet on macOS) and keeps it from taking input until it closes.
//!
//! [`message`] shows a modal message box, for what must be said before (or without) a window:
//! a start-up failure, command-line output in an app that has no console.

use std::path::{Path, PathBuf};

use raw_window_handle::{HasDisplayHandle, HasWindowHandle};

use crate::{NativeError, Result};

/// Longest title or file name passed to the OS.
const MAX_TEXT: usize = 512;
/// At most this many filters.
const MAX_FILTERS: usize = 64;

/// One filter row: a name and the extensions it accepts (without dots: `["png", "jpg"]`).
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub struct Filter {
    pub name: String,
    pub extensions: Vec<String>,
}

/// What a dialog shows. Every field is optional.
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub struct FileDialog {
    pub title: Option<String>,
    /// The folder the dialog opens in.
    pub directory: Option<PathBuf>,
    /// The suggested name (save dialogs).
    pub file_name: Option<String>,
    pub filters: Vec<Filter>,
}

fn clip(s: &str) -> String {
    s.chars().filter(|c| !c.is_control()).take(MAX_TEXT).collect()
}

/// An extension as rfd wants it: no leading dot, no separators, short.
fn clean_extension(e: &str) -> Option<String> {
    let e = e.trim().trim_start_matches("*.").trim_start_matches('.');
    let ok = !e.is_empty() && e.len() <= 32 && e.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-' || c == '*');
    ok.then(|| e.to_string())
}

impl FileDialog {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    pub fn directory(mut self, dir: impl AsRef<Path>) -> Self {
        self.directory = Some(dir.as_ref().to_path_buf());
        self
    }

    pub fn file_name(mut self, name: impl Into<String>) -> Self {
        self.file_name = Some(name.into());
        self
    }

    /// Add a filter row (`filter("Images", &["png", "jpg"])`). Extensions may be written `png`,
    /// `.png` or `*.png`; malformed ones are dropped, and a row left without extensions is skipped.
    pub fn filter(mut self, name: impl Into<String>, extensions: &[&str]) -> Self {
        self.filters.push(Filter { name: name.into(), extensions: extensions.iter().map(|e| e.to_string()).collect() });
        self
    }

    /// The filters as they are given to the OS: cleaned, bounded, empty rows dropped.
    pub fn clean_filters(&self) -> Vec<(String, Vec<String>)> {
        self.filters
            .iter()
            .take(MAX_FILTERS)
            .filter_map(|f| {
                let exts: Vec<String> = f.extensions.iter().filter_map(|e| clean_extension(e)).take(64).collect();
                (!exts.is_empty()).then(|| (clip(&f.name), exts))
            })
            .collect()
    }

    #[cfg(not(target_arch = "wasm32"))]
    /// The folder to open in, only when it exists (a missing folder makes some dialogs fail).
    fn existing_directory(&self) -> Option<&Path> {
        self.directory.as_deref().filter(|d| d.is_dir())
    }
}

/// Longest message text passed to the OS.
#[cfg(not(target_arch = "wasm32"))]
const MAX_MESSAGE: usize = 8192;

/// How serious a [`message`] is; the OS picks the icon.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MessageLevel {
    #[default]
    Info,
    Warning,
    Error,
}

/// Message text as it is given to the OS: line breaks and tabs kept, other control characters
/// dropped, at most [`MAX_MESSAGE`] characters.
#[cfg(not(target_arch = "wasm32"))]
fn clip_message(s: &str) -> String {
    s.chars().filter(|c| !c.is_control() || *c == '\n' || *c == '\t').take(MAX_MESSAGE).collect()
}

/// Show a modal message box with one OK button and wait until it is dismissed. Main thread on
/// macOS. `Unsupported` on the web.
pub fn message(level: MessageLevel, title: &str, text: &str) -> Result<()> {
    #[cfg(not(target_arch = "wasm32"))]
    {
        let level = match level {
            MessageLevel::Info => rfd::MessageLevel::Info,
            MessageLevel::Warning => rfd::MessageLevel::Warning,
            MessageLevel::Error => rfd::MessageLevel::Error,
        };
        let (title, text) = (clip(title), clip_message(text));
        crate::guarded("the message box", || {
            crate::modal::around(|| {
                rfd::MessageDialog::new().set_level(level).set_title(title).set_description(text).set_buttons(rfd::MessageButtons::Ok).show()
            });
            Ok(())
        })
    }
    #[cfg(target_arch = "wasm32")]
    {
        let _ = (level, title, text);
        Err(NativeError::Unsupported)
    }
}

/// A [`FileDialog`] shown over a window ([`FileDialog::parent`]). Its pickers block like the
/// unparented ones, so call them between frames, not inside one.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub struct Parented<'a, W: ?Sized> {
    dialog: &'a FileDialog,
    parent: &'a W,
}

impl FileDialog {
    /// Show the dialog over `window` (any window with a raw handle, such as `eframe::Frame`).
    pub fn parent<'a, W: HasWindowHandle + HasDisplayHandle + ?Sized>(&'a self, window: &'a W) -> Parented<'a, W> {
        Parented { dialog: self, parent: window }
    }
}

#[cfg(not(target_arch = "wasm32"))]
mod native {
    use super::*;

    fn sync(d: &FileDialog) -> rfd::FileDialog {
        sync_in::<NoWindow>(d, None)
    }

    /// Stands in for "no parent window" in [`sync_in`]; never built.
    enum NoWindow {}

    impl raw_window_handle::HasWindowHandle for NoWindow {
        fn window_handle(&self) -> std::result::Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
            match *self {}
        }
    }

    impl raw_window_handle::HasDisplayHandle for NoWindow {
        fn display_handle(&self) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
            match *self {}
        }
    }

    pub(super) fn sync_in<W: HasWindowHandle + HasDisplayHandle + ?Sized>(d: &FileDialog, parent: Option<&W>) -> rfd::FileDialog {
        let mut r = rfd::FileDialog::new();
        // a window without a usable handle (closing, headless) gets an unparented dialog
        if let Some(w) = parent
            && w.window_handle().is_ok()
            && w.display_handle().is_ok()
        {
            r = r.set_parent(w);
        }
        if let Some(t) = &d.title {
            r = r.set_title(clip(t));
        }
        if let Some(dir) = d.existing_directory() {
            r = r.set_directory(dir);
        }
        if let Some(n) = &d.file_name {
            r = r.set_file_name(clip(n));
        }
        for (name, exts) in d.clean_filters() {
            r = r.add_filter(name, &exts);
        }
        r
    }

    fn asynch(d: &FileDialog) -> rfd::AsyncFileDialog {
        let mut r = rfd::AsyncFileDialog::new();
        if let Some(t) = &d.title {
            r = r.set_title(clip(t));
        }
        if let Some(dir) = d.existing_directory() {
            r = r.set_directory(dir);
        }
        if let Some(n) = &d.file_name {
            r = r.set_file_name(clip(n));
        }
        for (name, exts) in d.clean_filters() {
            r = r.add_filter(name, &exts);
        }
        r
    }

    fn picked<T>(what: &str, f: impl FnOnce() -> Option<T>) -> Result<T> {
        crate::guarded(what, || crate::modal::around(f).ok_or(NativeError::Cancelled))
    }

    impl FileDialog {
        /// Ask for one existing file.
        pub fn open_file(&self) -> Result<PathBuf> {
            picked("the open dialog", || sync(self).pick_file())
        }

        /// Ask for one or more existing files.
        pub fn open_files(&self) -> Result<Vec<PathBuf>> {
            picked("the open dialog", || sync(self).pick_files()).and_then(non_empty)
        }

        /// Ask for a folder.
        pub fn pick_folder(&self) -> Result<PathBuf> {
            picked("the folder dialog", || sync(self).pick_folder())
        }

        /// Ask where to save. The OS has already asked about replacing an existing file.
        pub fn save_file(&self) -> Result<PathBuf> {
            picked("the save dialog", || sync(self).save_file())
        }

        pub async fn open_file_async(&self) -> Result<PathBuf> {
            asynch(self).pick_file().await.map(|h| h.path().to_path_buf()).ok_or(NativeError::Cancelled)
        }

        pub async fn open_files_async(&self) -> Result<Vec<PathBuf>> {
            let files = asynch(self).pick_files().await.ok_or(NativeError::Cancelled)?;
            non_empty(files.iter().map(|h| h.path().to_path_buf()).collect())
        }

        pub async fn pick_folder_async(&self) -> Result<PathBuf> {
            asynch(self).pick_folder().await.map(|h| h.path().to_path_buf()).ok_or(NativeError::Cancelled)
        }

        pub async fn save_file_async(&self) -> Result<PathBuf> {
            asynch(self).save_file().await.map(|h| h.path().to_path_buf()).ok_or(NativeError::Cancelled)
        }

        /// Ask for one file and read it: `(file name, contents)`. Works on every platform,
        /// including the web. Files larger than `max_bytes` are refused.
        pub async fn open_bytes_async(&self, max_bytes: u64) -> Result<(String, Vec<u8>)> {
            let h = asynch(self).pick_file().await.ok_or(NativeError::Cancelled)?;
            let path = h.path();
            let len = std::fs::metadata(path).map_err(|e| NativeError::Os(crate::os_text(e)))?.len();
            if len > max_bytes {
                return Err(NativeError::Invalid(format!("the file is larger than {max_bytes} bytes")));
            }
            let bytes = std::fs::read(path).map_err(|e| NativeError::Os(crate::os_text(e)))?;
            Ok((h.file_name(), bytes))
        }
    }

    impl<W: HasWindowHandle + HasDisplayHandle + ?Sized> Parented<'_, W> {
        /// Ask for one existing file, over the parent window.
        pub fn open_file(&self) -> Result<PathBuf> {
            picked("the open dialog", || sync_in(self.dialog, Some(self.parent)).pick_file())
        }

        /// Ask for one or more existing files, over the parent window.
        pub fn open_files(&self) -> Result<Vec<PathBuf>> {
            picked("the open dialog", || sync_in(self.dialog, Some(self.parent)).pick_files()).and_then(non_empty)
        }

        /// Ask for a folder, over the parent window.
        pub fn pick_folder(&self) -> Result<PathBuf> {
            picked("the folder dialog", || sync_in(self.dialog, Some(self.parent)).pick_folder())
        }

        /// Ask where to save, over the parent window.
        pub fn save_file(&self) -> Result<PathBuf> {
            picked("the save dialog", || sync_in(self.dialog, Some(self.parent)).save_file())
        }
    }

    fn non_empty<T>(v: Vec<T>) -> Result<Vec<T>> {
        if v.is_empty() { Err(NativeError::Cancelled) } else { Ok(v) }
    }
}

#[cfg(target_arch = "wasm32")]
mod web {
    use super::*;

    impl<W: ?Sized> Parented<'_, W> {
        pub fn open_file(&self) -> Result<PathBuf> {
            Err(NativeError::Unsupported)
        }
        pub fn open_files(&self) -> Result<Vec<PathBuf>> {
            Err(NativeError::Unsupported)
        }
        pub fn pick_folder(&self) -> Result<PathBuf> {
            Err(NativeError::Unsupported)
        }
        pub fn save_file(&self) -> Result<PathBuf> {
            Err(NativeError::Unsupported)
        }
    }

    impl FileDialog {
        pub fn open_file(&self) -> Result<PathBuf> {
            Err(NativeError::Unsupported)
        }
        pub fn open_files(&self) -> Result<Vec<PathBuf>> {
            Err(NativeError::Unsupported)
        }
        pub fn pick_folder(&self) -> Result<PathBuf> {
            Err(NativeError::Unsupported)
        }
        pub fn save_file(&self) -> Result<PathBuf> {
            Err(NativeError::Unsupported)
        }
        pub async fn open_file_async(&self) -> Result<PathBuf> {
            Err(NativeError::Unsupported)
        }
        pub async fn open_files_async(&self) -> Result<Vec<PathBuf>> {
            Err(NativeError::Unsupported)
        }
        pub async fn pick_folder_async(&self) -> Result<PathBuf> {
            Err(NativeError::Unsupported)
        }
        pub async fn save_file_async(&self) -> Result<PathBuf> {
            Err(NativeError::Unsupported)
        }

        /// Ask for one file and read it: `(file name, contents)`. Files larger than `max_bytes`
        /// are refused (the browser has read them by then; the check bounds what the app keeps).
        pub async fn open_bytes_async(&self, max_bytes: u64) -> Result<(String, Vec<u8>)> {
            let mut r = rfd::AsyncFileDialog::new();
            if let Some(t) = &self.title {
                r = r.set_title(clip(t));
            }
            for (name, exts) in self.clean_filters() {
                r = r.add_filter(name, &exts);
            }
            let h = r.pick_file().await.ok_or(NativeError::Cancelled)?;
            let bytes = h.read().await;
            if bytes.len() as u64 > max_bytes {
                return Err(NativeError::Invalid(format!("the file is larger than {max_bytes} bytes")));
            }
            Ok((h.file_name(), bytes))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn filters_are_cleaned_and_bounded() {
        let d = FileDialog::new()
            .filter("Images", &["png", ".jpg", "*.webp", "", "a/b", "../x"])
            .filter("Nothing valid", &["/", ""])
            .filter("All", &["*"]);
        assert_eq!(
            d.clean_filters(),
            vec![("Images".to_string(), vec!["png".to_string(), "jpg".into(), "webp".into()]), ("All".to_string(), vec!["*".to_string()])]
        );
        let many = (0..500).fold(FileDialog::new(), |d, i| d.filter(format!("f{i}"), &["txt"]));
        assert_eq!(many.clean_filters().len(), MAX_FILTERS);
    }

    #[test]
    fn message_text_keeps_its_lines_and_is_bounded() {
        assert_eq!(clip_message("usage:\n\t-h\u{0}\u{1b}[31m"), "usage:\n\t-h[31m");
        assert_eq!(clip_message(&"y".repeat(100_000)).chars().count(), MAX_MESSAGE);
        let level: MessageLevel = serde_json::from_str("\"error\"").unwrap_or_default();
        assert_eq!(level, MessageLevel::Error);
    }

    #[test]
    fn hostile_text_is_clipped() {
        let long = "x".repeat(10_000);
        assert_eq!(clip(&long).len(), MAX_TEXT);
        assert_eq!(clip("a\nb\u{0}c"), "abc");
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn a_missing_directory_is_not_passed_on() {
        let d = FileDialog::new().directory("/definitely/not/here/ashlar");
        assert!(d.existing_directory().is_none());
        let tmp = std::env::temp_dir();
        assert_eq!(FileDialog::new().directory(&tmp).existing_directory(), Some(tmp.as_path()));
    }

    #[test]
    fn the_description_round_trips_through_json() {
        let d = FileDialog::new().title("Export").file_name("clip.mp4").filter("Video", &["mp4"]);
        let v = serde_json::to_string(&d).unwrap_or_default();
        let back: FileDialog = serde_json::from_str(&v).unwrap_or_default();
        assert_eq!(back, d);
    }

    /// A window that has no handle (closing, or never shown).
    struct Gone;

    impl HasWindowHandle for Gone {
        fn window_handle(&self) -> std::result::Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
            Err(raw_window_handle::HandleError::Unavailable)
        }
    }

    impl HasDisplayHandle for Gone {
        fn display_handle(&self) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
            Err(raw_window_handle::HandleError::Unavailable)
        }
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn a_window_without_a_handle_gets_an_unparented_dialog() {
        let d = FileDialog::new().title("Open");
        // building the dialog must not panic or need the handle; nothing is shown
        let _ = native::sync_in(&d, Some(&Gone));
        let p = d.parent(&Gone);
        assert_eq!(p.dialog, &d);
    }
}