Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add delete recording capability (#660)

Richie McIlroy7ee689a9b998
diff --git a/apps/desktop/src-tauri/src/hotkeys.rs b/apps/desktop/src-tauri/src/hotkeys.rs
index df4cdc169..a5c69a9b5 100644
--- a/apps/desktop/src-tauri/src/hotkeys.rs
+++ b/apps/desktop/src-tauri/src/hotkeys.rs
@@ -1,6 +1,4 @@
-use crate::{
- RequestNewScreenshot, RequestRestartRecording, RequestStartRecording, RequestStopRecording,
-};
+use crate::{recording, RequestStartRecording};
use global_hotkey::HotKeyState;
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -42,7 +40,7 @@ impl Hotkey {
}
}
-#[derive(Serialize, Deserialize, Type, PartialEq, Eq, Hash)]
+#[derive(Serialize, Deserialize, Type, PartialEq, Eq, Hash, Clone, Copy)]
#[serde(rename_all = "camelCase")]
pub enum HotkeyAction {
StartRecording,
@@ -80,19 +78,7 @@ pub fn init(app: &AppHandle) {
for (action, hotkey) in &store.hotkeys {
if &hotkey.to_shortcut() == shortcut {
- match action {
- HotkeyAction::StartRecording => {
- let _ = RequestStartRecording.emit(app);
- }
- HotkeyAction::StopRecording => {
- let _ = RequestStopRecording.emit(app);
- }
- HotkeyAction::RestartRecording => {
- let _ = RequestRestartRecording.emit(app);
- } // HotkeyAction::TakeScreenshot => {
- // let _ = RequestNewScreenshot.emit(app);
- // }
- }
+ tokio::spawn(handle_hotkey(app.clone(), *action));
}
}
})
@@ -111,6 +97,19 @@ pub fn init(app: &AppHandle) {
app.manage(Mutex::new(store));
}
+async fn handle_hotkey(app: AppHandle, action: HotkeyAction) -> Result<(), String> {
+ match action {
+ HotkeyAction::StartRecording => {
+ let _ = RequestStartRecording.emit(&app);
+ Ok(())
+ }
+ HotkeyAction::StopRecording => recording::stop_recording(app.clone(), app.state()).await,
+ HotkeyAction::RestartRecording => {
+ recording::restart_recording(app.clone(), app.state()).await
+ }
+ }
+}
+
#[tauri::command(async)]
#[specta::specta]
pub fn set_hotkey(app: AppHandle, action: HotkeyAction, hotkey: Option<Hotkey>) -> Result<(), ()> {
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 1c7bd7a57..3154a6b47 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1,22 +1,20 @@
mod audio;
+mod audio_meter;
mod auth;
mod camera;
mod captions;
mod deeplink_actions;
+mod editor_window;
+mod export;
+mod fake_window;
mod flags;
mod general_settings;
mod hotkeys;
mod notifications;
mod permissions;
mod platform;
-mod recording;
-// mod resource;
-mod audio_meter;
-mod editor_window;
-mod export;
-mod fake_window;
-// mod live_state;
mod presets;
+mod recording;
mod tray;
mod upload;
mod web_api;
@@ -192,7 +190,6 @@ async fn set_camera_input(
match (&label, app.camera_feed.as_ref()) {
(Some(label), Some(camera_feed)) => {
- // Try to switch cameras on existing feed
camera_feed
.lock()
.await
@@ -213,21 +210,18 @@ async fn set_camera_input(
match result {
Ok(Ok(feed)) => {
let mut app = state.write().await;
- // Only attach if camera is still None
if app.camera_feed.is_none() {
feed.attach(camera_tx);
app.camera_feed = Some(Arc::new(Mutex::new(feed)));
return Ok(true);
} else {
- // Camera state changed while we were initializing
return Ok(false);
}
}
Ok(Err(e)) => return Err(e.to_string()),
- Err(_) => return Ok(false), // Channel closed
+ Err(_) => return Ok(false),
}
}
- // Periodically check if we should abandon this initialization
_ = tokio::time::sleep(tokio::time::Duration::from_millis(100)) => {
let app = state.read().await;
@@ -239,7 +233,6 @@ async fn set_camera_input(
}
}
(None, _) => {
- // User wants no camera
app.camera_feed.take();
Ok(true)
}
@@ -268,15 +261,9 @@ pub struct RecordingStopped;
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RequestStartRecording;
-#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
-pub struct RequestRestartRecording;
-
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RequestNewScreenshot;
-#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
-pub struct RequestStopRecording;
-
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RequestOpenSettings {
page: String,
@@ -545,7 +532,6 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(
if !is_screenshot {
if !is_valid_mp4(src_path) {
- // Wait for up to 10 seconds for the file to become valid
let mut attempts = 0;
while attempts < 10 {
std::thread::sleep(std::time::Duration::from_secs(1));
@@ -596,7 +582,6 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(
if !is_screenshot && !is_valid_mp4(std::path::Path::new(&dst)) {
last_error = Some("Destination file is not a valid MP4".to_string());
- // Delete the invalid file
let _ = tokio::fs::remove_file(&dst).await;
attempts += 1;
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
@@ -629,7 +614,6 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(
}
}
- // If we get here, all attempts failed
eprintln!(
"Failed to copy file from {} to {} after {} attempts. Last error: {}",
src,
@@ -650,7 +634,6 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(
Err(last_error.unwrap_or_else(|| "Maximum retry attempts exceeded".to_string()))
}
-/// Validates if a file at the given path is a valid MP4 file
pub fn is_valid_mp4(path: &std::path::Path) -> bool {
if let Ok(file) = std::fs::File::open(path) {
let file_size = match file.metadata() {
@@ -789,7 +772,6 @@ async fn create_editor_instance(window: Window) -> Result<SerializedEditorInstan
let editor_instance = EditorInstances::get_or_create(&window, path).await?;
- // Load the RecordingMeta to get the pretty name
let meta = editor_instance.meta();
println!("Pretty name: {}", meta.pretty_name);
@@ -809,7 +791,6 @@ async fn create_editor_instance(window: Window) -> Result<SerializedEditorInstan
#[tauri::command]
#[specta::specta]
async fn get_editor_meta(editor: WindowEditorInstance) -> Result<RecordingMeta, String> {
- // Always reload the latest meta from disk using the project path
let path = editor.project_path.clone();
RecordingMeta::load_for_project(&path).map_err(|e| e.to_string())
}
@@ -875,15 +856,13 @@ async fn get_video_metadata(path: PathBuf) -> Result<VideoRecordingMetadata, Str
},
};
- // Use the shorter duration
let duration = display_paths
.into_iter()
.map(get_duration_for_path)
.sum::<Result<_, _>>()?;
- // Calculate estimated size using same logic as get_export_estimates
- let (width, height) = (1920, 1080); // Default to 1080p
- let fps = 30; // Default to 30fps
+ let (width, height) = (1920, 1080);
+ let fps = 30;
let base_bitrate = if width <= 1280 && height <= 720 {
4_000_000.0
@@ -1011,7 +990,6 @@ async fn upload_exported_video(
return Ok(UploadResult::NotAuthenticated);
};
- // Get video metadata to check duration
let screen_metadata = get_video_metadata(path.clone()).await.map_err(|e| {
sentry::capture_message(
&format!("Failed to get video metadata: {}", e),
@@ -1022,19 +1000,15 @@ async fn upload_exported_video(
.to_string()
})?;
- // Get camera metadata if it exists
let camera_metadata = get_video_metadata(path.clone()).await.ok();
- // Use the longer duration between screen and camera
let duration = screen_metadata.duration.max(
camera_metadata
.map(|m| m.duration)
.unwrap_or(screen_metadata.duration),
);
- // Check if user is not pro and video is over 5 minutes
if !auth.is_upgraded() && duration > 300.0 {
- // 300 seconds = 5 minutes
return Ok(UploadResult::UpgradeRequired);
}
@@ -1046,7 +1020,6 @@ async fn upload_exported_video(
return Err("Failed to upload video: Rendered video not found".to_string());
}
- // Start upload progress
UploadProgress { progress: 0.0 }.emit(&app).ok();
let s3_config = async {
@@ -1082,7 +1055,6 @@ async fn upload_exported_video(
.await
{
Ok(uploaded_video) => {
- // Emit upload complete
UploadProgress { progress: 1.0 }.emit(&app).ok();
meta.sharing = Some(SharingMeta {
@@ -1117,7 +1089,6 @@ async fn upload_screenshot(
screenshot_path: PathBuf,
) -> Result<UploadResult, String> {
let Ok(Some(mut auth)) = AuthStore::get(&app) else {
- // Sign out and redirect to sign in
AuthStore::set(&app, None).map_err(|e| e.to_string())?;
return Ok(UploadResult::NotAuthenticated);
};
@@ -1133,11 +1104,9 @@ async fn upload_screenshot(
let mut meta = RecordingMeta::load_for_project(&screenshot_dir).unwrap();
let share_link = if let Some(sharing) = meta.sharing.as_ref() {
- // Screenshot already uploaded, use existing link
println!("Screenshot already uploaded, using existing link");
sharing.link.clone()
} else {
- // Upload the screenshot
let uploaded = upload_image(&app, screenshot_path.clone())
.await
.map_err(|e| e.to_string())?;
@@ -1153,10 +1122,8 @@ async fn upload_screenshot(
println!("Copying to clipboard: {:?}", share_link);
- // Copy link to clipboard
let _ = clipboard.write().await.set_text(share_link.clone());
- // Send notification after successful upload and clipboard copy
notifications::send_notification(&app, notifications::NotificationType::ShareableLinkCopied);
Ok(UploadResult::Success(share_link))
@@ -1176,9 +1143,7 @@ async fn take_screenshot(app: AppHandle, _state: MutableState<'_, App>) -> Resul
std::fs::create_dir_all(&recording_dir).map_err(|e| e.to_string())?;
- // Capture the screenshot synchronously before any await points
let (width, height, bgra_data) = {
- // Take screenshot using scap with optimized settings
let options = scap::capturer::Options {
fps: 1,
output_type: scap::frame::FrameType::BGRAFrame,
@@ -1186,12 +1151,10 @@ async fn take_screenshot(app: AppHandle, _state: MutableState<'_, App>) -> Resul
..Default::default()
};
- // Hide main window before taking screenshot
if let Some(window) = CapWindowId::Main.get(&app) {
window.hide().ok();
}
- // Create and use capturer on the main thread
let mut capturer = Capturer::new(options);
capturer.start_capture();
let frame = capturer
@@ -1199,7 +1162,6 @@ async fn take_screenshot(app: AppHandle, _state: MutableState<'_, App>) -> Resul
.map_err(|e| format!("Failed to get frame: {}", e))?;
capturer.stop_capture();
- // Show main window after taking screenshot
if let Some(window) = CapWindowId::Main.get(&app) {
window.show().ok();
}
@@ -1225,7 +1187,6 @@ async fn take_screenshot(app: AppHandle, _state: MutableState<'_, App>) -> Resul
let app_handle = app.clone();
let recording_dir = recording_dir.clone();
tokio::task::spawn_blocking(move || -> Result<(), String> {
- // Convert BGRA to RGBA
let mut rgba_data = vec![0; bgra_data.len()];
for (bgra, rgba) in bgra_data.chunks_exact(4).zip(rgba_data.chunks_exact_mut(4)) {
rgba[0] = bgra[2];
@@ -1234,7 +1195,6 @@ async fn take_screenshot(app: AppHandle, _state: MutableState<'_, App>) -> Resul
rgba[3] = bgra[3];
}
- // Create file and PNG encoder
let file = File::create(&screenshot_path).map_err(|e| e.to_string())?;
let w = &mut BufWriter::new(file);
@@ -1243,7 +1203,6 @@ async fn take_screenshot(app: AppHandle, _state: MutableState<'_, App>) -> Resul
encoder.set_compression(png::Compression::Fast);
let mut writer = encoder.write_header().map_err(|e| e.to_string())?;
- // Write image data
writer
.write_image_data(&rgba_data)
.map_err(|e| e.to_string())?;
@@ -1311,14 +1270,12 @@ async fn save_file_dialog(
file_name, file_type
);
- // Remove the ".cap" suffix if present
let file_name = file_name
.strip_suffix(".cap")
.unwrap_or(&file_name)
.to_string();
println!("File name after removing .cap suffix: {}", file_name);
- // Determine the file type and extension
let (name, extension) = match file_type.as_str() {
"recording" => {
println!("File type is recording");
@@ -1360,7 +1317,6 @@ async fn save_file_dialog(
match rx.recv() {
Ok(result) => {
println!("Save dialog result: {:?}", result);
- // Don't send any notifications here - we'll do it after the file is actually copied
Ok(result)
}
Err(e) => {
@@ -1417,7 +1373,6 @@ fn get_recording_meta(
fn list_recordings(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMetaWithType)>, String> {
let recordings_dir = recordings_path(&app);
- // First check if directory exists
if !recordings_dir.exists() {
return Ok(Vec::new());
}
@@ -1432,19 +1387,16 @@ fn list_recordings(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMetaWithType
let path = entry.path();
- // Multiple validation checks
if !path.is_dir() {
return None;
}
- // Try to get recording meta, skip if it fails
get_recording_meta(app.clone(), path.clone(), "recording".to_string())
.ok()
.map(|meta| (path, meta))
})
.collect::<Vec<_>>();
- // Sort the result by creation date of the actual file, newest first
result.sort_by(|a, b| {
let b_time =
b.0.metadata()
@@ -1476,10 +1428,9 @@ fn list_screenshots(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMeta)>, Str
let meta =
match get_recording_meta(app.clone(), path.clone(), "screenshot".to_string()) {
Ok(meta) => meta.inner,
- Err(_) => return None, // Skip this entry if metadata can't be loaded
+ Err(_) => return None,
};
- // Find the nearest .png file inside the .cap folder
let png_path = std::fs::read_dir(&path)
.ok()?
.filter_map(|e| e.ok())
@@ -1493,7 +1444,6 @@ fn list_screenshots(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMeta)>, Str
})
.collect::<Vec<_>>();
- // Sort the result by creation date of the actual file, newest first
result.sort_by(|a, b| {
b.0.metadata()
.and_then(|m| m.created())
@@ -1513,7 +1463,6 @@ fn list_screenshots(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMeta)>, Str
async fn check_upgraded_and_update(app: AppHandle) -> Result<bool, String> {
println!("Checking upgraded status and updating...");
- // Check for commercial license first
if let Ok(Some(settings)) = GeneralSettingsStore::get(&app) {
if settings.commercial_license.is_some() {
return Ok(true);
@@ -1526,7 +1475,6 @@ async fn check_upgraded_and_update(app: AppHandle) -> Result<bool, String> {
return Ok(false);
};
- // Return true early if plan is manually set
if let Some(ref plan) = auth.plan {
if plan.manual {
return Ok(true);
@@ -1581,7 +1529,6 @@ async fn check_upgraded_and_update(app: AppHandle) -> Result<bool, String> {
#[tauri::command]
#[specta::specta]
fn open_external_link(app: tauri::AppHandle, url: String) -> Result<(), String> {
- // Check settings first
if let Ok(Some(settings)) = GeneralSettingsStore::get(&app) {
if settings.disable_auto_open_links {
return Ok(());
@@ -1652,7 +1599,6 @@ async fn seek_to(editor_instance: WindowEditorInstance, frame_number: u32) -> Re
Ok(())
}
-// keep this async otherwise opening windows may hang on windows
#[tauri::command]
#[specta::specta]
async fn show_window(app: AppHandle, window: ShowCapWindow) -> Result<(), String> {
@@ -1673,7 +1619,6 @@ fn set_fail(name: String, value: bool) {
}
async fn check_notification_permissions(app: AppHandle) {
- // Check if we've already requested permissions
let Ok(Some(settings)) = GeneralSettingsStore::get(&app) else {
return;
};
@@ -1764,6 +1709,8 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
recording::stop_recording,
recording::pause_recording,
recording::resume_recording,
+ recording::restart_recording,
+ recording::delete_recording,
recording::list_cameras,
recording::list_capture_windows,
recording::list_capture_screens,
@@ -1834,8 +1781,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
RecordingStarted,
RecordingStopped,
RequestStartRecording,
- RequestRestartRecording,
- RequestStopRecording,
RequestNewScreenshot,
RequestOpenSettings,
NewNotification,
@@ -1912,7 +1857,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
.with_denylist(&[
CapWindowId::Setup.label().as_str(),
"window-capture-occluder",
- // CapWindowId::WindowCaptureOccluder.label().as_str(),
CapWindowId::CaptureArea.label().as_str(),
CapWindowId::Camera.label().as_str(),
CapWindowId::RecordingsOverlay.label().as_str(),
@@ -1946,7 +1890,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
});
}
- // These MUST be called before anything else!
{
app.manage(Arc::new(RwLock::new(App {
handle: app.clone(),
@@ -2003,37 +1946,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
tray::create_tray(&app).unwrap();
- RequestStopRecording::listen_any_spawn(&app, |_, app| async move {
- if let Err(e) = recording::stop_recording(app.clone(), app.state()).await {
- eprintln!("Failed to stop recording: {}", e);
- }
- });
-
- RequestRestartRecording::listen_any_spawn(&app, |_, app| async move {
- let state = app.state::<Arc<RwLock<App>>>();
-
- // Stop and discard the current recording
- let inputs = if let Some(recording) = state.write().await.clear_current_recording()
- {
- CurrentRecordingChanged.emit(&app).ok();
-
- let inputs = recording.inputs().clone();
-
- let _ = recording.cancel().await;
-
- Some(inputs)
- } else {
- None
- };
-
- if let Some(inputs) = inputs {
- tokio::time::sleep(Duration::from_millis(1000)).await;
- if let Err(e) = recording::start_recording(app.clone(), state, inputs).await {
- error!("Failed to start new recording: {}", e);
- }
- }
- });
-
RequestNewScreenshot::listen_any_spawn(&app, |_, app| async move {
if let Err(e) = take_screenshot(app.clone(), app.state()).await {
eprintln!("Failed to take screenshot: {}", e);
@@ -2048,9 +1960,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
.await;
});
- // Registering deep links at runtime is not possible on macOS,
- // so deep links can only be tested on the bundled application,
- // which must be installed in the /Applications directory.
let app_handle = app.clone();
app.deep_link().on_open_url(move |event| {
deeplink_actions::handle(&app_handle, event.urls());
@@ -2094,7 +2003,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
if let Some(window) = CapWindowId::Main.get(&app) {
let _ = window.show();
}
- // Don't quit the app when settings or upgrade window is closed
return;
}
_ => {}
@@ -2137,7 +2045,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
.run(|handle, event| match event {
#[cfg(target_os = "macos")]
tauri::RunEvent::Reopen { .. } => {
- // Check if any editor, settings or signin window is open
let has_window = handle.webview_windows().iter().any(|(label, _)| {
label.starts_with("editor-")
|| label.as_str() == "settings"
@@ -2145,7 +2052,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
});
if has_window {
- // Find and focus the editor, settings or signin window
if let Some(window) = handle
.webview_windows()
.iter()
@@ -2202,7 +2108,6 @@ async fn create_editor_instance_impl(
Ok(instance)
}
-// use EditorInstance.project_path instead of this
fn recordings_path(app: &AppHandle) -> PathBuf {
let path = app.path().app_data_dir().unwrap().join("recordings");
std::fs::create_dir_all(&path).unwrap_or_default();
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 5500b0429..3df049806 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -12,12 +12,11 @@ use crate::{
upload::{
create_or_get_video, prepare_screenshot_upload, upload_video, InstantMultipartUpload,
},
- web_api::{self, ManagerExt},
+ web_api::ManagerExt,
windows::{CapWindowId, ShowCapWindow},
App, CurrentRecordingChanged, DynLoggingLayer, MutableState, NewStudioRecordingAdded,
RecordingStarted, RecordingStopped, VideoUploadInfo,
};
-use base64::{prelude::BASE64_STANDARD, Engine};
use cap_fail::fail;
use cap_media::{feeds::CameraFeed, platform::display_for_window, sources::ScreenCaptureTarget};
use cap_media::{
@@ -30,12 +29,10 @@ use cap_project::{
};
use cap_recording::{
instant_recording::{CompletedInstantRecording, InstantRecordingHandle},
- CompletedStudioRecording, RecordingError, RecordingMode, RecordingOptions,
- StudioRecordingHandle,
+ CompletedStudioRecording, RecordingError, RecordingMode, StudioRecordingHandle,
};
use cap_rendering::ProjectRecordingsMeta;
use cap_utils::{ensure_dir, spawn_actor};
-use scap::Target;
use serde::Deserialize;
use specta::Type;
use tauri::{AppHandle, Manager};
@@ -50,11 +47,13 @@ pub enum InProgressRecording {
progressive_upload: Option<InstantMultipartUpload>,
video_upload_info: VideoUploadInfo,
inputs: StartRecordingInputs,
+ recording_dir: PathBuf,
},
Studio {
target_name: String,
handle: StudioRecordingHandle,
inputs: StartRecordingInputs,
+ recording_dir: PathBuf,
},
}
@@ -87,6 +86,13 @@ impl InProgressRecording {
}
}
+ pub fn recording_dir(&self) -> &PathBuf {
+ match self {
+ Self::Instant { recording_dir, .. } => recording_dir,
+ Self::Studio { recording_dir, .. } => recording_dir,
+ }
+ }
+
pub async fn stop(self) -> Result<CompletedRecording, RecordingError> {
Ok(match self {
Self::Instant {
@@ -370,6 +376,7 @@ pub async fn start_recording(
handle,
target_name,
inputs,
+ recording_dir: recording_dir.clone(),
},
actor_done_rx,
)
@@ -398,6 +405,7 @@ pub async fn start_recording(
video_upload_info,
target_name,
inputs,
+ recording_dir: recording_dir.clone(),
},
actor_done_rx,
)
@@ -516,6 +524,64 @@ pub async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Res
Ok(())
}
+#[tauri::command]
+#[specta::specta]
+pub async fn restart_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
+ let Some(recording) = state.write().await.clear_current_recording() else {
+ return Err("No recording in progress".to_string());
+ };
+
+ let _ = CurrentRecordingChanged.emit(&app);
+
+ let inputs = recording.inputs().clone();
+
+ let _ = recording.cancel().await;
+
+ tokio::time::sleep(Duration::from_millis(1000)).await;
+
+ start_recording(app.clone(), state, inputs).await
+}
+
+#[tauri::command]
+#[specta::specta]
+pub async fn delete_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
+ let recording_data = {
+ let mut app_state = state.write().await;
+ if let Some(recording) = app_state.clear_current_recording() {
+ let recording_dir = recording.recording_dir().clone();
+ let video_id = match &recording {
+ InProgressRecording::Instant {
+ video_upload_info, ..
+ } => Some(video_upload_info.id.clone()),
+ _ => None,
+ };
+ Some((recording, recording_dir, video_id))
+ } else {
+ None
+ }
+ };
+
+ if let Some((recording, recording_dir, video_id)) = recording_data {
+ CurrentRecordingChanged.emit(&app).ok();
+ RecordingStopped {}.emit(&app).ok();
+
+ let _ = recording.cancel().await;
+
+ std::fs::remove_dir_all(&recording_dir).ok();
+
+ if let Some(id) = video_id {
+ let _ = app
+ .authed_api_request(
+ format!("/api/desktop/video/delete?videoId={}", id),
+ |c, url| c.delete(url),
+ )
+ .await;
+ }
+ }
+
+ Ok(())
+}
+
// runs when a recording ends, whether from success or failure
async fn handle_recording_end(
handle: AppHandle,
diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs
index bfadc9d38..0b0d28912 100644
--- a/apps/desktop/src-tauri/src/tray.rs
+++ b/apps/desktop/src-tauri/src/tray.rs
@@ -1,12 +1,12 @@
use crate::windows::ShowCapWindow;
use crate::{
- RecordingStarted, RecordingStopped, RequestNewScreenshot, RequestOpenSettings,
- RequestStartRecording, RequestStopRecording,
+ recording, RecordingStarted, RecordingStopped, RequestNewScreenshot, RequestOpenSettings,
};
-use cap_fail::fail;
+
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tauri::menu::{MenuId, PredefinedMenuItem};
+use tauri::Manager;
use tauri::{
image::Image,
menu::{Menu, MenuItem},
@@ -134,7 +134,10 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {
move |tray, event| {
if let tauri::tray::TrayIconEvent::Click { .. } = event {
if is_recording.load(Ordering::Relaxed) {
- let _ = RequestStopRecording.emit(&app_handle);
+ let app = app_handle.clone();
+ tokio::spawn(async move {
+ let _ = recording::stop_recording(app.clone(), app.state()).await;
+ });
} else {
let _ = tray.set_visible(true);
}
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index b358fa39c..14ad48b40 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -443,8 +443,7 @@ impl ShowCapWindow {
Self::InProgressRecording {
position: _position,
} => {
- let mut width = 180.0 + 32.0;
-
+ let width = 244.0;
let height = 40.0;
let window = self
diff --git a/apps/desktop/src/routes/in-progress-recording.tsx b/apps/desktop/src/routes/in-progress-recording.tsx
index ad3afa60e..ccc4aca66 100644
--- a/apps/desktop/src/routes/in-progress-recording.tsx
+++ b/apps/desktop/src/routes/in-progress-recording.tsx
@@ -42,7 +42,10 @@ export default function () {
);
createEffect(() => {
- if (!currentRecording.isPending && currentRecording.data === undefined)
+ if (
+ !currentRecording.isPending &&
+ (currentRecording.data === undefined || currentRecording.data === null)
+ )
getCurrentWindow().close();
});
@@ -82,12 +85,28 @@ export default function () {
if (!shouldRestart) return;
- await events.requestRestartRecording.emit();
+ await commands.restartRecording();
+
setState("recording");
setTime(Date.now());
},
}));
+ const deleteRecording = createMutation(() => ({
+ mutationFn: async () => {
+ const shouldDelete = await dialog.confirm(
+ "Are you sure you want to delete the recording?",
+ { title: "Confirm Delete", okLabel: "Delete", cancelLabel: "Cancel" }
+ );
+
+ if (!shouldDelete) return;
+
+ await commands.deleteRecording();
+
+ setState("stopped");
+ },
+ }));
+
const adjustedTime = () => {
let t = time() - start;
for (const { pause, resume } of pauseResumes) {
@@ -153,6 +172,12 @@ export default function () {
>
<IconCapRestart />
</ActionButton>
+ <ActionButton
+ disabled={deleteRecording.isPending}
+ onClick={() => deleteRecording.mutate()}
+ >
+ <IconCapTrash />
+ </ActionButton>
</div>
</div>
<div
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 1bf6982a8..92fe99d66 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -23,6 +23,12 @@ async pauseRecording() : Promise<null> {
async resumeRecording() : Promise<null> {
return await TAURI_INVOKE("resume_recording");
},
+async restartRecording() : Promise<null> {
+ return await TAURI_INVOKE("restart_recording");
+},
+async deleteRecording() : Promise<null> {
+ return await TAURI_INVOKE("delete_recording");
+},
async listCameras() : Promise<string[]> {
return await TAURI_INVOKE("list_cameras");
},
@@ -247,9 +253,7 @@ recordingStopped: RecordingStopped,
renderFrameEvent: RenderFrameEvent,
requestNewScreenshot: RequestNewScreenshot,
requestOpenSettings: RequestOpenSettings,
-requestRestartRecording: RequestRestartRecording,
requestStartRecording: RequestStartRecording,
-requestStopRecording: RequestStopRecording,
uploadProgress: UploadProgress
}>({
audioInputLevelChange: "audio-input-level-change",
@@ -266,9 +270,7 @@ recordingStopped: "recording-stopped",
renderFrameEvent: "render-frame-event",
requestNewScreenshot: "request-new-screenshot",
requestOpenSettings: "request-open-settings",
-requestRestartRecording: "request-restart-recording",
requestStartRecording: "request-start-recording",
-requestStopRecording: "request-stop-recording",
uploadProgress: "upload-progress"
})
@@ -361,9 +363,7 @@ export type RecordingType = "studio" | "instant"
export type RenderFrameEvent = { frame_number: number; fps: number; resolution_base: XY<number> }
export type RequestNewScreenshot = null
export type RequestOpenSettings = { page: string }
-export type RequestRestartRecording = null
export type RequestStartRecording = null
-export type RequestStopRecording = null
export type S3UploadMeta = { id: string }
export type ScreenCaptureTarget = { variant: "window"; id: number } | { variant: "screen"; id: number } | { variant: "area"; screen: number; bounds: Bounds }
export type SegmentRecordings = { display: Video; camera: Video | null; mic: Audio | null; system_audio: Audio | null }
diff --git a/apps/web/app/api/desktop/[...route]/video.ts b/apps/web/app/api/desktop/[...route]/video.ts
index 2ff332a77..e8ab06ab9 100644
--- a/apps/web/app/api/desktop/[...route]/video.ts
+++ b/apps/web/app/api/desktop/[...route]/video.ts
@@ -1,5 +1,5 @@
import { dub } from "@/utils/dub";
-import { createBucketProvider, getS3Bucket, getS3Config } from "@/utils/s3";
+import { createBucketProvider } from "@/utils/s3";
import { db } from "@cap/database";
import { sendEmail } from "@cap/database/emails/config";
import { FirstShareableLink } from "@cap/database/emails/first-shareable-link";
@@ -7,7 +7,7 @@ import { nanoId } from "@cap/database/helpers";
import { s3Buckets, videos } from "@cap/database/schema";
import { buildEnv, NODE_ENV, serverEnv } from "@cap/env";
import { zValidator } from "@hono/zod-validator";
-import { count, eq } from "drizzle-orm";
+import { count, eq, and } from "drizzle-orm";
import { Hono } from "hono";
import { z } from "zod";
@@ -165,3 +165,48 @@ app.get(
}
}
);
+
+app.delete(
+ "/delete",
+ zValidator("query", z.object({ videoId: z.string() })),
+ async (c) => {
+ const { videoId } = c.req.valid("query");
+ const user = c.get("user");
+
+ try {
+ const [result] = await db()
+ .select({ video: videos, bucket: s3Buckets })
+ .from(videos)
+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
+ .where(eq(videos.id, videoId));
+
+ if (!result)
+ return c.json(
+ { error: true, message: "Video not found" },
+ { status: 404 }
+ );
+
+ await db()
+ .delete(videos)
+ .where(and(eq(videos.id, videoId), eq(videos.ownerId, user.id)));
+
+ const bucket = await createBucketProvider(result.bucket);
+
+ const listedObjects = await bucket.listObjects({
+ prefix: `${user.id}/${videoId}/`,
+ });
+
+ if (listedObjects.Contents?.length)
+ await bucket.deleteObjects(
+ listedObjects.Contents.map((content: any) => ({
+ Key: content.Key,
+ }))
+ );
+
+ return c.json(true);
+ } catch (error) {
+ console.error("Error in video delete endpoint:", error);
+ return c.json({ error: "Internal server error" }, { status: 500 });
+ }
+ }
+);
diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rs
index e373b6727..dede58b07 100644
--- a/crates/recording/src/cursor.rs
+++ b/crates/recording/src/cursor.rs
@@ -2,8 +2,8 @@ use std::{
collections::HashMap,
hash::{DefaultHasher, Hash, Hasher},
path::PathBuf,
- sync::{atomic::AtomicBool, Arc},
- time::{Duration, Instant, SystemTime},
+ pin::pin,
+ time::{Duration, SystemTime},
};
use cap_cursor_capture::RawCursorPosition;
@@ -12,8 +12,9 @@ use cap_media::{platform::Bounds, sources::CropRatio};
use cap_project::{CursorClickEvent, CursorMoveEvent, XY};
use cap_utils::spawn_actor;
use device_query::{DeviceQuery, DeviceState};
+use futures::future::Either;
use tokio::sync::oneshot;
-use tracing::{debug, error, info};
+use tracing::{error, info};
pub struct Cursor {
pub file_name: String,
@@ -32,14 +33,13 @@ pub struct CursorActorResponse {
}
pub struct CursorActor {
- stop_signal: Arc<AtomicBool>,
+ shutdown_tx: oneshot::Sender<()>,
rx: oneshot::Receiver<CursorActorResponse>,
}
impl CursorActor {
pub async fn stop(self) -> CursorActorResponse {
- self.stop_signal
- .store(true, std::sync::atomic::Ordering::Relaxed);
+ let _ = self.shutdown_tx.send(());
self.rx.await.unwrap()
}
}
@@ -54,178 +54,182 @@ pub fn spawn_cursor_recorder(
next_cursor_id: u32,
start_time: SystemTime,
) -> CursorActor {
- let stop_signal = Arc::new(AtomicBool::new(false));
+ let (shutdown_tx, mut shutdown_rx) = oneshot::channel::<()>();
let (tx, rx) = oneshot::channel();
- spawn_actor({
- let stop_signal = stop_signal.clone();
- async move {
- let device_state = DeviceState::new();
- let mut last_mouse_state = device_state.get_mouse();
+ spawn_actor(async move {
+ let device_state = DeviceState::new();
+ let mut last_mouse_state = device_state.get_mouse();
- #[cfg(target_os = "macos")]
- let mut last_position = RawCursorPosition::get();
+ #[cfg(target_os = "macos")]
+ let mut last_position = RawCursorPosition::get();
+
+ // Create cursors directory if it doesn't exist
+ std::fs::create_dir_all(&cursors_dir).unwrap();
- // Create cursors directory if it doesn't exist
- std::fs::create_dir_all(&cursors_dir).unwrap();
+ let mut response = CursorActorResponse {
+ cursors: prev_cursors,
+ next_cursor_id,
+ moves: vec![],
+ clicks: vec![],
+ };
- let mut response = CursorActorResponse {
- cursors: prev_cursors,
- next_cursor_id,
- moves: vec![],
- clicks: vec![],
+ loop {
+ let sleep = tokio::time::sleep(Duration::from_millis(10));
+ let Either::Right(_) = futures::future::select(&mut shutdown_rx, pin!(sleep)).await
+ else {
+ break;
};
- while !stop_signal.load(std::sync::atomic::Ordering::Relaxed) {
- let Ok(elapsed) = start_time.elapsed() else {
- continue;
- };
- let elapsed = elapsed.as_secs_f64() * 1000.0;
- let mouse_state = device_state.get_mouse();
-
- let cursor_data = get_cursor_image_data();
- let cursor_id = if let Some(data) = cursor_data {
- let mut hasher = DefaultHasher::default();
- data.image.hash(&mut hasher);
- let id = hasher.finish();
-
- // Check if we've seen this cursor data before
- if let Some(existing_id) = response.cursors.get(&id) {
- existing_id.id.to_string()
- } else {
- // New cursor data - save it
- let cursor_id = response.next_cursor_id.to_string();
- let file_name = format!("cursor_{}.png", cursor_id);
- let cursor_path = cursors_dir.join(&file_name);
-
- if let Ok(image) = image::load_from_memory(&data.image) {
- // Convert to RGBA
- let rgba_image = image.into_rgba8();
-
- if let Err(e) = rgba_image.save(&cursor_path) {
- error!("Failed to save cursor image: {}", e);
- } else {
- info!("Saved cursor {cursor_id} image to: {:?}", file_name);
- response.cursors.insert(
- id,
- Cursor {
- file_name,
- id: response.next_cursor_id,
- hotspot: data.hotspot,
- },
- );
- response.next_cursor_id += 1;
- }
+ let Ok(elapsed) = start_time.elapsed() else {
+ continue;
+ };
+ let elapsed = elapsed.as_secs_f64() * 1000.0;
+ let mouse_state = device_state.get_mouse();
+
+ let cursor_data = get_cursor_image_data();
+ let cursor_id = if let Some(data) = cursor_data {
+ let mut hasher = DefaultHasher::default();
+ data.image.hash(&mut hasher);
+ let id = hasher.finish();
+
+ // Check if we've seen this cursor data before
+ if let Some(existing_id) = response.cursors.get(&id) {
+ existing_id.id.to_string()
+ } else {
+ // New cursor data - save it
+ let cursor_id = response.next_cursor_id.to_string();
+ let file_name = format!("cursor_{}.png", cursor_id);
+ let cursor_path = cursors_dir.join(&file_name);
+
+ if let Ok(image) = image::load_from_memory(&data.image) {
+ // Convert to RGBA
+ let rgba_image = image.into_rgba8();
+
+ if let Err(e) = rgba_image.save(&cursor_path) {
+ error!("Failed to save cursor image: {}", e);
+ } else {
+ info!("Saved cursor {cursor_id} image to: {:?}", file_name);
+ response.cursors.insert(
+ id,
+ Cursor {
+ file_name,
+ id: response.next_cursor_id,
+ hotspot: data.hotspot,
+ },
+ );
+ response.next_cursor_id += 1;
}
-
- cursor_id
}
+
+ cursor_id
+ }
+ } else {
+ "default".to_string()
+ };
+
+ // TODO: use this on windows too
+ #[cfg(target_os = "macos")]
+ let position = {
+ let position = RawCursorPosition::get();
+
+ if position != last_position {
+ last_position = position;
+
+ let cropped_position = position
+ .relative_to_display(display)
+ .normalize()
+ .with_crop(crop_ratio.position, crop_ratio.size);
+
+ Some((cropped_position.x() as f64, cropped_position.y() as f64))
} else {
- "default".to_string()
- };
+ None
+ }
+ };
- // TODO: use this on windows too
- #[cfg(target_os = "macos")]
- let position = {
- let position = RawCursorPosition::get();
+ #[cfg(windows)]
+ let position = if mouse_state.coords != last_mouse_state.coords {
+ let (mouse_x, mouse_y) = {
+ (
+ mouse_state.coords.0 - screen_bounds.x as i32,
+ mouse_state.coords.1 - screen_bounds.y as i32,
+ )
+ };
- if position != last_position {
- last_position = position;
+ // Calculate normalized coordinates (0.0 to 1.0) within the screen bounds
+ // Check if screen_bounds dimensions are valid to avoid division by zero
+ let x = if screen_bounds.width > 0.0 {
+ mouse_x as f64 / screen_bounds.width
+ } else {
+ 0.5 // Fallback if width is invalid
+ };
- let cropped_position = position
- .relative_to_display(display)
- .normalize()
- .with_crop(crop_ratio.position, crop_ratio.size);
+ let y = if screen_bounds.height > 0.0 {
+ mouse_y as f64 / screen_bounds.height
+ } else {
+ 0.5 // Fallback if height is invalid
+ };
- Some((cropped_position.x() as f64, cropped_position.y() as f64))
- } else {
- None
- }
+ // Clamp values to ensure they're within valid range
+ let x = if x.is_nan() || x.is_infinite() {
+ debug!("X coordinate is invalid: {}", x);
+ 0.5
+ } else {
+ x
};
- #[cfg(windows)]
- let position = if mouse_state.coords != last_mouse_state.coords {
- let (mouse_x, mouse_y) = {
- (
- mouse_state.coords.0 - screen_bounds.x as i32,
- mouse_state.coords.1 - screen_bounds.y as i32,
- )
- };
-
- // Calculate normalized coordinates (0.0 to 1.0) within the screen bounds
- // Check if screen_bounds dimensions are valid to avoid division by zero
- let x = if screen_bounds.width > 0.0 {
- mouse_x as f64 / screen_bounds.width
- } else {
- 0.5 // Fallback if width is invalid
- };
-
- let y = if screen_bounds.height > 0.0 {
- mouse_y as f64 / screen_bounds.height
- } else {
- 0.5 // Fallback if height is invalid
- };
-
- // Clamp values to ensure they're within valid range
- let x = if x.is_nan() || x.is_infinite() {
- debug!("X coordinate is invalid: {}", x);
- 0.5
- } else {
- x
- };
-
- let y = if y.is_nan() || y.is_infinite() {
- debug!("Y coordinate is invalid: {}", y);
- 0.5
- } else {
- y
- };
-
- Some((x, y))
+ let y = if y.is_nan() || y.is_infinite() {
+ debug!("Y coordinate is invalid: {}", y);
+ 0.5
} else {
- None
+ y
};
- if let Some((x, y)) = position {
- let mouse_event = CursorMoveEvent {
- active_modifiers: vec![],
- cursor_id: cursor_id.clone(),
- time_ms: elapsed,
- x,
- y,
- };
+ Some((x, y))
+ } else {
+ None
+ };
- response.moves.push(mouse_event);
- }
+ if let Some((x, y)) = position {
+ let mouse_event = CursorMoveEvent {
+ active_modifiers: vec![],
+ cursor_id: cursor_id.clone(),
+ time_ms: elapsed,
+ x,
+ y,
+ };
- for (num, &pressed) in mouse_state.button_pressed.iter().enumerate() {
- let Some(prev) = last_mouse_state.button_pressed.get(num) else {
- continue;
- };
+ response.moves.push(mouse_event);
+ }
- if pressed == *prev {
- continue;
- }
+ for (num, &pressed) in mouse_state.button_pressed.iter().enumerate() {
+ let Some(prev) = last_mouse_state.button_pressed.get(num) else {
+ continue;
+ };
- let mouse_event = CursorClickEvent {
- down: pressed,
- active_modifiers: vec![],
- cursor_num: num as u8,
- cursor_id: cursor_id.clone(),
- time_ms: elapsed,
- };
- response.clicks.push(mouse_event);
+ if pressed == *prev {
+ continue;
}
- last_mouse_state = mouse_state;
- tokio::time::sleep(Duration::from_millis(10)).await;
+ let mouse_event = CursorClickEvent {
+ down: pressed,
+ active_modifiers: vec![],
+ cursor_num: num as u8,
+ cursor_id: cursor_id.clone(),
+ time_ms: elapsed,
+ };
+ response.clicks.push(mouse_event);
}
- tx.send(response).ok();
+ last_mouse_state = mouse_state;
}
+
+ info!("cursor recorder done");
+
+ let _ = tx.send(response);
});
- CursorActor { rx, stop_signal }
+ CursorActor { shutdown_tx, rx }
}
#[derive(Debug)]
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index 32d260492..db47baec8 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -844,8 +844,6 @@ async fn create_segment_pipeline(
None
};
- let (mut pipeline, pipeline_done_rx) = pipeline_builder.build().await?;
-
let cursor = custom_cursor_capture.then(move || {
let cursor = spawn_cursor_recorder(
screen.bounds.clone(),
@@ -877,6 +875,8 @@ async fn create_segment_pipeline(
}
});
+ let (mut pipeline, pipeline_done_rx) = pipeline_builder.build().await?;
+
pipeline.play().await?;
info!("pipeline playing");
diff --git a/packages/web-api-contract/src/desktop.ts b/packages/web-api-contract/src/desktop.ts
index e0899495a..050ad2932 100644
--- a/packages/web-api-contract/src/desktop.ts
+++ b/packages/web-api-contract/src/desktop.ts
@@ -128,6 +128,12 @@ const protectedContract = c.router(
}),
},
},
+ deleteVideo: {
+ method: "DELETE",
+ path: "/desktop/video/delete",
+ query: z.object({ videoId: z.string() }),
+ responses: { 200: z.unknown() },
+ },
},
{
baseHeaders: z.object({ authorization: z.string() }),