polyscope_rs/screenshot.rs
1use std::sync::Mutex;
2
3use crate::ScreenshotOptions;
4
5/// Global screenshot request storage.
6/// This allows `screenshot()` to be called from user code while `show()` is running.
7static SCREENSHOT_REQUEST: Mutex<Option<ScreenshotRequest>> = Mutex::new(None);
8
9/// A pending screenshot request.
10#[derive(Debug, Clone)]
11pub struct ScreenshotRequest {
12 /// Filename to save to. None means auto-generate.
13 pub filename: Option<String>,
14 /// Screenshot options.
15 pub options: ScreenshotOptions,
16}
17
18/// Requests a screenshot with an auto-generated filename.
19///
20/// The screenshot will be saved as `screenshot_NNNN.png` in the current directory,
21/// where NNNN is an auto-incrementing number.
22///
23/// This function can be called while `show()` is running.
24/// The screenshot will be captured on the next frame.
25///
26/// # Example
27///
28/// ```no_run
29/// use polyscope_rs::*;
30///
31/// init().unwrap();
32/// // ... register structures ...
33///
34/// // Request a screenshot (will be saved when show() runs)
35/// screenshot();
36///
37/// show();
38/// ```
39pub fn screenshot() {
40 screenshot_with_options(ScreenshotOptions::default());
41}
42
43/// Requests a screenshot with custom options.
44///
45/// # Arguments
46/// * `options` - Screenshot options (e.g., transparent background)
47pub fn screenshot_with_options(options: ScreenshotOptions) {
48 if let Ok(mut guard) = SCREENSHOT_REQUEST.lock() {
49 *guard = Some(ScreenshotRequest {
50 filename: None,
51 options,
52 });
53 }
54}
55
56/// Requests a screenshot to be saved to a specific file.
57///
58/// # Arguments
59/// * `filename` - The filename to save to (supports .png and .jpg)
60///
61/// # Example
62///
63/// ```no_run
64/// use polyscope_rs::*;
65///
66/// init().unwrap();
67/// // ... register structures ...
68///
69/// screenshot_to_file("my_scene.png");
70/// show();
71/// ```
72pub fn screenshot_to_file(filename: impl Into<String>) {
73 screenshot_to_file_with_options(filename, ScreenshotOptions::default());
74}
75
76/// Requests a screenshot to be saved to a specific file with custom options.
77///
78/// # Arguments
79/// * `filename` - The filename to save to (supports .png and .jpg)
80/// * `options` - Screenshot options
81pub fn screenshot_to_file_with_options(filename: impl Into<String>, options: ScreenshotOptions) {
82 if let Ok(mut guard) = SCREENSHOT_REQUEST.lock() {
83 *guard = Some(ScreenshotRequest {
84 filename: Some(filename.into()),
85 options,
86 });
87 }
88}
89
90/// Takes and returns a pending screenshot request (for internal use by App).
91pub(crate) fn take_screenshot_request() -> Option<ScreenshotRequest> {
92 SCREENSHOT_REQUEST
93 .lock()
94 .ok()
95 .and_then(|mut guard| guard.take())
96}