Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
tie editor instances to windows themselves (#288)
Brendan Allan21aec38c5acd
diff --git a/apps/desktop/src-tauri/src/editor_window.rs b/apps/desktop/src-tauri/src/editor_window.rsnew file mode 100644index 000000000..88bcc0f5b--- /dev/null+++ b/apps/desktop/src-tauri/src/editor_window.rs@@ -0,0 +1,71 @@+use std::{+ collections::HashMap,+ ops::Deref,+ sync::{Arc, RwLock},+};++use cap_editor::EditorInstance;+use tauri::{ipc::CommandArg, Manager, Runtime, Window};++#[derive(Clone)]+pub struct EditorInstances(Arc<RwLock<HashMap<String, Arc<EditorInstance>>>>);++pub struct WindowEditorInstance(pub Arc<EditorInstance>);++impl specta::function::FunctionArg for WindowEditorInstance {+ fn to_datatype(_: &mut specta::TypeMap) -> Option<specta::DataType> {+ None+ }+}++impl Deref for WindowEditorInstance {+ type Target = Arc<EditorInstance>;++ fn deref(&self) -> &Self::Target {+ &self.0+ }+}++impl AsRef<EditorInstance> for WindowEditorInstance {+ fn as_ref(&self) -> &EditorInstance {+ &self.0+ }+}++impl<'de, R: Runtime> CommandArg<'de, R> for WindowEditorInstance {+ fn from_command(+ command: tauri::ipc::CommandItem<'de, R>,+ ) -> Result<Self, tauri::ipc::InvokeError> {+ let window = Window::from_command(command)?;++ let instances = window.state::<EditorInstances>();+ let instance = instances.0.read().unwrap();++ Ok(Self(instance.get(window.label()).cloned().unwrap()))+ }+}++impl EditorInstances {+ pub fn add(window: &Window, instance: Arc<EditorInstance>) {+ let instances = match window.try_state::<EditorInstances>() {+ Some(s) => (*s).clone(),+ None => {+ let instances = Self(Arc::new(RwLock::new(HashMap::new())));+ window.manage(instances.clone());+ instances+ }+ };++ let mut instances = instances.0.write().unwrap();++ instances.insert(window.label().to_string(), instance);+ }++ pub fn remove(window: &Window) {+ let Some(instances) = window.try_state::<EditorInstances>() else {+ return;+ };++ instances.0.write().unwrap().remove(window.label());+ }+}diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rsindex 241ab3df2..ee8cdefe1 100644--- a/apps/desktop/src-tauri/src/export.rs+++ b/apps/desktop/src-tauri/src/export.rs@@ -1,14 +1,39 @@use crate::{- general_settings::GeneralSettingsStore, get_video_metadata, upsert_editor_instance,- windows::ShowCapWindow, AuthStore, RenderProgress, VideoRecordingMetadata, VideoType,+ create_editor_instance_impl, editor_window::WindowEditorInstance, get_video_metadata,+ windows::ShowCapWindow, AuthStore, RenderProgress, VideoType,};+use cap_editor::EditorInstance;use cap_project::{ProjectConfiguration, XY};-use std::path::PathBuf;+use std::{path::PathBuf, sync::Arc};use tauri::AppHandle;#[tauri::command]#[specta::specta]pub async fn export_video(+ editor_instance: WindowEditorInstance,+ app: AppHandle,+ video_id: String,+ project: ProjectConfiguration,+ progress: tauri::ipc::Channel<RenderProgress>,+ force: bool,+ fps: u32,+ resolution_base: XY<u32>,+) -> Result<PathBuf, String> {+ export_video_impl(+ editor_instance.0,+ app,+ video_id,+ project,+ progress,+ force,+ fps,+ resolution_base,+ )+ .await+}++pub async fn export_video_impl(+ editor_instance: Arc<EditorInstance>,app: AppHandle,video_id: String,project: ProjectConfiguration,@@ -45,7 +70,6 @@ pub async fn export_video(.unwrap_or(screen_metadata.duration),);- let editor_instance = upsert_editor_instance(&app, video_id.clone()).await?;let total_frames = editor_instance.get_total_frames(fps);let output_path = editor_instance.meta().output_path();@@ -137,8 +161,7 @@ pub async fn get_export_estimates(.await.ok();- let editor_instance = upsert_editor_instance(&app, video_id.clone()).await?;- let total_frames = editor_instance.get_total_frames(fps);+ let editor_instance = create_editor_instance_impl(&app, video_id).await?;let raw_duration = screen_metadata.duration.max(camera_metadatadiff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 91f3797f3..9fe569c17 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 editor_window;mod export;mod fake_window;mod tray;@@ -33,6 +34,8 @@ use cap_recording::RecordingOptions;use cap_rendering::ProjectRecordings;use clipboard_rs::common::RustImage;use clipboard_rs::{Clipboard, ClipboardContext};+use editor_window::EditorInstances;+use editor_window::WindowEditorInstance;use general_settings::{GeneralSettingsStore, RecordingConfig};use mp4::Mp4Reader;// use display::{list_capture_windows, Bounds, CaptureTarget, FPS};@@ -56,6 +59,7 @@ use std::{sync::Arc,time::Duration,};+use tauri::Window;use tauri::{AppHandle, Emitter, Manager, Runtime, State, WindowEvent};use tauri_plugin_deep_link::DeepLinkExt;use tauri_plugin_dialog::DialogExt;@@ -658,18 +662,6 @@ async fn create_thumbnail(input: PathBuf, output: PathBuf, size: (u32, u32)) ->.map_err(|e| format!("Task join error: {}", e))?}-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.meta().output_path();-- // If the file doesn't exist, return an error to trigger the progress-enabled path- if !output_path.exists() {- return Err("Rendered video does not exist".to_string());- }-- Ok(output_path)-}-#[tauri::command]#[specta::specta]async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(), String> {@@ -879,12 +871,11 @@ impl EditorStateChanged {#[specta::specta]async fn start_playback(app: AppHandle,- video_id: String,+ editor_instance: WindowEditorInstance,fps: u32,resolution_base: XY<u32>,) -> Result<(), String> {- upsert_editor_instance(&app, video_id)- .await?+ editor_instance.start_playback(fps,resolution_base,@@ -901,9 +892,7 @@ async fn start_playback(#[tauri::command]#[specta::specta]-async fn stop_playback(app: AppHandle, video_id: String) -> Result<(), String> {- let editor_instance = upsert_editor_instance(&app, video_id).await?;-+async fn stop_playback(editor_instance: WindowEditorInstance) -> Result<(), String> {let mut state = editor_instance.state.lock().await;if let Some(handle) = state.playback_task.take() {@@ -927,10 +916,11 @@ struct SerializedEditorInstance {#[tauri::command]#[specta::specta]async fn create_editor_instance(- app: AppHandle,+ window: Window,video_id: String,) -> Result<SerializedEditorInstance, String> {- let editor_instance = upsert_editor_instance(&app, video_id).await?;+ let editor_instance = create_editor_instance_impl(window.app_handle(), video_id).await?;+ EditorInstances::add(&window, editor_instance.clone());// Load the RecordingMeta to get the pretty namelet meta = RecordingMeta::load_for_project(&editor_instance.project_path)@@ -1104,12 +1094,9 @@ pub enum RenderProgress {#[tauri::command]#[specta::specta]async fn set_playhead_position(- app: AppHandle,- video_id: String,+ editor_instance: WindowEditorInstance,frame_number: u32,) -> Result<(), String> {- let editor_instance = upsert_editor_instance(&app, video_id).await?;-editor_instance.modify_and_emit_state(|state| {state.playhead_position = frame_number;@@ -1122,12 +1109,9 @@ async fn set_playhead_position(#[tauri::command]#[specta::specta]async fn set_project_config(- app: AppHandle,- video_id: String,+ editor_instance: WindowEditorInstance,config: ProjectConfiguration,) -> Result<(), String> {- let editor_instance = upsert_editor_instance(&app, video_id).await?;-config.write(&editor_instance.project_path).unwrap();editor_instance.project_config.0.send(config).ok();@@ -1870,9 +1854,7 @@ async fn is_camera_window_open(app: AppHandle) -> bool {#[tauri::command]#[specta::specta]-async fn seek_to(app: AppHandle, video_id: String, frame_number: u32) -> Result<(), String> {- let editor_instance = upsert_editor_instance(&app, video_id).await?;-+async fn seek_to(editor_instance: WindowEditorInstance, frame_number: u32) -> Result<(), String> {editor_instance.modify_and_emit_state(|state| {state.playhead_position = frame_number;@@ -2014,7 +1996,6 @@ pub async fn run() {global_message_dialog,show_window,write_clipboard_string,- get_editor_total_frames,platform::perform_haptic_feedback]).events(tauri_specta::collect_events![@@ -2266,12 +2247,8 @@ pub async fn run() {w.close().ok();}}- CapWindowId::Editor { project_id } => {- let app_handle = app.clone();- tokio::spawn(async move {- let _ = remove_editor_instance(&app_handle, project_id).await;- tokio::task::yield_now().await;- });+ CapWindowId::Editor { .. } => {+ EditorInstances::remove(window);}CapWindowId::Settings | CapWindowId::Upgrade => {// Don't quit the app when settings or upgrade window is closed@@ -2340,53 +2317,6 @@ pub async fn run() {});}-type EditorInstancesState = Arc<Mutex<HashMap<String, Arc<EditorInstance>>>>;--pub async fn remove_editor_instance(- app: &AppHandle<impl Runtime>,- video_id: String,-) -> Option<Arc<EditorInstance>> {- let map = match app.try_state::<EditorInstancesState>() {- Some(s) => (*s).clone(),- None => return None,- };-- let mut map = map.lock().await;-- if let Some(editor) = map.remove(&video_id) {- editor.dispose().await;- Some(editor)- } else {- None- }-}--pub async fn upsert_editor_instance(- app: &AppHandle,- video_id: String,-) -> Result<Arc<EditorInstance>, String> {- let map = match app.try_state::<EditorInstancesState>() {- Some(s) => (*s).clone(),- None => {- let map = Arc::new(Mutex::new(HashMap::new()));- app.manage(map.clone());- map- }- };-- let mut map = map.lock().await;-- use std::collections::hash_map::Entry;- Ok(match map.entry(video_id.clone()) {- Entry::Occupied(o) => o.get().clone(),- Entry::Vacant(v) => {- let instance = create_editor_instance_impl(app, video_id).await?;- v.insert(instance.clone());- instance- }- })-}-async fn create_editor_instance_impl(app: &AppHandle,video_id: String,@@ -2540,19 +2470,3 @@ trait EventExt: tauri_specta::Event {}impl<T: tauri_specta::Event> EventExt for T {}--#[tauri::command(async)]-#[specta::specta]-async fn get_editor_total_frames(- app: AppHandle,- video_id: String,- fps: u32,-) -> Result<u32, String> {- let editor_instances = app.state::<EditorInstancesState>();- let instances = editor_instances.lock().await;-- let instance = instances- .get(&video_id)- .ok_or_else(|| "Editor instance not found".to_string())?;- Ok(instance.get_total_frames(fps))-}diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex a4c00865d..c2315529f 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -3,10 +3,10 @@ use std::{sync::Arc, time::Instant};use crate::{audio::AppSounds,auth::AuthStore,- create_screenshot,- export::export_video,+ create_editor_instance_impl, create_screenshot,+ export::{export_video, export_video_impl},general_settings::GeneralSettingsStore,- list_recordings, notifications, open_editor, open_external_link, platform,+ notifications, open_editor, open_external_link,upload::get_s3_config,upload_exported_video, web_api,windows::{CapWindowId, ShowCapWindow},@@ -274,7 +274,9 @@ async fn handle_recording_finished(let max_retries = 3;let mut retry_count = 0;- export_video(+ let video_id = completed_recording.id.clone();+ export_video_impl(+ create_editor_instance_impl(&app, video_id).await.unwrap(),app.clone(),completed_recording.id.clone(),config,diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsxindex 424a4fcf0..4e230e5f9 100644--- a/apps/desktop/src/routes/editor/Player.tsx+++ b/apps/desktop/src/routes/editor/Player.tsx@@ -89,7 +89,7 @@ export function Player() {createEffect(() => {if (isAtEnd() && playing()) {- commands.stopPlayback(videoId);+ commands.stopPlayback();setPlaying(false);}});@@ -97,16 +97,16 @@ export function Player() {const handlePlayPauseClick = async () => {try {if (isAtEnd()) {- await commands.stopPlayback(videoId);+ await commands.stopPlayback();setPlaybackTime(0);- await commands.seekTo(videoId, 0);- await commands.startPlayback(videoId, FPS, OUTPUT_SIZE);+ await commands.seekTo(0);+ await commands.startPlayback(FPS, OUTPUT_SIZE);setPlaying(true);} else if (playing()) {- await commands.stopPlayback(videoId);+ await commands.stopPlayback();setPlaying(false);} else {- await commands.startPlayback(videoId, FPS, OUTPUT_SIZE);+ await commands.startPlayback(FPS, OUTPUT_SIZE);setPlaying(true);}} catch (error) {@@ -121,7 +121,7 @@ export function Player() {const time = previewTime();if (!playing() && time !== undefined) {setPlaybackTime(time);- await commands.seekTo(videoId, Math.floor(time * FPS));+ await commands.seekTo(Math.floor(time * FPS));}await handlePlayPauseClick();}@@ -250,8 +250,8 @@ export function Player() {type="button"onClick={async () => {setPlaying(false);- await commands.stopPlayback(videoId);- await commands.setPlayheadPosition(videoId, 0);+ await commands.stopPlayback();+ await commands.setPlayheadPosition(0);}}><IconCapFrameFirst class="size-[1.2rem]" />@@ -271,9 +271,8 @@ export function Player() {type="button"onClick={async () => {setPlaying(false);- await commands.stopPlayback(videoId);+ await commands.stopPlayback();await commands.setPlayheadPosition(- videoId,Math.floor(totalDuration() * FPS));}}diff --git a/apps/desktop/src/routes/editor/Timeline.tsx b/apps/desktop/src/routes/editor/Timeline.tsxindex 4595f2e82..c55b15d31 100644--- a/apps/desktop/src/routes/editor/Timeline.tsx+++ b/apps/desktop/src/routes/editor/Timeline.tsx@@ -56,7 +56,11 @@ export function Timeline() {const resume = history.pause();setProject("timeline", {segments: [- { timescale: 1, start: 0, end: duration(), recordingSegment: null },+ {+ timescale: 1,+ start: 0,+ end: duration(),+ },],});resume();@@ -66,9 +70,7 @@ export function Timeline() {const xPadding = 12;const segments = (): Array<TimelineSegment> =>- project.timeline?.segments ?? [- { start: 0, end: duration(), timescale: 1, recordingSegment: null },- ];+ project.timeline?.segments ?? [{ start: 0, end: duration(), timescale: 1 }];if (!project.timeline?.zoomSegments ||@@ -82,7 +84,6 @@ export function Timeline() {start: 0,end: duration(),timescale: 1,- recordingSegment: null,},],zoomSegments: [],@@ -100,7 +101,6 @@ export function Timeline() {const { left, width } = timelineBounds;if (zoomSegmentDragState.type !== "moving")commands.setPlayheadPosition(- videoId,Math.round(FPS *editorInstance.recordingDuration *diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.tsindex 42eb6ab12..02d3f3431 100644--- a/apps/desktop/src/routes/editor/context.ts+++ b/apps/desktop/src/routes/editor/context.ts@@ -66,7 +66,7 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(trackStore(project);},debounce(() => {- commands.setProjectConfig(editorInstanceContext.videoId, project);+ commands.setProjectConfig(project);}),{ defer: true })diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 84d27b61a..703b54e77 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -77,17 +77,17 @@ async getVideoMetadata(videoId: string, videoType: VideoType | null) : Promise<Vasync createEditorInstance(videoId: string) : Promise<SerializedEditorInstance> {return await TAURI_INVOKE("create_editor_instance", { videoId });},-async startPlayback(videoId: string, fps: number, resolutionBase: XY<number>) : Promise<null> {- return await TAURI_INVOKE("start_playback", { videoId, fps, resolutionBase });+async startPlayback(fps: number, resolutionBase: XY<number>) : Promise<null> {+ return await TAURI_INVOKE("start_playback", { fps, resolutionBase });},-async stopPlayback(videoId: string) : Promise<null> {- return await TAURI_INVOKE("stop_playback", { videoId });+async stopPlayback() : Promise<null> {+ return await TAURI_INVOKE("stop_playback");},-async setPlayheadPosition(videoId: string, frameNumber: number) : Promise<null> {- return await TAURI_INVOKE("set_playhead_position", { videoId, frameNumber });+async setPlayheadPosition(frameNumber: number) : Promise<null> {+ return await TAURI_INVOKE("set_playhead_position", { frameNumber });},-async setProjectConfig(videoId: string, config: ProjectConfiguration) : Promise<null> {- return await TAURI_INVOKE("set_project_config", { videoId, config });+async setProjectConfig(config: ProjectConfiguration) : Promise<null> {+ return await TAURI_INVOKE("set_project_config", { config });},async openEditor(id: string) : Promise<void> {await TAURI_INVOKE("open_editor", { id });@@ -143,8 +143,8 @@ async resetMicrophonePermissions() : Promise<null> {async isCameraWindowOpen() : Promise<boolean> {return await TAURI_INVOKE("is_camera_window_open");},-async seekTo(videoId: string, frameNumber: number) : Promise<null> {- return await TAURI_INVOKE("seek_to", { videoId, frameNumber });+async seekTo(frameNumber: number) : Promise<null> {+ return await TAURI_INVOKE("seek_to", { frameNumber });},async sendFeedbackRequest(feedback: string) : Promise<null> {return await TAURI_INVOKE("send_feedback_request", { feedback });@@ -164,9 +164,6 @@ async showWindow(window: ShowCapWindow) : Promise<void> {async writeClipboardString(text: string) : Promise<null> {return await TAURI_INVOKE("write_clipboard_string", { text });},-async getEditorTotalFrames(videoId: string, fps: number) : Promise<number> {- return await TAURI_INVOKE("get_editor_total_frames", { videoId, fps });-},async performHapticFeedback(pattern: HapticPattern | null, time: HapticPerformanceTime | null) : Promise<null> {return await TAURI_INVOKE("perform_haptic_feedback", { pattern, time });}diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rsindex fa360e7b4..1ffb24d96 100644--- a/crates/editor/src/editor_instance.rs+++ b/crates/editor/src/editor_instance.rs@@ -177,7 +177,7 @@ impl EditorInstance {}pub async fn start_playback(- self: Arc<Self>,+ self: &Arc<Self>,fps: u32,resolution_base: XY<u32>,is_upgraded: bool,@@ -204,6 +204,7 @@ impl EditorInstance {(playback_handle, prev)};+ let this = self.clone();tokio::spawn(async move {loop {let event = *handle.receive_event().await;@@ -211,7 +212,7 @@ impl EditorInstance {match event {playback::PlaybackEvent::Start => {}playback::PlaybackEvent::Frame(frame_number) => {- self.modify_and_emit_state(|state| {+ this.modify_and_emit_state(|state| {state.playhead_position = frame_number;}).await;