Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Open editor or file when .cap file is opened (#421)

Richie McIlroyafc2b9e82dcd
diff --git a/apps/desktop/src-tauri/src/editor_window.rs b/apps/desktop/src-tauri/src/editor_window.rs
index 83ae9d9e4..6e6d3f983 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<Arc<EditorInstance>, String> {
let instances = match window.try_state::<EditorInstances>() {
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 53a91e3d6..71d671ccb 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<RenderProgress>,
force: bool,
fps: u32,
resolution_base: XY<u32>,
) -> Result<PathBuf, String> {
- 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<u32>,
fps: u32,
) -> Result<ExportEstimates, String> {
- 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 5b1fccea8..8ec9b8828 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)]
@@ -975,15 +980,25 @@ struct SerializedEditorInstance {
#[tauri::command]
#[specta::specta]
-async fn create_editor_instance(
- window: Window,
- video_id: String,
-) -> Result<SerializedEditorInstance, String> {
- let editor_instance = EditorInstances::get_or_create(&window, &video_id).await?;
+async fn create_editor_instance(window: Window) -> Result<SerializedEditorInstance, String> {
+ 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);
@@ -996,7 +1011,7 @@ async fn create_editor_instance(
},
recordings: editor_instance.recordings.clone(),
path: editor_instance.project_path.clone(),
- meta,
+ meta: meta.clone(),
})
}
@@ -1019,25 +1034,8 @@ async fn copy_video_to_clipboard(
#[tauri::command]
#[specta::specta]
-async fn get_video_metadata(
- app: AppHandle,
- video_id: String,
- video_type: Option<VideoType>,
-) -> Result<VideoRecordingMetadata, String> {
- 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<VideoRecordingMetadata, String> {
+ let recording_meta = RecordingMeta::load_for_project(&path)?;
fn get_duration_for_path(path: PathBuf) -> Result<f64, String> {
let reader = BufReader::new(
@@ -1064,7 +1062,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 } => {
@@ -1110,19 +1108,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) {
@@ -1221,7 +1206,7 @@ pub enum UploadMode {
#[specta::specta]
async fn upload_exported_video(
app: AppHandle,
- video_id: String,
+ path: PathBuf,
mode: UploadMode,
) -> Result<UploadResult, String> {
let Ok(Some(auth)) = AuthStore::get(&app) else {
@@ -1230,26 +1215,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(
@@ -1264,13 +1241,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() {
@@ -1307,9 +1278,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")),
@@ -1330,7 +1303,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::<ArcLock<ClipboardContext>>()
@@ -1387,17 +1359,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
};
@@ -1624,11 +1585,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)]
@@ -1659,25 +1615,17 @@ pub enum RecordingType {
#[specta::specta]
fn get_recording_meta(
app: AppHandle,
- id: String,
+ path: PathBuf,
file_type: String,
) -> Result<RecordingMetaWithType, String> {
- 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<Vec<(String, PathBuf, RecordingMetaWithType)>, String> {
+fn list_recordings(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMetaWithType)>, String> {
let recordings_dir = recordings_path(&app);
// First check if directory exists
@@ -1700,33 +1648,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::<Vec<_>>();
// 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);
@@ -1738,7 +1675,7 @@ fn list_recordings(
#[tauri::command]
#[specta::specta]
-fn list_screenshots(app: AppHandle) -> Result<Vec<(String, PathBuf, RecordingMeta)>, String> {
+fn list_screenshots(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMeta)>, String> {
let screenshots_dir = screenshots_path(&app);
let mut result = std::fs::read_dir(&screenshots_dir)
@@ -1747,9 +1684,8 @@ fn list_screenshots(app: AppHandle) -> Result<Vec<(String, PathBuf, RecordingMet
let entry = entry.ok()?;
let path = entry.path();
if path.is_dir() && path.extension().and_then(|s| s.to_str()) == Some("cap") {
- let id = path.file_stem()?.to_str()?.to_string();
let meta =
- match get_recording_meta(app.clone(), id.clone(), "screenshot".to_string()) {
+ match get_recording_meta(app.clone(), path.clone(), "screenshot".to_string()) {
Ok(meta) => meta.inner,
Err(_) => return None, // Skip this entry if metadata can't be loaded
};
@@ -1761,7 +1697,7 @@ fn list_screenshots(app: AppHandle) -> Result<Vec<(String, PathBuf, RecordingMet
.find(|e| e.path().extension().and_then(|s| s.to_str()) == Some("png"))
.map(|e| e.path())?;
- Some((id, png_path, meta))
+ Some((png_path, meta))
} else {
None
}
@@ -1770,11 +1706,11 @@ fn list_screenshots(app: AppHandle) -> Result<Vec<(String, PathBuf, RecordingMet
// Sort the result by creation date of the actual file, newest first
result.sort_by(|a, b| {
- b.1.metadata()
+ b.0.metadata()
.and_then(|m| m.created())
.unwrap_or(std::time::SystemTime::UNIX_EPOCH)
.cmp(
- &a.1.metadata()
+ &a.0.metadata()
.and_then(|m| m.created())
.unwrap_or(std::time::SystemTime::UNIX_EPOCH),
)
@@ -1949,56 +1885,6 @@ fn set_fail(name: String, value: bool) {
cap_fail::set_fail(&name, value)
}
-#[tauri::command(async)]
-#[specta::specta]
-async fn reupload_instant_video(app: AppHandle, video_id: String) -> 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 {
@@ -2128,7 +2014,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,
@@ -2155,7 +2040,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![
@@ -2165,7 +2049,6 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
RenderFrameEvent,
EditorStateChanged,
CurrentRecordingChanged,
- RecordingMetaChanged,
RecordingStarted,
RecordingStopped,
RequestStartRecording,
@@ -2202,8 +2085,17 @@ 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 _ = ShowCapWindow::Main.show(app);
+ tauri::Builder::default().plugin(tauri_plugin_single_instance::init(|app, args, _cwd| {
+ let Some(cap_file) = args
+ .iter()
+ .find(|arg| arg.ends_with(".cap"))
+ .map(PathBuf::from)
+ else {
+ let _ = ShowCapWindow::Main.show(app);
+ return;
+ };
+
+ let _ = open_project_from_path(&cap_file, app.clone());
}));
#[cfg(target_os = "macos")]
@@ -2260,6 +2152,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| {
@@ -2410,7 +2303,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 => {
@@ -2445,6 +2341,13 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
}
}
}
+ WindowEvent::DragDrop(event) => {
+ if let tauri::DragDropEvent::Drop { paths, .. } = event {
+ for path in paths {
+ let _ = open_project_from_path(path, app.clone());
+ }
+ }
+ }
_ => {}
}
})
@@ -2490,11 +2393,11 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
async fn create_editor_instance_impl(
app: &AppHandle,
- video_id: &str,
+ path: PathBuf,
) -> Result<Arc<EditorInstance>, 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();
@@ -2604,3 +2507,29 @@ impl<F: Future<Output = T>, T, E> TransposeAsync for Result<F, E> {
}
}
}
+
+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_path = path.clone();
+
+ 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
+ .opener()
+ .open_path(mp4_path.to_str().unwrap_or_default(), None::<String>);
+ if let Some(main_window) = CapWindowId::Main.get(&app) {
+ main_window.close().ok();
+ }
+ }
+ }
+ }
+
+ Ok(())
+}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 03cb79cec..de516bf79 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, platform::display_for_window, sources::ScreenCaptureTarget};
use cap_media::{
@@ -632,7 +633,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 91506b0ea..d50c58d84 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -7,7 +7,12 @@ use cap_media::{platform::logical_monitor_bounds, 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 { screen_id: u32 },
CaptureArea,
@@ -51,7 +56,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::<u32>()
+ .map_err(|e| e.to_string())?,
},
s if s.starts_with("window-capture-occluder-") => Self::WindowCaptureOccluder {
screen_id: s
@@ -80,7 +88,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}"),
}
}
}
@@ -157,7 +165,7 @@ pub enum ShowCapWindow {
Setup,
Main,
Settings { page: Option<String> },
- Editor { project_id: String },
+ Editor { project_path: PathBuf },
RecordingsOverlay,
WindowCaptureOccluder { screen_id: u32 },
CaptureArea { screen_id: u32 },
@@ -170,13 +178,26 @@ pub enum ShowCapWindow {
impl ShowCapWindow {
pub async fn show(&self, app: &AppHandle<Wry>) -> tauri::Result<WebviewWindow> {
- if let Some(window) = self.id().get(app) {
+ if let Self::Editor { project_path } = self {
+ let state = app.state::<EditorWindowIds>();
+ 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 monitor = app.primary_monitor().unwrap().unwrap();
+ let id = self.id(app);
+ let monitor = app.primary_monitor()?.unwrap();
let window = match self {
Self::Setup => self
@@ -234,9 +255,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()
@@ -489,7 +514,7 @@ impl ShowCapWindow {
app: &'a AppHandle<Wry>,
url: impl Into<PathBuf>,
) -> WebviewWindowBuilder<'a, Wry, AppHandle<Wry>> {
- let id = self.id();
+ let id = self.id(app);
let mut builder = WebviewWindow::builder(app, id.label(), WebviewUrl::App(url.into()))
.title(id.title())
@@ -522,14 +547,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::<EditorWindowIds>();
+ 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 { screen_id } => {
CapWindowId::WindowCaptureOccluder {
@@ -668,3 +696,15 @@ pub fn set_window_transparent(window: tauri::Window, value: bool) {
}
}
}
+
+#[derive(Default, Clone)]
+pub struct EditorWindowIds {
+ pub ids: Arc<Mutex<Vec<(PathBuf, u32)>>>,
+ pub counter: Arc<AtomicU32>,
+}
+
+impl EditorWindowIds {
+ pub fn get(app: &AppHandle) -> Self {
+ app.state::<EditorWindowIds>().deref().clone()
+ }
+}
diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json
index ab5543d82..3d3cafac4 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"
+ }
+ ]
}
}
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx
index 8201de65a..f5230e737 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 89acf359a..618a97908 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 e7b1b5b78..86ecabe59 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 (
- <Show when={params.id} fallback="No video id available" keyed>
- {(videoId) => (
- <EditorInstanceContextProvider videoId={videoId}>
- <Show
- when={(() => {
- const ctx = useEditorInstanceContext();
- const editorInstance = ctx.editorInstance();
+ <EditorInstanceContextProvider path={params.path!}>
+ <Show
+ when={(() => {
+ const ctx = useEditorInstanceContext();
+ const editorInstance = ctx.editorInstance();
- if (!editorInstance) return;
+ if (!editorInstance) return;
- return { editorInstance };
- })()}
- >
- {(values) => (
- <EditorContextProvider {...values()}>
- <Inner />
- </EditorContextProvider>
- )}
- </Show>
- </EditorInstanceContextProvider>
- )}
- </Show>
+ return { editorInstance };
+ })()}
+ >
+ {(values) => (
+ <EditorContextProvider {...values()}>
+ <Inner />
+ </EditorContextProvider>
+ )}
+ </Show>
+ </EditorInstanceContextProvider>
);
}
diff --git a/apps/desktop/src/routes/editor/ExportDialog.tsx b/apps/desktop/src/routes/editor/ExportDialog.tsx
index cc9ecb6b0..4d384549a 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: <IconCapFile class="text-solid-white size-4" />,
@@ -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 076591581..cd999061d 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 1548c4851..d58dcf914 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<typeof transformMeta>;
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 ce62cb5c9..bb3249f10 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 eb7585982..e5c9ed19a 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -53,11 +53,11 @@ async focusCapturesPanel() : Promise<void> {
async getCurrentRecording() : Promise<JsonValue<CurrentRecording | null>> {
return await TAURI_INVOKE("get_current_recording");
},
-async exportVideo(videoId: string, progress: TAURI_CHANNEL<RenderProgress>, force: boolean, fps: number, resolutionBase: XY<number>) : Promise<string> {
- return await TAURI_INVOKE("export_video", { videoId, progress, force, fps, resolutionBase });
+async exportVideo(path: string, progress: TAURI_CHANNEL<RenderProgress>, force: boolean, fps: number, resolutionBase: XY<number>) : Promise<string> {
+ return await TAURI_INVOKE("export_video", { path, progress, force, fps, resolutionBase });
},
-async getExportEstimates(videoId: string, resolution: XY<number>, fps: number) : Promise<ExportEstimates> {
- return await TAURI_INVOKE("get_export_estimates", { videoId, resolution, fps });
+async getExportEstimates(path: string, resolution: XY<number>, fps: number) : Promise<ExportEstimates> {
+ return await TAURI_INVOKE("get_export_estimates", { path, resolution, fps });
},
async copyFileToPath(src: string, dst: string) : Promise<null> {
return await TAURI_INVOKE("copy_file_to_path", { src, dst });
@@ -71,11 +71,11 @@ async copyScreenshotToClipboard(path: string) : Promise<null> {
async openFilePath(path: string) : Promise<null> {
return await TAURI_INVOKE("open_file_path", { path });
},
-async getVideoMetadata(videoId: string, videoType: VideoType | null) : Promise<VideoRecordingMetadata> {
- return await TAURI_INVOKE("get_video_metadata", { videoId, videoType });
+async getVideoMetadata(path: string) : Promise<VideoRecordingMetadata> {
+ return await TAURI_INVOKE("get_video_metadata", { path });
},
-async createEditorInstance(videoId: string) : Promise<SerializedEditorInstance> {
- return await TAURI_INVOKE("create_editor_instance", { videoId });
+async createEditorInstance() : Promise<SerializedEditorInstance> {
+ return await TAURI_INVOKE("create_editor_instance");
},
async startPlayback(fps: number, resolutionBase: XY<number>) : Promise<null> {
return await TAURI_INVOKE("start_playback", { fps, resolutionBase });
@@ -89,9 +89,6 @@ async setPlayheadPosition(frameNumber: number) : Promise<null> {
async setProjectConfig(config: ProjectConfiguration) : Promise<null> {
return await TAURI_INVOKE("set_project_config", { config });
},
-async openEditor(id: string) : Promise<null> {
- return await TAURI_INVOKE("open_editor", { id });
-},
async openPermissionSettings(permission: OSPermission) : Promise<void> {
await TAURI_INVOKE("open_permission_settings", { permission });
},
@@ -101,22 +98,22 @@ async doPermissionsCheck(initialCheck: boolean) : Promise<OSPermissionsCheck> {
async requestPermission(permission: OSPermission) : Promise<void> {
await TAURI_INVOKE("request_permission", { permission });
},
-async uploadExportedVideo(videoId: string, mode: UploadMode) : Promise<UploadResult> {
- return await TAURI_INVOKE("upload_exported_video", { videoId, mode });
+async uploadExportedVideo(path: string, mode: UploadMode) : Promise<UploadResult> {
+ return await TAURI_INVOKE("upload_exported_video", { path, mode });
},
async uploadScreenshot(screenshotPath: string) : Promise<UploadResult> {
return await TAURI_INVOKE("upload_screenshot", { screenshotPath });
},
-async getRecordingMeta(id: string, fileType: string) : Promise<RecordingMetaWithType> {
- return await TAURI_INVOKE("get_recording_meta", { id, fileType });
+async getRecordingMeta(path: string, fileType: string) : Promise<RecordingMetaWithType> {
+ return await TAURI_INVOKE("get_recording_meta", { path, fileType });
},
async saveFileDialog(fileName: string, fileType: string) : Promise<string | null> {
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<boolean> {
@@ -170,9 +167,6 @@ async setFail(name: string, value: boolean) : Promise<void> {
async updateAuthPlan() : Promise<void> {
await TAURI_INVOKE("update_auth_plan");
},
-async reuploadInstantVideo(videoId: string) : Promise<null> {
- return await TAURI_INVOKE("reupload_instant_video", { videoId });
-},
async setWindowTransparent(value: boolean) : Promise<void> {
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: { screen_id: number } } | { 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: { screen_id: number } } | { 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<T> = { 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 314f95d4f..b92b2e0e1 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<ProjectRecordings>,
pub renderer: Arc<editor::RendererHandle>,
@@ -49,24 +48,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<Arc<Self>, 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 +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,
@@ -137,8 +124,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 +294,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
+ );
}
}