Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: add cursor style and ripple controls to the GPUI editor

Richie McIlroye6550139e087
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock
index 9dda7ec44..c6ed95126 100644
--- a/apps/desktop-gpui/Cargo.lock
+++ b/apps/desktop-gpui/Cargo.lock
@@ -1525,6 +1525,7 @@ dependencies = [
"base64 0.22.1",
"cap-camera",
"cap-camera-effects",
+ "cap-cursor-info",
"cap-editor",
"cap-enc-ffmpeg",
"cap-export",
@@ -1558,6 +1559,7 @@ dependencies = [
"parakeet-rs",
"raw-window-handle",
"reqwest 0.12.28",
+ "resvg 0.45.1",
"rfd",
"scap-targets",
"semver",
diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml
index b63436605..890ee0684 100644
--- a/apps/desktop-gpui/Cargo.toml
+++ b/apps/desktop-gpui/Cargo.toml
@@ -56,6 +56,12 @@ cap-enc-ffmpeg = { path = "../../crates/enc-ffmpeg" }
cap-timestamp = { path = "../../crates/timestamp" }
cap-utils = { path = "../../crates/utils" }
cap-project = { path = "../../crates/project" }
+# The cursor style picker draws the same SVG assets the renderer composites.
+# gpui's `svg()` keeps only a glyph's alpha, so the two-tone cursor art has to
+# be rasterised instead: `resvg` at the pin cap-rendering already builds, into
+# a `RenderImage` (`src/editor_sidebar/cursor.rs`).
+cap-cursor-info = { path = "../../crates/cursor-info" }
+resvg = "0.45"
# The editor stack. `cap-rendering` is not a new subtree -- cap-recording
# already depends on it, so wgpu 25 and its vendored wgpu-hal have been built
# by this workspace since the recording unit; naming it here only makes the
diff --git a/apps/desktop-gpui/assets/icons/mouse-pointer-click.svg b/apps/desktop-gpui/assets/icons/mouse-pointer-click.svg
new file mode 100644
index 000000000..0d67529c8
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/mouse-pointer-click.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 4.1 12 6"/><path d="m5.1 8-2.9-.8"/><path d="m6 12-1.9 2"/><path d="M7.2 2.2 8 5.1"/><path d="M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z"/></svg>
\ No newline at end of file
diff --git a/apps/desktop-gpui/src/assets.rs b/apps/desktop-gpui/src/assets.rs
index 03be91d21..e42ea95f3 100644
--- a/apps/desktop-gpui/src/assets.rs
+++ b/apps/desktop-gpui/src/assets.rs
@@ -168,6 +168,7 @@ const ICONS: &[(&str, &[u8])] = assets!("icons":
"maximize.svg",
"moon.svg",
"mouse-pointer-2.svg",
+ "mouse-pointer-click.svg",
"move.svg",
"move-right.svg",
"palette.svg",
@@ -324,6 +325,9 @@ mod tests {
// The five later tabs, the colour-grade section and the eight segment
// panels each name their own glyphs.
include_str!("editor_tabs.rs"),
+ // The cursor tab's style picker and ripple section live one directory
+ // down, and the ripple field names its own glyph.
+ include_str!("editor_sidebar/cursor.rs"),
include_str!("editor_color.rs"),
include_str!("editor_panels.rs"),
// The crop dialog's ratio / Full / Reset glyphs and the chevron
diff --git a/apps/desktop-gpui/src/editor_sidebar.rs b/apps/desktop-gpui/src/editor_sidebar.rs
index 057f37a49..a17b89f2c 100644
--- a/apps/desktop-gpui/src/editor_sidebar.rs
+++ b/apps/desktop-gpui/src/editor_sidebar.rs
@@ -35,7 +35,7 @@
//! re-encode (`src-tauri/src/recording.rs:181-208, 437-472`).
use std::{
- collections::HashMap,
+ collections::{BTreeMap, HashMap},
path::{Path, PathBuf},
sync::Arc,
time::Instant,
@@ -63,6 +63,7 @@ use crate::{
};
mod animated_gradient;
+mod cursor;
// ---------------------------------------------------------------------------
// The catalogue: every constant the background section reads
@@ -725,6 +726,9 @@ pub enum ColorTarget {
GradientTo,
AnimatedGradientStop(usize),
BorderColor,
+ /// The click ripple's ring colour, the one `[u8; 3]` target outside the
+ /// background tab.
+ CursorRipple,
CaptionColor,
CaptionBackground,
CaptionHighlight,
@@ -744,6 +748,7 @@ impl ColorTarget {
| Self::GradientTo
| Self::AnimatedGradientStop(_)
| Self::BorderColor
+ | Self::CursorRipple
)
}
}
@@ -797,6 +802,16 @@ pub struct SidebarState {
/// `KCollapsible open={!project.cursor.raw}` physics panel.
pub camera_shadow_open: CollapsibleState,
pub cursor_physics_open: CollapsibleState,
+ /// The click-ripple settings, revealed by their own toggle.
+ pub cursor_ripple_open: CollapsibleState,
+ /// The style picker's rasterised cursor art, keyed by shape and the device
+ /// pixel box it was drawn for. A `BTreeMap` because `CursorShape` is `Ord`
+ /// but not `Hash`.
+ cursor_previews:
+ std::cell::RefCell<BTreeMap<(cap_cursor_info::CursorShape, u32, u32), Arc<RenderImage>>>,
+ /// The device scale those were rasterised at, sampled once a frame from
+ /// `render` -- the only place in the sidebar's chain with a `&Window`.
+ cursor_scale: f32,
/// The 3D panel's three `Camera3DSection`s and the zoom panel's helper.
pub panel_sections: std::cell::RefCell<HashMap<PanelSection, std::rc::Rc<CollapsibleState>>>,
@@ -873,6 +888,9 @@ impl SidebarState {
grade_previews: std::cell::RefCell::new(HashMap::new()),
camera_shadow_open: CollapsibleState::new(false),
cursor_physics_open: CollapsibleState::new(!config.cursor.raw),
+ cursor_ripple_open: CollapsibleState::new(config.cursor.ripple.enabled),
+ cursor_previews: std::cell::RefCell::new(BTreeMap::new()),
+ cursor_scale: 2.,
panel_sections: std::cell::RefCell::new(HashMap::new()),
noise: std::cell::RefCell::new(None),
menu: None,
@@ -1628,6 +1646,7 @@ impl EditorWindow {
.as_ref()
.map_or(UI_BORDER_FALLBACK.color, |border| border.color),
),
+ ColorTarget::CursorRipple => Some(self.project.cursor.ripple.color),
_ => self.hex_string_for(target).and_then(|hex| {
hex_to_rgb(&hex).map(|rgba| [rgba[0] as u16, rgba[1] as u16, rgba[2] as u16])
}),
@@ -1664,6 +1683,17 @@ impl EditorWindow {
if target.is_hex_string() {
return self.set_hex_color(target, color, window, cx);
}
+ // The one `[u8; 3]` target that does not live under `background`, so
+ // it takes the general fan-out rather than `edit_background`.
+ if target == ColorTarget::CursorRipple {
+ return self.edit_project("cursor-ripple-color", window, cx, move |project| {
+ if project.cursor.ripple.color == color {
+ return false;
+ }
+ project.cursor.ripple.color = color;
+ true
+ });
+ }
self.edit_background(
"color",
|project| {
@@ -3864,6 +3894,8 @@ pub(crate) fn format_slider_value(value: f32, unit: &str) -> String {
"int" => format!("{}", value.round() as i32),
"x100%" => format!("{}%", (value * 100.).round() as i32),
"pct" => format!("{:.1}%", value * 100.),
+ // The ripple duration's `${v.toFixed(2)}s`.
+ "secs" => format!("{value:.2}s"),
unit => format!("{value:.1}{unit}"),
}
}
diff --git a/apps/desktop-gpui/src/editor_sidebar/cursor.rs b/apps/desktop-gpui/src/editor_sidebar/cursor.rs
new file mode 100644
index 000000000..6bbcb0c8f
--- /dev/null
+++ b/apps/desktop-gpui/src/editor_sidebar/cursor.rs
@@ -0,0 +1,474 @@
+//! The Cursor tab's style picker and its click-ripple section.
+//!
+//! The picker is one row of four tiles, each showing a family's arrow drawn
+//! from the **real** cursor art in `crates/cursor-info/assets` -- the same
+//! SVGs the renderer composites -- so the choice is made by looking at the
+//! cursor rather than by reading the word "Windows". The arrow alone is what
+//! makes a family recognisable, so the tile shows nothing else. `svg()` keeps
+//! only a glyph's alpha and tints it with the element's text colour, which
+//! would flatten a two-tone cursor into a silhouette, so each arrow is
+//! rasterised with `resvg` into a [`gpui::RenderImage`] and cached per
+//! (shape, device-pixel box).
+//!
+//! The tiles are plain theme surfaces: the assets carry their own
+//! black-on-white edge and a soft drop shadow, so they read on a light or a
+//! dark tile the way a real cursor reads over a light or dark window.
+//!
+//! The fourth tile is `Circle`, whose art has no asset: it is the renderer's
+//! own touch circle (`crates/rendering/src/layers/cursor.rs`
+//! `create_circle_cursor`) restated with gpui primitives.
+
+use cap_cursor_info::{CursorFamily, CursorShape};
+use cap_project::CursorType;
+
+use super::*;
+use crate::editor_tabs::CursorSlider;
+
+const CARD_GAP: f32 = 8.;
+const TILE_HEIGHT: f32 = 60.;
+const TILE_RADIUS: f32 = 10.;
+/// The arrow's box. Square, and every arrow asset is taller than it is wide,
+/// so the fit lands on the height and each family keeps its own width.
+const ARROW_BOX: f32 = 34.;
+const CIRCLE_DISC: f32 = 28.;
+const CARD_GROUP: &str = "cursor-style-card";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum CursorCard {
+ Family(CursorFamily),
+ Circle,
+}
+
+impl CursorCard {
+ fn label(self) -> &'static str {
+ match self {
+ Self::Family(CursorFamily::MacOS) => "macOS",
+ Self::Family(CursorFamily::MacOSTahoe) => "macOS Tahoe",
+ Self::Family(CursorFamily::Windows) => "Windows",
+ Self::Circle => "Circle",
+ }
+ }
+
+ fn key(self) -> &'static str {
+ match self {
+ Self::Family(CursorFamily::MacOS) => "macos",
+ Self::Family(CursorFamily::MacOSTahoe) => "tahoe",
+ Self::Family(CursorFamily::Windows) => "windows",
+ Self::Circle => "circle",
+ }
+ }
+
+ /// What clicking the card writes. Always explicit -- the picker never
+ /// writes `Auto` back, because a card is only ever shown selected on the
+ /// strength of a family it can name.
+ fn cursor_type(self) -> CursorType {
+ match self {
+ Self::Family(CursorFamily::MacOS) => CursorType::MacOS,
+ Self::Family(CursorFamily::MacOSTahoe) => CursorType::MacOSTahoe,
+ Self::Family(CursorFamily::Windows) => CursorType::Windows,
+ Self::Circle => CursorType::Circle,
+ }
+ }
+}
+
+/// Host order: the platform's own cursors first, then the other two, then the
+/// styled circle.
+fn cursor_cards() -> [CursorCard; 4] {
+ if cfg!(target_os = "windows") {
+ [
+ CursorCard::Family(CursorFamily::Windows),
+ CursorCard::Family(CursorFamily::MacOS),
+ CursorCard::Family(CursorFamily::MacOSTahoe),
+ CursorCard::Circle,
+ ]
+ } else {
+ [
+ CursorCard::Family(CursorFamily::MacOS),
+ CursorCard::Family(CursorFamily::MacOSTahoe),
+ CursorCard::Family(CursorFamily::Windows),
+ CursorCard::Circle,
+ ]
+ }
+}
+
+/// Which card reads as selected: the explicit type when there is one, and
+/// otherwise the family the recording was made with -- or, failing that, this
+/// host's -- because that is what `Auto` will actually draw.
+fn selected_card(cursor_type: &CursorType, recorded: Option<CursorFamily>) -> CursorCard {
+ if *cursor_type == CursorType::Circle {
+ return CursorCard::Circle;
+ }
+ match cursor_type.family() {
+ Some(family) => CursorCard::Family(family),
+ None => CursorCard::Family(recorded.unwrap_or(host_cursor_family())),
+ }
+}
+
+fn host_cursor_family() -> CursorFamily {
+ if cfg!(target_os = "windows") {
+ CursorFamily::Windows
+ } else {
+ CursorFamily::MacOS
+ }
+}
+
+fn white(alpha: f32) -> Hsla {
+ gpui::hsla(0., 0., 1., alpha)
+}
+
+fn black(alpha: f32) -> Hsla {
+ gpui::hsla(0., 0., 0., alpha)
+}
+
+/// One cursor shape, rasterised to fit `width` x `height` device pixels.
+fn rasterize_cursor(shape: CursorShape, width: u32, height: u32) -> Option<Arc<RenderImage>> {
+ let raw = shape.resolve()?.raw;
+ let tree = resvg::usvg::Tree::from_str(raw, &resvg::usvg::Options::default()).ok()?;
+ let size = tree.size();
+ let scale = (width as f32 / size.width()).min(height as f32 / size.height());
+ let mut pixmap = resvg::tiny_skia::Pixmap::new(width, height)?;
+ let transform = resvg::tiny_skia::Transform::from_translate(
+ (width as f32 - size.width() * scale) / 2.,
+ (height as f32 - size.height() * scale) / 2.,
+ )
+ .pre_scale(scale, scale);
+ resvg::render(&tree, transform, &mut pixmap.as_mut());
+
+ let mut buffer = image::RgbaImage::from_raw(width, height, pixmap.take())?;
+ // tiny-skia hands back premultiplied RGBA and gpui's atlas takes straight
+ // BGRA -- the same conversion `gpui::SvgRenderer::render_single_frame` does
+ // on its own pixmap. Skipping it darkens every antialiased edge.
+ for pixel in buffer.chunks_exact_mut(4) {
+ gpui::swap_rgba_pa_to_bgra(pixel);
+ }
+ Some(Arc::new(RenderImage::new(smallvec::smallvec![
+ image::Frame::new(buffer)
+ ])))
+}
+
+/// The touch circle: a translucent disc with a dark outer ring, a light inner
+/// ring and a faint shadow, as `create_circle_cursor` draws it.
+fn circle_art() -> AnyElement {
+ div()
+ .size(px(CIRCLE_DISC))
+ .rounded_full()
+ .bg(white(0.15))
+ .border_1()
+ .border_color(black(0.38))
+ .shadow(vec![gpui::BoxShadow {
+ color: black(0.16),
+ offset: gpui::point(px(0.), px(0.)),
+ blur_radius: px(5.),
+ spread_radius: px(0.),
+ inset: false,
+ }])
+ .child(
+ div()
+ .size_full()
+ .rounded_full()
+ .border_1()
+ .border_color(white(0.42)),
+ )
+ .into_any_element()
+}
+
+impl EditorWindow {
+ /// The ripple colour's hex field, and the device scale the previews are
+ /// rasterised for. Both need a `&mut Window`, which the sidebar's render
+ /// chain does not carry, so they are settled once a frame from `render`.
+ pub(crate) fn prepare_cursor_fields(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if self.sidebar.tab != SidebarTab::Cursor {
+ return;
+ }
+ self.sidebar.cursor_scale = window.scale_factor();
+ self.ensure_hex_input(ColorTarget::CursorRipple, window, cx);
+ }
+
+ fn selected_cursor_card(&self) -> CursorCard {
+ selected_card(
+ self.project.cursor.cursor_type(),
+ self.recorded_cursor_family,
+ )
+ }
+
+ fn cursor_preview(&self, shape: CursorShape, size: f32) -> Option<Arc<RenderImage>> {
+ let scale = self.sidebar.cursor_scale.max(1.);
+ let side = (size * scale).round() as u32;
+ let key = (shape, side, side);
+ if let Some(image) = self.sidebar.cursor_previews.borrow().get(&key) {
+ return Some(image.clone());
+ }
+ let image = rasterize_cursor(shape, side, side)?;
+ self.sidebar
+ .cursor_previews
+ .borrow_mut()
+ .insert(key, image.clone());
+ Some(image)
+ }
+
+ fn cursor_art(&self, shape: CursorShape, size: f32) -> AnyElement {
+ div()
+ .size(px(size))
+ .flex()
+ .items_center()
+ .justify_center()
+ .children(
+ self.cursor_preview(shape, size)
+ .map(|image| img(image).size(px(size))),
+ )
+ .into_any_element()
+ }
+
+ /// The tile: the family's arrow (or the touch circle) centred on a plain
+ /// surface. `RadioCards`' grammar for the states -- `border-gray-3
+ /// bg-gray-2`, `hover:border-gray-5`, and `border-blue-8 bg-blue-3/40`
+ /// plus a 1px ring (so a 2px edge) when checked.
+ fn render_cursor_tile(&self, card: CursorCard, selected: bool, recorded: bool) -> AnyElement {
+ let theme = self.theme;
+ let art = match card {
+ CursorCard::Family(family) => self.cursor_art(family.arrow(), ARROW_BOX),
+ CursorCard::Circle => circle_art(),
+ };
+
+ div()
+ .id(SharedString::from(format!("cursor-tile-{}", card.key())))
+ .w_full()
+ .h(px(TILE_HEIGHT))
+ .rounded(px(TILE_RADIUS))
+ .flex()
+ .items_center()
+ .justify_center()
+ .map(|this| {
+ if selected {
+ this.border_2()
+ .border_color(Hsla::from(theme.blue_8))
+ .bg(with_alpha(theme.blue_3, 0.4))
+ } else {
+ this.border_1()
+ .border_color(Hsla::from(theme.gray_3))
+ .bg(Hsla::from(theme.gray_2))
+ .group_hover(CARD_GROUP, |this| {
+ this.border_color(Hsla::from(theme.gray_5))
+ })
+ }
+ })
+ .when(recorded, |this| {
+ this.tooltip(move |_window, cx| {
+ ui::Tooltip::new(&theme, "Recorded with this cursor").view(cx)
+ })
+ })
+ .child(art)
+ .into_any_element()
+ }
+
+ fn render_cursor_card(
+ &self,
+ card: CursorCard,
+ selected: bool,
+ recorded: Option<CursorFamily>,
+ cx: &mut Context<Self>,
+ ) -> AnyElement {
+ let theme = self.theme;
+ let cursor_type = card.cursor_type();
+ let is_recorded = matches!(card, CursorCard::Family(family) if recorded == Some(family));
+
+ div()
+ .id(SharedString::from(format!("cursor-card-{}", card.key())))
+ .group(CARD_GROUP)
+ .flex_1()
+ .min_w_0()
+ .flex()
+ .flex_col()
+ .items_center()
+ .gap(px(6.))
+ .cursor_pointer()
+ .child(self.render_cursor_tile(card, selected, is_recorded))
+ .child(
+ div()
+ .max_w_full()
+ .whitespace_nowrap()
+ .overflow_hidden()
+ .text_ellipsis()
+ .text_size(px(11.))
+ .line_height(px(11.))
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(Hsla::from(if selected {
+ theme.gray_12
+ } else {
+ theme.gray_11
+ }))
+ .when(!selected, |this| {
+ this.group_hover(CARD_GROUP, |this| {
+ this.text_color(Hsla::from(theme.gray_12))
+ })
+ })
+ .child(card.label()),
+ )
+ .on_click(cx.listener(move |this, _, window, cx| {
+ // `CursorType` is not `Copy`, and the listener is an `Fn`.
+ let cursor_type = cursor_type.clone();
+ this.edit_project("cursor-type", window, cx, move |project| {
+ if *project.cursor.cursor_type() == cursor_type {
+ return false;
+ }
+ project.cursor.set_cursor_type(cursor_type);
+ true
+ });
+ }))
+ .into_any_element()
+ }
+
+ /// `grid grid-cols-4 gap-2`: one row, the four cards sharing the width.
+ pub(crate) fn render_cursor_style_picker(&self, cx: &mut Context<Self>) -> AnyElement {
+ let selected = self.selected_cursor_card();
+ let recorded = self.recorded_cursor_family;
+
+ div()
+ .flex()
+ .flex_row()
+ .gap(px(CARD_GAP))
+ .children(
+ cursor_cards()
+ .into_iter()
+ .map(|card| self.render_cursor_card(card, selected == card, recorded, cx)),
+ )
+ .into_any_element()
+ }
+
+ /// "Click Ripple" and, once it is on, the ring's colour and its three
+ /// shape sliders.
+ pub(crate) fn render_cursor_ripple(&self, cx: &mut Context<Self>) -> AnyElement {
+ let theme = self.theme;
+ let ripple = &self.project.cursor.ripple;
+ let enabled = ripple.enabled;
+ let color = ripple.color;
+
+ div()
+ .flex()
+ .flex_col()
+ .child(
+ ui::Field::plain(&theme, "Click Ripple")
+ .icon("icons/mouse-pointer-click.svg")
+ .value(
+ ui::Toggle::plain(&theme, "cursor-ripple", enabled)
+ .on_click(cx.listener(move |this, _, window, cx| {
+ let next = !this.project.cursor.ripple.enabled;
+ this.sidebar.cursor_ripple_open.set_open(next);
+ this.animate_collapsibles(window, cx);
+ this.edit_project("cursor-ripple", window, cx, move |project| {
+ project.cursor.ripple.enabled = next;
+ true
+ });
+ }))
+ .into_any_element(),
+ ),
+ )
+ .child(collapsible(
+ &self.sidebar.cursor_ripple_open,
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(16.))
+ .pt(px(16.))
+ .pb(px(24.))
+ .child(
+ ui::Subfield::plain(&theme, "Color").child(self.render_rgb_input(
+ "cursor-ripple-color",
+ ColorTarget::CursorRipple,
+ color,
+ cx,
+ )),
+ )
+ .child(ui::Field::plain(&theme, "Strength").child(self.slider(
+ SliderKey::Cursor(CursorSlider::RippleStrength),
+ "%",
+ cx,
+ )))
+ .child(ui::Field::plain(&theme, "Size").child(self.slider(
+ SliderKey::Cursor(CursorSlider::RippleSize),
+ "%",
+ cx,
+ )))
+ .child(ui::Field::plain(&theme, "Duration").child(self.slider(
+ SliderKey::Cursor(CursorSlider::RippleDuration),
+ "secs",
+ cx,
+ )))
+ .into_any_element(),
+ ))
+ .into_any_element()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cards_lead_with_the_host_family() {
+ let cards = cursor_cards();
+ assert_eq!(cards[0], CursorCard::Family(host_cursor_family()));
+ assert_eq!(cards[3], CursorCard::Circle);
+ for family in [
+ CursorFamily::MacOS,
+ CursorFamily::MacOSTahoe,
+ CursorFamily::Windows,
+ ] {
+ assert!(cards.contains(&CursorCard::Family(family)), "{family:?}");
+ }
+ }
+
+ /// Every card writes a type that resolves back to the card it was drawn
+ /// on, which is what keeps the selected ring on the card just clicked.
+ #[test]
+ fn every_card_round_trips_through_its_type() {
+ for card in cursor_cards() {
+ let written = card.cursor_type();
+ assert_ne!(written, CursorType::Auto);
+ assert_eq!(selected_card(&written, None), card, "{:?}", card.label());
+ }
+ }
+
+ #[test]
+ fn auto_follows_the_recording_then_the_host() {
+ assert_eq!(
+ selected_card(&CursorType::Auto, Some(CursorFamily::MacOSTahoe)),
+ CursorCard::Family(CursorFamily::MacOSTahoe)
+ );
+ // The legacy value renders exactly as `Auto` does.
+ assert_eq!(
+ selected_card(&CursorType::Pointer, Some(CursorFamily::Windows)),
+ CursorCard::Family(CursorFamily::Windows)
+ );
+ assert_eq!(
+ selected_card(&CursorType::Auto, None),
+ CursorCard::Family(host_cursor_family())
+ );
+ }
+
+ /// Every family's arrow resolves and rasterises at the tile's box (at 1x
+ /// and 2x) -- a card with a missing asset would silently draw an empty
+ /// tile.
+ #[test]
+ fn every_arrow_rasterises() {
+ for family in [
+ CursorFamily::MacOS,
+ CursorFamily::MacOSTahoe,
+ CursorFamily::Windows,
+ ] {
+ let shape = family.arrow();
+ for side in [ARROW_BOX as u32, (ARROW_BOX * 2.) as u32] {
+ let image = rasterize_cursor(shape, side, side)
+ .unwrap_or_else(|| panic!("{shape} at {side}px"));
+ let size = image.size(0);
+ assert_eq!(size.width.0 as u32, side);
+ assert_eq!(size.height.0 as u32, side);
+ let bytes = image.as_bytes(0).expect("one frame");
+ assert!(
+ bytes.chunks_exact(4).any(|pixel| pixel[3] > 0),
+ "{shape} rasterised to nothing"
+ );
+ }
+ }
+ }
+}
diff --git a/apps/desktop-gpui/src/editor_tabs.rs b/apps/desktop-gpui/src/editor_tabs.rs
index f5c9e9fc2..eb7c660a0 100644
--- a/apps/desktop-gpui/src/editor_tabs.rs
+++ b/apps/desktop-gpui/src/editor_tabs.rs
@@ -32,8 +32,8 @@ use std::{
use cap_project::CaptionsData;
use cap_project::{
BackgroundBlurConfig, BackgroundBlurMode, CameraShape, CameraXPosition, CameraYPosition,
- CaptionSegment, CaptionSettings, CornerStyle, CursorAnimationStyle, KeyboardData,
- KeyboardSettings, ProjectConfiguration, ShadowConfiguration, StereoMode,
+ CaptionSegment, CaptionSettings, CornerStyle, CursorAnimationStyle, CursorRippleConfig,
+ KeyboardData, KeyboardSettings, ProjectConfiguration, ShadowConfiguration, StereoMode,
};
use gpui::{
AnyElement, Context, EntityId, FontWeight, Hsla, InteractiveElement, IntoElement,
@@ -79,13 +79,6 @@ pub const STEREO_MODES: [(StereoMode, &str); 3] = [
(StereoMode::MonoR, "Mono R"),
];
-/// `CURSOR_TYPE_OPTIONS` (`:421-433`).
-pub const CURSOR_TYPES: [(&str, &str, &str); 3] = [
- ("auto", "Auto", "Use the cursor Cap recorded"),
- ("pointer", "Pointer", "Always draw the standard arrow"),
- ("circle", "Circle", "Draw a simple circle instead"),
-];
-
/// `CURSOR_ANIMATION_STYLE_OPTIONS` (`:434-476`) -- the four presets plus the
/// `custom` value the physics sliders drop the picker into.
pub const CURSOR_STYLES: [(CursorAnimationStyle, &str, &str); 4] = [
@@ -421,6 +414,9 @@ pub enum CursorSlider {
Tension,
Friction,
Mass,
+ RippleStrength,
+ RippleSize,
+ RippleDuration,
}
impl CursorSlider {
@@ -432,6 +428,15 @@ impl CursorSlider {
Self::Tension => (1., 600., 1.),
Self::Friction => (0., 200., 0.1),
Self::Mass => (0.1, 15., 0.01),
+ // Strength and size are stored as fractions and shown as
+ // percentages; `CursorRippleConfig`'s own ranges, x100.
+ Self::RippleStrength => (0., 100., 1.),
+ Self::RippleSize => (25., 300., 1.),
+ Self::RippleDuration => (
+ CursorRippleConfig::DURATION_RANGE.0,
+ CursorRippleConfig::DURATION_RANGE.1,
+ 0.05,
+ ),
}
}
@@ -444,6 +449,9 @@ impl CursorSlider {
Self::Tension => cursor.tension,
Self::Friction => cursor.friction,
Self::Mass => cursor.mass,
+ Self::RippleStrength => cursor.ripple.strength_clamped() * 100.,
+ Self::RippleSize => cursor.ripple.size_clamped() * 100.,
+ Self::RippleDuration => cursor.ripple.duration_clamped(),
}
}
}
@@ -1046,6 +1054,9 @@ impl EditorWindow {
match_cursor_preset(cursor.tension, cursor.mass, cursor.friction)
.unwrap_or(CursorAnimationStyle::Custom);
}
+ CursorSlider::RippleStrength => cursor.ripple.strength = value / 100.,
+ CursorSlider::RippleSize => cursor.ripple.size = value / 100.,
+ CursorSlider::RippleDuration => cursor.ripple.duration = value,
}
true
});
@@ -1628,10 +1639,6 @@ impl EditorWindow {
return body.into_any_element();
}
- let cursor_type = format!("{:?}", cursor.cursor_type()).to_lowercase();
- let type_index = CURSOR_TYPES
- .iter()
- .position(|(value, _, _)| *value == cursor_type);
let style_index = CURSOR_STYLES
.iter()
.position(|(style, _, _)| *style == cursor.animation_style);
@@ -1639,29 +1646,9 @@ impl EditorWindow {
body = body
.child(
- ui::Field::plain(&theme, "Cursor Type")
+ ui::Field::plain(&theme, "Cursor Style")
.icon("icons/cursor.svg")
- .child(
- ui::RadioCards::plain(
- &theme,
- "cursor-type",
- CURSOR_TYPES
- .iter()
- .map(|(_, label, description)| {
- ui::RadioCard::new(*label, Some(description))
- })
- .collect(),
- type_index,
- )
- .on_select(cx.listener(
- |this, index: &usize, window, cx| {
- let Some((value, _, _)) = CURSOR_TYPES.get(*index) else {
- return;
- };
- this.set_cursor_type(value, window, cx);
- },
- )),
- ),
+ .child(self.render_cursor_style_picker(cx)),
)
.child(
ui::Field::plain(&theme, "Size")
@@ -1673,6 +1660,7 @@ impl EditorWindow {
.icon("icons/rotate-3d.svg")
.child(self.slider(SliderKey::Cursor(CursorSlider::Tilt), "x100%", cx)),
)
+ .child(self.render_cursor_ripple(cx))
.child(
ui::Field::plain(&theme, "Hide When Idle")
.icon("icons/timer.svg")
@@ -1719,136 +1707,112 @@ impl EditorWindow {
}
let smooth = !cursor.raw;
- body.child(
- ui::Field::plain(&theme, "Cursor Movement Style")
- .icon("icons/rabbit.svg")
- .child(
- ui::RadioCards::plain(
- &theme,
- "cursor-style",
- CURSOR_STYLES
- .iter()
- .map(|(_, label, description)| {
- ui::RadioCard::new(*label, Some(description))
- })
- .collect(),
- style_index,
+ let mut body = body
+ .child(
+ ui::Field::plain(&theme, "Cursor Movement Style")
+ .icon("icons/rabbit.svg")
+ .child(
+ ui::RadioCards::plain(
+ &theme,
+ "cursor-style",
+ CURSOR_STYLES
+ .iter()
+ .map(|(_, label, description)| {
+ ui::RadioCard::new(*label, Some(description))
+ })
+ .collect(),
+ style_index,
+ )
+ .on_select(cx.listener(
+ |this, index: &usize, window, cx| {
+ let Some((style, _, _)) = CURSOR_STYLES.get(*index) else {
+ return;
+ };
+ let style = *style;
+ // `applyCursorStylePreset` (`:551-561`): the style and
+ // its three physics values, in one batch.
+ this.edit_project("cursor-style", window, cx, move |project| {
+ project.cursor.animation_style = style;
+ if let Some(preset) = style.preset() {
+ project.cursor.tension = preset.tension;
+ project.cursor.mass = preset.mass;
+ project.cursor.friction = preset.friction;
+ }
+ true
+ });
+ },
+ )),
+ ),
+ )
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .child(
+ ui::Field::plain(&theme, "Smooth Movement")
+ .icon("icons/ease-curve.svg")
+ .value(
+ ui::Toggle::plain(&theme, "cursor-smooth", smooth)
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.sidebar.cursor_physics_open.set_open(!smooth);
+ this.animate_collapsibles(window, cx);
+ this.edit_project("cursor-raw", window, cx, move |p| {
+ p.cursor.raw = smooth;
+ true
+ });
+ }))
+ .into_any_element(),
+ ),
)
- .on_select(cx.listener(
- |this, index: &usize, window, cx| {
- let Some((style, _, _)) = CURSOR_STYLES.get(*index) else {
- return;
- };
- let style = *style;
- // `applyCursorStylePreset` (`:551-561`): the style and
- // its three physics values, in one batch.
- this.edit_project("cursor-style", window, cx, move |project| {
- project.cursor.animation_style = style;
- if let Some(preset) = style.preset() {
- project.cursor.tension = preset.tension;
- project.cursor.mass = preset.mass;
- project.cursor.friction = preset.friction;
- }
- true
- });
- },
+ .child(collapsible(
+ &self.sidebar.cursor_physics_open,
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(16.))
+ // `pt-4 pb-6`
+ .pt(px(16.))
+ .pb(px(24.))
+ .child(ui::Field::plain(&theme, "Tension").child(self.slider(
+ SliderKey::Cursor(CursorSlider::Tension),
+ "",
+ cx,
+ )))
+ .child(ui::Field::plain(&theme, "Friction").child(self.slider(
+ SliderKey::Cursor(CursorSlider::Friction),
+ "",
+ cx,
+ )))
+ .child(ui::Field::plain(&theme, "Mass").child(self.slider(
+ SliderKey::Cursor(CursorSlider::Mass),
+ "",
+ cx,
+ )))
+ .into_any_element(),
)),
- ),
- )
- .child(
- div()
- .flex()
- .flex_col()
- .child(
- ui::Field::plain(&theme, "Smooth Movement")
- .icon("icons/ease-curve.svg")
- .value(
- ui::Toggle::plain(&theme, "cursor-smooth", smooth)
- .on_click(cx.listener(move |this, _, window, cx| {
- this.sidebar.cursor_physics_open.set_open(!smooth);
- this.animate_collapsibles(window, cx);
- this.edit_project("cursor-raw", window, cx, move |p| {
- p.cursor.raw = smooth;
- true
- });
- }))
- .into_any_element(),
- ),
- )
- .child(collapsible(
- &self.sidebar.cursor_physics_open,
- div()
- .flex()
- .flex_col()
- .gap(px(16.))
- // `pt-4 pb-6`
- .pt(px(16.))
- .pb(px(24.))
- .child(ui::Field::plain(&theme, "Tension").child(self.slider(
- SliderKey::Cursor(CursorSlider::Tension),
- "",
- cx,
- )))
- .child(ui::Field::plain(&theme, "Friction").child(self.slider(
- SliderKey::Cursor(CursorSlider::Friction),
- "",
- cx,
- )))
- .child(ui::Field::plain(&theme, "Mass").child(self.slider(
- SliderKey::Cursor(CursorSlider::Mass),
- "",
- cx,
- )))
- .into_any_element(),
- )),
- )
- .child(
- ui::Field::plain(&theme, "High Quality SVG Cursors")
- .icon("icons/sparkles.svg")
- .value(
- ui::Toggle::plain(&theme, "cursor-svg", cursor.use_svg)
- .on_click(cx.listener(|this, _, window, cx| {
- let next = !this.project.cursor.use_svg;
- this.edit_project("cursor-svg", window, cx, move |p| {
- p.cursor.use_svg = next;
- true
- });
- }))
- .into_any_element(),
- ),
- )
- .into_any_element()
- }
+ );
- /// `CursorConfiguration::type` is private in `cap-project` with a getter
- /// and no setter, and this app does not edit the shared crate -- so the
- /// write goes through serde, which is the field's public surface. One
- /// round trip per click of a radio card costs nothing.
- fn set_cursor_type(
- &mut self,
- value: &'static str,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- self.edit_project("cursor-type", window, cx, move |project| {
- let Ok(mut json) = serde_json::to_value(&project.cursor) else {
- return false;
- };
- let Some(object) = json.as_object_mut() else {
- return false;
- };
- if object.get("type").and_then(|value| value.as_str()) == Some(value) {
- return false;
- }
- object.insert("type".into(), serde_json::Value::String(value.into()));
- match serde_json::from_value(json) {
- Ok(cursor) => {
- project.cursor = cursor;
- true
- }
- Err(_) => false,
- }
- });
+ // An explicit family forces the SVG assets, so the toggle would be
+ // showing a setting the renderer is already overriding.
+ if cursor.cursor_type().family().is_none() {
+ body = body.child(
+ ui::Field::plain(&theme, "High Quality SVG Cursors")
+ .icon("icons/sparkles.svg")
+ .value(
+ ui::Toggle::plain(&theme, "cursor-svg", cursor.use_svg)
+ .on_click(cx.listener(|this, _, window, cx| {
+ let next = !this.project.cursor.use_svg;
+ this.edit_project("cursor-svg", window, cx, move |p| {
+ p.cursor.use_svg = next;
+ true
+ });
+ }))
+ .into_any_element(),
+ ),
+ );
+ }
+
+ body.into_any_element()
}
// -- Keyboard ------------------------------------------------------------
diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs
index 6b8517ab3..4e7458517 100644
--- a/apps/desktop-gpui/src/editor_window.rs
+++ b/apps/desktop-gpui/src/editor_window.rs
@@ -47,9 +47,10 @@ use std::{
time::{Duration, Instant},
};
+use cap_cursor_info::CursorFamily;
use cap_editor::{EditorFrameOutput, EditorInstance, EditorState};
use cap_project::{
- ClipSpeedAudioMode, ProjectConfiguration, RecordingMeta, RecordingMetaInner,
+ ClipSpeedAudioMode, Cursors, ProjectConfiguration, RecordingMeta, RecordingMetaInner,
StudioRecordingMeta, TimelineConfiguration, XY,
};
use cap_rendering::{FrameLayout, ProjectRecordingsMeta, RenderedFrame};
@@ -237,6 +238,10 @@ pub struct ProjectSummary {
/// The cursor tab is disabled on `!meta().hasRecordedCursorData`
/// (`ConfigSidebar.tsx:610`).
pub has_cursor_data: bool,
+ /// The asset family the recorded cursor shapes belong to, which the style
+ /// picker highlights as "Recorded" and falls back to while the project's
+ /// own type is `Auto`.
+ pub recorded_cursor_family: Option<CursorFamily>,
/// `editorInstance.recordings.segments[i].display.duration` -- the ceiling
/// a clip's end handle trims out to (`TL/ClipTrack.tsx:1160-1162`).
pub clip_display_durations: Vec<f64>,
@@ -374,6 +379,7 @@ pub fn preflight(path: &std::path::Path) -> Result<ProjectSummary, String> {
duration: duration.max(0.0),
has_camera,
has_cursor_data: has_recorded_cursor_data(&meta, studio.as_ref()),
+ recorded_cursor_family: recorded_cursor_family(studio.as_ref()),
clip_display_durations: recordings
.segments
.iter()
@@ -440,6 +446,25 @@ fn has_recorded_cursor_data(meta: &RecordingMeta, studio: &StudioRecordingMeta)
}
}
+/// The family the recording's own cursor shapes belong to.
+///
+/// Keyed by cursor id so the answer does not depend on `HashMap` iteration
+/// order: a bundle whose shapes span two families would otherwise pick a
+/// different card between two opens of the same recording.
+fn recorded_cursor_family(studio: &StudioRecordingMeta) -> Option<CursorFamily> {
+ let StudioRecordingMeta::MultipleSegments { inner } = studio else {
+ return None;
+ };
+ let Cursors::Correct(cursors) = &inner.cursors else {
+ return None;
+ };
+ let mut ids: Vec<_> = cursors.keys().collect();
+ ids.sort();
+ ids.into_iter()
+ .find_map(|id| cursors.get(id).and_then(|cursor| cursor.shape))
+ .map(|shape| shape.family())
+}
+
/// One rendered frame, lifted into gpui's sprite atlas.
///
/// Two conversions, both mandatory:
@@ -1310,6 +1335,9 @@ pub struct EditorWindow {
/// model can be rebuilt after every edit.
has_camera: bool,
multiple_clips: bool,
+ /// `ProjectSummary::recorded_cursor_family`, kept here because the cursor
+ /// tab renders long before (and independently of) the load state's box.
+ pub(crate) recorded_cursor_family: Option<CursorFamily>,
/// The debounced `project-config.json` write, and the task driving it.
pending_save: Rc<RefCell<PendingProjectSave>>,
save_task: Option<gpui::Task<()>>,
@@ -1620,6 +1648,7 @@ impl EditorWindow {
recording_duration: 0.0,
has_camera: false,
multiple_clips: false,
+ recorded_cursor_family: None,
pending_save: Rc::new(RefCell::new(PendingProjectSave::default())),
save_task: None,
name_input,
@@ -1709,6 +1738,7 @@ impl EditorWindow {
self.recording_duration = summary.recording_duration;
self.has_camera = summary.has_camera;
self.multiple_clips = summary.multiple_clips;
+ self.recorded_cursor_family = summary.recorded_cursor_family;
self.pending_save.borrow_mut().path = Some(self.project_path.clone());
// `zoom: zoomOutLimit()` is the store's *initial* value
// (`ED/context.ts:1455`), so it is set the moment a duration exists --
@@ -8336,6 +8366,7 @@ impl Render for EditorWindow {
// a brand-new box empty until something else asked for a frame.
self.prepare_sidebar_fields(window, cx);
self.prepare_animated_gradient_fields(window, cx);
+ self.prepare_cursor_fields(window, cx);
self.sync_hex_inputs(window, cx);
self.sync_picker_hex(window, cx);
self.sync_crop_container(window);