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
use crate::ViewerContext;

impl<'a> ViewerContext<'a> {
    /// Save some bytes to disk, after first showing a save dialog.
    #[allow(clippy::unused_self)] // Not used on Wasm
    pub fn save_file_dialog(&self, file_name: String, title: String, data: Vec<u8>) {
        re_tracing::profile_function!();

        #[cfg(target_arch = "wasm32")]
        {
            // Web
            wasm_bindgen_futures::spawn_local(async move {
                if let Err(err) = async_save_dialog(&file_name, &title, data).await {
                    re_log::error!("File saving failed: {err}");
                }
            });
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            // Native
            let path = {
                re_tracing::profile_scope!("file_dialog");
                rfd::FileDialog::new()
                    .set_file_name(file_name)
                    .set_title(title)
                    .save_file()
            };
            if let Some(path) = path {
                use crate::SystemCommandSender as _;
                self.command_sender
                    .send_system(crate::SystemCommand::FileSaver(Box::new(move || {
                        std::fs::write(&path, &data)?;
                        Ok(path)
                    })));
            }
        }
    }
}

#[cfg(target_arch = "wasm32")]
async fn async_save_dialog(file_name: &str, title: &str, data: Vec<u8>) -> anyhow::Result<()> {
    use anyhow::Context as _;

    let file_handle = rfd::AsyncFileDialog::new()
        .set_file_name(file_name)
        .set_title(title)
        .save_file()
        .await;

    let Some(file_handle) = file_handle else {
        return Ok(()); // aborted
    };

    file_handle
        .write(data.as_slice())
        .await
        .context("Failed to save")
}