Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
organise cursor capture
Brendan Allan530b370b7d57
diff --git a/apps/desktop/src-tauri/src/cursor.rs b/apps/desktop/src-tauri/src/cursor.rsnew file mode 100644index 000000000..5ce6cea79--- /dev/null+++ b/apps/desktop/src-tauri/src/cursor.rs@@ -0,0 +1,180 @@+use std::{+ collections::HashMap,+ fs::File,+ path::PathBuf,+ sync::{atomic::AtomicBool, Arc},+ time::{Duration, Instant},+};++use cap_media::platform::Bounds;+use cap_project::{CursorData, CursorEvent};+use device_query::{DeviceQuery, DeviceState};+use tokio::sync::oneshot;++pub fn spawn_cursor_recorder(+ stop_signal: Arc<AtomicBool>,+ screen_bounds: Bounds,+ content_dir: PathBuf,+ cursors_dir: PathBuf,+) -> (+ oneshot::Receiver<Vec<CursorEvent>>,+ oneshot::Receiver<Vec<CursorEvent>>,+) {+ let (move_tx, move_rx) = oneshot::channel();+ let (click_tx, click_rx) = oneshot::channel();++ tokio::spawn(async move {+ let device_state = DeviceState::new();+ let mut last_mouse_state = device_state.get_mouse();+ let start_time = Instant::now();++ let mut moves = vec![];+ let mut clicks = vec![];+ let mut cursor_images = HashMap::new();+ let mut seen_cursor_data: HashMap<Vec<u8>, String> = HashMap::new();+ let mut next_cursor_id = 0;++ // Create cursors directory if it doesn't exist+ std::fs::create_dir_all(&cursors_dir).unwrap();++ while !stop_signal.load(std::sync::atomic::Ordering::Relaxed) {+ let mouse_state = device_state.get_mouse();+ let elapsed = start_time.elapsed().as_secs_f64() * 1000.0;+ let unix_time = chrono::Utc::now().timestamp_millis() as f64;++ let cursor_data = get_cursor_image_data();+ let cursor_id = if let Some(data) = cursor_data {+ // Check if we've seen this cursor data before+ if let Some(existing_id) = seen_cursor_data.get(&data) {+ existing_id.clone()+ } else {+ // New cursor data - save it+ let cursor_id = next_cursor_id.to_string();+ let filename = format!("cursor_{}.png", cursor_id);+ let cursor_path = cursors_dir.join(&filename);++ println!("Saving new cursor image to: {:?}", cursor_path);++ if let Ok(image) = image::load_from_memory(&data) {+ // Convert to RGBA+ let rgba_image = image.into_rgba8();+ if let Err(e) = rgba_image.save(&cursor_path) {+ eprintln!("Failed to save cursor image: {}", e);+ } else {+ println!("Successfully saved cursor image {}", cursor_id);+ cursor_images.insert(cursor_id.clone(), filename.clone());+ seen_cursor_data.insert(data, cursor_id.clone());+ next_cursor_id += 1;+ }+ }+ cursor_id+ }+ } else {+ "default".to_string()+ };++ if mouse_state.coords != last_mouse_state.coords {+ let mouse_event = CursorEvent {+ active_modifiers: vec![],+ cursor_id: cursor_id.clone(),+ process_time_ms: elapsed,+ unix_time_ms: unix_time,+ x: (mouse_state.coords.0 as f64 - screen_bounds.x) / screen_bounds.width,+ y: (mouse_state.coords.1 as f64 - screen_bounds.y) / screen_bounds.height,+ };+ moves.push(mouse_event);+ }++ // cursor 0 doesn't do anything+ if mouse_state.button_pressed[1] && !last_mouse_state.button_pressed[1] {+ let mouse_event = CursorEvent {+ active_modifiers: vec![],+ cursor_id,+ process_time_ms: elapsed,+ unix_time_ms: unix_time,+ x: (mouse_state.coords.0 as f64 - screen_bounds.x) / screen_bounds.width,+ y: (mouse_state.coords.1 as f64 - screen_bounds.y) / screen_bounds.height,+ };+ clicks.push(mouse_event);+ }++ last_mouse_state = mouse_state;+ tokio::time::sleep(Duration::from_millis(10)).await;+ }++ // Save cursor data to cursor.json+ let cursor_data = CursorData {+ clicks: clicks.clone(),+ moves: moves.clone(),+ cursor_images,+ };++ let cursor_json_path = content_dir.join("cursor.json");+ println!("Saving cursor data to: {:?}", cursor_json_path);+ if let Ok(mut file) = File::create(&cursor_json_path) {+ if let Err(e) = serde_json::to_writer_pretty(&mut file, &cursor_data) {+ eprintln!("Failed to save cursor data: {}", e);+ } else {+ println!("Successfully saved cursor data");+ }+ }++ move_tx.send(moves).unwrap();+ click_tx.send(clicks).unwrap();+ });++ (move_rx, click_rx)+}++#[cfg(target_os = "macos")]+fn get_cursor_image_data() -> Option<Vec<u8>> {+ use cocoa::base::{id, nil};+ use cocoa::foundation::{NSData, NSUInteger};+ use objc::rc::autoreleasepool;+ use objc::runtime::Class;+ use objc::*;++ autoreleasepool(|| {+ let nscursor_class = match Class::get("NSCursor") {+ Some(cls) => cls,+ None => return None,+ };++ unsafe {+ // Get the current system cursor+ let current_cursor: id = msg_send![nscursor_class, currentSystemCursor];+ if current_cursor == nil {+ return None;+ }++ // Get the image of the cursor+ let cursor_image: id = msg_send![current_cursor, image];+ if cursor_image == nil {+ return None;+ }++ // Get the TIFF representation of the image+ let image_data: id = msg_send![cursor_image, TIFFRepresentation];+ if image_data == nil {+ return None;+ }++ // Get the length of the data+ let length: NSUInteger = msg_send![image_data, length];++ // Get the bytes of the data+ let bytes: *const u8 = msg_send![image_data, bytes];++ // Copy the data into a Vec<u8>+ let slice = std::slice::from_raw_parts(bytes, length as usize);+ let data = slice.to_vec();++ Some(data)+ }+ })+}++#[cfg(windows)]+fn get_cursor_image_data() -> Option<Vec<u8>> {+ todo!()+}diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 7ea42e3f8..e91f0bb2d 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -9,6 +9,7 @@ mod permissions;mod platform;mod recording;// mod resource;+mod cursor;mod tray;mod upload;mod web_api;@@ -345,6 +346,7 @@ async fn start_recording(app: AppHandle, state: MutableState<'_, App>) -> Result}match recording::start(+ id,recording_dir,&state.start_recording_options,state.camera_feed.as_ref(),@@ -497,77 +499,70 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<AppSounds::StopRecording.play();- let recording_id = recording- .recording_dir- .file_name()- .unwrap_or_default()- .to_string_lossy()- .to_string()- .trim_end_matches(".cap")- .to_string();+ if let Some((settings, auth)) = GeneralSettingsStore::get(&app)+ .ok()+ .flatten()+ .zip(AuthStore::get(&app).ok().flatten())+ {+ if auth.is_upgraded() && settings.auto_create_shareable_link {+ if let Some(pre_created_video) = state.pre_created_video.take() {+ // Copy link to clipboard+ #[cfg(target_os = "macos")]+ platform::write_string_to_pasteboard(&pre_created_video.link);- if let Ok(Some(settings)) = GeneralSettingsStore::get(&app) {- if let Ok(Some(auth)) = AuthStore::get(&app) {- if auth.is_upgraded() && settings.auto_create_shareable_link {- if let Some(pre_created_video) = state.pre_created_video.take() {- // Copy link to clipboard- #[cfg(target_os = "macos")]- platform::write_string_to_pasteboard(&pre_created_video.link);+ // Send notification for shareable link+ notifications::send_notification(+ &app,+ notifications::NotificationType::ShareableLinkCopied,+ );- // Send notification for shareable link- notifications::send_notification(- &app,- notifications::NotificationType::ShareableLinkCopied,- );+ // Open the pre-created shareable link+ open_external_link(app.clone(), pre_created_video.link.clone()).ok();- // Open the pre-created shareable link- open_external_link(app.clone(), pre_created_video.link.clone()).ok();-- // Start the upload process in the background with retry mechanism- let app_clone = app.clone();-- tauri::async_runtime::spawn(async move {- let max_retries = 3;- let mut retry_count = 0;-- while retry_count < max_retries {- match upload_rendered_video(- app_clone.clone(),- recording_id.clone(),- ProjectConfiguration::default(),- Some(pre_created_video.clone()),- )- .await- {- Ok(_) => {- println!("Video uploaded successfully");- // Don't send notification here since we already did it above- break;- }- Err(e) => {- retry_count += 1;- println!(- "Error during auto-upload (attempt {}/{}): {}",- retry_count, max_retries, e- );+ // Start the upload process in the background with retry mechanism+ let app_clone = app.clone();- if retry_count < max_retries {- tokio::time::sleep(std::time::Duration::from_secs(5)).await;- } else {- println!("Max retries reached. Upload failed.");- notifications::send_notification(- &app_clone,- notifications::NotificationType::UploadFailed,- );- }+ tauri::async_runtime::spawn(async move {+ let max_retries = 3;+ let mut retry_count = 0;++ while retry_count < max_retries {+ match upload_rendered_video(+ app_clone.clone(),+ recording.id.clone(),+ ProjectConfiguration::default(),+ Some(pre_created_video.clone()),+ )+ .await+ {+ Ok(_) => {+ println!("Video uploaded successfully");+ // Don't send notification here since we already did it above+ break;+ }+ Err(e) => {+ retry_count += 1;+ println!(+ "Error during auto-upload (attempt {}/{}): {}",+ retry_count, max_retries, e+ );++ if retry_count < max_retries {+ tokio::time::sleep(std::time::Duration::from_secs(5)).await;+ } else {+ println!("Max retries reached. Upload failed.");+ notifications::send_notification(+ &app_clone,+ notifications::NotificationType::UploadFailed,+ );}}}- });- }- } else if settings.open_editor_after_recording {- open_editor(app.clone(), recording_id);+ }+ });}+ } else if settings.open_editor_after_recording {+ open_editor(app.clone(), recording.id);}}diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex a781592b1..868b5e1ed 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -6,23 +6,15 @@ use serde::Serialize;use specta::Type;use std::collections::HashMap;use std::fs::File;+use std::sync::atomic::AtomicBool;use std::sync::Arc;use std::time::Instant;use std::time::{SystemTime, UNIX_EPOCH};use std::{path::PathBuf, time::Duration};use tokio::sync::{oneshot, Mutex};+use uuid::Uuid;-#[cfg(target_os = "macos")]-use cocoa::base::{id, nil};-#[cfg(target_os = "macos")]-use cocoa::foundation::{NSData, NSUInteger};-#[cfg(target_os = "macos")]-use objc::rc::autoreleasepool;-#[cfg(target_os = "macos")]-use objc::runtime::Class;-#[cfg(target_os = "macos")]-use objc::*;-+use crate::cursor::spawn_cursor_recorder;use crate::RecordingOptions;// TODO: Hacky, please fix@@ -56,6 +48,7 @@ pub fn list_cameras() -> Vec<String> {#[derive(Type, Serialize)]#[serde(rename_all = "camelCase")]pub struct InProgressRecording {+ pub id: String,pub recording_dir: PathBuf,#[serde(skip)]pub pipeline: Pipeline<SynchronisedClock<()>>,@@ -72,13 +65,14 @@ pub struct InProgressRecording {#[serde(skip)]pub cursor_clicks: oneshot::Receiver<Vec<CursorEvent>>,#[serde(skip)]- pub stop_signal: Arc<Mutex<bool>>,+ pub stop_signal: Arc<AtomicBool>,}unsafe impl Send for InProgressRecording {}unsafe impl Sync for InProgressRecording {}pub struct CompletedRecording {+ pub id: String,pub recording_dir: PathBuf,pub display_output_path: PathBuf,pub camera_output_path: Option<PathBuf>,@@ -144,7 +138,8 @@ impl InProgressRecording {eprintln!("Error while stopping recording: {error}");}- *self.stop_signal.lock().await = true;+ self.stop_signal+ .store(true, std::sync::atomic::Ordering::Relaxed);if FLAGS.record_mouse {// Save mouse events to files@@ -163,6 +158,7 @@ impl InProgressRecording {meta.save_for_project();CompletedRecording {+ id: self.id,recording_dir: self.recording_dir,display_output_path: self.display_output_path,camera_output_path: self.camera_output_path,@@ -197,6 +193,7 @@ impl InProgressRecording {}pub async fn start(+ id: String,recording_dir: PathBuf,recording_options: &RecordingOptions,camera_feed: Option<&CameraFeed>,@@ -273,118 +270,13 @@ pub async fn start(let mut pipeline = pipeline_builder.build().await?;pipeline.play().await?;- let stop_signal = Arc::new(Mutex::new(false));-- let (mouse_moves, mouse_clicks) = {- let (move_tx, move_rx) = oneshot::channel();- let (click_tx, click_rx) = oneshot::channel();-- let stop_signal = stop_signal.clone();- let cursors_dir = cursors_dir.clone();- tokio::spawn(async move {- let device_state = DeviceState::new();- let mut last_mouse_state = device_state.get_mouse();- let start_time = Instant::now();-- let mut moves = vec![];- let mut clicks = vec![];- let mut cursor_images = HashMap::new();- let mut seen_cursor_data: HashMap<Vec<u8>, String> = HashMap::new();- let mut next_cursor_id = 0;-- // Create cursors directory if it doesn't exist- std::fs::create_dir_all(&cursors_dir).unwrap();-- while !*stop_signal.lock().await {- let mouse_state = device_state.get_mouse();- let elapsed = start_time.elapsed().as_secs_f64() * 1000.0;- let unix_time = chrono::Utc::now().timestamp_millis() as f64;-- let cursor_data = get_cursor_image_data();- let cursor_id = if let Some(data) = cursor_data {- // Check if we've seen this cursor data before- if let Some(existing_id) = seen_cursor_data.get(&data) {- existing_id.clone()- } else {- // New cursor data - save it- let cursor_id = next_cursor_id.to_string();- let filename = format!("cursor_{}.png", cursor_id);- let cursor_path = cursors_dir.join(&filename);-- println!("Saving new cursor image to: {:?}", cursor_path);-- if let Ok(image) = image::load_from_memory(&data) {- // Convert to RGBA- let rgba_image = image.into_rgba8();- if let Err(e) = rgba_image.save(&cursor_path) {- eprintln!("Failed to save cursor image: {}", e);- } else {- println!("Successfully saved cursor image {}", cursor_id);- cursor_images.insert(cursor_id.clone(), filename.clone());- seen_cursor_data.insert(data, cursor_id.clone());- next_cursor_id += 1;- }- }- cursor_id- }- } else {- "default".to_string()- };-- if mouse_state.coords != last_mouse_state.coords {- let mouse_event = CursorEvent {- active_modifiers: vec![],- cursor_id: cursor_id.clone(),- process_time_ms: elapsed,- unix_time_ms: unix_time,- x: (mouse_state.coords.0 as f64 - screen_bounds.x) / screen_bounds.width,- y: (mouse_state.coords.1 as f64 - screen_bounds.y) / screen_bounds.height,- };- moves.push(mouse_event);- }-- // cursor 0 doesn't do anything- if mouse_state.button_pressed[1] && !last_mouse_state.button_pressed[1] {- let mouse_event = CursorEvent {- active_modifiers: vec![],- cursor_id,- process_time_ms: elapsed,- unix_time_ms: unix_time,- x: (mouse_state.coords.0 as f64 - screen_bounds.x) / screen_bounds.width,- y: (mouse_state.coords.1 as f64 - screen_bounds.y) / screen_bounds.height,- };- clicks.push(mouse_event);- }+ let stop_signal = Arc::new(AtomicBool::new(false));- last_mouse_state = mouse_state;- tokio::time::sleep(Duration::from_millis(10)).await;- }-- // Save cursor data to cursor.json- let cursor_data = CursorData {- clicks: clicks.clone(),- moves: moves.clone(),- cursor_images,- };-- let cursor_json_path = content_dir.join("cursor.json");- println!("Saving cursor data to: {:?}", cursor_json_path);- if let Ok(mut file) = File::create(&cursor_json_path) {- if let Err(e) = serde_json::to_writer_pretty(&mut file, &cursor_data) {- eprintln!("Failed to save cursor data: {}", e);- } else {- println!("Successfully saved cursor data");- }- }-- move_tx.send(moves).unwrap();- click_tx.send(clicks).unwrap();- });-- (move_rx, click_rx)- };+ let (mouse_moves, mouse_clicks) =+ spawn_cursor_recorder(stop_signal.clone(), screen_bounds, content_dir, cursors_dir);Ok(InProgressRecording {+ id,segments: vec![SystemTime::now().duration_since(UNIX_EPOCH).unwrap()@@ -400,50 +292,3 @@ pub async fn start(stop_signal,})}--#[cfg(windows)]-fn get_cursor_image_data() -> Option<Vec<u8>> {- todo!()-}--#[cfg(target_os = "macos")]-fn get_cursor_image_data() -> Option<Vec<u8>> {- autoreleasepool(|| {- let nscursor_class = match Class::get("NSCursor") {- Some(cls) => cls,- None => return None,- };-- unsafe {- // Get the current system cursor- let current_cursor: id = msg_send![nscursor_class, currentSystemCursor];- if current_cursor == nil {- return None;- }-- // Get the image of the cursor- let cursor_image: id = msg_send![current_cursor, image];- if cursor_image == nil {- return None;- }-- // Get the TIFF representation of the image- let image_data: id = msg_send![cursor_image, TIFFRepresentation];- if image_data == nil {- return None;- }-- // Get the length of the data- let length: NSUInteger = msg_send![image_data, length];-- // Get the bytes of the data- let bytes: *const u8 = msg_send![image_data, bytes];-- // Copy the data into a Vec<u8>- let slice = std::slice::from_raw_parts(bytes, length as usize);- let data = slice.to_vec();-- Some(data)- }- })-}diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 3fe5937e2..bc63f872a 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -394,7 +394,7 @@ export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean;export type HotkeyAction = "startRecording" | "stopRecording" | "restartRecording" | "takeScreenshot"export type HotkeysConfiguration = { show: boolean }export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } }-export type InProgressRecording = { recordingDir: string; displaySource: ScreenCaptureTarget; segments: number[] }+export type InProgressRecording = { id: string; recordingDir: string; displaySource: ScreenCaptureTarget; segments: number[] }export type JsonValue<T> = [T]export type NewNotification = { title: string; body: string; is_error: boolean }export type NewRecordingAdded = { path: string }diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rsindex b7a0a37a1..66b4c16c5 100644--- a/crates/project/src/lib.rs+++ b/crates/project/src/lib.rs@@ -89,56 +89,49 @@ impl RecordingMeta {}pub fn cursor_data(&self) -> CursorData {- if let Some(cursor_path) = &self.cursor {- let full_path = self.project_path.join(cursor_path);- println!("Loading cursor data from: {:?}", full_path);-- // Try to load the cursor data- match CursorData::load_from_file(&full_path) {- Ok(mut data) => {- // If cursor_images is empty but cursor files exist, populate it- if data.cursor_images.is_empty() {- let cursors_dir = self.project_path.join("content").join("cursors");- if cursors_dir.exists() {- println!("Scanning cursors directory: {:?}", cursors_dir);- if let Ok(entries) = std::fs::read_dir(&cursors_dir) {- for entry in entries {- if let Ok(entry) = entry {- let filename = entry.file_name();- let filename_str = filename.to_string_lossy();- if filename_str.starts_with("cursor_")- && filename_str.ends_with(".png")- {- // Extract cursor ID from filename (cursor_X.png -> X)- if let Some(id) = filename_str- .strip_prefix("cursor_")- .and_then(|s| s.strip_suffix(".png"))- {- println!(- "Found cursor image: {} -> {}",- id, filename_str- );- data.cursor_images.insert(- id.to_string(),- filename.to_string_lossy().into_owned(),- );- }- }- }- }- }- println!("Found {} cursor images", data.cursor_images.len());+ let Some(cursor_path) = &self.cursor else {+ return CursorData::default();+ };++ let full_path = self.project_path.join(cursor_path);+ println!("Loading cursor data from: {:?}", full_path);++ // Try to load the cursor data+ let mut data = match CursorData::load_from_file(&full_path) {+ Ok(data) => data,+ Err(e) => {+ eprintln!("Failed to load cursor data: {}", e);+ return CursorData::default();+ }+ };++ // If cursor_images is empty but cursor files exist, populate it+ let cursors_dir = self.project_path.join("content").join("cursors");+ if data.cursor_images.is_empty() && cursors_dir.exists() {+ println!("Scanning cursors directory: {:?}", cursors_dir);+ if let Ok(entries) = std::fs::read_dir(&cursors_dir) {+ for entry in entries {+ let Ok(entry) = entry else {+ continue;+ };++ let filename = entry.file_name();+ let filename_str = filename.to_string_lossy();+ if filename_str.starts_with("cursor_") && filename_str.ends_with(".png") {+ // Extract cursor ID from filename (cursor_X.png -> X)+ if let Some(id) = filename_str+ .strip_prefix("cursor_")+ .and_then(|s| s.strip_suffix(".png"))+ {+ println!("Found cursor image: {} -> {}", id, filename_str);+ data.cursor_images+ .insert(id.to_string(), filename.to_string_lossy().into_owned());}}- data- }- Err(e) => {- eprintln!("Failed to load cursor data: {}", e);- CursorData::default()}}- } else {- CursorData::default()+ println!("Found {} cursor images", data.cursor_images.len());}+ data}}