Skip to main content

xrack_runtime/
native_dialog.rs

1use crate::{Property, StandardButtonKind, VecModel};
2use std::{
3    cell::Cell,
4    collections::VecDeque,
5    fmt,
6    rc::Rc,
7    sync::atomic::{AtomicU64, Ordering},
8};
9
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub enum FileDialogMode {
12    #[default]
13    OpenFile,
14    OpenFiles,
15    SaveFile,
16    SelectFolder,
17    SelectFolders,
18}
19
20#[derive(Debug, Default)]
21pub struct FileDialogOptions {
22    pub mode: FileDialogMode,
23    pub title: String,
24    pub directory: String,
25    pub file_name: String,
26    pub name_filters: Vec<String>,
27}
28
29impl FileDialogOptions {
30    #[doc(hidden)]
31    pub fn read_bindings(
32        mode: impl FnOnce() -> FileDialogMode,
33        title: impl FnOnce() -> String,
34        directory: impl FnOnce() -> String,
35        file_name: impl FnOnce() -> String,
36        name_filters: impl FnOnce() -> Vec<String>,
37    ) -> Self {
38        Self::try_read_bindings(
39            || Ok::<_, std::convert::Infallible>(mode()),
40            || Ok(title()),
41            || Ok(directory()),
42            || Ok(file_name()),
43            || Ok(name_filters()),
44        )
45        .unwrap_or_else(|error| match error {})
46    }
47
48    #[doc(hidden)]
49    pub fn try_read_bindings<E>(
50        mode: impl FnOnce() -> Result<FileDialogMode, E>,
51        title: impl FnOnce() -> Result<String, E>,
52        directory: impl FnOnce() -> Result<String, E>,
53        file_name: impl FnOnce() -> Result<String, E>,
54        name_filters: impl FnOnce() -> Result<Vec<String>, E>,
55    ) -> Result<Self, E> {
56        Ok(Self {
57            mode: mode()?,
58            title: title()?,
59            directory: directory()?,
60            file_name: file_name()?,
61            name_filters: name_filters()?,
62        })
63    }
64
65    #[doc(hidden)]
66    pub fn filters(&self) -> Result<Vec<(&str, Vec<&str>)>, &'static str> {
67        if matches!(
68            self.mode,
69            FileDialogMode::SelectFolder | FileDialogMode::SelectFolders
70        ) {
71            return Ok(Vec::new());
72        }
73        self.name_filters
74            .iter()
75            .map(|filter| parse_filter(filter))
76            .collect::<Option<_>>()
77            .ok_or("Invalid name filter. Use a label and extension patterns, for example Text files (*.txt *.md).")
78    }
79}
80
81fn parse_filter(filter: &str) -> Option<(&str, Vec<&str>)> {
82    let (label, patterns) = filter.trim().strip_suffix(')')?.rsplit_once('(')?;
83    let label = label.trim();
84    let extensions = patterns
85        .split_whitespace()
86        .map(|pattern| {
87            if pattern == "*" || pattern == "*.*" {
88                return Some("*");
89            }
90            let extension = pattern.strip_prefix("*.")?;
91            (!extension.is_empty()
92                && extension
93                    .bytes()
94                    .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')))
95            .then_some(extension)
96        })
97        .collect::<Option<Vec<_>>>()?;
98    (!label.is_empty() && !extensions.is_empty()).then_some((label, extensions))
99}
100
101#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
102pub enum MessageLevel {
103    #[default]
104    Info,
105    Warning,
106    Error,
107}
108
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
110pub enum MessageButtons {
111    #[default]
112    Ok,
113    OkCancel,
114    YesNo,
115    YesNoCancel,
116}
117
118#[derive(Debug, Default)]
119pub struct MessageDialogOptions {
120    pub level: MessageLevel,
121    pub buttons: MessageButtons,
122    pub title: String,
123    pub text: String,
124    pub informative_text: String,
125}
126
127impl MessageDialogOptions {
128    #[doc(hidden)]
129    pub fn read_bindings(
130        level: impl FnOnce() -> MessageLevel,
131        buttons: impl FnOnce() -> MessageButtons,
132        title: impl FnOnce() -> String,
133        text: impl FnOnce() -> String,
134        informative_text: impl FnOnce() -> String,
135    ) -> Self {
136        Self::try_read_bindings(
137            || Ok::<_, std::convert::Infallible>(level()),
138            || Ok(buttons()),
139            || Ok(title()),
140            || Ok(text()),
141            || Ok(informative_text()),
142        )
143        .unwrap_or_else(|error| match error {})
144    }
145
146    #[doc(hidden)]
147    pub fn try_read_bindings<E>(
148        level: impl FnOnce() -> Result<MessageLevel, E>,
149        buttons: impl FnOnce() -> Result<MessageButtons, E>,
150        title: impl FnOnce() -> Result<String, E>,
151        text: impl FnOnce() -> Result<String, E>,
152        informative_text: impl FnOnce() -> Result<String, E>,
153    ) -> Result<Self, E> {
154        Ok(Self {
155            level: level()?,
156            buttons: buttons()?,
157            title: title()?,
158            text: text()?,
159            informative_text: informative_text()?,
160        })
161    }
162}
163
164#[doc(hidden)]
165#[derive(Debug)]
166pub enum NativeDialogOptions {
167    File(FileDialogOptions),
168    Message(MessageDialogOptions),
169}
170
171#[doc(hidden)]
172#[derive(Debug, PartialEq, Eq)]
173pub enum NativeDialogResult {
174    Files(Vec<String>),
175    Button(StandardButtonKind),
176    Canceled,
177    Failed(String),
178    Abandoned,
179}
180
181impl NativeDialogOptions {
182    fn accepts_result(&self, result: &NativeDialogResult) -> bool {
183        match result {
184            NativeDialogResult::Files(_) | NativeDialogResult::Canceled => {
185                matches!(self, Self::File(_))
186            }
187            NativeDialogResult::Button(_) => matches!(self, Self::Message(_)),
188            NativeDialogResult::Failed(_) | NativeDialogResult::Abandoned => true,
189        }
190    }
191}
192
193#[doc(hidden)]
194pub enum NativeDialogEvent {
195    FilesSelected(VecModel<String>),
196    FileCanceled,
197    MessageAccepted,
198    MessageRejected,
199    MessageFinished(StandardButtonKind),
200    Failed(String),
201}
202
203#[derive(Clone, Debug)]
204struct Request {
205    id: u64,
206    options: Rc<NativeDialogOptions>,
207}
208
209/// The component owns the pending request. Render snapshots only register it with the host.
210#[doc(hidden)]
211#[derive(Default)]
212pub struct NativeDialogSlot {
213    request: Property<Option<Request>>,
214    opening: Cell<bool>,
215}
216
217struct OpeningGuard<'a>(&'a Cell<bool>);
218
219impl Drop for OpeningGuard<'_> {
220    fn drop(&mut self) {
221        self.0.set(false);
222    }
223}
224
225impl NativeDialogSlot {
226    pub fn pending(&self) -> bool {
227        self.request.get(|| None).is_some()
228    }
229
230    pub fn open(&self, options: impl FnOnce() -> NativeDialogOptions) {
231        let _: Result<(), std::convert::Infallible> = self.try_open(|| Ok(options()));
232    }
233
234    pub fn try_open<E>(
235        &self,
236        options: impl FnOnce() -> Result<NativeDialogOptions, E>,
237    ) -> Result<(), E> {
238        self.try_open_if(|| Ok(true), options)
239    }
240
241    #[doc(hidden)]
242    pub fn open_if(
243        &self,
244        enabled: impl FnOnce() -> bool,
245        options: impl FnOnce() -> NativeDialogOptions,
246    ) {
247        let _: Result<(), std::convert::Infallible> =
248            self.try_open_if(|| Ok(enabled()), || Ok(options()));
249    }
250
251    /// Prevent reentry and publish only while the permission and options remain current.
252    #[doc(hidden)]
253    pub fn try_open_if<E>(
254        &self,
255        enabled: impl FnOnce() -> Result<bool, E>,
256        options: impl FnOnce() -> Result<NativeDialogOptions, E>,
257    ) -> Result<(), E> {
258        if self.opening.replace(true) {
259            return Ok(());
260        }
261        let _opening = OpeningGuard(&self.opening);
262        let request = crate::property::watch_reads(|reads| {
263            if self.pending() || !enabled()? || reads.changed() {
264                return Ok(None);
265            }
266            static NEXT: AtomicU64 = AtomicU64::new(1);
267            let id = NEXT
268                .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
269                .expect("native dialog request identities exhausted");
270            let options = options()?;
271            Ok((!reads.changed()).then(|| Request {
272                id,
273                options: Rc::new(options),
274            }))
275        })?;
276        if let Some(request) = request {
277            self.request.set(Some(request));
278        }
279        Ok(())
280    }
281
282    pub fn register(
283        &self,
284        deliver: impl Fn(u64, NativeDialogResult) -> bool + 'static,
285    ) -> Option<NativeDialogRegistration> {
286        Some(NativeDialogRegistration {
287            request: self.request.get(|| None)?,
288            deliver: Rc::new(deliver),
289        })
290    }
291
292    #[doc(hidden)]
293    pub fn complete(
294        &self,
295        id: u64,
296        result: NativeDialogResult,
297        selection: Option<&FileDialogSelection>,
298        mut notify: impl FnMut(NativeDialogEvent),
299    ) -> bool {
300        self.try_complete(id, result, selection, |event| {
301            notify(event);
302            Ok::<_, std::convert::Infallible>(())
303        })
304        .unwrap_or_else(|error| match error {})
305    }
306
307    /// Clear the pending request and commit the selection before notifying handlers.
308    #[doc(hidden)]
309    pub fn try_complete<E>(
310        &self,
311        id: u64,
312        result: NativeDialogResult,
313        selection: Option<&FileDialogSelection>,
314        mut notify: impl FnMut(NativeDialogEvent) -> Result<(), E>,
315    ) -> Result<bool, E> {
316        let Some(request) = self.request.get(|| None).filter(|request| request.id == id) else {
317            return Ok(false);
318        };
319        if !request.options.accepts_result(&result) {
320            return Ok(false);
321        }
322        let selection_matches = match &result {
323            NativeDialogResult::Files(_) | NativeDialogResult::Canceled => selection.is_some(),
324            NativeDialogResult::Button(_) => selection.is_none(),
325            NativeDialogResult::Failed(_) | NativeDialogResult::Abandoned => true,
326        };
327        if !selection_matches {
328            return Ok(false);
329        }
330        self.request.set(None);
331        match result {
332            NativeDialogResult::Files(paths) => {
333                let selection = selection.expect("validated file dialog selection");
334                selection.commit(&paths);
335                notify(NativeDialogEvent::FilesSelected(VecModel::from(paths)))?;
336            }
337            NativeDialogResult::Canceled => {
338                notify(NativeDialogEvent::FileCanceled)?;
339            }
340            NativeDialogResult::Button(button) => {
341                notify(if button.accepts_message() {
342                    NativeDialogEvent::MessageAccepted
343                } else {
344                    NativeDialogEvent::MessageRejected
345                })?;
346                notify(NativeDialogEvent::MessageFinished(button))?;
347            }
348            NativeDialogResult::Failed(message) => notify(NativeDialogEvent::Failed(message))?,
349            NativeDialogResult::Abandoned => {}
350        }
351        Ok(true)
352    }
353
354    pub fn finish(&self, id: u64) -> bool {
355        if self
356            .request
357            .get(|| None)
358            .is_none_or(|request| request.id != id)
359        {
360            return false;
361        }
362        self.request.set(None);
363        true
364    }
365}
366
367/// The last accepted result, independent of mutable lists handed to callbacks.
368#[doc(hidden)]
369#[derive(Default)]
370pub struct FileDialogSelection(Property<Rc<[String]>>);
371
372impl FileDialogSelection {
373    pub fn commit(&self, paths: &[String]) {
374        self.0.set_if_changed(Rc::from(paths));
375    }
376
377    pub fn selected_file(&self) -> String {
378        self.0.get(Rc::default).first().cloned().unwrap_or_default()
379    }
380
381    pub fn selected_files(&self) -> VecModel<String> {
382        VecModel::from(self.0.get(Rc::default).to_vec())
383    }
384}
385
386#[doc(hidden)]
387#[derive(Clone)]
388pub struct NativeDialogRegistration {
389    request: Request,
390    deliver: Rc<dyn Fn(u64, NativeDialogResult) -> bool>,
391}
392
393impl NativeDialogRegistration {
394    pub fn id(&self) -> u64 {
395        self.request.id
396    }
397
398    pub fn options(&self) -> Rc<NativeDialogOptions> {
399        self.request.options.clone()
400    }
401
402    pub fn deliver(self, result: NativeDialogResult) -> bool {
403        (self.deliver)(self.request.id, result)
404    }
405}
406
407impl fmt::Debug for NativeDialogRegistration {
408    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409        f.debug_struct("NativeDialogRegistration")
410            .field("id", &self.id())
411            .finish()
412    }
413}
414
415impl PartialEq for NativeDialogRegistration {
416    fn eq(&self, other: &Self) -> bool {
417        self.id() == other.id()
418    }
419}
420
421struct ActiveDialog {
422    registration: NativeDialogRegistration,
423    abandoned: Rc<Cell<bool>>,
424}
425
426#[doc(hidden)]
427pub struct NativeDialogPresentation {
428    pub id: u64,
429    pub options: Rc<NativeDialogOptions>,
430    abandoned: Rc<Cell<bool>>,
431}
432
433impl NativeDialogPresentation {
434    pub fn is_abandoned(&self) -> bool {
435        self.abandoned.get()
436    }
437}
438
439/// Serializes native panels and keeps delayed results tied to their original request.
440#[doc(hidden)]
441#[derive(Default)]
442pub struct NativeDialogQueue {
443    waiting: VecDeque<NativeDialogRegistration>,
444    active: Option<ActiveDialog>,
445}
446
447impl NativeDialogQueue {
448    pub fn close(&mut self) {
449        self.sync(&[]);
450        if let Some(active) = self.active.take() {
451            active.registration.deliver(NativeDialogResult::Abandoned);
452        }
453    }
454
455    pub fn sync(&mut self, live: &[&NativeDialogRegistration]) {
456        let is_live = |id| live.iter().any(|entry| entry.id() == id);
457        if let Some(active) = &self.active
458            && !is_live(active.registration.id())
459        {
460            active.abandoned.set(true);
461        }
462        self.waiting.retain(|entry| {
463            if !is_live(entry.id()) {
464                entry.clone().deliver(NativeDialogResult::Abandoned);
465                return false;
466            }
467            true
468        });
469        let queued = self.waiting.len();
470        for entry in live {
471            if self
472                .active
473                .as_ref()
474                .is_some_and(|active| active.registration.id() == entry.id())
475                || self.waiting.iter().any(|queued| queued.id() == entry.id())
476            {
477                continue;
478            }
479            self.waiting.push_back((*entry).clone());
480        }
481        if self.waiting.len() > queued {
482            // Registration traversal follows scene order, which can differ from request order.
483            self.waiting
484                .make_contiguous()
485                .sort_by_key(NativeDialogRegistration::id);
486        }
487    }
488
489    pub fn begin_next(&mut self) -> Option<NativeDialogPresentation> {
490        if self.active.is_some() {
491            return None;
492        }
493        let registration = self.waiting.pop_front()?;
494        let abandoned = Rc::new(Cell::new(false));
495        let request = NativeDialogPresentation {
496            id: registration.id(),
497            options: registration.options(),
498            abandoned: abandoned.clone(),
499        };
500        self.active = Some(ActiveDialog {
501            registration,
502            abandoned,
503        });
504        Some(request)
505    }
506
507    pub fn complete(&mut self, id: u64, result: NativeDialogResult) -> bool {
508        let Some(active) = self.active.take_if(|active| {
509            active.registration.id() == id
510                && (active.abandoned.get()
511                    || active.registration.request.options.accepts_result(&result))
512        }) else {
513            return false;
514        };
515        active.registration.deliver(if active.abandoned.get() {
516            NativeDialogResult::Abandoned
517        } else {
518            result
519        });
520        true
521    }
522}
523
524#[cfg(test)]
525mod tests {
526    use super::{
527        FileDialogOptions, FileDialogSelection, NativeDialogOptions, NativeDialogSlot, parse_filter,
528    };
529    use std::panic::{AssertUnwindSafe, catch_unwind};
530
531    #[test]
532    fn failed_open_bindings_release_the_slot() {
533        let slot = NativeDialogSlot::default();
534        assert_eq!(
535            slot.try_open(|| Err("invalid options")),
536            Err("invalid options")
537        );
538        assert!(
539            catch_unwind(AssertUnwindSafe(
540                || slot.open(|| panic!("option callback failed"))
541            ))
542            .is_err()
543        );
544        assert!(!slot.pending());
545
546        slot.open(|| NativeDialogOptions::File(FileDialogOptions::default()));
547        assert!(slot.pending());
548    }
549
550    #[test]
551    fn name_filters_preserve_labels_and_validate_extensions() {
552        assert_eq!(
553            parse_filter("Text (source) (*.txt *.md)"),
554            Some(("Text (source)", vec!["txt", "md"]))
555        );
556        assert_eq!(
557            parse_filter("All files (*.*)"),
558            Some(("All files", vec!["*"]))
559        );
560        for invalid in [
561            "*.txt",
562            "Text ()",
563            "(*.txt)",
564            "Text (file*.txt)",
565            "Text (*../x)",
566        ] {
567            assert_eq!(parse_filter(invalid), None);
568        }
569    }
570
571    #[test]
572    fn accepted_paths_are_independent_of_the_returned_model() {
573        let selection = FileDialogSelection::default();
574        assert!(selection.selected_file().is_empty());
575        assert!(selection.selected_files().is_empty());
576        selection.commit(&["/workspace/src".into(), "/workspace/tests".into()]);
577        let model = selection.selected_files();
578        assert!(model.set_row(0, "/modified".into()));
579        assert_eq!(selection.selected_file(), "/workspace/src");
580        assert_eq!(
581            selection.selected_files().snapshot(),
582            ["/workspace/src", "/workspace/tests"]
583        );
584    }
585}