From 75c71681162a4d4b7a31807eecde3a8fc584fe2c Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 9 Apr 2025 14:24:39 +0100 Subject: [PATCH 1/9] feat: Open editor or file when .cap file is opened --- apps/desktop/src-tauri/src/lib.rs | 65 +++++++++++++++++++++++++- apps/desktop/src-tauri/tauri.conf.json | 10 +++- 2 files changed, 72 insertions(+), 3 deletions(-) diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 7be4ce20e42..95dc97f3ef1 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -2209,7 +2209,31 @@ pub async fn run(recording_logging_handle: LoggingHandle) { #[allow(unused_mut)] let mut builder = - tauri::Builder::default().plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| { + tauri::Builder::default().plugin(tauri_plugin_single_instance::init(|app, args, _cwd| { + let cap_file = args + .iter() + .find(|arg| arg.ends_with(".cap")) + .map(|arg| std::path::PathBuf::from(arg)); + + if let Some(path) = cap_file { + if path.exists() && path.is_file() { + if let Some(file_name) = path.file_stem() { + let project_id = file_name.to_string_lossy().to_string(); + println!("Opening .cap file: {}", project_id); + + let app_handle = app.clone(); + tokio::spawn(async move { + ShowCapWindow::Editor { project_id } + .show(&app_handle) + .await + .ok(); + }); + return; + } + } + } + + // Default behavior if no .cap file was passed let _ = ShowCapWindow::Main.show(app); })); @@ -2290,7 +2314,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) { capture_system_audio: false, }, current_recording: None, - recording_logging_handle, + recording_logging_handle: recording_logging_handle.clone(), }))); app.manage(Arc::new(RwLock::new( @@ -2387,6 +2411,9 @@ pub async fn run(recording_logging_handle: LoggingHandle) { .await; }); + // Tauri v2 handles file associations through the fileAssociations configuration + // and file drop events are handled in the on_window_event handler + Ok(()) }) .on_window_event(|window, event| { @@ -2448,6 +2475,36 @@ pub async fn run(recording_logging_handle: LoggingHandle) { } } } + WindowEvent::DragDrop(event) => { + if let tauri::DragDropEvent::Drop { paths, .. } = event { + if let Some(path) = paths.first() { + if path.extension().map_or(false, |ext| ext == "cap") { + if let Some(file_name) = path.file_stem() { + let project_id = file_name.to_string_lossy().to_string(); + let app_handle = app.clone(); + + // Check if content/output.mp4 exists inside the .cap folder + let mp4_path = path.join("content/output.mp4"); + + if mp4_path.exists() && mp4_path.is_file() { + // Open the MP4 file with the system's default video player + let _ = app_handle + .shell() + .open(mp4_path.to_str().unwrap_or_default(), None); + } else { + // Proceed with opening the editor as before + tokio::spawn(async move { + ShowCapWindow::Editor { project_id } + .show(&app_handle) + .await + .ok(); + }); + } + } + } + } + } + } _ => {} } }) @@ -2482,6 +2539,10 @@ pub async fn run(recording_logging_handle: LoggingHandle) { let _ = tokio::spawn(async move { ShowCapWindow::Main.show(&handle).await }); } } + tauri::RunEvent::Ready => { + // Nothing special to do on ready - the file associations are configured + // in tauri.conf.json and the single-instance plugin will handle file opening + } tauri::RunEvent::ExitRequested { code, api, .. } => { if code.is_none() { api.prevent_exit(); diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index ab5543d82a9..3d3cafac486 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -77,6 +77,14 @@ "bannerPath": "assets/wix-banner.bmp", "dialogImagePath": "assets/wix-dialog.bmp" } - } + }, + "fileAssociations": [ + { + "ext": ["cap"], + "name": "Cap Project", + "mimeType": "application/x-cap-project", + "role": "Editor" + } + ] } } From 8748e3d714fbd4b4ce94090b078a2bf164746c09 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 9 Apr 2025 14:34:48 +0100 Subject: [PATCH 2/9] feat: Close main window on open --- apps/desktop/src-tauri/src/lib.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 95dc97f3ef1..9c45078a568 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -2227,6 +2227,9 @@ pub async fn run(recording_logging_handle: LoggingHandle) { .show(&app_handle) .await .ok(); + if let Some(main_window) = CapWindowId::Main.get(&app_handle) { + main_window.close().ok(); + } }); return; } @@ -2487,17 +2490,25 @@ pub async fn run(recording_logging_handle: LoggingHandle) { let mp4_path = path.join("content/output.mp4"); if mp4_path.exists() && mp4_path.is_file() { - // Open the MP4 file with the system's default video player let _ = app_handle .shell() .open(mp4_path.to_str().unwrap_or_default(), None); + if let Some(main_window) = + CapWindowId::Main.get(&app_handle) + { + main_window.close().ok(); + } } else { - // Proceed with opening the editor as before tokio::spawn(async move { ShowCapWindow::Editor { project_id } .show(&app_handle) .await .ok(); + if let Some(main_window) = + CapWindowId::Main.get(&app_handle) + { + main_window.close().ok(); + } }); } } From 6cb3a1b34483e686880c0e110183edccc63c1ef2 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Wed, 9 Apr 2025 14:35:59 +0100 Subject: [PATCH 3/9] Remove logs --- apps/desktop/src-tauri/src/lib.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 9c45078a568..1d17c6b7d94 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -2414,9 +2414,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) { .await; }); - // Tauri v2 handles file associations through the fileAssociations configuration - // and file drop events are handled in the on_window_event handler - Ok(()) }) .on_window_event(|window, event| { @@ -2550,10 +2547,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) { let _ = tokio::spawn(async move { ShowCapWindow::Main.show(&handle).await }); } } - tauri::RunEvent::Ready => { - // Nothing special to do on ready - the file associations are configured - // in tauri.conf.json and the single-instance plugin will handle file opening - } tauri::RunEvent::ExitRequested { code, api, .. } => { if code.is_none() { api.prevent_exit(); From 6c01a9cdaf4648f21cf07b843d1e13782777f590 Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Sat, 12 Apr 2025 17:55:19 +0800 Subject: [PATCH 4/9] simplify project opening --- apps/desktop/src-tauri/src/lib.rs | 97 +++++++++++---------------- apps/desktop/src-tauri/src/windows.rs | 4 ++ 2 files changed, 43 insertions(+), 58 deletions(-) diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 1d17c6b7d94..4e223b0c463 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -2210,34 +2210,16 @@ pub async fn run(recording_logging_handle: LoggingHandle) { #[allow(unused_mut)] let mut builder = tauri::Builder::default().plugin(tauri_plugin_single_instance::init(|app, args, _cwd| { - let cap_file = args + let Some(cap_file) = args .iter() .find(|arg| arg.ends_with(".cap")) - .map(|arg| std::path::PathBuf::from(arg)); - - if let Some(path) = cap_file { - if path.exists() && path.is_file() { - if let Some(file_name) = path.file_stem() { - let project_id = file_name.to_string_lossy().to_string(); - println!("Opening .cap file: {}", project_id); - - let app_handle = app.clone(); - tokio::spawn(async move { - ShowCapWindow::Editor { project_id } - .show(&app_handle) - .await - .ok(); - if let Some(main_window) = CapWindowId::Main.get(&app_handle) { - main_window.close().ok(); - } - }); - return; - } - } - } + .map(PathBuf::from) + else { + let _ = ShowCapWindow::Main.show(app); + return; + }; - // Default behavior if no .cap file was passed - let _ = ShowCapWindow::Main.show(app); + let _ = open_project_from_path(&cap_file, app.clone()); })); #[cfg(target_os = "macos")] @@ -2477,39 +2459,8 @@ pub async fn run(recording_logging_handle: LoggingHandle) { } WindowEvent::DragDrop(event) => { if let tauri::DragDropEvent::Drop { paths, .. } = event { - if let Some(path) = paths.first() { - if path.extension().map_or(false, |ext| ext == "cap") { - if let Some(file_name) = path.file_stem() { - let project_id = file_name.to_string_lossy().to_string(); - let app_handle = app.clone(); - - // Check if content/output.mp4 exists inside the .cap folder - let mp4_path = path.join("content/output.mp4"); - - if mp4_path.exists() && mp4_path.is_file() { - let _ = app_handle - .shell() - .open(mp4_path.to_str().unwrap_or_default(), None); - if let Some(main_window) = - CapWindowId::Main.get(&app_handle) - { - main_window.close().ok(); - } - } else { - tokio::spawn(async move { - ShowCapWindow::Editor { project_id } - .show(&app_handle) - .await - .ok(); - if let Some(main_window) = - CapWindowId::Main.get(&app_handle) - { - main_window.close().ok(); - } - }); - } - } - } + for path in paths { + let _ = open_project_from_path(path, app.clone()); } } } @@ -2672,3 +2623,33 @@ impl, T, E> TransposeAsync for Result { } } } + +fn open_project_from_path(path: &PathBuf, app: AppHandle) -> Result<(), String> { + let meta = RecordingMeta::load_for_project(path)?; + + match &meta.inner { + RecordingMetaInner::Studio(_) => { + let project_id = path + .file_stem() + .ok_or_else(|| "No file stem".to_string())? + .to_string_lossy() + .to_string(); + + tokio::spawn(async move { ShowCapWindow::Editor { project_id }.show(&app).await }); + } + RecordingMetaInner::Instant(_) => { + let mp4_path = path.join("content/output.mp4"); + + if mp4_path.exists() && mp4_path.is_file() { + let _ = app + .shell() + .open(mp4_path.to_str().unwrap_or_default(), None); + if let Some(main_window) = CapWindowId::Main.get(&app) { + main_window.close().ok(); + } + } + } + } + + Ok(()) +} diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs index 39543ce497e..e86473c89a7 100644 --- a/apps/desktop/src-tauri/src/windows.rs +++ b/apps/desktop/src-tauri/src/windows.rs @@ -228,6 +228,10 @@ impl ShowCapWindow { .center() .build()?, Self::Editor { project_id } => { + if let Some(main) = CapWindowId::Main.get(app) { + let _ = main.close(); + }; + let window = self .window_builder(app, format!("/editor?id={project_id}")) .maximizable(true) From a1f4b42fd558f59aee5e795ae00d55a01416cb15 Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Sat, 12 Apr 2025 17:56:34 +0800 Subject: [PATCH 5/9] cleanup --- apps/desktop/src-tauri/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 4e223b0c463..b46f7788f22 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -2299,7 +2299,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) { capture_system_audio: false, }, current_recording: None, - recording_logging_handle: recording_logging_handle.clone(), + recording_logging_handle, }))); app.manage(Arc::new(RwLock::new( From b423bc732c57954b38ea0198e08a8c02795ab670 Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Sun, 13 Apr 2025 14:28:09 +0800 Subject: [PATCH 6/9] remove recording IDs entirely --- Cargo.lock | 19 ++ apps/desktop/src-tauri/Cargo.toml | 1 + apps/desktop/src-tauri/src/editor_window.rs | 6 +- apps/desktop/src-tauri/src/export.rs | 74 ++---- apps/desktop/src-tauri/src/lib.rs | 247 +++++------------- apps/desktop/src-tauri/src/recording.rs | 5 +- apps/desktop/src-tauri/src/windows.rs | 75 ++++-- .../(window-chrome)/settings/recordings.tsx | 25 +- .../(window-chrome)/settings/screenshots.tsx | 4 +- apps/desktop/src/routes/editor/Editor.tsx | 38 ++- .../src/routes/editor/ExportDialog.tsx | 22 +- .../desktop/src/routes/editor/ShareButton.tsx | 18 +- apps/desktop/src/routes/editor/context.ts | 8 +- .../desktop/src/routes/recordings-overlay.tsx | 6 +- apps/desktop/src/utils/tauri.ts | 40 ++- crates/editor/src/editor_instance.rs | 26 +- 16 files changed, 252 insertions(+), 362 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 37ed6c519e8..20be214a873 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -573,6 +573,15 @@ dependencies = [ "rustc-demangle", ] +[[package]] +name = "base64" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b25d992356d2eb0ed82172f5248873db5560c4721f564b13cb5193bda5e668e" +dependencies = [ + "byteorder", +] + [[package]] name = "base64" version = "0.21.7" @@ -955,6 +964,7 @@ dependencies = [ "nix 0.29.0", "objc", "objc2-app-kit 0.3.0", + "paths-as-strings", "png", "rand 0.8.5", "relative-path", @@ -5319,6 +5329,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" +[[package]] +name = "paths-as-strings" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7963201bed34799ddd0f54a2e1e4c5082313ca260db118822109f344f13b285c" +dependencies = [ + "base64 0.10.1", +] + [[package]] name = "peeking_take_while" version = "0.1.2" diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index dc96d3951f1..dbf926af45f 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -90,6 +90,7 @@ relative-path = "1.9.3" cap-fail = { version = "0.1.0", path = "../../../crates/fail" } tokio-stream = { version = "0.1.17", features = ["sync"] } md5 = "0.7.0" +paths-as-strings = "0.1.1" [target.'cfg(target_os = "macos")'.dependencies] core-graphics = "0.24.0" diff --git a/apps/desktop/src-tauri/src/editor_window.rs b/apps/desktop/src-tauri/src/editor_window.rs index 83ae9d9e47a..6e6d3f983b4 100644 --- a/apps/desktop/src-tauri/src/editor_window.rs +++ b/apps/desktop/src-tauri/src/editor_window.rs @@ -1,4 +1,4 @@ -use std::{collections::HashMap, ops::Deref, sync::Arc}; +use std::{collections::HashMap, ops::Deref, path::PathBuf, sync::Arc}; use cap_editor::EditorInstance; use tauri::{ipc::CommandArg, Manager, Runtime, Window}; @@ -47,7 +47,7 @@ impl<'de, R: Runtime> CommandArg<'de, R> for WindowEditorInstance { impl EditorInstances { pub async fn get_or_create( window: &Window, - video_id: &str, + path: PathBuf, ) -> Result, String> { let instances = match window.try_state::() { Some(s) => (*s).clone(), @@ -64,7 +64,7 @@ impl EditorInstances { match instances.entry(window.label().to_string()) { Entry::Vacant(entry) => { - let instance = create_editor_instance_impl(window.app_handle(), video_id).await?; + let instance = create_editor_instance_impl(window.app_handle(), path).await?; entry.insert(instance.clone()); Ok(instance) } diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs index 53a91e3d61f..71d671ccbb6 100644 --- a/apps/desktop/src-tauri/src/export.rs +++ b/apps/desktop/src-tauri/src/export.rs @@ -1,7 +1,4 @@ -use crate::{ - create_editor_instance_impl, get_video_metadata, recordings_path, windows::ShowCapWindow, - AuthStore, RenderProgress, VideoType, -}; +use crate::{create_editor_instance_impl, get_video_metadata, RenderProgress}; use cap_editor::EditorInstance; use cap_project::{ProjectConfiguration, RecordingMeta, XY}; use std::path::PathBuf; @@ -11,34 +8,25 @@ use tauri::AppHandle; #[specta::specta] pub async fn export_video( app: AppHandle, - video_id: String, + path: PathBuf, progress: tauri::ipc::Channel, force: bool, fps: u32, resolution_base: XY, ) -> Result { - let editor_instance = create_editor_instance_impl(&app, &video_id).await?; - - let screen_metadata = - match get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Screen)).await { - Ok(meta) => meta, - Err(e) => { - sentry::capture_message( - &format!("Failed to get video metadata: {}", e), - sentry::Level::Error, - ); - return Err( - "Failed to read video metadata. The recording may be from an incompatible version." - .to_string(), - ); - } - }; + let editor_instance = create_editor_instance_impl(&app, path.clone()).await?; + + let screen_metadata = get_video_metadata(path.clone()).await.map_err(|e| { + sentry::capture_message( + &format!("Failed to get video metadata: {}", e), + sentry::Level::Error, + ); + "Failed to read video metadata. The recording may be from an incompatible version." + .to_string() + })?; // Get camera metadata if it exists - let camera_metadata = - get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Camera)) - .await - .ok(); + let camera_metadata = get_video_metadata(path.clone()).await.ok(); // Use the longer duration between screen and camera let duration = screen_metadata.duration.max( @@ -71,7 +59,7 @@ pub async fn export_video( } } - let exporter = cap_export::Exporter::new( + cap_export::Exporter::new( modified_project, output_path.clone(), move |frame_index| { @@ -82,7 +70,7 @@ pub async fn export_video( .ok(); }, editor_instance.project_path.clone(), - editor_instance.meta(), + editor_instance.meta().clone(), editor_instance.render_constants.clone(), &editor_instance.segments, fps, @@ -93,17 +81,13 @@ pub async fn export_video( .map_err(|e| { sentry::capture_message(&e.to_string(), sentry::Level::Error); e.to_string() - })?; - - let result = exporter.export_with_custom_muxer().await; - - match result { - Ok(_) => Ok(output_path), - Err(e) => { - sentry::capture_message(&e.to_string(), sentry::Level::Error); - Err(e.to_string()) - } - } + })? + .export_with_custom_muxer() + .await + .map_err(|e| { + sentry::capture_message(&e.to_string(), sentry::Level::Error); + e.to_string() + }) } #[derive(Debug, serde::Serialize, specta::Type)] @@ -117,17 +101,12 @@ pub struct ExportEstimates { #[tauri::command] #[specta::specta] pub async fn get_export_estimates( - app: AppHandle, - video_id: String, + path: PathBuf, resolution: XY, fps: u32, ) -> Result { - let screen_metadata = - get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Screen)).await?; - let camera_metadata = - get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Camera)) - .await - .ok(); + let screen_metadata = get_video_metadata(path.clone()).await?; + let camera_metadata = get_video_metadata(path.clone()).await.ok(); let raw_duration = screen_metadata.duration.max( camera_metadata @@ -135,8 +114,7 @@ pub async fn get_export_estimates( .unwrap_or(screen_metadata.duration), ); - let project_path = EditorInstance::project_path(&recordings_path(&app), &video_id); - let meta = RecordingMeta::load_for_project(&project_path).unwrap(); + let meta = RecordingMeta::load_for_project(&path).unwrap(); let project_config = meta.project_config(); let duration_seconds = if let Some(timeline) = &project_config.timeline { timeline diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index b46f7788f22..7796451cc46 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -22,6 +22,8 @@ mod windows; use audio::AppSounds; use auth::{AuthStore, AuthenticationInvalid, Plan}; +use base64::prelude::BASE64_STANDARD; +use base64::Engine; use camera::create_camera_preview_ws; use cap_editor::EditorInstance; use cap_editor::EditorState; @@ -59,6 +61,7 @@ use serde::{Deserialize, Serialize}; use serde_json::json; use specta::Type; use std::collections::BTreeMap; +use std::ffi::OsString; use std::time::Duration; use std::{ fs::File, @@ -74,6 +77,7 @@ use tauri::Window; use tauri::{AppHandle, Manager, State, WindowEvent}; use tauri_plugin_dialog::DialogExt; use tauri_plugin_notification::{NotificationExt, PermissionState}; +use tauri_plugin_opener::OpenerExt; use tauri_plugin_shell::ShellExt; use tauri_specta::Event; use tokio::sync::{Mutex, RwLock}; @@ -85,6 +89,7 @@ use tracing_subscriber::Layer; use upload::{get_s3_config, upload_image, upload_video, S3UploadMeta}; use web_api::ManagerExt as WebManagerExt; use windows::set_window_transparent; +use windows::EditorWindowIds; use windows::{CapWindowId, ShowCapWindow}; #[derive(specta::Type, Serialize)] @@ -982,15 +987,25 @@ struct SerializedEditorInstance { #[tauri::command] #[specta::specta] -async fn create_editor_instance( - window: Window, - video_id: String, -) -> Result { - let editor_instance = EditorInstances::get_or_create(&window, &video_id).await?; +async fn create_editor_instance(window: Window) -> Result { + let CapWindowId::Editor { id } = CapWindowId::from_str(window.label()).unwrap() else { + return Err("Invalid window".to_string()); + }; + + let path = { + let window_ids = EditorWindowIds::get(window.app_handle()); + let window_ids = window_ids.ids.lock().unwrap(); + + let Some((path, _)) = window_ids.iter().find(|(_, _id)| *_id == id) else { + return Err("Editor instance not found".to_string()); + }; + path.clone() + }; + + let editor_instance = EditorInstances::get_or_create(&window, path).await?; // Load the RecordingMeta to get the pretty name - let meta = RecordingMeta::load_for_project(&editor_instance.project_path) - .map_err(|e| format!("Failed to load recording meta: {}", e))?; + let meta = editor_instance.meta(); println!("Pretty name: {}", meta.pretty_name); @@ -1003,7 +1018,7 @@ async fn create_editor_instance( }, recordings: editor_instance.recordings.clone(), path: editor_instance.project_path.clone(), - meta, + meta: meta.clone(), }) } @@ -1026,25 +1041,8 @@ async fn copy_video_to_clipboard( #[tauri::command] #[specta::specta] -async fn get_video_metadata( - app: AppHandle, - video_id: String, - video_type: Option, -) -> Result { - let video_id = if video_id.ends_with(".cap") { - video_id.trim_end_matches(".cap").to_string() - } else { - video_id - }; - - let project_path = app - .path() - .app_data_dir() - .unwrap() - .join("recordings") - .join(format!("{}.cap", video_id)); - - let recording_meta = RecordingMeta::load_for_project(&project_path)?; +async fn get_video_metadata(path: PathBuf) -> Result { + let recording_meta = RecordingMeta::load_for_project(&path)?; fn get_duration_for_path(path: PathBuf) -> Result { let reader = BufReader::new( @@ -1071,7 +1069,7 @@ async fn get_video_metadata( let display_paths = match &recording_meta.inner { RecordingMetaInner::Instant(_) => { - vec![project_path.join("content/output.mp4")] + vec![path.join("content/output.mp4")] } RecordingMetaInner::Studio(meta) => match meta { StudioRecordingMeta::SingleSegment { segment } => { @@ -1117,19 +1115,6 @@ async fn get_video_metadata( }) } -#[tauri::command] -#[specta::specta] -async fn open_editor(app: AppHandle, id: String) -> Result<(), String> { - println!("Opening editor for recording: {}", id); - - ShowCapWindow::Editor { project_id: id } - .show(&app) - .await - .unwrap(); - - Ok(()) -} - #[tauri::command] #[specta::specta] fn close_recordings_overlay_window(app: AppHandle) { @@ -1228,7 +1213,7 @@ pub enum UploadMode { #[specta::specta] async fn upload_exported_video( app: AppHandle, - video_id: String, + path: PathBuf, mode: UploadMode, ) -> Result { let Ok(Some(auth)) = AuthStore::get(&app) else { @@ -1237,26 +1222,18 @@ async fn upload_exported_video( }; // Get video metadata to check duration - let screen_metadata = - match get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Screen)).await { - Ok(meta) => meta, - Err(e) => { - sentry::capture_message( - &format!("Failed to get video metadata: {}", e), - sentry::Level::Error, - ); - return Err( - "Failed to read video metadata. The recording may be from an incompatible version." - .to_string(), - ); - } - }; + let screen_metadata = get_video_metadata(path.clone()).await.map_err(|e| { + sentry::capture_message( + &format!("Failed to get video metadata: {}", e), + sentry::Level::Error, + ); + + "Failed to read video metadata. The recording may be from an incompatible version." + .to_string() + })?; // Get camera metadata if it exists - let camera_metadata = - get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Camera)) - .await - .ok(); + let camera_metadata = get_video_metadata(path.clone()).await.ok(); // Use the longer duration between screen and camera let duration = screen_metadata.duration.max( @@ -1271,13 +1248,7 @@ async fn upload_exported_video( return Ok(UploadResult::UpgradeRequired); } - let mut meta = RecordingMeta::load_for_project( - &app.path() - .app_data_dir() - .unwrap() - .join("recordings") - .join(format!("{}.cap", video_id)), - )?; + let mut meta = RecordingMeta::load_for_project(&path)?; let output_path = meta.output_path(); if !output_path.exists() { @@ -1314,9 +1285,11 @@ async fn upload_exported_video( } .await?; + let upload_id = s3_config.id().to_string(); + match upload_video( &app, - video_id.clone(), + upload_id.clone(), output_path, Some(s3_config), Some(meta.project_path.join("screenshots/display.jpg")), @@ -1337,7 +1310,6 @@ async fn upload_exported_video( id: uploaded_video.id.clone(), }); meta.save_for_project().ok(); - RecordingMetaChanged { id: video_id }.emit(&app).ok(); let _ = app .state::>() @@ -1394,17 +1366,6 @@ async fn upload_screenshot( }); meta.save_for_project(); - RecordingMetaChanged { - id: screenshot_path - .file_stem() - .unwrap() - .to_str() - .unwrap() - .to_string(), - } - .emit(&app) - .ok(); - uploaded.link }; @@ -1631,11 +1592,6 @@ async fn save_file_dialog( } } -#[derive(Serialize, specta::Type, tauri_specta::Event, Debug, Clone)] -struct RecordingMetaChanged { - id: String, -} - #[derive(Serialize, specta::Type)] pub struct RecordingMetaWithType { #[serde(flatten)] @@ -1666,25 +1622,17 @@ pub enum RecordingType { #[specta::specta] fn get_recording_meta( app: AppHandle, - id: String, + path: PathBuf, file_type: String, ) -> Result { - let meta_path = match file_type.as_str() { - "recording" => recording_path(&app, &id), - "screenshot" => screenshot_path(&app, &id), - _ => return Err("Invalid file type".to_string()), - }; - - RecordingMeta::load_for_project(&meta_path) + RecordingMeta::load_for_project(&path) .map(RecordingMetaWithType::new) .map_err(|e| format!("Failed to load recording meta: {}", e)) } #[tauri::command] #[specta::specta] -fn list_recordings( - app: AppHandle, -) -> Result, String> { +fn list_recordings(app: AppHandle) -> Result, String> { let recordings_dir = recordings_path(&app); // First check if directory exists @@ -1707,33 +1655,22 @@ fn list_recordings( return None; } - let extension = match path.extension().and_then(|s| s.to_str()) { - Some("cap") => "cap", - _ => return None, - }; - - let id = match path.file_stem().and_then(|s| s.to_str()) { - Some(stem) => stem.to_string(), - None => return None, - }; - // Try to get recording meta, skip if it fails - match get_recording_meta(app.clone(), id.clone(), "recording".to_string()) { - Ok(meta) => Some((id, path.clone(), meta)), - Err(e) => None, - } + get_recording_meta(app.clone(), path.clone(), "recording".to_string()) + .ok() + .map(|meta| (path, meta)) }) .collect::>(); // Sort the result by creation date of the actual file, newest first result.sort_by(|a, b| { let b_time = - b.1.metadata() + b.0.metadata() .and_then(|m| m.created()) .unwrap_or(std::time::SystemTime::UNIX_EPOCH); let a_time = - a.1.metadata() + a.0.metadata() .and_then(|m| m.created()) .unwrap_or(std::time::SystemTime::UNIX_EPOCH); @@ -1745,7 +1682,7 @@ fn list_recordings( #[tauri::command] #[specta::specta] -fn list_screenshots(app: AppHandle) -> Result, String> { +fn list_screenshots(app: AppHandle) -> Result, String> { let screenshots_dir = screenshots_path(&app); let mut result = std::fs::read_dir(&screenshots_dir) @@ -1754,9 +1691,8 @@ fn list_screenshots(app: AppHandle) -> Result meta.inner, Err(_) => return None, // Skip this entry if metadata can't be loaded }; @@ -1768,7 +1704,7 @@ fn list_screenshots(app: AppHandle) -> Result Result Result<(), String> { - let recording_dir = app - .path() - .app_data_dir() - .unwrap() - .join("recordings") - .join(format!("{video_id}.cap")); - - let meta = RecordingMeta::load_for_project(&recording_dir)?; - - let Some(share_id) = meta.sharing.map(|s| s.id) else { - return Err("Video share data not found".to_string()); - }; - - let config = match AuthStore::get(&app).ok().flatten() { - Some(_) => match get_s3_config(&app, false, Some(share_id)).await { - Ok(s3_config) => { - let link = web_api::make_url(format!("/s/{}", s3_config.id())); - info!("Created shareable link: {}", link); - - VideoUploadInfo { - id: s3_config.id().to_string(), - link: link.clone(), - config: s3_config, - } - } - Err(e) => return Err(format!("Failed to get upload config: {e}")), - }, - // Allow the recording to proceed without error for any signed-in user - _ => { - // User is not signed in - ShowCapWindow::SignIn.show(&app).await.ok(); - return Err("Please sign in to use instant recording".to_string()); - } - }; - - upload::InstantMultipartUpload::run( - app, - video_id, - recording_dir.join("content/output.mp4"), - config, - None, - ) - .await?; - - Ok(()) -} - async fn check_notification_permissions(app: AppHandle) { // Check if we've already requested permissions let Ok(Some(settings)) = GeneralSettingsStore::get(&app) else { @@ -2135,7 +2021,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) { stop_playback, set_playhead_position, set_project_config, - open_editor, permissions::open_permission_settings, permissions::do_permissions_check, permissions::request_permission, @@ -2162,7 +2047,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) { list_fails, set_fail, update_auth_plan, - reupload_instant_video, set_window_transparent ]) .events(tauri_specta::collect_events![ @@ -2172,7 +2056,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) { RenderFrameEvent, EditorStateChanged, CurrentRecordingChanged, - RecordingMetaChanged, RecordingStarted, RecordingStopped, RequestStartRecording, @@ -2272,6 +2155,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) { hotkeys::init(&app); general_settings::init(&app); fake_window::init(&app); + app.manage(EditorWindowIds::default()); if let Ok(Some(auth)) = AuthStore::load(&app) { sentry::configure_scope(|scope| { @@ -2422,7 +2306,10 @@ pub async fn run(recording_logging_handle: LoggingHandle) { } }); } - CapWindowId::Editor { .. } => { + CapWindowId::Editor { id } => { + let window_ids = EditorWindowIds::get(window.app_handle()); + window_ids.ids.lock().unwrap().retain(|(_, _id)| *_id != id); + tokio::spawn(EditorInstances::remove(window.clone())); } CapWindowId::Settings | CapWindowId::Upgrade => { @@ -2509,11 +2396,11 @@ pub async fn run(recording_logging_handle: LoggingHandle) { async fn create_editor_instance_impl( app: &AppHandle, - video_id: &str, + path: PathBuf, ) -> Result, String> { let app = app.clone(); - let instance = EditorInstance::new(recordings_path(&app), video_id, { + let instance = EditorInstance::new(path, { let app = app.clone(); move |state| { EditorStateChanged::new(state).emit(&app).ok(); @@ -2629,21 +2516,17 @@ fn open_project_from_path(path: &PathBuf, app: AppHandle) -> Result<(), String> match &meta.inner { RecordingMetaInner::Studio(_) => { - let project_id = path - .file_stem() - .ok_or_else(|| "No file stem".to_string())? - .to_string_lossy() - .to_string(); + let project_path = path.clone(); - tokio::spawn(async move { ShowCapWindow::Editor { project_id }.show(&app).await }); + tokio::spawn(async move { ShowCapWindow::Editor { project_path }.show(&app).await }); } RecordingMetaInner::Instant(_) => { let mp4_path = path.join("content/output.mp4"); if mp4_path.exists() && mp4_path.is_file() { let _ = app - .shell() - .open(mp4_path.to_str().unwrap_or_default(), None); + .opener() + .open_path(mp4_path.to_str().unwrap_or_default(), None::); if let Some(main_window) = CapWindowId::Main.get(&app) { main_window.close().ok(); } diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs index db91ce75fe0..3b9e1131c3f 100644 --- a/apps/desktop/src-tauri/src/recording.rs +++ b/apps/desktop/src-tauri/src/recording.rs @@ -7,7 +7,7 @@ use crate::{ general_settings::{ GeneralSettingsStore, MainWindowRecordingStartBehaviour, PostStudioRecordingBehaviour, }, - open_editor, open_external_link, + open_external_link, presets::PresetsStore, upload::{get_s3_config, prepare_screenshot_upload, upload_video, InstantMultipartUpload}, web_api, @@ -15,6 +15,7 @@ use crate::{ App, CurrentRecordingChanged, DynLoggingLayer, MutableState, NewStudioRecordingAdded, RecordingStarted, RecordingStopped, VideoUploadInfo, }; +use base64::{prelude::BASE64_STANDARD, Engine}; use cap_fail::fail; use cap_media::{feeds::CameraFeed, sources::ScreenCaptureTarget}; use cap_media::{ @@ -613,7 +614,7 @@ async fn handle_recording_finish( { PostStudioRecordingBehaviour::OpenEditor => { let _ = ShowCapWindow::Editor { - project_id: id.clone(), + project_path: recording_dir, } .show(&app) .await; diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs index e86473c89a7..8f9be84b35a 100644 --- a/apps/desktop/src-tauri/src/windows.rs +++ b/apps/desktop/src-tauri/src/windows.rs @@ -7,7 +7,12 @@ use cap_media::sources::CaptureScreen; use futures::pin_mut; use serde::Deserialize; use specta::Type; -use std::{path::PathBuf, str::FromStr, sync::Arc}; +use std::{ + ops::Deref, + path::PathBuf, + str::FromStr, + sync::{atomic::AtomicU32, Arc, Mutex}, +}; use tauri::{ AppHandle, LogicalPosition, Manager, Monitor, PhysicalPosition, PhysicalSize, WebviewUrl, WebviewWindow, WebviewWindowBuilder, Wry, @@ -24,7 +29,7 @@ pub enum CapWindowId { Setup, Main, Settings, - Editor { project_id: String }, + Editor { id: u32 }, RecordingsOverlay, WindowCaptureOccluder, CaptureArea, @@ -52,7 +57,10 @@ impl FromStr for CapWindowId { "signin" => Self::SignIn, "mode-select" => Self::ModeSelect, s if s.starts_with("editor-") => Self::Editor { - project_id: s.replace("editor-", ""), + id: s + .replace("editor-", "") + .parse::() + .map_err(|e| e.to_string())?, }, _ => return Err(format!("unknown window label: {}", s)), }) @@ -73,7 +81,7 @@ impl std::fmt::Display for CapWindowId { Self::Upgrade => write!(f, "upgrade"), Self::SignIn => write!(f, "signin"), Self::ModeSelect => write!(f, "mode-select"), - Self::Editor { project_id } => write!(f, "editor-{}", project_id), + Self::Editor { id } => write!(f, "editor-{id}"), } } } @@ -150,7 +158,7 @@ pub enum ShowCapWindow { Setup, Main, Settings { page: Option }, - Editor { project_id: String }, + Editor { project_path: PathBuf }, RecordingsOverlay, WindowCaptureOccluder, CaptureArea { screen_id: u32 }, @@ -163,12 +171,25 @@ pub enum ShowCapWindow { impl ShowCapWindow { pub async fn show(&self, app: &AppHandle) -> tauri::Result { - if let Some(window) = self.id().get(app) { + if let Self::Editor { project_path } = self { + let state = app.state::(); + let mut s = state.ids.lock().unwrap(); + if s.iter().find(|(path, _)| path == project_path).is_none() { + s.push(( + project_path.clone(), + state + .counter + .fetch_add(1, std::sync::atomic::Ordering::SeqCst), + )); + } + } + + if let Some(window) = self.id(app).get(app) { window.set_focus().ok(); return Ok(window); } - let id = self.id(); + let id = self.id(app); let monitor = app.primary_monitor()?.unwrap(); let window = match self { @@ -227,13 +248,13 @@ impl ShowCapWindow { .maximized(false) .center() .build()?, - Self::Editor { project_id } => { + Self::Editor { .. } => { if let Some(main) = CapWindowId::Main.get(app) { let _ = main.close(); }; let window = self - .window_builder(app, format!("/editor?id={project_id}")) + .window_builder(app, "/editor") .maximizable(true) .inner_size(1240.0, 800.0) .center() @@ -485,13 +506,14 @@ impl ShowCapWindow { app: &'a AppHandle, url: impl Into, ) -> WebviewWindowBuilder<'a, Wry, AppHandle> { - let id = self.id(); + let id = self.id(app); - let mut builder = WebviewWindow::builder(app, id.label(), WebviewUrl::App(url.into())) - .title(id.title()) - .visible(false) - .accept_first_mouse(true) - .shadow(true); + let mut builder = + WebviewWindow::builder(app, dbg!(id.label()), WebviewUrl::App(url.into())) + .title(id.title()) + .visible(false) + .accept_first_mouse(true) + .shadow(true); if let Some(min) = id.min_size() { builder = builder @@ -518,14 +540,17 @@ impl ShowCapWindow { builder } - pub fn id(&self) -> CapWindowId { + pub fn id(&self, app: &AppHandle) -> CapWindowId { match self { ShowCapWindow::Setup => CapWindowId::Setup, ShowCapWindow::Main => CapWindowId::Main, ShowCapWindow::Settings { .. } => CapWindowId::Settings, - ShowCapWindow::Editor { project_id } => CapWindowId::Editor { - project_id: project_id.clone(), - }, + ShowCapWindow::Editor { project_path } => { + let state = app.state::(); + let s = state.ids.lock().unwrap(); + let id = s.iter().find(|(path, _)| path == project_path).unwrap().1; + CapWindowId::Editor { id } + } ShowCapWindow::RecordingsOverlay => CapWindowId::RecordingsOverlay, ShowCapWindow::WindowCaptureOccluder => CapWindowId::WindowCaptureOccluder, ShowCapWindow::CaptureArea { .. } => CapWindowId::CaptureArea, @@ -660,3 +685,15 @@ pub fn set_window_transparent(window: tauri::Window, value: bool) { } } } + +#[derive(Default, Clone)] +pub struct EditorWindowIds { + pub ids: Arc>>, + pub counter: Arc, +} + +impl EditorWindowIds { + pub fn get(app: &AppHandle) -> Self { + app.state::().deref().clone() + } +} diff --git a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx index 8201de65ab6..f5230e7378a 100644 --- a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx +++ b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx @@ -25,7 +25,6 @@ import { commands, events, RecordingMetaWithType } from "~/utils/tauri"; type Recording = { meta: RecordingMetaWithType; - id: string; path: string; prettyName: string; thumbnailPath: string; @@ -55,12 +54,11 @@ const recordingsQuery = queryOptions({ const recordings = await Promise.all( result.map(async (file) => { - const [id, path, meta] = file; + const [path, meta] = file; const thumbnailPath = `${path}/screenshots/display.jpg`; return { meta, - id, path, prettyName: meta.pretty_name, thumbnailPath, @@ -90,28 +88,24 @@ export default function Recordings() { }); const handleRecordingClick = (recording: Recording) => { - trackEvent("recording_view_clicked", { recording_id: recording.id }); + trackEvent("recording_view_clicked"); events.newStudioRecordingAdded.emit({ path: recording.path }); }; const handleOpenFolder = (path: string) => { - trackEvent("recording_folder_clicked", { path }); + trackEvent("recording_folder_clicked"); commands.openFilePath(path); }; const handleCopyVideoToClipboard = (path: string) => { - trackEvent("recording_copy_clicked", { path }); + trackEvent("recording_copy_clicked"); commands.copyVideoToClipboard(path); }; - const handleOpenEditor = (id: string) => { - const normalizedPath = id.replace(/\\/g, "/"); - const fileName = normalizedPath.split("/").pop() || ""; - trackEvent("recording_editor_clicked", { - recording_id: fileName.replace(".cap", ""), - }); + const handleOpenEditor = (path: string) => { + trackEvent("recording_editor_clicked"); commands.showWindow({ - Editor: { project_id: fileName.replace(".cap", "") }, + Editor: { project_path: path }, }); }; @@ -238,7 +232,10 @@ function RecordingItem(props: { {(_) => { const reupload = createMutation(() => ({ mutationFn: () => { - return commands.reuploadInstantVideo(props.recording.id); + return commands.uploadExportedVideo( + props.recording.path, + "Reupload" + ); }, })); diff --git a/apps/desktop/src/routes/(window-chrome)/settings/screenshots.tsx b/apps/desktop/src/routes/(window-chrome)/settings/screenshots.tsx index 89acf359a07..618a9790883 100644 --- a/apps/desktop/src/routes/(window-chrome)/settings/screenshots.tsx +++ b/apps/desktop/src/routes/(window-chrome)/settings/screenshots.tsx @@ -5,7 +5,6 @@ import { convertFileSrc } from "@tauri-apps/api/core"; import { commands, events } from "~/utils/tauri"; type MediaEntry = { - id: string; path: string; prettyName: string; isNew: boolean; @@ -24,10 +23,9 @@ export default function Screenshots() { ); const screenshots = await Promise.all( result.map(async (file) => { - const [id, pngPath, meta] = file; + const [pngPath, meta] = file; return { - id, path: pngPath, prettyName: meta.pretty_name, isNew: false, diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx index e7b1b5b7836..86ecabe599a 100644 --- a/apps/desktop/src/routes/editor/Editor.tsx +++ b/apps/desktop/src/routes/editor/Editor.tsx @@ -44,31 +44,27 @@ import { } from "./ui"; export function Editor() { - const [params] = useSearchParams<{ id: string }>(); + const [params] = useSearchParams<{ path: string }>(); return ( - - {(videoId) => ( - - { - const ctx = useEditorInstanceContext(); - const editorInstance = ctx.editorInstance(); + + { + const ctx = useEditorInstanceContext(); + const editorInstance = ctx.editorInstance(); - if (!editorInstance) return; + if (!editorInstance) return; - return { editorInstance }; - })()} - > - {(values) => ( - - - - )} - - - )} - + return { editorInstance }; + })()} + > + {(values) => ( + + + + )} + + ); } diff --git a/apps/desktop/src/routes/editor/ExportDialog.tsx b/apps/desktop/src/routes/editor/ExportDialog.tsx index cc9ecb6b097..4d384549a66 100644 --- a/apps/desktop/src/routes/editor/ExportDialog.tsx +++ b/apps/desktop/src/routes/editor/ExportDialog.tsx @@ -68,7 +68,7 @@ type ExportToOption = (typeof EXPORT_TO_OPTIONS)[number]["value"]; const ExportDialog = () => { const { - videoId, + path, prettyName, setDialog, exportState, @@ -115,15 +115,13 @@ const ExportDialog = () => { const [exportEstimates] = createResource( () => ({ - videoId, resolution: { x: selectedResolution().width, y: selectedResolution().height, }, fps: selectedFps(), }), - (params) => - commands.getExportEstimates(params.videoId, params.resolution, params.fps) + (params) => commands.getExportEstimates(path, params.resolution, params.fps) ); const exportButtonIcon: Record<"file" | "clipboard" | "link", JSX.Element> = { file: , @@ -167,7 +165,7 @@ const ExportDialog = () => { // First try to get existing rendered video const outputPath = await commands.exportVideo( - videoId, + path, progress, true, selectedFps(), @@ -200,7 +198,7 @@ const ExportDialog = () => { })); const [recordingMeta, metaActions] = createResource(() => - commands.getRecordingMeta(videoId, "recording") + commands.getRecordingMeta(path, "recording") ); const exportWithSettings = createMutation(() => ({ @@ -248,7 +246,7 @@ const ExportDialog = () => { try { const videoPath = await commands.exportVideo( - videoId, + path, progress, true, selectedFps(), @@ -307,7 +305,7 @@ const ExportDialog = () => { throw new Error("Recording metadata not available"); } - const metadata = await commands.getVideoMetadata(videoId, null); + const metadata = await commands.getVideoMetadata(path); const plan = await commands.checkUpgradedAndUpdate(); const canShare = { allowed: plan || metadata.duration < 300, @@ -366,7 +364,7 @@ const ExportDialog = () => { ); }; - await commands.exportVideo(videoId, progress, true, selectedFps(), { + await commands.exportVideo(path, progress, true, selectedFps(), { x: selectedResolution().width, y: selectedResolution().height, }); @@ -375,8 +373,8 @@ const ExportDialog = () => { // Now proceed with upload const result = recordingMeta()?.sharing - ? await commands.uploadExportedVideo(videoId, "Reupload") - : await commands.uploadExportedVideo(videoId, { + ? await commands.uploadExportedVideo(path, "Reupload") + : await commands.uploadExportedVideo(path, { Initial: { pre_created_video: null }, }); @@ -403,7 +401,7 @@ const ExportDialog = () => { onSuccess: () => { metaActions.refetch(); setUploadState({ type: "complete" }); - metaUpdateStore.notifyUpdate(videoId); + metaUpdateStore.notifyUpdate(path); }, onError: (error) => { commands.globalMessageDialog( diff --git a/apps/desktop/src/routes/editor/ShareButton.tsx b/apps/desktop/src/routes/editor/ShareButton.tsx index 07659158177..cd999061dda 100644 --- a/apps/desktop/src/routes/editor/ShareButton.tsx +++ b/apps/desktop/src/routes/editor/ShareButton.tsx @@ -13,9 +13,11 @@ import { RESOLUTION_OPTIONS } from "./Header"; import { Dialog, DialogContent } from "./ui"; function ShareButton() { - const { videoId, metaUpdateStore } = useEditorContext(); + const { editorInstance, metaUpdateStore } = useEditorContext(); + const path = editorInstance.path; + const [recordingMeta, metaActions] = createResource(() => - commands.getRecordingMeta(videoId, "recording") + commands.getRecordingMeta(path, "recording") ); const [copyPressed, setCopyPressed] = createSignal(false); const selectedFps = Number(localStorage.getItem("cap-export-fps")) || 30; @@ -43,7 +45,7 @@ function ShareButton() { throw new Error("Recording metadata not available"); } - const metadata = await commands.getVideoMetadata(videoId, null); + const metadata = await commands.getVideoMetadata(path); const plan = await commands.checkUpgradedAndUpdate(); const canShare = { allowed: plan || metadata.duration < 300, @@ -95,7 +97,7 @@ function ShareButton() { ); }; - await commands.exportVideo(videoId, progress, true, selectedFps, { + await commands.exportVideo(path, progress, true, selectedFps, { x: selectedResolution.width, y: selectedResolution.height, }); @@ -104,8 +106,8 @@ function ShareButton() { // Now proceed with upload const result = recordingMeta()?.sharing - ? await commands.uploadExportedVideo(videoId, "Reupload") - : await commands.uploadExportedVideo(videoId, { + ? await commands.uploadExportedVideo(path, "Reupload") + : await commands.uploadExportedVideo(path, { Initial: { pre_created_video: null }, }); @@ -165,9 +167,7 @@ function ShareButton() { // Watch for metadata updates createEffect(() => { const update = metaUpdateStore.getLastUpdate(); - if (update && update.videoId === videoId) { - metaActions.refetch(); - } + if (update) metaActions.refetch(); }); return ( diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts index 1548c485190..d58dcf91421 100644 --- a/apps/desktop/src/routes/editor/context.ts +++ b/apps/desktop/src/routes/editor/context.ts @@ -291,16 +291,16 @@ function transformMeta(instance: SerializedEditorInstance) { export type TransformedMeta = ReturnType; export const [EditorInstanceContextProvider, useEditorInstanceContext] = - createContextProvider((props: { videoId: string }) => { + createContextProvider((props: { path: string }) => { const [latestFrame, setLatestFrame] = createLazySignal<{ width: number; data: ImageData; }>(); const [editorInstance] = createResource(async () => { - const instance = await commands.createEditorInstance(props.videoId); + const instance = await commands.createEditorInstance(); - const [ws, isConnected] = createImageDataWS( + const [_ws, isConnected] = createImageDataWS( instance.framesSocketUrl, setLatestFrame ); @@ -323,7 +323,7 @@ export const [EditorInstanceContextProvider, useEditorInstanceContext] = return { editorInstance, - videoId: props.videoId, + path: props.path, latestFrame, presets: createPresets(), prettyName: () => editorInstance()?.meta.prettyName ?? "Cap Recording", diff --git a/apps/desktop/src/routes/recordings-overlay.tsx b/apps/desktop/src/routes/recordings-overlay.tsx index ce62cb5c9ab..bb3249f10a7 100644 --- a/apps/desktop/src/routes/recordings-overlay.tsx +++ b/apps/desktop/src/routes/recordings-overlay.tsx @@ -122,7 +122,7 @@ export default function () { if (!isRecording) return null; const result = await commands - .getVideoMetadata(media.path, null) + .getVideoMetadata(media.path) .catch((e) => { console.error(`Failed to get metadata: ${e}`); }); @@ -333,7 +333,7 @@ export default function () { }) ); commands.showWindow({ - Editor: { project_id: mediaId }, + Editor: { project_path: media.path }, }); }} > @@ -722,7 +722,7 @@ function createRecordingMutations( throw new Error("You need to sign in to share recordings"); } - const metadata = await commands.getVideoMetadata(media.path, null); + const metadata = await commands.getVideoMetadata(media.path); const plan = await commands.checkUpgradedAndUpdate(); const canShare = { allowed: plan || metadata.duration < 300, diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts index 6ede462a171..6b19cda2115 100644 --- a/apps/desktop/src/utils/tauri.ts +++ b/apps/desktop/src/utils/tauri.ts @@ -53,11 +53,11 @@ async focusCapturesPanel() : Promise { async getCurrentRecording() : Promise> { return await TAURI_INVOKE("get_current_recording"); }, -async exportVideo(videoId: string, progress: TAURI_CHANNEL, force: boolean, fps: number, resolutionBase: XY) : Promise { - return await TAURI_INVOKE("export_video", { videoId, progress, force, fps, resolutionBase }); +async exportVideo(path: string, progress: TAURI_CHANNEL, force: boolean, fps: number, resolutionBase: XY) : Promise { + return await TAURI_INVOKE("export_video", { path, progress, force, fps, resolutionBase }); }, -async getExportEstimates(videoId: string, resolution: XY, fps: number) : Promise { - return await TAURI_INVOKE("get_export_estimates", { videoId, resolution, fps }); +async getExportEstimates(path: string, resolution: XY, fps: number) : Promise { + return await TAURI_INVOKE("get_export_estimates", { path, resolution, fps }); }, async copyFileToPath(src: string, dst: string) : Promise { return await TAURI_INVOKE("copy_file_to_path", { src, dst }); @@ -71,11 +71,11 @@ async copyScreenshotToClipboard(path: string) : Promise { async openFilePath(path: string) : Promise { return await TAURI_INVOKE("open_file_path", { path }); }, -async getVideoMetadata(videoId: string, videoType: VideoType | null) : Promise { - return await TAURI_INVOKE("get_video_metadata", { videoId, videoType }); +async getVideoMetadata(path: string) : Promise { + return await TAURI_INVOKE("get_video_metadata", { path }); }, -async createEditorInstance(videoId: string) : Promise { - return await TAURI_INVOKE("create_editor_instance", { videoId }); +async createEditorInstance() : Promise { + return await TAURI_INVOKE("create_editor_instance"); }, async startPlayback(fps: number, resolutionBase: XY) : Promise { return await TAURI_INVOKE("start_playback", { fps, resolutionBase }); @@ -89,9 +89,6 @@ async setPlayheadPosition(frameNumber: number) : Promise { async setProjectConfig(config: ProjectConfiguration) : Promise { return await TAURI_INVOKE("set_project_config", { config }); }, -async openEditor(id: string) : Promise { - return await TAURI_INVOKE("open_editor", { id }); -}, async openPermissionSettings(permission: OSPermission) : Promise { await TAURI_INVOKE("open_permission_settings", { permission }); }, @@ -101,22 +98,22 @@ async doPermissionsCheck(initialCheck: boolean) : Promise { async requestPermission(permission: OSPermission) : Promise { await TAURI_INVOKE("request_permission", { permission }); }, -async uploadExportedVideo(videoId: string, mode: UploadMode) : Promise { - return await TAURI_INVOKE("upload_exported_video", { videoId, mode }); +async uploadExportedVideo(path: string, mode: UploadMode) : Promise { + return await TAURI_INVOKE("upload_exported_video", { path, mode }); }, async uploadScreenshot(screenshotPath: string) : Promise { return await TAURI_INVOKE("upload_screenshot", { screenshotPath }); }, -async getRecordingMeta(id: string, fileType: string) : Promise { - return await TAURI_INVOKE("get_recording_meta", { id, fileType }); +async getRecordingMeta(path: string, fileType: string) : Promise { + return await TAURI_INVOKE("get_recording_meta", { path, fileType }); }, async saveFileDialog(fileName: string, fileType: string) : Promise { return await TAURI_INVOKE("save_file_dialog", { fileName, fileType }); }, -async listRecordings() : Promise<([string, string, RecordingMetaWithType])[]> { +async listRecordings() : Promise<([string, RecordingMetaWithType])[]> { return await TAURI_INVOKE("list_recordings"); }, -async listScreenshots() : Promise<([string, string, RecordingMeta])[]> { +async listScreenshots() : Promise<([string, RecordingMeta])[]> { return await TAURI_INVOKE("list_screenshots"); }, async checkUpgradedAndUpdate() : Promise { @@ -170,9 +167,6 @@ async setFail(name: string, value: boolean) : Promise { async updateAuthPlan() : Promise { await TAURI_INVOKE("update_auth_plan"); }, -async reuploadInstantVideo(videoId: string) : Promise { - return await TAURI_INVOKE("reupload_instant_video", { videoId }); -}, async setWindowTransparent(value: boolean) : Promise { await TAURI_INVOKE("set_window_transparent", { value }); } @@ -189,7 +183,6 @@ editorStateChanged: EditorStateChanged, newNotification: NewNotification, newScreenshotAdded: NewScreenshotAdded, newStudioRecordingAdded: NewStudioRecordingAdded, -recordingMetaChanged: RecordingMetaChanged, recordingOptionsChanged: RecordingOptionsChanged, recordingStarted: RecordingStarted, recordingStopped: RecordingStopped, @@ -208,7 +201,6 @@ editorStateChanged: "editor-state-changed", newNotification: "new-notification", newScreenshotAdded: "new-screenshot-added", newStudioRecordingAdded: "new-studio-recording-added", -recordingMetaChanged: "recording-meta-changed", recordingOptionsChanged: "recording-options-changed", recordingStarted: "recording-started", recordingStopped: "recording-stopped", @@ -291,7 +283,6 @@ export type PresetsStore = { presets: Preset[]; default: number | null } export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null } export type ProjectRecordings = { segments: SegmentRecordings[] } export type RecordingMeta = (StudioRecordingMeta | InstantRecordingMeta) & { platform: Platform | null; pretty_name: string; sharing?: SharingMeta | null } -export type RecordingMetaChanged = { id: string } export type RecordingMetaWithType = ((StudioRecordingMeta | InstantRecordingMeta) & { platform: Platform | null; pretty_name: string; sharing?: SharingMeta | null }) & { type: RecordingType } export type RecordingMode = "studio" | "instant" export type RecordingOptions = { captureTarget: ScreenCaptureTarget; micName: string | null; cameraLabel: string | null; captureSystemAudio?: boolean; mode: RecordingMode } @@ -312,7 +303,7 @@ export type SegmentRecordings = { display: Video; camera: Video | null; mic: Aud export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordings; path: string; meta: RecordingMeta } export type ShadowConfiguration = { size: number; opacity: number; blur: number } export type SharingMeta = { id: string; link: string } -export type ShowCapWindow = "Setup" | "Main" | { Settings: { page: string | null } } | { Editor: { project_id: string } } | "RecordingsOverlay" | "WindowCaptureOccluder" | { CaptureArea: { screen_id: number } } | { Camera: { ws_port: number } } | { InProgressRecording: { position: [number, number] | null } } | "Upgrade" | "SignIn" | "ModeSelect" +export type ShowCapWindow = "Setup" | "Main" | { Settings: { page: string | null } } | { Editor: { project_path: string } } | "RecordingsOverlay" | "WindowCaptureOccluder" | { CaptureArea: { screen_id: number } } | { Camera: { ws_port: number } } | { InProgressRecording: { position: [number, number] | null } } | "Upgrade" | "SignIn" | "ModeSelect" export type SingleSegment = { display: VideoMeta; camera?: VideoMeta | null; audio?: AudioMeta | null; cursor?: string | null } export type StudioRecordingMeta = { segment: SingleSegment } | { inner: MultipleSegments } export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[] } @@ -327,7 +318,6 @@ export type VideoMeta = { path: string; fps?: number; */ start_time?: number | null } export type VideoRecordingMetadata = { duration: number; size: number } -export type VideoType = "screen" | "output" | "camera" export type VideoUploadInfo = { id: string; link: string; config: S3UploadMeta } export type XY = { x: T; y: T } export type ZoomMode = "auto" | { manual: { x: number; y: number } } diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs index 314f95d4fc9..e7998ba89c0 100644 --- a/crates/editor/src/editor_instance.rs +++ b/crates/editor/src/editor_instance.rs @@ -18,7 +18,7 @@ use tokio::sync::{mpsc, watch, Mutex}; pub struct EditorInstance { pub project_path: PathBuf, - pub id: String, + // pub id: String, pub ws_port: u16, pub recordings: Arc, pub renderer: Arc, @@ -49,24 +49,13 @@ impl EditorInstance { } pub async fn new( - projects_path: PathBuf, - video_id: &str, + project_path: PathBuf, on_state_change: impl Fn(&EditorState) + Send + Sync + 'static, ) -> Result, String> { sentry::configure_scope(|scope| { scope.set_tag("crate", "editor"); }); - let project_path = projects_path.join(format!( - "{}{}", - video_id, - if video_id.ends_with(".cap") { - "" - } else { - ".cap" - } - )); - if !project_path.exists() { println!("Video path {} not found!", project_path.display()); panic!("Video path {} not found!", project_path.display()); @@ -112,7 +101,7 @@ impl EditorInstance { let (preview_tx, preview_rx) = watch::channel(None); let this = Arc::new(Self { - id: video_id.to_string(), + // id: video_id.to_string(), project_path, recordings, ws_port, @@ -137,8 +126,8 @@ impl EditorInstance { Ok(this) } - pub fn meta(&self) -> RecordingMeta { - self.meta.clone() + pub fn meta(&self) -> &RecordingMeta { + &self.meta } pub async fn dispose(&self) { @@ -307,7 +296,10 @@ impl Drop for EditorInstance { fn drop(&mut self) { // TODO: Ensure that *all* resources have been released by this point? // For now the `dispose` method is adequate. - println!("*** Editor instance {} has been released. ***", self.id); + println!( + "*** Editor instance has been released: {:?} ***", + self.project_path + ); } } From 9c3e4bb819fba430f55e2bc56342bbb685d797ba Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Sun, 13 Apr 2025 14:35:05 +0800 Subject: [PATCH 7/9] cleanup --- Cargo.lock | 19 ------------------- apps/desktop/src-tauri/Cargo.toml | 1 - 2 files changed, 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 20be214a873..37ed6c519e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -573,15 +573,6 @@ dependencies = [ "rustc-demangle", ] -[[package]] -name = "base64" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b25d992356d2eb0ed82172f5248873db5560c4721f564b13cb5193bda5e668e" -dependencies = [ - "byteorder", -] - [[package]] name = "base64" version = "0.21.7" @@ -964,7 +955,6 @@ dependencies = [ "nix 0.29.0", "objc", "objc2-app-kit 0.3.0", - "paths-as-strings", "png", "rand 0.8.5", "relative-path", @@ -5329,15 +5319,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" -[[package]] -name = "paths-as-strings" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7963201bed34799ddd0f54a2e1e4c5082313ca260db118822109f344f13b285c" -dependencies = [ - "base64 0.10.1", -] - [[package]] name = "peeking_take_while" version = "0.1.2" diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index dbf926af45f..dc96d3951f1 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -90,7 +90,6 @@ relative-path = "1.9.3" cap-fail = { version = "0.1.0", path = "../../../crates/fail" } tokio-stream = { version = "0.1.17", features = ["sync"] } md5 = "0.7.0" -paths-as-strings = "0.1.1" [target.'cfg(target_os = "macos")'.dependencies] core-graphics = "0.24.0" From 7969082f76d717b4c6e59c095b2cc36fc89508a1 Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Sun, 13 Apr 2025 16:28:21 +0800 Subject: [PATCH 8/9] cleanup --- crates/editor/src/editor_instance.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs index e7998ba89c0..b92b2e0e1c1 100644 --- a/crates/editor/src/editor_instance.rs +++ b/crates/editor/src/editor_instance.rs @@ -18,7 +18,6 @@ use tokio::sync::{mpsc, watch, Mutex}; pub struct EditorInstance { pub project_path: PathBuf, - // pub id: String, pub ws_port: u16, pub recordings: Arc, pub renderer: Arc, @@ -101,7 +100,6 @@ impl EditorInstance { let (preview_tx, preview_rx) = watch::channel(None); let this = Arc::new(Self { - // id: video_id.to_string(), project_path, recordings, ws_port, From 778e5e5f863a62ff74b1050c1fa879a750380eac Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Sun, 13 Apr 2025 16:39:27 +0800 Subject: [PATCH 9/9] clippy --- apps/desktop/src-tauri/src/windows.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs index 9f417436bf2..d50c58d849e 100644 --- a/apps/desktop/src-tauri/src/windows.rs +++ b/apps/desktop/src-tauri/src/windows.rs @@ -516,12 +516,11 @@ impl ShowCapWindow { ) -> WebviewWindowBuilder<'a, Wry, AppHandle> { let id = self.id(app); - let mut builder = - WebviewWindow::builder(app, dbg!(id.label()), WebviewUrl::App(url.into())) - .title(id.title()) - .visible(false) - .accept_first_mouse(true) - .shadow(true); + let mut builder = WebviewWindow::builder(app, id.label(), WebviewUrl::App(url.into())) + .title(id.title()) + .visible(false) + .accept_first_mouse(true) + .shadow(true); if let Some(min) = id.min_size() { builder = builder