Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
unify window opening and video upload commands
Brendan Allan49e7620926ea
diff --git a/apps/desktop/src-tauri/src/auth.rs b/apps/desktop/src-tauri/src/auth.rsindex c2cb90bc9..8fa536818 100644--- a/apps/desktop/src-tauri/src/auth.rs+++ b/apps/desktop/src-tauri/src/auth.rs@@ -1,4 +1,3 @@-use std::sync::Arc;use serde::{Deserialize, Serialize};use serde_json::json;diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rsnew file mode 100644index 000000000..cf9d481ff--- /dev/null+++ b/apps/desktop/src-tauri/src/export.rs@@ -0,0 +1,65 @@+use crate::{+ get_video_metadata, upsert_editor_instance, windows::ShowCapWindow, RenderProgress, VideoType,+};+use cap_project::ProjectConfiguration;+use std::path::PathBuf;+use tauri::AppHandle;++#[tauri::command]+#[specta::specta]+pub async fn export_video(+ app: AppHandle,+ video_id: String,+ project: ProjectConfiguration,+ progress: tauri::ipc::Channel<RenderProgress>,+ force: bool,+) -> Result<PathBuf, String> {+ sentry::configure_scope(|scope| {+ scope.set_tag("cmd", "export_video");+ });++ let (duration, _size) =+ get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Screen))+ .await+ .unwrap();++ // 30 FPS (calculated for output video)+ let total_frames = (duration * 30.0).round() as u32;++ let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;++ let output_path = editor_instance.meta().output_path();++ // If the file exists, return it immediately+ if output_path.exists() && !force {+ return Ok(output_path);+ }++ progress+ .send(RenderProgress::EstimatedTotalFrames { total_frames })+ .ok();++ cap_export::export_video_to_file(+ project,+ output_path.clone(),+ move |current_frame| {+ progress+ .send(RenderProgress::FrameRendered { current_frame })+ .ok();+ },+ &editor_instance.project_path,+ editor_instance.audio.clone(),+ editor_instance.meta(),+ editor_instance.render_constants.clone(),+ editor_instance.cursor.clone(),+ )+ .await+ .map_err(|e| {+ sentry::capture_message(&e.to_string(), sentry::Level::Error);+ e.to_string()+ })?;++ ShowCapWindow::PrevRecordings.show(&app).ok();++ Ok(output_path)+}diff --git a/apps/desktop/src-tauri/src/fake_window.rs b/apps/desktop/src-tauri/src/fake_window.rsindex 6428ae42e..be7fa0e92 100644--- a/apps/desktop/src-tauri/src/fake_window.rs+++ b/apps/desktop/src-tauri/src/fake_window.rs@@ -1,6 +1,7 @@use cap_media::platform::Bounds;-use std::{collections::HashMap, sync::Arc};-use tokio::sync::RwLock;+use std::{collections::HashMap, sync::Arc, time::Duration};+use tauri::{AppHandle, Manager, WebviewWindow};+use tokio::{sync::RwLock, time::sleep};pub struct FakeWindowBounds(pub Arc<RwLock<HashMap<String, HashMap<String, Bounds>>>>);@@ -40,3 +41,53 @@ pub async fn remove_fake_window(Ok(())}++pub fn spawn_fake_window_listener(app: AppHandle, window: WebviewWindow) {+ tokio::spawn(async move {+ let state = app.state::<FakeWindowBounds>();++ loop {+ sleep(Duration::from_millis(1000 / 10)).await;++ let map = state.0.read().await;+ let Some(windows) = map.get(window.label()) else {+ window.set_ignore_cursor_events(true).ok();+ continue;+ };++ let window_position = window.outer_position().unwrap();+ let mouse_position = window.cursor_position().unwrap();+ let scale_factor = window.scale_factor().unwrap();++ let mut ignore = true;++ for bounds in windows.values() {+ let x_min = (window_position.x as f64) + bounds.x * scale_factor;+ let x_max = (window_position.x as f64) + (bounds.x + bounds.width) * scale_factor;+ let y_min = (window_position.y as f64) + bounds.y * scale_factor;+ let y_max = (window_position.y as f64) + (bounds.y + bounds.height) * scale_factor;++ if mouse_position.x >= x_min+ && mouse_position.x <= x_max+ && mouse_position.y >= y_min+ && mouse_position.y <= y_max+ {+ ignore = false;+ // ShowCapturesPanel.emit(&app).ok();+ break;+ }+ }++ window.set_ignore_cursor_events(ignore).ok();++ let focused = window.is_focused().unwrap_or(false);+ if !ignore {+ if !focused {+ window.set_focus().ok();+ }+ } else if focused {+ window.set_ignore_cursor_events(ignore).ok();+ }+ }+ });+}diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex b5c1a990b..99219cbe4 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -10,6 +10,7 @@ mod platform;mod recording;// mod resource;mod audio_meter;+mod export;mod fake_window;mod tray;mod upload;@@ -21,7 +22,7 @@ use auth::{AuthStore, AuthenticationInvalid};use cap_editor::{EditorInstance, FRAMES_WS_PATH};use cap_editor::{EditorState, ProjectRecordings};use cap_media::feeds::{AudioInputFeed, AudioInputSamplesSender};-use cap_media::sources::{CaptureScreen, CaptureWindow};+use cap_media::sources::CaptureScreen;use cap_media::{feeds::{CameraFeed, CameraFrameSender},sources::ScreenCaptureTarget,@@ -40,21 +41,19 @@ use serde::{Deserialize, Serialize};use serde_json::json;use specta::Type;use std::fs::File;+use std::future::Future;use std::io::BufWriter;use std::str::FromStr;use std::{collections::HashMap, io::BufReader, marker::PhantomData, path::PathBuf, process::Command,- sync::Arc, time::Duration,+ sync::Arc,};use tauri::{AppHandle, Emitter, Manager, Runtime, State, WindowEvent};use tauri_plugin_dialog::DialogExt;use tauri_plugin_notification::{NotificationExt, PermissionState};use tauri_plugin_shell::ShellExt;use tauri_specta::Event;-use tokio::{- sync::{Mutex, RwLock},- time::sleep,-};+use tokio::sync::{Mutex, RwLock};use upload::{get_s3_config, upload_image, upload_video, S3UploadMeta};use windows::{CapWindowId, ShowCapWindow};@@ -95,7 +94,7 @@ enum UploadResult {}#[derive(Clone, Serialize, Deserialize, specta::Type)]-struct PreCreatedVideo {+pub struct PreCreatedVideo {id: String,link: String,config: S3UploadMeta,@@ -227,10 +226,6 @@ impl App {#[derive(specta::Type, Serialize, tauri_specta::Event, Clone)]pub struct RecordingOptionsChanged;-// dedicated event + command used as panel must be accessed on main thread-#[derive(specta::Type, Serialize, tauri_specta::Event, Clone)]-pub struct ShowCapturesPanel;-#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]pub struct NewRecordingAdded {path: PathBuf,@@ -503,18 +498,9 @@ async fn create_thumbnail(input: PathBuf, output: PathBuf, size: (u32, u32)) ->.map_err(|e| format!("Task join error: {}", e))?}-#[tauri::command]-#[specta::specta]-async fn get_rendered_video(- app: AppHandle,- video_id: String,- project: ProjectConfiguration,-) -> Result<PathBuf, String> {+async fn get_rendered_video_path(app: AppHandle, video_id: String) -> Result<PathBuf, String> {let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;- let output_path = editor_instance- .project_path- .join("output")- .join("result.mp4");+ let output_path = editor_instance.meta().output_path();// If the file doesn't exist, return an error to trigger the progress-enabled pathif !output_path.exists() {@@ -524,83 +510,6 @@ async fn get_rendered_video(Ok(output_path)}-#[tauri::command]-#[specta::specta]-async fn get_rendered_video_with_progress(- app: AppHandle,- video_id: String,- project: ProjectConfiguration,- progress_channel: tauri::ipc::Channel<RenderProgress>,-) -> Result<PathBuf, String> {- get_rendered_video_impl(app, video_id, project, Some(progress_channel)).await-}--async fn get_rendered_video_impl(- app: AppHandle,- video_id: String,- project: ProjectConfiguration,- progress_channel: Option<tauri::ipc::Channel<RenderProgress>>,-) -> Result<PathBuf, String> {- let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;- let output_path = editor_instance- .project_path- .join("output")- .join("result.mp4");-- // If the file exists, return it immediately- if output_path.exists() {- return Ok(output_path);- }-- // If we need to render and have a progress channel, use it- if let Some(progress) = progress_channel {- let (duration, _size) =- get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Screen))- .await- .unwrap();-- // 30 FPS (calculated for output video)- let total_frames = (duration * 30.0).round() as u32;-- progress- .send(RenderProgress::EstimatedTotalFrames { total_frames })- .ok();-- cap_export::export_video_to_file(- project,- output_path.clone(),- move |current_frame| {- progress- .send(RenderProgress::FrameRendered { current_frame })- .ok();- },- &editor_instance.project_path,- editor_instance.audio.clone(),- editor_instance.meta(),- editor_instance.render_constants.clone(),- editor_instance.cursor.clone(),- )- .await- .map_err(|e| e.to_string())?;- } else {- // Render without progress updates- cap_export::export_video_to_file(- project,- output_path.clone(),- |_| {},- &editor_instance.project_path,- editor_instance.audio.clone(),- editor_instance.meta(),- editor_instance.render_constants.clone(),- editor_instance.cursor.clone(),- )- .await- .map_err(|e| e.to_string())?;- }-- Ok(output_path)-}-#[tauri::command]#[specta::specta]async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(), String> {@@ -995,75 +904,6 @@ async fn get_video_metadata(Ok((duration, size))}-// #[tauri::command(async)]-// #[specta::specta]-// fn show_notifications_window(app: AppHandle) {-// if app.get_webview_window("notifications").is_some() {-// println!("notifications window already exists");-// return;-// }--// CapWindow::Notifications.show(&app).unwrap();-// }--#[tauri::command(async)]-#[specta::specta]-fn show_previous_recordings_window(app: AppHandle) {- if app.get_webview_window("prev-recordings").is_some() {- println!("prev-recordings window already exists");- return;- }-- let window = ShowCapWindow::PrevRecordings.show(&app).unwrap();-- tokio::spawn(async move {- let state = app.state::<FakeWindowBounds>();-- loop {- sleep(Duration::from_millis(1000 / 10)).await;-- let map = state.0.read().await;- let Some(windows) = map.get("prev-recordings") else {- window.set_ignore_cursor_events(true).ok();- continue;- };-- let window_position = window.outer_position().unwrap();- let mouse_position = window.cursor_position().unwrap();- let scale_factor = window.scale_factor().unwrap();-- let mut ignore = true;-- for bounds in windows.values() {- let x_min = (window_position.x as f64) + bounds.x * scale_factor;- let x_max = (window_position.x as f64) + (bounds.x + bounds.width) * scale_factor;- let y_min = (window_position.y as f64) + bounds.y * scale_factor;- let y_max = (window_position.y as f64) + (bounds.y + bounds.height) * scale_factor;-- if mouse_position.x >= x_min- && mouse_position.x <= x_max- && mouse_position.y >= y_min- && mouse_position.y <= y_max- {- ignore = false;- // ShowCapturesPanel.emit(&app).ok();- break;- }- }-- window.set_ignore_cursor_events(ignore).ok();-- if !ignore {- if !window.is_focused().unwrap_or(false) {- window.set_focus().ok();- }- } else if window.is_focused().unwrap_or(false) {- window.set_ignore_cursor_events(true).ok();- }- }- });-}-#[tauri::command(async)]#[specta::specta]fn open_editor(app: AppHandle, id: String) {@@ -1109,63 +949,6 @@ enum RenderProgress {FrameRendered { current_frame: u32 },}-#[tauri::command]-#[specta::specta]-async fn render_to_file(- app: AppHandle,- video_id: String,- project: ProjectConfiguration,- progress_channel: tauri::ipc::Channel<RenderProgress>,-) -> Result<PathBuf, String> {- sentry::configure_scope(|scope| {- scope.set_tag("cmd", "render_to_file");- });-- let (duration, _size) =- get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Screen))- .await- .unwrap();-- // 30 FPS (calculated for output video)- let total_frames = (duration * 30.0).round() as u32;-- let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;-- let output_path = editor_instance- .project_path- .join("output")- .join("result.mp4");-- cap_export::export_video_to_file(- project,- output_path.clone(),- move |current_frame| {- if current_frame == 0 {- progress_channel- .send(RenderProgress::EstimatedTotalFrames { total_frames })- .ok();- }- progress_channel- .send(RenderProgress::FrameRendered { current_frame })- .ok();- },- &editor_instance.project_path,- editor_instance.audio.clone(),- editor_instance.meta(),- editor_instance.render_constants.clone(),- editor_instance.cursor.clone(),- )- .await- .map_err(|e| {- sentry::capture_message(&e.to_string(), sentry::Level::Error);- e.to_string()- })?;-- ShowCapturesPanel.emit(&app).ok();-- Ok(output_path)-}-#[tauri::command]#[specta::specta]async fn set_playhead_position(app: AppHandle, video_id: String, frame_number: u32) {@@ -1212,18 +995,6 @@ fn open_main_window(app: AppHandle) {ShowCapWindow::Main.show(&app).ok();}-#[tauri::command]-#[specta::specta]-async fn open_upgrade_window(app: AppHandle) {- ShowCapWindow::Upgrade.show(&app).ok();-}--#[tauri::command]-#[specta::specta]-async fn open_settings_window(app: AppHandle, page: String) {- ShowCapWindow::Settings { page: Some(page) }.show(&app);-}-#[derive(Serialize, Type, tauri_specta::Event, Debug, Clone)]pub struct UploadProgress {stage: String,@@ -1231,13 +1002,20 @@ pub struct UploadProgress {message: String,}+#[derive(Deserialize, Type)]+pub enum UploadMode {+ Initial {+ pre_created_video: Option<PreCreatedVideo>,+ },+ Reupload,+}+#[tauri::command]#[specta::specta]-async fn upload_rendered_video(+async fn upload_exported_video(app: AppHandle,video_id: String,- project: ProjectConfiguration,- pre_created_video: Option<PreCreatedVideo>,+ mode: UploadMode,) -> Result<UploadResult, String> {let Ok(Some(mut auth)) = AuthStore::get(&app) else {AuthStore::set(&app, None).map_err(|e| e.to_string())?;@@ -1265,7 +1043,7 @@ async fn upload_rendered_video(}if !auth.is_upgraded() {- open_upgrade_window(app).await;+ ShowCapWindow::Upgrade.show(&app).ok();return Ok(UploadResult::UpgradeRequired);}}@@ -1273,31 +1051,11 @@ async fn upload_rendered_video(let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;let mut meta = editor_instance.meta();- UploadProgress {- stage: "rendering".to_string(),- progress: 0.0,- message: "Preparing video...".to_string(),+ let output_path = meta.output_path();+ if !output_path.exists() {+ notifications::send_notification(&app, notifications::NotificationType::UploadFailed);+ return Err("Failed to upload video: Rendered video not found".to_string());}- .emit(&app)- .ok();-- let output_path = match get_rendered_video(app.clone(), video_id.clone(), project).await {- Ok(path) => {- // Emit rendering complete- UploadProgress {- stage: "rendering".to_string(),- progress: 1.0,- message: "Rendering complete".to_string(),- }- .emit(&app)- .ok();- path- }- Err(e) => {- notifications::send_notification(&app, notifications::NotificationType::UploadFailed);- return Err(format!("Failed to get rendered video: {}", e));- }- };// Start upload progressUploadProgress {@@ -1308,21 +1066,28 @@ async fn upload_rendered_video(.emit(&app).ok();- let s3_config = if let Some(pre_created) = pre_created_video {- pre_created.config- } else {- get_s3_config(&app, false, None).await?- };+ let s3_config = async {+ let video_id = match mode {+ UploadMode::Initial { pre_created_video } => {+ if let Some(pre_created) = pre_created_video {+ return Ok(pre_created.config);+ }+ None+ }+ UploadMode::Reupload => {+ let Some(sharing) = meta.sharing.clone() else {+ return Err("No sharing metadata found".to_string());+ };- match upload_video(- &app,- video_id.clone(),- output_path,- false,- Some(s3_config.clone()),- )- .await- {+ Some(sharing.id)+ }+ };++ get_s3_config(&app, false, video_id).await+ }+ .await?;++ match upload_video(&app, video_id.clone(), output_path, false, Some(s3_config)).await {Ok(uploaded_video) => {// Emit upload completeUploadProgress {@@ -1337,7 +1102,7 @@ async fn upload_rendered_video(link: uploaded_video.link.clone(),id: uploaded_video.id.clone(),});- meta.save_for_project();+ meta.save_for_project().ok();RecordingMetaChanged { id: video_id }.emit(&app).ok();NotificationType::ShareableLinkCopied.send(&app);@@ -1386,7 +1151,7 @@ async fn upload_screenshot(}if !auth.is_upgraded() {- open_upgrade_window(app).await;+ ShowCapWindow::Upgrade.show(&app).ok();return Ok(UploadResult::UpgradeRequired);}}@@ -1570,8 +1335,6 @@ async fn save_file_dialog() -> Result<Option<String>, String> {use tauri_plugin_dialog::DialogExt;- open_main_window(app.clone());-println!("save_file_dialog called with file_name: {}, file_type: {}",file_name, file_type@@ -1782,8 +1545,6 @@ async fn delete_auth_open_signin(app: AppHandle) -> Result<(), String> {tokio::time::sleep(std::time::Duration::from_millis(100)).await;}- open_main_window(app.clone());-Ok(())}@@ -1845,33 +1606,43 @@ async fn seek_to(app: AppHandle, video_id: String, frame_number: u32) {.await;}-async fn check_notification_permissions(app: &AppHandle) {+#[tauri::command]+#[specta::specta]+fn show_window(app: AppHandle, window: ShowCapWindow) {+ window.show(&app).ok();+}++async fn check_notification_permissions(app: AppHandle) {// Check if we've already requested permissions- if let Ok(Some(settings)) = GeneralSettingsStore::get(app) {- if settings.enable_notifications {- match app.notification().permission_state() {- Ok(state) if state != PermissionState::Granted => {- println!("Requesting notification permission");- match app.notification().request_permission() {- Ok(PermissionState::Granted) => {- println!("Notification permission granted");- }- Ok(_) | Err(_) => {- GeneralSettingsStore::update(app, |s| {- s.enable_notifications = false;- })- .ok();- }- }- }- Ok(_) => {- println!("Notification permission already granted");+ let Ok(Some(settings)) = GeneralSettingsStore::get(&app) else {+ return;+ };++ if !settings.enable_notifications {+ return;+ }++ match app.notification().permission_state() {+ Ok(state) if state != PermissionState::Granted => {+ println!("Requesting notification permission");+ match app.notification().request_permission() {+ Ok(PermissionState::Granted) => {+ println!("Notification permission granted");}- Err(e) => {- eprintln!("Error checking notification permission state: {}", e);+ Ok(_) | Err(_) => {+ GeneralSettingsStore::update(&app, |s| {+ s.enable_notifications = false;+ })+ .ok();}}}+ Ok(_) => {+ println!("Notification permission already granted");+ }+ Err(e) => {+ eprintln!("Error checking notification permission state: {}", e);+ }}}@@ -1890,16 +1661,12 @@ pub async fn run() {recording::list_capture_screens,take_screenshot,list_audio_devices,- show_previous_recordings_window,close_previous_recordings_window,fake_window::set_fake_window_bounds,fake_window::remove_fake_window,focus_captures_panel,get_current_recording,- render_to_file,- get_rendered_video,- get_rendered_video_with_progress,- render_video_with_progress,+ export::export_video,copy_file_to_path,copy_video_to_clipboard,copy_screenshot_to_clipboard,@@ -1915,11 +1682,9 @@ pub async fn run() {permissions::open_permission_settings,permissions::do_permissions_check,permissions::request_permission,- upload_rendered_video,+ upload_exported_video,upload_screenshot,get_recording_meta,- open_upgrade_window,- open_settings_window,save_file_dialog,list_recordings,list_screenshots,@@ -1933,12 +1698,11 @@ pub async fn run() {seek_to,send_feedback_request,windows::position_traffic_lights,- reupload_rendered_video,- global_message_dialog+ global_message_dialog,+ show_window]).events(tauri_specta::collect_events![RecordingOptionsChanged,- ShowCapturesPanel,NewRecordingAdded,NewScreenshotAdded,RenderFrameEvent,@@ -2003,10 +1767,10 @@ pub async fn run() {.plugin(tauri_plugin_window_state::Builder::new().with_denylist(&[- "setup",- "window-capture-occluder",- "camera",- "prev-recordings",+ CapWindowId::Setup.label().as_str(),+ CapWindowId::WindowCaptureOccluder.label().as_str(),+ CapWindowId::Camera.label().as_str(),+ CapWindowId::PrevRecordings.label().as_str(),]).map_label(|label| match label {label if label.starts_with("editor-") => "editor",@@ -2017,13 +1781,12 @@ pub async fn run() {.plugin(flags::plugin::init()).invoke_handler(specta_builder.invoke_handler()).setup(move |app| {- specta_builder.mount_events(app);- hotkeys::init(app.handle());- general_settings::init(app.handle());-- let app_handle = app.handle().clone();+ let app = app.handle().clone();+ specta_builder.mount_events(&app);+ hotkeys::init(&app);+ general_settings::init(&app);- if let Ok(Some(auth)) = AuthStore::load(&app_handle) {+ if let Ok(Some(auth)) = AuthStore::load(&app) {sentry::configure_scope(|scope| {scope.set_user(Some(sentry::User {id: Some(auth.user_id),@@ -2033,10 +1796,7 @@ pub async fn run() {}// Add this line to check notification permissions on startup- let notification_handle = app_handle.clone();- tauri::async_runtime::spawn(async move {- check_notification_permissions(¬ification_handle).await;- });+ tokio::spawn(check_notification_permissions(app.clone()));println!("Checking startup completion and permissions...");let permissions = permissions::do_permissions_check(false);@@ -2044,23 +1804,25 @@ pub async fn run() {if !permissions.screen_recording.permitted()|| !permissions.accessibility.permitted()- || GeneralSettingsStore::get(app.handle())+ || GeneralSettingsStore::get(&app).ok().flatten().map(|s| !s.has_completed_startup).unwrap_or(false){- ShowCapWindow::Setup.show(&app_handle).ok();+ ShowCapWindow::Setup.show(&app).ok();} else {println!("Permissions granted, showing main window");- ShowCapWindow::Main.show(&app_handle).ok();+ ShowCapWindow::Main.show(&app).ok();}- audio_meter::spawn_event_emitter(app_handle.clone(), audio_input_rx);+ ShowCapWindow::PrevRecordings.show(&app).ok();++ audio_meter::spawn_event_emitter(app.clone(), audio_input_rx);app.manage(Arc::new(RwLock::new(App {- handle: app_handle.clone(),+ handle: app.clone(),camera_tx,camera_ws_port,camera_feed: None,@@ -2080,96 +1842,70 @@ pub async fn run() {app.manage(FakeWindowBounds(Arc::new(RwLock::new(HashMap::new()))));- tray::create_tray(&app_handle).unwrap();+ tray::create_tray(&app).unwrap();- let app_handle_clone = app_handle.clone();- RequestStartRecording::listen_any(app, move |_| {- let app_handle = app_handle_clone.clone();- tauri::async_runtime::spawn(async move {- let state = app_handle.state::<Arc<RwLock<App>>>();- let is_recording = {- let app_state = state.read().await;- app_state.current_recording.is_some()- };+ RequestStartRecording::listen_any_spawn(&app, |_, app| async move {+ let state = app.state::<Arc<RwLock<App>>>();+ let is_recording = {+ let app_state = state.read().await;+ app_state.current_recording.is_some()+ };- if is_recording {- if let Err(e) =- recording::stop_recording(app_handle.clone(), app_handle.state()).await- {- eprintln!("Failed to stop recording: {}", e);- }- } else if let Err(e) =- recording::start_recording(app_handle.clone(), app_handle.state()).await- {- eprintln!("Failed to start recording: {}", e);+ if is_recording {+ if let Err(e) = recording::stop_recording(app.clone(), app.state()).await {+ eprintln!("Failed to stop recording: {}", e);}- });+ } else if let Err(e) = recording::start_recording(app.clone(), app.state()).await {+ eprintln!("Failed to start recording: {}", e);+ }});- let app_handle_clone = app_handle.clone();- RequestStopRecording::listen_any(app, move |_| {- let app_handle = app_handle_clone.clone();- tauri::async_runtime::spawn(async move {- if let Err(e) =- recording::stop_recording(app_handle.clone(), app_handle.state()).await- {- eprintln!("Failed to stop recording: {}", e);- }- });+ 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);+ }});- let app_handle_clone = app_handle.clone();- RequestRestartRecording::listen_any(app, move |_| {- let app_handle = app_handle_clone.clone();- tauri::async_runtime::spawn(async move {- let state = app_handle.state::<Arc<RwLock<App>>>();+ RequestRestartRecording::listen_any_spawn(&app, |_, app| async move {+ let state = app.state::<Arc<RwLock<App>>>();- // Stop and discard the current recording- {- let mut app_state = state.write().await;- if let Some(recording) = app_state.clear_current_recording() {- CurrentRecordingChanged /*(JsonValue::new(&None))*/- .emit(&app_handle)- .ok();+ // Stop and discard the current recording+ {+ let mut app_state = state.write().await;+ if let Some(recording) = app_state.clear_current_recording() {+ CurrentRecordingChanged /*(JsonValue::new(&None))*/+ .emit(&app)+ .ok();- recording.stop().await.ok();+ recording.stop().await.ok();- // recording.stop_and_discard();- }+ // recording.stop_and_discard();}+ }- if let Err(e) = recording::start_recording(app_handle.clone(), state).await {- eprintln!("Failed to start new recording: {}", e);- } else {- println!("New recording started successfully");- }- });+ if let Err(e) = recording::start_recording(app.clone(), state).await {+ eprintln!("Failed to start new recording: {}", e);+ } else {+ println!("New recording started successfully");+ }});- let app_handle_clone = app_handle.clone();- RequestNewScreenshot::listen_any(app, move |_| {- let app_handle = app_handle_clone.clone();- tauri::async_runtime::spawn(async move {- if let Err(e) = take_screenshot(app_handle.clone(), app_handle.state()).await {- eprintln!("Failed to take screenshot: {}", 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);+ }});- let app_handle_clone = app_handle.clone();- RequestOpenSettings::listen_any(app, move |e| {- let app_handle = app_handle_clone.clone();- tauri::async_runtime::spawn(async move {- open_settings_window(app_handle, e.payload.page).await;- });+ RequestOpenSettings::listen_any_spawn(&app, |payload, app| async move {+ ShowCapWindow::Settings {+ page: Some(payload.page),+ }+ .show(&app)+ .ok();});- let app_handle_clone = app_handle.clone();- AuthenticationInvalid::listen_any(app, move |_| {- let app_handle = app_handle_clone.clone();- tauri::async_runtime::spawn(async move {- delete_auth_open_signin(app_handle).await.ok();- });+ AuthenticationInvalid::listen_any_spawn(&app, |_, app| async move {+ delete_auth_open_signin(app).await.ok();});Ok(())@@ -2358,164 +2094,30 @@ async fn send_feedback_request(app: AppHandle, feedback: String) -> Result<(), SOk(())}-#[tauri::command]-#[specta::specta]-async fn reupload_rendered_video(- app: AppHandle,- video_id: String,- project: ProjectConfiguration,-) -> Result<UploadResult, String> {- let Ok(Some(mut auth)) = AuthStore::get(&app) else {- AuthStore::set(&app, None).map_err(|e| e.to_string())?;- return Ok(UploadResult::NotAuthenticated);- };-- // Check if user has an upgraded plan- if !auth.is_upgraded() {- match AuthStore::fetch_and_update_plan(&app).await {- Ok(_) => match AuthStore::get(&app) {- Ok(Some(updated_auth)) => {- auth = updated_auth;- }- Ok(None) => {- return Ok(UploadResult::NotAuthenticated);- }- Err(e) => return Err(format!("Failed to refresh auth: {}", e)),- },- Err(e) => {- if e.contains("Authentication expired") {- return Ok(UploadResult::NotAuthenticated);- }- return Ok(UploadResult::PlanCheckFailed);- }- }-- if !auth.is_upgraded() {- open_upgrade_window(app).await;- return Ok(UploadResult::UpgradeRequired);- }- }-- let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;- let meta = editor_instance.meta();-- let Some(sharing) = meta.sharing.clone() else {- return Err("No sharing metadata found".to_string());- };-- UploadProgress {- stage: "rendering".to_string(),- progress: 0.0,- message: "Preparing video...".to_string(),- }- .emit(&app)- .ok();-- let output_path = match get_rendered_video(app.clone(), video_id.clone(), project).await {- Ok(path) => {- UploadProgress {- stage: "rendering".to_string(),- progress: 1.0,- message: "Rendering complete".to_string(),- }- .emit(&app)- .ok();- path- }- Err(e) => {- notifications::send_notification(&app, notifications::NotificationType::UploadFailed);- return Err(format!("Failed to get rendered video: {}", e));- }- };-- // Start upload progress- UploadProgress {- stage: "uploading".to_string(),- progress: 0.0,- message: "Starting upload...".to_string(),- }- .emit(&app)- .ok();-- // Get S3 config with the existing video ID- let s3_config = get_s3_config(&app, false, Some(sharing.id)).await?;-- match upload_video(&app, video_id.clone(), output_path, false, Some(s3_config)).await {- Ok(uploaded_video) => {- // Emit upload complete- UploadProgress {- stage: "uploading".to_string(),- progress: 1.0,- message: "Upload complete!".to_string(),- }- .emit(&app)- .ok();-- notifications::send_notification(- &app,- notifications::NotificationType::ShareableLinkCopied,- );-- #[cfg(target_os = "macos")]- platform::write_string_to_pasteboard(&uploaded_video.link);-- Ok(UploadResult::Success(sharing.link)) // Use existing sharing link- }- Err(e) => {- notifications::send_notification(&app, notifications::NotificationType::UploadFailed);- Err(e)- }- }-}-#[tauri::command]#[specta::specta]fn global_message_dialog(app: AppHandle, message: String) {app.dialog().message(message).show(|_| {});}-#[tauri::command]-#[specta::specta]-async fn render_video_with_progress(- app: AppHandle,- video_id: String,- project: ProjectConfiguration,- progress_channel: tauri::ipc::Channel<RenderProgress>,-) -> Result<PathBuf, String> {- let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;- let output_path = editor_instance- .project_path- .join("output")- .join("result.mp4");-- let (duration, _size) =- get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Screen))- .await- .unwrap();-- // 30 FPS (calculated for output video)- let total_frames = (duration * 30.0).round() as u32;-- progress_channel- .send(RenderProgress::EstimatedTotalFrames { total_frames })- .ok();-- cap_export::export_video_to_file(- project,- output_path.clone(),- move |current_frame| {- progress_channel- .send(RenderProgress::FrameRendered { current_frame })- .ok();- },- &editor_instance.project_path,- editor_instance.audio.clone(),- editor_instance.meta(),- editor_instance.render_constants.clone(),- editor_instance.cursor.clone(),- )- .await- .map_err(|e| e.to_string())?;-- Ok(output_path)+trait EventExt: tauri_specta::Event {+ fn listen_any_spawn<Fut>(+ app: &AppHandle,+ handler: impl Fn(Self, AppHandle) -> Fut + Send + 'static + Clone,+ ) -> tauri::EventId+ where+ Fut: Future + Send,+ Self: serde::de::DeserializeOwned + Send + 'static,+ {+ let app = app.clone();+ Self::listen_any(&app.clone(), move |e| {+ let app = app.clone();+ let handler = handler.clone();+ tokio::spawn(async move {+ (handler)(e.payload, app).await;+ });+ })+ }}++impl<T: tauri_specta::Event> EventExt for T {}diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 004ff2d26..bda7fe907 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -1,12 +1,15 @@-use crate::audio::AppSounds;-use crate::auth::AuthStore;-use crate::general_settings::GeneralSettingsStore;-use crate::upload::get_s3_config;-use crate::windows::{CapWindowId, ShowCapWindow};use crate::{- create_screenshot, notifications, open_editor, open_external_link, platform,- upload_rendered_video, web_api, App, CurrentRecordingChanged, MutableState, NewRecordingAdded,- PreCreatedVideo, RecordingStarted, RecordingStopped, ShowCapturesPanel,+ audio::AppSounds,+ auth::AuthStore,+ create_screenshot,+ export::export_video,+ general_settings::GeneralSettingsStore,+ notifications, open_editor, open_external_link, platform,+ upload::get_s3_config,+ upload_exported_video, web_api,+ windows::{CapWindowId, ShowCapWindow},+ App, CurrentRecordingChanged, MutableState, NewRecordingAdded, PreCreatedVideo,+ RecordingStarted, RecordingStopped, UploadMode,};use cap_editor::ProjectRecordings;use cap_media::feeds::CameraFeed;@@ -180,7 +183,7 @@ pub async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Reslet recording_dir = recording.recording_dir.clone();- ShowCapturesPanel.emit(&app).ok();+ ShowCapWindow::PrevRecordings.show(&app).ok();NewRecordingAdded {path: recording_dir.clone(),@@ -288,18 +291,29 @@ pub async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Resopen_external_link(app.clone(), pre_created_video.link.clone()).ok();// Start the upload process in the background with retry mechanism- let app_clone = app.clone();+ let app = app.clone();tauri::async_runtime::spawn(async move {let max_retries = 3;let mut retry_count = 0;+ export_video(+ app.clone(),+ recording.id.clone(),+ config,+ tauri::ipc::Channel::new(|_| Ok(())),+ true,+ )+ .await+ .ok();+while retry_count < max_retries {- match upload_rendered_video(- app_clone.clone(),+ match upload_exported_video(+ app.clone(),recording.id.clone(),- ProjectConfiguration::default(),- Some(pre_created_video.clone()),+ UploadMode::Initial {+ pre_created_video: Some(pre_created_video.clone()),+ },).await{@@ -320,7 +334,7 @@ pub async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Res} else {println!("Max retries reached. Upload failed.");notifications::send_notification(- &app_clone,+ &app,notifications::NotificationType::UploadFailed,);}diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rsindex 63f9c7713..8114e20c0 100644--- a/apps/desktop/src-tauri/src/tray.rs+++ b/apps/desktop/src-tauri/src/tray.rs@@ -100,7 +100,7 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {&MenuItem::with_id(app, TrayItem::Quit, "Quit Cap", true, None::<&str>)?,],)?;- let app_handle = app.clone();+ let app = app.clone();let is_recording = Arc::new(AtomicBool::new(false));let _ = TrayIconBuilder::with_id("tray").icon(Image::from_bytes(include_bytes!(@@ -109,14 +109,12 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {.menu(&menu).menu_on_left_click(true).on_menu_event({- let app_handle = app_handle.clone();+ let app_handle = app.clone();move |app: &AppHandle, event| match TrayItem::from(event.id) {TrayItem::OpenCap => {- ShowCapWindow::Main.show(&app_handle);+ ShowCapWindow::Main.show(&app_handle).ok();}TrayItem::StartNewRecording => {- ShowCapWindow::Main.show(&app_handle);-let _ = RequestStartRecording.emit(&app_handle);}TrayItem::TakeScreenshot => {@@ -135,7 +133,9 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {.emit(&app_handle);}TrayItem::OpenSettings => {- ShowCapWindow::Settings { page: None }.show(&app_handle);+ ShowCapWindow::Settings { page: None }+ .show(&app_handle)+ .ok();}TrayItem::Quit => {app.exit(0);@@ -144,7 +144,7 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {}).on_tray_icon_event({let is_recording = Arc::clone(&is_recording);- let app_handle = app_handle.clone();+ let app_handle = app.clone();move |tray, event| {if let tauri::tray::TrayIconEvent::Click { .. } = event {if is_recording.load(Ordering::Relaxed) {@@ -155,43 +155,35 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {}}})- .build(app);+ .build(&app);- RecordingStarted::listen_any(app, {- let app_handle = app.clone();- let is_recording = Arc::clone(&is_recording);+ RecordingStarted::listen_any(&app, {+ let app = app.clone();+ let is_recording = is_recording.clone();move |_| {- let app_handle = app_handle.clone();- let is_recording = Arc::clone(&is_recording);- tauri::async_runtime::spawn(async move {- is_recording.store(true, Ordering::Relaxed);- if let Some(tray) = app_handle.tray_by_id("tray") {- if let Ok(icon) =- Image::from_bytes(include_bytes!("../icons/tray-stop-icon.png"))- {- let _ = tray.set_icon(Some(icon));- }- }- });+ is_recording.store(true, Ordering::Relaxed);+ let Some(tray) = app.tray_by_id("tray") else {+ return;+ };++ if let Ok(icon) = Image::from_bytes(include_bytes!("../icons/tray-stop-icon.png")) {+ let _ = tray.set_icon(Some(icon));+ }}});- RecordingStopped::listen_any(app, {+ RecordingStopped::listen_any(&app, {let app_handle = app.clone();- let is_recording = Arc::clone(&is_recording);+ let is_recording = is_recording.clone();move |_| {- let app_handle = app_handle.clone();- let is_recording = Arc::clone(&is_recording);- tauri::async_runtime::spawn(async move {- is_recording.store(false, Ordering::Relaxed);- if let Some(tray) = app_handle.tray_by_id("tray") {- if let Ok(icon) =- Image::from_bytes(include_bytes!("../icons/tray-default-icon.png"))- {- let _ = tray.set_icon(Some(icon));- }- }- });+ is_recording.store(false, Ordering::Relaxed);+ let Some(tray) = app_handle.tray_by_id("tray") else {+ return;+ };++ if let Ok(icon) = Image::from_bytes(include_bytes!("../icons/tray-default-icon.png")) {+ let _ = tray.set_icon(Some(icon));+ }}});diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex 0187b9ab2..1ecadcd79 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -1,6 +1,9 @@#![allow(unused_mut)]-use std::{path::PathBuf, str::FromStr};+use crate::fake_window;+use serde::Deserialize;+use specta::Type;+use std::{path::PathBuf, str::FromStr};use tauri::{AppHandle, LogicalPosition, Manager, WebviewUrl, WebviewWindow, WebviewWindowBuilder, Wry,};@@ -97,7 +100,7 @@ impl CapWindowId {}}-#[derive(Clone)]+#[derive(Clone, Type, Deserialize)]pub enum ShowCapWindow {Setup,Main,@@ -306,6 +309,8 @@ impl ShowCapWindow {}).ok();}+ fake_window::spawn_fake_window_listener(app.clone(), window.clone());+window}};diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsxindex 13f15b249..3d71e8b8e 100644--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx@@ -66,15 +66,6 @@ export default function () {const { options, setOptions } = createOptionsQuery();const currentRecording = createCurrentRecordingQuery();- events.showCapturesPanel.listen(() => {- commands.showPreviousRecordingsWindow();- });-- onMount(async () => {- await commands.showPreviousRecordingsWindow();- // await commands.showNotificationsWindow();- });-const isRecording = () => !!currentRecording.data;const toggleRecording = createMutation(() => ({@@ -114,7 +105,7 @@ export default function () {variant="secondary"size="xs"onClick={() => {- commands.openSettingsWindow("feedback");+ commands.showWindow({ Settings: { page: "feedback" } });}}>Feedback@@ -133,7 +124,9 @@ export default function () {<Tooltip.Trigger><buttontype="button"- onClick={() => commands.openSettingsWindow("recordings")}+ onClick={() =>+ commands.showWindow({ Settings: { page: "recordings" } })+ }><IconLucideSquarePlay class="w-[1.25rem] h-[1.25rem] text-gray-400 hover:text-gray-500" /></button>@@ -150,7 +143,9 @@ export default function () {<Tooltip.Trigger><buttontype="button"- onClick={() => commands.openSettingsWindow("general")}+ onClick={() =>+ commands.showWindow({ Settings: { page: "general" } })+ }><IconCapSettings class="w-[1.25rem] h-[1.25rem] text-gray-400 hover:text-gray-500" /></button>@@ -712,7 +707,7 @@ function ChangelogButton() {);const handleChangelogClick = () => {- commands.openSettingsWindow("changelog");+ commands.showWindow({ Settings: { page: "changelog" } });const version = currentVersion();if (version) {setChangelogState({diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsxindex 6aeb78264..315b973f8 100644--- a/apps/desktop/src/routes/editor/Header.tsx+++ b/apps/desktop/src/routes/editor/Header.tsx@@ -58,15 +58,15 @@ export function Header() {<Titlebar /><Dialog.Rootopen={progressState.type !== "idle"}- onOpenChange={() => { }} // Empty handler prevents closing+ onOpenChange={() => {}} // Empty handler prevents closing><DialogContenttitle={progressState.type === "copying"? "Link Copied": progressState.type === "uploading"- ? "Creating Shareable Link"- : "Exporting Recording"+ ? "Creating Shareable Link"+ : "Exporting Recording"}confirm={<></>}class="bg-gray-600"@@ -91,15 +91,16 @@ export function Header() {<divclass="bg-blue-300 h-2.5 rounded-full transition-all duration-200"style={{- width: `${state.stage === "rendering"- ? Math.min(- ((state.renderProgress || 0) /- (state.totalFrames || 1)) *- 100,- 100- )- : Math.min(state.progress || 0, 100)- }%`,+ width: `${+ state.stage === "rendering"+ ? Math.min(+ ((state.renderProgress || 0) /+ (state.totalFrames || 1)) *+ 100,+ 100+ )+ : Math.min(state.progress || 0, 100)+ }%`,}}/></div>@@ -127,15 +128,16 @@ export function Header() {<divclass="bg-blue-300 h-2.5 rounded-full transition-all duration-200"style={{- width: `${state.stage === "rendering"- ? Math.min(- ((state.renderProgress || 0) /- (state.totalFrames || 1)) *- 100,- 100- )- : Math.min(state.progress || 0, 100)- }%`,+ width: `${+ state.stage === "rendering"+ ? Math.min(+ ((state.renderProgress || 0) /+ (state.totalFrames || 1)) *+ 100,+ 100+ )+ : Math.min(state.progress || 0, 100)+ }%`,}}/></div>@@ -163,13 +165,14 @@ export function Header() {<divclass="bg-blue-300 h-2.5 rounded-full transition-all duration-200"style={{- width: `${state.stage === "rendering"- ? Math.min(state.renderProgress || 0, 100)- : Math.min(- (state.uploadProgress || 0) * 100,- 100- )- }%`,+ width: `${+ state.stage === "rendering"+ ? Math.min(state.renderProgress || 0, 100)+ : Math.min(+ (state.uploadProgress || 0) * 100,+ 100+ )+ }%`,}}/></div>@@ -177,8 +180,8 @@ export function Header() {<p class="text-xs text-white mt-3 relative z-10">{state.stage === "rendering"? `Rendering - ${Math.round(- state.renderProgress || 0- )}%`+ state.renderProgress || 0+ )}%`: state.message}</p></div>@@ -241,7 +244,12 @@ function ExportButton() {}};- const videoPath = await commands.renderToFile(videoId, project, progress);+ const videoPath = await commands.exportVideo(+ videoId,+ project,+ progress,+ false+ );await commands.copyFileToPath(videoPath, path);setProgressState({@@ -309,7 +317,7 @@ function ShareButton() {setProgressState({type: "uploading",renderProgress: 100,- uploadProgress: progress,+ uploadProgress: progress / 100,message: `Uploading - ${progress}%`,mediaPath: videoId,stage: "uploading",@@ -322,59 +330,51 @@ function ShareButton() {const projectConfig =project ?? presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG;- // First try to get or render the video- try {- setProgressState({- type: "uploading",- renderProgress: 0,- uploadProgress: 0,- message: "Rendering - 0%",- mediaPath: videoId,- stage: "rendering",- });+ setProgressState({+ type: "uploading",+ renderProgress: 0,+ uploadProgress: 0,+ message: "Rendering - 0%",+ mediaPath: videoId,+ stage: "rendering",+ });- const progress = new Channel<RenderProgress>();- progress.onmessage = (p) => {- console.log("Progress channel message:", p);- if (- p.type === "FrameRendered" &&- progressState.type === "uploading"- ) {- const renderProgress = Math.round(- (p.current_frame / (progressState.totalFrames || 1)) * 100- );- setProgressState({- ...progressState,- message: `Rendering - ${renderProgress}%`,- renderProgress,- });- }- if (- p.type === "EstimatedTotalFrames" &&- progressState.type === "uploading"- ) {- console.log("Got total frames:", p.total_frames);- setProgressState({- ...progressState,- totalFrames: p.total_frames,- });- }- };-- await commands.renderVideoWithProgress(- videoId,- projectConfig,- progress- );- } catch (error) {- console.error("Error rendering video:", error);- throw new Error("Failed to render video");- }+ const progress = new Channel<RenderProgress>();+ progress.onmessage = (p) => {+ console.log("Progress channel message:", p);+ if (+ p.type === "FrameRendered" &&+ progressState.type === "uploading"+ ) {+ const renderProgress = Math.round(+ (p.current_frame / (progressState.totalFrames || 1)) * 100+ );+ setProgressState({+ ...progressState,+ message: `Rendering - ${renderProgress}%`,+ renderProgress,+ });+ }+ if (+ p.type === "EstimatedTotalFrames" &&+ progressState.type === "uploading"+ ) {+ console.log("Got total frames:", p.total_frames);+ setProgressState({+ ...progressState,+ totalFrames: p.total_frames,+ });+ }+ };++ await commands.exportVideo(videoId, projectConfig, progress, false);// Now proceed with uploadconst result = recordingMeta()?.sharing- ? await commands.reuploadRenderedVideo(videoId, projectConfig)- : await commands.uploadRenderedVideo(videoId, projectConfig, null);+ ? await commands.uploadExportedVideo(videoId, "Reupload")+ : await commands.uploadExportedVideo(videoId, {+ Initial: { pre_created_video: null },+ });console.log("Upload result:", result);diff --git a/apps/desktop/src/routes/prev-recordings.tsx b/apps/desktop/src/routes/prev-recordings.tsxindex d53fecda2..25d1bc04e 100644--- a/apps/desktop/src/routes/prev-recordings.tsx+++ b/apps/desktop/src/routes/prev-recordings.tsx@@ -23,6 +23,7 @@ import { createElementBounds } from "@solid-primitives/bounds";import { TransitionGroup } from "solid-transition-group";import { makePersisted } from "@solid-primitives/storage";import { Channel } from "@tauri-apps/api/core";+import { createStore, produce } from "solid-js/store";import {commands,@@ -33,7 +34,6 @@ import {import { DEFAULT_PROJECT_CONFIG } from "./editor/projectConfig";import { createPresets } from "~/utils/createPresets";import { progressState, setProgressState } from "~/store/progress";-import { createStore, produce } from "solid-js/store";type MediaEntry = {path: string;@@ -43,7 +43,6 @@ type MediaEntry = {};export default function () {- const presets = createPresets();const [recordings, setRecordings] = makePersisted(createStore<MediaEntry[]>([]),{ name: "recordings-store" }@@ -146,451 +145,37 @@ export default function () {exitActiveClass="absolute"><For each={allMedia()}>- {(media, i) => {+ {(media) => {const [ref, setRef] = createSignal<HTMLElement | null>(null);const normalizedPath = media.path.replace(/\\/g, "/");const mediaId = normalizedPath.split("/").pop()?.split(".")[0]!;const type = media.type ?? "recording";- const fileId =- type === "recording"- ? mediaId- : normalizedPath- .split("screenshots/")[1]- .split("/")[0]- .replace(".cap", "");const isRecording = type !== "screenshot";- const recordingMeta = createQuery(() => ({- queryKey: ["recordingMeta", fileId],- queryFn: () =>- commands.getRecordingMeta(- fileId,- isRecording ? "recording" : "screenshot"- ),- enabled: true,- }));-- const copyMedia = createMutation(() => ({- mutationFn: async () => {- setProgressState({- type: "copying",- progress: 0,- renderProgress: 0,- totalFrames: 0,- message: "Preparing...",- mediaPath: media.path,- stage: "rendering",- });-- try {- if (isRecording) {- let outputPath: string;-- try {- // First try to get existing rendered video- outputPath = await commands.getRenderedVideo(- mediaId,- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG- );- console.log("Using existing rendered video");-- // Show quick progress animation for existing video- setProgressState({- type: "copying",- progress: 0,- renderProgress: 100,- totalFrames: 100,- message: "Copying to clipboard...",- mediaPath: media.path,- stage: "rendering",- });-- await commands.copyVideoToClipboard(outputPath);- } catch (error) {- console.log(- "Need to render video with progress:",- error- );- const progress = new Channel<RenderProgress>();- progress.onmessage = (p) => {- console.log("Progress channel message:", p);- if (- p.type === "FrameRendered" &&- progressState.type === "copying"- ) {- console.log(- "Frame rendered:",- p.current_frame,- "Total frames:",- progressState.totalFrames- );- setProgressState({- ...progressState,- message: "Rendering video...",- renderProgress: p.current_frame,- });- }- if (- p.type === "EstimatedTotalFrames" &&- progressState.type === "copying"- ) {- console.log("Got total frames:", p.total_frames);- setProgressState({- ...progressState,- totalFrames: p.total_frames,- });- }- };-- outputPath = await commands.renderVideoWithProgress(- mediaId,- presets.getDefaultConfig() ??- DEFAULT_PROJECT_CONFIG,- progress- );- console.log("Video rendered, copying to clipboard");- await commands.copyVideoToClipboard(outputPath);- }- } else {- // For screenshots, show quick progress animation- setProgressState({- type: "copying",- progress: 50,- renderProgress: 100,- totalFrames: 100,- message: "Copying image to clipboard...",- mediaPath: media.path,- stage: "rendering",- });- await commands.copyScreenshotToClipboard(media.path);- }-- setProgressState({- type: "copying",- progress: 100,- renderProgress: 100,- totalFrames: 100,- message: "Copied successfully!",- mediaPath: media.path,- stage: "rendering",- });-- setTimeout(() => {- setProgressState({ type: "idle" });- }, 1500);- } catch (error) {- console.error("Error in copy media:", error);- setProgressState({ type: "idle" });- throw error;- }- },- }));+ const { copy, save, upload } = createRecordingMutations(+ media,+ (e) => {+ if (e === "upgradeRequired") setShowUpgradeTooltip(true);+ }+ );- const saveMedia = createMutation(() => ({- mutationFn: async () => {- setProgressState({- type: "saving",- progress: 0,- renderProgress: 0,- totalFrames: 0,- message: isRecording- ? "Choose where to save video..."- : "Choose where to save image...",- mediaPath: media.path,- stage: "rendering",- });+ const [metadata] = createResource(async () => {+ if (!isRecording) return null;- try {- const meta = recordingMeta.data;- if (!meta) {- throw new Error("Recording metadata not available");- }-- const defaultName = isRecording- ? "Cap Recording"- : media.path.split(".cap/")[1];- const suggestedName = meta.pretty_name || defaultName;-- const fileType = isRecording ? "recording" : "screenshot";- const extension = isRecording ? ".mp4" : ".png";-- const fullFileName = suggestedName.endsWith(extension)- ? suggestedName- : `${suggestedName}${extension}`;-- const savePath = await commands.saveFileDialog(- fullFileName,- fileType- );-- if (!savePath) {- setProgressState({ type: "idle" });- return false;- }-- if (isRecording) {- let outputPath: string;-- try {- // First try to get existing rendered video- outputPath = await commands.getRenderedVideo(- mediaId,- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG- );- console.log("Using existing rendered video");-- // Show quick progress animation for existing video- setProgressState({- type: "saving",- progress: 0,- renderProgress: 100,- totalFrames: 100,- message: "Saving video...",- mediaPath: media.path,- stage: "rendering",- });- } catch (error) {- // If it doesn't exist, render with progress- console.log("Need to render video:", error);- const progress = new Channel<RenderProgress>();- progress.onmessage = (p) => {- console.log("Progress channel message:", p);- if (- p.type === "FrameRendered" &&- progressState.type === "saving"- ) {- console.log(- "Frame rendered:",- p.current_frame,- "Total frames:",- progressState.totalFrames- );- setProgressState({- ...progressState,- message: "Rendering video...",- renderProgress: p.current_frame,- });- }- if (- p.type === "EstimatedTotalFrames" &&- progressState.type === "saving"- ) {- console.log("Got total frames:", p.total_frames);- setProgressState({- ...progressState,- totalFrames: p.total_frames,- });- }- };-- outputPath = await commands.renderVideoWithProgress(- mediaId,- presets.getDefaultConfig() ??- DEFAULT_PROJECT_CONFIG,- progress- );- }-- // Show copying progress- setProgressState({- type: "saving",- progress: 50,- renderProgress: 100,- totalFrames: 100,- message: "Copying file...",- mediaPath: media.path,- stage: "rendering",- });-- await commands.copyFileToPath(outputPath, savePath);- } else {- // For screenshots, show quick progress animation- setProgressState({- type: "saving",- progress: 50,- renderProgress: 0,- totalFrames: 0,- message: "Saving image...",- mediaPath: media.path,- stage: "rendering",- });-- await commands.copyFileToPath(media.path, savePath);- }-- setProgressState({- type: "saving",- progress: 100,- renderProgress: 100,- totalFrames: 100,- message: "Saved successfully!",- mediaPath: media.path,- stage: "rendering",- });-- setTimeout(() => {- setProgressState({ type: "idle" });- }, 1500);-- return true;- } catch (error) {- setProgressState({ type: "idle" });- throw error;- }- },- }));- const uploadMedia = createMutation(() => ({- mutationFn: async () => {- if (recordingMeta.data?.sharing) {- setProgressState({- type: "copying",- progress: 100,- message: "Link copied to clipboard!",- mediaPath: media.path,- });-- setTimeout(() => {- setProgressState({ type: "idle" });- }, 1500);-- return;- }-- const isUpgraded = await commands.checkUpgradedAndUpdate();- if (!isUpgraded) {- await commands.openUpgradeWindow();- return;- }-- setProgressState({- type: "uploading",- renderProgress: 0,- uploadProgress: 0,- message: "Preparing to render...",- mediaPath: media.path,- stage: "rendering",+ const result = await commands+ .getVideoMetadata(media.path, null)+ .catch((e) => {+ console.error(`Failed to get metadata: ${e}`);});+ if (!result) return;- try {- let res: UploadResult;- if (isRecording) {- let outputPath: string;- try {- // First try to get existing rendered video- outputPath = await commands.getRenderedVideo(- mediaId,- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG- );- console.log("Using existing rendered video");-- // Show quick progress animation for existing video- setProgressState({- type: "uploading",- renderProgress: 100,- uploadProgress: 0,- message: "Starting upload...",- mediaPath: media.path,- stage: "uploading",- });- } catch (error) {- // If it doesn't exist, render with progress- console.log(- "Need to render video with progress:",- error- );- const progress = new Channel<RenderProgress>();- progress.onmessage = (p) => {- console.log("Progress channel message:", p);- if (- p.type === "FrameRendered" &&- progressState.type === "uploading"- ) {- console.log(- "Frame rendered:",- p.current_frame,- "Total frames:",- progressState.totalFrames- );- setProgressState({- ...progressState,- message: "Rendering video...",- renderProgress: progressState.totalFrames- ? Math.round(- (p.current_frame /- progressState.totalFrames) *- 100- )- : 0,- });- }- if (- p.type === "EstimatedTotalFrames" &&- progressState.type === "uploading"- ) {- console.log("Got total frames:", p.total_frames);- setProgressState({- ...progressState,- totalFrames: p.total_frames,- });- }- };-- outputPath = await commands.renderVideoWithProgress(- mediaId,- presets.getDefaultConfig() ??- DEFAULT_PROJECT_CONFIG,- progress- );- }-- res = await commands.uploadRenderedVideo(- mediaId,- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,- null- );- } else {- res = await commands.uploadScreenshot(media.path);- }-- switch (res) {- case "NotAuthenticated":- throw new Error("Not authenticated");- case "PlanCheckFailed":- throw new Error("Plan check failed");- case "UpgradeRequired":- setProgressState({ type: "idle" });- setShowUpgradeTooltip(true);- return;- default:- break;- }- } catch (error) {- setProgressState({ type: "idle" });- throw error;- }- },- onSuccess: () =>- startTransition(() => recordingMeta.refetch()),- }));+ const [duration, size] = result;+ console.log(+ `Metadata for ${media.path}: duration=${duration}, size=${size}`+ );- const [metadata] = createResource(async () => {- if (isRecording) {- const result = await commands- .getVideoMetadata(media.path, null)- .catch((e) => {- console.error(`Failed to get metadata: ${e}`);- });- if (!result) return;-- const [duration, size] = result;- console.log(- `Metadata for ${media.path}: duration=${duration}, size=${size}`- );-- return { duration, size };- }- return null;+ return { duration, size };});const [imageExists, setImageExists] = createSignal(true);@@ -598,12 +183,23 @@ export default function () {createSignal(false);const isLoading = () =>- copyMedia.isPending ||- saveMedia.isPending ||- uploadMedia.isPending;+ copy.isPending || save.isPending || upload.isPending;createFakeWindowBounds(ref, () => media.path);+ const fileId =+ type === "recording"+ ? mediaId+ : normalizedPath+ .split("screenshots/")[1]+ .split("/")[0]+ .replace(".cap", "");++ const recordingMeta = createQuery(() => ({+ queryKey: ["recordingMeta", fileId],+ queryFn: () => commands.getRecordingMeta(fileId, type),+ }));+return (<Suspense><div@@ -824,26 +420,24 @@ export default function () {<TooltipIconButtonclass="absolute right-3 top-3 z-20"tooltipText={- copyMedia.isPending+ copy.isPending? "Copying to Clipboard": "Copy to Clipboard"}tooltipPlacement="left"- onClick={() => copyMedia.mutate()}- disabled={- saveMedia.isPending || uploadMedia.isPending- }+ onClick={() => copy.mutate()}+ disabled={save.isPending || upload.isPending}><Switchfallback={<IconCapCopy class="size-[1rem]" />}>- <Match when={copyMedia.isPending}>+ <Match when={copy.isPending}><IconLucideLoaderCircle class="size-[1rem] animate-spin" /></Match>- <Match when={copyMedia.isSuccess}>+ <Match when={copy.isSuccess}>{(_) => {setTimeout(() => {- if (!copyMedia.isPending) copyMedia.reset();+ if (!copy.isPending) copy.reset();}, 2000);return (@@ -858,7 +452,7 @@ export default function () {tooltipText={recordingMeta.data?.sharing? "Copy Shareable Link"- : uploadMedia.isPending+ : upload.isPending? "Uploading Cap": showUpgradeTooltip()? "Upgrade Required"@@ -866,11 +460,11 @@ export default function () {}tooltipPlacement="left"onClick={() => {- uploadMedia.mutate();+ upload.mutate();}}disabled={- copyMedia.isPending ||- saveMedia.isPending ||+ copy.isPending ||+ save.isPending ||recordingMeta.isLoading ||recordingMeta.isError}@@ -878,14 +472,13 @@ export default function () {<Switchfallback={<IconCapUpload class="size-[1rem]" />}>- <Match when={uploadMedia.isPending}>+ <Match when={upload.isPending}><IconLucideLoaderCircle class="size-[1rem] animate-spin" /></Match>- <Match when={uploadMedia.isSuccess}>+ <Match when={upload.isSuccess}>{(_) => {setTimeout(() => {- if (!uploadMedia.isPending)- uploadMedia.reset();+ if (!upload.isPending) upload.reset();}, 2000);return (@@ -899,25 +492,17 @@ export default function () {<Buttonvariant="secondary"size="sm"- onClick={() => saveMedia.mutate()}- disabled={- copyMedia.isPending || uploadMedia.isPending- }+ onClick={() => save.mutate()}+ disabled={copy.isPending || upload.isPending}><Switch fallback="Save">- <Match when={saveMedia.isPending}>- Saving...- </Match>+ <Match when={save.isPending}>Saving...</Match><Match- when={- saveMedia.isSuccess &&- saveMedia.data === true- }+ when={save.isSuccess && save.data === true}>{(_) => {setTimeout(() => {- if (!saveMedia.isPending)- saveMedia.reset();+ if (!save.isPending) save.reset();}, 2000);return "Saved!";@@ -927,7 +512,7 @@ export default function () {</Button></div></div>- <Show when={isRecording && metadata()}>+ <Show when={metadata()}>{(metadata) => (<divstyle={{ color: "white", "font-size": "14px" }}@@ -1037,3 +622,362 @@ function createFakeWindowBounds(commands.removeFakeWindow(key());});}++function createRecordingMutations(+ media: MediaEntry,+ onEvent: (e: "upgradeRequired") => void+) {+ const presets = createPresets();++ const normalizedPath = media.path.replace(/\\/g, "/");+ const mediaId = normalizedPath.split("/").pop()?.split(".")[0]!;+ const type = media.type ?? "recording";+ const isRecording = type !== "screenshot";++ const fileId =+ type === "recording"+ ? mediaId+ : normalizedPath+ .split("screenshots/")[1]+ .split("/")[0]+ .replace(".cap", "");++ const recordingMeta = createQuery(() => ({+ queryKey: ["recordingMeta", fileId],+ queryFn: () => commands.getRecordingMeta(fileId, type),+ }));++ const copy = createMutation(() => ({+ mutationFn: async () => {+ setProgressState({+ type: "copying",+ progress: 0,+ renderProgress: 0,+ totalFrames: 0,+ message: "Preparing...",+ mediaPath: media.path,+ stage: "rendering",+ });++ try {+ if (isRecording) {+ const progress = new Channel<RenderProgress>();+ progress.onmessage = (p) => {+ console.log("Progress channel message:", p);+ if (+ p.type === "FrameRendered" &&+ progressState.type === "copying"+ ) {+ console.log(+ "Frame rendered:",+ p.current_frame,+ "Total frames:",+ progressState.totalFrames+ );+ setProgressState({+ ...progressState,+ message: "Rendering video...",+ renderProgress: p.current_frame,+ });+ }+ if (+ p.type === "EstimatedTotalFrames" &&+ progressState.type === "copying"+ ) {+ console.log("Got total frames:", p.total_frames);+ setProgressState({+ ...progressState,+ totalFrames: p.total_frames,+ });+ }+ };++ // First try to get existing rendered video+ const outputPath = await commands.exportVideo(+ mediaId,+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,+ progress,+ false+ );++ // Show quick progress animation for existing video+ setProgressState({+ type: "copying",+ progress: 0,+ renderProgress: 100,+ totalFrames: 100,+ message: "Copying to clipboard...",+ mediaPath: media.path,+ stage: "rendering",+ });++ await commands.copyVideoToClipboard(outputPath);+ } else {+ // For screenshots, show quick progress animation+ setProgressState({+ type: "copying",+ progress: 50,+ renderProgress: 100,+ totalFrames: 100,+ message: "Copying image to clipboard...",+ mediaPath: media.path,+ stage: "rendering",+ });+ await commands.copyScreenshotToClipboard(media.path);+ }++ setProgressState({+ type: "copying",+ progress: 100,+ renderProgress: 100,+ totalFrames: 100,+ message: "Copied successfully!",+ mediaPath: media.path,+ stage: "rendering",+ });++ setTimeout(() => {+ setProgressState({ type: "idle" });+ }, 1500);+ } catch (error) {+ console.error("Error in copy media:", error);+ setProgressState({ type: "idle" });+ throw error;+ }+ },+ }));++ const save = createMutation(() => ({+ mutationFn: async () => {+ setProgressState({+ type: "saving",+ progress: 0,+ renderProgress: 0,+ totalFrames: 0,+ message: isRecording+ ? "Choose where to save video..."+ : "Choose where to save image...",+ mediaPath: media.path,+ stage: "rendering",+ });++ try {+ const meta = recordingMeta.data;+ if (!meta) {+ throw new Error("Recording metadata not available");+ }++ const defaultName = isRecording+ ? "Cap Recording"+ : media.path.split(".cap/")[1];+ const suggestedName = meta.pretty_name || defaultName;++ const fileType = isRecording ? "recording" : "screenshot";+ const extension = isRecording ? ".mp4" : ".png";++ const fullFileName = suggestedName.endsWith(extension)+ ? suggestedName+ : `${suggestedName}${extension}`;++ const savePath = await commands.saveFileDialog(fullFileName, fileType);++ if (!savePath) {+ setProgressState({ type: "idle" });+ return false;+ }++ if (isRecording) {+ let outputPath: string;++ const progress = new Channel<RenderProgress>();+ progress.onmessage = (p) => {+ console.log("Progress channel message:", p);+ if (p.type === "FrameRendered" && progressState.type === "saving") {+ console.log(+ "Frame rendered:",+ p.current_frame,+ "Total frames:",+ progressState.totalFrames+ );+ setProgressState({+ ...progressState,+ message: "Rendering video...",+ renderProgress: p.current_frame,+ });+ }+ if (+ p.type === "EstimatedTotalFrames" &&+ progressState.type === "saving"+ ) {+ console.log("Got total frames:", p.total_frames);+ setProgressState({+ ...progressState,+ totalFrames: p.total_frames,+ });+ }+ };++ // First try to get existing rendered video+ outputPath = await commands.exportVideo(+ mediaId,+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,+ progress,+ false+ );++ await commands.copyFileToPath(outputPath, savePath);+ } else {+ // For screenshots, show quick progress animation+ setProgressState({+ type: "saving",+ progress: 50,+ renderProgress: 0,+ totalFrames: 0,+ message: "Saving image...",+ mediaPath: media.path,+ stage: "rendering",+ });++ await commands.copyFileToPath(media.path, savePath);+ }++ setProgressState({+ type: "saving",+ progress: 100,+ renderProgress: 100,+ totalFrames: 100,+ message: "Saved successfully!",+ mediaPath: media.path,+ stage: "rendering",+ });++ setTimeout(() => {+ setProgressState({ type: "idle" });+ }, 1500);++ return true;+ } catch (error) {+ setProgressState({ type: "idle" });+ throw error;+ }+ },+ }));++ const upload = createMutation(() => ({+ mutationFn: async () => {+ if (recordingMeta.data?.sharing) {+ setProgressState({+ type: "copying",+ progress: 100,+ message: "Link copied to clipboard!",+ mediaPath: media.path,+ });++ setTimeout(() => {+ setProgressState({ type: "idle" });+ }, 1500);++ return;+ }++ const isUpgraded = await commands.checkUpgradedAndUpdate();+ if (!isUpgraded) {+ await commands.showWindow("Upgrade");+ return;+ }++ setProgressState({+ type: "uploading",+ renderProgress: 0,+ uploadProgress: 0,+ message: "Preparing to render...",+ mediaPath: media.path,+ stage: "rendering",+ });++ try {+ let res: UploadResult;+ if (isRecording) {+ const progress = new Channel<RenderProgress>();+ progress.onmessage = (p) => {+ console.log("Progress channel message:", p);+ if (+ p.type === "FrameRendered" &&+ progressState.type === "uploading"+ ) {+ console.log(+ "Frame rendered:",+ p.current_frame,+ "Total frames:",+ progressState.totalFrames+ );+ setProgressState({+ ...progressState,+ message: "Rendering video...",+ renderProgress: progressState.totalFrames+ ? Math.round(+ (p.current_frame / progressState.totalFrames) * 100+ )+ : 0,+ });+ }+ if (+ p.type === "EstimatedTotalFrames" &&+ progressState.type === "uploading"+ ) {+ console.log("Got total frames:", p.total_frames);+ setProgressState({+ ...progressState,+ totalFrames: p.total_frames,+ });+ }+ };++ // First try to get existing rendered video+ await commands.exportVideo(+ mediaId,+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,+ progress,+ false+ );+ console.log("Using existing rendered video");++ // Show quick progress animation for existing video+ setProgressState({+ type: "uploading",+ renderProgress: 100,+ uploadProgress: 0,+ message: "Starting upload...",+ mediaPath: media.path,+ stage: "uploading",+ });++ res = await commands.uploadExportedVideo(mediaId, {+ Initial: { pre_created_video: null },+ });+ } else {+ res = await commands.uploadScreenshot(media.path);+ }++ switch (res) {+ case "NotAuthenticated":+ throw new Error("Not authenticated");+ case "PlanCheckFailed":+ throw new Error("Plan check failed");+ case "UpgradeRequired":+ setProgressState({ type: "idle" });+ onEvent("upgradeRequired");+ return;+ default:+ break;+ }+ } catch (error) {+ setProgressState({ type: "idle" });+ throw error;+ }+ },+ onSuccess: () => startTransition(() => recordingMeta.refetch()),+ }));++ return { copy, save, upload };+}diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 1de0c5df6..91117069a 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -38,9 +38,6 @@ async takeScreenshot() : Promise<null> {async listAudioDevices() : Promise<string[]> {return await TAURI_INVOKE("list_audio_devices");},-async showPreviousRecordingsWindow() : Promise<void> {- await TAURI_INVOKE("show_previous_recordings_window");-},async closePreviousRecordingsWindow() : Promise<void> {await TAURI_INVOKE("close_previous_recordings_window");},@@ -56,17 +53,8 @@ async focusCapturesPanel() : Promise<void> {async getCurrentRecording() : Promise<JsonValue<RecordingInfo | null>> {return await TAURI_INVOKE("get_current_recording");},-async renderToFile(videoId: string, project: ProjectConfiguration, progressChannel: TAURI_CHANNEL<RenderProgress>) : Promise<string> {- return await TAURI_INVOKE("render_to_file", { videoId, project, progressChannel });-},-async getRenderedVideo(videoId: string, project: ProjectConfiguration) : Promise<string> {- return await TAURI_INVOKE("get_rendered_video", { videoId, project });-},-async getRenderedVideoWithProgress(videoId: string, project: ProjectConfiguration, progressChannel: TAURI_CHANNEL<RenderProgress>) : Promise<string> {- return await TAURI_INVOKE("get_rendered_video_with_progress", { videoId, project, progressChannel });-},-async renderVideoWithProgress(videoId: string, project: ProjectConfiguration, progressChannel: TAURI_CHANNEL<RenderProgress>) : Promise<string> {- return await TAURI_INVOKE("render_video_with_progress", { videoId, project, progressChannel });+async exportVideo(videoId: string, project: ProjectConfiguration, progress: TAURI_CHANNEL<RenderProgress>, force: boolean) : Promise<string> {+ return await TAURI_INVOKE("export_video", { videoId, project, progress, force });},async copyFileToPath(src: string, dst: string) : Promise<null> {return await TAURI_INVOKE("copy_file_to_path", { src, dst });@@ -113,8 +101,8 @@ async doPermissionsCheck(initialCheck: boolean) : Promise<OSPermissionsCheck> {async requestPermission(permission: OSPermission) : Promise<void> {await TAURI_INVOKE("request_permission", { permission });},-async uploadRenderedVideo(videoId: string, project: ProjectConfiguration, preCreatedVideo: PreCreatedVideo | null) : Promise<UploadResult> {- return await TAURI_INVOKE("upload_rendered_video", { videoId, project, preCreatedVideo });+async uploadExportedVideo(videoId: string, mode: UploadMode) : Promise<UploadResult> {+ return await TAURI_INVOKE("upload_exported_video", { videoId, mode });},async uploadScreenshot(screenshotPath: string) : Promise<UploadResult> {return await TAURI_INVOKE("upload_screenshot", { screenshotPath });@@ -122,12 +110,6 @@ async uploadScreenshot(screenshotPath: string) : Promise<UploadResult> {async getRecordingMeta(id: string, fileType: string) : Promise<RecordingMeta> {return await TAURI_INVOKE("get_recording_meta", { id, fileType });},-async openUpgradeWindow() : Promise<void> {- await TAURI_INVOKE("open_upgrade_window");-},-async openSettingsWindow(page: string) : Promise<void> {- await TAURI_INVOKE("open_settings_window", { page });-},async saveFileDialog(fileName: string, fileType: string) : Promise<string | null> {return await TAURI_INVOKE("save_file_dialog", { fileName, fileType });},@@ -167,11 +149,11 @@ async sendFeedbackRequest(feedback: string) : Promise<null> {async positionTrafficLights(controlsInset: [number, number] | null) : Promise<void> {await TAURI_INVOKE("position_traffic_lights", { controlsInset });},-async reuploadRenderedVideo(videoId: string, project: ProjectConfiguration) : Promise<UploadResult> {- return await TAURI_INVOKE("reupload_rendered_video", { videoId, project });-},async globalMessageDialog(message: string) : Promise<void> {await TAURI_INVOKE("global_message_dialog", { message });+},+async showWindow(window: ShowCapWindow) : Promise<void> {+ await TAURI_INVOKE("show_window", { window });}}@@ -196,7 +178,6 @@ requestOpenSettings: RequestOpenSettings,requestRestartRecording: RequestRestartRecording,requestStartRecording: RequestStartRecording,requestStopRecording: RequestStopRecording,-showCapturesPanel: ShowCapturesPanel,uploadProgress: UploadProgress}>({audioInputLevelChange: "audio-input-level-change",@@ -216,7 +197,6 @@ requestOpenSettings: "request-open-settings",requestRestartRecording: "request-restart-recording",requestStartRecording: "request-start-recording",requestStopRecording: "request-stop-recording",-showCapturesPanel: "show-captures-panel",uploadProgress: "upload-progress"})@@ -286,9 +266,10 @@ export type S3UploadMeta = { id: string; user_id: string; aws_region: string; awexport type ScreenCaptureTarget = ({ variant: "window" } & CaptureWindow) | ({ variant: "screen" } & CaptureScreen)export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordings; path: string; prettyName: string }export type SharingMeta = { id: string; link: string }-export type ShowCapturesPanel = null+export type ShowCapWindow = "Setup" | "Main" | { Settings: { page: string | null } } | { Editor: { project_id: string } } | "PrevRecordings" | "WindowCaptureOccluder" | { Camera: { ws_port: number } } | { InProgressRecording: { position: [number, number] | null } } | "Upgrade"export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments?: ZoomSegment[] }export type TimelineSegment = { timescale: number; start: number; end: number }+export type UploadMode = { Initial: { pre_created_video: PreCreatedVideo | null } } | "Reupload"export type UploadProgress = { stage: string; progress: number; message: string }export type UploadResult = { Success: string } | "NotAuthenticated" | "PlanCheckFailed" | "UpgradeRequired"export type Video = { duration: number; width: number; height: number }diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rsindex 20aac3aa0..2d8888fee 100644--- a/crates/project/src/lib.rs+++ b/crates/project/src/lib.rs@@ -136,4 +136,8 @@ impl RecordingMeta {}data}++ pub fn output_path(&self) -> PathBuf {+ self.project_path.join("output").join("result.mp4")+ }}