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
use std::marker::PhantomData;
use std::path::PathBuf;

use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
use bevy_tasks::prelude::*;
use crossbeam_channel::bounded;
use rfd::AsyncFileDialog;

use crate::{
    handle_dialog_result, DialogResult, FileDialog, FileDialogPlugin, StreamReceiver, StreamSender,
};

/// Event that gets sent when directory path gets selected from file system.
#[derive(Event)]
pub struct DialogDirectoryPicked<T: PickDirectoryPath> {
    /// Path of picked directory.
    pub path: PathBuf,

    marker: PhantomData<T>,
}

/// Event that gets sent when user closes pick directory dialog without picking any directory.
#[derive(Event)]
pub struct DialogDirectoryPickCanceled<T: PickDirectoryPath>(PhantomData<T>);

impl<T: PickDirectoryPath> Default for DialogDirectoryPickCanceled<T> {
    fn default() -> Self {
        Self(Default::default())
    }
}

/// Marker trait saying what directory path are we picking.
pub trait PickDirectoryPath: Send + Sync + 'static {}

impl<T> PickDirectoryPath for T where T: Send + Sync + 'static {}

/// Event that gets sent when file path gets selected from file system.
#[derive(Event)]
pub struct DialogFilePicked<T: PickFilePath> {
    /// Path of picked file.
    pub path: PathBuf,

    marker: PhantomData<T>,
}

/// Event that gets sent when user closes pick file dialog without picking any file.
#[derive(Event)]
pub struct DialogFilePickCanceled<T: PickFilePath>(PhantomData<T>);

impl<T: PickFilePath> Default for DialogFilePickCanceled<T> {
    fn default() -> Self {
        Self(Default::default())
    }
}

/// Marker trait saying what file path are we picking.
pub trait PickFilePath: Send + Sync + 'static {}

impl<T> PickFilePath for T where T: Send + Sync + 'static {}

impl FileDialogPlugin {
    /// Allow picking directory paths. This allows you to call
    /// [`FileDialog::pick_directory_path`] and
    /// [`FileDialog::pick_multiple_directory_paths`] on [`Commands`]. For each
    /// `with_pick_directory` you will receive [`DialogDirectoryPicked<T>`] in your
    /// systems when picking completes.
    ///
    /// Does not exist in `WASM32`.
    pub fn with_pick_directory<T: PickDirectoryPath>(mut self) -> Self {
        self.0.push(Box::new(|app| {
            let (tx, rx) = bounded::<DialogResult<DialogDirectoryPicked<T>>>(1);
            app.insert_resource(StreamSender(tx));
            app.insert_resource(StreamReceiver(rx));
            app.add_event::<DialogDirectoryPicked<T>>();
            app.add_event::<DialogDirectoryPickCanceled<T>>();
            app.add_systems(
                First,
                handle_dialog_result::<DialogDirectoryPicked<T>, DialogDirectoryPickCanceled<T>>,
            );
        }));
        self
    }

    /// Allow picking file paths. This allows you to call
    /// [`FileDialog::pick_file_path`] and
    /// [`FileDialog::pick_multiple_file_paths`] on [`Commands`]. For each
    /// `with_pick_file` you will receive [`DialogFilePicked<T>`] in your
    /// systems when picking completes.
    ///
    /// Does not exist in `WASM32`. If you want cross-platform solution for
    /// files, you need to use [`FileDialogPlugin::with_load_file`], which
    /// allows picking and loading in one step which is compatible with wasm.
    pub fn with_pick_file<T: PickFilePath>(mut self) -> Self {
        self.0.push(Box::new(|app| {
            let (tx, rx) = bounded::<DialogResult<DialogFilePicked<T>>>(1);
            app.insert_resource(StreamSender(tx));
            app.insert_resource(StreamReceiver(rx));
            app.add_event::<DialogFilePicked<T>>();
            app.add_event::<DialogFilePickCanceled<T>>();
            app.add_systems(
                First,
                handle_dialog_result::<DialogFilePicked<T>, DialogFilePickCanceled<T>>,
            );
        }));
        self
    }
}

