Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(desktop): preserve clipboard, deep links, and app switching
Richie McIlroy95f7443de628
diff --git a/apps/desktop/src-tauri/src/gpui_app.rs b/apps/desktop/src-tauri/src/gpui_app.rsindex b5be66ddf..43de84e91 100644--- a/apps/desktop/src-tauri/src/gpui_app.rs+++ b/apps/desktop/src-tauri/src/gpui_app.rs@@ -8,8 +8,8 @@//! relaunch.//!//! The binary is discovered in order: `CAP_GPUI_BIN` (explicit override), the-//! bundled `gpui/` resource dir (staged by the release pipeline; absent in-//! builds that don't ship it), and -- in debug builds only -- the sibling+//! installed executable directory (where Tauri bundles and signs sidecars), the+//! legacy `gpui/` resource dir, and -- in debug builds only -- the sibling//! `apps/desktop-gpui` target dir, so the toggle works from a source checkout.//!//! ## The handoff marker@@ -35,6 +35,47 @@ const BINARY_NAME: &str = "cap-gpui.exe";#[cfg(not(windows))]const BINARY_NAME: &str = "cap-gpui";+#[cfg(any(target_os = "macos", windows, test))]+const MAX_FORWARDED_DEEP_LINK_BYTES: usize = 1024 * 1024;++#[cfg(any(target_os = "macos", windows, test))]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct GpuiForwardingEndpoint {+ pid: u32,+ port: u16,+ secret: u64,+}++#[cfg(any(target_os = "macos", test))]+#[derive(Default)]+pub(crate) struct StartupRedirectState(std::sync::atomic::AtomicU8);++#[cfg(any(target_os = "macos", test))]+impl StartupRedirectState {+ pub(crate) fn begin_forwarding(&self) -> bool {+ self.transition(0, 1)+ }++ pub(crate) fn exit_if_pending(&self) -> bool {+ self.transition(0, 2)+ }++ pub(crate) fn exit_after_forwarding(&self) -> bool {+ self.transition(1, 2)+ }++ fn transition(&self, from: u8, to: u8) -> bool {+ self.0+ .compare_exchange(+ from,+ to,+ std::sync::atomic::Ordering::AcqRel,+ std::sync::atomic::Ordering::Acquire,+ )+ .is_ok()+ }+}+fn existing_file(path: PathBuf) -> Option<PathBuf> {path.is_file().then_some(path)}@@ -46,6 +87,13 @@ fn binary_path(app: &AppHandle) -> Option<PathBuf> {return Some(path);}+ if let Ok(executable) = std::env::current_exe()+ && let Some(parent) = executable.parent()+ && let Some(path) = existing_file(parent.join(BINARY_NAME))+ {+ return Some(path);+ }+if let Ok(resources) = app.path().resource_dir()&& let Some(path) = existing_file(resources.join("gpui").join(BINARY_NAME)){@@ -99,7 +147,6 @@ fn shared_data_dir() -> PathBuf {base}-#[cfg(unix)]fn gpui_pidfile() -> PathBuf {shared_data_dir().join("cap-gpui.pid")}@@ -172,6 +219,120 @@ fn handoff_marker() -> PathBuf {shared_data_dir().join("cap-gpui.handoff")}+fn update_handoff_marker() -> PathBuf {+ shared_data_dir().join("cap-gpui.update-handoff")+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct UpdateHandoff {+ pid: u32,+ simulated: bool,+}++fn parse_update_handoff(contents: &str) -> Option<UpdateHandoff> {+ let contents = contents.trim();+ let (pid, simulated) = match contents.strip_prefix("simulate:") {+ Some(pid) if cfg!(debug_assertions) => (pid, true),+ Some(_) => return None,+ None => (contents, false),+ };+ let pid = pid.parse().ok()?;+ (pid != 0).then_some(UpdateHandoff { pid, simulated })+}++fn take_update_handoff() -> Option<bool> {+ let marker = update_handoff_marker();+ let contents = match std::fs::read_to_string(&marker) {+ Ok(contents) => contents,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return None,+ Err(error) => {+ warn!(%error, "could not read the Cap GPUI update hand-off");+ return None;+ }+ };++ let Some(handoff) = parse_update_handoff(&contents) else {+ warn!("discarding an invalid Cap GPUI update hand-off");+ let _ = std::fs::remove_file(&marker);+ return None;+ };++ let expected_pid = std::fs::read_to_string(gpui_pidfile())+ .ok()+ .and_then(|contents| contents.trim().parse::<u32>().ok());+ let stale = marker+ .metadata()+ .ok()+ .and_then(|metadata| metadata.modified().ok())+ .and_then(|modified| modified.elapsed().ok())+ .is_some_and(|age| age > std::time::Duration::from_secs(15 * 60));+ if expected_pid.is_some_and(|pid| pid != handoff.pid) || stale {+ warn!(+ pid = handoff.pid,+ "discarding a stale Cap GPUI update hand-off"+ );+ let _ = std::fs::remove_file(&marker);+ return None;+ }++ match std::fs::remove_file(&marker) {+ Ok(()) => {+ info!(+ pid = handoff.pid,+ "taking ownership from Cap GPUI for an update check"+ );+ Some(handoff.simulated)+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,+ Err(error) => {+ warn!(%error, "could not consume the Cap GPUI update hand-off");+ None+ }+ }+}++fn show_update_page_when_ready(app: AppHandle, simulated: bool) {+ tauri::async_runtime::spawn(async move {+ for _ in 0..300 {+ if let Some(window) = app+ .get_webview_window("main")+ .or_else(|| app.get_webview_window("onboarding"))+ {+ match window.url() {+ Ok(mut url) => {+ url.set_path("/update");+ url.set_query(Some(if simulated {+ "source=gpui&simulateUpdate=1"+ } else {+ "source=gpui"+ }));+ if let Err(error) = window.navigate(url) {+ warn!(%error, "could not open the updater after the GPUI hand-off");+ } else {+ let _ = window.show();+ let _ = window.set_focus();+ }+ }+ Err(error) => {+ warn!(%error, "could not read the window URL for the GPUI updater");+ }+ }+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ warn!("no window became ready for the GPUI update hand-off");+ });+}++pub(crate) fn handle_update_handoff(app: &AppHandle) -> bool {+ let Some(simulated) = take_update_handoff() else {+ return false;+ };+ show_update_page_when_ready(app.clone(), simulated);+ true+}+/// The dev switch-back's readiness handshake (`store::classic_pending_path`/// in apps/desktop-gpui): `cap-gpui` writes this and stays on screen until the/// classic app deletes it, so a minutes-long dev rebuild never leaves the user@@ -185,30 +346,190 @@ fn classic_pending() -> PathBuf {/// kills the previous process, so a handoff that relaunched unconditionally/// would restart a session the user may be recording in.fn running_instance_pid() -> Option<u32> {+ let pid = std::fs::read_to_string(gpui_pidfile())+ .ok()?+ .trim()+ .parse::<u32>()+ .ok()?;+#[cfg(unix)]{- let pid = std::fs::read_to_string(gpui_pidfile())- .ok()?- .trim()- .parse::<u32>()- .ok()?;let alive = std::process::Command::new("ps").args(["-p", &pid.to_string(), "-o", "comm="]).output().is_ok_and(|output| {output.status.success()- && String::from_utf8_lossy(&output.stdout).contains("cap-gpui")+ && is_gpui_process_image(std::path::Path::new(+ String::from_utf8_lossy(&output.stdout).trim(),+ ))});alive.then_some(pid)}- #[cfg(not(unix))]++ #[cfg(windows)]{- None+ let process_id = sysinfo::Pid::from_u32(pid);+ let mut system = sysinfo::System::new();+ system.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[process_id]), true);+ system+ .process(process_id)+ .and_then(sysinfo::Process::exe)+ .is_some_and(is_gpui_process_image)+ .then_some(pid)}}+fn is_gpui_process_image(path: &std::path::Path) -> bool {+ path.file_name()+ .and_then(std::ffi::OsStr::to_str)+ .is_some_and(|name| name.eq_ignore_ascii_case(BINARY_NAME))+}++#[cfg(any(target_os = "macos", windows, test))]+fn parse_gpui_forwarding_endpoint(contents: &str) -> Option<GpuiForwardingEndpoint> {+ let mut parts = contents.trim().split(':');+ let pid = parts.next()?.parse().ok()?;+ let port = parts.next()?.parse().ok()?;+ let secret = u64::from_str_radix(parts.next()?, 16).ok()?;+ (pid != 0 && port != 0 && parts.next().is_none()).then_some(GpuiForwardingEndpoint {+ pid,+ port,+ secret,+ })+}++#[cfg(any(target_os = "macos", windows, test))]+fn is_forwardable_gpui_deep_link(url: &str) -> bool {+ !url.is_empty()+ && url.len() <= MAX_FORWARDED_DEEP_LINK_BYTES+ && reqwest::Url::parse(url)+ .is_ok_and(|parsed| matches!(parsed.scheme(), "cap-desktop" | "cap"))+}++#[cfg(any(target_os = "macos", windows, test))]+fn forwarded_gpui_argument(argument: &str) -> Option<String> {+ if is_forwardable_gpui_deep_link(argument) {+ return Some(argument.to_string());+ }++ let path = match reqwest::Url::parse(argument) {+ Ok(url) if url.scheme() == "file" => url.to_file_path().ok()?,+ _ => PathBuf::from(argument),+ };+ if !path+ .extension()+ .and_then(std::ffi::OsStr::to_str)+ .is_some_and(|extension| extension.eq_ignore_ascii_case("cap"))+ {+ return None;+ }++ let metadata = std::fs::symlink_metadata(&path).ok()?;+ if metadata.file_type().is_symlink() || !metadata.is_dir() {+ return None;+ }+ let path = path.canonicalize().ok()?;+ let value = serde_json::json!({ "open_editor": { "project_path": path } }).to_string();+ let mut url = reqwest::Url::parse("cap-desktop://action").ok()?;+ url.query_pairs_mut().append_pair("value", &value);+ let url = url.to_string();+ is_forwardable_gpui_deep_link(&url).then_some(url)+}++#[cfg(any(target_os = "macos", windows))]+fn forward_deep_links_to_gpui(pid: u32, args: &[String]) -> bool {+ use std::io::Write;++ let urls = args+ .iter()+ .filter_map(|argument| forwarded_gpui_argument(argument))+ .collect::<Vec<_>>();+ if urls.is_empty() {+ return false;+ }++ let endpoint_path = gpui_pidfile().with_extension("ipc");+ let endpoint = (0..40).find_map(|attempt| {+ let endpoint = std::fs::read_to_string(&endpoint_path)+ .ok()+ .and_then(|contents| parse_gpui_forwarding_endpoint(&contents))+ .filter(|endpoint| endpoint.pid == pid);+ if endpoint.is_none() && attempt < 39 {+ std::thread::sleep(std::time::Duration::from_millis(50));+ }+ endpoint+ });+ let Some(endpoint) = endpoint else {+ warn!(pid, "could not find the Cap GPUI deep-link endpoint");+ return false;+ };++ let mut forwarded = false;+ for url in urls {+ let result = std::net::TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, endpoint.port))+ .and_then(|mut stream| {+ stream.set_write_timeout(Some(std::time::Duration::from_secs(2)))?;+ stream.write_all(&endpoint.secret.to_be_bytes())?;+ stream.write_all(&(url.len() as u32).to_be_bytes())?;+ stream.write_all(url.as_bytes())+ });+ match result {+ Ok(()) => forwarded = true,+ Err(error) => warn!(%error, "could not forward a deep link to Cap GPUI"),+ }+ }++ forwarded+}++#[cfg(any(target_os = "macos", windows))]+pub(crate) fn forward_deep_links_to_active_gpui(app: &AppHandle, args: &[String]) -> bool {+ let own = GeneralSettingsStore::get(app)+ .ok()+ .flatten()+ .is_some_and(|settings| settings.enable_gpui_app);+ let enabled = if own_store_is_shared(app) {+ own+ } else {+ shared_store_flag().unwrap_or(false)+ };+ if !enabled {+ return false;+ }++ let Some(pid) = running_instance_pid() else {+ return false;+ };+ if !forward_deep_links_to_gpui(pid, args) {+ return false;+ }++ activate_instance(pid);+ true+}+#[cfg(target_os = "macos")]-fn activate_instance(pid: u32) {+pub(crate) fn forward_deep_links_to_gpui_when_ready(args: &[String]) -> Option<u32> {+ if !args+ .iter()+ .any(|argument| forwarded_gpui_argument(argument).is_some())+ {+ return None;+ }++ let pid = (0..40).find_map(|attempt| {+ let pid = running_instance_pid();+ if pid.is_none() && attempt < 39 {+ std::thread::sleep(std::time::Duration::from_millis(50));+ }+ pid+ })?;++ forward_deep_links_to_gpui(pid, args).then_some(pid)+}++#[cfg(target_os = "macos")]+pub(crate) fn activate_instance(pid: u32) {use objc2_app_kit::{NSApplicationActivationOptions, NSRunningApplication};if let Some(instance) =@@ -220,7 +541,61 @@ fn activate_instance(pid: u32) {}}-#[cfg(not(target_os = "macos"))]+#[cfg(windows)]+fn activate_instance(pid: u32) {+ use windows::{+ Win32::{+ Foundation::{HWND, LPARAM, TRUE},+ UI::WindowsAndMessaging::{+ EnumWindows, GetWindowThreadProcessId, IsWindowVisible, SW_RESTORE,+ SetForegroundWindow, ShowWindow,+ },+ },+ core::BOOL,+ };++ struct Activation {+ pid: u32,+ visible: Option<HWND>,+ fallback: Option<HWND>,+ }++ unsafe extern "system" fn find_window(window: HWND, data: LPARAM) -> BOOL {+ let activation = unsafe { &mut *(data.0 as *mut Activation) };+ let mut owner = 0;+ unsafe { GetWindowThreadProcessId(window, Some(&mut owner)) };+ if owner == activation.pid {+ if activation.fallback.is_none() {+ activation.fallback = Some(window);+ }+ if activation.visible.is_none() && unsafe { IsWindowVisible(window) }.as_bool() {+ activation.visible = Some(window);+ }+ }+ TRUE+ }++ let mut activation = Activation {+ pid,+ visible: None,+ fallback: None,+ };+ let _ = unsafe {+ EnumWindows(+ Some(find_window),+ LPARAM(std::ptr::addr_of_mut!(activation) as isize),+ )+ };++ if let Some(window) = activation.visible.or(activation.fallback) {+ unsafe {+ let _ = ShowWindow(window, SW_RESTORE);+ let _ = SetForegroundWindow(window);+ }+ }+}++#[cfg(not(any(target_os = "macos", windows)))]fn activate_instance(_pid: u32) {}fn write_handoff_marker() {@@ -244,7 +619,7 @@ fn write_handoff_marker() {/// second after launch. Its output goes to a file instead of `/dev/null`/// because a handoff launch has no terminal, and a startup failure there is/// only ever diagnosable from that file.-fn spawn_detached(path: &std::path::Path) -> Result<(), String> {+fn spawn_detached(path: &std::path::Path, args: &[String]) -> Result<(), String> {use std::process::Stdio;let log_path = shared_data_dir().join("cap-gpui.log");@@ -267,7 +642,11 @@ fn spawn_detached(path: &std::path::Path) -> Result<(), String> {};let mut command = std::process::Command::new(path);- command.stdin(Stdio::null()).stdout(stdout).stderr(stderr);+ command+ .args(args)+ .stdin(Stdio::null())+ .stdout(stdout)+ .stderr(stderr);// Its own process group, so signals aimed at the terminal this app was// started from never reach the app that outlives it.#[cfg(unix)]@@ -309,6 +688,11 @@ pub async fn switch_to_gpui_app("Wait for your export to finish before switching to the native app.".to_string(),);}+ if crate::upload::upload_session_active() {+ return Err(+ "Wait for your upload to finish before switching to the native app.".to_string(),+ );+ }let path =binary_path(&app).ok_or_else(|| "Cap GPUI isn't included in this build".to_string())?;@@ -327,7 +711,7 @@ pub async fn switch_to_gpui_app(None => {write_handoff_marker();info!(path = %path.display(), "handing off to Cap GPUI");- if let Err(error) = spawn_detached(&path) {+ if let Err(error) = spawn_detached(&path, &[]) {let _ = std::fs::remove_file(handoff_marker());if !own_store_is_shared(&app) {write_shared_store_flag(false);@@ -345,15 +729,18 @@ pub async fn switch_to_gpui_app(////// `true` means the caller must exit before any window is created.pub fn redirect_at_startup_if_enabled(app: &AppHandle) -> bool {- let redirect = redirect_decision(app);+ let update_handoff = handle_update_handoff(app);+ let redirect = !update_handoff && redirect_decision(app);if !redirect {// Staying up IS the readiness signal the waiting `cap-gpui` needs --// and the wait can begin while this app is ALREADY running (switching// back with both apps up), so the signal has to keep firing, not just// fire once at startup.- tauri::async_runtime::spawn(async {+ let app = app.clone();+ tauri::async_runtime::spawn(async move {loop {let _ = std::fs::remove_file(classic_pending());+ handle_update_handoff(&app);tokio::time::sleep(std::time::Duration::from_secs(1)).await;}});@@ -395,6 +782,11 @@ fn redirect_decision(app: &AppHandle) -> bool {// before proving itself, the marker survives it and the next launch heals.if let Some(pid) = running_instance_pid() {info!(pid, "Cap GPUI is already running; handing over to it");+ #[cfg(any(target_os = "macos", windows))]+ {+ let args = std::env::args().skip(1).collect::<Vec<_>>();+ forward_deep_links_to_gpui(pid, &args);+ }activate_instance(pid);return true;}@@ -426,10 +818,185 @@ fn redirect_decision(app: &AppHandle) -> bool {write_handoff_marker();info!(path = %path.display(), "handing off to Cap GPUI at startup");- if let Err(error) = spawn_detached(&path) {+ #[cfg(any(target_os = "macos", windows))]+ let args = std::env::args()+ .skip(1)+ .filter_map(|argument| forwarded_gpui_argument(&argument))+ .collect::<Vec<_>>();+ #[cfg(not(any(target_os = "macos", windows)))]+ let args = Vec::new();+ if let Err(error) = spawn_detached(&path, &args) {warn!("{error}");let _ = std::fs::remove_file(handoff_marker());return false;}true}++#[cfg(test)]+mod tests {+ use super::{+ BINARY_NAME, GpuiForwardingEndpoint, MAX_FORWARDED_DEEP_LINK_BYTES, StartupRedirectState,+ UpdateHandoff, forwarded_gpui_argument, is_forwardable_gpui_deep_link,+ is_gpui_process_image, parse_gpui_forwarding_endpoint, parse_update_handoff,+ };++ #[test]+ fn startup_redirect_exits_once_when_no_open_event_arrives() {+ let state = StartupRedirectState::default();++ assert!(state.exit_if_pending());+ assert!(!state.exit_if_pending());+ assert!(!state.begin_forwarding());+ assert!(!state.exit_after_forwarding());+ }++ #[test]+ fn startup_redirect_waits_for_forwarding_before_exiting_once() {+ let state = StartupRedirectState::default();++ assert!(state.begin_forwarding());+ assert!(!state.begin_forwarding());+ assert!(!state.exit_if_pending());+ assert!(state.exit_after_forwarding());+ assert!(!state.exit_after_forwarding());+ }++ #[test]+ fn update_handoff_requires_a_valid_process_id() {+ assert_eq!(+ parse_update_handoff("1234"),+ Some(UpdateHandoff {+ pid: 1234,+ simulated: false,+ })+ );+ assert_eq!(parse_update_handoff("0"), None);+ assert_eq!(parse_update_handoff("cap-gpui"), None);+ assert_eq!(parse_update_handoff("simulate:0"), None);+ }++ #[test]+ fn simulated_update_handoffs_are_debug_only() {+ let parsed = parse_update_handoff("simulate:4321");+ if cfg!(debug_assertions) {+ assert_eq!(+ parsed,+ Some(UpdateHandoff {+ pid: 4321,+ simulated: true,+ })+ );+ } else {+ assert_eq!(parsed, None);+ }+ }++ #[test]+ fn gpui_process_image_must_match_exactly() {+ assert!(is_gpui_process_image(std::path::Path::new(BINARY_NAME)));+ assert!(is_gpui_process_image(std::path::Path::new(+ &BINARY_NAME.to_ascii_uppercase()+ )));+ assert!(!is_gpui_process_image(std::path::Path::new("not-cap-gpui")));+ assert!(!is_gpui_process_image(std::path::Path::new(+ "cap-gpui-helper"+ )));+ }++ #[test]+ fn gpui_forwarding_endpoint_requires_the_owner_identity() {+ assert_eq!(+ parse_gpui_forwarding_endpoint("4321:49152:0123456789abcdef"),+ Some(GpuiForwardingEndpoint {+ pid: 4321,+ port: 49152,+ secret: 0x0123_4567_89ab_cdef,+ })+ );+ assert_eq!(parse_gpui_forwarding_endpoint("0:49152:1234"), None);+ assert_eq!(parse_gpui_forwarding_endpoint("4321:0:1234"), None);+ assert_eq!(parse_gpui_forwarding_endpoint("4321:49152:xyz"), None);+ assert_eq!(+ parse_gpui_forwarding_endpoint("4321:49152:1234:extra"),+ None+ );+ }++ #[test]+ fn forwarded_gpui_deep_links_are_scheme_and_size_limited() {+ assert!(is_forwardable_gpui_deep_link(+ "cap-desktop://signin?token=test"+ ));+ assert!(is_forwardable_gpui_deep_link(+ "cap://action?value=%22stop_recording%22"+ ));+ assert!(!is_forwardable_gpui_deep_link("https://cap.so/signin"));+ assert!(!is_forwardable_gpui_deep_link("cap-desktop-other://signin"));+ assert!(!is_forwardable_gpui_deep_link(&format!(+ "cap://action?value={}",+ "x".repeat(MAX_FORWARDED_DEEP_LINK_BYTES)+ )));+ }++ #[test]+ fn project_arguments_become_encoded_open_editor_actions() {+ let directory = tempfile::tempdir().unwrap();+ let project = directory.path().join("Recording #1 & draft.cap");+ std::fs::create_dir(&project).unwrap();++ let forwarded = forwarded_gpui_argument(project.to_str().unwrap()).unwrap();+ let url = reqwest::Url::parse(&forwarded).unwrap();+ let value = url+ .query_pairs()+ .find_map(|(key, value)| (key == "value").then_some(value.into_owned()))+ .unwrap();+ let action: serde_json::Value = serde_json::from_str(&value).unwrap();++ assert_eq!(url.scheme(), "cap-desktop");+ assert_eq!(url.host_str(), Some("action"));+ assert_eq!(+ action["open_editor"]["project_path"],+ project.canonicalize().unwrap().to_string_lossy().as_ref()+ );+ }++ #[test]+ fn forwarded_project_arguments_reject_missing_and_non_project_paths() {+ let directory = tempfile::tempdir().unwrap();+ let ordinary = directory.path().join("notes.txt");+ std::fs::write(&ordinary, "notes").unwrap();++ assert!(forwarded_gpui_argument(ordinary.to_str().unwrap()).is_none());+ assert!(+ forwarded_gpui_argument(directory.path().join("missing.cap").to_str().unwrap())+ .is_none()+ );+ assert_eq!(+ forwarded_gpui_argument("cap-desktop://signin?token=secret"),+ Some("cap-desktop://signin?token=secret".to_string())+ );+ }++ #[cfg(unix)]+ #[test]+ fn forwarded_project_arguments_reject_symlinks() {+ let directory = tempfile::tempdir().unwrap();+ let project = directory.path().join("Recording.cap");+ let symlink = directory.path().join("Shortcut.cap");+ std::fs::create_dir(&project).unwrap();+ std::os::unix::fs::symlink(&project, &symlink).unwrap();++ assert!(forwarded_gpui_argument(symlink.to_str().unwrap()).is_none());+ }++ #[test]+ fn file_urls_become_open_editor_actions() {+ let directory = tempfile::tempdir().unwrap();+ let project = directory.path().join("Recording.cap");+ std::fs::create_dir(&project).unwrap();+ let file_url = reqwest::Url::from_file_path(&project).unwrap();++ assert!(forwarded_gpui_argument(file_url.as_str()).is_some());+ }+}diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex d15821788..692dd7327 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -70,8 +70,12 @@ use cap_recording::{sources::screen_capture::ScreenCaptureTarget,};use cap_rendering::ProjectRecordingsMeta;+use clipboard_rs::Clipboard;+#[cfg(not(target_os = "linux"))]+use clipboard_rs::ClipboardContext;+#[cfg(target_os = "linux")]+use clipboard_rs::ClipboardContext as PlatformClipboardContext;use clipboard_rs::common::RustImage;-use clipboard_rs::{Clipboard, ClipboardContext};use cpal::StreamError;use editor_window::{EditorInstances, PendingEditorInstances, WindowEditorInstance};use ffmpeg::ffi::AV_TIME_BASE;@@ -107,6 +111,8 @@ use std::{};use tauri::Listener;use tauri::{AppHandle, Emitter, Manager, State, Window, WindowEvent, ipc::Channel};+#[cfg(target_os = "linux")]+use tauri_plugin_clipboard_manager::ClipboardExt;use tauri_plugin_deep_link::DeepLinkExt;use tauri_plugin_dialog::DialogExt;use tauri_plugin_global_shortcut::GlobalShortcutExt;@@ -203,6 +209,22 @@ mod tests {);}+ #[cfg(target_os = "linux")]+ #[test]+ fn wayland_clipboard_fallback_requires_wayland_without_x11() {+ use std::ffi::OsStr;++ assert!(uses_wayland_clipboard_fallback(+ Some(OsStr::new("wayland-1")),+ None+ ));+ assert!(!uses_wayland_clipboard_fallback(+ Some(OsStr::new("wayland-1")),+ Some(OsStr::new(":0"))+ ));+ assert!(!uses_wayland_clipboard_fallback(None, None));+ }+#[test]fn graphics_recovery_only_engages_for_gpu_init_deaths() {use crash_sentinel::UnexpectedTermination;@@ -320,23 +342,38 @@ impl CameraWindowCloseGate {}}-pub struct AppExitState(AtomicBool);+pub struct AppExitState {+ exiting: AtomicBool,+ restarting: AtomicBool,+}impl Default for AppExitState {fn default() -> Self {- Self(AtomicBool::new(false))+ Self {+ exiting: AtomicBool::new(false),+ restarting: AtomicBool::new(false),+ }}}impl AppExitState {pub fn begin(&self) -> bool {- self.0+ self.exiting.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_ok()}+ pub fn begin_restart(&self) {+ self.restarting.store(true, Ordering::Release);+ self.exiting.store(true, Ordering::Release);+ }+pub fn is_exiting(&self) -> bool {- self.0.load(Ordering::Acquire)+ self.exiting.load(Ordering::Acquire)+ }++ pub fn is_restarting(&self) -> bool {+ self.restarting.load(Ordering::Acquire)}}@@ -1752,6 +1789,12 @@ async fn get_devices_snapshot() -> DevicesUpdated {}}+fn any_webview_window_visible(app: &AppHandle) -> bool {+ app.webview_windows()+ .values()+ .any(|window| window.is_visible().unwrap_or(false))+}+fn spawn_devices_snapshot_emitter(app_handle: AppHandle) {tokio::spawn(async move {let mut last_perm_tuple: (u8, u8, u8, u8) = (255, 255, 255, 255);@@ -1768,6 +1811,11 @@ fn spawn_devices_snapshot_emitter(app_handle: AppHandle) {continue;}+ if !any_webview_window_visible(&app_handle) {+ tokio::time::sleep(std::time::Duration::from_secs(5)).await;+ continue;+ }+let permissions = permissions::do_permissions_check(false);let Some((cameras, microphones)) = collect_device_inventory(|| app_is_exiting(&app_handle),@@ -2476,6 +2524,83 @@ pub struct NewNotification {type ArcLock<T> = Arc<RwLock<T>>;pub type MutableState<'a, T> = State<'a, Arc<RwLock<T>>>;+#[cfg(target_os = "linux")]+pub enum ClipboardContext {+ Platform(PlatformClipboardContext),+ Wayland(AppHandle),+}++#[cfg(target_os = "linux")]+fn uses_wayland_clipboard_fallback(+ wayland_display: Option<&std::ffi::OsStr>,+ x11_display: Option<&std::ffi::OsStr>,+) -> bool {+ wayland_display.is_some() && x11_display.is_none()+}++#[cfg(target_os = "linux")]+impl ClipboardContext {+ fn new(app: &AppHandle) -> clipboard_rs::common::Result<Self> {+ match PlatformClipboardContext::new() {+ Ok(context) => Ok(Self::Platform(context)),+ Err(error)+ if uses_wayland_clipboard_fallback(+ std::env::var_os("WAYLAND_DISPLAY").as_deref(),+ std::env::var_os("DISPLAY").as_deref(),+ ) =>+ {+ info!(%error, "Using native Wayland clipboard");+ Ok(Self::Wayland(app.clone()))+ }+ Err(error) => Err(error),+ }+ }++ fn set_text(&self, text: String) -> clipboard_rs::common::Result<()> {+ match self {+ Self::Platform(context) => context.set_text(text),+ Self::Wayland(app) => app.clipboard().write_text(text).map_err(Into::into),+ }+ }++ fn set_image(&self, image: clipboard_rs::RustImageData) -> clipboard_rs::common::Result<()> {+ match self {+ Self::Platform(context) => context.set_image(image),+ Self::Wayland(app) => {+ let rgba = image.to_rgba8()?;+ let width = rgba.width();+ let height = rgba.height();+ let image = tauri::image::Image::new_owned(rgba.into_raw(), width, height);+ app.clipboard().write_image(&image).map_err(Into::into)+ }+ }+ }++ fn set_files(&self, files: Vec<String>) -> clipboard_rs::common::Result<()> {+ match self {+ Self::Platform(context) => context.set_files(files),+ Self::Wayland(app) => {+ let urls = files+ .into_iter()+ .map(|path| {+ tauri::Url::from_file_path(&path)+ .map(|url| url.to_string())+ .map_err(|()| format!("Invalid clipboard file path: {path}"))+ })+ .collect::<Result<Vec<_>, _>>()?;++ if urls.is_empty() {+ return Err("No files supplied for clipboard".into());+ }++ app.clipboard()+ .write_text(urls.join("\r\n"))+ .map_err(Into::into)+ }+ }+ }+}+type SingleTuple<T> = (T,);#[derive(Serialize, Type)]@@ -4741,9 +4866,7 @@ pub async fn open_target_picker() {use tauri::Manager;- if let Some(window) = CapWindowId::Main.get(app) {- window.hide().ok();- }+ hide_main_window(app);let state = app.state::<target_select_overlay::WindowFocusManager>();let display_id = None;@@ -5196,7 +5319,16 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {#[cfg(not(target_os = "linux"))]{builder = builder.plugin(tauri_plugin_single_instance::init(|app, args, _cwd| {- trace!("Single instance invoked with args {args:?}");+ trace!(arg_count = args.len(), "Single instance invoked");++ if gpui_app::handle_update_handoff(app) {+ return;+ }++ #[cfg(any(target_os = "macos", windows))]+ if gpui_app::forward_deep_links_to_active_gpui(app, &args) {+ return;+ }let action_urls = args.iter()@@ -5301,7 +5433,6 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {}specta_builder.mount_events(&app);- hotkeys::init(&app);general_settings::init(&app);// Before anything shows a window or initialises further state: when// the native app owns the session, this one only exists to start it.@@ -5313,9 +5444,28 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {exit_state.begin();app.manage(exit_state);crash_sentinel::mark_clean_exit();++ #[cfg(target_os = "macos")]+ {+ app.manage(gpui_app::StartupRedirectState::default());+ let app = app.clone();+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(750)).await;+ if app+ .try_state::<gpui_app::StartupRedirectState>()+ .is_some_and(|state| state.exit_if_pending())+ {+ app.exit(0);+ }+ });+ }++ #[cfg(not(target_os = "macos"))]app.exit(0);+return Ok(());}+ hotkeys::init(&app);configure_camera_blur_recovery(&app, previous_termination);fake_window::init(&app);app.manage(target_select_overlay::WindowFocusManager::default());@@ -5456,9 +5606,13 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {install_macos_native_terminate_handler(&app);spawn_process_memory_sampler(app.clone());- app.manage(Arc::new(RwLock::new(- ClipboardContext::new().expect("Failed to create clipboard context"),- )));+ #[cfg(target_os = "linux")]+ let clipboard = ClipboardContext::new(&app)+ .expect("Failed to create clipboard context");+ #[cfg(not(target_os = "linux"))]+ let clipboard = ClipboardContext::new()+ .expect("Failed to create clipboard context");+ app.manage(Arc::new(RwLock::new(clipboard)));}app.listen_any("main-window-ready", {@@ -5665,7 +5819,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {}CapWindowId::Main => {api.prevent_close();- let _ = window.hide();+ hide_main_window(app);#[cfg(target_os = "macos")]crate::permissions::schedule_macos_dock_visibility_sync(app);@@ -6106,8 +6260,70 @@ wherefn handle_run_event(_handle: &AppHandle, event: tauri::RunEvent) {match event {+ #[cfg(target_os = "macos")]+ tauri::RunEvent::Opened { urls } => {+ let arguments = urls+ .iter()+ .map(|url| url.as_str().to_string())+ .collect::<Vec<_>>();++ if let Some(redirect) = _handle.try_state::<gpui_app::StartupRedirectState>() {+ if redirect.begin_forwarding() {+ let app = _handle.clone();+ tokio::spawn(async move {+ let forwarded = tokio::task::spawn_blocking(move || {+ gpui_app::forward_deep_links_to_gpui_when_ready(&arguments)+ })+ .await+ .ok()+ .flatten();++ if let Some(pid) = forwarded {+ if let Err(error) = app.run_on_main_thread(move || {+ gpui_app::activate_instance(pid);+ }) {+ warn!(%error, "Could not activate Cap GPUI after forwarding a project");+ }+ } else {+ warn!("Could not forward the requested project to Cap GPUI");+ }+ if app+ .try_state::<gpui_app::StartupRedirectState>()+ .is_some_and(|state| state.exit_after_forwarding())+ {+ app.exit(0);+ }+ });+ }+ return;+ }++ if gpui_app::forward_deep_links_to_active_gpui(_handle, &arguments) {+ return;+ }++ for url in urls {+ if url.scheme() == "file"+ && let Ok(path) = url.to_file_path()+ && let Err(error) = open_project_from_path(&path, _handle.clone())+ {+ warn!(path = %path.display(), %error, "Could not open the requested project");+ }+ }+ }#[cfg(target_os = "macos")]tauri::RunEvent::Reopen { .. } => {+ if _handle+ .try_state::<gpui_app::StartupRedirectState>()+ .is_some()+ {+ return;+ }++ if gpui_app::handle_update_handoff(_handle) {+ return;+ }+let should_focus_onboarding = should_show_onboarding(_handle);if should_focus_onboarding@@ -6159,12 +6375,12 @@ fn handle_run_event(_handle: &AppHandle, event: tauri::RunEvent) {_handle.try_state::<AppExitState>().is_some_and(|state| state.is_exiting()),- export::export_session_active(),+ export::export_session_active() || upload::upload_session_active(),code.is_some(),+ code == Some(tauri::RESTART_EXIT_CODE),|| api.prevent_exit(),) {ExitRequestDecision::StartCleanup => {- let _ = code;let handle = _handle.clone();spawn_on_runtime(async move {request_app_exit(handle).await;@@ -6172,19 +6388,36 @@ fn handle_run_event(_handle: &AppHandle, event: tauri::RunEvent) {}ExitRequestDecision::AlreadyExiting => {}ExitRequestDecision::ExportActive => {- warn!("Preventing app exit request during active export");+ warn!("Preventing app exit request during an active export or upload");}ExitRequestDecision::AllowRuntimeExit => {}+ ExitRequestDecision::AllowRuntimeRestart => {+ if let Some(state) = _handle.try_state::<AppExitState>() {+ state.begin_restart();+ }+ crash_sentinel::mark_clean_exit();+ info!("Allowing Tauri to restart the app");+ }}}tauri::RunEvent::Exit => {#[cfg(target_os = "macos")]{// This arm runs on the AppKit main thread, so reverse the Liquid Glass- // SPI inline before the hard _exit. This is the last-chance teardown for- // terminal paths that skip cleanup_app_resources_for_exit; touching the- // NSWindow/NSView here is safe precisely because we are on main.+ // SPI inline before restart or a hard _exit. This is the last-chance+ // teardown for terminal paths that skip cleanup_app_resources_for_exit;+ // touching the NSWindow/NSView here is safe because we are on main.let torn_down = crate::platform::teardown_all_liquid_glass_on_main(_handle);+ if _handle+ .try_state::<AppExitState>()+ .is_some_and(|state| state.is_restarting())+ {+ info!(+ windows = torn_down,+ "macOS runtime exit reached; allowing Tauri to restart"+ );+ return;+ }warn!(windows = torn_down,"macOS runtime exit reached; tore down liquid glass, forcing process exit"@@ -6819,9 +7052,11 @@ fn show_import_error_dialog(app: &AppHandle, message: String) {.show(|_| {});}-fn hide_main_window(app: &AppHandle) {- if let Some(main_window) = CapWindowId::Main.get(app) {- let _ = main_window.hide();+pub(crate) fn hide_main_window(app: &AppHandle) {+ if let Some(main_window) = CapWindowId::Main.get(app)+ && main_window.hide().is_ok()+ {+ let _ = main_window.emit_to(CapWindowId::Main.label(), "main-window-hidden", ());}}@@ -6901,9 +7136,7 @@ fn open_project_from_path(path: &Path, app: AppHandle) -> Result<(), String> {let _ = app.opener().open_path(mp4_path.to_str().unwrap_or_default(), None::<String>);- if let Some(main_window) = CapWindowId::Main.get(&app) {- main_window.hide().ok();- }+ hide_main_window(&app);}}}diff --git a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsxindex 3beeea4d6..7e71765ed 100644--- a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx+++ b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx@@ -19,7 +19,6 @@ import {PhysicalPosition,} from "@tauri-apps/api/window";import * as dialog from "@tauri-apps/plugin-dialog";-import { relaunch } from "@tauri-apps/plugin-process";import * as shell from "@tauri-apps/plugin-shell";import { cx } from "cva";import {@@ -55,6 +54,7 @@ import {type MicrophoneWithDetails,} from "~/utils/devices";import { clientEnv } from "~/utils/env";+import { hideCurrentWindow } from "~/utils/hide-window";import {importImageFromPicker,importVideoFromPicker,@@ -86,6 +86,7 @@ import {type UploadProgress,} from "~/utils/tauri";import { openTeleprompter } from "~/utils/teleprompter";+import { restartAfterUpdate } from "~/utils/updater";import IconCapLogoFull from "~icons/cap/logo-full";import IconCapLogoFullDark from "~icons/cap/logo-full-dark";import IconLucideAppWindowMac from "~icons/lucide/app-window-mac";@@ -1741,6 +1742,7 @@ export default function () {}let hasChecked = false;+const [installingUpdate, setInstallingUpdate] = createSignal(false);function createUpdateCheck() {if (import.meta.env.DEV) return;@@ -1799,17 +1801,21 @@ function createUpdateReadyToast() {<div class="flex gap-2 items-center"><buttontype="button"- class="px-2.5 py-1 text-xs font-medium rounded-lg transition-colors bg-blue-9 text-white hover:bg-blue-10"+ disabled={installingUpdate()}+ class="px-2.5 py-1 text-xs font-medium rounded-lg transition-colors bg-blue-9 text-white hover:bg-blue-10 disabled:cursor-not-allowed disabled:opacity-60"onClick={() => {- toast.dismiss(t.id);- const install = update.installed- ? Promise.resolve(null)- : commands.updatesDownloadAndInstall();- // On Windows the NSIS installer restarts Cap itself, so the- // relaunch call is unreachable there; that matches update.tsx.- install- .then(() => relaunch())- .catch((e) => console.error("Failed to install update:", e));+ if (installingUpdate()) return;+ setInstallingUpdate(true);+ restartAfterUpdate()+ .catch((error) => {+ console.error("Failed to install update:", error);+ toast.error(+ typeof error === "string"+ ? error+ : "Unable to restart Cap safely.",+ );+ })+ .finally(() => setInstallingUpdate(false));}}>{update.installed ? "Restart now" : "Install and restart"}@@ -2024,7 +2030,7 @@ function Page() {if (pickerActive && !hasHidden && !recording) {setHasHiddenMainWindowForPicker(true);setShouldRevealMainWindowAfterPicker(!editorPicker);- void getCurrentWindow().hide();+ void hideCurrentWindow();} else if (pickerActive && hasHidden) {setShouldRevealMainWindowAfterPicker(!editorPicker);} else if (recording) {@@ -2922,7 +2928,7 @@ function Page() {await shell.open(link);}- await getCurrentWindow().hide();+ await hideCurrentWindow();};const openScreenshot = async (screenshot: ScreenshotWithPath) => {@@ -3224,7 +3230,7 @@ function Page() {type="button"onClick={async () => {await commands.showWindow({ Settings: { page: "general" } });- getCurrentWindow().hide();+ hideCurrentWindow();}}class="flex items-center justify-center size-5 focus:outline-hidden">@@ -3412,7 +3418,7 @@ function Page() {await commands.showWindow({Settings: { page: "recordings" },});- getCurrentWindow().hide();+ hideCurrentWindow();}}uploadProgress={uploadProgress}reuploadingPaths={reuploadingPaths()}@@ -3436,7 +3442,7 @@ function Page() {await commands.showWindow({Settings: { page: "screenshots" },});- getCurrentWindow().hide();+ hideCurrentWindow();}}/>) : variant === "camera" ? (diff --git a/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx b/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsxindex f21fcc5a3..126fd3323 100644--- a/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx+++ b/apps/desktop/src/routes/(window-chrome)/settings/experimental.tsx@@ -157,14 +157,7 @@ function Inner(props: {return (<div class="cap-settings-page flex flex-col h-full custom-scroll"><SettingsPageContent>- <Show- when={props.osType !== "windows"}- fallback={- <p class="text-xs leading-relaxed text-gray-10 px-1">- No experimental features are currently available on this platform.- </p>- }- >+ <Show when={props.osType === "macos"}><Section title="Preview"><SectionRows><ToggleSettingItem