Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Store desktop background snapshot for studio recordings

Richie McIlroydb9652593b23
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index e19866904..23b44dec9 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -80,6 +80,231 @@ fn recording_stopped_share_url(link: &str) -> String {
}
}
+const CURRENT_DESKTOP_BACKGROUND_FILENAME: &str = "current-desktop-background.jpg";
+const CURRENT_DESKTOP_BACKGROUND_PENDING_FILENAME: &str = "current-desktop-background.pending.jpg";
+
+fn current_desktop_background_snapshot_path(recording_dir: &Path) -> PathBuf {
+ recording_dir
+ .join("assets")
+ .join(CURRENT_DESKTOP_BACKGROUND_FILENAME)
+}
+
+fn stored_current_desktop_background_path(recording_dir: &Path) -> Option<String> {
+ let path = current_desktop_background_snapshot_path(recording_dir);
+ path.exists().then(|| path.to_string_lossy().into_owned())
+}
+
+fn pending_current_desktop_background_snapshot_path(recording_dir: &Path) -> PathBuf {
+ recording_dir
+ .join("assets")
+ .join(CURRENT_DESKTOP_BACKGROUND_PENDING_FILENAME)
+}
+
+fn spawn_current_desktop_background_snapshot(
+ recording_dir: PathBuf,
+ capture_target: ScreenCaptureTarget,
+) {
+ if matches!(capture_target, ScreenCaptureTarget::CameraOnly) {
+ return;
+ }
+
+ tokio::spawn(async move {
+ match store_current_desktop_background_snapshot(recording_dir, capture_target).await {
+ Ok(path) => debug!(
+ path = %path.display(),
+ "Stored current desktop background for recording"
+ ),
+ Err(error) => debug!(%error, "Failed to store current desktop background"),
+ }
+ });
+}
+
+async fn store_current_desktop_background_snapshot(
+ recording_dir: PathBuf,
+ capture_target: ScreenCaptureTarget,
+) -> Result<PathBuf, String> {
+ tokio::task::spawn_blocking(move || {
+ let output_path = current_desktop_background_snapshot_path(&recording_dir);
+ let pending_path = pending_current_desktop_background_snapshot_path(&recording_dir);
+ let display_id = capture_target
+ .display()
+ .map(|display| display.id().to_string());
+ let source_path = current_desktop_background_source_path(display_id.as_deref())
+ .ok_or_else(|| "Current desktop background path not found".to_string())?;
+
+ if !source_path.exists() {
+ return Err(format!(
+ "Current desktop background does not exist: {}",
+ source_path.display()
+ ));
+ }
+
+ if let Some(parent) = output_path.parent() {
+ std::fs::create_dir_all(parent)
+ .map_err(|err| format!("Failed to create background assets directory: {err}"))?;
+ }
+
+ let _ = std::fs::remove_file(&pending_path);
+ if let Err(error) = write_desktop_background_snapshot(&source_path, &pending_path) {
+ let _ = std::fs::remove_file(&pending_path);
+ return Err(error);
+ }
+
+ if output_path.exists() {
+ std::fs::remove_file(&output_path)
+ .map_err(|err| format!("Failed to replace current desktop background: {err}"))?;
+ }
+
+ std::fs::rename(&pending_path, &output_path)
+ .map_err(|err| format!("Failed to store current desktop background: {err}"))?;
+ Ok(output_path)
+ })
+ .await
+ .map_err(|err| format!("Desktop background snapshot task failed: {err}"))?
+}
+
+#[cfg(target_os = "macos")]
+fn current_desktop_background_source_path(display_id: Option<&str>) -> Option<PathBuf> {
+ use cocoa::appkit::NSScreen;
+ use cocoa::base::{id, nil};
+ use cocoa::foundation::NSString;
+ use objc::{class, msg_send, sel, sel_impl};
+ use std::ffi::CStr;
+
+ unsafe {
+ let screen =
+ macos_screen_for_display_id(display_id).unwrap_or_else(|| NSScreen::mainScreen(nil));
+ if screen == nil {
+ return None;
+ }
+
+ let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
+ if workspace == nil {
+ return None;
+ }
+
+ let url: id = msg_send![workspace, desktopImageURLForScreen: screen];
+ if url == nil {
+ return None;
+ }
+
+ let path: id = msg_send![url, path];
+ if path == nil {
+ return None;
+ }
+
+ let path = CStr::from_ptr(NSString::UTF8String(path))
+ .to_string_lossy()
+ .to_string();
+ (!path.is_empty()).then(|| PathBuf::from(path))
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn macos_screen_for_display_id(display_id: Option<&str>) -> Option<cocoa::base::id> {
+ use cocoa::appkit::NSScreen;
+ use cocoa::base::{id, nil};
+ use cocoa::foundation::{NSArray, NSDictionary, NSString};
+ use objc::{msg_send, sel, sel_impl};
+
+ let expected_id = display_id?.parse::<u32>().ok()?;
+
+ unsafe {
+ let screens = NSScreen::screens(nil);
+ if screens == nil {
+ return None;
+ }
+
+ let screen_number_key = NSString::alloc(nil).init_str("NSScreenNumber");
+ for index in 0..NSArray::count(screens) {
+ let screen: id = screens.objectAtIndex(index);
+ if screen == nil {
+ continue;
+ }
+
+ let device_description = NSScreen::deviceDescription(screen);
+ let number = NSDictionary::valueForKey_(device_description, screen_number_key) as id;
+ if number == nil {
+ continue;
+ }
+
+ let number_value: u32 = msg_send![number, unsignedIntValue];
+ if number_value == expected_id {
+ return Some(screen);
+ }
+ }
+ }
+
+ None
+}
+
+#[cfg(target_os = "windows")]
+fn current_desktop_background_source_path(_display_id: Option<&str>) -> Option<PathBuf> {
+ use std::{ffi::OsString, os::windows::ffi::OsStringExt};
+ use windows::Win32::UI::WindowsAndMessaging::{
+ SPI_GETDESKWALLPAPER, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW,
+ };
+
+ let mut buffer = vec![0u16; 32_768];
+ unsafe {
+ SystemParametersInfoW(
+ SPI_GETDESKWALLPAPER,
+ u32::try_from(buffer.len()).ok()?,
+ Some(buffer.as_mut_ptr().cast()),
+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
+ )
+ .ok()?;
+ }
+
+ let len = buffer
+ .iter()
+ .position(|character| *character == 0)
+ .unwrap_or(buffer.len());
+ (len > 0).then(|| PathBuf::from(OsString::from_wide(&buffer[..len])))
+}
+
+#[cfg(not(any(target_os = "macos", target_os = "windows")))]
+fn current_desktop_background_source_path(_display_id: Option<&str>) -> Option<PathBuf> {
+ None
+}
+
+#[cfg(target_os = "macos")]
+fn write_desktop_background_snapshot(source_path: &Path, output_path: &Path) -> Result<(), String> {
+ let sips_result = std::process::Command::new("sips")
+ .arg("-s")
+ .arg("format")
+ .arg("jpeg")
+ .arg(source_path)
+ .arg("--out")
+ .arg(output_path)
+ .output();
+
+ if let Ok(output) = sips_result
+ && output.status.success()
+ {
+ return Ok(());
+ }
+
+ write_desktop_background_snapshot_with_image_crate(source_path, output_path)
+}
+
+#[cfg(not(target_os = "macos"))]
+fn write_desktop_background_snapshot(source_path: &Path, output_path: &Path) -> Result<(), String> {
+ write_desktop_background_snapshot_with_image_crate(source_path, output_path)
+}
+
+fn write_desktop_background_snapshot_with_image_crate(
+ source_path: &Path,
+ output_path: &Path,
+) -> Result<(), String> {
+ let image = image::open(source_path)
+ .map_err(|err| format!("Failed to decode current desktop background: {err}"))?;
+ image
+ .to_rgb8()
+ .save_with_format(output_path, image::ImageFormat::Jpeg)
+ .map_err(|err| format!("Failed to save current desktop background: {err}"))
+}
+
#[derive(Clone)]
pub struct InProgressRecordingCommon {
pub target_name: String,
@@ -1420,6 +1645,13 @@ pub async fn start_recording(
}
};
+ if matches!(inputs.mode, RecordingMode::Studio) {
+ spawn_current_desktop_background_snapshot(
+ project_file_path.clone(),
+ inputs.capture_target.clone(),
+ );
+ }
+
let _ = RecordingEvent::Started.emit(&app);
let _ = RecordingStarted.emit(&app);
@@ -2508,6 +2740,7 @@ async fn handle_recording_finish(
&recordings,
PresetsStore::get_default_preset(app)?.map(|p| p.config),
Some(&capture_target),
+ stored_current_desktop_background_path(&recording_dir),
);
config.write(&recording_dir).map_err(|e| e.to_string())?;
@@ -2752,6 +2985,7 @@ async fn finalize_studio_recording(
&recordings,
default_preset,
capture_target.as_ref(),
+ stored_current_desktop_background_path(&recording_dir),
);
config
@@ -2906,6 +3140,7 @@ fn project_config_from_recording(
recordings: &ProjectRecordingsMeta,
default_config: Option<ProjectConfiguration>,
capture_target: Option<&ScreenCaptureTarget>,
+ stored_desktop_background_path: Option<String>,
) -> ProjectConfiguration {
let settings = GeneralSettingsStore::get(app)
.unwrap_or(None)
@@ -2914,7 +3149,13 @@ fn project_config_from_recording(
let using_default_config = default_config.is_none();
let mut config = default_config.unwrap_or_default();
config.cursor.size = cap_project::CursorConfiguration::default().size;
- apply_recording_presentation_defaults(app, &mut config, capture_target, using_default_config);
+ apply_recording_presentation_defaults(
+ app,
+ &mut config,
+ capture_target,
+ using_default_config,
+ stored_desktop_background_path,
+ );
let camera_preview_manager = CameraPreviewManager::new(app);
if let Ok(camera_preview_state) = camera_preview_manager.get_state() {
@@ -2974,12 +3215,15 @@ fn apply_recording_presentation_defaults(
config: &mut ProjectConfiguration,
capture_target: Option<&ScreenCaptureTarget>,
using_default_config: bool,
+ stored_desktop_background_path: Option<String>,
) {
let default_wallpaper_path = if using_default_config {
- app.path()
- .resolve("assets/backgrounds/cities/sf.jpg", BaseDirectory::Resource)
- .ok()
- .map(|path| path.to_string_lossy().into_owned())
+ stored_desktop_background_path.or_else(|| {
+ app.path()
+ .resolve("assets/backgrounds/cities/sf.jpg", BaseDirectory::Resource)
+ .ok()
+ .map(|path| path.to_string_lossy().into_owned())
+ })
} else {
None
};
@@ -2992,6 +3236,8 @@ fn apply_recording_presentation_defaults(
);
}
+const DEFAULT_SCREEN_RECORDING_BACKGROUND_ROUNDING_PERCENT: f64 = 7.5;
+
fn apply_screen_recording_presentation_defaults(
config: &mut ProjectConfiguration,
capture_target: Option<&ScreenCaptureTarget>,
@@ -3024,7 +3270,7 @@ fn apply_screen_recording_presentation_defaults(
Some(ScreenCaptureTarget::Window { .. } | ScreenCaptureTarget::Display { .. })
) && config.background.rounding <= f64::EPSILON
{
- config.background.rounding = 2.0;
+ config.background.rounding = DEFAULT_SCREEN_RECORDING_BACKGROUND_ROUNDING_PERCENT;
}
if (config.screen_movement_spring.stiffness - 120.0).abs() < f32::EPSILON
@@ -3419,7 +3665,7 @@ mod tests {
);
assert_eq!(config.background.padding, 10.0);
- assert_eq!(config.background.rounding, 2.0);
+ assert_eq!(config.background.rounding, 7.5);
assert!(matches!(
config.background.source,
cap_project::BackgroundSource::Wallpaper { path: Some(path) } if path == "wallpaper.jpg"
@@ -3440,7 +3686,7 @@ mod tests {
Some("wallpaper.jpg".to_string()),
);
- assert_eq!(config.background.rounding, 2.0);
+ assert_eq!(config.background.rounding, 7.5);
assert!(config.background.border.is_none());
}