Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
account for cursor hotspot
Brendan Allanbf2a0f747f49
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 9361e6bd4..1222fea3d 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -245,6 +245,7 @@ export type Crop = { position: XY<number>; size: XY<number> }export type CurrentRecordingChanged = nullexport type CursorAnimationStyle = "regular" | "slow" | "fast"export type CursorConfiguration = { hideWhenIdle: boolean; size: number; type: CursorType; animationStyle: CursorAnimationStyle }+export type CursorMeta = { imagePath: string; hotspot: XY<number> }export type CursorType = "pointer" | "circle"export type Display = { path: string; fps?: number }export type EditorStateChanged = { playhead_position: number }@@ -259,7 +260,7 @@ export type HotkeysConfiguration = { show: boolean }export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } }export type JsonValue<T> = [T]export type MultipleSegment = { display: Display; camera?: CameraMeta | null; audio?: AudioMeta | null; cursor?: string | null }-export type MultipleSegments = { segments: MultipleSegment[]; cursors: { [key in string]: string } }+export type MultipleSegments = { segments: MultipleSegment[]; cursors: { [key in string]: CursorMeta } }export type NewNotification = { title: string; body: string; is_error: boolean }export type NewRecordingAdded = { path: string }export type NewScreenshotAdded = { path: string }diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rsindex c118c67b6..ab2937a18 100644--- a/crates/editor/src/editor_instance.rs+++ b/crates/editor/src/editor_instance.rs@@ -336,8 +336,6 @@ pub async fn create_segments(meta: &RecordingMeta) -> Result<Vec<Segment>, Strin.map(|audio_meta| AudioData::from_file(meta.path(&audio_meta.path)).unwrap()),);- let cursor = Arc::new(s.cursor_data(&meta).into());-let decoders = RecordingSegmentDecoders::new(&meta,SegmentVideoPaths {@@ -350,7 +348,7 @@ pub async fn create_segments(meta: &RecordingMeta) -> Result<Vec<Segment>, StrinOk(vec![Segment {audio,- cursor,+ cursor: Default::default(),decoders,}])}diff --git a/crates/project/src/cursor.rs b/crates/project/src/cursor.rsindex e4a118122..e86c2a46d 100644--- a/crates/project/src/cursor.rs+++ b/crates/project/src/cursor.rs@@ -4,6 +4,8 @@ use std::collections::HashMap;use std::fs::File;use std::path::{Path, PathBuf};+use crate::XY;+#[derive(Serialize, Deserialize, Clone, Type, Debug)]pub struct CursorMoveEvent {pub active_modifiers: Vec<String>,@@ -28,7 +30,13 @@ pub struct CursorClickEvent {#[derive(Default, Serialize, Deserialize, Debug, Clone)]#[serde(transparent)]-pub struct CursorImages(pub HashMap<String, PathBuf>);+pub struct CursorImages(pub HashMap<String, CursorImage>);++#[derive(Default, Serialize, Deserialize, Debug, Clone)]+pub struct CursorImage {+ pub path: PathBuf,+ pub hotspot: XY<f64>,+}#[derive(Default, Serialize, Deserialize, Debug, Clone)]pub struct CursorData {diff --git a/crates/project/src/meta.rs b/crates/project/src/meta.rsindex efb2fc613..100f86d9c 100644--- a/crates/project/src/meta.rs+++ b/crates/project/src/meta.rs@@ -8,7 +8,7 @@ use std::{path::{Path, PathBuf},};-use crate::{CursorData, CursorEvents, CursorImages, ProjectConfiguration};+use crate::{CursorEvents, CursorImage, CursorImages, ProjectConfiguration, XY};#[derive(Debug, Clone, Serialize, Deserialize, Type)]pub struct Display {@@ -85,7 +85,7 @@ impl RecordingMeta {}#[derive(Debug, Clone, Serialize, Deserialize, Type)]-#[serde(untagged)]+#[serde(untagged, rename_all = "camelCase")]pub enum Content {SingleSegment {#[serde(flatten)]@@ -128,6 +128,7 @@ impl Content {}#[derive(Debug, Clone, Serialize, Deserialize, Type)]+#[serde(rename_all = "camelCase")]pub struct SingleSegment {pub display: Display,#[serde(default, skip_serializing_if = "Option::is_none")]@@ -139,60 +140,20 @@ pub struct SingleSegment {pub cursor: Option<RelativePathBuf>,}-impl SingleSegment {- pub fn cursor_data(&self, meta: &RecordingMeta) -> CursorData {- let Some(cursor_path) = &self.cursor else {- return CursorData::default();- };-- let full_path = meta.path(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 = meta.path(&RelativePathBuf::from("./cursors"));- if data.cursor_images.0.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.0.insert(id.to_string(), entry.path());- }- }- }- }- println!("Found {} cursor images", data.cursor_images.0.len());- }- data- }-}-#[derive(Debug, Clone, Serialize, Deserialize, Type)]+#[serde(rename_all = "camelCase")]pub struct MultipleSegments {pub segments: Vec<MultipleSegment>,#[serde(default, skip_serializing_if = "HashMap::is_empty")]- #[specta(type = HashMap<String, String>)]- pub cursors: HashMap<String, RelativePathBuf>,+ pub cursors: HashMap<String, CursorMeta>,+}++#[derive(Debug, Clone, Serialize, Deserialize, Type)]+#[serde(rename_all = "camelCase")]+pub struct CursorMeta {+ #[specta(type = String)]+ pub image_path: RelativePathBuf,+ pub hotspot: XY<f64>,}impl MultipleSegments {@@ -200,11 +161,19 @@ impl MultipleSegments {meta.project_path.join(path)}- pub fn cursor_images(&self, meta: &RecordingMeta) -> Result<CursorImages, String> {+ pub fn cursor_images(&self, meta: &RecordingMeta) -> Result<CursorImages, CursorImage> {Ok(CursorImages(self.cursors.iter()- .map(|(k, v)| (k.clone(), meta.path(v)))+ .map(|(k, v)| {+ (+ k.clone(),+ CursorImage {+ path: meta.path(&v.image_path),+ hotspot: v.hotspot,+ },+ )+ }).collect::<_>(),))}diff --git a/crates/recording/src/actor.rs b/crates/recording/src/actor.rsindex f0fdf8fe1..58c22394d 100644--- a/crates/recording/src/actor.rs+++ b/crates/recording/src/actor.rs@@ -478,10 +478,14 @@ async fn stop_recording(},cursors: cursors.into_values()- .map(|(file_name, id)| {+ .map(|cursor| {(- id.to_string(),- RelativePathBuf::from("content/cursors").join(&file_name),+ cursor.id.to_string(),+ CursorMeta {+ image_path: RelativePathBuf::from("content/cursors")+ .join(&cursor.file_name),+ hotspot: cursor.hotspot,+ },)}).collect(),diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rsindex 249945651..65dbb7400 100644--- a/crates/recording/src/cursor.rs+++ b/crates/recording/src/cursor.rs@@ -7,13 +7,20 @@ use std::{};use cap_media::platform::Bounds;-use cap_project::{CursorClickEvent, CursorMoveEvent};+use cap_project::{CursorClickEvent, CursorMoveEvent, XY};use cap_utils::spawn_actor;use device_query::{DeviceQuery, DeviceState};+use image::GenericImageView;use tokio::sync::oneshot;use tracing::{debug, error, info};-pub type Cursors = HashMap<u64, (String, u32)>;+pub struct Cursor {+ pub file_name: String,+ pub id: u32,+ pub hotspot: XY<f64>,+}++pub type Cursors = HashMap<u64, Cursor>;pub struct CursorActorResponse {// pub cursor_images: HashMap<String, Vec<u8>>,@@ -71,29 +78,35 @@ pub fn spawn_cursor_recorder(let cursor_data = get_cursor_image_data();let cursor_id = if let Some(data) = cursor_data {let mut hasher = DefaultHasher::default();- data.hash(&mut hasher);+ data.image.hash(&mut hasher);let id = hasher.finish();// Check if we've seen this cursor data beforeif let Some(existing_id) = response.cursors.get(&id) {- existing_id.1.to_string()+ existing_id.id.to_string()} else {// New cursor data - save itlet cursor_id = response.next_cursor_id.to_string();- let filename = format!("cursor_{}.png", cursor_id);- let cursor_path = cursors_dir.join(&filename);+ let file_name = format!("cursor_{}.png", cursor_id);+ let cursor_path = cursors_dir.join(&file_name);- if let Ok(image) = image::load_from_memory(&data) {+ if let Ok(image) = image::load_from_memory(&data.image) {+ dbg!(image.dimensions());// Convert to RGBAlet rgba_image = image.into_rgba8();if let Err(e) = rgba_image.save(&cursor_path) {error!("Failed to save cursor image: {}", e);} else {- info!("Saved cursor {cursor_id} image to: {:?}", filename);- response- .cursors- .insert(id, (filename.clone(), response.next_cursor_id));+ info!("Saved cursor {cursor_id} image to: {:?}", file_name);+ response.cursors.insert(+ id,+ Cursor {+ file_name,+ id: response.next_cursor_id,+ hotspot: data.hotspot,+ },+ );response.next_cursor_id += 1;}}@@ -149,10 +162,16 @@ pub fn spawn_cursor_recorder(CursorActor { rx, stop_signal }}+#[derive(Debug)]+struct CursorData {+ image: Vec<u8>,+ hotspot: XY<f64>,+}+#[cfg(target_os = "macos")]-fn get_cursor_image_data() -> Option<Vec<u8>> {+fn get_cursor_image_data() -> Option<CursorData> {use cocoa::base::{id, nil};- use cocoa::foundation::NSUInteger;+ use cocoa::foundation::{NSPoint, NSSize, NSUInteger};use objc::rc::autoreleasepool;use objc::runtime::Class;use objc::*;@@ -176,6 +195,9 @@ fn get_cursor_image_data() -> Option<Vec<u8>> {return None;}+ let cursor_size: NSSize = msg_send![cursor_image, size];+ let cursor_hotspot: NSPoint = msg_send![current_cursor, hotSpot];+// Get the TIFF representation of the imagelet image_data: id = msg_send![cursor_image, TIFFRepresentation];if image_data == nil {@@ -192,7 +214,13 @@ fn get_cursor_image_data() -> Option<Vec<u8>> {let slice = std::slice::from_raw_parts(bytes, length as usize);let data = slice.to_vec();- Some(data)+ Some(CursorData {+ image: data,+ hotspot: XY::new(+ cursor_hotspot.x / cursor_size.width,+ cursor_hotspot.y / cursor_size.height,+ ),+ })}})}diff --git a/crates/rendering/src/layers/cursor.rs b/crates/rendering/src/layers/cursor.rsindex f0a795b2b..1fb28e519 100644--- a/crates/rendering/src/layers/cursor.rs+++ b/crates/rendering/src/layers/cursor.rs@@ -2,18 +2,40 @@ use std::collections::HashMap;use bytemuck::{Pod, Zeroable};use cap_project::*;-use wgpu::{include_wgsl, util::DeviceExt};+use wgpu::{include_wgsl, util::DeviceExt, FilterMode};use crate::{frame_pipeline::{FramePipeline, FramePipelineState},zoom::InterpolatedZoom,- Coord, DecodedSegmentFrames, ProjectUniforms, RawDisplayUVSpace, STANDARD_CURSOR_HEIGHT,+ Coord, DecodedSegmentFrames, ProjectUniforms, RawDisplayUVSpace, RenderVideoConstants,+ STANDARD_CURSOR_HEIGHT,};-pub struct CursorLayer;+pub struct CursorLayer {+ uniform_buffer: wgpu::Buffer,+ texture_sampler: wgpu::Sampler,+}impl CursorLayer {+ pub fn new(device: &wgpu::Device) -> Self {+ Self {+ uniform_buffer: device.create_buffer_init(&wgpu::util::BufferInitDescriptor {+ label: Some("Cursor Uniform Buffer"),+ contents: bytemuck::cast_slice(&[CursorUniforms::default()]),+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ }),+ texture_sampler: device.create_sampler(&wgpu::SamplerDescriptor {+ mag_filter: FilterMode::Linear,+ min_filter: FilterMode::Linear,+ mipmap_filter: FilterMode::Linear,+ anisotropy_clamp: 4,+ ..Default::default()+ }),+ }+ }+pub fn render(+ &self,pipeline: &mut FramePipeline,segment_frames: &DecodedSegmentFrames,resolution_base: XY<u32>,@@ -76,7 +98,7 @@ impl CursorLayer {return;};- let cursor_size = cursor_texture.size();+ let cursor_size = cursor_texture.inner.size();let aspect_ratio = cursor_size.width as f32 / cursor_size.height as f32;let cursor_size_percentage = if uniforms.cursor_size <= 0.0 {@@ -113,7 +135,7 @@ impl CursorLayer {let display_size =ProjectUniforms::display_size(&constants.options, &uniforms.project, resolution_base);- let cursor_uniforms = CursorUniforms {+ let uniforms = CursorUniforms {position: [relative_position[0], relative_position[1], 0.0, 0.0],size: [normalized_size[0], normalized_size[1], 0.0, 0.0],output_size: [@@ -130,17 +152,16 @@ impl CursorLayer {last_click_time,velocity,motion_blur_amount,- _alignment: [0.0; 7],+ hotspot: [+ cursor_texture.hotspot.x as f32,+ cursor_texture.hotspot.y as f32,+ ],+ _alignment: [0.0; 5],};- let cursor_uniform_buffer =- constants- .device- .create_buffer_init(&wgpu::util::BufferInitDescriptor {- label: Some("Cursor Uniform Buffer"),- contents: bytemuck::cast_slice(&[cursor_uniforms]),- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,- });+ constants+ .queue+ .write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&[uniforms]));let cursor_bind_group = constants.device@@ -149,21 +170,19 @@ impl CursorLayer {entries: &[wgpu::BindGroupEntry {binding: 0,- resource: cursor_uniform_buffer.as_entire_binding(),+ resource: self.uniform_buffer.as_entire_binding(),},wgpu::BindGroupEntry {binding: 1,resource: wgpu::BindingResource::TextureView(- &cursor_texture.create_view(&wgpu::TextureViewDescriptor::default()),+ &cursor_texture+ .inner+ .create_view(&wgpu::TextureViewDescriptor::default()),),},wgpu::BindGroupEntry {binding: 2,- resource: wgpu::BindingResource::Sampler(- &constants- .device- .create_sampler(&wgpu::SamplerDescriptor::default()),- ),+ resource: wgpu::BindingResource::Sampler(&self.texture_sampler),},],label: Some("Cursor Bind Group"),@@ -184,7 +203,7 @@ pub struct CursorPipeline {}#[repr(C, align(16))]-#[derive(Debug, Clone, Copy, Pod, Zeroable)]+#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]pub struct CursorUniforms {position: [f32; 4],size: [f32; 4],@@ -194,7 +213,8 @@ pub struct CursorUniforms {last_click_time: f32,velocity: [f32; 2],motion_blur_amount: f32,- _alignment: [f32; 7],+ hotspot: [f32; 2],+ _alignment: [f32; 5],}pub fn find_cursor_event(cursor: &CursorEvents, time: f32) -> &CursorMoveEvent {diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex 77b7285ed..8572322e7 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -262,6 +262,11 @@ pub fn get_duration(}}+pub struct CursorTexture {+ inner: wgpu::Texture,+ hotspot: XY<f64>,+}+pub struct RenderVideoConstants {pub _instance: wgpu::Instance,pub _adapter: wgpu::Adapter,@@ -269,7 +274,7 @@ pub struct RenderVideoConstants {pub device: wgpu::Device,pub options: RenderOptions,composite_video_frame_pipeline: CompositeVideoFramePipeline,- pub cursor_textures: HashMap<String, wgpu::Texture>,+ pub cursor_textures: HashMap<String, CursorTexture>,cursor_pipeline: CursorPipeline,gradient_or_color_pipeline: GradientOrColorPipeline,image_background_pipeline: ImageBackgroundPipeline,@@ -277,6 +282,7 @@ pub struct RenderVideoConstants {background_textures: std::sync::Arc<tokio::sync::RwLock<HashMap<String, wgpu::Texture>>>,screen_frame: (wgpu::Texture, wgpu::TextureView),camera_frame: Option<(wgpu::Texture, wgpu::TextureView)>,+ cursor_layer: CursorLayer,}impl RenderVideoConstants {@@ -360,6 +366,7 @@ impl RenderVideoConstants {Ok(Self {_instance: instance,_adapter: adapter,+ cursor_layer: CursorLayer::new(&device),device,queue,options,@@ -379,7 +386,7 @@ impl RenderVideoConstants {device: &wgpu::Device,queue: &wgpu::Queue,meta: &RecordingMeta,- ) -> HashMap<String, wgpu::Texture> {+ ) -> HashMap<String, CursorTexture> {println!("Starting to load cursor textures");println!("Project path: {:?}", meta.project_path);// println!("Cursor images to load: {:?}", cursor.cursor_images);@@ -391,21 +398,25 @@ impl RenderVideoConstants {println!("Cursors directory: {:?}", cursors_dir);let cursor_images = match &meta.content {- Content::SingleSegment { segment } => segment.cursor_data(meta).cursor_images,+ Content::SingleSegment { .. } => Default::default(),Content::MultipleSegments { inner } => inner.cursor_images(meta).unwrap_or_default(),};- for (cursor_id, path) in &cursor_images.0 {- println!("Loading cursor image: {} -> {}", cursor_id, path.display());+ for (cursor_id, cursor) in &cursor_images.0 {+ println!(+ "Loading cursor image: {} -> {}",+ cursor_id,+ cursor.path.display()+ );- println!("Full cursor path: {:?}", path);+ println!("Full cursor path: {:?}", cursor);- if !path.exists() {- println!("Cursor image file does not exist: {:?}", path);+ if !cursor.path.exists() {+ println!("Cursor image file does not exist: {:?}", cursor);continue;}- match image::open(&path) {+ match image::open(&cursor.path) {Ok(img) => {let dimensions = img.dimensions();println!(@@ -451,11 +462,21 @@ impl RenderVideoConstants {},);- textures.insert(cursor_id.clone(), texture);+ textures.insert(+ cursor_id.clone(),+ CursorTexture {+ inner: texture,+ hotspot: cursor.hotspot,+ },+ );println!("Successfully loaded cursor texture: {}", cursor_id);}Err(e) => {- println!("Failed to load cursor image {}: {}", path.display(), e);+ println!(+ "Failed to load cursor image {}: {}",+ cursor.path.display(),+ e+ );// Don't return error, just skip this cursor imagecontinue;}@@ -930,6 +951,8 @@ impl<'a> FrameRenderer<'a> {}}+// TODO: reuse as many resources as possible+// https://github.com/gfx-rs/wgpu/wiki/Encapsulating-Graphics-Workasync fn produce_frame(constants: &RenderVideoConstants,segment_frames: DecodedSegmentFrames,@@ -954,7 +977,7 @@ async fn produce_frame(DisplayLayer::render(&mut pipeline, &segment_frames);- CursorLayer::render(+ constants.cursor_layer.render(&mut pipeline,&segment_frames,resolution_base,diff --git a/crates/rendering/src/shaders/cursor.wgsl b/crates/rendering/src/shaders/cursor.wgslindex e251e8183..bdc8b6ee1 100644--- a/crates/rendering/src/shaders/cursor.wgsl+++ b/crates/rendering/src/shaders/cursor.wgsl@@ -12,6 +12,7 @@ struct Uniforms {last_click_time: f32,velocity: vec2<f32>,motion_blur_amount: f32,+ hotspot: vec2<f32>,_alignment: vec4<f32>,};@@ -40,13 +41,10 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {vec2<f32>(1.0, 1.0));- let pos = positions[vertex_index];+ let pos = positions[vertex_index] - uniforms.hotspot;let size = uniforms.size.xy;let screen_pos = uniforms.position.xy;- // Calculate click animation scale factor- let time_since_click = uniforms.last_click_time;-let scaled_size = size * uniforms.cursor_size;// Calculate final position - centered around cursor position