Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Screenshot functionality, shareable link wip
Richie McIlroy3e2d94c65fdb
diff --git a/Cargo.lock b/Cargo.lockindex 269c61347..54216346c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1421,6 +1421,7 @@ dependencies = ["core-graphics 0.24.0","cpal","dotenvy_macro",+ "fast_image_resize","ffmpeg-next","ffmpeg-sidecar 1.1.0 (git+https://github.com/CapSoftware/ffmpeg-sidecar?branch=main)","futures",@@ -1435,6 +1436,7 @@ dependencies = ["num-traits","objc","objc2-app-kit",+ "png","reqwest","rodio","scap",@@ -1736,6 +1738,18 @@ dependencies = ["zune-inflate",]+[[package]]+name = "fast_image_resize"+version = "4.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ca4b58827213977eabab8ee8d8258db8441338f3a1832a1c0f2de3372175531"+dependencies = [+ "cfg-if 1.0.0",+ "document-features",+ "num-traits",+ "thiserror",+]+[[package]]name = "fastrand"version = "2.1.0"diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex d468d51ca..d83634db5 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -65,6 +65,8 @@ tempfile = "3.12.0"ffmpeg-next.workspace = truechrono = "0.4.38"rodio = "0.19.0"+fast_image_resize = "4.2.1"+png = "0.17.13"cap-utils = { path = "../../../crates/utils" }cap-project = { path = "../../../crates/project" }diff --git a/apps/desktop/src-tauri/sounds/screenshot.ogg b/apps/desktop/src-tauri/sounds/screenshot.oggnew file mode 100644index 000000000..40e297b41Binary files /dev/null and b/apps/desktop/src-tauri/sounds/screenshot.ogg differdiff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex bb9e50ccf..562529daa 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -25,33 +25,32 @@ use image::{ImageBuffer, Rgba};use mp4::Mp4Reader;use num_traits::ToBytes;use objc2_app_kit::NSScreenSaverWindowLevel;+use png::{ColorType, Encoder};use project_recordings::ProjectRecordings;use recording::{DisplaySource, InProgressRecording};+use scap::capturer::Capturer;+use scap::frame::Frame;use serde::{Deserialize, Serialize};use serde_json::json;use specta::Type;use std::fs::File;+use std::io::BufWriter;use std::io::{BufReader, Write};-use std::sync::atomic::{AtomicBool, Ordering};use std::{- collections::HashMap,- marker::PhantomData,- path::PathBuf,- process::Command,- sync::Arc,- time::{Duration, Instant},+ collections::HashMap, marker::PhantomData, path::PathBuf, process::Command, sync::Arc,+ time::Duration,};use tauri::{AppHandle, Manager, State, WebviewUrl, WebviewWindow, WindowEvent};use tauri_nspanel::{cocoa::appkit::NSMainMenuWindowLevel, ManagerExt};use tauri_plugin_decorum::WebviewWindowExt;use tauri_specta::Event;-use tempfile::TempDir;use tokio::sync::mpsc;+use tokio::task;use tokio::{sync::{Mutex, RwLock},time::sleep,};-use upload::upload_video;+use upload::{upload_image, upload_video};#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]#[serde(rename_all = "camelCase")]@@ -183,6 +182,11 @@ pub struct NewRecordingAdded {path: PathBuf,}+#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]+pub struct NewScreenshotAdded {+ path: PathBuf,+}+#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]pub struct RecordingStarted;@@ -194,6 +198,9 @@ pub struct RecordingStopped {#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]pub struct RequestStartRecording;+#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]+pub struct RequestNewScreenshot;+#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]pub struct RequestStopRecording;@@ -430,6 +437,90 @@ async fn copy_file_to_path(src: String, dst: String) -> Result<(), String> {}}+#[tauri::command]+#[specta::specta]+async fn copy_screenshot_to_clipboard(app: AppHandle, path: PathBuf) -> Result<(), String> {+ println!("Copying screenshot to clipboard: {:?}", path);++ let image_data = match tokio::fs::read(&path).await {+ Ok(data) => data,+ Err(e) => {+ println!("Failed to read screenshot file: {}", e);+ return Err(format!("Failed to read screenshot file: {}", e));+ }+ };++ #[cfg(target_os = "macos")]+ {+ use cocoa::appkit::{NSImage, NSPasteboard};+ use cocoa::base::{id, nil};+ use cocoa::foundation::{NSArray, NSData};+ use objc::rc::autoreleasepool;++ unsafe {+ autoreleasepool(|| {+ let pasteboard: id = NSPasteboard::generalPasteboard(nil);+ NSPasteboard::clearContents(pasteboard);++ let ns_data = NSData::dataWithBytes_length_(+ nil,+ image_data.as_ptr() as *const std::os::raw::c_void,+ image_data.len() as u64,+ );++ let image = NSImage::initWithData_(NSImage::alloc(nil), ns_data);+ if image != nil {+ NSPasteboard::writeObjects(pasteboard, NSArray::arrayWithObject(nil, image));+ Ok(())+ } else {+ Err("Failed to create NSImage from data".to_string())+ }+ })+ }+ }++ #[cfg(not(target_os = "macos"))]+ {+ Err("Clipboard operations are only supported on macOS".to_string())+ }+}++#[tauri::command]+#[specta::specta]+async fn open_file_path(app: AppHandle, path: PathBuf) -> Result<(), String> {+ #[cfg(target_os = "macos")]+ {+ use std::process::Command;+ Command::new("open")+ .arg(&path)+ .output()+ .map_err(|e| format!("Failed to open file: {}", e))?;+ }++ #[cfg(target_os = "windows")]+ {+ use std::os::windows::process::CommandExt;+ use std::process::Command;+ Command::new("cmd")+ .args(&["/C", "start", ""])+ .arg(&path)+ .creation_flags(0x08000000) // CREATE_NO_WINDOW+ .output()+ .map_err(|e| format!("Failed to open file: {}", e))?;+ }++ #[cfg(target_os = "linux")]+ {+ use std::process::Command;+ Command::new("xdg-open")+ .arg(&path)+ .output()+ .map_err(|e| format!("Failed to open file: {}", e))?;+ }++ Ok(())+}+struct AudioRender {data: AudioData,pipe_tx: mpsc::UnboundedSender<Vec<f64>>,@@ -1385,6 +1476,256 @@ async fn upload_rendered_video(Ok(())}+#[tauri::command]+#[specta::specta]+async fn upload_screenshot(app: AppHandle, screenshot_path: PathBuf) -> Result<(), String> {+ let Ok(Some(auth)) = AuthStore::get(&app) else {+ println!("not authenticated!");+ return Err("Not authenticated".to_string());+ };++ println!("Uploading screenshot: {:?}", screenshot_path);++ let uploaded_screenshot = upload_image(auth.token, screenshot_path.clone(), true)+ .await+ .unwrap();++ let screenshot_dir = screenshot_path.parent().unwrap().to_path_buf();+ let meta_path = screenshot_dir.join("recording-meta.json");++ let mut meta = RecordingMeta::load_for_project(&meta_path).unwrap();++ meta.sharing = Some(SharingMeta {+ link: uploaded_screenshot.link.clone(),+ id: uploaded_screenshot.id.clone(),+ });+ meta.save_for_project();+ RecordingMetaChanged {+ id: screenshot_path+ .file_stem()+ .unwrap()+ .to_str()+ .unwrap()+ .to_string(),+ }+ .emit(&app)+ .ok();++ println!("Copying to clipboard: {:?}", uploaded_screenshot.link);++ #[cfg(target_os = "macos")]+ {+ use cocoa::appkit::NSPasteboard;+ use cocoa::base::{id, nil};+ use cocoa::foundation::{NSArray, NSString};+ use objc::rc::autoreleasepool;++ unsafe {+ autoreleasepool(|| {+ let pasteboard: id = NSPasteboard::generalPasteboard(nil);+ NSPasteboard::clearContents(pasteboard);++ let ns_string = NSString::alloc(nil).init_str(&uploaded_screenshot.link);++ let objects: id = NSArray::arrayWithObject(nil, ns_string);++ NSPasteboard::writeObjects(pasteboard, objects);+ });+ }+ }++ Ok(())+}++#[tauri::command]+#[specta::specta]+async fn take_screenshot(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {+ let id = uuid::Uuid::new_v4().to_string();++ let recording_dir = app+ .path()+ .app_data_dir()+ .unwrap()+ .join("screenshots")+ .join(format!("{id}.cap"));++ std::fs::create_dir_all(&recording_dir).map_err(|e| e.to_string())?;++ // Take screenshot using scap with optimized settings+ let options = scap::capturer::Options {+ fps: 1,+ output_type: scap::frame::FrameType::BGRAFrame,+ show_highlight: false,+ ..Default::default()+ };++ if let Some(window) = app.get_webview_window("main") {+ window.hide().ok();+ }++ let mut capturer = Capturer::new(options);+ capturer.start_capture();++ let frame = match capturer.get_next_frame() {+ Ok(frame) => frame,+ Err(e) => return Err(format!("Failed to get frame: {}", e)),+ };++ capturer.stop_capture();++ if let Frame::BGRA(bgra_frame) = frame {+ let width = bgra_frame.width as u32;+ let height = bgra_frame.height as u32;++ let now = chrono::Local::now();+ let screenshot_name = format!(+ "Cap {} at {}.png",+ now.format("%Y-%m-%d"),+ now.format("%H.%M.%S")+ );+ let screenshot_path = recording_dir.join(&screenshot_name);++ // Perform image processing and saving asynchronously+ let app_handle = app.clone();+ task::spawn_blocking(move || -> Result<(), String> {+ // Convert BGRA to RGBA+ let mut rgba_data = vec![0; bgra_frame.data.len()];+ for (bgra, rgba) in bgra_frame+ .data+ .chunks_exact(4)+ .zip(rgba_data.chunks_exact_mut(4))+ {+ rgba[0] = bgra[2];+ rgba[1] = bgra[1];+ rgba[2] = bgra[0];+ rgba[3] = bgra[3];+ }++ // Create file and PNG encoder+ let file = File::create(&screenshot_path).map_err(|e| e.to_string())?;+ let ref mut w = BufWriter::new(file);++ let mut encoder = Encoder::new(w, width, height);+ encoder.set_color(ColorType::Rgba);+ encoder.set_compression(png::Compression::Fast);+ let mut writer = encoder.write_header().map_err(|e| e.to_string())?;++ // Write image data+ writer+ .write_image_data(&rgba_data)+ .map_err(|e| e.to_string())?;++ audio::play_audio(include_bytes!("../sounds/screenshot.ogg"));++ if let Some(window) = app.get_webview_window("main") {+ window.show().ok();+ }++ let now = chrono::Local::now();+ let screenshot_name = format!(+ "Cap {} at {}.png",+ now.format("%Y-%m-%d"),+ now.format("%H.%M.%S")+ );++ use cap_project::*;+ RecordingMeta {+ project_path: recording_dir.clone(),+ sharing: None,+ pretty_name: screenshot_name,+ display: Display {+ path: screenshot_path.clone(),+ },+ camera: None,+ audio: None,+ }+ .save_for_project();++ NewScreenshotAdded {+ path: screenshot_path,+ }+ .emit(&app_handle)+ .ok();++ Ok(())+ })+ .await+ .map_err(|e| e.to_string())??;++ Ok(())+ } else {+ Err("Unexpected frame type".to_string())+ }+}++#[tauri::command]+#[specta::specta]+async fn save_file_dialog(+ app: AppHandle,+ file_name: String,+ file_type: String,+) -> Result<Option<String>, String> {+ use tauri_plugin_dialog::DialogExt;++ open_main_window(app.clone());++ println!(+ "save_file_dialog called with file_name: {}, file_type: {}",+ file_name, file_type+ );++ // Remove the ".cap" suffix if present+ let file_name = file_name+ .strip_suffix(".cap")+ .unwrap_or(&file_name)+ .to_string();+ println!("File name after removing .cap suffix: {}", file_name);++ // Determine the file type and extension+ let (name, extension) = match file_type.as_str() {+ "recording" => {+ println!("File type is recording");+ ("MP4 Video", "mp4")+ }+ "screenshot" => {+ println!("File type is screenshot");+ ("PNG Image", "png")+ }+ _ => {+ println!("Invalid file type: {}", file_type);+ return Err("Invalid file type".to_string());+ }+ };++ println!(+ "Showing save dialog with name: {}, extension: {}",+ name, extension+ );++ let (tx, rx) = std::sync::mpsc::channel();+ println!("Created channel for communication");++ app.dialog()+ .file()+ .set_title("Save File")+ .set_file_name(file_name)+ .add_filter(name, &[extension])+ .save_file(move |path| {+ println!("Save file callback triggered");+ let _ = tx.send(path.map(|p| p.to_string_lossy().to_string()));+ });++ println!("Waiting for user selection");+ let result = rx.recv().map_err(|e| {+ println!("Error receiving result: {}", e);+ e.to_string()+ })?;++ println!("Save dialog result: {:?}", result);++ Ok(result)+}+#[derive(Serialize, specta::Type, tauri_specta::Event, Debug, Clone)]struct RecordingMetaChanged {id: String,@@ -1392,8 +1733,23 @@ struct RecordingMetaChanged {#[tauri::command(async)]#[specta::specta]-fn get_recording_meta(app: AppHandle, id: String) -> RecordingMeta {- RecordingMeta::load_for_project(&recording_path(&app, &id)).unwrap()+fn get_recording_meta(+ app: AppHandle,+ id: String,+ file_type: String,+) -> Result<RecordingMeta, String> {+ println!(+ "get_recording_meta called with id: {}, file_type: {}",+ id, file_type+ );+ let meta_path = match file_type.as_str() {+ "recording" => recording_path(&app, &id),+ "screenshot" => screenshot_path(&app, &id),+ _ => return Err(format!("Invalid file type: {}", file_type)),+ };++ RecordingMeta::load_for_project(&meta_path)+ .map_err(|e| format!("Failed to load recording meta for {}: {}", id, e))}#[cfg_attr(mobile, tauri::mobile_entry_point)]@@ -1405,6 +1761,7 @@ pub fn run() {create_camera_window,start_recording,stop_recording,+ take_screenshot,list_cameras,list_capture_windows,list_audio_devices,@@ -1418,6 +1775,8 @@ pub fn run() {get_rendered_video,copy_file_to_path,copy_rendered_video_to_clipboard,+ copy_screenshot_to_clipboard,+ open_file_path,get_video_metadata,create_editor_instance,start_playback,@@ -1431,16 +1790,19 @@ pub fn run() {permissions::do_permissions_check,permissions::request_permission,upload_rendered_video,+ upload_screenshot,get_recording_meta,open_feedback_window,open_settings_window,open_changelog_window,+ save_file_dialog,hotkeys::set_hotkey]).events(tauri_specta::collect_events![RecordingOptionsChanged,ShowCapturesPanel,NewRecordingAdded,+ NewScreenshotAdded,RenderFrameEvent,EditorStateChanged,CurrentRecordingChanged,@@ -1449,6 +1811,7 @@ pub fn run() {RecordingStopped,RequestStartRecording,RequestStopRecording,+ RequestNewScreenshot,]).ty::<ProjectConfiguration>().ty::<AuthStore>()@@ -1520,6 +1883,15 @@ pub fn run() {});});+ let app_handle_clone = app_handle.clone();+ RequestNewScreenshot::listen_any(app, move |_| {+ let app_handle = app_handle_clone.clone();+ tauri::async_runtime::spawn(async move {+ if let Err(e) = take_screenshot(app_handle.clone(), app_handle.state()).await {+ eprintln!("Failed to take screenshot: {}", e);+ }+ });+ });Ok(())}).on_window_event(|window, event| {@@ -1609,3 +1981,11 @@ fn recordings_path(app: &AppHandle) -> PathBuf {fn recording_path(app: &AppHandle, recording_id: &str) -> PathBuf {recordings_path(app).join(format!("{}.cap", recording_id))}++fn screenshots_path(app: &AppHandle) -> PathBuf {+ app.path().app_data_dir().unwrap().join("screenshots")+}++fn screenshot_path(app: &AppHandle, screenshot_id: &str) -> PathBuf {+ screenshots_path(app).join(format!("{}.cap", screenshot_id))+}diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rsindex 84725abca..afd8ad175 100644--- a/apps/desktop/src-tauri/src/tray.rs+++ b/apps/desktop/src-tauri/src/tray.rs@@ -1,6 +1,6 @@use crate::{- NewRecordingAdded, RecordingStarted, RecordingStopped, RequestStartRecording,- RequestStopRecording,+ NewRecordingAdded, NewScreenshotAdded, RecordingStarted, RecordingStopped,+ RequestNewScreenshot, RequestStartRecording, RequestStopRecording,};use cap_project::RecordingMeta;use std::path::PathBuf;@@ -34,9 +34,20 @@ pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {None::<&str>,)?;+ let take_screenshot_i = MenuItem::with_id(+ app,+ "take_screenshot",+ "Take Screenshot",+ true,+ None::<&str>,+ )?;+// Create a submenu for previous recordingslet prev_recordings_submenu = create_prev_recordings_submenu(app)?;+ // Create a submenu for previous screenshots+ let prev_screenshots_submenu = create_prev_screenshots_submenu(app)?;+let quit_i = MenuItem::with_id(app, "quit", "Quit Cap", true, None::<&str>)?;let menu = Menu::with_items(@@ -44,7 +55,9 @@ pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {&[&version_i,&new_recording_i,+ &take_screenshot_i,&prev_recordings_submenu,+ &prev_screenshots_submenu,&quit_i,],)?;@@ -91,19 +104,22 @@ pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {// #[cfg(target_os = "macos")]// window.set_traffic_lights_inset(14.0, 22.0).unwrap();}+ "take_screenshot" => {+ let _ = RequestNewScreenshot.emit(&app_handle);+ }"quit" => {app.exit(0);}_ => {// Handle previous recording menu item clicks- if event.id.as_ref().starts_with("Cap ") {- if let Some(path) =- get_recording_path_by_pretty_name(app, event.id.as_ref())- {- NewRecordingAdded { path }.emit(app).unwrap();- } else {- println!("Unknown menu item clicked: {:?}", event);- }+ if let Some(path) =+ get_recording_path_by_pretty_name(app, event.id.as_ref())+ {+ NewRecordingAdded { path }.emit(app).unwrap();+ } else if let Some(path) =+ get_screenshot_path_by_name(app, event.id.as_ref())+ {+ NewScreenshotAdded { path }.emit(app).unwrap();} else {println!("Unhandled menu item clicked: {:?}", event);}@@ -189,9 +205,22 @@ fn create_prev_recordings_submenu<R: Runtime>(app: &AppHandle<R>) -> tauri::Resulet pretty_name = meta.pretty_name.clone();let id = pretty_name.clone();- let thumbnail_path = path.join("screenshots").join("thumbnail.png");- if thumbnail_path.exists() {- match Image::from_path(&thumbnail_path) {+ let screenshots_dir = path.join("screenshots");+ let png_files: Vec<_> = std::fs::read_dir(screenshots_dir)+ .ok()?+ .filter_map(|entry| {+ let entry = entry.ok()?;+ let path = entry.path();+ if path.extension()?.to_str()? == "png" {+ Some(path)+ } else {+ None+ }+ })+ .collect();++ if let Some(png_path) = png_files.first() {+ match Image::from_path(png_path) {Ok(image) => IconMenuItem::with_id(app,&id,@@ -223,6 +252,78 @@ fn create_prev_recordings_submenu<R: Runtime>(app: &AppHandle<R>) -> tauri::ResuSubmenu::with_items(app, "Previous Recordings", true, &items_ref)}+fn create_prev_screenshots_submenu<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<Submenu<R>> {+ let screenshots_dir = app+ .path()+ .app_data_dir()+ .map(|dir| dir.join("screenshots"))?;++ let items: Vec<MenuItemKind<R>> = if !screenshots_dir.exists() {+ vec![MenuItem::with_id(+ app,+ "no_screenshots",+ "No screenshots yet",+ false,+ None::<&str>,+ )+ .map(MenuItemKind::MenuItem)+ .unwrap()]+ } else {+ std::fs::read_dir(screenshots_dir)+ .map_err(tauri::Error::Io)?+ .filter_map(|entry| {+ let entry = entry.ok()?;+ let path = entry.path();+ if path.is_dir() {+ let png_files: Vec<_> = std::fs::read_dir(&path)+ .ok()?+ .filter_map(|file_entry| {+ let file_entry = file_entry.ok()?;+ let file_path = file_entry.path();+ if file_path.extension()?.to_str()? == "png" {+ Some(file_path)+ } else {+ None+ }+ })+ .collect();++ if let Some(png_path) = png_files.first() {+ let file_name = png_path.file_stem()?.to_str()?.to_string();+ let id = file_name.clone();+ match Image::from_path(png_path) {+ Ok(image) => IconMenuItem::with_id(+ app,+ &id,+ &file_name,+ true,+ Some(image),+ None::<&str>,+ )+ .map(MenuItemKind::Icon)+ .ok(),+ Err(_) => MenuItem::with_id(app, &id, &file_name, true, None::<&str>)+ .map(MenuItemKind::MenuItem)+ .ok(),+ }+ } else {+ None+ }+ } else {+ None+ }+ })+ .collect()+ };++ let items_ref: Vec<&dyn IsMenuItem<R>> = items+ .iter()+ .map(|item| item as &dyn IsMenuItem<R>)+ .collect();++ Submenu::with_items(app, "Previous Screenshots", true, &items_ref)+}+fn get_prev_recordings<R: Runtime>(app: &AppHandle<R>) -> Result<Vec<PathBuf>, tauri::Error> {let recordings_dir = app.path()@@ -260,13 +361,23 @@ fn handle_new_recording_added<R: Runtime>(app: &AppHandle<R>, path: PathBuf) ->true,None::<&str>,)?;+ let take_screenshot_i = MenuItem::with_id(+ app,+ "take_screenshot",+ "Take Screenshot",+ true,+ None::<&str>,+ )?;let prev_recordings_submenu = create_prev_recordings_submenu(app)?;+ let prev_screenshots_submenu = create_prev_screenshots_submenu(app)?;let quit_i = MenuItem::with_id(app, "quit", "Quit Cap", true, None::<&str>)?;let menu_items: Vec<&dyn IsMenuItem<R>> = vec![&version_i,&new_recording_i,+ &take_screenshot_i,&prev_recordings_submenu,+ &prev_screenshots_submenu,&quit_i,];let menu = Menu::with_items(app, &menu_items)?;@@ -289,3 +400,29 @@ fn get_recording_path_by_pretty_name<R: Runtime>(meta.pretty_name == pretty_name})}++fn get_screenshot_path_by_name<R: Runtime>(app: &AppHandle<R>, name: &str) -> Option<PathBuf> {+ let screenshots_dir = app.path().app_data_dir().ok()?.join("screenshots");++ std::fs::read_dir(screenshots_dir)+ .ok()?+ .filter_map(Result::ok)+ .find_map(|entry| {+ let path = entry.path();+ if path.is_dir() {+ std::fs::read_dir(path)+ .ok()?+ .filter_map(Result::ok)+ .find_map(|file_entry| {+ let file_path = file_entry.path();+ if file_path.file_stem()?.to_str()? == name {+ Some(file_path)+ } else {+ None+ }+ })+ } else {+ None+ }+ })+}diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex 6c9438fb3..0309ab315 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -1,7 +1,11 @@// credit @filleduchaos+use image::codecs::jpeg::JpegEncoder;+use image::ImageReader;use reqwest::{multipart::Form, Client, StatusCode};+use std::io::Cursor;use std::path::PathBuf;+use tokio::task;#[derive(serde::Deserialize)]struct S3UploadMeta {@@ -32,11 +36,23 @@ struct S3VideoUploadBody {video_codec: String,}+#[derive(serde::Serialize)]+#[serde(rename_all = "camelCase")]+struct S3ImageUploadBody {+ #[serde(flatten)]+ base: S3UploadBody,+}+pub struct UploadedVideo {pub link: String,pub id: String,}+pub struct UploadedImage {+ pub link: String,+ pub id: String,+}+pub async fn upload_video(video_id: String,auth_token: String,@@ -52,7 +68,7 @@ pub async fn upload_video(let client = reqwest::Client::new();let server_url_base: &'static str = dotenvy_macro::dotenv!("NEXT_PUBLIC_URL");- let s3_config = get_s3_config(&client, server_url_base, &auth_token).await?;+ let s3_config = get_s3_config(&client, server_url_base, &auth_token, false).await?;let file_key = format!("{}/{}/{}", s3_config.user_id, s3_config.id, file_name);@@ -61,10 +77,10 @@ pub async fn upload_video(let body = build_video_upload_body(&file_path,S3UploadBody {- user_id: s3_config.user_id,+ user_id: s3_config.user_id.clone(),file_key: file_key.clone(),- aws_bucket: s3_config.aws_bucket,- aws_region: s3_config.aws_region,+ aws_bucket: s3_config.aws_bucket.clone(),+ aws_region: s3_config.aws_region.clone(),},)?;@@ -80,6 +96,126 @@ pub async fn upload_video(.map_err(|e| format!("Error setting MIME type: {}", e))?;form = form.part("file", file_part);+ // Prepare screenshot upload+ let screenshot_path = file_path+ .parent()+ .unwrap()+ .parent()+ .unwrap()+ .join("screenshots")+ .join("display.jpg");++ let screenshot_upload = if screenshot_path.exists() {+ Some(prepare_screenshot_upload(&client, &s3_config, &auth_token, screenshot_path).await?)+ } else {+ None+ };++ let (video_upload, screenshot_result): (+ Result<reqwest::Response, reqwest::Error>,+ Option<Result<reqwest::Response, reqwest::Error>>,+ ) = tokio::join!(client.post(upload_url).multipart(form).send(), async {+ if let Some((screenshot_url, screenshot_form)) = screenshot_upload {+ Some(+ client+ .post(screenshot_url)+ .multipart(screenshot_form)+ .send()+ .await,+ )+ } else {+ None+ }+ });++ let response =+ video_upload.map_err(|e| format!("Failed to send upload file request: {}", e))?;++ if response.status().is_success() {+ println!("Video uploaded successfully");++ if let Some(Ok(screenshot_response)) = screenshot_result {+ if screenshot_response.status().is_success() {+ println!("Screenshot uploaded successfully");+ } else {+ println!(+ "Failed to upload screenshot: {}",+ screenshot_response.status()+ );+ }+ }++ return Ok(UploadedVideo {+ link: format!("{server_url_base}/s/{}", &s3_config.id),+ id: s3_config.id,+ });+ }++ let status = response.status();+ let error_body = response+ .text()+ .await+ .unwrap_or_else(|_| "<no response body>".to_string());+ tracing::error!(+ "Failed to upload file. Status: {}. Body: {}",+ status,+ error_body+ );+ Err(format!(+ "Failed to upload file. Status: {}. Body: {}",+ status, error_body+ ))+}++pub async fn upload_image(+ auth_token: String,+ file_path: PathBuf,+ solo_screenshot: bool,+) -> Result<UploadedImage, String> {+ let file_name = file_path+ .file_name()+ .and_then(|name| name.to_str())+ .ok_or("Invalid file path")?+ .to_string();++ let client = reqwest::Client::new();+ let server_url_base: &'static str = dotenvy_macro::dotenv!("NEXT_PUBLIC_URL");++ let s3_config = get_s3_config(&client, server_url_base, &auth_token, solo_screenshot).await?;++ let file_key: String = if solo_screenshot {+ format!("{}/{}/{}", s3_config.user_id, s3_config.id, file_name)+ } else {+ format!(+ "{}/{}/screenshot/screen-capture.jpg",+ s3_config.user_id, s3_config.id+ )+ };++ println!("File key: {file_key}");++ let body = S3ImageUploadBody {+ base: S3UploadBody {+ user_id: s3_config.user_id,+ file_key: file_key.clone(),+ aws_bucket: s3_config.aws_bucket,+ aws_region: s3_config.aws_region,+ },+ };++ let (upload_url, mut form) =+ presigned_s3_url_image(&client, server_url_base, body, &auth_token).await?;++ let file_content = tokio::fs::read(&file_path)+ .await+ .map_err(|e| format!("Failed to read file: {}", e))?;++ let file_part = reqwest::multipart::Part::bytes(file_content)+ .file_name(file_name.clone())+ .mime_str("image/jpeg")+ .map_err(|e| format!("Error setting MIME type: {}", e))?;+ form = form.part("file", file_part);+let response = client.post(upload_url).multipart(form)@@ -89,7 +225,7 @@ pub async fn upload_video(if response.status().is_success() {println!("File uploaded successfully");- return Ok(UploadedVideo {+ return Ok(UploadedImage {link: format!("{server_url_base}/s/{}", &s3_config.id),id: s3_config.id,});@@ -115,11 +251,19 @@ async fn get_s3_config(client: &Client,server_url_base: &str,auth_token: &str,+ is_screenshot: bool,) -> Result<S3UploadMeta, String> {- let config_url = format!(- "{}/api/desktop/video/create?origin={}&recordingMode=desktopMP4",- server_url_base, server_url_base- );+ let config_url = if is_screenshot {+ format!(+ "{}/api/desktop/video/create?origin={}&recordingMode=desktopMP4&isScreenshot=true",+ server_url_base, server_url_base+ )+ } else {+ format!(+ "{}/api/desktop/video/create?origin={}&recordingMode=desktopMP4",+ server_url_base, server_url_base+ )+ };let response = client.get(config_url)@@ -192,6 +336,51 @@ async fn presigned_s3_url(Ok((post_url, form))}+async fn presigned_s3_url_image(+ client: &Client,+ server_url_base: &str,+ body: S3ImageUploadBody,+ auth_token: &str,+) -> Result<(String, Form), String> {+ let presigned_upload_url = format!("{}/api/upload/signed", server_url_base);++ let response = client+ .post(presigned_upload_url)+ .json(&serde_json::json!(body))+ .header("Authorization", format!("Bearer {auth_token}"))+ .send()+ .await+ .map_err(|e| format!("Failed to send request to Next.js handler: {}", e))?;++ if response.status() == StatusCode::UNAUTHORIZED {+ return Err("Failed to authenticate request; please log in again".into());+ }++ let presigned_post_data = response+ .json::<serde_json::Value>()+ .await+ .map_err(|e| format!("Failed to deserialize server response: {}", e))?;++ let fields = presigned_post_data["presignedPostData"]["fields"]+ .as_object()+ .ok_or("Fields object is missing or not an object")?;+ let post_url = presigned_post_data["presignedPostData"]["url"]+ .as_str()+ .ok_or("URL is missing or not a string")?+ .to_string();++ let mut form = Form::new();++ for (key, value) in fields.iter() {+ let value_str = value+ .as_str()+ .ok_or(format!("Value for key '{}' is not a string", key))?;+ form = form.text(key.to_string(), value_str.to_owned());+ }++ Ok((post_url, form))+}+fn build_video_upload_body(path: &PathBuf,base: S3UploadBody,@@ -226,3 +415,72 @@ fn build_video_upload_body(video_codec: format!("{codec_name:?}").replace("Id::", "").to_lowercase(),})}++async fn prepare_screenshot_upload(+ client: &Client,+ s3_config: &S3UploadMeta,+ auth_token: &str,+ screenshot_path: PathBuf,+) -> Result<(String, Form), String> {+ let server_url_base: &'static str = dotenvy_macro::dotenv!("NEXT_PUBLIC_URL");+ let file_name = screenshot_path+ .file_name()+ .and_then(|name| name.to_str())+ .ok_or("Invalid screenshot file path")?+ .to_string();+ let file_key = format!(+ "{}/{}/screenshot/screen-capture.jpg",+ s3_config.user_id, s3_config.id+ );++ let body = S3ImageUploadBody {+ base: S3UploadBody {+ user_id: s3_config.user_id.clone(),+ file_key: file_key.clone(),+ aws_bucket: s3_config.aws_bucket.clone(),+ aws_region: s3_config.aws_region.clone(),+ },+ };++ let (upload_url, mut form) =+ presigned_s3_url_image(client, server_url_base, body, auth_token).await?;++ let compressed_image = compress_image(screenshot_path).await?;++ let file_part = reqwest::multipart::Part::bytes(compressed_image)+ .file_name(file_name)+ .mime_str("image/jpeg")+ .map_err(|e| format!("Error setting MIME type for screenshot: {}", e))?;+ form = form.part("file", file_part);++ Ok((upload_url, form))+}++async fn compress_image(path: PathBuf) -> Result<Vec<u8>, String> {+ task::spawn_blocking(move || {+ let img = ImageReader::open(&path)+ .map_err(|e| format!("Failed to open image: {}", e))?+ .decode()+ .map_err(|e| format!("Failed to decode image: {}", e))?;++ let new_width = img.width() / 2;+ let new_height = img.height() / 2;++ let resized_img = img.resize(new_width, new_height, image::imageops::FilterType::Nearest);++ let mut buffer = Vec::new();+ let mut encoder = JpegEncoder::new_with_quality(&mut buffer, 30);+ encoder+ .encode(+ resized_img.as_bytes(),+ new_width,+ new_height,+ resized_img.color().into(),+ )+ .map_err(|e| format!("Failed to compress image: {}", e))?;++ Ok(buffer)+ })+ .await+ .map_err(|e| format!("Failed to compress image: {}", e))?+}diff --git a/apps/desktop/src/routes/(window-chrome)/index.tsx b/apps/desktop/src/routes/(window-chrome)/index.tsxindex 6b47fc2c9..646be8433 100644--- a/apps/desktop/src/routes/(window-chrome)/index.tsx+++ b/apps/desktop/src/routes/(window-chrome)/index.tsx@@ -449,14 +449,25 @@ export default function () {</KSelect.Portal></KSelect></div>- <Button- disabled={toggleRecording.isPending}- variant={isRecording() ? "destructive" : "primary"}- size="md"- onClick={() => toggleRecording.mutate()}- >- {isRecording() ? "Stop Recording" : "Start Recording"}- </Button>+ <div class="w-full flex items-center space-x-1">+ <Button+ disabled={toggleRecording.isPending}+ variant={isRecording() ? "destructive" : "primary"}+ size="md"+ onClick={() => toggleRecording.mutate()}+ class="flex-grow"+ >+ {isRecording() ? "Stop Recording" : "Start Recording"}+ </Button>+ <Button+ disabled={isRecording()}+ variant="secondary"+ size="md"+ onClick={() => commands.takeScreenshot()}+ >+ <IconLucideCamera class="w-[1rem] h-[1rem]" />+ </Button>+ </div><ahref="https://cap.so/dashboard"target="_blank"diff --git a/apps/desktop/src/routes/prev-recordings.tsx b/apps/desktop/src/routes/prev-recordings.tsxindex 475d906dd..b30c441fc 100644--- a/apps/desktop/src/routes/prev-recordings.tsx+++ b/apps/desktop/src/routes/prev-recordings.tsx@@ -26,24 +26,24 @@ import { makePersisted } from "@solid-primitives/storage";import { commands, events } from "~/utils/tauri";import { DEFAULT_PROJECT_CONFIG } from "./editor/projectConfig";import { createPresets } from "~/utils/createPresets";+import { basename } from "@tauri-apps/api/path";-type RecordingEntry = {+type MediaEntry = {path: string;prettyName: string;isNew: boolean;+ type: "recording" | "screenshot";};export default function () {const presets = createPresets();- const [recordings, setRecordings] = makePersisted(- createStore<RecordingEntry[]>([]),- { name: "recordings-store" }+ const [mediaEntries, setMediaEntries] = makePersisted(+ createStore<MediaEntry[]>([]),+ { name: "media-entries-store" });- // Listen for new recordings- events.newRecordingAdded.listen((event) => {- const path = event.payload.path;- setRecordings(+ const addMediaEntry = (path: string, type: "recording" | "screenshot") => {+ setMediaEntries(produce((state) => {if (state.some((entry) => entry.path === path)) return;const fileName = path.split("/").pop() || "";@@ -51,12 +51,12 @@ export default function () {/Cap (\d{4}-\d{2}-\d{2} at \d{2}\.\d{2}\.\d{2})/);const prettyName = match ? match[1].replace(/\./g, ":") : fileName;- state.push({ path, prettyName, isNew: true });+ state.unshift({ path, prettyName, isNew: true, type });}));setTimeout(() => {- setRecordings(+ setMediaEntries(produce((state) => {const index = state.findIndex((entry) => entry.path === path);if (index !== -1) {@@ -65,6 +65,16 @@ export default function () {}));}, 3000);+ };++ // Listen for new recordings+ events.newRecordingAdded.listen((event) => {+ addMediaEntry(event.payload.path, "recording");+ });++ // Listen for new screenshots+ events.newScreenshotAdded.listen((event) => {+ addMediaEntry(event.payload.path, "screenshot");});return (@@ -78,266 +88,329 @@ export default function () {exitClass="opacity-100 translate-x-0"exitActiveClass="absolute">- <For each={recordings}>- {(recording, i) => {+ <For each={mediaEntries}>+ {(media, i) => {const [ref, setRef] = createSignal<HTMLElement | null>(null);- const videoId = recording.path.split("/").pop()?.split(".")[0]!;+ const mediaId = media.path.split("/").pop()?.split(".")[0]!;++ const isRecording = media.type === "recording";const recordingMeta = createQuery(() => ({- queryKey: ["recordingMeta", videoId],- queryFn: () => commands.getRecordingMeta(videoId),+ queryKey: ["recordingMeta", mediaId],+ queryFn: () => commands.getRecordingMeta(mediaId, media.type),+ enabled: true,}));- // createQueryInvalidate(record)- const copyVideo = createMutation(() => ({+ const copyMedia = createMutation(() => ({mutationFn: async () => {- const res = await commands.copyRenderedVideoToClipboard(- videoId,- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG- );- if (res.status !== "ok") throw new Error(res.error);+ if (isRecording) {+ const res = await commands.copyRenderedVideoToClipboard(+ mediaId,+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG+ );+ if (res.status !== "ok") throw new Error(res.error);+ } else {+ const res = await commands.copyScreenshotToClipboard(+ media.path+ );+ if (res.status !== "ok") throw new Error(res.error);+ }},}));- const saveVideo = createMutation(() => ({+ //TODO: Use pretty name for cap recording+ const saveMedia = createMutation(() => ({mutationFn: async () => {- const renderedPath = await commands.getRenderedVideo(- videoId,- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG+ const newFileName = isRecording+ ? "Cap Recording"+ : media.path.split(".cap/")[1];+ const fileType = isRecording ? "recording" : "screenshot";++ const savePathResult = await commands.saveFileDialog(+ newFileName,+ fileType);- if (renderedPath.status !== "ok")- throw new Error("Failed to get rendered video path");-- const savePath = await save({- filters: [{ name: "MP4 Video", extensions: ["mp4"] }],- });-- if (!savePath) return false;-- await commands.copyFileToPath(renderedPath.data, savePath);+ if (+ savePathResult.status !== "ok" ||+ !savePathResult.data+ ) {+ return false;+ }++ const savePath = savePathResult.data;++ if (isRecording) {+ const renderedPath = await commands.getRenderedVideo(+ mediaId,+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG+ );++ if (renderedPath.status !== "ok" || !renderedPath.data) {+ throw new Error("Failed to get rendered video path");+ }++ const copyResult = await commands.copyFileToPath(+ renderedPath.data,+ savePath+ );+ if (copyResult.status !== "ok") {+ throw new Error(+ `Failed to copy file: ${copyResult.error}`+ );+ }+ } else {+ const copyResult = await commands.copyFileToPath(+ media.path,+ savePath+ );+ if (copyResult.status !== "ok") {+ throw new Error(+ `Failed to copy file: ${copyResult.error}`+ );+ }+ }return true;},}));- const uploadVideo = createMutation(() => ({+ const uploadMedia = createMutation(() => ({mutationFn: async () => {- const res = await commands.uploadRenderedVideo(- videoId,- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG- );- if (res.status !== "ok") throw new Error(res.error);+ if (isRecording) {+ const res = await commands.uploadRenderedVideo(+ mediaId,+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG+ );+ if (res.status !== "ok") throw new Error(res.error);+ } else {+ const res = await commands.uploadScreenshot(media.path);+ if (res.status !== "ok") throw new Error(res.error);+ }},onSuccess: () =>startTransition(() => recordingMeta.refetch()),}));const [metadata] = createResource(async () => {- const result = await commands.getVideoMetadata(- recording.path,- null- );-- if (result.status !== "ok") {- console.error(`Failed to get metadata: ${result.status}`);- return;- }+ if (isRecording) {+ const result = await commands.getVideoMetadata(+ media.path,+ null+ );++ if (result.status !== "ok") {+ console.error(`Failed to get metadata: ${result.status}`);+ return;+ }- const [duration, size] = result.data;- console.log(- `Metadata for ${recording.path}: duration=${duration}, size=${size}`- );+ const [duration, size] = result.data;+ console.log(+ `Metadata for ${media.path}: duration=${duration}, size=${size}`+ );- return { duration, size };+ return { duration, size };+ }+ return null;});const [imageExists, setImageExists] = createSignal(true);const isLoading = () =>- copyVideo.isPending ||- saveVideo.isPending ||- uploadVideo.isPending;+ copyMedia.isPending ||+ saveMedia.isPending ||+ uploadMedia.isPending;- createFakeWindowBounds(ref, () => recording.path);+ createFakeWindowBounds(ref, () => media.path);return (<Suspense>- <Show when={metadata()}>- {(metadata) => (+ <div+ ref={setRef}+ style={{ "border-color": "rgba(255, 255, 255, 0.2)" }}+ class={cx(+ "w-[260px] h-[150px] p-[0.1875rem] bg-gray-500/50 rounded-[12px] overflow-hidden shadow border-[1px] group relative",+ "transition-all duration-300",+ media.isNew && "ring-2 ring-blue-500 ring-opacity-75"+ )}+ >+ <div+ class={cx(+ "w-full h-full flex relative bg-transparent rounded-[8px] border-[1px] overflow-hidden z-10",+ "transition-all",+ isLoading() && "backdrop-blur bg-gray-500/80"+ )}+ style={{+ "border-color": "rgba(255, 255, 255, 0.2)",+ }}+ >+ <Show+ when={imageExists()}+ fallback={+ <div class="pointer-events-none w-[105%] h-[105%] absolute inset-0 -z-10 bg-gray-400" />+ }+ >+ <img+ class="pointer-events-none w-[105%] h-[105%] object-cover absolute inset-0 -z-10"+ alt="media preview"+ src={`${convertFileSrc(+ isRecording+ ? `${media.path}/screenshots/display.jpg`+ : `${media.path}`+ )}?t=${Date.now()}`}+ onError={() => setImageExists(false)}+ />+ </Show><div- ref={setRef}- style={{ "border-color": "rgba(255, 255, 255, 0.2)" }}class={cx(- "w-[260px] h-[150px] p-[0.1875rem] bg-gray-500/50 rounded-[12px] overflow-hidden shadow border-[1px] group relative",- "transition-all duration-300",- recording.isNew &&- "ring-2 ring-blue-500 ring-opacity-75"+ "w-full h-full absolute inset-0 transition-all",+ isLoading()+ ? "opacity-100"+ : "opacity-0 group-hover:opacity-100",+ "backdrop-blur bg-gray-500/80 text-white p-2")}>- <div- class={cx(- "w-full h-full flex relative bg-transparent rounded-[8px] border-[1px] overflow-hidden z-10",- "transition-all",- isLoading() && "backdrop-blur bg-gray-500/80"- )}- style={{- "border-color": "rgba(255, 255, 255, 0.2)",- }}+ <TooltipIconButton+ class="absolute left-3 top-3 z-20"+ tooltipText="Close"+ tooltipPlacement="right"+ onClick={() =>+ setMediaEntries(+ produce((state) => {+ state.splice(i(), 1);+ })+ )+ }>- <Show- when={imageExists()}- fallback={- <div class="pointer-events-none w-[105%] h-[105%] absolute inset-0 -z-10 bg-gray-400" />- }+ <IconCapCircleX class="size-[1rem]" />+ </TooltipIconButton>+ {isRecording ? (+ <TooltipIconButton+ class="absolute left-3 bottom-3 z-20"+ tooltipText="Edit"+ tooltipPlacement="right"+ onClick={() => {+ commands.openEditor(mediaId);+ }}>- <img- class="pointer-events-none w-[105%] h-[105%] object-cover absolute inset-0 -z-10"- alt="screenshot"- src={`${convertFileSrc(- `${recording.path}/screenshots/display.jpg`- )}?t=${Date.now()}`}- onError={() => setImageExists(false)}- />- </Show>- <div- class={cx(- "w-full h-full absolute inset-0 transition-all",- isLoading()- ? "opacity-100"- : "opacity-0 group-hover:opacity-100",- "backdrop-blur bg-gray-500/80 text-white p-2"- )}+ <IconCapEditor class="size-[1rem]" />+ </TooltipIconButton>+ ) : (+ <TooltipIconButton+ class="absolute left-3 bottom-3 z-20"+ tooltipText="View"+ tooltipPlacement="right"+ onClick={() => {+ commands.openFilePath(media.path);+ }}+ >+ <IconLucideEye class="size-[1rem]" />+ </TooltipIconButton>+ )}+ <TooltipIconButton+ class="absolute right-3 top-3 z-20"+ tooltipText={+ copyMedia.isPending+ ? "Copying to Clipboard"+ : "Copy to Clipboard"+ }+ forceOpen={copyMedia.isPending}+ tooltipPlacement="left"+ onClick={() => copyMedia.mutate()}+ disabled={+ saveMedia.isPending || uploadMedia.isPending+ }+ >+ <Switch+ fallback={<IconCapCopy class="size-[1rem]" />}>- <TooltipIconButton- class="absolute left-3 top-3 z-20"- tooltipText="Close"- tooltipPlacement="right"- onClick={() =>- setRecordings(- produce((state) => {- state.splice(i(), 1);- })- )- }- >- <IconCapCircleX class="size-[1rem]" />- </TooltipIconButton>- <TooltipIconButton- class="absolute left-3 bottom-3 z-20"- tooltipText="Edit"- tooltipPlacement="right"- onClick={() => {- commands.openEditor(videoId);+ <Match when={copyMedia.isPending}>+ <IconLucideLoaderCircle class="size-[1rem] animate-spin" />+ </Match>+ <Match when={copyMedia.isSuccess}>+ {(_) => {+ setTimeout(() => {+ if (!copyMedia.isPending) copyMedia.reset();+ }, 2000);++ return (+ <IconLucideCheck class="size-[1rem]" />+ );}}- >- <IconCapEditor class="size-[1rem]" />- </TooltipIconButton>- <TooltipIconButton- class="absolute right-3 top-3 z-20"- tooltipText={- copyVideo.isPending- ? "Copying to Clipboard"- : "Copy to Clipboard"- }- forceOpen={copyVideo.isPending}- tooltipPlacement="left"- onClick={() => copyVideo.mutate()}- disabled={- saveVideo.isPending || uploadVideo.isPending- }- >- <Switch- fallback={<IconCapCopy class="size-[1rem]" />}- >- <Match when={copyVideo.isPending}>- <IconLucideLoaderCircle class="size-[1rem] animate-spin" />- </Match>- <Match when={copyVideo.isSuccess}>- {(_) => {- setTimeout(() => {- if (!copyVideo.isPending)- copyVideo.reset();- }, 2000);-- return (- <IconLucideCheck class="size-[1rem]" />- );- }}- </Match>- </Switch>- </TooltipIconButton>- <TooltipIconButton- class="absolute right-3 bottom-3 z-20"- tooltipText={- recordingMeta.data?.sharing- ? "Copy Shareable Link"- : uploadVideo.isPending- ? "Uploading Cap"- : "Create Shareable Link"- }- forceOpen={uploadVideo.isPending}- tooltipPlacement="left"- onClick={() => uploadVideo.mutate()}- disabled={- copyVideo.isPending || saveVideo.isPending- }- >- <Switch- fallback={- <IconCapUpload class="size-[1rem]" />- }- >- <Match when={uploadVideo.isPending}>- <IconLucideLoaderCircle class="size-[1rem] animate-spin" />- </Match>- <Match when={uploadVideo.isSuccess}>- {(_) => {- setTimeout(() => {- if (!uploadVideo.isPending)- uploadVideo.reset();- }, 2000);-- return (- <IconLucideCheck class="size-[1rem]" />- );- }}- </Match>- </Switch>- </TooltipIconButton>- <div class="absolute inset-0 flex items-center justify-center">- <Button- variant="secondary"- size="sm"- onClick={() => saveVideo.mutate()}- disabled={- copyVideo.isPending || uploadVideo.isPending+ </Match>+ </Switch>+ </TooltipIconButton>+ <TooltipIconButton+ class="absolute right-3 bottom-3 z-20"+ tooltipText={+ recordingMeta.data?.sharing+ ? "Copy Shareable Link"+ : uploadMedia.isPending+ ? "Uploading Cap"+ : "Create Shareable Link"+ }+ forceOpen={uploadMedia.isPending}+ tooltipPlacement="left"+ onClick={() => uploadMedia.mutate()}+ disabled={+ copyMedia.isPending || saveMedia.isPending+ }+ >+ <Switch+ fallback={<IconCapUpload class="size-[1rem]" />}+ >+ <Match when={uploadMedia.isPending}>+ <IconLucideLoaderCircle class="size-[1rem] animate-spin" />+ </Match>+ <Match when={uploadMedia.isSuccess}>+ {(_) => {+ setTimeout(() => {+ if (!uploadMedia.isPending)+ uploadMedia.reset();+ }, 2000);++ return (+ <IconLucideCheck class="size-[1rem]" />+ );+ }}+ </Match>+ </Switch>+ </TooltipIconButton>+ <div class="absolute inset-0 flex items-center justify-center">+ <Button+ variant="secondary"+ size="sm"+ onClick={() => saveMedia.mutate()}+ disabled={+ copyMedia.isPending || uploadMedia.isPending+ }+ >+ <Switch fallback="Save">+ <Match when={saveMedia.isPending}>+ Saving...+ </Match>+ <Match+ when={+ saveMedia.isSuccess &&+ saveMedia.data === true}>- <Switch fallback="Save">- <Match when={saveVideo.isPending}>- Saving...- </Match>- <Match- when={- saveVideo.isSuccess &&- saveVideo.data === true- }- >- {(_) => {- setTimeout(() => {- if (!saveVideo.isPending)- saveVideo.reset();- }, 2000);-- return "Saved!";- }}- </Match>- </Switch>- </Button>- </div>- </div>+ {(_) => {+ setTimeout(() => {+ if (!saveMedia.isPending)+ saveMedia.reset();+ }, 2000);++ return "Saved!";+ }}+ </Match>+ </Switch>+ </Button>+ </div>+ </div>+ <Show when={isRecording && metadata()}>+ {(metadata) => (<divstyle={{ color: "white", "font-size": "14px" }}class={cx(@@ -356,10 +429,10 @@ export default function () {</p><p>{metadata().size.toFixed(2)} MB</p></div>- </div>- </div>- )}- </Show>+ )}+ </Show>+ </div>+ </div></Suspense>);}}diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 7001d8c3c..84aa37fe4 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -40,6 +40,14 @@ async stopRecording() : Promise<Result<null, string>> {else return { status: "error", error: e as any };}},+async takeScreenshot() : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("take_screenshot") };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},async listCameras() : Promise<string[]> {return await TAURI_INVOKE("list_cameras");},@@ -114,6 +122,22 @@ async copyRenderedVideoToClipboard(videoId: string, project: ProjectConfiguratioelse return { status: "error", error: e as any };}},+async copyScreenshotToClipboard(path: string) : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("copy_screenshot_to_clipboard", { path }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},+async openFilePath(path: string) : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("open_file_path", { path }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},async getVideoMetadata(videoId: string, videoType: VideoType | null) : Promise<Result<[number, number], string>> {try {return { status: "ok", data: await TAURI_INVOKE("get_video_metadata", { videoId, videoType }) };@@ -168,8 +192,21 @@ async uploadRenderedVideo(videoId: string, project: ProjectConfiguration) : Promelse return { status: "error", error: e as any };}},-async getRecordingMeta(id: string) : Promise<RecordingMeta> {- return await TAURI_INVOKE("get_recording_meta", { id });+async uploadScreenshot(screenshotPath: string) : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("upload_screenshot", { screenshotPath }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},+async getRecordingMeta(id: string, fileType: string) : Promise<Result<RecordingMeta, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("get_recording_meta", { id, fileType }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}},async openFeedbackWindow() : Promise<void> {await TAURI_INVOKE("open_feedback_window");@@ -180,6 +217,14 @@ async openSettingsWindow() : Promise<void> {async openChangelogWindow() : Promise<void> {await TAURI_INVOKE("open_changelog_window");},+async saveFileDialog(fileName: string, fileType: string) : Promise<Result<string | null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("save_file_dialog", { fileName, fileType }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},async setHotkey(action: HotkeyAction, hotkey: Hotkey | null) : Promise<Result<null, null>> {try {return { status: "ok", data: await TAURI_INVOKE("set_hotkey", { action, hotkey }) };@@ -197,11 +242,13 @@ export const events = __makeEvents__<{currentRecordingChanged: CurrentRecordingChanged,editorStateChanged: EditorStateChanged,newRecordingAdded: NewRecordingAdded,+newScreenshotAdded: NewScreenshotAdded,recordingMetaChanged: RecordingMetaChanged,recordingOptionsChanged: RecordingOptionsChanged,recordingStarted: RecordingStarted,recordingStopped: RecordingStopped,renderFrameEvent: RenderFrameEvent,+requestNewScreenshot: RequestNewScreenshot,requestStartRecording: RequestStartRecording,requestStopRecording: RequestStopRecording,showCapturesPanel: ShowCapturesPanel@@ -209,11 +256,13 @@ showCapturesPanel: ShowCapturesPanelcurrentRecordingChanged: "current-recording-changed",editorStateChanged: "editor-state-changed",newRecordingAdded: "new-recording-added",+newScreenshotAdded: "new-screenshot-added",recordingMetaChanged: "recording-meta-changed",recordingOptionsChanged: "recording-options-changed",recordingStarted: "recording-started",recordingStopped: "recording-stopped",renderFrameEvent: "render-frame-event",+requestNewScreenshot: "request-new-screenshot",requestStartRecording: "request-start-recording",requestStopRecording: "request-stop-recording",showCapturesPanel: "show-captures-panel"@@ -254,6 +303,7 @@ export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } }export type InProgressRecording = { recordingDir: string; displaySource: DisplaySource }export type JsonValue<T> = [T]export type NewRecordingAdded = { path: string }+export type NewScreenshotAdded = { path: string }export type OSPermission = "screenRecording" | "camera" | "microphone"export type OSPermissionStatus = "notNeeded" | "empty" | "granted" | "denied"export type OSPermissionsCheck = { screenRecording: OSPermissionStatus; microphone: OSPermissionStatus; camera: OSPermissionStatus }@@ -267,6 +317,7 @@ export type RecordingStarted = nullexport type RecordingStopped = { path: string }export type RenderFrameEvent = { frame_number: number; project: ProjectConfiguration }export type RenderProgress = { type: "Starting"; total_frames: number } | { type: "EstimatedTotalFrames"; total_frames: number } | { type: "FrameRendered"; current_frame: number }+export type RequestNewScreenshot = nullexport type RequestStartRecording = nullexport type RequestStopRecording = nullexport type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration | null; recordings: ProjectRecordings; path: string }diff --git a/apps/web/app/api/desktop/video/create/route.ts b/apps/web/app/api/desktop/video/create/route.tsindex 88df0454a..9e15dd661 100644--- a/apps/web/app/api/desktop/video/create/route.ts+++ b/apps/web/app/api/desktop/video/create/route.ts@@ -60,7 +60,7 @@ export async function GET(req: NextRequest) {const recordingMode: "hls" | "desktopMP4" | null = params.get("recordingMode") as any;-+ const isScreenshot = params.get("isScreenshot") === "true";if (!user) {console.log("User not authenticated, returning 401");@@ -86,7 +86,6 @@ export async function GET(req: NextRequest) {month: "long",})} ${date.getFullYear()}`;-await db.insert(videos).values({id: id,name: `My Cap Recording - ${formattedDate}`,@@ -99,6 +98,7 @@ export async function GET(req: NextRequest) {: recordingMode === "desktopMP4"? { type: "desktopMP4" }: undefined,+ isScreenshot: isScreenshot,});if (diff --git a/packages/database/schema.ts b/packages/database/schema.tsindex 6ae96bcb3..88dd567db 100644--- a/packages/database/schema.ts+++ b/packages/database/schema.ts@@ -152,6 +152,7 @@ export const videos = mysqlTable(xStreamInfo: text("xStreamInfo"),jobId: varchar("jobId", { length: 255 }),jobStatus: varchar("jobStatus", { length: 255 }),+ isScreenshot: boolean("isScreenshot").notNull().default(false),skipProcessing: boolean("skipProcessing").notNull().default(false),transcriptionStatus: varchar("transcriptionStatus", { length: 255 }),createdAt: timestamp("createdAt").notNull().defaultNow(),diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.tsindex a96f144ff..61acd2e27 100644--- a/packages/ui-solid/src/auto-imports.d.ts+++ b/packages/ui-solid/src/auto-imports.d.ts@@ -21,6 +21,7 @@ declare global {const IconCapCursor: typeof import('~icons/cap/cursor.jsx')['default']const IconCapEditor: typeof import('~icons/cap/editor.jsx')['default']const IconCapEnlarge: typeof import('~icons/cap/enlarge.jsx')['default']+ const IconCapEye: typeof import('~icons/cap/eye.jsx')['default']const IconCapFrameFirst: typeof import('~icons/cap/frame-first.jsx')['default']const IconCapFrameLast: typeof import('~icons/cap/frame-last.jsx')['default']const IconCapHotkeys: typeof import('~icons/cap/hotkeys.jsx')['default']@@ -44,7 +45,9 @@ declare global {const IconCapUndo: typeof import('~icons/cap/undo.jsx')['default']const IconCapUpload: typeof import('~icons/cap/upload.jsx')['default']const IconLucideBell: typeof import('~icons/lucide/bell.jsx')['default']+ const IconLucideCamera: typeof import('~icons/lucide/camera.jsx')['default']const IconLucideCheck: typeof import('~icons/lucide/check.jsx')['default']+ const IconLucideEye: typeof import('~icons/lucide/eye.jsx')['default']const IconLucideLoaderCircle: typeof import('~icons/lucide/loader-circle.jsx')['default']const IconLucideSmile: typeof import('~icons/lucide/smile.jsx')['default']}