Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(tauri): session-scoped camera windows and preview error events

Richie McIlroy0b23aefc42b8
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 865d58f95..c73eb8572 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -94,7 +94,7 @@ use std::{
time::{Duration, SystemTime, UNIX_EPOCH},
};
use tauri::Listener;
-use tauri::{AppHandle, Manager, State, Window, WindowEvent, ipc::Channel};
+use tauri::{AppHandle, Emitter, Manager, State, Window, WindowEvent, ipc::Channel};
use tauri_plugin_deep_link::DeepLinkExt;
use tauri_plugin_dialog::DialogExt;
use tauri_plugin_global_shortcut::GlobalShortcutExt;
@@ -370,6 +370,51 @@ pub struct VideoRecordingMetadata {
pub size: f64,
}
+const CAMERA_PREVIEW_ERROR_EVENT: &str = "camera-preview-error";
+const CAMERA_PREVIEW_CLEAR_EVENT: &str = "camera-preview-clear";
+
+#[derive(Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct CameraPreviewErrorPayload {
+ title: String,
+ message: String,
+}
+
+fn camera_preview_error_message(err: &str) -> String {
+ if err.contains("DeviceNotFound") {
+ return "This camera is no longer available. Check that it is connected and allowed by system permissions.".to_string();
+ }
+
+ if err.contains("CameraTimeout") {
+ return "No frames were received from this camera. It may be closed, disconnected, covered, or in use by another app.".to_string();
+ }
+
+ if err.contains("StartCapturing") {
+ return "The system could not start this camera. It may be unavailable or in use by another app.".to_string();
+ }
+
+ if err.contains("InvalidFormat") {
+ return "This camera did not report a usable capture format.".to_string();
+ }
+
+ "The selected camera could not be started. Choose another camera or reconnect this one."
+ .to_string()
+}
+
+fn emit_camera_preview_error(app_handle: &AppHandle, message: String) {
+ let _ = app_handle.emit(
+ CAMERA_PREVIEW_ERROR_EVENT,
+ CameraPreviewErrorPayload {
+ title: "Camera unavailable".to_string(),
+ message,
+ },
+ );
+}
+
+fn emit_camera_preview_clear(app_handle: &AppHandle) {
+ let _ = app_handle.emit(CAMERA_PREVIEW_CLEAR_EVENT, ());
+}
+
impl App {
pub fn set_pending_recording(&mut self, mode: RecordingMode, target: ScreenCaptureTarget) {
self.recording_state = RecordingState::Pending { mode, target };
@@ -762,19 +807,28 @@ async fn set_camera_input(
match &id {
None => {
- {
+ let shutdown_rx = {
let app = &mut *state.write().await;
app.camera_in_use = false;
app.selected_camera_id = None;
- app.camera_preview.pause();
+ app.camera_preview.begin_shutdown()
};
camera_feed
.ask(feeds::camera::RemoveInput)
.await
.map_err(|e| e.to_string())?;
+
+ if let Some(rx) = shutdown_rx {
+ let _ = tokio::time::timeout(Duration::from_millis(500), rx).await;
+ }
+
+ if !skip_camera_window {
+ windows::cleanup_camera_window(&app_handle, None, true, true).await;
+ }
}
Some(id) => {
+ emit_camera_preview_clear(&app_handle);
let settings =
recording_settings::RecordingSettingsStore::camera_settings_for(&app_handle, id);
let (camera_ws_sender, native_preview_active) = {
@@ -807,6 +861,7 @@ async fn set_camera_input(
}
}
+ let mut showed_camera_window = skip_camera_window;
let mut attempts = 0;
let init_result: Result<(), String> = loop {
attempts += 1;
@@ -819,6 +874,16 @@ async fn set_camera_input(
.await
.map_err(|e| e.to_string());
+ if !showed_camera_window {
+ showed_camera_window = true;
+ let show_result = ShowCapWindow::Camera { centered: false }
+ .show(&app_handle)
+ .await;
+ show_result
+ .map_err(|err| error!("Failed to show camera preview window: {err}"))
+ .ok();
+ }
+
let result = match request {
Ok(future) => future.await.map_err(|e| e.to_string()),
Err(e) => Err(e),
@@ -826,9 +891,16 @@ async fn set_camera_input(
match result {
Ok(_) => {
+ emit_camera_preview_clear(&app_handle);
break Ok(());
}
Err(e) => {
+ if attempts == 1 && !skip_camera_window {
+ emit_camera_preview_error(
+ &app_handle,
+ camera_preview_error_message(&e),
+ );
+ }
if attempts >= 3 {
break Err(format!(
"Failed to initialize camera after {attempts} attempts: {e}"
@@ -844,21 +916,27 @@ async fn set_camera_input(
};
if let Err(e) = init_result {
+ let message = camera_preview_error_message(&e);
let _ = camera_feed.ask(feeds::camera::RemoveInput).await;
- let app = &mut *state.write().await;
- app.selected_camera_id = None;
- app.camera_in_use = false;
- app.camera_preview.pause();
- return Err(e);
- }
-
- if !skip_camera_window {
- let show_result = ShowCapWindow::Camera { centered: false }
- .show(&app_handle)
- .await;
- show_result
- .map_err(|err| error!("Failed to show camera preview window: {err}"))
- .ok();
+ let emit_input_lost = {
+ let app = &mut *state.write().await;
+ app.camera_in_use = false;
+ app.disconnected_inputs.insert(RecordingInputKind::Camera)
+ };
+ if emit_input_lost {
+ let _ = RecordingEvent::InputLost {
+ input: RecordingInputKind::Camera,
+ }
+ .emit(&app_handle);
+ }
+ emit_camera_preview_error(&app_handle, message.clone());
+ let _ = NewNotification {
+ title: "Camera unavailable".to_string(),
+ body: message,
+ is_error: true,
+ }
+ .emit(&app_handle);
+ return Ok(());
}
}
}
@@ -3865,6 +3943,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
"screenshot-editor",
])
.map_label(|label| match label {
+ label if label.starts_with("camera-") => "camera",
label if label.starts_with("editor-") => "editor",
label if label.starts_with("screenshot-editor-") => "screenshot-editor",
label if label.starts_with("window-capture-occluder-") => {
@@ -4631,6 +4710,13 @@ where
}
}
+fn show_camera_window_unlocked(app: &AppHandle) {
+ let app = app.clone();
+ spawn_on_runtime(async move {
+ let _ = ShowCapWindow::Camera { centered: false }.show(&app).await;
+ });
+}
+
#[cfg(target_os = "windows")]
fn has_open_editor_window(app: &AppHandle) -> bool {
app.webview_windows()
diff --git a/apps/desktop/src-tauri/src/target_select_overlay.rs b/apps/desktop/src-tauri/src/target_select_overlay.rs
index bd88bfee0..91bb67df5 100644
--- a/apps/desktop/src-tauri/src/target_select_overlay.rs
+++ b/apps/desktop/src-tauri/src/target_select_overlay.rs
@@ -258,8 +258,8 @@ pub async fn update_camera_overlay_bounds(
width: f64,
height: f64,
) -> Result<(), String> {
- let window = app
- .get_webview_window("camera")
+ let window = CapWindowId::Camera
+ .get(&app)
.ok_or("Camera window not found")?;
let width_u32 = width as u32;
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index 5071acc6c..85dcb8556 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -25,15 +25,17 @@ use tokio::sync::RwLock;
use tracing::{debug, error, instrument, warn};
#[cfg(target_os = "macos")]
-use crate::panel_manager::{PanelManager, PanelState, PanelWindowType};
+use crate::panel_manager::{PanelManager, PanelState, PanelWindowType, is_window_handle_valid};
use crate::{
App, ArcLock, CameraWindowCloseGate, CameraWindowPositionGuard, MainWindowReadyState,
- RequestScreenCapturePrewarm, RequestSetTargetMode,
+ NewNotification, RequestScreenCapturePrewarm, RequestSetTargetMode,
+ camera_preview_error_message,
editor_window::PendingEditorInstances,
- fake_window,
+ emit_camera_preview_clear, emit_camera_preview_error, fake_window,
general_settings::{self, AppTheme, GeneralSettingsStore},
permissions,
+ recording::{RecordingEvent, RecordingInputKind},
recording_settings::RecordingTargetMode,
screenshot_editor::PendingScreenshotEditorInstances,
target_select_overlay::WindowFocusManager,
@@ -128,8 +130,88 @@ fn hide_recording_windows(app: &AppHandle) {
}
}
-fn bump_camera_window_session(app: &AppHandle) {
- app.state::<Arc<AtomicU64>>().fetch_add(1, Ordering::AcqRel);
+fn bump_camera_window_session(app: &AppHandle) -> u64 {
+ app.state::<Arc<AtomicU64>>().fetch_add(1, Ordering::AcqRel) + 1
+}
+
+fn camera_window_label_for_session(session_id: u64) -> String {
+ format!("camera-{session_id}")
+}
+
+fn is_camera_window_label(label: &str) -> bool {
+ label == "camera"
+ || label
+ .strip_prefix("camera-")
+ .is_some_and(|suffix| suffix.parse::<u64>().is_ok())
+}
+
+fn camera_window_rank(label: &str) -> u64 {
+ if label == "camera" {
+ return 0;
+ }
+
+ label
+ .strip_prefix("camera-")
+ .and_then(|suffix| suffix.parse::<u64>().ok())
+ .unwrap_or(0)
+}
+
+#[cfg(target_os = "macos")]
+fn camera_window_labels(app: &AppHandle<Wry>) -> Vec<String> {
+ app.webview_windows()
+ .into_keys()
+ .filter(|label| is_camera_window_label(label))
+ .collect()
+}
+
+fn camera_webview_window_entries(app: &AppHandle<Wry>) -> Vec<(String, WebviewWindow)> {
+ app.webview_windows()
+ .into_iter()
+ .filter(|(label, _)| is_camera_window_label(label))
+ .collect()
+}
+
+fn camera_webview_windows(app: &AppHandle<Wry>) -> Vec<WebviewWindow> {
+ camera_webview_window_entries(app)
+ .into_iter()
+ .map(|(_, window)| window)
+ .collect()
+}
+
+fn current_camera_window(app: &AppHandle<Wry>) -> Option<WebviewWindow> {
+ #[cfg(target_os = "macos")]
+ {
+ camera_webview_window_entries(app)
+ .into_iter()
+ .filter(|(_, window)| is_window_handle_valid(window))
+ .max_by_key(|(label, _)| camera_window_rank(label))
+ .map(|(_, window)| window)
+ }
+
+ #[cfg(not(target_os = "macos"))]
+ {
+ camera_webview_window_entries(app)
+ .into_iter()
+ .max_by_key(|(label, _)| camera_window_rank(label))
+ .map(|(_, window)| window)
+ }
+}
+
+fn destroy_camera_window_handle(
+ app: &AppHandle<Wry>,
+ window: WebviewWindow,
+) -> tokio::sync::oneshot::Receiver<()> {
+ let (destroy_tx, destroy_rx) = tokio::sync::oneshot::channel();
+ let _ = window.as_ref().close();
+ app.run_on_main_thread({
+ let window = window.clone();
+ move || {
+ let _ = window.destroy();
+ let _ = destroy_tx.send(());
+ }
+ })
+ .ok();
+ destroy_rx
}
async fn ensure_camera_input_active(app_state: &mut App) {
@@ -207,6 +289,7 @@ async fn restore_main_window_inputs(app: &AppHandle) {
.unwrap_or(None);
if let Some(camera_id) = camera_to_restore {
+ emit_camera_preview_clear(app);
let settings =
crate::recording_settings::RecordingSettingsStore::camera_settings_for(app, &camera_id);
@@ -236,6 +319,7 @@ async fn restore_main_window_inputs(app: &AppHandle) {
.await;
}
+ let mut showed_camera_window = false;
let mut attempts = 0;
let init_result: Result<(), String> = loop {
attempts += 1;
@@ -247,10 +331,24 @@ async fn restore_main_window_inputs(app: &AppHandle) {
.await
.map_err(|e| e.to_string());
+ if !showed_camera_window {
+ showed_camera_window = true;
+ crate::show_camera_window_unlocked(app);
+ }
+
match request {
Ok(future) => match future.await {
- Ok(_) => break Ok(()),
+ Ok(_) => {
+ emit_camera_preview_clear(app);
+ break Ok(());
+ }
Err(e) => {
+ if attempts == 1 {
+ emit_camera_preview_error(
+ app,
+ camera_preview_error_message(&e.to_string()),
+ );
+ }
if attempts >= 3 {
break Err(format!(
"Failed to restore camera after {attempts} attempts: {e}"
@@ -272,15 +370,35 @@ async fn restore_main_window_inputs(app: &AppHandle) {
drop(operation_guard);
- if init_result.is_ok() {
- crate::restore_camera_window(app);
- } else {
- warn!("Failed to restore camera input for main window");
- let _ = camera_feed.ask(feeds::camera::RemoveInput).await;
- let app_state = &mut *state.write().await;
- app_state.selected_camera_id = None;
- app_state.camera_in_use = false;
- app_state.camera_preview.pause();
+ match init_result {
+ Ok(()) => crate::restore_camera_window(app),
+ Err(error) => {
+ let message = camera_preview_error_message(&error);
+ warn!("Failed to restore camera input for main window: {error}");
+ let _ = camera_feed.ask(feeds::camera::RemoveInput).await;
+ let emit_input_lost = {
+ let app_state = &mut *state.write().await;
+ app_state.selected_camera_id = None;
+ app_state.camera_in_use = false;
+ app_state
+ .disconnected_inputs
+ .insert(RecordingInputKind::Camera)
+ };
+ crate::show_camera_window_unlocked(app);
+ if emit_input_lost {
+ let _ = RecordingEvent::InputLost {
+ input: RecordingInputKind::Camera,
+ }
+ .emit(app);
+ }
+ emit_camera_preview_error(app, message.clone());
+ let _ = NewNotification {
+ title: "Camera unavailable".to_string(),
+ body: message,
+ is_error: true,
+ }
+ .emit(app);
+ }
}
}
}
@@ -303,14 +421,18 @@ pub(crate) async fn cleanup_camera_window(
#[cfg(target_os = "macos")]
{
+ let panel_labels = window
+ .map(|window| vec![window.label().to_string()])
+ .unwrap_or_else(|| camera_window_labels(app));
let (panel_close_tx, panel_close_rx) = tokio::sync::oneshot::channel();
let app_for_close = app.clone();
app.run_on_main_thread(move || {
use tauri_nspanel::ManagerExt;
- let label = CapWindowId::Camera.label();
- if let Ok(panel) = app_for_close.get_webview_panel(&label) {
- panel.released_when_closed(false);
- panel.close();
+ for label in panel_labels {
+ if let Ok(panel) = app_for_close.get_webview_panel(&label) {
+ panel.released_when_closed(false);
+ panel.close();
+ }
}
let _ = panel_close_tx.send(());
})
@@ -318,39 +440,24 @@ pub(crate) async fn cleanup_camera_window(
let _ = tokio::time::timeout(std::time::Duration::from_millis(500), panel_close_rx).await;
}
- if let Some(window) = window {
- let (destroy_tx, destroy_rx) = tokio::sync::oneshot::channel();
- app.run_on_main_thread({
- let window = window.clone();
- move || {
- let _ = window.destroy();
- let _ = destroy_tx.send(());
- }
- })
- .ok();
- let _ = tokio::time::timeout(std::time::Duration::from_millis(500), destroy_rx).await;
- } else if let Some(stale) = CapWindowId::Camera.get(app) {
- let (destroy_tx, destroy_rx) = tokio::sync::oneshot::channel();
- app.run_on_main_thread({
- let stale = stale.clone();
- move || {
- let _ = stale.destroy();
- let _ = destroy_tx.send(());
- }
- })
- .ok();
+ let windows = window
+ .cloned()
+ .map(|window| vec![window])
+ .unwrap_or_else(|| camera_webview_windows(app));
+ for window in windows {
+ let destroy_rx = destroy_camera_window_handle(app, window);
let _ = tokio::time::timeout(std::time::Duration::from_millis(500), destroy_rx).await;
}
if wait_for_removal {
let start = std::time::Instant::now();
let timeout = std::time::Duration::from_millis(2000);
- while start.elapsed() < timeout && CapWindowId::Camera.get(app).is_some() {
+ while start.elapsed() < timeout && !camera_webview_windows(app).is_empty() {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
- let still_exists = CapWindowId::Camera.get(app).is_some();
+ let still_exists = !camera_webview_windows(app).is_empty();
app.state::<CameraWindowCloseGate>().set_allow_close(false);
!still_exists
@@ -592,7 +699,7 @@ impl FromStr for CapWindowId {
Ok(match s {
"main" => Self::Main,
"settings" => Self::Settings,
- "camera" => Self::Camera,
+ s if is_camera_window_label(s) => Self::Camera,
"capture-area" => Self::CaptureArea,
// legacy identifier
"in-progress-recording" => Self::RecordingControls,
@@ -706,6 +813,10 @@ impl CapWindowId {
}
pub fn get(&self, app: &AppHandle<Wry>) -> Option<WebviewWindow> {
+ if matches!(self, Self::Camera) {
+ return current_camera_window(app);
+ }
+
let label = self.label();
app.get_webview_window(&label)
}
@@ -815,6 +926,14 @@ impl ShowCapWindow {
}
}
+ let camera_window_label = if matches!(self, Self::Camera { .. }) {
+ Some(camera_window_label_for_session(bump_camera_window_session(
+ app,
+ )))
+ } else {
+ None
+ };
+
if let Self::Camera { centered } = self {
#[cfg(target_os = "macos")]
{
@@ -850,8 +969,6 @@ impl ShowCapWindow {
}
}
- bump_camera_window_session(app);
-
if let Some(window) = self.id(app).get(app) {
#[cfg(target_os = "macos")]
{
@@ -1778,8 +1895,11 @@ impl ShowCapWindow {
#[cfg(target_os = "macos")]
permissions::prepare_macos_panel_window(app);
+ let label = camera_window_label
+ .clone()
+ .unwrap_or_else(|| CapWindowId::Camera.label());
let mut window_builder = self
- .window_builder(app, "/camera")
+ .window_builder_with_label(app, "/camera", label)
.maximized(false)
.resizable(false)
.shadow(false)
@@ -2333,6 +2453,16 @@ impl ShowCapWindow {
url: impl Into<PathBuf>,
) -> WebviewWindowBuilder<'a, Wry, AppHandle<Wry>> {
let id = self.id(app);
+ self.window_builder_with_label(app, url, id.label())
+ }
+
+ fn window_builder_with_label<'a>(
+ &'a self,
+ app: &'a AppHandle<Wry>,
+ url: impl Into<PathBuf>,
+ label: impl Into<String>,
+ ) -> WebviewWindowBuilder<'a, Wry, AppHandle<Wry>> {
+ let id = self.id(app);
let theme = GeneralSettingsStore::get(app)
.ok()
@@ -2344,7 +2474,7 @@ impl ShowCapWindow {
})
.unwrap_or(None);
- let mut builder = WebviewWindow::builder(app, id.label(), WebviewUrl::App(url.into()))
+ let mut builder = WebviewWindow::builder(app, label, WebviewUrl::App(url.into()))
.title(id.title())
.visible(false)
.accept_first_mouse(true)