Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Cursor position improvements (#845)

Oscar Beaumont16da7ad57500
diff --git a/Cargo.lock b/Cargo.lock
index 4c1aad0f2..93e190e85 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -960,10 +960,12 @@ name = "cap-cursor-info"
version = "0.0.0"
dependencies = [
"hex",
- "image",
"objc2 0.6.1",
"objc2-app-kit",
+ "serde",
"sha2",
+ "specta",
+ "strum",
"windows 0.60.0",
]
@@ -1213,6 +1215,7 @@ dependencies = [
name = "cap-project"
version = "0.1.0"
dependencies = [
+ "cap-cursor-info",
"either",
"log",
"relative-path",
@@ -1227,6 +1230,7 @@ name = "cap-recording"
version = "0.1.0"
dependencies = [
"cap-cursor-capture",
+ "cap-cursor-info",
"cap-displays",
"cap-flags",
"cap-media",
diff --git a/apps/desktop/src/components/Toggle.tsx b/apps/desktop/src/components/Toggle.tsx
index 5fd05b16b..85a6523e5 100644
--- a/apps/desktop/src/components/Toggle.tsx
+++ b/apps/desktop/src/components/Toggle.tsx
@@ -8,7 +8,7 @@ const toggleControlStyles = cva(
variants: {
size: {
sm: "w-9 h-[1.25rem] p-[0.125rem]",
- md: "w-11 h-[1.4rem] p-[0.125rem]",
+ md: "w-11 h-[1.5rem] p-[0.125rem]",
lg: "w-14 h-[1.75rem] p-[0.1875rem]",
},
},
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 9b072346a..600099367 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -335,7 +335,7 @@ export type CurrentRecordingChanged = null
export type CurrentRecordingTarget = { window: { id: number; bounds: Bounds } } | { screen: { id: number } } | { area: { screen: number; bounds: Bounds } }
export type CursorAnimationStyle = "regular" | "slow" | "fast"
export type CursorConfiguration = { hide?: boolean; hideWhenIdle: boolean; size: number; type: CursorType; animationStyle: CursorAnimationStyle; tension: number; mass: number; friction: number; raw?: boolean; motionBlur?: number; useSvg?: boolean }
-export type CursorMeta = { imagePath: string; hotspot: XY<number>; hash?: string | null }
+export type CursorMeta = { imagePath: string; hotspot: XY<number>; shape?: string | null }
export type CursorType = "pointer" | "circle"
export type Cursors = { [key in string]: string } | { [key in string]: CursorMeta }
export type DeviceOrModelID = { DeviceID: string } | { ModelID: ModelIDType }
diff --git a/crates/cursor-info/Cargo.toml b/crates/cursor-info/Cargo.toml
index b604feab2..ff60f499c 100644
--- a/crates/cursor-info/Cargo.toml
+++ b/crates/cursor-info/Cargo.toml
@@ -4,20 +4,25 @@ version = "0.0.0"
edition = "2024"
publish = false
-[dev-dependencies]
-hex = "0.4.3"
-image = "0.25.6"
-sha2 = "0.10.9"
-
-[target.'cfg(target_os = "macos")'.dev-dependencies]
-objc2-app-kit = "0.3.1"
-objc2 = "0.6.1"
+[dependencies]
+serde = { version = "1.0.219", features = ["derive"] }
+specta = { workspace = true, features = ["derive"] }
+strum = { version = "0.27.2", features = ["derive"] }
-[target.'cfg(target_os= "windows")'.dev-dependencies]
+[target.'cfg(target_os= "windows")'.dependencies]
windows = { workspace = true, features = [
"Win32_Graphics_Gdi",
"Win32_UI_WindowsAndMessaging",
] }
+[dev-dependencies]
+hex = "0.4"
+sha2 = "0.10"
+
+[target.'cfg(target_os = "macos")'.dev-dependencies]
+objc2 = "0.6"
+objc2-app-kit = { version = "0.3.0", features = ["NSCursor", "NSApplication"] }
+
+
[lints]
workspace = true
diff --git a/crates/cursor-info/README.md b/crates/cursor-info/README.md
new file mode 100644
index 000000000..3bef7782f
--- /dev/null
+++ b/crates/cursor-info/README.md
@@ -0,0 +1,189 @@
+# Cap Cursor Info
+
+A cross-platform Rust crate for detecting cursor shapes and providing accurate cursor assets with hotspot information.
+
+## Features
+
+- πŸ–±οΈ **Cross-platform cursor detection** - Support for macOS and Windows
+- 🎯 **Accurate hotspot information** - Precise cursor positioning data
+- 🎨 **High-quality SVG assets** - Scalable cursor graphics for all supported shapes
+- πŸ” **Real-time cursor monitoring** - Track cursor changes as they happen
+- πŸ“¦ **Serialization support** - Built-in serde and specta support
+- πŸ› οΈ **Development tools** - Interactive viewer and CLI monitoring
+
+## Installation
+
+Add this to your `Cargo.toml`:
+
+```toml
+[dependencies]
+cap-cursor-info = "0.0.0"
+```
+
+### Platform-specific dependencies
+
+The crate automatically includes platform-specific dependencies:
+
+- **macOS**: Uses `objc2` and `objc2-app-kit` for cursor detection
+- **Windows**: Uses `windows` crate for Win32 API integration
+
+## Usage
+
+### Basic Usage
+
+```rust
+use cap_cursor_info::{CursorShape, CursorShapeMacOS, CursorShapeWindows};
+
+// Create a cursor shape
+let cursor = CursorShape::MacOS(CursorShapeMacOS::Arrow);
+
+// Resolve to get SVG asset and hotspot
+if let Some(resolved) = cursor.resolve() {
+ println!("SVG: {}", resolved.raw);
+ println!("Hotspot: ({}, {})", resolved.hotspot.0, resolved.hotspot.1);
+}
+
+// Display cursor information
+println!("Cursor: {}", cursor); // Output: "MacOS|Arrow"
+```
+
+### Platform-specific Detection
+
+#### macOS
+
+```rust
+#[cfg(target_os = "macos")]
+use cap_cursor_info::CursorShapeMacOS;
+
+// Detect cursor from hash (macOS uses image hashing)
+let hash = "de2d1f4a81e520b65fd1317b845b00a1c51a4d1f71cca3cd4ccdab52b98d1ac9";
+if let Some(cursor) = CursorShapeMacOS::from_hash(hash) {
+ println!("Detected cursor: {:?}", cursor);
+}
+```
+
+#### Windows
+
+```rust
+#[cfg(target_os = "windows")]
+use cap_cursor_info::CursorShape;
+use windows::Win32::UI::WindowsAndMessaging::HCURSOR;
+
+// Convert from Windows HCURSOR
+let hcursor: HCURSOR = get_current_cursor(); // Your implementation
+if let Ok(cursor) = CursorShape::try_from(&hcursor) {
+ println!("Detected cursor: {}", cursor);
+}
+```
+
+### Serialization
+
+The crate supports serde serialization:
+
+```rust
+use cap_cursor_info::CursorShape;
+use serde_json;
+
+let cursor = CursorShape::MacOS(CursorShapeMacOS::Arrow);
+let json = serde_json::to_string(&cursor).unwrap();
+println!("{}", json); // "MacOS|Arrow"
+
+let deserialized: CursorShape = serde_json::from_str(&json).unwrap();
+```
+
+## Supported Cursors
+
+### macOS Cursors
+
+- `Arrow` - Standard arrow pointer
+- `ContextualMenu` - Context menu indicator
+- `ClosedHand` - Closed hand for dragging
+- `Crosshair` - Precision crosshair
+- `DragCopy` - Copy operation indicator
+- `DragLink` - Link operation indicator
+- `IBeam` - Text selection cursor
+- `IBeamVerticalForVerticalLayout` - Vertical text cursor
+- `OpenHand` - Open hand for grabbable items
+- `OperationNotAllowed` - Prohibited operation
+- `PointingHand` - Clickable link pointer
+- `ResizeDown/Up/Left/Right` - Directional resize cursors
+- `ResizeLeftRight/UpDown` - Bidirectional resize cursors
+
+### Windows Cursors
+
+- `Arrow` - Standard arrow pointer
+- `IBeam` - Text selection cursor
+- `Wait` - Loading/busy indicator
+- `Cross` - Crosshair cursor
+- `UpArrow` - Vertical selection
+- `SizeNWSE/NESW/WE/NS/All` - Various resize cursors
+- `No` - Prohibited operation
+- `Hand` - Clickable link pointer
+- `AppStarting` - Application loading
+- `Help` - Help/question cursor
+- `Pin/Person` - Specialized cursors
+- `Pen` - Drawing/writing cursor
+
+## Development Tools
+
+### Interactive Cursor Viewer
+
+Open `cursors.html` in your browser to:
+- View all cursor assets with accurate scaling
+- See hotspot positions visually
+- Copy hotspot coordinates for development
+- Test cursor appearance on different backgrounds
+
+### CLI Monitoring Tool
+
+Run the example to monitor cursor changes in real-time:
+
+```bash
+cargo run --example cli
+```
+
+This will:
+- Display current cursor information
+- Show hash values (macOS) or handle info (Windows)
+- Update in real-time as you move between applications
+
+## Platform Details
+
+### macOS Implementation
+
+macOS cursor detection uses SHA-256 hashing of the cursor's TIFF image data. This approach is necessary because:
+- `NSCursor` instances cannot be compared directly
+- Cursors are resolution-independent
+- Hash comparison provides reliable identification
+
+### Windows Implementation
+
+Windows cursor detection uses `HCURSOR` handle comparison with a cached lookup table of system cursors loaded at runtime.
+
+## Asset Information
+
+All cursor assets are:
+- **Format**: SVG for scalability
+- **Quality**: High-fidelity reproductions of system cursors
+- **Hotspots**: Precisely measured for accurate positioning
+- **License**: See individual asset licenses in `assets/` directories
+
+### Hotspot Coordinates
+
+Hotspot coordinates are normalized (0.0 to 1.0) relative to the cursor's dimensions:
+- `(0.0, 0.0)` = Top-left corner
+- `(1.0, 1.0)` = Bottom-right corner
+- `(0.5, 0.5)` = Center
+
+## Contributing
+
+We welcome contributions! Please:
+
+1. Test on both macOS and Windows when possible
+2. Include hotspot measurements for new cursor assets
+3. Update the HTML viewer when adding new cursors
+4. Run the CLI example to verify cursor detection
+
+## License
+
+This project is released under the Apple User Agreement for macOS assets. See individual license files in the assets directories for specific terms.
\ No newline at end of file
diff --git a/crates/cursor-info/examples/cli.rs b/crates/cursor-info/examples/cli.rs
index 9047c9c60..2d9b3f744 100644
--- a/crates/cursor-info/examples/cli.rs
+++ b/crates/cursor-info/examples/cli.rs
@@ -1,5 +1,6 @@
use std::collections::HashMap;
+use cap_cursor_info::{CursorShape, CursorShapeMacOS, CursorShapeWindows};
use sha2::{Digest, Sha256};
fn main() {
@@ -54,7 +55,7 @@ fn run() {
cursor_lookup.insert(hash, name);
}
- // return;
+ println!("\nStarting cursor monitoring...\n");
loop {
#[allow(deprecated)]
@@ -67,385 +68,52 @@ fn run() {
.as_bytes_unchecked(),
));
- if cursor_lookup.get(&hash).is_none() {
- panic!("Cursor hash '{hash}' not known",);
- };
+ // Try to resolve to CursorShape
+ if let Some(cursor_shape_macos) = CursorShapeMacOS::from_hash(&hash) {
+ let cursor_shape = CursorShape::MacOS(cursor_shape_macos);
+ println!("CursorShape: {} | Hash: {}", cursor_shape, hash);
+ } else {
+ println!("Unknown cursor | Hash: {}", hash);
+ }
- println!(
- "{cursor:?} {hash} {}",
- cursor_lookup.get(&hash).unwrap_or(&"Unknown")
- );
+ std::thread::sleep(std::time::Duration::from_millis(100));
}
};
}
#[cfg(target_os = "windows")]
fn run() {
- use windows::{
- Win32::{
- Foundation::POINT,
- UI::WindowsAndMessaging::{
- CURSORINFO, CURSORINFO_FLAGS, GetCursorInfo, GetIconInfo, HCURSOR, ICONINFO,
- IDC_APPSTARTING, IDC_ARROW, IDC_CROSS, IDC_HAND, IDC_HELP, IDC_IBEAM, IDC_NO,
- IDC_PERSON, IDC_PIN, IDC_SIZEALL, IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE,
- IDC_SIZEWE, IDC_UPARROW, IDC_WAIT, LoadCursorW,
- },
- },
- core::PCWSTR,
+ use windows::Win32::{
+ Foundation::POINT,
+ UI::WindowsAndMessaging::{CURSORINFO, CURSORINFO_FLAGS, GetCursorInfo, HCURSOR},
};
- #[inline]
- fn load_cursor(lpcursorname: PCWSTR) -> HCURSOR {
- unsafe { LoadCursorW(None, lpcursorname) }.expect("Failed to load default system cursors")
- }
+ println!("Starting cursor monitoring...\n");
- fn get_icon(hCursor: HCURSOR) -> Vec<u8> {
+ loop {
unsafe {
- // Get icon info
- use windows::Win32::{
- Foundation::HWND,
- Graphics::Gdi::{
- BITMAP, BITMAPINFO, BITMAPINFOHEADER, CreateCompatibleDC, CreateDIBSection,
- DIB_RGB_COLORS, DeleteDC, DeleteObject, GetDC, GetObjectA, ReleaseDC,
- SelectObject,
- },
- UI::WindowsAndMessaging::{DI_NORMAL, DrawIconEx},
- };
- let mut icon_info = ICONINFO::default();
- if GetIconInfo(hCursor, &mut icon_info).is_err() {
- panic!("Error getting icon info");
- }
-
- // Get bitmap info for the cursor
- let mut bitmap = BITMAP::default();
- let bitmap_handle = if !icon_info.hbmColor.is_invalid() {
- icon_info.hbmColor
- } else {
- icon_info.hbmMask
- };
-
- if GetObjectA(
- bitmap_handle,
- std::mem::size_of::<BITMAP>() as i32,
- Some(&mut bitmap as *mut _ as *mut _),
- ) == 0
- {
- // Clean up handles
- if !icon_info.hbmColor.is_invalid() {
- use windows::Win32::Graphics::Gdi::DeleteObject;
-
- DeleteObject(icon_info.hbmColor);
- }
- if !icon_info.hbmMask.is_invalid() {
- use windows::Win32::Graphics::Gdi::DeleteObject;
-
- DeleteObject(icon_info.hbmMask);
- }
- panic!("Error");
- }
-
- // Create DCs
- let screen_dc = GetDC(HWND::default());
- let mem_dc = CreateCompatibleDC(screen_dc);
-
- // Get cursor dimensions
- let width = bitmap.bmWidth;
- let height = if icon_info.hbmColor.is_invalid() && bitmap.bmHeight > 0 {
- // For mask cursors, the height is doubled (AND mask + XOR mask)
- bitmap.bmHeight / 2
- } else {
- bitmap.bmHeight
- };
-
- // Create bitmap info header for 32-bit RGBA
- let bi = BITMAPINFOHEADER {
- biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
- biWidth: width,
- biHeight: -height, // Negative for top-down DIB
- biPlanes: 1,
- biBitCount: 32, // 32-bit RGBA
- biCompression: 0,
- biSizeImage: 0,
- biXPelsPerMeter: 0,
- biYPelsPerMeter: 0,
- biClrUsed: 0,
- biClrImportant: 0,
- };
-
- let bitmap_info = BITMAPINFO {
- bmiHeader: bi,
- bmiColors: [Default::default()],
- };
-
- // Create DIB section
- let mut bits: *mut std::ffi::c_void = std::ptr::null_mut();
- let dib = CreateDIBSection(mem_dc, &bitmap_info, DIB_RGB_COLORS, &mut bits, None, 0);
-
- if dib.is_err() {
- // Clean up
-
- use windows::Win32::Graphics::Gdi::{DeleteDC, ReleaseDC};
- DeleteDC(mem_dc);
- ReleaseDC(HWND::default(), screen_dc);
- if !icon_info.hbmColor.is_invalid() {
- use windows::Win32::Graphics::Gdi::DeleteObject;
-
- DeleteObject(icon_info.hbmColor);
- }
- if !icon_info.hbmMask.is_invalid() {
- use windows::Win32::Graphics::Gdi::DeleteObject;
-
- DeleteObject(icon_info.hbmMask);
- }
- panic!("Error");
- }
-
- let dib = dib.unwrap();
-
- // Select DIB into DC
- let old_bitmap = SelectObject(mem_dc, dib);
-
- // Draw the cursor onto our bitmap with transparency
- if DrawIconEx(
- mem_dc, 0, 0, hCursor, 0, // Use actual size
- 0, // Use actual size
- 0, None, DI_NORMAL,
- )
- .is_err()
- {
- // Clean up
-
- use windows::Win32::Graphics::Gdi::{DeleteDC, DeleteObject, ReleaseDC};
- SelectObject(mem_dc, old_bitmap);
- DeleteObject(dib);
- DeleteDC(mem_dc);
- ReleaseDC(HWND::default(), screen_dc);
- if !icon_info.hbmColor.is_invalid() {
- DeleteObject(icon_info.hbmColor);
- }
- if !icon_info.hbmMask.is_invalid() {
- DeleteObject(icon_info.hbmMask);
- }
- panic!("Error");
- }
-
- // Get image data
- let size = (width * height * 4) as usize;
- let mut image_data = vec![0u8; size];
- unsafe { std::ptr::copy_nonoverlapping(bits, image_data.as_mut_ptr() as *mut _, size) };
-
- // Calculate hotspot
- let mut hotspot_x = if icon_info.fIcon.as_bool() == false {
- icon_info.xHotspot as f64 / width as f64
- } else {
- 0.5
- };
-
- let mut hotspot_y = if icon_info.fIcon.as_bool() == false {
- icon_info.yHotspot as f64 / height as f64
- } else {
- 0.5
+ let mut cursor_info = CURSORINFO {
+ cbSize: std::mem::size_of::<CURSORINFO>() as u32,
+ flags: CURSORINFO_FLAGS(0),
+ hCursor: HCURSOR(std::ptr::null_mut()),
+ ptScreenPos: POINT { x: 0, y: 0 },
};
- // Cleanup
- SelectObject(mem_dc, old_bitmap);
- DeleteObject(dib);
- DeleteDC(mem_dc);
- ReleaseDC(HWND::default(), screen_dc);
- if !icon_info.hbmColor.is_invalid() {
- DeleteObject(icon_info.hbmColor);
- }
- if !icon_info.hbmMask.is_invalid() {
- DeleteObject(icon_info.hbmMask);
- }
-
- // Process the image data to ensure proper alpha channel
- for i in (0..size).step_by(4) {
- // Windows DIB format is BGRA, we need to:
- // 1. Swap B and R channels
- let b = image_data[i];
- image_data[i] = image_data[i + 2]; // B <- R
- image_data[i + 2] = b; // R <- B
-
- // 2. Pre-multiply alpha if needed
- // This is already handled by DrawIconEx
- }
-
- // Convert to RGBA image
- let mut rgba_image =
- image::RgbaImage::from_raw(width as u32, height as u32, image_data).unwrap();
-
- // For text cursor (I-beam), enhance visibility by adding a shadow/outline
- // Check if this is likely a text cursor by examining dimensions and pixels
- let is_text_cursor = width <= 20 && height >= 20 && width <= height / 2;
-
- if is_text_cursor {
- // Add a subtle shadow/outline to make it visible on white backgrounds
- for y in 0..height as u32 {
- for x in 0..width as u32 {
- let pixel = rgba_image.get_pixel(x, y);
- // If this is a solid pixel of the cursor
- if pixel[3] > 200 {
- // If alpha is high (visible pixel)
- // Add shadow pixels around it
- for dx in [-1, 0, 1].iter() {
- for dy in [-1, 0, 1].iter() {
- let nx = x as i32 + dx;
- let ny = y as i32 + dy;
-
- // Skip if out of bounds or same pixel
- if nx < 0
- || ny < 0
- || nx >= width as i32
- || ny >= height as i32
- || (*dx == 0 && *dy == 0)
- {
- continue;
- }
-
- let nx = nx as u32;
- let ny = ny as u32;
-
- let shadow_pixel = rgba_image.get_pixel(nx, ny);
- // Only add shadow where there isn't already content
- if shadow_pixel[3] < 100 {
- rgba_image.put_pixel(nx, ny, image::Rgba([0, 0, 0, 100]));
- }
- }
- }
- }
+ if GetCursorInfo(&mut cursor_info).is_ok() {
+ // Try to convert HCURSOR to CursorShape using the TryFrom implementation
+ match CursorShape::try_from(&cursor_info.hCursor) {
+ Ok(cursor_shape) => {
+ println!("CursorShape: {}", cursor_shape);
}
- }
- }
-
- // Find the bounds of non-transparent pixels to trim whitespace
- let mut min_x = width as u32;
- let mut min_y = height as u32;
- let mut max_x = 0u32;
- let mut max_y = 0u32;
-
- let mut has_content = false;
-
- for y in 0..height as u32 {
- for x in 0..width as u32 {
- let pixel = rgba_image.get_pixel(x, y);
- if pixel[3] > 0 {
- // If pixel has any opacity
- has_content = true;
- min_x = min_x.min(x);
- min_y = min_y.min(y);
- max_x = max_x.max(x);
- max_y = max_y.max(y);
- }
- }
- }
-
- // Only trim if we found content and there's actually whitespace to trim
- if has_content
- && (min_x > 0 || min_y > 0 || max_x < width as u32 - 1 || max_y < height as u32 - 1)
- {
- // Add a small padding (2 pixels) around the content
- let padding = 2u32;
- let trim_min_x = min_x.saturating_sub(padding);
- let trim_min_y = min_y.saturating_sub(padding);
- let trim_max_x = (max_x + padding).min(width as u32 - 1);
- let trim_max_y = (max_y + padding).min(height as u32 - 1);
-
- let trim_width = trim_max_x - trim_min_x + 1;
- let trim_height = trim_max_y - trim_min_y + 1;
-
- // Create a new image with the trimmed dimensions
- let mut trimmed = image::RgbaImage::new(trim_width, trim_height);
-
- // Copy the content to the new image
- for y in 0..trim_height {
- for x in 0..trim_width {
- let src_x = trim_min_x + x;
- let src_y = trim_min_y + y;
- let pixel = rgba_image.get_pixel(src_x, src_y);
- trimmed.put_pixel(x, y, *pixel);
+ Err(_) => {
+ println!("Unknown cursor: {:?}", cursor_info.hCursor);
}
}
-
- // Adjust hotspot coordinates for the trimmed image
- hotspot_x = (hotspot_x * width as f64 - trim_min_x as f64) / trim_width as f64;
- hotspot_y = (hotspot_y * height as f64 - trim_min_y as f64) / trim_height as f64;
-
- trimmed
} else {
- rgba_image
+ println!("Failed to get cursor info");
}
- .to_vec()
- }
- }
-
- let cursors = vec![
- ("IDC_ARROW", load_cursor(IDC_ARROW)),
- ("IDC_IBEAM", load_cursor(IDC_IBEAM)),
- ("IDC_WAIT", load_cursor(IDC_WAIT)),
- ("IDC_CROSS", load_cursor(IDC_CROSS)),
- ("IDC_UPARROW", load_cursor(IDC_UPARROW)),
- ("IDC_SIZENWSE", load_cursor(IDC_SIZENWSE)),
- ("IDC_SIZENESW", load_cursor(IDC_SIZENESW)),
- ("IDC_SIZEWE", load_cursor(IDC_SIZEWE)),
- ("IDC_SIZENS", load_cursor(IDC_SIZENS)),
- ("IDC_SIZEALL", load_cursor(IDC_SIZEALL)),
- ("IDC_NO", load_cursor(IDC_NO)),
- ("IDC_HAND", load_cursor(IDC_HAND)),
- ("IDC_APPSTARTING", load_cursor(IDC_APPSTARTING)),
- ("IDC_HELP", load_cursor(IDC_HELP)),
- ("IDC_PIN", load_cursor(IDC_PIN)),
- ("IDC_PERSON", load_cursor(IDC_PERSON)),
- ("Pen", load_cursor(PCWSTR(32631u16 as _))),
- ("ScrolNS", load_cursor(PCWSTR(32652u16 as _))),
- ("ScrollWE", load_cursor(PCWSTR(32653u16 as _))),
- ("ScrollNSEW", load_cursor(PCWSTR(32654u16 as _))),
- ("ScrollN", load_cursor(PCWSTR(32655u16 as _))),
- ("ScrollS", load_cursor(PCWSTR(32656u16 as _))),
- ("ScrollW", load_cursor(PCWSTR(32657u16 as _))),
- ("ScrollE", load_cursor(PCWSTR(32658u16 as _))),
- ("ScrollNW", load_cursor(PCWSTR(32659u16 as _))),
- ("ScrollNE", load_cursor(PCWSTR(32660u16 as _))),
- ("ScrollSW", load_cursor(PCWSTR(32661u16 as _))),
- ("ScrollSE", load_cursor(PCWSTR(32662u16 as _))),
- ("ArrowCD", load_cursor(PCWSTR(32663u16 as _))),
- ];
-
- let mut cursor_lookup = HashMap::new();
-
- for (name, cursor) in cursors {
- let icon = get_icon(cursor);
- let hash = hex::encode(Sha256::digest(icon));
- println!("{name}: {hash}");
- cursor_lookup.insert(hash, name);
- }
-
- return;
-
- loop {
- let mut cursor_info = CURSORINFO {
- cbSize: std::mem::size_of::<CURSORINFO>() as u32,
- flags: CURSORINFO_FLAGS(0),
- hCursor: Default::default(),
- ptScreenPos: POINT::default(),
- };
-
- if unsafe { GetCursorInfo(&mut cursor_info).is_err() } {
- panic!("Failed to get cursor info")
- }
-
- if cursor_info.hCursor.is_invalid() {
- panic!("Hcursor is invalid")
- }
-
- let trimmed_image = get_icon(cursor_info.hCursor);
-
- let hash = hex::encode(Sha256::digest(&trimmed_image));
-
- if !cursor_lookup.contains_key(&*hash) {
- panic!("Found unknown cursor hash {hash}");
}
- println!("{hash} {}", cursor_lookup.get(&*hash).unwrap_or(&"Unknown"));
+ std::thread::sleep(std::time::Duration::from_millis(100));
}
}
diff --git a/crates/cursor-info/src/lib.rs b/crates/cursor-info/src/lib.rs
index 1806f2767..0c22d8570 100644
--- a/crates/cursor-info/src/lib.rs
+++ b/crates/cursor-info/src/lib.rs
@@ -1,5 +1,15 @@
//! Cap Cursor Info: A crate for getting cursor information, assets and hotspot information.
+mod macos;
+mod windows;
+
+use std::{fmt, str::FromStr};
+
+pub use macos::CursorShapeMacOS;
+use serde::{Deserialize, Serialize};
+use specta::Type;
+pub use windows::CursorShapeWindows;
+
/// Information about a resolved cursor shape
#[derive(Debug, Clone)]
pub struct ResolvedCursor {
@@ -9,222 +19,86 @@ pub struct ResolvedCursor {
pub hotspot: (f64, f64),
}
-impl ResolvedCursor {
- /// Resolve the SVG asset from a given cursor hash
- ///
- /// We hash the cursor's image on macOS as `NSCursor`'s can't be reliably compared.
- /// On Windows we technically don't need to but storing a hash is useful as it means we can modify the cursors,
- /// interpretation without rerecording if we were to support custom cursors or add new OS cursors.
- pub fn from_hash(s: String) -> Option<ResolvedCursor> {
- Some(match s.as_str() {
- //
- // macOS Cursors
- // https://developer.apple.com/documentation/appkit/nscursor
- //
+/// Defines the shape of the cursor
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub enum CursorShape {
+ MacOS(CursorShapeMacOS),
+ Windows(CursorShapeWindows),
+}
+
+impl CursorShape {
+ /// Resolve a cursor identifier to an asset and hotspot information
+ pub fn resolve(&self) -> Option<ResolvedCursor> {
+ match self {
+ CursorShape::MacOS(cursor) => cursor.resolve(),
+ CursorShape::Windows(cursor) => cursor.resolve(),
+ }
+ }
+}
+
+impl fmt::Display for CursorShape {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let kind = match self {
+ CursorShape::MacOS(_) => "MacOS",
+ CursorShape::Windows(_) => "Windows",
+ };
+
+ let variant: &'static str = match self {
+ CursorShape::MacOS(cursor) => cursor.into(),
+ CursorShape::Windows(cursor) => cursor.into(),
+ };
+
+ write!(f, "{kind}|{variant}")
+ }
+}
+
+impl Serialize for CursorShape {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ serializer.serialize_str(&self.to_string())
+ }
+}
+
+impl<'de> Deserialize<'de> for CursorShape {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let string = String::deserialize(deserializer)?;
- // https://developer.apple.com/documentation/appkit/nscursor/arrow
- "de2d1f4a81e520b65fd1317b845b00a1c51a4d1f71cca3cd4ccdab52b98d1ac9" => ResolvedCursor {
- raw: include_str!("../assets/mac/arrow.svg"),
- hotspot: (0.347, 0.33),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/contextualmenu
- "ab26ca862492d41355b711c58544687a799dd7ae14cf161959ca524bbc97c322" => ResolvedCursor {
- raw: include_str!("../assets/mac/contextual_menu.svg"),
- hotspot: (0.278, 0.295),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/closedhand
- "fbb165d4603dd8808b536f45bb74a9a72d9358ad19714b318bb7c06358a7d3c2" => ResolvedCursor {
- raw: include_str!("../assets/mac/closed_hand.svg"),
- hotspot: (0.5, 0.5),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/crosshair
- "c583f776531f4e7b76ea7ba2ab159765e2da11fd63cb897cc10362183859d1d8" => ResolvedCursor {
- raw: include_str!("../assets/mac/crosshair.svg"),
- hotspot: (0.52, 0.51),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/disappearingitem
- "67c369820fbc37af9b59b840c675ca24117ca8dfdccec7702b10894058617951" => return None,
- // https://developer.apple.com/documentation/appkit/nscursor/dragcopy
- "af060876004c8647d82411eeac1bbd613d2991d46794aba16b56c91d3081e128" => ResolvedCursor {
- raw: include_str!("../assets/mac/drag_copy.svg"),
- hotspot: (0.255, 0.1),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/draglink
- "59ac2483461f4ad577a0a6b68be89fe663c36263b583c5f038eee2ae6a5ad98f" => ResolvedCursor {
- raw: include_str!("../assets/mac/drag_link.svg"),
- hotspot: (0.621, 0.309),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/ibeam
- "492dca0bb6751a30607ac728803af992ba69365052b7df2dff1c0dfe463e653c" => ResolvedCursor {
- raw: include_str!("../assets/mac/ibeam.svg"),
- hotspot: (0.525, 0.52),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/openhand
- "3f6a5594a3c9334065944b9c56d9f73fd5fe5f02108a5e28f37e222e770be476" => ResolvedCursor {
- raw: include_str!("../assets/mac/open_hand.svg"),
- hotspot: (0.5, 0.5),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/operationnotallowed
- "37287ef1d097704d3e9d0be9c1049ce1fb6dfabd6d210af0429b1b6ec7084c59" => ResolvedCursor {
- raw: include_str!("../assets/mac/operation_not_allowed.svg"),
- hotspot: (0.24, 0.1),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/pointinghand
- "b0443e9f72e724cb6d94b879bf29c6cb18376d0357c6233e5a7561cf8a9943c6" => ResolvedCursor {
- raw: include_str!("../assets/mac/pointing_hand.svg"),
- hotspot: (0.406, 0.25),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/resizedown
- "3c9bf0ce893b64fe9e4363793b406140d4b3900b7beafa1c409e78cf5a8cf954" => ResolvedCursor {
- raw: include_str!("../assets/mac/resize_down.svg"),
- hotspot: (0.5, 0.5),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/resizeleft
- "50431d8fd537119aefb4c3673f9b9ff00d3cd1d2bf6c35e5dfb09ed40cfd5e7c" => ResolvedCursor {
- raw: include_str!("../assets/mac/resize_left.svg"),
- hotspot: (0.5, 0.5),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/resizeleftright
- "0fdaea89910bcbe34ad0d4d63a6ada2095489df18537bbf54dd0d0769588b381" => ResolvedCursor {
- raw: include_str!("../assets/mac/resize_left_right.svg"),
- hotspot: (0.5, 0.5),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/resizeright
- "e74de88f863f059e5beb27152b2dfc2cd1e8dcc458ce775607765e9a4859667e" => ResolvedCursor {
- raw: include_str!("../assets/mac/resize_right.svg"),
- hotspot: (0.5, 0.5),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/resizeup
- "912ca42451a9624f6fb8c1d53c29c26782b7590d383a66075a6768c4409024d9" => ResolvedCursor {
- raw: include_str!("../assets/mac/resize_up.svg"),
- hotspot: (0.5, 0.5),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/resizeupdown
- "9c93eb53df68d7fd86298ba1eb3e3b32ccd34d168b81a31a6fc4bb79f131331f" => ResolvedCursor {
- raw: include_str!("../assets/mac/resize_up_down.svg"),
- hotspot: (0.5, 0.5),
- },
- // https://developer.apple.com/documentation/appkit/nscursor/ibeamcursorforverticallayout
- "024e1d486a7f16368669d419e69c9a326e464ec1b8ed39645e5c89cb183e03c5" => ResolvedCursor {
- raw: include_str!("../assets/mac/ibeam_vertical.svg"),
- hotspot: (0.51, 0.49),
- },
+ let Some((kind, variant)) = string.split_once("|") else {
+ return Err(serde::de::Error::custom(
+ "Invalid CursorShape. Missing delimiter",
+ ));
+ };
- //
- // Windows Cursors
- // https://learn.microsoft.com/en-us/windows/win32/menurc/about-cursors
- //
+ match kind {
+ "MacOS" => Ok(CursorShape::MacOS(
+ CursorShapeMacOS::from_str(variant).map_err(|err| {
+ serde::de::Error::custom(
+ format!("Failed to parse MacOS cursor variant: {err}",),
+ )
+ })?,
+ )),
+ "Windows" => Ok(CursorShape::Windows(
+ CursorShapeWindows::from_str(variant).map_err(|err| {
+ serde::de::Error::custom(format!(
+ "Failed to parse Windows cursor variant: {err}",
+ ))
+ })?,
+ )),
+ _ => Err(serde::de::Error::custom("Failed to parse CursorShape kind")),
+ }
+ }
+}
- // IDC_ARROW
- "19502718917bb8a86b83ffb168021cf90517b5c5e510c33423060d230c9e2d20" => ResolvedCursor {
- raw: include_str!("../assets/windows/arrow.svg"),
- hotspot: (0.055, 0.085),
- },
- // IDC_IBEAM
- "77cc4cedcf68f3e1d41bfe16c567961b2306c6236b35b966cd3d5c9516565e33" => ResolvedCursor {
- raw: include_str!("../assets/windows/ibeam.svg"),
- hotspot: (0.5, 0.5),
- },
- // IDC_WAIT
- "5991d86a0d4e915dd0cb0fdd9bef3bf37ed6a3b321256fcb5b240db7ac1a6324" => ResolvedCursor {
- raw: include_str!("../assets/windows/wait.svg"),
- hotspot: (0.5, 0.52),
- },
- // IDC_CROSS
- "cd2c775b1a124e4deaed1ed345efae25eb28a9133fc39691555902a2c1d7d578" => ResolvedCursor {
- raw: include_str!("../assets/windows/cross.svg"),
- hotspot: (0.5, 0.5),
- },
- // IDC_UPARROW
- "823d642acdc51ffbc29c2710303606270ed24936daf45215ead531333df102ba" => ResolvedCursor {
- raw: include_str!("../assets/windows/uparrow.svg"),
- hotspot: (0.5, 0.05),
- },
- // IDC_SIZENWSE
- "2daf2a40e4c7ecadec3270fbdb243a12ac22a14bb0b3a08a56b38a38322f9296" => ResolvedCursor {
- raw: include_str!("../assets/windows/idcsizenwse.svg"),
- hotspot: (0.5, 0.5),
- },
- // IDC_SIZENESW
- "47b4d609cb404feae70c7e20b525ac901d1e7a5f1a2e8a240418b3710ee43473" => ResolvedCursor {
- raw: include_str!("../assets/windows/size-nesw.svg"),
- hotspot: (0.5, 0.5),
- },
- // IDC_SIZEWE
- "8a024cf4bec4d58a4c149af2320206088981357312b3d82fbfcc07bee38c71ac" => ResolvedCursor {
- raw: include_str!("../assets/windows/idcsizewe.svg"),
- hotspot: (0.5, 0.5),
- },
- // IDC_SIZENS
- "253b9e5360de1e12561be6a8f84484d4b108fd54d31e7d2c8f3b66d1c71b9880" => ResolvedCursor {
- raw: include_str!("../assets/windows/size-ns.svg"),
- hotspot: (0.5, 0.5),
- },
- // IDC_SIZEALL
- "8066a12792e4e8ef21636e5ade61adaaf0fecc2ffc69536ffa0c2dd5bedc6903" => ResolvedCursor {
- raw: include_str!("../assets/windows/sizeall.svg"),
- hotspot: (0.5, 0.5),
- },
- // IDC_NO
- "7df883a459aced72acf32b969ff1119676d334d9acfcbe668ef92fe01094a7d6" => ResolvedCursor {
- raw: include_str!("../assets/windows/no.svg"),
- hotspot: (0.5, 0.5),
- },
- // IDC_HAND
- "44a554b439a681410d337d239bf08afe7c66486538563ebb93dc1c309f0a9209" => ResolvedCursor {
- raw: include_str!("../assets/windows/hand.svg"),
- hotspot: (0.42, 0.0),
- },
- // IDC_APPSTARTING
- "1486a2339478da61a52a6eecf8ee3446be62f12d375dba8befd42bb553eea7bf" => ResolvedCursor {
- raw: include_str!("../assets/windows/appstarting.svg"),
- hotspot: (0.055, 0.368),
- },
- // IDC_HELP
- "5d0b4df6188bc8d540abfbd4235199cc0f67fb41d5e0dcbfd40a3011f8808fea" => ResolvedCursor {
- raw: include_str!("../assets/windows/idchelp.svg"),
- hotspot: (0.056, 0.127),
- },
- // IDC_PIN
- "cb74a2d34774dbc43004882e43f9c058b2d2ee60184185567d0328ca013f5bc3" => ResolvedCursor {
- raw: include_str!("../assets/windows/idcpin.svg"),
- hotspot: (0.245, 0.05),
- },
- // IDC_PERSON
- "1f5209791a75916697c26cf2d018d267ae1102c71dbd196de6c83132f5627f09" => ResolvedCursor {
- raw: include_str!("../assets/windows/idcperson.svg"),
- hotspot: (0.235, 0.05),
- },
- // MAKEINTRESOURCE(32631) - Pen
- "7340ea75802db8fef3a103e9385e65b2c8c358e077ef949faaf572fb502dd9e2" => ResolvedCursor {
- raw: include_str!("../assets/windows/pen.svg"),
- hotspot: (0.055, 0.945),
- },
- // // MAKEINTRESOURCE(32652) - ScrolNS
- // "4c89e1d64c35cc88d09aaddcc78ab685ceab8d974006d3d94af23a9e888a74d7" => todo!(),
- // // MAKEINTRESOURCE(32653) - ScrollWE
- // "c5b16cfc625082dfdaa8e43111909baf9201fca39433ee8cdd117221f66cb4d1" => todo!(),
- // // MAKEINTRESOURCE(32654) - ScrollNSEW
- // "65527a0605a3bf225f90b9fe5b27b1c70743f4fa017b780abe27d5910cfdf69d" => todo!(),
- // // MAKEINTRESOURCE(32655) - ScrollN
- // "fe1b1ac207a874a452b4dd28949008282e6038c3ca903aba5da151d718e3d811" => todo!(),
- // // MAKEINTRESOURCE(32656) - ScrollS
- // "1d7c1ea6ecedfa467c8b082f4082a8382c76d01033222f59f367267ba04c2b18" => todo!(),
- // // MAKEINTRESOURCE(32657) - ScrollW
- // "81fc32f5284680bf9503fe6af204f4a2494da213de935e5e0a59e85ce3ed7685" => todo!(),
- // // MAKEINTRESOURCE(32658) - ScrollE
- // "c0a4f452e2f564bfa0193523e47ab4fbdcb9ac2c475566c01ef8df61752ab8af" => todo!(),
- // // MAKEINTRESOURCE(32659) - ScrollNW
- // "b5c891535897b0665553d8ec1217a9919a1ca6147144d8b142516c9e829ca15a" => todo!(),
- // // MAKEINTRESOURCE(32660) - ScrollNE
- // "7b6008d5752a204e0aca2e45db3ea8d0901419b4d772c49bcb46821f9c23b85b" => todo!(),
- // // MAKEINTRESOURCE(32661) - ScrollSW
- // "56b8ae43318dd75770a10786e60b9f12f9ba8408eee8cb3a946a56ebbace7297" => todo!(),
- // // MAKEINTRESOURCE(32662) - ScrollSE
- // "178f8c96aaace35760dd01d5a7d4341b0690f7e3de45919bfd696d0c60c14895" => todo!(),
- // // MAKEINTRESOURCE(32663) - ArrowCD
- // "a8bcbabdbb363b9be601cbeaa29b46e0e64834ff1ae0812646ad6d0c64efb2da" => todo!(),
- _ => return None,
- })
+impl Type for CursorShape {
+ fn inline(
+ types: &mut specta::TypeMap,
+ generics: specta::Generics,
+ ) -> specta::datatype::DataType {
+ String::inline(types, generics)
}
}
diff --git a/crates/cursor-info/src/macos.rs b/crates/cursor-info/src/macos.rs
new file mode 100644
index 000000000..a45c2cfbd
--- /dev/null
+++ b/crates/cursor-info/src/macos.rs
@@ -0,0 +1,168 @@
+use strum::{EnumString, IntoStaticStr};
+
+use crate::{CursorShape, ResolvedCursor};
+
+/// macOS Cursors
+/// https://developer.apple.com/documentation/appkit/nscursor
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, EnumString, IntoStaticStr)]
+pub enum CursorShapeMacOS {
+ /// https://developer.apple.com/documentation/appkit/nscursor/arrow
+ Arrow,
+ /// https://developer.apple.com/documentation/appkit/nscursor/contextualmenu
+ ContextualMenu,
+ /// https://developer.apple.com/documentation/appkit/nscursor/closedhand
+ ClosedHand,
+ /// https://developer.apple.com/documentation/appkit/nscursor/crosshair
+ Crosshair,
+ /// https://developer.apple.com/documentation/appkit/nscursor/disappearingitem
+ DisappearingItem,
+ /// https://developer.apple.com/documentation/appkit/nscursor/dragcopy
+ DragCopy,
+ /// https://developer.apple.com/documentation/appkit/nscursor/draglink
+ DragLink,
+ /// https://developer.apple.com/documentation/appkit/nscursor/ibeam
+ IBeam,
+ /// https://developer.apple.com/documentation/appkit/nscursor/openhand
+ OpenHand,
+ /// https://developer.apple.com/documentation/appkit/nscursor/operationnotallowed
+ OperationNotAllowed,
+ /// https://developer.apple.com/documentation/appkit/nscursor/pointinghand
+ PointingHand,
+ /// https://developer.apple.com/documentation/appkit/nscursor/resizedown
+ ResizeDown,
+ /// https://developer.apple.com/documentation/appkit/nscursor/resizeleft
+ ResizeLeft,
+ /// https://developer.apple.com/documentation/appkit/nscursor/resizeleftright
+ ResizeLeftRight,
+ /// https://developer.apple.com/documentation/appkit/nscursor/resizeright
+ ResizeRight,
+ /// https://developer.apple.com/documentation/appkit/nscursor/resizeup
+ ResizeUp,
+ /// https://developer.apple.com/documentation/appkit/nscursor/resizeupdown
+ ResizeUpDown,
+ /// https://developer.apple.com/documentation/appkit/nscursor/ibeamcursorforverticallayout
+ IBeamVerticalForVerticalLayout,
+}
+
+impl CursorShapeMacOS {
+ pub fn resolve(&self) -> Option<ResolvedCursor> {
+ Some(match self {
+ Self::Arrow => ResolvedCursor {
+ raw: include_str!("../assets/mac/arrow.svg"),
+ hotspot: (0.347, 0.33),
+ },
+ Self::ContextualMenu => ResolvedCursor {
+ raw: include_str!("../assets/mac/contextual_menu.svg"),
+ hotspot: (0.278, 0.295),
+ },
+ Self::ClosedHand => ResolvedCursor {
+ raw: include_str!("../assets/mac/closed_hand.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::Crosshair => ResolvedCursor {
+ raw: include_str!("../assets/mac/crosshair.svg"),
+ hotspot: (0.52, 0.51),
+ },
+ Self::DisappearingItem => return None,
+ Self::DragCopy => ResolvedCursor {
+ raw: include_str!("../assets/mac/drag_copy.svg"),
+ hotspot: (0.255, 0.1),
+ },
+ Self::DragLink => ResolvedCursor {
+ raw: include_str!("../assets/mac/drag_link.svg"),
+ hotspot: (0.621, 0.309),
+ },
+ Self::IBeam => ResolvedCursor {
+ raw: include_str!("../assets/mac/ibeam.svg"),
+ hotspot: (0.525, 0.52),
+ },
+ Self::OpenHand => ResolvedCursor {
+ raw: include_str!("../assets/mac/open_hand.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::OperationNotAllowed => ResolvedCursor {
+ raw: include_str!("../assets/mac/operation_not_allowed.svg"),
+ hotspot: (0.24, 0.1),
+ },
+ Self::PointingHand => ResolvedCursor {
+ raw: include_str!("../assets/mac/pointing_hand.svg"),
+ hotspot: (0.406, 0.25),
+ },
+ Self::ResizeDown => ResolvedCursor {
+ raw: include_str!("../assets/mac/resize_down.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::ResizeLeft => ResolvedCursor {
+ raw: include_str!("../assets/mac/resize_left.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::ResizeLeftRight => ResolvedCursor {
+ raw: include_str!("../assets/mac/resize_left_right.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::ResizeRight => ResolvedCursor {
+ raw: include_str!("../assets/mac/resize_right.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::ResizeUpDown => ResolvedCursor {
+ raw: include_str!("../assets/mac/resize_up_down.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::ResizeUp => ResolvedCursor {
+ raw: include_str!("../assets/mac/resize_up.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::IBeamVerticalForVerticalLayout => ResolvedCursor {
+ raw: include_str!("../assets/mac/ibeam_vertical.svg"),
+ hotspot: (0.51, 0.49),
+ },
+ })
+ }
+
+ /// Derive the cursor type from a hash
+ /// macOS doesn't allow comparing `NSCursor` instances directly so we hash the image data.
+ /// macOS cursor are also resolution-independent so this works.
+ pub fn from_hash(hash: &str) -> Option<Self> {
+ Some(match hash {
+ "de2d1f4a81e520b65fd1317b845b00a1c51a4d1f71cca3cd4ccdab52b98d1ac9" => Self::Arrow,
+ "ab26ca862492d41355b711c58544687a799dd7ae14cf161959ca524bbc97c322" => {
+ Self::ContextualMenu
+ }
+ "fbb165d4603dd8808b536f45bb74a9a72d9358ad19714b318bb7c06358a7d3c2" => Self::ClosedHand,
+ "c583f776531f4e7b76ea7ba2ab159765e2da11fd63cb897cc10362183859d1d8" => Self::Crosshair,
+ "67c369820fbc37af9b59b840c675ca24117ca8dfdccec7702b10894058617951" => {
+ Self::DisappearingItem
+ }
+ "af060876004c8647d82411eeac1bbd613d2991d46794aba16b56c91d3081e128" => Self::DragCopy,
+ "59ac2483461f4ad577a0a6b68be89fe663c36263b583c5f038eee2ae6a5ad98f" => Self::DragLink,
+ "492dca0bb6751a30607ac728803af992ba69365052b7df2dff1c0dfe463e653c" => Self::IBeam,
+ "3f6a5594a3c9334065944b9c56d9f73fd5fe5f02108a5e28f37e222e770be476" => Self::OpenHand,
+ "37287ef1d097704d3e9d0be9c1049ce1fb6dfabd6d210af0429b1b6ec7084c59" => {
+ Self::OperationNotAllowed
+ }
+ "b0443e9f72e724cb6d94b879bf29c6cb18376d0357c6233e5a7561cf8a9943c6" => {
+ Self::PointingHand
+ }
+ "3c9bf0ce893b64fe9e4363793b406140d4b3900b7beafa1c409e78cf5a8cf954" => Self::ResizeDown,
+ "50431d8fd537119aefb4c3673f9b9ff00d3cd1d2bf6c35e5dfb09ed40cfd5e7c" => Self::ResizeLeft,
+ "0fdaea89910bcbe34ad0d4d63a6ada2095489df18537bbf54dd0d0769588b381" => {
+ Self::ResizeLeftRight
+ }
+ "e74de88f863f059e5beb27152b2dfc2cd1e8dcc458ce775607765e9a4859667e" => Self::ResizeRight,
+ "912ca42451a9624f6fb8c1d53c29c26782b7590d383a66075a6768c4409024d9" => Self::ResizeUp,
+ "9c93eb53df68d7fd86298ba1eb3e3b32ccd34d168b81a31a6fc4bb79f131331f" => {
+ Self::ResizeUpDown
+ }
+ "024e1d486a7f16368669d419e69c9a326e464ec1b8ed39645e5c89cb183e03c5" => {
+ Self::IBeamVerticalForVerticalLayout
+ }
+ _ => return None,
+ })
+ }
+}
+
+impl From<CursorShapeMacOS> for CursorShape {
+ fn from(value: CursorShapeMacOS) -> Self {
+ CursorShape::MacOS(value)
+ }
+}
diff --git a/crates/cursor-info/src/windows.rs b/crates/cursor-info/src/windows.rs
new file mode 100644
index 000000000..66fa9a07e
--- /dev/null
+++ b/crates/cursor-info/src/windows.rs
@@ -0,0 +1,271 @@
+use strum::{EnumString, IntoStaticStr};
+
+use crate::{CursorShape, ResolvedCursor};
+
+// https://learn.microsoft.com/en-us/windows/win32/menurc/about-cursors
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, EnumString, IntoStaticStr)]
+pub enum CursorShapeWindows {
+ /// IDC_ARROW
+ Arrow,
+ /// IDC_IBEAM
+ IBeam,
+ /// IDC_WAIT
+ Wait,
+ /// IDC_CROSS
+ Cross,
+ /// IDC_UPARROW
+ UpArrow,
+ /// IDC_SIZENWSE
+ SizeNWSE,
+ /// IDC_SIZENESW
+ SizeNESW,
+ /// IDC_SIZEWE
+ SizeWE,
+ /// IDC_SIZENS
+ SizeNS,
+ /// IDC_SIZEALL
+ SizeAll,
+ /// IDC_NO
+ No,
+ /// IDC_HAND
+ Hand,
+ /// IDC_APPSTARTING
+ AppStarting,
+ /// IDC_HELP
+ Help,
+ /// IDC_PIN
+ Pin,
+ /// IDC_PERSON
+ Person,
+ /// MAKEINTRESOURCE(32631)
+ Pen,
+ /// MAKEINTRESOURCE(32652)
+ ScrollNS,
+ /// MAKEINTRESOURCE(32653)
+ ScrollWE,
+ /// MAKEINTRESOURCE(32654)
+ ScrollNSEW,
+ /// MAKEINTRESOURCE(32655)
+ ScrollN,
+ /// MAKEINTRESOURCE(32656)
+ ScrollS,
+ /// MAKEINTRESOURCE(32657)
+ ScrollW,
+ /// MAKEINTRESOURCE(32658)
+ ScrollE,
+ /// MAKEINTRESOURCE(32659)
+ ScrollNW,
+ /// MAKEINTRESOURCE(32660)
+ ScrollNE,
+ /// MAKEINTRESOURCE(32661)
+ ScrollSW,
+ /// MAKEINTRESOURCE(32662)
+ ScrollSE,
+ /// MAKEINTRESOURCE(32663)
+ ArrowCD,
+}
+
+impl CursorShapeWindows {
+ pub fn resolve(&self) -> Option<ResolvedCursor> {
+ Some(match self {
+ Self::Arrow => ResolvedCursor {
+ raw: include_str!("../assets/windows/arrow.svg"),
+ hotspot: (0.055, 0.085),
+ },
+ Self::IBeam => ResolvedCursor {
+ raw: include_str!("../assets/windows/ibeam.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::Wait => ResolvedCursor {
+ raw: include_str!("../assets/windows/wait.svg"),
+ hotspot: (0.5, 0.52),
+ },
+ Self::Cross => ResolvedCursor {
+ raw: include_str!("../assets/windows/cross.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::UpArrow => ResolvedCursor {
+ raw: include_str!("../assets/windows/uparrow.svg"),
+ hotspot: (0.5, 0.05),
+ },
+ Self::SizeNWSE => ResolvedCursor {
+ raw: include_str!("../assets/windows/idcsizenwse.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::SizeNESW => ResolvedCursor {
+ raw: include_str!("../assets/windows/size-nesw.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::SizeWE => ResolvedCursor {
+ raw: include_str!("../assets/windows/idcsizewe.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::SizeNS => ResolvedCursor {
+ raw: include_str!("../assets/windows/size-ns.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::SizeAll => ResolvedCursor {
+ raw: include_str!("../assets/windows/sizeall.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::No => ResolvedCursor {
+ raw: include_str!("../assets/windows/no.svg"),
+ hotspot: (0.5, 0.5),
+ },
+ Self::Hand => ResolvedCursor {
+ raw: include_str!("../assets/windows/hand.svg"),
+ hotspot: (0.42, 0.0),
+ },
+ Self::AppStarting => ResolvedCursor {
+ raw: include_str!("../assets/windows/appstarting.svg"),
+ hotspot: (0.055, 0.368),
+ },
+ Self::Help => ResolvedCursor {
+ raw: include_str!("../assets/windows/idchelp.svg"),
+ hotspot: (0.056, 0.127),
+ },
+ Self::Pin => ResolvedCursor {
+ raw: include_str!("../assets/windows/idcpin.svg"),
+ hotspot: (0.245, 0.05),
+ },
+ Self::Person => ResolvedCursor {
+ raw: include_str!("../assets/windows/idcperson.svg"),
+ hotspot: (0.235, 0.05),
+ },
+ Self::Pen => ResolvedCursor {
+ raw: include_str!("../assets/windows/pen.svg"),
+ hotspot: (0.055, 0.945),
+ },
+ // Self::ScrolNS => todo!(),
+ // Self::ScrollWE => todo!(),
+ // Self::ScrollNSEW => todo!(),
+ // Self::ScrollN => todo!(),
+ // Self::ScrollS => todo!(),
+ // Self::ScrollW => todo!(),
+ // Self::ScrollE => todo!(),
+ // Self::ScrollNW => todo!(),
+ // Self::ScrollNE => todo!(),
+ // Self::ScrollSW => todo!(),
+ // Self::ScrollSE => todo!(),
+ // Self::ArrowCD => todo!(),
+ _ => return None,
+ })
+ }
+}
+
+#[cfg(target_os = "windows")]
+mod windows {
+ use super::*;
+ use ::windows::{
+ Win32::UI::WindowsAndMessaging::{
+ HCURSOR, IDC_APPSTARTING, IDC_ARROW, IDC_CROSS, IDC_HAND, IDC_HELP, IDC_IBEAM, IDC_NO,
+ IDC_PERSON, IDC_PIN, IDC_SIZEALL, IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZEWE,
+ IDC_UPARROW, IDC_WAIT, LoadCursorW,
+ },
+ core::PCWSTR,
+ };
+ use std::{collections::HashMap, sync::OnceLock};
+
+ static CURSOR_CACHE: OnceLock<HashMap<usize, CursorShapeWindows>> = OnceLock::new();
+
+ fn get_cursor_cache() -> &'static HashMap<usize, CursorShapeWindows> {
+ CURSOR_CACHE.get_or_init(|| {
+ #[inline]
+ fn load_cursor(lpcursorname: PCWSTR) -> usize {
+ let cursor = unsafe { LoadCursorW(None, lpcursorname) }
+ .expect("Failed to load default system cursors");
+ cursor.0 as usize
+ }
+
+ let mut cursors = HashMap::new();
+
+ cursors.insert(load_cursor(IDC_ARROW), CursorShapeWindows::Arrow);
+ cursors.insert(load_cursor(IDC_IBEAM), CursorShapeWindows::IBeam);
+ cursors.insert(load_cursor(IDC_WAIT), CursorShapeWindows::Wait);
+ cursors.insert(load_cursor(IDC_CROSS), CursorShapeWindows::Cross);
+ cursors.insert(load_cursor(IDC_UPARROW), CursorShapeWindows::UpArrow);
+ cursors.insert(load_cursor(IDC_SIZENWSE), CursorShapeWindows::SizeNWSE);
+ cursors.insert(load_cursor(IDC_SIZENESW), CursorShapeWindows::SizeNESW);
+ cursors.insert(load_cursor(IDC_SIZEWE), CursorShapeWindows::SizeWE);
+ cursors.insert(load_cursor(IDC_SIZENS), CursorShapeWindows::SizeNS);
+ cursors.insert(load_cursor(IDC_SIZEALL), CursorShapeWindows::SizeAll);
+ cursors.insert(load_cursor(IDC_NO), CursorShapeWindows::No);
+ cursors.insert(load_cursor(IDC_HAND), CursorShapeWindows::Hand);
+ cursors.insert(
+ load_cursor(IDC_APPSTARTING),
+ CursorShapeWindows::AppStarting,
+ );
+ cursors.insert(load_cursor(IDC_HELP), CursorShapeWindows::Help);
+ cursors.insert(load_cursor(IDC_PIN), CursorShapeWindows::Pin);
+ cursors.insert(load_cursor(IDC_PERSON), CursorShapeWindows::Person);
+ cursors.insert(load_cursor(PCWSTR(32631u16 as _)), CursorShapeWindows::Pen);
+ cursors.insert(
+ load_cursor(PCWSTR(32652u16 as _)),
+ CursorShapeWindows::ScrollNS,
+ );
+ cursors.insert(
+ load_cursor(PCWSTR(32653u16 as _)),
+ CursorShapeWindows::ScrollWE,
+ );
+ cursors.insert(
+ load_cursor(PCWSTR(32654u16 as _)),
+ CursorShapeWindows::ScrollNSEW,
+ );
+ cursors.insert(
+ load_cursor(PCWSTR(32655u16 as _)),
+ CursorShapeWindows::ScrollN,
+ );
+ cursors.insert(
+ load_cursor(PCWSTR(32656u16 as _)),
+ CursorShapeWindows::ScrollS,
+ );
+ cursors.insert(
+ load_cursor(PCWSTR(32657u16 as _)),
+ CursorShapeWindows::ScrollW,
+ );
+ cursors.insert(
+ load_cursor(PCWSTR(32658u16 as _)),
+ CursorShapeWindows::ScrollE,
+ );
+ cursors.insert(
+ load_cursor(PCWSTR(32659u16 as _)),
+ CursorShapeWindows::ScrollNW,
+ );
+ cursors.insert(
+ load_cursor(PCWSTR(32660u16 as _)),
+ CursorShapeWindows::ScrollNE,
+ );
+ cursors.insert(
+ load_cursor(PCWSTR(32661u16 as _)),
+ CursorShapeWindows::ScrollSW,
+ );
+ cursors.insert(
+ load_cursor(PCWSTR(32662u16 as _)),
+ CursorShapeWindows::ScrollSE,
+ );
+ cursors.insert(
+ load_cursor(PCWSTR(32663u16 as _)),
+ CursorShapeWindows::ArrowCD,
+ );
+
+ cursors
+ })
+ }
+
+ impl TryFrom<&HCURSOR> for super::CursorShape {
+ type Error = ();
+
+ fn try_from(cursor: &HCURSOR) -> Result<Self, Self::Error> {
+ match get_cursor_cache().get(&(cursor.0 as usize)) {
+ Some(cursor_shape) => Ok(super::CursorShape::Windows(*cursor_shape)),
+ None => Err(()),
+ }
+ }
+ }
+}
+
+impl From<CursorShapeWindows> for CursorShape {
+ fn from(value: CursorShapeWindows) -> Self {
+ CursorShape::Windows(value)
+ }
+}
diff --git a/crates/project/Cargo.toml b/crates/project/Cargo.toml
index 8c23f1023..cc51c6fde 100644
--- a/crates/project/Cargo.toml
+++ b/crates/project/Cargo.toml
@@ -7,9 +7,11 @@ edition = "2021"
workspace = true
[dependencies]
-specta.workspace = true
+cap-cursor-info = { path = "../cursor-info" }
+specta.workspace = true
serde = { workspace = true }
+
serde_json = "1.0.127"
either = "1.13.0"
relative-path = { version = "1.9.3", features = ["serde"] }
diff --git a/crates/project/src/meta.rs b/crates/project/src/meta.rs
index 2d8013dca..583d41be1 100644
--- a/crates/project/src/meta.rs
+++ b/crates/project/src/meta.rs
@@ -244,7 +244,7 @@ pub struct CursorMeta {
pub image_path: RelativePathBuf,
pub hotspot: XY<f64>,
#[serde(default)]
- pub hash: Option<String>,
+ pub shape: Option<cap_cursor_info::CursorShape>,
}
impl MultipleSegments {
diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml
index ab6bb41b7..11385c7b1 100644
--- a/crates/recording/Cargo.toml
+++ b/crates/recording/Cargo.toml
@@ -15,6 +15,7 @@ cap-displays = { path = "../displays" }
cap-cursor-capture = { path = "../cursor-capture" }
cap-media-encoders = { path = "../media-encoders" }
cap-media-info = { path = "../media-info" }
+cap-cursor-info = { path = "../cursor-info" }
specta.workspace = true
tokio.workspace = true
diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rs
index 926243efe..ab67b39f2 100644
--- a/crates/recording/src/cursor.rs
+++ b/crates/recording/src/cursor.rs
@@ -7,6 +7,7 @@ use std::{
};
use cap_cursor_capture::RawCursorPosition;
+use cap_cursor_info::CursorShape;
use cap_displays::Display;
use cap_media::{platform::Bounds, sources::CropRatio};
use cap_project::{CursorClickEvent, CursorMoveEvent, XY};
@@ -22,7 +23,7 @@ pub struct Cursor {
pub file_name: String,
pub id: u32,
pub hotspot: XY<f64>,
- pub hash: String,
+ pub shape: Option<CursorShape>,
}
pub type Cursors = HashMap<u64, Cursor>;
@@ -107,7 +108,6 @@ pub fn spawn_cursor_recorder(
let file_name = format!("cursor_{}.png", cursor_id);
let cursor_path = cursors_dir.join(&file_name);
- let hash = hex::encode(Sha256::digest(&data.image));
if let Ok(image) = image::load_from_memory(&data.image) {
// Convert to RGBA
let rgba_image = image.into_rgba8();
@@ -122,7 +122,7 @@ pub fn spawn_cursor_recorder(
file_name,
id: response.next_cursor_id,
hotspot: data.hotspot,
- hash,
+ shape: data.shape,
},
);
response.next_cursor_id += 1;
@@ -244,6 +244,7 @@ pub fn spawn_cursor_recorder(
struct CursorData {
image: Vec<u8>,
hotspot: XY<f64>,
+ shape: Option<CursorShape>,
}
#[cfg(target_os = "macos")]
@@ -264,9 +265,13 @@ fn get_cursor_data() -> Option<CursorData> {
let image = image_data.as_bytes_unchecked().to_vec();
+ let shape =
+ cap_cursor_info::CursorShapeMacOS::from_hash(&hex::encode(Sha256::digest(&image)));
+
Some(CursorData {
image,
hotspot: XY::new(hotspot.x / size.width, hotspot.y / size.height),
+ shape: shape.map(Into::into),
})
})
}
@@ -576,6 +581,7 @@ fn get_cursor_data() -> Option<CursorData> {
Some(CursorData {
image: png_data,
hotspot: XY::new(hotspot_x, hotspot_y),
+ shape: CursorShape::try_from(&cursor_info.hCursor).ok(),
})
}
}
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index b068d282e..80413acb3 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -525,7 +525,7 @@ async fn stop_recording(
image_path: RelativePathBuf::from("content/cursors")
.join(&cursor.file_name),
hotspot: cursor.hotspot,
- hash: Some(cursor.hash),
+ shape: cursor.shape,
},
)
})
diff --git a/crates/rendering/src/layers/cursor.rs b/crates/rendering/src/layers/cursor.rs
index 6ed259438..8dd1b946e 100644
--- a/crates/rendering/src/layers/cursor.rs
+++ b/crates/rendering/src/layers/cursor.rs
@@ -213,21 +213,19 @@ impl CursorLayer {
let speed = (velocity[0] * velocity[0] + velocity[1] * velocity[1]).sqrt();
let motion_blur_amount = (speed * 0.3).min(1.0) * 0.0; // uniforms.project.cursor.motion_blur;
- let is_svg_assets_enabled = !uniforms.project.cursor.raw && uniforms.project.cursor.use_svg;
-
// Remove all cursor assets if the svg configuration changes.
// it might change the texture.
//
// This would be better if it only invalidated the required assets but that would be more complicated.
- if self.prev_is_svg_assets_enabled != Some(is_svg_assets_enabled) {
- self.prev_is_svg_assets_enabled = Some(is_svg_assets_enabled);
+ if self.prev_is_svg_assets_enabled != Some(uniforms.project.cursor.use_svg) {
+ self.prev_is_svg_assets_enabled = Some(uniforms.project.cursor.use_svg);
self.cursors.drain();
}
if !self.cursors.contains_key(&interpolated_cursor.cursor_id) {
let mut cursor = None;
- let cursor_hash = match &constants.recording_meta.inner {
+ let cursor_shape = match &constants.recording_meta.inner {
RecordingMetaInner::Studio(StudioRecordingMeta::MultipleSegments {
inner:
MultipleSegments {
@@ -236,16 +234,16 @@ impl CursorLayer {
},
}) => cursors
.get(&interpolated_cursor.cursor_id)
- .and_then(|v| v.hash.clone()),
+ .and_then(|v| v.shape.clone()),
_ => None,
};
// Attempt to find and load a higher-quality SVG cursor included in Cap.
// These are used instead of the OS provided cursor images when possible as the quality is better.
- if let Some(cursor_hash) = cursor_hash
+ if let Some(cursor_shape) = cursor_shape
&& uniforms.project.cursor.use_svg
{
- if let Some(info) = ResolvedCursor::from_hash(cursor_hash) {
+ if let Some(info) = cursor_shape.resolve() {
cursor = CursorTexture::prepare_svg(&constants, info.raw, info.hotspot.into())
.map_err(|err| {
error!(
@@ -288,43 +286,48 @@ impl CursorLayer {
};
let size = {
- let cursor_texture_size = cursor_texture.texture.size();
- let cursor_texture_size_aspect =
- cursor_texture_size.width as f32 / cursor_texture_size.height as f32;
+ let base_size_px = STANDARD_CURSOR_HEIGHT / constants.options.screen_size.y as f32
+ * uniforms.output_size.1 as f32;
- let cursor_size_percentage = if uniforms.cursor_size <= 0.0 {
+ let cursor_size_factor = if uniforms.cursor_size <= 0.0 {
100.0
} else {
uniforms.cursor_size / 100.0
};
- let factor = STANDARD_CURSOR_HEIGHT / constants.options.screen_size.y as f32
- * uniforms.output_size.1 as f32;
- let cursor_size_constant = factor * cursor_size_percentage;
+ // 0 -> 1 indicating how much to shrink from click
+ let click_t = get_click_t(&cursor.clicks, (time_s as f64) * 1000.0);
+ // lerp shrink size
+ let click_scale_factor = click_t * 1.0 + (1.0 - click_t) * CLICK_SHRINK_SIZE;
+
+ let size = base_size_px * cursor_size_factor * click_scale_factor;
- Coord::<FrameSpace>::new(if cursor_texture_size_aspect > 1.0 {
+ let texture_size_aspect = {
+ let texture_size = cursor_texture.texture.size();
+ texture_size.width as f32 / texture_size.height as f32
+ };
+
+ Coord::<FrameSpace>::new(if texture_size_aspect > 1.0 {
// Wide cursor: base sizing on width to prevent excessive width
- let width = cursor_size_constant;
- let height = cursor_size_constant / cursor_texture_size_aspect;
+ let width = size;
+ let height = size / texture_size_aspect;
XY::new(width, height).into()
} else {
// Tall or square cursor: base sizing on height (current behavior)
- XY::new(
- cursor_size_constant * cursor_texture_size_aspect,
- cursor_size_constant,
- )
- .into()
+ XY::new(size * texture_size_aspect, size).into()
})
};
let hotspot = Coord::<FrameSpace>::new(size.coord * cursor_texture.hotspot);
+ // Calculate position without hotspot first
let position = interpolated_cursor.position.to_frame_space(
&constants.options,
&uniforms.project,
resolution_base,
) - hotspot;
+ // Transform to zoomed space
let zoomed_position = position.to_zoomed_frame_space(
&constants.options,
&uniforms.project,
@@ -339,16 +342,9 @@ impl CursorLayer {
zoom,
) - zoomed_position;
- let click_scale_factor = get_click_t(&cursor.clicks, (time_s as f64) * 1000.0)
- // lerp shrink size
- * (1.0 - CLICK_SHRINK_SIZE)
- + CLICK_SHRINK_SIZE;
-
- let cursor_size_px = zoomed_size.coord * click_scale_factor as f64;
-
let uniforms = CursorUniforms {
position: [zoomed_position.x as f32, zoomed_position.y as f32],
- size: [cursor_size_px.x as f32, cursor_size_px.y as f32],
+ size: [zoomed_size.x as f32, zoomed_size.y as f32],
output_size: [uniforms.output_size.0 as f32, uniforms.output_size.1 as f32],
screen_bounds: uniforms.display.target_bounds,
velocity,