impl<'w, 's, 'a> FileDialog<'w, 's, 'a> {
    /// Open pick directory dialog and send [`DialogDirectoryPicked<T>`]
    /// event. You can read this event with Bevy's
    /// [`EventReader<DialogDirectoryPicked<T>>`].
    ///
    /// Does not exist in `wasm32`.
    pub fn pick_directory_path<T: PickDirectoryPath>(self) {
        self.commands.add(|world: &mut World| {
            let sender = world
                .get_resource::<StreamSender<DialogResult<DialogDirectoryPicked<T>>>>()
                .expect("FileDialogPlugin not initialized with 'with_pick_directory::<T>()'")
                .0
                .clone();

            AsyncComputeTaskPool::get()
                .spawn(async move {
                    let file = self.dialog.pick_folder().await;

                    let Some(file) = file else {
                        sender.send(DialogResult::Canceled).unwrap();
                        return;
                    };

                    let event = DialogDirectoryPicked {
                        path: file.path().to_path_buf(),
                        marker: PhantomData,
                    };

                    sender.send(DialogResult::Single(event)).unwrap();
                })
                .detach();
        });
    }

    /// Open pick multiple directories dialog and send
    /// [`DialogDirectoryPicked<T>`] for each selected directory path. You
    /// can get each path by reading every event received with with Bevy's
    /// [`EventReader<DialogDirectoryPicked<T>>`].
    ///
    /// Does not exist in `wasm32`.
    pub fn pick_multiple_directory_paths<T: PickDirectoryPath>(self) {
        self.commands.add(|world: &mut World| {
            let sender = world
                .get_resource::<StreamSender<DialogResult<DialogDirectoryPicked<T>>>>()
                .expect("FileDialogPlugin not initialized with 'with_pick_directory::<T>()'")
                .0
                .clone();

            AsyncComputeTaskPool::get()
                .spawn(async move {
                    let files = AsyncFileDialog::new().pick_folders().await;

                    let Some(files) = files else {
                        sender.send(DialogResult::Canceled).unwrap();
                        return;
                    };

                    let events = files
                        .into_iter()
                        .map(|file| DialogDirectoryPicked {
                            path: file.path().to_path_buf(),
                            marker: PhantomData,
                        })
                        .collect();

                    sender.send(DialogResult::Batch(events)).unwrap();
                })
                .detach();
        });
    }

    /// Open pick file dialog and send [`DialogFilePicked<T>`]
    /// event. You can read this event with Bevy's
    /// [`EventReader<DialogFilePicked<T>>`].
    ///
    /// Does not exist in `wasm32`. If you want cross-platform solution, you
    /// need to use [`FileDialog::load_file`], which does picking and loading in
    /// one step which is compatible with wasm.
    pub fn pick_file_path<T: PickFilePath>(self) {
        self.commands.add(|world: &mut World| {
            let sender = world
                .get_resource::<StreamSender<DialogResult<DialogFilePicked<T>>>>()
                .expect("FileDialogPlugin not initialized with 'with_pick_file::<T>()'")
                .0
                .clone();

            AsyncComputeTaskPool::get()
                .spawn(async move {
                    let file = self.dialog.pick_file().await;

                    let Some(file) = file else {
                        sender.send(DialogResult::Canceled).unwrap();
                        return;
                    };

                    let event = DialogFilePicked {
                        path: file.path().to_path_buf(),
                        marker: PhantomData,
                    };

                    sender.send(DialogResult::Single(event)).unwrap();
                })
                .detach();
        });
    }

    /// Open pick multiple files dialog and send
    /// [`DialogFilePicked<T>`] for each selected file path. You
    /// can get each path by reading every event received with with Bevy's
    /// [`EventReader<DialogFilePicked<T>>`].
    ///
    /// Does not exist in `wasm32`. If you want cross-platform solution, you
    /// need to use [`FileDialog::load_multiple_files`], which does picking and
    /// loading in one step which is compatible with wasm.
    pub fn pick_multiple_file_paths<T: PickDirectoryPath>(self) {
        self.commands.add(|world: &mut World| {
            let sender = world
                .get_resource::<StreamSender<DialogResult<DialogFilePicked<T>>>>()
                .expect("FileDialogPlugin not initialized with 'with_pick_file::<T>()'")
                .0
                .clone();

            AsyncComputeTaskPool::get()
                .spawn(async move {
                    let files = AsyncFileDialog::new().pick_files().await;

                    let Some(files) = files else {
                        sender.send(DialogResult::Canceled).unwrap();
                        return;
                    };

                    let events = files
                        .into_iter()
                        .map(|file| DialogFilePicked {
                            path: file.path().to_path_buf(),
                            marker: PhantomData,
                        })
                        .collect();

                    sender.send(DialogResult::Batch(events)).unwrap();
                })
                .detach();
        });
    }
}