Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Refactor screenshot editor and add screenshots tab
Richie McIlroy11007c25e823
diff --git a/apps/desktop/src-tauri/src/frame_ws.rs b/apps/desktop/src-tauri/src/frame_ws.rsindex 1276f2108..69bb1bb6e 100644--- a/apps/desktop/src-tauri/src/frame_ws.rs+++ b/apps/desktop/src-tauri/src/frame_ws.rs@@ -1,8 +1,9 @@use std::sync::Arc;-use flume::Receiver;+use tokio::sync::watch;use tokio_util::sync::CancellationToken;+#[derive(Clone)]pub struct WSFrame {pub data: Vec<u8>,pub width: u32,@@ -10,7 +11,9 @@ pub struct WSFrame {pub stride: u32,}-pub async fn create_frame_ws(frame_rx: Receiver<WSFrame>) -> (u16, CancellationToken) {+pub async fn create_watch_frame_ws(+ frame_rx: watch::Receiver<Option<WSFrame>>,+) -> (u16, CancellationToken) {use axum::{extract::{State,@@ -19,9 +22,8 @@ pub async fn create_frame_ws(frame_rx: Receiver<WSFrame>) -> (u16, CancellationTresponse::IntoResponse,routing::get,};- use tokio::sync::Mutex;- type RouterState = Arc<Mutex<Receiver<WSFrame>>>;+ type RouterState = watch::Receiver<Option<WSFrame>>;#[axum::debug_handler]async fn ws_handler(@@ -31,17 +33,133 @@ pub async fn create_frame_ws(frame_rx: Receiver<WSFrame>) -> (u16, CancellationTws.on_upgrade(move |socket| handle_socket(socket, state))}- async fn handle_socket(mut socket: WebSocket, state: RouterState) {- let camera_rx = state.lock().await;+ async fn handle_socket(mut socket: WebSocket, mut camera_rx: RouterState) {+ println!("socket connection established");+ tracing::info!("Socket connection established");+ let now = std::time::Instant::now();++ // Send the current frame immediately upon connection (if one exists)+ // This ensures the client doesn't wait for the next config change to see the image+ {+ let frame_opt = camera_rx.borrow().clone();+ if let Some(mut frame) = frame_opt {+ frame.data.extend_from_slice(&frame.stride.to_le_bytes());+ frame.data.extend_from_slice(&frame.height.to_le_bytes());+ frame.data.extend_from_slice(&frame.width.to_le_bytes());++ if let Err(e) = socket.send(Message::Binary(frame.data)).await {+ tracing::error!("Failed to send initial frame to socket: {:?}", e);+ return;+ }+ }+ }++ loop {+ tokio::select! {+ msg = socket.recv() => {+ match msg {+ Some(Ok(Message::Close(_))) | None => {+ tracing::info!("WebSocket closed");+ break;+ }+ Some(Ok(_)) => {+ tracing::info!("Received message from socket (ignoring)");+ }+ Some(Err(e)) => {+ tracing::error!("WebSocket error: {:?}", e);+ break;+ }+ }+ },+ res = camera_rx.changed() => {+ if res.is_err() {+ tracing::error!("Camera channel closed");+ break;+ }+ let frame_opt = camera_rx.borrow().clone();+ if let Some(mut frame) = frame_opt {+ frame.data.extend_from_slice(&frame.stride.to_le_bytes());+ frame.data.extend_from_slice(&frame.height.to_le_bytes());+ frame.data.extend_from_slice(&frame.width.to_le_bytes());++ if let Err(e) = socket.send(Message::Binary(frame.data)).await {+ tracing::error!("Failed to send frame to socket: {:?}", e);+ break;+ }+ }+ }+ }+ }++ let elapsed = now.elapsed();+ println!("Websocket closing after {elapsed:.2?}");+ tracing::info!("Websocket closing after {elapsed:.2?}");+ }++ let router = axum::Router::new()+ .route("/", get(ws_handler))+ .with_state(frame_rx);++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ tracing::info!("WebSocket server listening on port {}", port);++ let cancel_token = CancellationToken::new();+ let cancel_token_child = cancel_token.child_token();+ tokio::spawn(async move {+ let server = axum::serve(listener, router.into_make_service());+ tokio::select! {+ _ = server => {},+ _ = cancel_token.cancelled() => {+ println!("WebSocket server shutting down");+ }+ }+ });++ (port, cancel_token_child)+}++pub async fn create_frame_ws(frame_rx: flume::Receiver<WSFrame>) -> (u16, CancellationToken) {+ use axum::{+ extract::{+ State,+ ws::{Message, WebSocket, WebSocketUpgrade},+ },+ response::IntoResponse,+ routing::get,+ };++ type RouterState = Arc<flume::Receiver<WSFrame>>;++ #[axum::debug_handler]+ async fn ws_handler(+ ws: WebSocketUpgrade,+ State(state): State<RouterState>,+ ) -> impl IntoResponse {+ ws.on_upgrade(move |socket| handle_socket(socket, state))+ }++ async fn handle_socket(mut socket: WebSocket, camera_rx: RouterState) {println!("socket connection established");tracing::info!("Socket connection established");let now = std::time::Instant::now();loop {tokio::select! {- _ = socket.recv() => {- tracing::info!("Received message from socket");- break;+ msg = socket.recv() => {+ match msg {+ Some(Ok(Message::Close(_))) | None => {+ tracing::info!("WebSocket closed");+ break;+ }+ Some(Ok(_)) => {+ tracing::info!("Received message from socket (ignoring)");+ }+ Some(Err(e)) => {+ tracing::error!("WebSocket error: {:?}", e);+ break;+ }+ }},incoming_frame = camera_rx.recv_async() => {match incoming_frame {@@ -74,7 +192,7 @@ pub async fn create_frame_ws(frame_rx: Receiver<WSFrame>) -> (u16, CancellationTlet router = axum::Router::new().route("/", get(ws_handler))- .with_state(Arc::new(Mutex::new(frame_rx)));+ .with_state(Arc::new(frame_rx));let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let port = listener.local_addr().unwrap().port();diff --git a/apps/desktop/src-tauri/src/screenshot_editor.rs b/apps/desktop/src-tauri/src/screenshot_editor.rsindex fcfea6787..2a77d4b5b 100644--- a/apps/desktop/src-tauri/src/screenshot_editor.rs+++ b/apps/desktop/src-tauri/src/screenshot_editor.rs@@ -1,18 +1,20 @@-use crate::frame_ws::{WSFrame, create_frame_ws};+use crate::frame_ws::{WSFrame, create_watch_frame_ws};+use crate::windows::{CapWindowId, ScreenshotEditorWindowIds};use cap_project::{- ProjectConfiguration, RecordingMeta, RecordingMetaInner, Resolution, SingleSegment,- StudioRecordingMeta, VideoMeta,+ ProjectConfiguration, RecordingMeta, RecordingMetaInner, SingleSegment, StudioRecordingMeta,+ VideoMeta,};use cap_rendering::{- DecodedFrame, DecodedSegmentFrames, FrameRenderer, ProjectUniforms, RenderSession,- RenderVideoConstants, RenderedFrame, RendererLayers,+ DecodedFrame, DecodedSegmentFrames, FrameRenderer, ProjectUniforms, RenderVideoConstants,+ RendererLayers,};use image::GenericImageView;use relative_path::RelativePathBuf;use serde::Serialize;use specta::Type;+use std::str::FromStr;use std::{collections::HashMap, ops::Deref, path::PathBuf, sync::Arc};-use tauri::{AppHandle, Manager, Runtime, Window, ipc::CommandArg};+use tauri::{Manager, Runtime, Window, ipc::CommandArg};use tokio::sync::{RwLock, watch};use tokio_util::sync::CancellationToken;@@ -81,8 +83,8 @@ impl ScreenshotEditorInstances {match instances.entry(window.label().to_string()) {Entry::Vacant(entry) => {- let (frame_tx, frame_rx) = flume::bounded(4);- let (ws_port, ws_shutdown_token) = create_frame_ws(frame_rx).await;+ let (frame_tx, frame_rx) = watch::channel(None);+ let (ws_port, ws_shutdown_token) = create_watch_frame_ws(frame_rx).await;// Load imagelet img = image::open(&path).map_err(|e| format!("Failed to open image: {e}"))?;@@ -90,27 +92,48 @@ impl ScreenshotEditorInstances {let img_rgba = img.to_rgba8();let data = img_rgba.into_raw();- // Create dummy meta- let relative_path = RelativePathBuf::from_path(&path).unwrap();- let video_meta = VideoMeta {- path: relative_path.clone(),- fps: 30,- start_time: Some(0.0),- };- let segment = SingleSegment {- display: video_meta.clone(),- camera: None,- audio: None,- cursor: None,+ // Try to load existing meta if in a .cap directory+ let (recording_meta, loaded_config) = if let Some(parent) = path.parent() {+ if parent.extension().and_then(|s| s.to_str()) == Some("cap") {+ let meta = RecordingMeta::load_for_project(parent).ok();+ let config = ProjectConfiguration::load(parent).ok();+ (meta, config)+ } else {+ (None, None)+ }+ } else {+ (None, None)};- let studio_meta = StudioRecordingMeta::SingleSegment { segment };- let recording_meta = RecordingMeta {- platform: None,- project_path: path.parent().unwrap().to_path_buf(),- pretty_name: "Screenshot".to_string(),- sharing: None,- inner: RecordingMetaInner::Studio(studio_meta.clone()),- upload: None,++ let recording_meta = if let Some(meta) = recording_meta {+ meta+ } else {+ // Create dummy meta+ let filename = path+ .file_name()+ .ok_or_else(|| "Invalid path".to_string())?+ .to_string_lossy();+ let relative_path = RelativePathBuf::from(filename.as_ref());+ let video_meta = VideoMeta {+ path: relative_path.clone(),+ fps: 30,+ start_time: Some(0.0),+ };+ let segment = SingleSegment {+ display: video_meta.clone(),+ camera: None,+ audio: None,+ cursor: None,+ };+ let studio_meta = StudioRecordingMeta::SingleSegment { segment };+ RecordingMeta {+ platform: None,+ project_path: path.parent().unwrap().to_path_buf(),+ pretty_name: "Screenshot".to_string(),+ sharing: None,+ inner: RecordingMetaInner::Studio(studio_meta.clone()),+ upload: None,+ }};let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());@@ -137,6 +160,12 @@ impl ScreenshotEditorInstances {camera_size: None,};+ // We need to extract the studio meta from the recording meta+ let studio_meta = match &recording_meta.inner {+ RecordingMetaInner::Studio(meta) => meta.clone(),+ _ => return Err("Invalid recording meta for screenshot".to_string()),+ };+let constants = RenderVideoConstants {_instance: instance,_adapter: adapter,@@ -148,7 +177,7 @@ impl ScreenshotEditorInstances {background_textures: Arc::new(tokio::sync::RwLock::new(HashMap::new())),};- let (config_tx, mut config_rx) = watch::channel(ProjectConfiguration::default());+ let (config_tx, mut config_rx) = watch::channel(loaded_config.unwrap_or_default());let instance = Arc::new(ScreenshotEditorInstance {ws_port,@@ -158,7 +187,6 @@ impl ScreenshotEditorInstances {});// Spawn render loop- let frame_tx = frame_tx.clone();let decoded_frame = DecodedFrame::new(data, width, height);tokio::spawn(async move {@@ -166,15 +194,14 @@ impl ScreenshotEditorInstances {let mut layers = RendererLayers::new(&constants.device, &constants.queue);// Initial render+ println!("Initial screenshot render");let mut current_config = config_rx.borrow().clone();loop {- // Wait for config change- if config_rx.changed().await.is_err() {- break;- }- current_config = config_rx.borrow().clone();-+ println!(+ "Rendering screenshot frame with config: {:?}",+ current_config+ );let segment_frames = DecodedSegmentFrames {screen_frame: DecodedFrame::new(decoded_frame.data().to_vec(),@@ -207,24 +234,55 @@ impl ScreenshotEditorInstances {match rendered_frame {Ok(frame) => {- let _ = frame_tx.send(WSFrame {+ println!(+ "Frame rendered successfully: {}x{}",+ frame.width, frame.height+ );+ let _ = frame_tx.send(Some(WSFrame {data: frame.data,width: frame.width,height: frame.height,stride: frame.padded_bytes_per_row,- });+ }));}Err(e) => {eprintln!("Failed to render frame: {e}");}}++ // Wait for config change+ println!("Waiting for config change");+ if config_rx.changed().await.is_err() {+ println!("Config channel closed");+ break;+ }+ current_config = config_rx.borrow().clone();+ println!("Config changed");}});entry.insert(instance.clone());Ok(instance)}- Entry::Occupied(entry) => Ok(entry.get().clone()),+ Entry::Occupied(entry) => {+ let instance = entry.get().clone();+ // Force a re-render for the new client by sending the current config again+ let config = instance.config_tx.borrow().clone();+ let _ = instance.config_tx.send(config);+ Ok(instance)+ }+ }+ }++ pub async fn remove(window: Window) {+ let instances = match window.try_state::<ScreenshotEditorInstances>() {+ Some(s) => (*s).clone(),+ None => return,+ };++ let mut instances = instances.0.write().await;+ if let Some(instance) = instances.remove(window.label()) {+ instance.dispose().await;}}}@@ -234,19 +292,36 @@ impl ScreenshotEditorInstances {pub struct SerializedScreenshotEditorInstance {pub frames_socket_url: String,pub path: PathBuf,+ pub config: Option<ProjectConfiguration>,}#[tauri::command]#[specta::specta]pub async fn create_screenshot_editor_instance(window: Window,- path: PathBuf,) -> Result<SerializedScreenshotEditorInstance, String> {+ let CapWindowId::ScreenshotEditor { id } =+ CapWindowId::from_str(window.label()).map_err(|e| e.to_string())?+ else {+ return Err("Invalid window".to_string());+ };++ let path = {+ let window_ids = ScreenshotEditorWindowIds::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("Screenshot editor instance not found".to_string());+ };+ path.clone()+ };+let instance = ScreenshotEditorInstances::get_or_create(&window, path).await?;+ let config = instance.config_tx.borrow().clone();Ok(SerializedScreenshotEditorInstance {frames_socket_url: format!("ws://localhost:{}", instance.ws_port),path: instance.path.clone(),+ config: Some(config),})}@@ -255,7 +330,26 @@ pub async fn create_screenshot_editor_instance(pub async fn update_screenshot_config(instance: WindowScreenshotEditorInstance,config: ProjectConfiguration,+ save: bool,) -> Result<(), String> {- let _ = instance.config_tx.send(config);+ let _ = instance.config_tx.send(config.clone());++ if save {+ if let Some(parent) = instance.path.parent() {+ if parent.extension().and_then(|s| s.to_str()) == Some("cap") {+ let path = parent.to_path_buf();+ if let Err(e) = config.write(&path) {+ eprintln!("Failed to save screenshot config: {}", e);+ } else {+ println!("Saved screenshot config to {:?}", path);+ }+ } else {+ println!(+ "Not saving config: parent {:?} is not a .cap directory",+ parent+ );+ }+ }+ }Ok(())}diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex 1ea90ff01..37cc8f10b 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -49,7 +49,7 @@ pub enum CapWindowId {Upgrade,ModeSelect,Debug,- ScreenshotEditor,+ ScreenshotEditor { id: u32 },}impl FromStr for CapWindowId {@@ -68,13 +68,18 @@ impl FromStr for CapWindowId {"upgrade" => Self::Upgrade,"mode-select" => Self::ModeSelect,"debug" => Self::Debug,- "screenshot-editor" => Self::ScreenshotEditor,s if s.starts_with("editor-") => Self::Editor {id: s.replace("editor-", "").parse::<u32>().map_err(|e| e.to_string())?,},+ s if s.starts_with("screenshot-editor-") => Self::ScreenshotEditor {+ id: s+ .replace("screenshot-editor-", "")+ .parse::<u32>()+ .map_err(|e| e.to_string())?,+ },s if s.starts_with("window-capture-occluder-") => Self::WindowCaptureOccluder {screen_id: s.replace("window-capture-occluder-", "")@@ -112,7 +117,7 @@ impl std::fmt::Display for CapWindowId {Self::ModeSelect => write!(f, "mode-select"),Self::Editor { id } => write!(f, "editor-{id}"),Self::Debug => write!(f, "debug"),- Self::ScreenshotEditor => write!(f, "screenshot-editor"),+ Self::ScreenshotEditor { id } => write!(f, "screenshot-editor-{id}"),}}}@@ -130,7 +135,7 @@ impl CapWindowId {Self::CaptureArea => "Cap Capture Area".to_string(),Self::RecordingControls => "Cap Recording Controls".to_string(),Self::Editor { .. } => "Cap Editor".to_string(),- Self::ScreenshotEditor => "Cap Screenshot Editor".to_string(),+ Self::ScreenshotEditor { .. } => "Cap Screenshot Editor".to_string(),Self::ModeSelect => "Cap Mode Selection".to_string(),Self::Camera => "Cap Camera".to_string(),Self::RecordingsOverlay => "Cap Recordings Overlay".to_string(),@@ -144,7 +149,7 @@ impl CapWindowId {Self::Setup| Self::Main| Self::Editor { .. }- | Self::ScreenshotEditor+ | Self::ScreenshotEditor { .. }| Self::Settings| Self::Upgrade| Self::ModeSelect@@ -159,7 +164,7 @@ impl CapWindowId {#[cfg(target_os = "macos")]pub fn traffic_lights_position(&self) -> Option<Option<LogicalPosition<f64>>> {match self {- Self::Editor { .. } | Self::ScreenshotEditor => {+ Self::Editor { .. } | Self::ScreenshotEditor { .. } => {Some(Some(LogicalPosition::new(20.0, 32.0)))}Self::RecordingControls => Some(Some(LogicalPosition::new(-100.0, -100.0))),@@ -177,7 +182,7 @@ impl CapWindowId {Self::Setup => (600.0, 600.0),Self::Main => (300.0, 360.0),Self::Editor { .. } => (1275.0, 800.0),- Self::ScreenshotEditor => (800.0, 600.0),+ Self::ScreenshotEditor { .. } => (800.0, 600.0),Self::Settings => (600.0, 450.0),Self::Camera => (200.0, 200.0),Self::Upgrade => (950.0, 850.0),@@ -235,6 +240,19 @@ impl ShowCapWindow {}}+ if let Self::ScreenshotEditor { path } = &self {+ let state = app.state::<ScreenshotEditorWindowIds>();+ let mut s = state.ids.lock().unwrap();+ if !s.iter().any(|(p, _)| p == path) {+ s.push((+ path.clone(),+ state+ .counter+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst),+ ));+ }+ }+if let Some(window) = self.id(app).get(app) {window.show().ok();window.unminimize().ok();@@ -425,7 +443,7 @@ impl ShowCapWindow {.center().build()?}- Self::ScreenshotEditor { path } => {+ Self::ScreenshotEditor { path: _ } => {if let Some(main) = CapWindowId::Main.get(app) {let _ = main.close();};@@ -434,10 +452,6 @@ impl ShowCapWindow {.maximizable(true).inner_size(1240.0, 800.0).center()- .initialization_script(format!(- "window.__CAP__ = window.__CAP__ ?? {{}}; window.__CAP__.screenshotPath = {:?};",- path- )).build()?}Self::Upgrade => {@@ -829,7 +843,12 @@ impl ShowCapWindow {ShowCapWindow::InProgressRecording { .. } => CapWindowId::RecordingControls,ShowCapWindow::Upgrade => CapWindowId::Upgrade,ShowCapWindow::ModeSelect => CapWindowId::ModeSelect,- ShowCapWindow::ScreenshotEditor { .. } => CapWindowId::ScreenshotEditor,+ ShowCapWindow::ScreenshotEditor { path } => {+ let state = app.state::<ScreenshotEditorWindowIds>();+ let s = state.ids.lock().unwrap();+ let id = s.iter().find(|(p, _)| p == path).unwrap().1;+ CapWindowId::ScreenshotEditor { id }+ }}}}@@ -1035,3 +1054,15 @@ impl EditorWindowIds {app.state::<EditorWindowIds>().deref().clone()}}++#[derive(Default, Clone)]+pub struct ScreenshotEditorWindowIds {+ pub ids: Arc<Mutex<Vec<(PathBuf, u32)>>>,+ pub counter: Arc<AtomicU32>,+}++impl ScreenshotEditorWindowIds {+ pub fn get(app: &AppHandle) -> Self {+ app.state::<ScreenshotEditorWindowIds>().deref().clone()+ }+}diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsxindex 23e41f6f2..c1e51068b 100644--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx@@ -278,7 +278,7 @@ function Page() {<IconCapSettings class="text-gray-11 size-5 hover:text-gray-12" /></button></Tooltip>- <Tooltip content={<span>Previous Recordings</span>}>+ <Tooltip content={<span>Recordings</span>}><buttontype="button"onClick={async () => {diff --git a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsxindex 82c008f32..668f5afd5 100644--- a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx+++ b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx@@ -58,6 +58,7 @@ import {} from "~/utils/tauri";import IconLucideAppWindowMac from "~icons/lucide/app-window-mac";import IconLucideArrowLeft from "~icons/lucide/arrow-left";+import IconLucideImage from "~icons/lucide/image";import IconLucideSearch from "~icons/lucide/search";import IconMaterialSymbolsScreenshotFrame2Rounded from "~icons/material-symbols/screenshot-frame-2-rounded";import IconMdiMonitor from "~icons/mdi/monitor";@@ -801,7 +802,7 @@ function Page() {<IconCapSettings class="transition-colors text-gray-11 size-4 hover:text-gray-12" /></button></Tooltip>- <Tooltip content={<span>Previous Recordings</span>}>+ <Tooltip content={<span>Recordings</span>}><buttontype="button"onClick={async () => {@@ -815,6 +816,20 @@ function Page() {<IconLucideSquarePlay class="transition-colors text-gray-11 size-4 hover:text-gray-12" /></button></Tooltip>+ <Tooltip content={<span>Screenshots</span>}>+ <button+ type="button"+ onClick={async () => {+ await commands.showWindow({+ Settings: { page: "screenshots" },+ });+ getCurrentWindow().hide();+ }}+ class="flex justify-center items-center size-5"+ >+ <IconLucideImage class="transition-colors text-gray-11 size-4 hover:text-gray-12" />+ </button>+ </Tooltip><ChangelogButton />{import.meta.env.DEV && (<buttondiff --git a/apps/desktop/src/routes/(window-chrome)/settings.tsx b/apps/desktop/src/routes/(window-chrome)/settings.tsxindex 0dfb55e17..7130fd503 100644--- a/apps/desktop/src/routes/(window-chrome)/settings.tsx+++ b/apps/desktop/src/routes/(window-chrome)/settings.tsx@@ -38,9 +38,14 @@ export default function Settings(props: RouteSectionProps) {},{href: "recordings",- name: "Previous Recordings",+ name: "Recordings",icon: IconLucideSquarePlay,},+ {+ href: "screenshots",+ name: "Screenshots",+ icon: IconLucideImage,+ },{href: "integrations",name: "Integrations",diff --git a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsxindex 75f24dff3..5713e85cf 100644--- a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx+++ b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx@@ -138,7 +138,7 @@ export default function Recordings() {return (<div class="flex relative flex-col p-4 space-y-4 w-full h-full"><div class="flex flex-col">- <h2 class="text-lg font-medium text-gray-12">Previous Recordings</h2>+ <h2 class="text-lg font-medium text-gray-12">Recordings</h2><p class="text-sm text-gray-10">Manage your recordings and perform actions.</p>diff --git a/apps/desktop/src/routes/(window-chrome)/settings/screenshots.tsx b/apps/desktop/src/routes/(window-chrome)/settings/screenshots.tsxindex cb788f88e..998fdb22e 100644--- a/apps/desktop/src/routes/(window-chrome)/settings/screenshots.tsx+++ b/apps/desktop/src/routes/(window-chrome)/settings/screenshots.tsx@@ -1,95 +1,197 @@-import { createQuery } from "@tanstack/solid-query";+import Tooltip from "@corvu/tooltip";+import {+ createQuery,+ queryOptions,+ useQueryClient,+} from "@tanstack/solid-query";import { convertFileSrc } from "@tauri-apps/api/core";-import { createSignal, For, Show } from "solid-js";-import { commands, events } from "~/utils/tauri";-import IconLucideEye from "~icons/lucide/eye";+import { ask } from "@tauri-apps/plugin-dialog";+import { remove } from "@tauri-apps/plugin-fs";+import { cx } from "cva";+import {+ createMemo,+ createSignal,+ For,+ type JSX,+ type ParentProps,+ Show,+} from "solid-js";+import { reconcile } from "solid-js/store";+import { trackEvent } from "~/utils/analytics";+import { createTauriEventListener } from "~/utils/createEventListener";+import { commands, events, type RecordingMeta } from "~/utils/tauri";++// Icons+import IconCapTrash from "~icons/cap/trash";+import IconLucideCopy from "~icons/lucide/copy";+import IconLucideEdit from "~icons/lucide/edit";import IconLucideFolder from "~icons/lucide/folder";-type MediaEntry = {- path: string;+type Screenshot = {+ meta: RecordingMeta;+ path: string; // png pathprettyName: string;- isNew: boolean;thumbnailPath: string;};+const Tabs: { id: string; label: string; icon?: JSX.Element }[] = [+ {+ id: "all",+ label: "Show all",+ },+];++const screenshotsQuery = queryOptions({+ queryKey: ["screenshots"],+ queryFn: async () => {+ const result = await commands.listScreenshots().catch(() => [] as const);++ const screenshots = await Promise.all(+ result.map(async (file) => {+ const [path, meta] = file;+ // path is the png path.+ // thumbnail is the same as path for screenshots.++ return {+ meta,+ path,+ prettyName: meta.pretty_name,+ thumbnailPath: path,+ };+ }),+ );+ return screenshots;+ },+ reconcile: (old, n) => reconcile(n)(old),+ refetchInterval: 2000,+});+export default function Screenshots() {- const fetchScreenshots = createQuery(() => ({- queryKey: ["screenshots"],- queryFn: async () => {- const result = await commands- .listScreenshots()- .catch(- () =>- Promise.resolve([]) as ReturnType<typeof commands.listScreenshots>,- );- const screenshots = await Promise.all(- result.map(async (file) => {- const [pngPath, meta] = file;-- return {- path: pngPath,- prettyName: meta.pretty_name,- isNew: false,- thumbnailPath: pngPath,- };- }),- );- return screenshots;- },- }));-- const handleScreenshotClick = (screenshot: MediaEntry) => {- events.newScreenshotAdded.emit({ path: screenshot.path });+ const [activeTab, setActiveTab] = createSignal<(typeof Tabs)[number]["id"]>(+ Tabs[0].id,+ );++ const screenshots = createQuery(() => screenshotsQuery);++ createTauriEventListener(events.newScreenshotAdded, () =>+ screenshots.refetch(),+ );++ const filteredScreenshots = createMemo(() => {+ if (!screenshots.data) {+ return [];+ }+ return screenshots.data;+ });++ const handleScreenshotClick = (screenshot: Screenshot) => {+ trackEvent("screenshot_view_clicked");+ // events.newScreenshotAdded.emit({ path: screenshot.path });+ commands.showWindow({+ ScreenshotEditor: {+ path: screenshot.path,+ },+ });+ };++ const handleOpenEditor = (path: string) => {+ trackEvent("screenshot_editor_clicked");+ commands.showWindow({+ ScreenshotEditor: {+ path,+ },+ });};const handleOpenFolder = (path: string) => {+ trackEvent("screenshot_folder_clicked");commands.openFilePath(path);};+ const handleCopyImageToClipboard = (path: string) => {+ trackEvent("screenshot_copy_clicked");+ commands.copyScreenshotToClipboard(path);+ };+return (- <div class="flex flex-col pt-1 pb-12 w-full h-full divide-y divide-gray-200">- <div class="overflow-y-auto relative flex-1">- <ul class="p-[0.625rem] flex flex-col gap-[0.5rem] w-full">- <Show- when={fetchScreenshots.data && fetchScreenshots.data.length > 0}- fallback={- <p class="text-center text-[--text-tertiary] absolute flex items-center justify-center w-full h-full">- No screenshots found- </p>- }- >- <For each={fetchScreenshots.data}>+ <div class="flex relative flex-col p-4 space-y-4 w-full h-full">+ <div class="flex flex-col">+ <h2 class="text-lg font-medium text-gray-12">Screenshots</h2>+ <p class="text-sm text-gray-10">+ Manage your screenshots and perform actions.+ </p>+ </div>+ <Show+ when={screenshots.data && screenshots.data.length > 0}+ fallback={+ <p class="text-center text-[--text-tertiary] absolute flex items-center justify-center w-full h-full">+ No screenshots found+ </p>+ }+ >+ <div class="flex gap-3 items-center pb-4 w-full border-b border-gray-2">+ <For each={Tabs}>+ {(tab) => (+ <div+ class={cx(+ "flex gap-1.5 items-center transition-colors duration-200 p-2 px-3 border rounded-full",+ activeTab() === tab.id+ ? "bg-gray-5 cursor-default border-gray-5"+ : "bg-transparent cursor-pointer hover:bg-gray-3 border-gray-5",+ )}+ onClick={() => setActiveTab(tab.id)}+ >+ {tab.icon && tab.icon}+ <p class="text-xs text-gray-12">{tab.label}</p>+ </div>+ )}+ </For>+ </div>++ <div class="flex relative flex-col flex-1 mt-4 rounded-xl border custom-scroll bg-gray-2 border-gray-3">+ <ul class="flex flex-col w-full text-[--text-primary]">+ <For each={filteredScreenshots()}>{(screenshot) => (<ScreenshotItemscreenshot={screenshot}onClick={() => handleScreenshotClick(screenshot)}+ onOpenEditor={() => handleOpenEditor(screenshot.path)}onOpenFolder={() => handleOpenFolder(screenshot.path)}+ onCopyImageToClipboard={() =>+ handleCopyImageToClipboard(screenshot.path)+ }/>)}</For>- </Show>- </ul>- </div>+ </ul>+ </div>+ </Show></div>);}function ScreenshotItem(props: {- screenshot: MediaEntry;+ screenshot: Screenshot;onClick: () => void;+ onOpenEditor: () => void;onOpenFolder: () => void;+ onCopyImageToClipboard: () => void;}) {const [imageExists, setImageExists] = createSignal(true);+ const queryClient = useQueryClient();return (- <li class="flex flex-row justify-between items-center p-2 w-full rounded hover:bg-gray-2 dark:hover:bg-gray-3">- <div class="flex items-center">+ <li+ onClick={props.onClick}+ class="flex flex-row justify-between p-3 [&:not(:last-child)]:border-b [&:not(:last-child)]:border-gray-3 items-center w-full cursor-pointer hover:bg-gray-3 transition-colors duration-200"+ >+ <div class="flex gap-5 items-center"><Showwhen={imageExists()}- fallback={<div class="mr-4 w-8 h-8 bg-gray-10 rounded" />}+ fallback={<div class="mr-4 rounded bg-gray-10 size-11" />}><img- class="object-cover mr-4 w-8 h-8 rounded"+ class="object-cover rounded size-12"alt="Screenshot thumbnail"src={`${convertFileSrc(props.screenshot.thumbnailPath,@@ -97,32 +199,77 @@ function ScreenshotItem(props: {onError={() => setImageExists(false)}/></Show>- <span class="text-[--text-primary]">- {props.screenshot.prettyName.replace(".png", "")}- </span>+ <div class="flex flex-col gap-2">+ <span>{props.screenshot.prettyName}</span>+ </div></div>- <div class="flex items-center">- <button- type="button"- onClick={(e) => {- e.stopPropagation();- props.onOpenFolder();- }}- class="p-2 hover:bg-gray-3 dark:hover:bg-gray-5 text-[--text-tertiary] hover:text-[--text-primary] rounded-full mr-2"+ <div class="flex gap-2 items-center">+ <TooltipIconButton+ tooltipText="Open folder"+ onClick={props.onOpenFolder}+ >+ <IconLucideFolder class="size-4" />+ </TooltipIconButton>++ <TooltipIconButton+ tooltipText="Open in editor"+ onClick={props.onOpenEditor}+ >+ <IconLucideEdit class="size-4" />+ </TooltipIconButton>++ <TooltipIconButton+ tooltipText="Copy image"+ onClick={props.onCopyImageToClipboard}>- <IconLucideFolder class="size-5" />- </button>- <button- type="button"- onClick={(e) => {- e.stopPropagation();- props.onClick();+ <IconLucideCopy class="size-4" />+ </TooltipIconButton>++ <TooltipIconButton+ tooltipText="Delete"+ onClick={async () => {+ if (+ !(await ask("Are you sure you want to delete this screenshot?"))+ )+ return;+ // screenshot.path is the png file. Parent is the .cap folder.+ const parent = props.screenshot.path.replace(/[/\\][^/\\]+$/, "");+ await remove(parent, { recursive: true });++ queryClient.invalidateQueries({ queryKey: ["screenshots"] });}}- class="p-2 hover:bg-gray-3 dark:hover:bg-gray-5 text-[--text-tertiary] hover:text-[--text-primary] rounded-full">- <IconLucideEye class="size-5" />- </button>+ <IconCapTrash class="size-4" />+ </TooltipIconButton></div></li>);}++function TooltipIconButton(+ props: ParentProps<{+ onClick: () => void;+ tooltipText: string;+ disabled?: boolean;+ }>,+) {+ return (+ <Tooltip>+ <Tooltip.Trigger+ onClick={(e: MouseEvent) => {+ e.stopPropagation();+ props.onClick();+ }}+ disabled={props.disabled}+ class="p-2.5 opacity-70 will-change-transform hover:opacity-100 rounded-full transition-all duration-200 hover:bg-gray-3 dark:hover:bg-gray-5 disabled:pointer-events-none disabled:opacity-45 disabled:hover:opacity-45"+ >+ {props.children}+ </Tooltip.Trigger>+ <Tooltip.Portal>+ <Tooltip.Content class="py-2 px-3 font-medium bg-gray-2 text-gray-12 border border-gray-3 text-xs rounded-lg animate-in fade-in slide-in-from-top-0.5">+ {props.tooltipText}+ </Tooltip.Content>+ </Tooltip.Portal>+ </Tooltip>+ );+}diff --git a/apps/desktop/src/routes/screenshot-editor/ConfigSidebar.tsx b/apps/desktop/src/routes/screenshot-editor/ConfigSidebar.tsxindex 536fbe7a0..f73625076 100644--- a/apps/desktop/src/routes/screenshot-editor/ConfigSidebar.tsx+++ b/apps/desktop/src/routes/screenshot-editor/ConfigSidebar.tsx@@ -318,8 +318,18 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) {};const ensurePaddingForBackground = () => {- if (project.background.padding === 0)- setProject("background", "padding", 10);+ batch(() => {+ const isPaddingZero = project.background.padding === 0;+ const isRoundingZero = project.background.rounding === 0;++ if (isPaddingZero) {+ setProject("background", "padding", 10);+ }++ if (isPaddingZero && isRoundingZero) {+ setProject("background", "rounding", 8);+ }+ });};return (diff --git a/apps/desktop/src/routes/screenshot-editor/Preview.tsx b/apps/desktop/src/routes/screenshot-editor/Preview.tsxindex d161d5284..988548c40 100644--- a/apps/desktop/src/routes/screenshot-editor/Preview.tsx+++ b/apps/desktop/src/routes/screenshot-editor/Preview.tsx@@ -1,3 +1,4 @@+import { createElementBounds } from "@solid-primitives/bounds";import { convertFileSrc } from "@tauri-apps/api/core";import { cx } from "cva";import { createEffect, createMemo, createSignal, Show } from "solid-js";@@ -9,12 +10,28 @@ import { EditorButton, Slider } from "../editor/ui";import AspectRatioSelect from "./AspectRatioSelect";import { useScreenshotEditorContext } from "./context";+// CSS for checkerboard grid (adaptive to light/dark mode)+const gridStyle = {+ "background-image":+ "linear-gradient(45deg, rgba(128,128,128,0.12) 25%, transparent 25%), " ++ "linear-gradient(-45deg, rgba(128,128,128,0.12) 25%, transparent 25%), " ++ "linear-gradient(45deg, transparent 75%, rgba(128,128,128,0.12) 75%), " ++ "linear-gradient(-45deg, transparent 75%, rgba(128,128,128,0.12) 75%)",+ "background-size": "40px 40px",+ "background-position": "0 0, 0 20px, 20px -20px, -20px 0px",+ "background-color": "rgba(200,200,200,0.08)",+};+export function Preview() {const { path, project, setDialog, latestFrame } =useScreenshotEditorContext();const [zoom, setZoom] = createSignal(1);let canvasRef: HTMLCanvasElement | undefined;+ const [canvasContainerRef, setCanvasContainerRef] =+ createSignal<HTMLDivElement>();+ const containerBounds = createElementBounds(canvasContainerRef);+createEffect(() => {const frame = latestFrame();if (frame && canvasRef) {@@ -59,27 +76,82 @@ export function Preview() {</div>{/* Preview Area */}- <div class="flex-1 relative flex items-center justify-center bg-[--bg-subtle] overflow-hidden">- <div- class="relative shadow-2xl transition-transform duration-200 ease-out"- style={{- transform: `scale(${zoom()})`,- }}+ <div+ ref={setCanvasContainerRef}+ class="flex-1 relative flex items-center justify-center bg-[--bg-subtle] overflow-hidden"+ >+ <Show+ when={!!latestFrame()}+ fallback={<div class="text-gray-11">Loading preview...</div>}>- <Show- when={latestFrame()}- fallback={<div class="text-gray-11">Loading preview...</div>}- >- {(frame) => (- <canvas- ref={canvasRef}- width={frame().width}- height={frame().height}- class="max-w-full max-h-[80vh] block"- />- )}- </Show>- </div>+ {(_) => {+ const padding = 20;+ const frame = () => {+ const f = latestFrame();+ if (!f)+ return {+ width: 0,+ data: { width: 0, height: 0 } as ImageData,+ };+ return f;+ };++ const frameWidth = () => frame().width;+ const frameHeight = () => frame().data.height;++ const availableWidth = () =>+ Math.max((containerBounds.width ?? 0) - padding * 2, 0);+ const availableHeight = () =>+ Math.max((containerBounds.height ?? 0) - padding * 2, 0);++ const containerAspect = () => {+ const width = availableWidth();+ const height = availableHeight();+ if (width === 0 || height === 0) return 1;+ return width / height;+ };++ const frameAspect = () => {+ const width = frameWidth();+ const height = frameHeight();+ if (width === 0 || height === 0) return containerAspect();+ return width / height;+ };++ const size = () => {+ let width: number;+ let height: number;+ if (frameAspect() < containerAspect()) {+ height = availableHeight();+ width = height * frameAspect();+ } else {+ width = availableWidth();+ height = width / frameAspect();+ }++ return {+ width: Math.min(width, frameWidth()),+ height: Math.min(height, frameHeight()),+ };+ };++ return (+ <div class="flex overflow-hidden absolute inset-0 justify-center items-center h-full">+ <canvas+ ref={canvasRef}+ width={frameWidth()}+ height={frameHeight()}+ style={{+ width: `${size().width * zoom()}px`,+ height: `${size().height * zoom()}px`,+ ...gridStyle,+ }}+ class="rounded shadow-lg transition-all duration-200 ease-out"+ />+ </div>+ );+ }}+ </Show></div>{/* Bottom Toolbar (Zoom) */}diff --git a/apps/desktop/src/routes/screenshot-editor/context.tsx b/apps/desktop/src/routes/screenshot-editor/context.tsxindex b7d2eaf7a..55f160619 100644--- a/apps/desktop/src/routes/screenshot-editor/context.tsx+++ b/apps/desktop/src/routes/screenshot-editor/context.tsx@@ -1,27 +1,23 @@import { createContextProvider } from "@solid-primitives/context";import { trackStore } from "@solid-primitives/deep";+import { debounce } from "@solid-primitives/scheduled";import { createEffect, createResource, createSignal, on } from "solid-js";-import { createStore } from "solid-js/store";+import { createStore, reconcile, unwrap } from "solid-js/store";import { createImageDataWS, createLazySignal } from "~/utils/socket";import {type AspectRatio,+ type AudioConfiguration,type BackgroundConfiguration,+ type Camera,+ type CameraPosition,+ type CursorConfiguration,commands,+ type HotkeysConfiguration,+ type ProjectConfiguration,type XY,} from "~/utils/tauri";-import {- normalizeProject,- serializeProjectConfiguration,-} from "../editor/context";-import {- DEFAULT_GRADIENT_FROM,- DEFAULT_GRADIENT_TO,-} from "../editor/projectConfig";-export type ScreenshotProject = {- background: BackgroundConfiguration;- aspectRatio: AspectRatio | null;-};+export type ScreenshotProject = ProjectConfiguration;export type CurrentDialog =| { type: "createPreset" }@@ -32,6 +28,46 @@ export type CurrentDialog =export type DialogState = { open: false } | ({ open: boolean } & CurrentDialog);+const DEFAULT_CAMERA: Camera = {+ hide: false,+ mirror: false,+ position: { x: "right", y: "bottom" },+ size: 30,+ zoom_size: 60,+ rounding: 0,+ shadow: 0,+ advancedShadow: null,+ shape: "square",+ roundingType: "squircle",+};++const DEFAULT_AUDIO: AudioConfiguration = {+ mute: false,+ improve: false,+ micVolumeDb: 0,+ micStereoMode: "stereo",+ systemVolumeDb: 0,+};++const DEFAULT_CURSOR: CursorConfiguration = {+ hide: false,+ hideWhenIdle: false,+ hideWhenIdleDelay: 2,+ size: 100,+ type: "pointer",+ animationStyle: "mellow",+ tension: 120,+ mass: 1.1,+ friction: 18,+ raw: false,+ motionBlur: 0,+ useSvg: true,+};++const DEFAULT_HOTKEYS: HotkeysConfiguration = {+ show: false,+};+const DEFAULT_PROJECT: ScreenshotProject = {background: {source: {@@ -49,10 +85,17 @@ const DEFAULT_PROJECT: ScreenshotProject = {border: null,},aspectRatio: null,+ camera: DEFAULT_CAMERA,+ audio: DEFAULT_AUDIO,+ cursor: DEFAULT_CURSOR,+ hotkeys: DEFAULT_HOTKEYS,+ timeline: null,+ captions: null,+ clips: [],};export const [ScreenshotEditorProvider, useScreenshotEditorContext] =- createContextProvider((props: { path: string }) => {+ createContextProvider(() => {const [project, setProject] =createStore<ScreenshotProject>(DEFAULT_PROJECT);const [dialog, setDialog] = createSignal<DialogState>({@@ -65,9 +108,12 @@ export const [ScreenshotEditorProvider, useScreenshotEditorContext] =}>();const [editorInstance] = createResource(async () => {- const instance = await commands.createScreenshotEditorInstance(- props.path,- );+ // @ts-expect-error - types not updated yet+ const instance = await commands.createScreenshotEditorInstance();++ if (instance.config) {+ setProject(reconcile(instance.config));+ }const [_ws, isConnected] = createImageDataWS(instance.framesSocketUrl,@@ -77,33 +123,21 @@ export const [ScreenshotEditorProvider, useScreenshotEditorContext] =return instance;});+ const saveConfig = debounce((config: ProjectConfiguration) => {+ // @ts-expect-error - command signature update+ commands.updateScreenshotConfig(config, true);+ }, 1000);+createEffect(- on(- () => trackStore(project),- async () => {- const instance = editorInstance();- if (!instance) return;-- // Convert ScreenshotProject to ProjectConfiguration- // We need to construct a full ProjectConfiguration from the partial ScreenshotProject- // For now, we can use a default one and override background- const config = serializeProjectConfiguration({- ...normalizeProject({- // @ts-expect-error - partial config- background: project.background,- // @ts-expect-error - partial config- camera: {- source: { type: "none" },- },- }),- // @ts-expect-error- aspectRatio: project.aspectRatio,- });-- await commands.updateScreenshotConfig(instance, config);- },- { defer: true },- ),+ on([() => trackStore(project), editorInstance], async ([, instance]) => {+ if (!instance) return;++ const config = unwrap(project);++ // @ts-expect-error - command signature update+ commands.updateScreenshotConfig(config, false);+ saveConfig(config);+ }),);// Mock history for now or implement if needed@@ -118,7 +152,9 @@ export const [ScreenshotEditorProvider, useScreenshotEditorContext] =};return {- path: props.path,+ get path() {+ return editorInstance()?.path ?? "";+ },project,setProject,projectHistory,diff --git a/apps/desktop/src/routes/screenshot-editor/index.tsx b/apps/desktop/src/routes/screenshot-editor/index.tsxindex 491dcec89..f1d993c60 100644--- a/apps/desktop/src/routes/screenshot-editor/index.tsx+++ b/apps/desktop/src/routes/screenshot-editor/index.tsx@@ -1,8 +1,7 @@import { Effect, getCurrentWindow } from "@tauri-apps/api/window";import { type as ostype } from "@tauri-apps/plugin-os";import { cx } from "cva";-import { createEffect, createSignal, onMount, Show } from "solid-js";-import { AbsoluteInsetLoader } from "~/components/Loader";+import { createEffect } from "solid-js";import { generalSettingsStore } from "~/store";import { commands } from "~/utils/tauri";import { ScreenshotEditorProvider } from "./context";@@ -10,15 +9,6 @@ import { Editor } from "./Editor";export default function ScreenshotEditorRoute() {const generalSettings = generalSettingsStore.createQuery();- const [path, setPath] = createSignal<string | null>(null);-- onMount(() => {- // @ts-expect-error- const initialPath = window.__CAP__?.screenshotPath;- if (initialPath) {- setPath(initialPath);- }- });createEffect(() => {const transparent = generalSettings.data?.windowTransparency ?? false;@@ -37,13 +27,9 @@ export default function ScreenshotEditorRoute() {) && "bg-transparent-window",)}>- <Show when={path()} fallback={<AbsoluteInsetLoader />}>- {(p) => (- <ScreenshotEditorProvider path={p()}>- <Editor />- </ScreenshotEditorProvider>- )}- </Show>+ <ScreenshotEditorProvider>+ <Editor />+ </ScreenshotEditorProvider></div>);}