Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix cursor offset + add zoom segment auto-generation
Brendan Allan7d1f7ad956f4
diff --git a/Cargo.lock b/Cargo.lockindex 7481af89d..6c4bbb04e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2044,9 +2044,9 @@ dependencies = [[[package]]name = "fastrand"-version = "2.1.0"+version = "2.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a"+checksum = "e8c02a5121d4ea3eb16a80748c74f5549a5665e4c21333c6098f283870fbdea6"[[package]]name = "fdeflate"@@ -3464,9 +3464,9 @@ dependencies = [[[package]]name = "libc"-version = "0.2.158"+version = "0.2.161"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439"+checksum = "8e9489c2807c139ffd9c1794f4af0ebe86a828db53ecdc7fea2111d0fed085d1"[[package]]name = "libdbus-sys"@@ -5553,9 +5553,9 @@ dependencies = [[[package]]name = "rustix"-version = "0.38.34"+version = "0.38.39"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f"+checksum = "375116bee2be9ed569afe2154ea6a99dfdffd257f533f187498c2a8f5feaf4ee"dependencies = ["bitflags 2.6.0","errno",@@ -6956,9 +6956,9 @@ dependencies = [[[package]]name = "tempfile"-version = "3.12.0"+version = "3.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "04cbcdd0c794ebb0d4cf35e88edd2f7d2c4c3e9a5a6dab322839b321c6a87a64"+checksum = "f0f2c9fc62d0beef6951ccffd757e241266a2c833136efbe35af6cd2567dca5b"dependencies = ["cfg-if 1.0.0","fastrand",diff --git a/Cargo.toml b/Cargo.tomlindex 5c60a3b39..7ca7bf3b1 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,15 +1,6 @@[workspace]resolver = "2"-members = [- "apps/desktop/src-tauri",- "crates/rendering",- "crates/ffmpeg",- "crates/media",- "crates/utils",- "crates/project",- "crates/editor",- "crates/flags",-]+members = ["apps/desktop/src-tauri", "crates/*"][workspace.dependencies]anyhow = "1.0.86"diff --git a/apps/desktop/src-tauri/src/cursor.rs b/apps/desktop/src-tauri/src/cursor.rsindex 5ce6cea79..f5d67d695 100644--- a/apps/desktop/src-tauri/src/cursor.rs+++ b/apps/desktop/src-tauri/src/cursor.rs@@ -7,7 +7,7 @@ use std::{};use cap_media::platform::Bounds;-use cap_project::{CursorData, CursorEvent};+use cap_project::{CursorClickEvent, CursorData, CursorMoveEvent};use device_query::{DeviceQuery, DeviceState};use tokio::sync::oneshot;@@ -17,8 +17,8 @@ pub fn spawn_cursor_recorder(content_dir: PathBuf,cursors_dir: PathBuf,) -> (- oneshot::Receiver<Vec<CursorEvent>>,- oneshot::Receiver<Vec<CursorEvent>>,+ oneshot::Receiver<Vec<CursorMoveEvent>>,+ oneshot::Receiver<Vec<CursorClickEvent>>,) {let (move_tx, move_rx) = oneshot::channel();let (click_tx, click_rx) = oneshot::channel();@@ -74,7 +74,7 @@ pub fn spawn_cursor_recorder(};if mouse_state.coords != last_mouse_state.coords {- let mouse_event = CursorEvent {+ let mouse_event = CursorMoveEvent {active_modifiers: vec![],cursor_id: cursor_id.clone(),process_time_ms: elapsed,@@ -85,11 +85,20 @@ pub fn spawn_cursor_recorder(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 {+ for (num, &pressed) in mouse_state.button_pressed.iter().enumerate() {+ let Some(prev) = last_mouse_state.button_pressed.get(num) else {+ continue;+ };++ if pressed == *prev {+ continue;+ }++ let mouse_event = CursorClickEvent {+ down: pressed,active_modifiers: vec![],- cursor_id,+ cursor_num: num as u8,+ 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,diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex e91f0bb2d..67105d4d4 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -27,8 +27,9 @@ use cap_media::{};use cap_project::{ProjectConfiguration, RecordingMeta, SharingMeta, TimelineConfiguration, TimelineSegment,+ ZoomSegment,};-use cap_rendering::ProjectUniforms;+use cap_rendering::{ProjectUniforms, ZOOM_DURATION};use cap_utils::create_named_pipe;// use display::{list_capture_windows, Bounds, CaptureTarget, FPS};use general_settings::GeneralSettingsStore;@@ -65,12 +66,6 @@ use tokio::{use upload::{get_s3_config, upload_image, upload_video, S3UploadMeta};use windows::{CapWindow, CapWindowId};-#[cfg(target_os = "macos")]-use cocoa::foundation::{NSBundle, NSString};--#[cfg(target_os = "macos")]-use tauri_nspanel::ManagerExt;-#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]#[serde(rename_all = "camelCase")]pub struct RecordingOptions {@@ -471,25 +466,64 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<.ok();let recordings = ProjectRecordings::new(&recording.meta);+ let max_duration = recordings.duration();let config = {- let mut segments = vec![];- let mut passed_duration = 0.0;-- for i in (0..recording.segments.len()).step_by(2) {- let start = passed_duration;- passed_duration += recording.segments[i + 1] - recording.segments[i];- segments.push(TimelineSegment {- start,- end: passed_duration.min(recordings.duration()),- timescale: 1.0,- });- }+ let segments = {+ let mut segments = vec![];+ let mut passed_duration = 0.0;++ for i in (0..recording.segments.len()).step_by(2) {+ let start = passed_duration;+ passed_duration += recording.segments[i + 1] - recording.segments[i];+ segments.push(TimelineSegment {+ start,+ end: passed_duration.min(recordings.duration()),+ timescale: 1.0,+ });+ }+ segments+ };++ let zoom_segments = {+ let mut segments = vec![];++ const ZOOM_SEGMENT_AFTER_CLICK_PADDING: f64 = 1.5;++ for click in &recording.cursor_data.clicks {+ if segments.last().is_none() {+ segments.push(ZoomSegment {+ start: (click.process_time_ms / 1000.0 - (ZOOM_DURATION + 0.2)).max(0.0),+ end: click.process_time_ms / 1000.0 + ZOOM_SEGMENT_AFTER_CLICK_PADDING,+ amount: 2.0,+ });+ } else {+ let last_segment = segments.last_mut().unwrap();++ if click.down {+ let time = click.process_time_ms / 1000.0;++ if last_segment.end > time {+ last_segment.end = (time + ZOOM_SEGMENT_AFTER_CLICK_PADDING)+ .min(recordings.duration());+ } else if time < max_duration - ZOOM_DURATION {+ segments.push(ZoomSegment {+ start: (time - ZOOM_DURATION).max(0.0),+ end: time + ZOOM_SEGMENT_AFTER_CLICK_PADDING,+ amount: 2.0,+ });+ }+ }+ }+ }++ segments+ };ProjectConfiguration {timeline: Some(TimelineConfiguration {segments,- zoom_segments: vec![],+ zoom_segments,}),..Default::default()}@@ -1559,6 +1593,7 @@ fn open_editor(app: AppHandle, id: String) {fn close_previous_recordings_window(app: AppHandle) {#[cfg(target_os = "macos")]{+ use tauri_nspanel::ManagerExt;if let Ok(panel) = app.get_webview_panel(&CapWindowId::PrevRecordings.label()) {panel.released_when_closed(true);panel.close();@@ -1569,8 +1604,12 @@ fn close_previous_recordings_window(app: AppHandle) {#[tauri::command(async)]#[specta::specta]fn focus_captures_panel(app: AppHandle) {- if let Ok(panel) = app.get_webview_panel(&CapWindowId::PrevRecordings.label()) {- panel.make_key_window();+ #[cfg(target_os = "macos")]+ {+ use tauri_nspanel::ManagerExt;+ if let Ok(panel) = app.get_webview_panel(&CapWindowId::PrevRecordings.label()) {+ panel.make_key_window();+ }}}diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 868b5e1ed..f4f12b610 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -1,14 +1,12 @@use cap_flags::FLAGS;use cap_media::{encoders::*, feeds::*, filters::*, pipeline::*, sources::*, MediaError};-use cap_project::{CursorEvent, RecordingMeta};-use device_query::{DeviceEvents, DeviceQuery, DeviceState};+use cap_project::{CursorClickEvent, CursorMoveEvent, RecordingMeta};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};@@ -20,13 +18,6 @@ use crate::RecordingOptions;// TODO: Hacky, please fixpub const FPS: u32 = 30;-#[derive(Serialize)]-struct CursorData {- moves: Vec<CursorEvent>,- clicks: Vec<CursorEvent>,- cursor_images: HashMap<String, String>, // Maps cursor ID to filename-}-#[tauri::command(async)]#[specta::specta]pub fn list_capture_screens() -> Vec<CaptureScreen> {@@ -61,9 +52,9 @@ pub struct InProgressRecording {pub display_source: ScreenCaptureTarget,pub segments: Vec<f64>,#[serde(skip)]- pub cursor_moves: oneshot::Receiver<Vec<CursorEvent>>,+ pub cursor_moves: oneshot::Receiver<Vec<CursorMoveEvent>>,#[serde(skip)]- pub cursor_clicks: oneshot::Receiver<Vec<CursorEvent>>,+ pub cursor_clicks: oneshot::Receiver<Vec<CursorClickEvent>>,#[serde(skip)]pub stop_signal: Arc<AtomicBool>,}@@ -80,6 +71,7 @@ pub struct CompletedRecording {pub display_source: ScreenCaptureTarget,pub segments: Vec<f64>,pub meta: RecordingMeta,+ pub cursor_data: cap_project::CursorData,}impl InProgressRecording {@@ -141,18 +133,16 @@ impl InProgressRecording {self.stop_signal.store(true, std::sync::atomic::Ordering::Relaxed);+ let cursor_data = cap_project::CursorData {+ clicks: self.cursor_clicks.await.unwrap(),+ moves: self.cursor_moves.await.unwrap(),+ cursor_images: HashMap::new(), // This will be populated during recording+ };+if FLAGS.record_mouse {// Save mouse events to fileslet mut file = File::create(self.recording_dir.join("cursor.json")).unwrap();- serde_json::to_writer_pretty(- &mut file,- &CursorData {- clicks: self.cursor_clicks.await.unwrap(),- moves: self.cursor_moves.await.unwrap(),- cursor_images: HashMap::new(), // This will be populated during recording- },- )- .unwrap();+ serde_json::to_writer_pretty(&mut file, &cursor_data).unwrap();}meta.save_for_project();@@ -166,6 +156,7 @@ impl InProgressRecording {display_source: self.display_source,segments: self.segments,meta,+ cursor_data,}}diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.jsonindex 3ddeeaec2..880268dec 100644--- a/apps/desktop/src-tauri/tauri.conf.json+++ b/apps/desktop/src-tauri/tauri.conf.json@@ -2,6 +2,7 @@"$schema": "../node_modules/@tauri-apps/cli/schema.json","productName": "Cap - Development","identifier": "so.cap.desktop.dev",+ "mainBinaryName": "Cap - Development","build": {"beforeDevCommand": "node scripts/prepareSidecars.js && pnpm localdev","devUrl": "http://localhost:3001",diff --git a/apps/desktop/src-tauri/tauri.conf.prod.json b/apps/desktop/src-tauri/tauri.conf.prod.jsonindex 4c759bb63..d93375b4b 100644--- a/apps/desktop/src-tauri/tauri.conf.prod.json+++ b/apps/desktop/src-tauri/tauri.conf.prod.json@@ -1,6 +1,7 @@{"$schema": "../node_modules/@tauri-apps/cli/schema.json","productName": "Cap",+ "mainBinaryName": "Cap","identifier": "so.cap.desktop","plugins": {"updater": {diff --git a/apps/desktop/src/routes/editor/Timeline.tsx b/apps/desktop/src/routes/editor/Timeline.tsxindex 4175195b2..52daeb70a 100644--- a/apps/desktop/src/routes/editor/Timeline.tsx+++ b/apps/desktop/src/routes/editor/Timeline.tsx@@ -40,7 +40,6 @@ export function Timeline() {setPreviewTime,history,split,- state,setState,} = useEditorContext();diff --git a/crates/project/src/cursor.rs b/crates/project/src/cursor.rsindex 92996b19d..71ba686ba 100644--- a/crates/project/src/cursor.rs+++ b/crates/project/src/cursor.rs@@ -5,7 +5,7 @@ use std::fs::File;use std::path::Path;#[derive(Serialize, Deserialize, Clone, Type, Debug)]-pub struct CursorEvent {+pub struct CursorMoveEvent {pub active_modifiers: Vec<String>,pub cursor_id: String,pub process_time_ms: f64,@@ -14,10 +14,22 @@ pub struct CursorEvent {pub y: f64,}+#[derive(Serialize, Deserialize, Clone, Type, Debug)]+pub struct CursorClickEvent {+ pub active_modifiers: Vec<String>,+ pub cursor_num: u8,+ pub cursor_id: String,+ pub process_time_ms: f64,+ pub unix_time_ms: f64,+ pub down: bool,+ pub x: f64,+ pub y: f64,+}+#[derive(Default, Serialize, Deserialize, Debug, Clone)]pub struct CursorData {- pub clicks: Vec<CursorEvent>,- pub moves: Vec<CursorEvent>,+ pub clicks: Vec<CursorClickEvent>,+ pub moves: Vec<CursorMoveEvent>,pub cursor_images: HashMap<String, String>,}diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex df896095c..1e897da1b 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -12,8 +12,8 @@ use wgpu::util::DeviceExt;use wgpu::{CommandEncoder, COPY_BYTES_PER_ROW_ALIGNMENT};use cap_project::{- AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Crop, CursorData, CursorEvent,- ProjectConfiguration, XY,+ AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Crop, CursorClickEvent,+ CursorData, CursorMoveEvent, ProjectConfiguration, XY,};use std::time::Instant;@@ -430,6 +430,48 @@ impl ProjectUniforms {((width + 1) & !1, (height + 1) & !1)}+ pub fn get_display_offset(+ options: &RenderOptions,+ project: &ProjectConfiguration,+ ) -> Coord<FrameSpace> {+ let output_size = Self::get_output_size(options, project);+ let output_size = XY::new(output_size.0 as f64, output_size.1 as f64);++ let output_aspect = output_size.x as f64 / output_size.y as f64;++ let crop = Self::get_crop(options, project);++ let crop_start =+ Coord::<RawDisplaySpace>::new(XY::new(crop.position.x as f64, crop.position.y as f64));+ let crop_end = Coord::<RawDisplaySpace>::new(XY::new(+ (crop.position.x + crop.size.x) as f64,+ (crop.position.y + crop.size.y) as f64,+ ));++ let cropped_size = crop_end.coord - crop_start.coord;++ let cropped_aspect = cropped_size.x / cropped_size.y;++ let padding = Self::get_padding(options, project);+ let is_height_constrained = cropped_aspect <= output_aspect;++ let available_size = output_size - 2.0 * padding;++ let target_size = if is_height_constrained {+ XY::new(available_size.y * cropped_aspect, available_size.y)+ } else {+ XY::new(available_size.x, available_size.x / cropped_aspect)+ };++ let target_offset = (output_size - target_size) / 2.0;++ Coord::new(if is_height_constrained {+ XY::new(target_offset.x, padding)+ } else {+ XY::new(padding, target_offset.y)+ })+ }+pub fn new(constants: &RenderVideoConstants,project: &ProjectConfiguration,@@ -437,7 +479,6 @@ impl ProjectUniforms {) -> Self {let options = &constants.options;let output_size = Self::get_output_size(options, project);- let output_aspect = output_size.0 as f64 / output_size.1 as f64;let cursor_position = interpolate_cursor_position(&constants.cursor, time);@@ -451,11 +492,9 @@ impl ProjectUniforms {let crop = Self::get_crop(options, project);- let zoom_origin = zoom_origin_uv.to_raw_display_space(XY {- x: options.screen_size.x as f64,- y: options.screen_size.y as f64,- });- let zoom_origin = zoom_origin.to_cropped_display_space(crop);+ let zoom_origin = zoom_origin_uv+ .to_raw_display_space(options)+ .to_cropped_display_space(options, project);let (display, zoom) = {let output_size = XY::new(output_size.0 as f64, output_size.1 as f64);@@ -470,34 +509,13 @@ impl ProjectUniforms {(crop.position.y + crop.size.y) as f64,));- let cropped_size = crop_end.coord - crop_start.coord;+ let display_offset = Self::get_display_offset(options, project);- let cropped_aspect = cropped_size.x / cropped_size.y;-- let padding = Self::get_padding(options, project);- let is_height_constrained = cropped_aspect <= output_aspect;-- let available_size = output_size - 2.0 * padding;-- let target_size = if is_height_constrained {- XY::new(available_size.y * cropped_aspect, available_size.y)- } else {- XY::new(available_size.x, available_size.x / cropped_aspect)- };-- let target_offset = (output_size - target_size) / 2.0;-- let start = Coord::new(if is_height_constrained {- XY::new(target_offset.x, padding)- } else {- XY::new(padding, target_offset.y)- });-- let end = Coord::new(output_size) - start;+ let end = Coord::new(output_size) - display_offset;let screen_scale_origin = zoom_origin- .to_frame_space(start.coord)- .clamp(start.coord, end.coord);+ .to_frame_space(options, project)+ .clamp(display_offset.coord, end.coord);let zoom = Zoom {amount: zoom,@@ -505,7 +523,7 @@ impl ProjectUniforms {// padding: screen_scale_origin,};- let start = zoom.apply_scale(start);+ let start = zoom.apply_scale(display_offset);let end = zoom.apply_scale(end);let target_size = end - start;@@ -605,7 +623,7 @@ pub struct ZoomKeyframe {#[derive(Debug)]pub struct ZoomKeyframes(Vec<ZoomKeyframe>);-const ZOOM_DURATION: f64 = 0.3;+pub const ZOOM_DURATION: f64 = 0.3;impl ZoomKeyframes {pub fn new(config: &ProjectConfiguration) -> Self {@@ -997,18 +1015,9 @@ fn draw_cursor(STANDARD_CURSOR_HEIGHT,];- let position = uniforms.zoom.apply_scale(- cursor_position- .to_raw_display_space(constants.options.screen_size.map(|v| v as f64))- .to_cropped_display_space(ProjectUniforms::get_crop(- &constants.options,- &uniforms.project,- ))- .to_frame_space(XY::new(- uniforms.display.target_bounds[0] as f64,- uniforms.display.target_bounds[1] as f64,- )),- );+ let position = uniforms+ .zoom+ .apply_scale(cursor_position.to_frame_space(&constants.options, &uniforms.project));let cursor_uniforms = CursorUniforms {position: [position.x as f32, position.y as f32, 0.0, 0.0],@@ -1495,7 +1504,7 @@ struct CursorUniforms {_alignment: [f32; 4],}-fn find_cursor_event(cursor: &CursorData, time: f32) -> &CursorEvent {+fn find_cursor_event(cursor: &CursorData, time: f32) -> &CursorMoveEvent {let time_ms = time * 1000.0;let event = cursor@@ -1629,13 +1638,13 @@ struct RawDisplayUVSpace;struct CroppedDisplaySpace;#[derive(Default, Clone, Copy, Debug)]-struct FrameSpace;+pub struct FrameSpace;#[derive(Default, Clone, Copy, Debug)]struct TransformedDisplaySpace;#[derive(Clone, Copy, Debug)]-struct Coord<TSpace> {+pub struct Coord<TSpace> {coord: XY<f64>,space: TSpace,}@@ -1668,20 +1677,40 @@ impl<T> Deref for Coord<T> {}impl Coord<RawDisplayUVSpace> {- fn to_raw_display_space(&self, size: XY<f64>) -> Coord<RawDisplaySpace> {- Coord::new(self.coord * size)+ fn to_raw_display_space(&self, options: &RenderOptions) -> Coord<RawDisplaySpace> {+ Coord::new(self.coord * options.screen_size.map(|v| v as f64))+ }++ fn to_frame_space(+ &self,+ options: &RenderOptions,+ project: &ProjectConfiguration,+ ) -> Coord<FrameSpace> {+ self.to_raw_display_space(options)+ .to_cropped_display_space(options, project)+ .to_frame_space(options, project)}}impl Coord<RawDisplaySpace> {- fn to_cropped_display_space(&self, crop: Crop) -> Coord<CroppedDisplaySpace> {+ fn to_cropped_display_space(+ &self,+ options: &RenderOptions,+ project: &ProjectConfiguration,+ ) -> Coord<CroppedDisplaySpace> {+ let crop = ProjectUniforms::get_crop(options, project);Coord::new(self.coord - crop.position.map(|v| v as f64))}}impl Coord<CroppedDisplaySpace> {- fn to_frame_space(&self, padding: XY<f64>) -> Coord<FrameSpace> {- Coord::new(self.coord + padding)+ fn to_frame_space(+ &self,+ options: &RenderOptions,+ project: &ProjectConfiguration,+ ) -> Coord<FrameSpace> {+ let padding = ProjectUniforms::get_display_offset(options, project);+ Coord::new(self.coord + *padding)}}