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
use re_space_view::ScreenshotMode;
use re_viewport_blueprint::SpaceViewBlueprint;

pub fn handle_pending_space_view_screenshots(
    space_view: &SpaceViewBlueprint,
    data: &[u8],
    extent: glam::UVec2,
    mode: ScreenshotMode,
) {
    // Set to clipboard.
    #[cfg(not(target_arch = "wasm32"))]
    re_viewer_context::Clipboard::with(|clipboard| {
        clipboard.set_image([extent.x as _, extent.y as _], data);
    });
    if mode == ScreenshotMode::CopyToClipboard {
        return;
    }

    // Get next available file name.
    fn is_safe_filename_char(c: char) -> bool {
        c.is_alphanumeric() || matches!(c, ' ' | '-' | '_')
    }
    let safe_display_name = space_view
        .display_name_or_default()
        .as_ref()
        .replace(|c: char| !is_safe_filename_char(c), "");
    let mut i = 1;
    let filename = loop {
        let filename = format!("Screenshot {safe_display_name} - {i}.png");
        if !std::path::Path::new(&filename).exists() {
            break filename;
        }
        i += 1;
    };
    let filename = std::path::Path::new(&filename);

    match image::save_buffer(filename, data, extent.x, extent.y, image::ColorType::Rgba8) {
        Ok(_) => {
            re_log::info!(
                "Saved screenshot to {:?}.",
                filename.canonicalize().unwrap_or(filename.to_path_buf())
            );
        }
        Err(err) => {
            re_log::error!(
                "Failed to safe screenshot to {:?}: {}",
                filename.canonicalize().unwrap_or(filename.to_path_buf()),
                err
            );
        }
    }
}