diff --git a/Cargo.lock b/Cargo.lock index c5679d39d4f..d8479db2f88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -213,6 +213,12 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + [[package]] name = "arrayvec" version = "0.7.6" @@ -307,9 +313,9 @@ dependencies = [ [[package]] name = "async-lock" -version = "3.4.0" +version = "3.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" +checksum = "5fd03604047cee9b6ce9de9f70c6cd540a0520c813cbd49bae61f33ab80ed1dc" dependencies = [ "event-listener", "event-listener-strategy", @@ -949,6 +955,18 @@ dependencies = [ "device_query", ] +[[package]] +name = "cap-cursor-info" +version = "0.0.0" +dependencies = [ + "hex", + "image", + "objc2 0.6.1", + "objc2-app-kit", + "sha2", + "windows 0.60.0", +] + [[package]] name = "cap-desktop" version = "0.3.61-beta.1" @@ -1223,13 +1241,16 @@ dependencies = [ "ffmpeg-next", "flume", "futures", + "hex", "image", "objc", + "objc2-app-kit", "relative-path", "scap", "screencapturekit", "serde", "serde_json", + "sha2", "specta", "tempfile", "thiserror 1.0.69", @@ -1248,6 +1269,7 @@ dependencies = [ "bezier_easing", "build-time", "bytemuck", + "cap-cursor-info", "cap-flags", "cap-project", "cap-video-decode", @@ -1262,9 +1284,11 @@ dependencies = [ "log", "pretty_assertions", "reactive_graph", + "resvg", "serde", "specta", "thiserror 1.0.69", + "tiny-skia", "tokio", "tracing", "wgpu", @@ -1348,9 +1372,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.30" +version = "1.2.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "deec109607ca693028562ed836a5f1c4b8bd77755c4e132fc5ce11b0b6211ae7" +checksum = "c3a42d84bb6b69d3a8b3eaacf0d88f179e1929695e1ad012b6cf64d9caaa5fd2" dependencies = [ "jobserver", "libc", @@ -1854,6 +1878,15 @@ dependencies = [ "thiserror 2.0.12", ] +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + [[package]] name = "coreaudio-rs" version = "0.11.3" @@ -1881,11 +1914,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da46a9d5a8905cc538a4a5bceb6a4510de7a51049c5588c0114efce102bcbbe8" dependencies = [ "bitflags 2.9.1", - "fontdb", + "fontdb 0.16.2", "log", "rangemap", "rustc-hash 1.1.0", - "rustybuzz", + "rustybuzz 0.14.1", "self_cell", "smol_str", "swash", @@ -2532,9 +2565,9 @@ dependencies = [ [[package]] name = "event-listener" -version = "5.4.0" +version = "5.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3492acde4c3fc54c845eaab3eed8bd00c7a7d881f78bfc801e43a93dec1331ae" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" dependencies = [ "concurrent-queue", "parking", @@ -2663,6 +2696,12 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + [[package]] name = "flume" version = "0.11.1" @@ -2719,6 +2758,20 @@ dependencies = [ "ttf-parser 0.20.0", ] +[[package]] +name = "fontdb" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", + "ttf-parser 0.25.1", +] + [[package]] name = "foreign-types" version = "0.3.2" @@ -2853,9 +2906,9 @@ checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" [[package]] name = "futures-lite" -version = "2.6.0" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5edaec856126859abb19ed65f39e90fea3a9574b9707f13539acf4abf7eb532" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" dependencies = [ "fastrand", "futures-core", @@ -3811,6 +3864,12 @@ dependencies = [ "quick-error", ] +[[package]] +name = "imagesize" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285" + [[package]] name = "imgref" version = "1.11.0" @@ -4115,6 +4174,17 @@ dependencies = [ "selectors", ] +[[package]] +name = "kurbo" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62" +dependencies = [ + "arrayvec", + "euclid", + "smallvec", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -5565,6 +5635,12 @@ dependencies = [ "siphasher 1.0.1", ] +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + [[package]] name = "pin-project-lite" version = "0.2.16" @@ -5630,7 +5706,7 @@ checksum = "3af6b589e163c5a788fab00ce0c0366f6efbb9959c2f9874b224936af7fce7e1" dependencies = [ "base64 0.22.1", "indexmap 2.10.0", - "quick-xml 0.38.0", + "quick-xml 0.38.1", "serde", "time", ] @@ -5650,9 +5726,9 @@ dependencies = [ [[package]] name = "polling" -version = "3.9.0" +version = "3.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ee9b2fa7a4517d2c91ff5bc6c297a427a96749d15f98fcdbb22c05571a4d4b7" +checksum = "b5bd19146350fe804f7cb2669c851c03d69da628803dab0d98018142aaa5d829" dependencies = [ "cfg-if", "concurrent-queue", @@ -5861,9 +5937,9 @@ dependencies = [ [[package]] name = "quick-xml" -version = "0.38.0" +version = "0.38.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8927b0664f5c5a98265138b7e3f90aa19a6b21353182469ace36d4ac527b7b1b" +checksum = "9845d9dccf565065824e69f9f235fafba1587031eda353c1f1561cd6a6be78f4" dependencies = [ "memchr", ] @@ -6188,9 +6264,9 @@ dependencies = [ [[package]] name = "redox_users" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78eaea1f52c56d57821be178b2d47e09ff26481a6042e8e042fcb0ced068b470" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" dependencies = [ "getrandom 0.2.16", "libredox", @@ -6327,6 +6403,23 @@ dependencies = [ "webpki-roots", ] +[[package]] +name = "resvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" +dependencies = [ + "gif", + "image-webp", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", + "zune-jpeg", +] + [[package]] name = "rfd" version = "0.15.4" @@ -6357,6 +6450,9 @@ name = "rgb" version = "0.8.52" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c6a884d2998352bb4daf0183589aec883f16a6da1f4dde84d8e2e9a5409a1ce" +dependencies = [ + "bytemuck", +] [[package]] name = "ring" @@ -6518,8 +6614,26 @@ dependencies = [ "libm", "smallvec", "ttf-parser 0.21.1", - "unicode-bidi-mirroring", - "unicode-ccc", + "unicode-bidi-mirroring 0.2.0", + "unicode-ccc 0.2.0", + "unicode-properties", + "unicode-script", +] + +[[package]] +name = "rustybuzz" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702" +dependencies = [ + "bitflags 2.9.1", + "bytemuck", + "core_maths", + "log", + "smallvec", + "ttf-parser 0.25.1", + "unicode-bidi-mirroring 0.4.0", + "unicode-ccc 0.4.0", "unicode-properties", "unicode-script", ] @@ -6875,9 +6989,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.141" +version = "1.0.142" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" +checksum = "030fedb782600dcbd6f02d479bf0d817ac3bb40d644745b769d6a96bc3afc5a7" dependencies = [ "itoa", "memchr", @@ -7082,9 +7196,9 @@ dependencies = [ [[package]] name = "signal-hook-registry" -version = "1.4.5" +version = "1.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9203b8055f63a2a00e2f593bb0510367fe707d7ff1e5c872de2f537b339e5410" +checksum = "b2a4719bff48cee6b39d12c020eeb490953ad2443b7055bd0b21fca26bd8c28b" dependencies = [ "libc", ] @@ -7104,6 +7218,15 @@ dependencies = [ "quote", ] +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + [[package]] name = "siphasher" version = "0.3.11" @@ -7325,6 +7448,15 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + [[package]] name = "string_cache" version = "0.8.9" @@ -7389,6 +7521,16 @@ version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0193cc4331cfd2f3d2011ef287590868599a2f33c3e69bc22c1a3d3acf9e02fb" +[[package]] +name = "svgtypes" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc" +dependencies = [ + "kurbo", + "siphasher 1.0.1", +] + [[package]] name = "swash" version = "0.2.5" @@ -8359,6 +8501,32 @@ dependencies = [ "crunchy", ] +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + [[package]] name = "tinystr" version = "0.8.1" @@ -8386,9 +8554,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.47.0" +version = "1.47.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43864ed400b6043a4757a25c7a64a8efde741aed79a056a2fb348a406701bb35" +checksum = "89e49afdadebb872d3145a5638b59eb0691ea23e46ca484037cfab3b76b95038" dependencies = [ "backtrace", "bytes", @@ -8461,9 +8629,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.15" +version = "0.7.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66a539a9ad6d5d281510d5bd368c973d636c02dbf8a67300bfb6b950696ad7df" +checksum = "14307c986784f72ef81c89db7d9e28d6ac26d16213b109ea501696195e6e3ce5" dependencies = [ "bytes", "futures-core", @@ -8747,6 +8915,15 @@ version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c591d83f69777866b9126b24c6dd9a18351f177e49d625920d19f989fd31cf8" +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] + [[package]] name = "tungstenite" version = "0.24.0" @@ -8856,12 +9033,24 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23cb788ffebc92c5948d0e997106233eeb1d8b9512f93f41651f52b6c5f5af86" +[[package]] +name = "unicode-bidi-mirroring" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe" + [[package]] name = "unicode-ccc" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1df77b101bcc4ea3d78dafc5ad7e4f58ceffe0b2b16bf446aeb50b6cb4157656" +[[package]] +name = "unicode-ccc" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e" + [[package]] name = "unicode-ident" version = "1.0.18" @@ -8892,6 +9081,12 @@ version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" +[[package]] +name = "unicode-vo" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" + [[package]] name = "unicode-width" version = "0.1.14" @@ -8947,6 +9142,33 @@ dependencies = [ "url", ] +[[package]] +name = "usvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" +dependencies = [ + "base64 0.22.1", + "data-url", + "flate2", + "fontdb 0.23.0", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree", + "rustybuzz 0.20.1", + "simplecss", + "siphasher 1.0.1", + "strict-num", + "svgtypes", + "tiny-skia-path", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + [[package]] name = "utf-8" version = "0.7.6" @@ -10389,6 +10611,12 @@ version = "0.8.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fd8403733700263c6eb89f192880191f1b83e332f7a20371ddcf421c4a337c7" +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + [[package]] name = "yansi" version = "1.0.1" diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx index eddb0837d16..bcc5be6cf61 100644 --- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx +++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx @@ -33,7 +33,7 @@ import { import { createStore, produce } from "solid-js/store"; import { Dynamic } from "solid-js/web"; import toast from "solid-toast"; - +import IconLucideSparkles from "~icons/lucide/sparkles"; import colorBg from "~/assets/illustrations/color.webp"; import gradientBg from "~/assets/illustrations/gradient.webp"; import imageBg from "~/assets/illustrations/image.webp"; @@ -241,7 +241,7 @@ export function ConfigSidebar() { id: TAB_IDS.camera, icon: IconCapCamera, disabled: editorInstance.recordings.segments.every( - (s) => s.camera === null + (s) => s.camera === null, ), }, { id: TAB_IDS.audio, icon: IconCapAudioOn }, @@ -275,7 +275,7 @@ export function ConfigSidebar() { class={cx( "flex justify-center relative border-transparent border z-10 items-center rounded-md size-9 transition will-change-transform", state.selectedTab !== item.id && - "group-hover:border-gray-300 group-disabled:border-none" + "group-hover:border-gray-300 group-disabled:border-none", )} > @@ -313,7 +313,7 @@ export function ConfigSidebar() { optionValue="value" optionTextValue="name" value={STEREO_MODES.find( - (v) => v.value === project.audio.micStereoMode + (v) => v.value === project.audio.micStereoMode, )} onChange={(v) => { if (v) setProject("audio", "micStereoMode", v.value); @@ -480,6 +480,18 @@ export function ConfigSidebar() { + } + value={ + { + setProject("cursor", "useSvg" as any, value); + }} + /> + } + /> {/* @@ -660,7 +672,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { // Get the raw path without any URL prefixes const rawPath = decodeURIComponent( - photoUrl.replace("file://", "") + photoUrl.replace("file://", ""), ); debouncedSetProject(rawPath); @@ -720,7 +732,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { } }, }, - { passive: false } + { passive: false }, ); let fileInput!: HTMLInputElement; @@ -886,7 +898,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { project.background.source.path ) { const convertedPath = convertFileSrc( - project.background.source.path + project.background.source.path, ); // Only use converted path if it's valid if (convertedPath) { @@ -904,7 +916,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { project.background.source as { path?: string; } - ).path?.includes(w.id) + ).path?.includes(w.id), ); // Only use wallpaper URL if it exists if (selectedWallpaper?.url) { @@ -971,7 +983,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { setBackgroundTab( - key as keyof typeof BACKGROUND_THEMES + key as keyof typeof BACKGROUND_THEMES, ) } value={key} @@ -988,17 +1000,17 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { + ? (wallpapers()?.find((w) => ( project.background.source as { path?: string } - ).path?.includes(w.id) - )?.url ?? undefined + ).path?.includes(w.id), + )?.url ?? undefined) : undefined } onChange={(photoUrl) => { try { const wallpaper = wallpapers()?.find( - (w) => w.url === photoUrl + (w) => w.url === photoUrl, ); if (!wallpaper) return; @@ -1199,7 +1211,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { setProject( "background", "source", - backgrounds.color + backgrounds.color, ); } }} @@ -1283,7 +1295,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { const rawNewAngle = Math.round( start + - (downEvent.clientY - moveEvent.clientY) + (downEvent.clientY - moveEvent.clientY), ) % max; const newAngle = moveEvent.shiftKey ? rawNewAngle @@ -1298,7 +1310,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { ) { commands.performHapticFeedback( "Alignment", - "Now" + "Now", ); } @@ -1308,7 +1320,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { newAngle < 0 ? newAngle + max : newAngle, }); }, - }) + }), ); }} > @@ -1333,7 +1345,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { setProject( "background", "source", - backgrounds.gradient + backgrounds.gradient, ); } }} @@ -1342,7 +1354,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) { class="rounded-lg transition-all duration-200 cursor-pointer size-8 peer-checked:hover:opacity-100 peer-hover:opacity-70 peer-checked:ring-2 peer-checked:ring-gray-500 peer-checked:ring-offset-2 peer-checked:ring-offset-gray-200" style={{ background: `linear-gradient(${angle()}deg, rgb(${gradient.from.join( - "," + ",", )}), rgb(${gradient.to.join(",")}))`, }} /> @@ -1506,9 +1518,9 @@ function CameraConfig(props: { scrollRef: HTMLDivElement }) { item.x === "left" ? "left-2" : item.x === "right" - ? "right-2" - : "left-1/2 transform -translate-x-1/2", - item.y === "top" ? "top-2" : "bottom-2" + ? "right-2" + : "left-1/2 transform -translate-x-1/2", + item.y === "top" ? "top-2" : "bottom-2", )} onClick={() => setProject("camera", "position", item)} > @@ -1537,7 +1549,7 @@ function CameraConfig(props: { scrollRef: HTMLDivElement }) { optionValue="value" optionTextValue="name" value={CAMERA_SHAPES.find( - (v) => v.value === project.camera.shape + (v) => v.value === project.camera.shape, )} onChange={(v) => { if (v) setProject("camera", "shape", v.value); @@ -1744,7 +1756,7 @@ function ZoomSegmentConfig(props: { "zoomSegments", props.segmentIndex, "amount", - v[0] + v[0], ) } minValue={1} @@ -1763,7 +1775,7 @@ function ZoomSegmentConfig(props: { "zoomSegments", props.segmentIndex, "mode", - v === "auto" ? "auto" : { manual: states.manual } + v === "auto" ? "auto" : { manual: states.manual }, ); }} > @@ -1804,7 +1816,7 @@ function ZoomSegmentConfig(props: { const st = start(); let i = project.timeline?.segments.findIndex( - (s) => s.start <= st && s.end > st + (s) => s.start <= st && s.end > st, ); if (i === undefined || i === -1) return 0; return i; @@ -1816,7 +1828,7 @@ function ZoomSegmentConfig(props: { // TODO: this shouldn't be so hardcoded `${ editorInstance.path - }/content/segments/segment-${segmentIndex()}/display.mp4` + }/content/segments/segment-${segmentIndex()}/display.mp4`, ); }); @@ -1834,8 +1846,8 @@ function ZoomSegmentConfig(props: { }, () => { render(); - } - ) + }, + ), ); const render = () => { @@ -1850,7 +1862,7 @@ function ZoomSegmentConfig(props: { 0, 0, canvasRef.width!, - canvasRef.height! + canvasRef.height!, ); }; @@ -1913,19 +1925,19 @@ function ZoomSegmentConfig(props: { Math.min( (moveEvent.clientX - bounds.left) / bounds.width, - 1 + 1, ), - 0 + 0, ), y: Math.max( Math.min( (moveEvent.clientY - bounds.top) / bounds.height, - 1 + 1, ), - 0 + 0, ), - } + }, ); }, }); @@ -1989,7 +2001,7 @@ function ClipSegmentConfig(props: { disabled={ ( project.timeline?.segments.filter( - (s) => s.recordingSegment === props.segment.recordingSegment + (s) => s.recordingSegment === props.segment.recordingSegment, ) ?? [] ).length < 2 } diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts index dcdbbed2eff..283e5f4a1df 100644 --- a/apps/desktop/src/utils/tauri.ts +++ b/apps/desktop/src/utils/tauri.ts @@ -334,8 +334,8 @@ export type CurrentRecording = { target: CurrentRecordingTarget; type: Recording 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 } -export type CursorMeta = { imagePath: string; hotspot: XY } +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; hash?: 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 new file mode 100644 index 00000000000..b604feab2c2 --- /dev/null +++ b/crates/cursor-info/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "cap-cursor-info" +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" + +[target.'cfg(target_os= "windows")'.dev-dependencies] +windows = { workspace = true, features = [ + "Win32_Graphics_Gdi", + "Win32_UI_WindowsAndMessaging", +] } + +[lints] +workspace = true diff --git a/crates/cursor-info/assets/mac/LICENCE b/crates/cursor-info/assets/mac/LICENCE new file mode 100644 index 00000000000..915e9e7330c --- /dev/null +++ b/crates/cursor-info/assets/mac/LICENCE @@ -0,0 +1,3 @@ +This software is released under the Apple User Agreement. + +Icons taken from: https://github.com/daviddarnes/mac-cursors diff --git a/crates/cursor-info/assets/mac/arrow.svg b/crates/cursor-info/assets/mac/arrow.svg new file mode 100644 index 00000000000..42ae068a3a2 --- /dev/null +++ b/crates/cursor-info/assets/mac/arrow.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/closed_hand.svg b/crates/cursor-info/assets/mac/closed_hand.svg new file mode 100644 index 00000000000..e30f0c8c039 --- /dev/null +++ b/crates/cursor-info/assets/mac/closed_hand.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/contextual_menu.svg b/crates/cursor-info/assets/mac/contextual_menu.svg new file mode 100644 index 00000000000..2d3e11929e4 --- /dev/null +++ b/crates/cursor-info/assets/mac/contextual_menu.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/crosshair.svg b/crates/cursor-info/assets/mac/crosshair.svg new file mode 100644 index 00000000000..5e78d1eecf5 --- /dev/null +++ b/crates/cursor-info/assets/mac/crosshair.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/drag_copy.svg b/crates/cursor-info/assets/mac/drag_copy.svg new file mode 100644 index 00000000000..adf185db229 --- /dev/null +++ b/crates/cursor-info/assets/mac/drag_copy.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/drag_link.svg b/crates/cursor-info/assets/mac/drag_link.svg new file mode 100644 index 00000000000..33d4604798b --- /dev/null +++ b/crates/cursor-info/assets/mac/drag_link.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/ibeam.svg b/crates/cursor-info/assets/mac/ibeam.svg new file mode 100644 index 00000000000..b7de00fe1a0 --- /dev/null +++ b/crates/cursor-info/assets/mac/ibeam.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/ibeam_vertical.svg b/crates/cursor-info/assets/mac/ibeam_vertical.svg new file mode 100644 index 00000000000..4d77ae9c0b5 --- /dev/null +++ b/crates/cursor-info/assets/mac/ibeam_vertical.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/open_hand.svg b/crates/cursor-info/assets/mac/open_hand.svg new file mode 100644 index 00000000000..9b4b6a096c0 --- /dev/null +++ b/crates/cursor-info/assets/mac/open_hand.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/operation_not_allowed.svg b/crates/cursor-info/assets/mac/operation_not_allowed.svg new file mode 100644 index 00000000000..65d0d2a3c31 --- /dev/null +++ b/crates/cursor-info/assets/mac/operation_not_allowed.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/pointing_hand.svg b/crates/cursor-info/assets/mac/pointing_hand.svg new file mode 100644 index 00000000000..ef77a7d706e --- /dev/null +++ b/crates/cursor-info/assets/mac/pointing_hand.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/resize_down.svg b/crates/cursor-info/assets/mac/resize_down.svg new file mode 100644 index 00000000000..794d7a672f1 --- /dev/null +++ b/crates/cursor-info/assets/mac/resize_down.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/resize_left.svg b/crates/cursor-info/assets/mac/resize_left.svg new file mode 100644 index 00000000000..ee59c47d475 --- /dev/null +++ b/crates/cursor-info/assets/mac/resize_left.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/resize_left_right.svg b/crates/cursor-info/assets/mac/resize_left_right.svg new file mode 100644 index 00000000000..fc280d40756 --- /dev/null +++ b/crates/cursor-info/assets/mac/resize_left_right.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/resize_right.svg b/crates/cursor-info/assets/mac/resize_right.svg new file mode 100644 index 00000000000..f0fe6c64b34 --- /dev/null +++ b/crates/cursor-info/assets/mac/resize_right.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/resize_up.svg b/crates/cursor-info/assets/mac/resize_up.svg new file mode 100644 index 00000000000..41bcc685b67 --- /dev/null +++ b/crates/cursor-info/assets/mac/resize_up.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/mac/resize_up_down.svg b/crates/cursor-info/assets/mac/resize_up_down.svg new file mode 100644 index 00000000000..09eccb1962e --- /dev/null +++ b/crates/cursor-info/assets/mac/resize_up_down.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/cursor-info/assets/windows/arrow.svg b/crates/cursor-info/assets/windows/arrow.svg new file mode 100644 index 00000000000..8fc222050eb --- /dev/null +++ b/crates/cursor-info/assets/windows/arrow.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/cursor-info/assets/windows/cross.svg b/crates/cursor-info/assets/windows/cross.svg new file mode 100644 index 00000000000..a96f1b0a0e6 --- /dev/null +++ b/crates/cursor-info/assets/windows/cross.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/cursor-info/assets/windows/hand.svg b/crates/cursor-info/assets/windows/hand.svg new file mode 100644 index 00000000000..9705811906a --- /dev/null +++ b/crates/cursor-info/assets/windows/hand.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/crates/cursor-info/assets/windows/ibeam.svg b/crates/cursor-info/assets/windows/ibeam.svg new file mode 100644 index 00000000000..bd12ae6b23b --- /dev/null +++ b/crates/cursor-info/assets/windows/ibeam.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/cursor-info/assets/windows/no.svg b/crates/cursor-info/assets/windows/no.svg new file mode 100644 index 00000000000..c9a3dc140f5 --- /dev/null +++ b/crates/cursor-info/assets/windows/no.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/cursor-info/assets/windows/pen.svg b/crates/cursor-info/assets/windows/pen.svg new file mode 100644 index 00000000000..720137b75be --- /dev/null +++ b/crates/cursor-info/assets/windows/pen.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/crates/cursor-info/assets/windows/size-nesw.svg b/crates/cursor-info/assets/windows/size-nesw.svg new file mode 100644 index 00000000000..889732e7510 --- /dev/null +++ b/crates/cursor-info/assets/windows/size-nesw.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/cursor-info/assets/windows/size-ns.svg b/crates/cursor-info/assets/windows/size-ns.svg new file mode 100644 index 00000000000..6d1be6bf43e --- /dev/null +++ b/crates/cursor-info/assets/windows/size-ns.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/cursor-info/assets/windows/sizeall.svg b/crates/cursor-info/assets/windows/sizeall.svg new file mode 100644 index 00000000000..a3d615abd02 --- /dev/null +++ b/crates/cursor-info/assets/windows/sizeall.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/cursor-info/assets/windows/wait.svg b/crates/cursor-info/assets/windows/wait.svg new file mode 100644 index 00000000000..256de2f5d0c --- /dev/null +++ b/crates/cursor-info/assets/windows/wait.svg @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/cursor-info/cursors.html b/crates/cursor-info/cursors.html new file mode 100644 index 00000000000..df920e5f02e --- /dev/null +++ b/crates/cursor-info/cursors.html @@ -0,0 +1,427 @@ + + + + + + Cursor Hotspot Viewer + + + +
+

Cursor Hotspot Viewer

+

+ Hover over cursors to see mouse coordinates, click to copy hotspot + values +

+
+ +
+

macOS Cursors

+
+
+ +
+

Windows Cursors

+
+
+ + + + diff --git a/crates/cursor-info/examples/cli.rs b/crates/cursor-info/examples/cli.rs new file mode 100644 index 00000000000..9047c9c602f --- /dev/null +++ b/crates/cursor-info/examples/cli.rs @@ -0,0 +1,451 @@ +use std::collections::HashMap; + +use sha2::{Digest, Sha256}; + +fn main() { + #[cfg(any(target_os = "macos", target_os = "windows"))] + return run(); + #[allow(unreachable_code)] + panic!("Unsupported platform!"); +} + +#[cfg(target_os = "macos")] +#[allow(deprecated)] +fn run() { + use objc2::{MainThreadMarker, rc::Retained}; + use objc2_app_kit::{NSApplication, NSCursor}; + + let mtm = MainThreadMarker::new().expect("Not on main thread"); + let _app: Retained = NSApplication::sharedApplication(mtm); + + let cursors = vec![ + ("arrow", NSCursor::arrowCursor()), + ("contextualMenu", NSCursor::contextualMenuCursor()), + ("closedHand", NSCursor::closedHandCursor()), + ("crosshair", NSCursor::crosshairCursor()), + ("disappearingItem", NSCursor::disappearingItemCursor()), + ("dragCopy", NSCursor::dragCopyCursor()), + ("dragLink", NSCursor::dragLinkCursor()), + ("IBeam", NSCursor::IBeamCursor()), + ("openHand", NSCursor::openHandCursor()), + ("operationNotAllowed", NSCursor::operationNotAllowedCursor()), + ("pointingHand", NSCursor::pointingHandCursor()), + ("resizeDown", NSCursor::resizeDownCursor()), + ("resizeLeft", NSCursor::resizeLeftCursor()), + ("resizeLeftRight", NSCursor::resizeLeftRightCursor()), + ("resizeRight", NSCursor::resizeRightCursor()), + ("resizeUp", NSCursor::resizeUpCursor()), + ("resizeUpDown", NSCursor::resizeUpDownCursor()), + ("IBeamVertical", NSCursor::IBeamCursorForVerticalLayout()), + ]; + + unsafe { + let mut cursor_lookup = HashMap::new(); + + for (name, cursor) in cursors { + let hash = hex::encode(Sha256::digest( + &cursor + .image() + .TIFFRepresentation() + .expect("Failed to get TIFF representation of built-in cursor") + .as_bytes_unchecked(), + )); + println!("{name}: {}", hash); + cursor_lookup.insert(hash, name); + } + + // return; + + loop { + #[allow(deprecated)] + let cursor = NSCursor::currentSystemCursor().unwrap_or(NSCursor::currentCursor()); + let hash = hex::encode(Sha256::digest( + &cursor + .image() + .TIFFRepresentation() + .expect("Failed to get TIFF representation of built-in cursor") + .as_bytes_unchecked(), + )); + + if cursor_lookup.get(&hash).is_none() { + panic!("Cursor hash '{hash}' not known",); + }; + + println!( + "{cursor:?} {hash} {}", + cursor_lookup.get(&hash).unwrap_or(&"Unknown") + ); + } + }; +} + +#[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, + }; + + #[inline] + fn load_cursor(lpcursorname: PCWSTR) -> HCURSOR { + unsafe { LoadCursorW(None, lpcursorname) }.expect("Failed to load default system cursors") + } + + fn get_icon(hCursor: HCURSOR) -> Vec { + 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::() 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::() 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 + }; + + // 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])); + } + } + } + } + } + } + } + + // 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); + } + } + + // 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 + } + .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::() 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")); + } +} diff --git a/crates/cursor-info/src/lib.rs b/crates/cursor-info/src/lib.rs new file mode 100644 index 00000000000..db0a9b3c2ff --- /dev/null +++ b/crates/cursor-info/src/lib.rs @@ -0,0 +1,206 @@ +//! Cap Cursor Info: A crate for getting cursor information, assets and hotspot information. + +/// Information about a resolved cursor shape +#[derive(Debug, Clone)] +pub struct ResolvedCursor { + /// Raw svg definition of the cursor asset + pub raw: &'static str, + /// The location of the hotspot within the cursor asset + 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 { + Some(match s.as_str() { + // + // macOS Cursors + // https://developer.apple.com/documentation/appkit/nscursor + // + + // https://developer.apple.com/documentation/appkit/nscursor/arrow + "de2d1f4a81e520b65fd1317b845b00a1c51a4d1f71cca3cd4ccdab52b98d1ac9" => ResolvedCursor { + raw: include_str!("../assets/mac/arrow.svg"), + hotspot: (0.235, 0.174), // 40.0/170.0, 40.0/230.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/contextualmenu + "ab26ca862492d41355b711c58544687a799dd7ae14cf161959ca524bbc97c322" => ResolvedCursor { + raw: include_str!("../assets/mac/contextual_menu.svg"), + hotspot: (0.179, 0.125), // 10.0/56.0, 10.0/80.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/closedhand + "fbb165d4603dd8808b536f45bb74a9a72d9358ad19714b318bb7c06358a7d3c2" => ResolvedCursor { + raw: include_str!("../assets/mac/closed_hand.svg"), + hotspot: (0.5, 0.5), // 32.0/64.0, 32.0/64.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/crosshair + "c583f776531f4e7b76ea7ba2ab159765e2da11fd63cb897cc10362183859d1d8" => ResolvedCursor { + raw: include_str!("../assets/mac/crosshair.svg"), + hotspot: (0.458, 0.458), // 22.0/48.0, 22.0/48.0 + }, + // 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.179, 0.125), // 10.0/56.0, 10.0/80.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/draglink + "59ac2483461f4ad577a0a6b68be89fe663c36263b583c5f038eee2ae6a5ad98f" => ResolvedCursor { + raw: include_str!("../assets/mac/drag_link.svg"), + hotspot: (0.688, 0.143), // 22.0/32.0, 6.0/42.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/ibeam + "492dca0bb6751a30607ac728803af992ba69365052b7df2dff1c0dfe463e653c" => ResolvedCursor { + raw: include_str!("../assets/mac/ibeam.svg"), + hotspot: (0.444, 0.5), // 40.0/90.0, 90.0/180.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/openhand + "3f6a5594a3c9334065944b9c56d9f73fd5fe5f02108a5e28f37e222e770be476" => ResolvedCursor { + raw: include_str!("../assets/mac/open_hand.svg"), + hotspot: (0.5, 0.5), // 32.0/64.0, 32.0/64.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/operationnotallowed + "37287ef1d097704d3e9d0be9c1049ce1fb6dfabd6d210af0429b1b6ec7084c59" => ResolvedCursor { + raw: include_str!("../assets/mac/operation_not_allowed.svg"), + hotspot: (0.179, 0.125), // 10.0/56.0, 10.0/80.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/pointinghand + "b0443e9f72e724cb6d94b879bf29c6cb18376d0357c6233e5a7561cf8a9943c6" => ResolvedCursor { + raw: include_str!("../assets/mac/pointing_hand.svg"), + hotspot: (0.406, 0.25), // 26.0/64.0, 16.0/64.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/resizedown + "3c9bf0ce893b64fe9e4363793b406140d4b3900b7beafa1c409e78cf5a8cf954" => ResolvedCursor { + raw: include_str!("../assets/mac/resize_down.svg"), + hotspot: (0.5, 0.5), // 24.0/48.0, 24.0/48.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/resizeleft + "50431d8fd537119aefb4c3673f9b9ff00d3cd1d2bf6c35e5dfb09ed40cfd5e7c" => ResolvedCursor { + raw: include_str!("../assets/mac/resize_left.svg"), + hotspot: (0.5, 0.5), // 24.0/48.0, 24.0/48.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/resizeleftright + "0fdaea89910bcbe34ad0d4d63a6ada2095489df18537bbf54dd0d0769588b381" => ResolvedCursor { + raw: include_str!("../assets/mac/resize_left_right.svg"), + hotspot: (0.5, 0.5), // 24.0/48.0, 24.0/48.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/resizeright + "e74de88f863f059e5beb27152b2dfc2cd1e8dcc458ce775607765e9a4859667e" => ResolvedCursor { + raw: include_str!("../assets/mac/resize_right.svg"), + hotspot: (0.5, 0.5), // 24.0/48.0, 24.0/48.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/resizeup + "912ca42451a9624f6fb8c1d53c29c26782b7590d383a66075a6768c4409024d9" => ResolvedCursor { + raw: include_str!("../assets/mac/resize_up.svg"), + hotspot: (0.5, 0.5), // 24.0/48.0, 24.0/48.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/resizeupdown + "9c93eb53df68d7fd86298ba1eb3e3b32ccd34d168b81a31a6fc4bb79f131331f" => ResolvedCursor { + raw: include_str!("../assets/mac/resize_up_down.svg"), + hotspot: (0.5, 0.5), // 24.0/48.0, 24.0/48.0 + }, + // https://developer.apple.com/documentation/appkit/nscursor/ibeamcursorforverticallayout + "024e1d486a7f16368669d419e69c9a326e464ec1b8ed39645e5c89cb183e03c5" => ResolvedCursor { + raw: include_str!("../assets/mac/ibeam_vertical.svg"), + hotspot: (0.389, 0.25), // 14.0/36.0, 8.0/32.0 + }, + + // + // Windows Cursors + // https://learn.microsoft.com/en-us/windows/win32/menurc/about-cursors + // + + // IDC_ARROW + "19502718917bb8a86b83ffb168021cf90517b5c5e510c33423060d230c9e2d20" => ResolvedCursor { + raw: include_str!("../assets/windows/arrow.svg"), + hotspot: (0.027, 0.041), // Arrow tip at top-left + }, + // IDC_IBEAM + "77cc4cedcf68f3e1d41bfe16c567961b2306c6236b35b966cd3d5c9516565e33" => ResolvedCursor { + raw: include_str!("../assets/windows/ibeam.svg"), + hotspot: (0.5, 0.5), // Center of I-beam + }, + // IDC_WAIT + "5991d86a0d4e915dd0cb0fdd9bef3bf37ed6a3b321256fcb5b240db7ac1a6324" => ResolvedCursor { + raw: include_str!("../assets/windows/wait.svg"), + hotspot: (0.5, 0.5), // Center of hourglass + }, + // IDC_CROSS + "cd2c775b1a124e4deaed1ed345efae25eb28a9133fc39691555902a2c1d7d578" => ResolvedCursor { + raw: include_str!("../assets/windows/cross.svg"), + hotspot: (0.5, 0.5), // Center of crosshair + }, + // // IDC_UPARROW + // "823d642acdc51ffbc29c2710303606270ed24936daf45215ead531333df102ba" => todo!(), + // // IDC_SIZENWSE + // "2daf2a40e4c7ecadec3270fbdb243a12ac22a14bb0b3a08a56b38a38322f9296" => todo!(), + // IDC_SIZENESW + "47b4d609cb404feae70c7e20b525ac901d1e7a5f1a2e8a240418b3710ee43473" => ResolvedCursor { + raw: include_str!("../assets/windows/size-nesw.svg"), + hotspot: (0.5, 0.5), // Center of resize cursor + }, + // // IDC_SIZEWE + // "8a024cf4bec4d58a4c149af2320206088981357312b3d82fbfcc07bee38c71ac" => todo!(), + // IDC_SIZENS + "253b9e5360de1e12561be6a8f84484d4b108fd54d31e7d2c8f3b66d1c71b9880" => ResolvedCursor { + raw: include_str!("../assets/windows/size-ns.svg"), + hotspot: (0.5, 0.5), // Center of vertical resize cursor + }, + // // IDC_SIZEALL + // "8066a12792e4e8ef21636e5ade61adaaf0fecc2ffc69536ffa0c2dd5bedc6903" => todo!(), + // IDC_NO + "7df883a459aced72acf32b969ff1119676d334d9acfcbe668ef92fe01094a7d6" => ResolvedCursor { + raw: include_str!("../assets/windows/no.svg"), + hotspot: (0.5, 0.5), // Center of "not allowed" symbol + }, + // IDC_HAND + "44a554b439a681410d337d239bf08afe7c66486538563ebb93dc1c309f0a9209" => ResolvedCursor { + raw: include_str!("../assets/windows/hand.svg"), + hotspot: (0.421, 0.009), // Tip of pointing finger + }, + // // IDC_APPSTARTING + // "1486a2339478da61a52a6eecf8ee3446be62f12d375dba8befd42bb553eea7bf" => todo!(), + // // IDC_HELP + // "5d0b4df6188bc8d540abfbd4235199cc0f67fb41d5e0dcbfd40a3011f8808fea" => todo!(), + // // IDC_PIN + // "cb74a2d34774dbc43004882e43f9c058b2d2ee60184185567d0328ca013f5bc3" => todo!(), + // // IDC_PERSON + // "1f5209791a75916697c26cf2d018d267ae1102c71dbd196de6c83132f5627f09" => todo!(), + // MAKEINTRESOURCE(32631) - Pen + "7340ea75802db8fef3a103e9385e65b2c8c358e077ef949faaf572fb502dd9e2" => ResolvedCursor { + raw: include_str!("../assets/windows/pen.svg"), + hotspot: (0.03, 0.97), // Tip of pen at bottom-left + }, + // // 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, + }) + } +} diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs index 4804911dc80..14eae6f0a5c 100644 --- a/crates/editor/src/editor_instance.rs +++ b/crates/editor/src/editor_instance.rs @@ -65,7 +65,7 @@ impl EditorInstance { let (ws_port, ws_shutdown_token) = create_frame_ws(frame_rx).await; let render_constants = Arc::new( - RenderVideoConstants::new(&recordings.segments, &recording_meta, meta) + RenderVideoConstants::new(&recordings.segments, recording_meta.clone(), meta.clone()) .await .unwrap(), ); diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index 9923c977fed..ccb4fe953f3 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -2,7 +2,7 @@ pub mod gif; pub mod mp4; use cap_editor::Segment; -use cap_project::{ProjectConfiguration, RecordingMeta, StudioRecordingMeta, XY}; +use cap_project::{ProjectConfiguration, RecordingMeta, StudioRecordingMeta}; use cap_rendering::{ProjectRecordingsMeta, RenderVideoConstants}; use std::{path::PathBuf, sync::Arc}; use tracing::error; @@ -82,9 +82,13 @@ impl ExporterBuilder { ); let render_constants = Arc::new( - RenderVideoConstants::new(&recordings.segments, &recording_meta, studio_meta) - .await - .unwrap(), + RenderVideoConstants::new( + &recordings.segments, + recording_meta.clone(), + studio_meta.clone(), + ) + .await + .unwrap(), ); let segments = cap_editor::create_segments(&recording_meta, studio_meta) diff --git a/crates/media/src/platform/mod.rs b/crates/media/src/platform/mod.rs index fc667d5d745..894d20d4b5c 100644 --- a/crates/media/src/platform/mod.rs +++ b/crates/media/src/platform/mod.rs @@ -28,74 +28,6 @@ pub struct Window { pub bounds: Bounds, } -#[derive(Debug, Clone, Copy, Serialize, Deserialize, Type, PartialEq, Eq, PartialOrd, Ord)] -pub enum CursorShape { - /// Windows: IDC_ARROW - Arrow, - /// Windows: IDC_IBEAM - IBeam, - /// Windows: IDC_CROSS - Crosshair, - /// macOS Only. Windows not supported. - ClosedHand, - /// macOS Only. Windows not supported. - OpenHand, - /// macOS Only. Windows not supported. - PointingHand, - /// macOS Only. Windows not supported. - ResizeLeft, - /// macOS Only. Windows not supported. - ResizeRight, - /// Windows: IDC_SIZEWE - ResizeLeftRight, - /// Windows: IDC_UPARROW - ResizeUp, - /// macOS Only. Windows not supported. - ResizeDown, - /// Windows: IDC_SIZENS - ResizeUpDown, - /// Windows: IDC_SIZENWSE - /// - /// Windows only. macOS not supported. - ResizeUpLeftAndDownRight, - /// Windows: IDC_SIZENESW - /// - /// Windows only. macOS not supported. - ResizeUpRightAndDownLeft, - /// Windows: IDC_SIZEALL - /// - /// Windows only. macOS not supported. - ResizeAll, - /// macOS Only. Windows not supported. - DisappearingItem, - /// macOS Only. Windows not supported. - VerticalIBeam, - /// Windows: IDC_NO - NotAllowed, - /// macOS Only. Windows not supported. - DragLink, - /// macOS Only. Windows not supported. - DragCopy, - /// macOS Only. Windows not supported. - ContextualMenu, - /// Windows only. macOS not supported. - Appstarting, - /// Windows: IDC_WAIT - /// - /// Windows only. macOS not supported. - Wait, - /// Windows: IDC_HELP - /// - /// Windows only. macOS not supported. - Help, - /// Windows only. macOS not supported. - /// - /// Indicates the cursor is not visible. - Hidden, - /// Couldn't get the cursor shape. - Unknown, -} - #[derive(Debug, Clone, Copy)] pub struct LogicalPosition { pub x: f64, diff --git a/crates/media/src/platform/win.rs b/crates/media/src/platform/win.rs index 80d44d2e2f5..897b4a7893c 100644 --- a/crates/media/src/platform/win.rs +++ b/crates/media/src/platform/win.rs @@ -3,7 +3,7 @@ use std::ffi::{c_void, OsString}; use std::os::windows::ffi::OsStringExt; use std::path::PathBuf; -use super::{Bounds, CursorShape, LogicalBounds, LogicalPosition, LogicalSize, Window}; +use super::{Bounds, LogicalBounds, LogicalPosition, LogicalSize, Window}; use tracing::debug; use windows::core::{BOOL, PCWSTR, PWSTR}; @@ -35,87 +35,6 @@ pub fn bring_window_to_focus(window_id: u32) { let _ = unsafe { SetForegroundWindow(HWND(window_id as *mut c_void)) }; } -pub fn get_cursor_shape(cursors: &DefaultCursors) -> CursorShape { - let mut cursor_info = CURSORINFO { - cbSize: std::mem::size_of::() as u32, - ..Default::default() - }; - match unsafe { GetCursorInfo(&mut cursor_info) } { - Ok(_) => match cursor_info.hCursor.0 { - ptr if ptr == cursors.arrow => CursorShape::Arrow, - ptr if ptr == cursors.ibeam => CursorShape::IBeam, - ptr if ptr == cursors.wait => CursorShape::Wait, - ptr if ptr == cursors.cross => CursorShape::Crosshair, - ptr if ptr == cursors.up_arrow => CursorShape::ResizeUp, - ptr if ptr == cursors.size_we => CursorShape::ResizeLeftRight, - ptr if ptr == cursors.size_ns => CursorShape::ResizeUpDown, - ptr if ptr == cursors.size_nwse => CursorShape::ResizeUpLeftAndDownRight, - ptr if ptr == cursors.size_nesw => CursorShape::ResizeUpRightAndDownLeft, - ptr if ptr == cursors.size_all => CursorShape::ResizeAll, - ptr if ptr == cursors.hand => CursorShape::OpenHand, - ptr if ptr == cursors.no => CursorShape::NotAllowed, - ptr if ptr == cursors.appstarting => CursorShape::Appstarting, - ptr if ptr == cursors.help => CursorShape::Help, - ptr if ptr == cursors.pin || ptr == cursors.person => CursorShape::OpenHand, - // Usually 0, meaning the cursor is hidden. On Windows 8+, a value of 2 means the cursor is supressed - // as the user is using touch input instead. - _ => CursorShape::Hidden, - }, - Err(_) => CursorShape::Unknown, - } -} - -/// Keeps handles to default cursor. -/// Read more: [MS Doc - About Cursors](https://learn.microsoft.com/en-us/windows/win32/menurc/about-cursors) -pub struct DefaultCursors { - arrow: *mut c_void, - ibeam: *mut c_void, - wait: *mut c_void, - cross: *mut c_void, - up_arrow: *mut c_void, - size_nwse: *mut c_void, - size_nesw: *mut c_void, - size_we: *mut c_void, - size_ns: *mut c_void, - size_all: *mut c_void, - no: *mut c_void, - hand: *mut c_void, - appstarting: *mut c_void, - help: *mut c_void, - pin: *mut c_void, - person: *mut c_void, -} - -impl Default for DefaultCursors { - fn default() -> Self { - #[inline] - fn load_cursor(lpcursorname: PCWSTR) -> *mut c_void { - unsafe { LoadCursorW(None, lpcursorname) } - .expect("Failed to load default system cursors") - .0 - } - - DefaultCursors { - arrow: load_cursor(IDC_ARROW), - ibeam: load_cursor(IDC_IBEAM), - cross: load_cursor(IDC_CROSS), - hand: load_cursor(IDC_HAND), - help: load_cursor(IDC_HELP), - no: load_cursor(IDC_NO), - size_all: load_cursor(IDC_SIZEALL), - size_ns: load_cursor(IDC_SIZENS), - size_we: load_cursor(IDC_SIZEWE), - size_nwse: load_cursor(IDC_SIZENWSE), - size_nesw: load_cursor(IDC_SIZENESW), - up_arrow: load_cursor(IDC_UPARROW), - wait: load_cursor(IDC_WAIT), - appstarting: load_cursor(IDC_APPSTARTING), - pin: load_cursor(IDC_PIN), - person: load_cursor(IDC_PERSON), - } - } -} - unsafe fn pid_to_exe_path(pid: u32) -> Result { let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid)?; if handle.is_invalid() { diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs index 3e29d07c342..1e9fae991ca 100644 --- a/crates/project/src/configuration.rs +++ b/crates/project/src/configuration.rs @@ -59,7 +59,7 @@ pub struct XY { } impl XY { - pub fn new(x: T, y: T) -> Self { + pub const fn new(x: T, y: T) -> Self { Self { x, y } } @@ -148,6 +148,24 @@ impl> Div> for XY { } } +impl Into> for XY { + fn into(self) -> XY { + XY { + x: self.x as f64, + y: self.y as f64, + } + } +} + +impl Into> for (T, T) { + fn into(self) -> XY { + XY { + x: self.0, + y: self.1, + } + } +} + #[derive(Type, Serialize, Deserialize, Clone, Debug, Default)] #[serde(rename_all = "camelCase")] pub struct Crop { @@ -354,6 +372,12 @@ pub struct CursorConfiguration { pub raw: bool, #[serde(default)] pub motion_blur: f32, + #[serde(default = "yes")] + pub use_svg: bool, +} + +fn yes() -> bool { + true } impl Default for CursorConfiguration { @@ -369,6 +393,7 @@ impl Default for CursorConfiguration { friction: 20.0, raw: false, motion_blur: 0.5, + use_svg: true, } } } @@ -539,7 +564,7 @@ impl ProjectConfiguration { pub fn load(project_path: impl AsRef) -> Result { let config_str = std::fs::read_to_string(project_path.as_ref().join("project-config.json"))?; - let mut config: Self = serde_json::from_str(&config_str).unwrap_or_default(); + let config: Self = serde_json::from_str(&config_str).unwrap_or_default(); Ok(config) } diff --git a/crates/project/src/meta.rs b/crates/project/src/meta.rs index 45e0e05609b..2d8013dca98 100644 --- a/crates/project/src/meta.rs +++ b/crates/project/src/meta.rs @@ -10,7 +10,7 @@ use std::{ use tracing::{debug, info, warn}; // use tracing::{debug, warn}; -use crate::{CaptionsData, CursorEvents, CursorImage, CursorImages, ProjectConfiguration, XY}; +use crate::{CaptionsData, CursorEvents, CursorImage, ProjectConfiguration, XY}; #[derive(Debug, Clone, Serialize, Deserialize, Type)] pub struct VideoMeta { @@ -60,6 +60,7 @@ impl Default for Platform { #[derive(Debug, Clone, Serialize, Deserialize, Type)] pub struct RecordingMeta { + #[serde(default)] pub platform: Option, // this field is just for convenience, it shouldn't be persisted #[serde(skip_serializing, default)] @@ -242,6 +243,8 @@ pub struct CursorMeta { #[specta(type = String)] pub image_path: RelativePathBuf, pub hotspot: XY, + #[serde(default)] + pub hash: Option, } impl MultipleSegments { @@ -249,22 +252,17 @@ impl MultipleSegments { meta.project_path.join(path) } - pub fn cursor_images(&self, meta: &RecordingMeta) -> Result { - Ok(CursorImages(match &self.cursors { - Cursors::Old(_) => Default::default(), - Cursors::Correct(map) => map - .iter() - .map(|(k, v)| { - ( - k.clone(), - CursorImage { - path: meta.path(&v.image_path), - hotspot: v.hotspot, - }, - ) + pub fn get_cursor_image(&self, meta: &RecordingMeta, id: &str) -> Option { + match &self.cursors { + Cursors::Old(_) => None, + Cursors::Correct(map) => { + let cursor = map.get(id)?; + Some(CursorImage { + path: meta.path(&cursor.image_path), + hotspot: cursor.hotspot, }) - .collect::<_>(), - })) + } + } } } diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml index 4468eb9c9a6..ab6bb41b787 100644 --- a/crates/recording/Cargo.toml +++ b/crates/recording/Cargo.toml @@ -34,12 +34,15 @@ tracing-subscriber = { version = "0.3.19", features = ["env-filter"] } relative-path = "1.9.3" futures = "0.3.31" tokio-util = "0.7.15" +sha2 = "0.10.9" +hex = "0.4.3" [target.'cfg(target_os = "macos")'.dependencies] screencapturekit = "0.3.5" cocoa = "0.26.0" objc = "0.2.7" cidre = { workspace = true } +objc2-app-kit = "0.3.1" [target.'cfg(target_os = "windows")'.dependencies] windows = { workspace = true, features = [ diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rs index 27dea01329f..926243efe97 100644 --- a/crates/recording/src/cursor.rs +++ b/crates/recording/src/cursor.rs @@ -13,6 +13,7 @@ use cap_project::{CursorClickEvent, CursorMoveEvent, XY}; use cap_utils::spawn_actor; use device_query::{DeviceQuery, DeviceState}; use futures::future::Either; +use sha2::{Digest, Sha256}; use tokio::sync::oneshot; use tokio_util::sync::CancellationToken; use tracing::{error, info}; @@ -21,6 +22,7 @@ pub struct Cursor { pub file_name: String, pub id: u32, pub hotspot: XY, + pub hash: String, } pub type Cursors = HashMap; @@ -90,7 +92,7 @@ pub fn spawn_cursor_recorder( let elapsed = elapsed.as_secs_f64() * 1000.0; let mouse_state = device_state.get_mouse(); - let cursor_data = get_cursor_image_data(); + let cursor_data = get_cursor_data(); let cursor_id = if let Some(data) = cursor_data { let mut hasher = DefaultHasher::default(); data.image.hash(&mut hasher); @@ -105,6 +107,7 @@ 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(); @@ -119,6 +122,7 @@ pub fn spawn_cursor_recorder( file_name, id: response.next_cursor_id, hotspot: data.hotspot, + hash, }, ); response.next_cursor_id += 1; @@ -243,64 +247,32 @@ struct CursorData { } #[cfg(target_os = "macos")] -fn get_cursor_image_data() -> Option { - use cocoa::base::{id, nil}; - use cocoa::foundation::{NSPoint, NSSize, NSUInteger}; +fn get_cursor_data() -> Option { use objc::rc::autoreleasepool; - use objc::runtime::Class; - use objc::*; + use objc2_app_kit::NSCursor; - autoreleasepool(|| { - let nscursor_class = match Class::get("NSCursor") { - Some(cls) => cls, - None => return None, - }; - - unsafe { - // Get the current system cursor - let current_cursor: id = msg_send![nscursor_class, currentSystemCursor]; - if current_cursor == nil { - return None; - } - - // Get the image of the cursor - let cursor_image: id = msg_send![current_cursor, image]; - if cursor_image == nil { - return None; - } - - let cursor_size: NSSize = msg_send![cursor_image, size]; - let cursor_hotspot: NSPoint = msg_send![current_cursor, hotSpot]; - - // Get the TIFF representation of the image - let image_data: id = msg_send![cursor_image, TIFFRepresentation]; - if image_data == nil { - return None; - } - - // Get the length of the data - let length: NSUInteger = msg_send![image_data, length]; + autoreleasepool(|| unsafe { + #[allow(deprecated)] + let cursor = NSCursor::currentSystemCursor().unwrap_or(NSCursor::currentCursor()); - // Get the bytes of the data - let bytes: *const u8 = msg_send![image_data, bytes]; + let image = cursor.image(); + let size = image.size(); + let hotspot = cursor.hotSpot(); + let Some(image_data) = image.TIFFRepresentation() else { + return None; + }; - // Copy the data into a Vec - let slice = std::slice::from_raw_parts(bytes, length as usize); - let data = slice.to_vec(); + let image = image_data.as_bytes_unchecked().to_vec(); - Some(CursorData { - image: data, - hotspot: XY::new( - cursor_hotspot.x / cursor_size.width, - cursor_hotspot.y / cursor_size.height, - ), - }) - } + Some(CursorData { + image, + hotspot: XY::new(hotspot.x / size.width, hotspot.y / size.height), + }) }) } #[cfg(windows)] -fn get_cursor_image_data() -> Option { +fn get_cursor_data() -> Option { use windows::Win32::Foundation::{HWND, POINT}; use windows::Win32::Graphics::Gdi::{ CreateCompatibleDC, CreateDIBSection, DeleteDC, DeleteObject, GetDC, GetObjectA, ReleaseDC, diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index b178ce16f0a..b068d282e88 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -525,6 +525,7 @@ async fn stop_recording( image_path: RelativePathBuf::from("content/cursors") .join(&cursor.file_name), hotspot: cursor.hotspot, + hash: Some(cursor.hash), }, ) }) diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml index be965326537..2baf9af1107 100644 --- a/crates/rendering/Cargo.toml +++ b/crates/rendering/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "cap-rendering" version = "0.1.0" -edition = "2021" +edition = "2024" [lints] workspace = true @@ -12,6 +12,7 @@ bytemuck = { version = "1.7", features = ["derive"] } cap-flags = { path = "../flags" } cap-project = { path = "../project" } cap-video-decode = { path = "../video-decode" } +cap-cursor-info = { path = "../cursor-info" } ffmpeg-hw-device = { path = "../ffmpeg-hw-device" } tokio.workspace = true ffmpeg.workspace = true @@ -28,6 +29,8 @@ bezier_easing = "0.1.1" reactive_graph = "0.1.5" glyphon = "0.9.0" tracing.workspace = true +resvg = "0.45" +tiny-skia = "0.11" [target.'cfg(target_os = "macos")'.dependencies] cidre.workspace = true diff --git a/crates/rendering/src/coord.rs b/crates/rendering/src/coord.rs index f301dd1284f..29cc5046f2b 100644 --- a/crates/rendering/src/coord.rs +++ b/crates/rendering/src/coord.rs @@ -2,7 +2,7 @@ use std::ops::{Add, Deref, Mul, Sub}; use cap_project::{ProjectConfiguration, XY}; -use crate::{zoom::InterpolatedZoom, ProjectUniforms, RenderOptions}; +use crate::{ProjectUniforms, RenderOptions, zoom::InterpolatedZoom}; #[derive(Default, Clone, Copy, Debug)] pub struct RawDisplaySpace; diff --git a/crates/rendering/src/cursor_interpolation.rs b/crates/rendering/src/cursor_interpolation.rs index cd620143858..3b899236635 100644 --- a/crates/rendering/src/cursor_interpolation.rs +++ b/crates/rendering/src/cursor_interpolation.rs @@ -1,8 +1,8 @@ use cap_project::{CursorEvents, CursorMoveEvent, XY}; use crate::{ - spring_mass_damper::{SpringMassDamperSimulation, SpringMassDamperSimulationConfig}, Coord, RawDisplayUVSpace, + spring_mass_damper::{SpringMassDamperSimulation, SpringMassDamperSimulationConfig}, }; #[derive(Debug, Clone)] diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rs index 0e9d87b22c7..6b3fc203ad2 100644 --- a/crates/rendering/src/decoder/avassetreader.rs +++ b/crates/rendering/src/decoder/avassetreader.rs @@ -3,17 +3,17 @@ use std::{ collections::BTreeMap, path::PathBuf, rc::Rc, - sync::{mpsc, Arc}, + sync::{Arc, mpsc}, }; use cidre::{ arc::R, cv::{self, pixel_buffer::LockFlags}, }; -use ffmpeg::{format, frame, Rational}; +use ffmpeg::{Rational, format, frame}; use tokio::{runtime::Handle as TokioHandle, sync::oneshot}; -use super::{pts_to_frame, VideoDecoderMessage, FRAME_CACHE_SIZE}; +use super::{FRAME_CACHE_SIZE, VideoDecoderMessage, pts_to_frame}; #[derive(Clone)] struct ProcessedFrame { @@ -338,11 +338,7 @@ impl AVAssetReaderDecoder { let min = *cache.keys().min().unwrap(); let max = *cache.keys().max().unwrap(); - if current_frame > max { - min - } else { - max - } + if current_frame > max { min } else { max } }; cache.remove(&frame); diff --git a/crates/rendering/src/decoder/ffmpeg.rs b/crates/rendering/src/decoder/ffmpeg.rs index 8d23341b3da..d60e65aca90 100644 --- a/crates/rendering/src/decoder/ffmpeg.rs +++ b/crates/rendering/src/decoder/ffmpeg.rs @@ -3,15 +3,15 @@ use std::{ collections::BTreeMap, path::PathBuf, rc::Rc, - sync::{mpsc, Arc}, + sync::{Arc, mpsc}, }; -use ffmpeg::{codec, format, frame, software, Codec}; -use ffmpeg_sys_next::{avcodec_find_decoder, AVHWDeviceType}; +use ffmpeg::{Codec, codec, format, frame, software}; +use ffmpeg_sys_next::{AVHWDeviceType, avcodec_find_decoder}; use log::debug; use tokio::sync::oneshot; -use super::{pts_to_frame, VideoDecoderMessage, FRAME_CACHE_SIZE}; +use super::{FRAME_CACHE_SIZE, VideoDecoderMessage, pts_to_frame}; #[derive(Clone)] struct ProcessedFrame { @@ -201,11 +201,7 @@ impl FfmpegDecoder { let min = *cache.keys().min().unwrap(); let max = *cache.keys().max().unwrap(); - if current_frame > max { - min - } else { - max - } + if current_frame > max { min } else { max } }; cache.remove(&frame); diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rs index 1ff92d5f5ca..0cad645b2c1 100644 --- a/crates/rendering/src/decoder/mod.rs +++ b/crates/rendering/src/decoder/mod.rs @@ -1,7 +1,7 @@ use ::ffmpeg::Rational; use std::{ path::PathBuf, - sync::{mpsc, Arc}, + sync::{Arc, mpsc}, }; use tokio::sync::oneshot; diff --git a/crates/rendering/src/layers/background.rs b/crates/rendering/src/layers/background.rs index b328c8e0de1..441e9f44990 100644 --- a/crates/rendering/src/layers/background.rs +++ b/crates/rendering/src/layers/background.rs @@ -6,8 +6,8 @@ use specta::Type; use wgpu::{include_wgsl, util::DeviceExt}; use crate::{ - create_shader_render_pipeline, srgb_to_linear, ProjectUniforms, RenderVideoConstants, - RenderingError, + ProjectUniforms, RenderVideoConstants, RenderingError, create_shader_render_pipeline, + srgb_to_linear, }; #[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize, Type)] diff --git a/crates/rendering/src/layers/camera.rs b/crates/rendering/src/layers/camera.rs index 8b92395f2a4..9fa14f51440 100644 --- a/crates/rendering/src/layers/camera.rs +++ b/crates/rendering/src/layers/camera.rs @@ -2,7 +2,7 @@ use cap_project::XY; use wgpu::util::DeviceExt; use crate::{ - composite_frame::CompositeVideoFramePipeline, CompositeVideoFrameUniforms, DecodedFrame, + CompositeVideoFrameUniforms, DecodedFrame, composite_frame::CompositeVideoFramePipeline, }; pub struct CameraLayer { diff --git a/crates/rendering/src/layers/captions.rs b/crates/rendering/src/layers/captions.rs index eb7e51c9c9d..1a8b3461d60 100644 --- a/crates/rendering/src/layers/captions.rs +++ b/crates/rendering/src/layers/captions.rs @@ -5,9 +5,9 @@ use glyphon::{ TextArea, TextAtlas, TextBounds, TextRenderer, Viewport, }; use log::{debug, info, warn}; -use wgpu::{util::DeviceExt, Device, Queue}; +use wgpu::{Device, Queue, util::DeviceExt}; -use crate::{parse_color_component, DecodedSegmentFrames, ProjectUniforms, RenderVideoConstants}; +use crate::{DecodedSegmentFrames, ProjectUniforms, RenderVideoConstants, parse_color_component}; /// Represents a caption segment with timing and text #[derive(Debug, Clone)] diff --git a/crates/rendering/src/layers/cursor.rs b/crates/rendering/src/layers/cursor.rs index ef90e5b7324..fd6f912b966 100644 --- a/crates/rendering/src/layers/cursor.rs +++ b/crates/rendering/src/layers/cursor.rs @@ -1,19 +1,29 @@ +use std::collections::HashMap; + use bytemuck::{Pod, Zeroable}; +use cap_cursor_info::ResolvedCursor; use cap_project::*; -use wgpu::{include_wgsl, util::DeviceExt, BindGroup, FilterMode}; +use image::GenericImageView; +use tracing::error; +use wgpu::{BindGroup, FilterMode, include_wgsl, util::DeviceExt}; use crate::{ - zoom::InterpolatedZoom, DecodedSegmentFrames, ProjectUniforms, RenderVideoConstants, - STANDARD_CURSOR_HEIGHT, + DecodedSegmentFrames, ProjectUniforms, RenderVideoConstants, STANDARD_CURSOR_HEIGHT, + zoom::InterpolatedZoom, }; const CURSOR_CLICK_DURATION: f64 = 0.25; const CURSOR_CLICK_DURATION_MS: f64 = CURSOR_CLICK_DURATION * 1000.0; const CLICK_SHRINK_SIZE: f32 = 0.7; +/// The size to render the svg to. +static SVG_CURSOR_RASTERIZED_HEIGHT: u32 = 200; + pub struct CursorLayer { statics: Statics, bind_group: Option, + cursors: HashMap, + prev_is_svg_assets_enabled: Option, } struct Statics { @@ -169,6 +179,8 @@ impl CursorLayer { Self { statics, bind_group: None, + cursors: Default::default(), + prev_is_svg_assets_enabled: None, } } @@ -201,40 +213,116 @@ 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 Some(cursor_texture) = constants - .cursor_textures - .get(&interpolated_cursor.cursor_id) - else { + 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); + self.cursors.drain(); + } + + if !self.cursors.contains_key(&interpolated_cursor.cursor_id) { + let mut cursor = None; + + let cursor_hash = match &constants.recording_meta.inner { + RecordingMetaInner::Studio(StudioRecordingMeta::MultipleSegments { + inner: + MultipleSegments { + cursors: Cursors::Correct(cursors), + .. + }, + }) => cursors + .get(&interpolated_cursor.cursor_id) + .and_then(|v| v.hash.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 + && !uniforms.project.cursor.raw + && uniforms.project.cursor.use_svg + { + if let Some(info) = ResolvedCursor::from_hash(cursor_hash) { + cursor = CursorTexture::prepare_svg(&constants, info.raw, info.hotspot.into()) + .map_err(|err| { + error!( + "Error loading SVG cursor {:?}: {err}", + interpolated_cursor.cursor_id + ) + }) + .ok(); + } + } + + // If not we attempt to load the low-quality image cursor + if let StudioRecordingMeta::MultipleSegments { inner, .. } = &constants.meta + && cursor.is_none() + { + if let Some(c) = inner + .get_cursor_image(&constants.recording_meta, &interpolated_cursor.cursor_id) + { + if let Ok(img) = image::open(&c.path).map_err(|err| { + error!("Failed to load cursor image from {:?}: {err}", c.path) + }) { + cursor = Some(CursorTexture::prepare( + constants, + &img.to_rgba8(), + img.dimensions(), + c.hotspot, + )); + } + } + } + + if let Some(cursor) = cursor { + self.cursors + .insert(interpolated_cursor.cursor_id.clone(), cursor); + } + } + let Some(cursor_texture) = self.cursors.get(&interpolated_cursor.cursor_id) else { + error!("Cursor {:?} not found!", interpolated_cursor.cursor_id); return; }; let cursor_base_size_px = { - let cursor_texture_size = cursor_texture.inner.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 screen_size = constants.options.screen_size; let cursor_size_percentage = 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 factor = - STANDARD_CURSOR_HEIGHT / screen_size.y as f32 * uniforms.output_size.1 as f32; + let cursor_size_constant = + factor * cursor_size_percentage * zoom.display_amount() as f32; - XY::new( - factor * cursor_texture_size_aspect * cursor_size_percentage, - factor * cursor_size_percentage, - ) + if cursor_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; + XY::new(width, height) + } else { + // Tall or square cursor: base sizing on height (current behavior) + XY::new( + cursor_size_constant * cursor_texture_size_aspect, + cursor_size_constant, + ) + } }; let click_scale_factor = get_click_t(&cursor.clicks, (time_s as f64) * 1000.0) * (1.0 - CLICK_SHRINK_SIZE) + CLICK_SHRINK_SIZE; - let cursor_size_px = - cursor_base_size_px * click_scale_factor * zoom.display_amount() as f32; + let cursor_size_px: XY = (cursor_base_size_px * click_scale_factor).into(); let hotspot_px = cursor_texture.hotspot * cursor_size_px; @@ -254,7 +342,7 @@ impl CursorLayer { let uniforms = CursorUniforms { position: [position.x as f32, position.y as f32], - size: [cursor_size_px.x, cursor_size_px.y], + size: [cursor_size_px.x as f32, cursor_size_px.y as f32], output_size: [uniforms.output_size.0 as f32, uniforms.output_size.1 as f32], screen_bounds: uniforms.display.target_bounds, velocity, @@ -270,7 +358,7 @@ impl CursorLayer { self.bind_group = Some( self.statics - .create_bind_group(&constants.device, &cursor_texture.inner), + .create_bind_group(&constants.device, &cursor_texture.texture), ); } @@ -363,3 +451,104 @@ fn get_click_t(clicks: &[CursorClickEvent], time_ms: f64) -> f32 { 1.0 } + +struct CursorTexture { + texture: wgpu::Texture, + hotspot: XY, +} + +impl CursorTexture { + /// Prepare a cursor texture on the GPU from RGBA data. + fn prepare( + constants: &RenderVideoConstants, + rgba: &[u8], + dimensions: (u32, u32), + hotspot: XY, + ) -> Self { + let texture = constants.device.create_texture(&wgpu::TextureDescriptor { + label: Some("Cursor Texture"), + size: wgpu::Extent3d { + width: dimensions.0, + height: dimensions.1, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8UnormSrgb, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + + constants.queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &texture, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + &rgba, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(4 * dimensions.0), + rows_per_image: None, + }, + wgpu::Extent3d { + width: dimensions.0, + height: dimensions.1, + depth_or_array_layers: 1, + }, + ); + + Self { texture, hotspot } + } + + /// Prepare a cursor texture on the GPU from a raw SVG file + fn prepare_svg( + constants: &RenderVideoConstants, + svg_data: &str, + hotspot: XY, + ) -> Result { + let rtree = resvg::usvg::Tree::from_str(svg_data, &resvg::usvg::Options::default()) + .map_err(|e| format!("Failed to parse SVG: {}", e))?; + + // Although we could probably determine the size that the cursor is going to be render, + // that would depend on the cursor size the user selects. + // + // This would require reinitializing the texture every time that changes which would be more complicated. + // So we trade a small about VRAM for only initializing it once. + let aspect_ratio = rtree.size().width() / rtree.size().height(); + let width = (aspect_ratio * SVG_CURSOR_RASTERIZED_HEIGHT as f32) as u32; + + let mut pixmap = tiny_skia::Pixmap::new(width as u32, SVG_CURSOR_RASTERIZED_HEIGHT as u32) + .ok_or("Failed to create pixmap")?; + + // Calculate scale to fit the SVG into the target size while maintaining aspect ratio + let scale_x = width as f32 / rtree.size().width(); + let scale_y = SVG_CURSOR_RASTERIZED_HEIGHT as f32 / rtree.size().height(); + let scale = scale_x.min(scale_y) * 1.5; + let transform = tiny_skia::Transform::from_row( + scale, + 0.0, + 0.0, + scale, + (SVG_CURSOR_RASTERIZED_HEIGHT / 4) as f32 * -1.0, + (SVG_CURSOR_RASTERIZED_HEIGHT / 4) as f32 * -1.0, + ); + + resvg::render(&rtree, transform, &mut pixmap.as_mut()); + + let rgba: Vec = pixmap + .pixels() + .iter() + .flat_map(|p| [p.red(), p.green(), p.red(), p.alpha()]) + .collect(); + + Ok(Self::prepare( + constants, + &rgba, + (pixmap.width(), pixmap.height()), + hotspot, + )) + } +} diff --git a/crates/rendering/src/layers/display.rs b/crates/rendering/src/layers/display.rs index bc8eb5ff03e..f86e40e5f82 100644 --- a/crates/rendering/src/layers/display.rs +++ b/crates/rendering/src/layers/display.rs @@ -1,8 +1,8 @@ use cap_project::XY; use crate::{ - composite_frame::{CompositeVideoFramePipeline, CompositeVideoFrameUniforms}, DecodedSegmentFrames, + composite_frame::{CompositeVideoFramePipeline, CompositeVideoFrameUniforms}, }; pub struct DisplayLayer { diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs index d82d5b076c3..06756a2e6b5 100644 --- a/crates/rendering/src/lib.rs +++ b/crates/rendering/src/lib.rs @@ -5,12 +5,11 @@ use cap_project::{ }; use composite_frame::CompositeVideoFrameUniforms; use core::f64; -use cursor_interpolation::{interpolate_cursor, InterpolatedCursorPosition}; -use decoder::{spawn_decoder, AsyncVideoDecoderHandle}; +use cursor_interpolation::{InterpolatedCursorPosition, interpolate_cursor}; +use decoder::{AsyncVideoDecoderHandle, spawn_decoder}; use frame_pipeline::finish_encoder; -use futures::future::OptionFuture; use futures::FutureExt; -use image::GenericImageView; +use futures::future::OptionFuture; use layers::{ Background, BackgroundLayer, BlurLayer, CameraLayer, CaptionsLayer, CursorLayer, DisplayLayer, }; @@ -19,6 +18,7 @@ use spring_mass_damper::SpringMassDamperSimulationConfig; use std::{collections::HashMap, sync::Arc}; use std::{path::PathBuf, time::Instant}; use tokio::sync::mpsc; +use tracing::error; mod composite_frame; mod coord; @@ -293,26 +293,22 @@ pub fn get_duration( } } -pub struct CursorTexture { - inner: wgpu::Texture, - hotspot: XY, -} - pub struct RenderVideoConstants { pub _instance: wgpu::Instance, pub _adapter: wgpu::Adapter, pub queue: wgpu::Queue, pub device: wgpu::Device, pub options: RenderOptions, - pub cursor_textures: HashMap, - background_textures: std::sync::Arc>>, + pub meta: StudioRecordingMeta, + pub recording_meta: RecordingMeta, + pub background_textures: std::sync::Arc>>, } impl RenderVideoConstants { pub async fn new( segments: &[SegmentRecordings], - recording_meta: &RecordingMeta, - meta: &StudioRecordingMeta, + recording_meta: RecordingMeta, + meta: StudioRecordingMeta, ) -> Result { let options = RenderOptions { screen_size: XY::new(segments[0].display.width, segments[0].display.height), @@ -334,7 +330,6 @@ impl RenderVideoConstants { }) .await?; - let cursor_textures = Self::load_cursor_textures(&device, &queue, recording_meta, meta); let background_textures = Arc::new(tokio::sync::RwLock::new(HashMap::new())); Ok(Self { @@ -343,95 +338,11 @@ impl RenderVideoConstants { device, queue, options, - cursor_textures, background_textures, + meta, + recording_meta, }) } - - fn load_cursor_textures( - device: &wgpu::Device, - queue: &wgpu::Queue, - recording_meta: &RecordingMeta, - meta: &StudioRecordingMeta, - ) -> HashMap { - let mut textures = HashMap::new(); - - let cursor_images = match &meta { - StudioRecordingMeta::SingleSegment { .. } => Default::default(), - StudioRecordingMeta::MultipleSegments { inner, .. } => { - inner.cursor_images(recording_meta).unwrap_or_default() - } - }; - - for (cursor_id, cursor) in &cursor_images.0 { - if !cursor.path.exists() { - continue; - } - - match image::open(&cursor.path) { - Ok(img) => { - let dimensions = img.dimensions(); - - let rgba = img.into_rgba8(); - - // Create the texture - let texture = device.create_texture(&wgpu::TextureDescriptor { - label: Some(&format!("Cursor Texture {}", cursor_id)), - size: wgpu::Extent3d { - width: dimensions.0, - height: dimensions.1, - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Rgba8UnormSrgb, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - - queue.write_texture( - wgpu::TexelCopyTextureInfo { - texture: &texture, - mip_level: 0, - origin: wgpu::Origin3d::ZERO, - aspect: wgpu::TextureAspect::All, - }, - &rgba, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(4 * dimensions.0), - rows_per_image: None, - }, - wgpu::Extent3d { - width: dimensions.0, - height: dimensions.1, - depth_or_array_layers: 1, - }, - ); - - textures.insert( - cursor_id.clone(), - CursorTexture { - inner: texture, - hotspot: cursor.hotspot.map(|v| v as f32), - }, - ); - } - Err(e) => { - println!( - "Failed to load cursor image {}: {}", - cursor.path.display(), - e - ); - // Don't return error, just skip this cursor image - continue; - } - } - } - - textures - } } #[derive(Clone, Debug)] @@ -1266,9 +1177,5 @@ fn srgb_to_linear(c: u16) -> f32 { } fn get_either((a, b): (T, T), left: bool) -> T { - if left { - a - } else { - b - } + if left { a } else { b } } diff --git a/crates/rendering/src/zoom.rs b/crates/rendering/src/zoom.rs index 7522924127c..068badd92f1 100644 --- a/crates/rendering/src/zoom.rs +++ b/crates/rendering/src/zoom.rs @@ -1,4 +1,4 @@ -use cap_project::{ZoomSegment, XY}; +use cap_project::{XY, ZoomSegment}; use crate::{Coord, RawDisplayUVSpace}; diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts index 6d1f4abd401..4bc68431505 100644 --- a/packages/ui-solid/src/auto-imports.d.ts +++ b/packages/ui-solid/src/auto-imports.d.ts @@ -6,78 +6,106 @@ // biome-ignore lint: disable export {} declare global { - const IconCapArrows: typeof import('~icons/cap/arrows.jsx')['default'] - const IconCapAudioOn: typeof import('~icons/cap/audio-on.jsx')['default'] - const IconCapBgBlur: typeof import('~icons/cap/bg-blur.jsx')['default'] + const IconCapArrows: typeof import("~icons/cap/arrows.jsx")["default"] + const IconCapAudioOn: typeof import("~icons/cap/audio-on.jsx")["default"] + const IconCapAuto: typeof import("~icons/cap/auto.jsx")["default"] + const IconCapBgBlur: typeof import("~icons/cap/bg-blur.jsx")["default"] + const IconCapBlur: typeof import("~icons/cap/blur.jsx")["default"] const IconCapCamera: typeof import('~icons/cap/camera.jsx')['default'] - const IconCapCaptions: typeof import('~icons/cap/captions.jsx')['default'] + const IconCapCaptions: typeof import("~icons/cap/captions.jsx")["default"] + const IconCapCheck: typeof import("~icons/cap/check.jsx")["default"] const IconCapChevronDown: typeof import('~icons/cap/chevron-down.jsx')['default'] - const IconCapCircle: typeof import('~icons/cap/circle.jsx')['default'] - const IconCapCircleCheck: typeof import('~icons/cap/circle-check.jsx')['default'] - const IconCapCirclePlus: typeof import('~icons/cap/circle-plus.jsx')['default'] - const IconCapCircleX: typeof import('~icons/cap/circle-x.jsx')['default'] - const IconCapCopy: typeof import('~icons/cap/copy.jsx')['default'] - const IconCapCorners: typeof import('~icons/cap/corners.jsx')['default'] + const IconCapCircle: typeof import("~icons/cap/circle.jsx")["default"] + const IconCapCircleCheck: typeof import("~icons/cap/circle-check.jsx")["default"] + const IconCapCirclePlus: typeof import("~icons/cap/circle-plus.jsx")["default"] + const IconCapCircleX: typeof import("~icons/cap/circle-x.jsx")["default"] + const IconCapClock: typeof import("~icons/cap/clock.jsx")["default"] + const IconCapCopy: typeof import("~icons/cap/copy.jsx")["default"] + const IconCapCorners: typeof import("~icons/cap/corners.jsx")["default"] const IconCapCrop: typeof import('~icons/cap/crop.jsx')['default'] - const IconCapCursor: typeof import('~icons/cap/cursor.jsx')['default'] - const IconCapEditor: typeof import('~icons/cap/editor.jsx')['default'] - const IconCapEnlarge: typeof import('~icons/cap/enlarge.jsx')['default'] - const IconCapFile: typeof import('~icons/cap/file.jsx')['default'] + const IconCapCursor: typeof import("~icons/cap/cursor.jsx")["default"] + const IconCapDownload: typeof import("~icons/cap/download.jsx")["default"] + const IconCapEditor: typeof import("~icons/cap/editor.jsx")["default"] + const IconCapEnlarge: typeof import("~icons/cap/enlarge.jsx")["default"] + const IconCapFile: typeof import("~icons/cap/file.jsx")["default"] const IconCapFilmCut: typeof import('~icons/cap/film-cut.jsx')['default'] - const IconCapGauge: typeof import('~icons/cap/gauge.jsx')['default'] - const IconCapHotkeys: typeof import('~icons/cap/hotkeys.jsx')['default'] - const IconCapImage: typeof import('~icons/cap/image.jsx')['default'] + const IconCapFrameFirst: typeof import("~icons/cap/frame-first.jsx")["default"] + const IconCapFrameLast: typeof import("~icons/cap/frame-last.jsx")["default"] + const IconCapGauge: typeof import("~icons/cap/gauge.jsx")["default"] + const IconCapHotkeys: typeof import("~icons/cap/hotkeys.jsx")["default"] + const IconCapImage: typeof import("~icons/cap/image.jsx")["default"] const IconCapInfo: typeof import('~icons/cap/info.jsx')['default'] + const IconCapInset: typeof import("~icons/cap/inset.jsx")["default"] const IconCapInstant: typeof import('~icons/cap/instant.jsx')['default'] - const IconCapLayout: typeof import('~icons/cap/layout.jsx')['default'] - const IconCapLink: typeof import('~icons/cap/link.jsx')['default'] + const IconCapLayout: typeof import("~icons/cap/layout.jsx")["default"] + const IconCapLink: typeof import("~icons/cap/link.jsx")["default"] const IconCapLogo: typeof import('~icons/cap/logo.jsx')['default'] const IconCapLogoFull: typeof import('~icons/cap/logo-full.jsx')['default'] const IconCapLogoFullDark: typeof import('~icons/cap/logo-full-dark.jsx')['default'] - const IconCapMessageBubble: typeof import('~icons/cap/message-bubble.jsx')['default'] + const IconCapMessageBubble: typeof import("~icons/cap/message-bubble.jsx")["default"] const IconCapMicrophone: typeof import('~icons/cap/microphone.jsx')['default'] - const IconCapMoreVertical: typeof import('~icons/cap/more-vertical.jsx')['default'] - const IconCapNext: typeof import('~icons/cap/next.jsx')['default'] - const IconCapPadding: typeof import('~icons/cap/padding.jsx')['default'] - const IconCapPause: typeof import('~icons/cap/pause.jsx')['default'] - const IconCapPauseCircle: typeof import('~icons/cap/pause-circle.jsx')['default'] - const IconCapPlay: typeof import('~icons/cap/play.jsx')['default'] - const IconCapPlayCircle: typeof import('~icons/cap/play-circle.jsx')['default'] - const IconCapPresets: typeof import('~icons/cap/presets.jsx')['default'] - const IconCapPrev: typeof import('~icons/cap/prev.jsx')['default'] - const IconCapRedo: typeof import('~icons/cap/redo.jsx')['default'] - const IconCapRestart: typeof import('~icons/cap/restart.jsx')['default'] - const IconCapScissors: typeof import('~icons/cap/scissors.jsx')['default'] + const IconCapMoreVertical: typeof import("~icons/cap/more-vertical.jsx")["default"] + const IconCapMoveLeft: typeof import("~icons/cap/move-left.jsx")["default"] + const IconCapMoveRight: typeof import("~icons/cap/move-right.jsx")["default"] + const IconCapNext: typeof import("~icons/cap/next.jsx")["default"] + const IconCapPadding: typeof import("~icons/cap/padding.jsx")["default"] + const IconCapPause: typeof import("~icons/cap/pause.jsx")["default"] + const IconCapPauseCircle: typeof import("~icons/cap/pause-circle.jsx")["default"] + const IconCapPlay: typeof import("~icons/cap/play.jsx")["default"] + const IconCapPlayCircle: typeof import("~icons/cap/play-circle.jsx")["default"] + const IconCapPresets: typeof import("~icons/cap/presets.jsx")["default"] + const IconCapPrev: typeof import("~icons/cap/prev.jsx")["default"] + const IconCapRedo: typeof import("~icons/cap/redo.jsx")["default"] + const IconCapRefresh: typeof import("~icons/cap/refresh.jsx")["default"] + const IconCapRestart: typeof import("~icons/cap/restart.jsx")["default"] + const IconCapScissors: typeof import("~icons/cap/scissors.jsx")["default"] const IconCapSettings: typeof import('~icons/cap/settings.jsx')['default'] - const IconCapShadow: typeof import('~icons/cap/shadow.jsx')['default'] - const IconCapSquare: typeof import('~icons/cap/square.jsx')['default'] - const IconCapStopCircle: typeof import('~icons/cap/stop-circle.jsx')['default'] - const IconCapTrash: typeof import('~icons/cap/trash.jsx')['default'] - const IconCapUndo: typeof import('~icons/cap/undo.jsx')['default'] - const IconCapUpload: typeof import('~icons/cap/upload.jsx')['default'] - const IconCapZoomIn: typeof import('~icons/cap/zoom-in.jsx')['default'] - const IconCapZoomOut: typeof import('~icons/cap/zoom-out.jsx')['default'] - const IconHugeiconsEaseCurveControlPoints: typeof import('~icons/hugeicons/ease-curve-control-points.jsx')['default'] + const IconCapShadow: typeof import("~icons/cap/shadow.jsx")["default"] + const IconCapSize: typeof import("~icons/cap/size.jsx")["default"] + const IconCapSquare: typeof import("~icons/cap/square.jsx")["default"] + const IconCapStop: typeof import("~icons/cap/stop.jsx")["default"] + const IconCapStopCircle: typeof import("~icons/cap/stop-circle.jsx")["default"] + const IconCapTrash: typeof import("~icons/cap/trash.jsx")["default"] + const IconCapUndo: typeof import("~icons/cap/undo.jsx")["default"] + const IconCapUpload: typeof import("~icons/cap/upload.jsx")["default"] + const IconCapWindow: typeof import("~icons/cap/window.jsx")["default"] + const IconCapX: typeof import("~icons/cap/x.jsx")["default"] + const IconCapZoomIn: typeof import("~icons/cap/zoom-in.jsx")["default"] + const IconCapZoomOut: typeof import("~icons/cap/zoom-out.jsx")["default"] + const IconHugeiconsEaseCurveControlPoints: typeof import("~icons/hugeicons/ease-curve-control-points.jsx")["default"] + const IconIcBaselineMonitor: typeof import("~icons/ic/baseline-monitor.jsx")["default"] + const IconIcRoundSearch: typeof import("~icons/ic/round-search.jsx")["default"] const IconLucideBell: typeof import('~icons/lucide/bell.jsx')['default'] const IconLucideBug: typeof import('~icons/lucide/bug.jsx')['default'] - const IconLucideCheck: typeof import('~icons/lucide/check.jsx')['default'] - const IconLucideClock: typeof import('~icons/lucide/clock.jsx')['default'] - const IconLucideDatabase: typeof import('~icons/lucide/database.jsx')['default'] - const IconLucideEdit: typeof import('~icons/lucide/edit.jsx')['default'] - const IconLucideEye: typeof import('~icons/lucide/eye.jsx')['default'] - const IconLucideFolder: typeof import('~icons/lucide/folder.jsx')['default'] + const IconLucideCamera: typeof import("~icons/lucide/camera.jsx")["default"] + const IconLucideCheck: typeof import("~icons/lucide/check.jsx")["default"] + const IconLucideChevronDown: typeof import("~icons/lucide/chevron-down.jsx")["default"] + const IconLucideClock: typeof import("~icons/lucide/clock.jsx")["default"] + const IconLucideDatabase: typeof import("~icons/lucide/database.jsx")["default"] + const IconLucideEdit: typeof import("~icons/lucide/edit.jsx")["default"] + const IconLucideEye: typeof import("~icons/lucide/eye.jsx")["default"] + const IconLucideFolder: typeof import("~icons/lucide/folder.jsx")["default"] const IconLucideGift: typeof import('~icons/lucide/gift.jsx')['default'] - const IconLucideHardDrive: typeof import('~icons/lucide/hard-drive.jsx')['default'] - const IconLucideLoaderCircle: typeof import('~icons/lucide/loader-circle.jsx')['default'] - const IconLucideMessageSquarePlus: typeof import('~icons/lucide/message-square-plus.jsx')['default'] - const IconLucideMicOff: typeof import('~icons/lucide/mic-off.jsx')['default'] - const IconLucideMonitor: typeof import('~icons/lucide/monitor.jsx')['default'] - const IconLucideRectangleHorizontal: typeof import('~icons/lucide/rectangle-horizontal.jsx')['default'] - const IconLucideRotateCcw: typeof import('~icons/lucide/rotate-ccw.jsx')['default'] - const IconLucideSearch: typeof import('~icons/lucide/search.jsx')['default'] + const IconLucideHardDrive: typeof import("~icons/lucide/hard-drive.jsx")["default"] + const IconLucideLayoutGrid: typeof import("~icons/lucide/layout-grid.jsx")["default"] + const IconLucideLoaderCircle: typeof import("~icons/lucide/loader-circle.jsx")["default"] + const IconLucideMessageCircle: typeof import("~icons/lucide/message-circle.jsx")["default"] + const IconLucideMessageSquare: typeof import("~icons/lucide/message-square.jsx")["default"] + const IconLucideMessageSquarePlus: typeof import("~icons/lucide/message-square-plus.jsx")["default"] + const IconLucideMicOff: typeof import("~icons/lucide/mic-off.jsx")["default"] + const IconLucideMonitor: typeof import("~icons/lucide/monitor.jsx")["default"] + const IconLucideRabbit: typeof import("~icons/lucide/rabbit.jsx")["default"] + const IconLucideRectangle: typeof import("~icons/lucide/rectangle.jsx")["default"] + const IconLucideRectangleHorizontal: typeof import("~icons/lucide/rectangle-horizontal.jsx")["default"] + const IconLucideRectangleSquare: typeof import("~icons/lucide/rectangle-square.jsx")["default"] + const IconLucideRotateCcw: typeof import("~icons/lucide/rotate-ccw.jsx")["default"] + const IconLucideSearch: typeof import("~icons/lucide/search.jsx")["default"] const IconLucideSquarePlay: typeof import('~icons/lucide/square-play.jsx')['default'] - const IconLucideUnplug: typeof import('~icons/lucide/unplug.jsx')['default'] - const IconLucideVolume2: typeof import('~icons/lucide/volume2.jsx')['default'] - const IconLucideVolumeX: typeof import('~icons/lucide/volume-x.jsx')['default'] + const IconLucideUnplug: typeof import("~icons/lucide/unplug.jsx")["default"] + const IconLucideVideo: typeof import("~icons/lucide/video.jsx")["default"] + const IconLucideVolume2: typeof import("~icons/lucide/volume2.jsx")["default"] + const IconLucideVolumeX: typeof import("~icons/lucide/volume-x.jsx")["default"] + const IconLucideX: typeof import("~icons/lucide/x.jsx")["default"] + const IconMdiMonitor: typeof import("~icons/mdi/monitor.jsx")["default"] const IconPhMonitorBold: typeof import('~icons/ph/monitor-bold.jsx')['default'] }