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    #[expect(
254        clippy::expect_used,
255        reason = "native dialog request IDs must stay unique even if the counter reaches its limit"
256    )]
257    pub fn try_open_if<E>(
258        &self,
259        enabled: impl FnOnce() -> Result<bool, E>,
260        options: impl FnOnce() -> Result<NativeDialogOptions, E>,
261    ) -> Result<(), E> {
262        if self.opening.replace(true) {
263            return Ok(());
264        }
265        let _opening = OpeningGuard(&self.opening);
266        let request = crate::property::watch_reads(|reads| {
267            if self.pending() || !enabled()? || reads.changed() {
268                return Ok(None);
269            }
270            static NEXT: AtomicU64 = AtomicU64::new(1);
271            let id = NEXT
272                .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
273                .expect("native dialog request identities exhausted");
274            let options = options()?;
275            Ok((!reads.changed()).then(|| Request {
276                id,
277                options: Rc::new(options),
278            }))
279        })?;
280        if let Some(request) = request {
281            self.request.set(Some(request));
282        }
283        Ok(())
284    }
285
286    pub fn register(
287        &self,
288        deliver: impl Fn(u64, NativeDialogResult) -> bool + 'static,
289    ) -> Option<NativeDialogRegistration> {
290        Some(NativeDialogRegistration {
291            request: self.request.get(|| None)?,
292            deliver: Rc::new(deliver),
293        })
294    }
295
296    #[doc(hidden)]
297    pub fn complete(
298        &self,
299        id: u64,
300        result: NativeDialogResult,
301        selection: Option<&FileDialogSelection>,
302        mut notify: impl FnMut(NativeDialogEvent),
303    ) -> bool {
304        self.try_complete(id, result, selection, |event| {
305            notify(event);
306            Ok::<_, std::convert::Infallible>(())
307        })
308        .unwrap_or_else(|error| match error {})
309    }
310
311    /// Clear the pending request and commit the selection before notifying handlers.
312    #[doc(hidden)]
313    pub fn try_complete<E>(
314        &self,
315        id: u64,
316        result: NativeDialogResult,
317        selection: Option<&FileDialogSelection>,
318        mut notify: impl FnMut(NativeDialogEvent) -> Result<(), E>,
319    ) -> Result<bool, E> {
320        let Some(request) = self.request.get(|| None).filter(|request| request.id == id) else {
321            return Ok(false);
322        };
323        if !request.options.accepts_result(&result) {
324            return Ok(false);
325        }
326        let selection_matches = match &result {
327            NativeDialogResult::Files(_) | NativeDialogResult::Canceled => selection.is_some(),
328            NativeDialogResult::Button(_) => selection.is_none(),
329            NativeDialogResult::Failed(_) | NativeDialogResult::Abandoned => true,
330        };
331        if !selection_matches {
332            return Ok(false);
333        }
334        self.request.set(None);
335        match result {
336            NativeDialogResult::Files(paths) => {
337                if let Some(selection) = selection {
338                    selection.commit(&paths);
339                }
340                notify(NativeDialogEvent::FilesSelected(VecModel::from(paths)))?;
341            }
342            NativeDialogResult::Canceled => {
343                notify(NativeDialogEvent::FileCanceled)?;
344            }
345            NativeDialogResult::Button(button) => {
346                notify(if button.accepts_message() {
347                    NativeDialogEvent::MessageAccepted
348                } else {
349                    NativeDialogEvent::MessageRejected
350                })?;
351                notify(NativeDialogEvent::MessageFinished(button))?;
352            }
353            NativeDialogResult::Failed(message) => notify(NativeDialogEvent::Failed(message))?,
354            NativeDialogResult::Abandoned => {}
355        }
356        Ok(true)
357    }
358
359    pub fn finish(&self, id: u64) -> bool {
360        if self
361            .request
362            .get(|| None)
363            .is_none_or(|request| request.id != id)
364        {
365            return false;
366        }
367        self.request.set(None);
368        true
369    }
370}
371
372/// The last accepted result, independent of mutable lists handed to callbacks.
373#[doc(hidden)]
374#[derive(Default)]
375pub struct FileDialogSelection(Property<Rc<[String]>>);
376
377impl FileDialogSelection {
378    pub fn commit(&self, paths: &[String]) {
379        self.0.set_if_changed(Rc::from(paths));
380    }
381
382    pub fn selected_file(&self) -> String {
383        self.0.get(Rc::default).first().cloned().unwrap_or_default()
384    }
385
386    pub fn selected_files(&self) -> VecModel<String> {
387        VecModel::from(self.0.get(Rc::default).to_vec())
388    }
389}
390
391#[doc(hidden)]
392#[derive(Clone)]
393pub struct NativeDialogRegistration {
394    request: Request,
395    deliver: Rc<dyn Fn(u64, NativeDialogResult) -> bool>,
396}
397
398impl NativeDialogRegistration {
399    pub fn id(&self) -> u64 {
400        self.request.id
401    }
402
403    pub fn options(&self) -> Rc<NativeDialogOptions> {
404        self.request.options.clone()
405    }
406
407    pub fn deliver(self, result: NativeDialogResult) -> bool {
408        (self.deliver)(self.request.id, result)
409    }
410}
411
412impl fmt::Debug for NativeDialogRegistration {
413    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
414        f.debug_struct("NativeDialogRegistration")
415            .field("id", &self.id())
416            .finish()
417    }
418}
419
420impl PartialEq for NativeDialogRegistration {
421    fn eq(&self, other: &Self) -> bool {
422        self.id() == other.id()
423    }
424}
425
426struct ActiveDialog {
427    registration: NativeDialogRegistration,
428    abandoned: Rc<Cell<bool>>,
429}
430
431#[doc(hidden)]
432pub struct NativeDialogPresentation {
433    pub id: u64,
434    pub options: Rc<NativeDialogOptions>,
435    abandoned: Rc<Cell<bool>>,
436}
437
438impl NativeDialogPresentation {
439    pub fn is_abandoned(&self) -> bool {
440        self.abandoned.get()
441    }
442}
443
444/// Serializes native panels and keeps delayed results tied to their original request.
445#[doc(hidden)]
446#[derive(Default)]
447pub struct NativeDialogQueue {
448    waiting: VecDeque<NativeDialogRegistration>,
449    active: Option<ActiveDialog>,
450}
451
452impl NativeDialogQueue {
453    pub fn close(&mut self) {
454        self.sync(&[]);
455        if let Some(active) = self.active.take() {
456            active.registration.deliver(NativeDialogResult::Abandoned);
457        }
458    }
459
460    pub fn sync(&mut self, live: &[&NativeDialogRegistration]) {
461        let is_live = |id| live.iter().any(|entry| entry.id() == id);
462        if let Some(active) = &self.active
463            && !is_live(active.registration.id())
464        {
465            active.abandoned.set(true);
466        }
467        self.waiting.retain(|entry| {
468            if !is_live(entry.id()) {
469                entry.clone().deliver(NativeDialogResult::Abandoned);
470                return false;
471            }
472            true
473        });
474        let queued = self.waiting.len();
475        for entry in live {
476            if self
477                .active
478                .as_ref()
479                .is_some_and(|active| active.registration.id() == entry.id())
480                || self.waiting.iter().any(|queued| queued.id() == entry.id())
481            {
482                continue;
483            }
484            self.waiting.push_back((*entry).clone());
485        }
486        if self.waiting.len() > queued {
487            // Registration traversal follows scene order, which can differ from request order.
488            self.waiting
489                .make_contiguous()
490                .sort_by_key(NativeDialogRegistration::id);
491        }
492    }
493
494    pub fn begin_next(&mut self) -> Option<NativeDialogPresentation> {
495        if self.active.is_some() {
496            return None;
497        }
498        let registration = self.waiting.pop_front()?;
499        let abandoned = Rc::new(Cell::new(false));
500        let request = NativeDialogPresentation {
501            id: registration.id(),
502            options: registration.options(),
503            abandoned: abandoned.clone(),
504        };
505        self.active = Some(ActiveDialog {
506            registration,
507            abandoned,
508        });
509        Some(request)
510    }
511
512    pub fn complete(&mut self, id: u64, result: NativeDialogResult) -> bool {
513        let Some(active) = self.active.take_if(|active| {
514            active.registration.id() == id
515                && (active.abandoned.get()
516                    || active.registration.request.options.accepts_result(&result))
517        }) else {
518            return false;
519        };
520        active.registration.deliver(if active.abandoned.get() {
521            NativeDialogResult::Abandoned
522        } else {
523            result
524        });
525        true
526    }
527}
528
529#[cfg(test)]
530mod tests {
531    use super::{
532        FileDialogOptions, FileDialogSelection, NativeDialogOptions, NativeDialogSlot, parse_filter,
533    };
534    use std::panic::{AssertUnwindSafe, catch_unwind};
535
536    #[test]
537    fn failed_open_bindings_release_the_slot() {
538        let slot = NativeDialogSlot::default();
539        assert_eq!(
540            slot.try_open(|| Err("invalid options")),
541            Err("invalid options")
542        );
543        assert!(
544            catch_unwind(AssertUnwindSafe(
545                || slot.open(|| panic!("option callback failed"))
546            ))
547            .is_err()
548        );
549        assert!(!slot.pending());
550
551        slot.open(|| NativeDialogOptions::File(FileDialogOptions::default()));
552        assert!(slot.pending());
553    }
554
555    #[test]
556    fn name_filters_preserve_labels_and_validate_extensions() {
557        assert_eq!(
558            parse_filter("Text (source) (*.txt *.md)"),
559            Some(("Text (source)", vec!["txt", "md"]))
560        );
561        assert_eq!(
562            parse_filter("All files (*.*)"),
563            Some(("All files", vec!["*"]))
564        );
565        for invalid in [
566            "*.txt",
567            "Text ()",
568            "(*.txt)",
569            "Text (file*.txt)",
570            "Text (*../x)",
571        ] {
572            assert_eq!(parse_filter(invalid), None);
573        }
574    }
575
576    #[test]
577    fn accepted_paths_are_independent_of_the_returned_model() {
578        let selection = FileDialogSelection::default();
579        assert!(selection.selected_file().is_empty());
580        assert!(selection.selected_files().is_empty());
581        selection.commit(&["/workspace/src".into(), "/workspace/tests".into()]);
582        let model = selection.selected_files();
583        assert!(model.set_row(0, "/modified".into()));
584        assert_eq!(selection.selected_file(), "/workspace/src");
585        assert_eq!(
586            selection.selected_files().snapshot(),
587            ["/workspace/src", "/workspace/tests"]
588        );
589    }
590}