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