Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): keep the resting agent cursor animating on every platform (#4131)

Francesco Bonacci7b4b595ef88d
diff --git a/libs/cua-driver/docs/cursor-themes.md b/libs/cua-driver/docs/cursor-themes.md
index 4a554beb1a..a9b71a83a2 100644
--- a/libs/cua-driver/docs/cursor-themes.md
+++ b/libs/cua-driver/docs/cursor-themes.md
@@ -11,7 +11,11 @@ plus a tighter, softer glow so they remain legible without competing with it.
Every semantic state inherits the same gentle levitation and rotation as the
idle pointer, with its action-specific motion layered on top. The pointer and
semantic mark therefore move as one visual unit.
-Reduced-motion mode removes this shared movement. The anonymous/default cursor
+The macOS, Windows, X11, and Wayland overlays keep rendering frames while a
+visible cursor rests, so the levitation continues until the idle fade hides it.
+A cursor set never to hide (`idle_hide_ms` 0) rests still instead, so the
+overlay stops rendering once activity settles. Reduced-motion mode removes this
+shared movement and lets the overlay stop rendering while the cursor is still. The anonymous/default cursor
uses Cua blue. Named sessions receive a stable fill
from the built-in session palette, so concurrent agents remain visually
distinct.
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index 7a51a5a15c..7e74b758da 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -1397,6 +1397,7 @@ dependencies = [
"cua-driver-contract",
"fontdue",
"image",
+ "indexmap",
"postcard",
"serde",
"serde_json",
@@ -3546,7 +3547,6 @@ dependencies = [
"futures-util",
"getrandom 0.4.2",
"image",
- "indexmap",
"libc",
"objc2 0.5.2",
"objc2-app-kit 0.2.2",
@@ -3581,7 +3581,6 @@ dependencies = [
"cursor-overlay",
"getrandom 0.4.2",
"image",
- "indexmap",
"keyring",
"pip-preview",
"serde",
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/Cargo.toml b/libs/cua-driver/rust/crates/cursor-overlay/Cargo.toml
index f7af314d8d..1f86c01a87 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cursor-overlay/Cargo.toml
@@ -13,6 +13,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
anyhow = { workspace = true }
tracing = { workspace = true }
+indexmap = "2"
postcard.workspace = true
sha2.workspace = true
zstd.workspace = true
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
index 0e2f2835f2..dd90baaaa2 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
@@ -11,6 +11,7 @@ pub mod bezier;
pub mod capture_utils;
pub mod motion;
pub mod path_planner;
+pub mod render_map;
pub mod render_state;
pub mod session_badge;
pub mod theme;
@@ -21,6 +22,10 @@ pub use badge_glyphs::{BadgeChip, BadgeGlyph};
pub use bezier::CubicBezier;
pub use motion::{MotionConfig, Spring};
pub use path_planner::{PathPlanner, PathState, PlannedPath};
+pub use render_map::{
+ keyed_config, seed_position, CursorMap, MsgOutcome, RenderEntry, RenderMap, ScreenFrame,
+ DEFAULT_CURSOR_KEY, SEED_OFFSET,
+};
pub use render_state::{
paint_cursor, render_frame, FocusRect, RenderStateCore, SESSION_BADGE_FADE_SECS,
SESSION_BADGE_HOLD_SECS,
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/render_map.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/render_map.rs
new file mode 100644
index 0000000000..bfe0243e1d
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/render_map.rs
@@ -0,0 +1,727 @@
+//! Keyed per-session cursor render map shared by every platform overlay.
+//!
+//! Each declared session owns one cursor, keyed by [`CursorKey`]. The macOS,
+//! Windows, X11, and Wayland adapters all drain the same [`OverlayMsg`]
+//! stream into this map, so the lifecycle contract lives here once:
+//!
+//! - lazy creation from the launch template, with the key as the cursor's
+//! color identity (`cursor_id`), so every session inherits the selected
+//! theme and motion;
+//! - a stable z-order: insertion order, unchanged when a cursor is touched
+//! again (later keys paint on top);
+//! - `session_end` removal plus a tombstone that drops late in-flight
+//! commands instead of resurrecting the cursor, and an explicit revival
+//! that clears the tombstone without recreating the cursor;
+//! - the `"default"` guard: the anonymous cursor is never removed or
+//! tombstoned;
+//! - the sentinel seed that places a never-shown cursor near its first
+//! target so the first action glides in;
+//! - the frame-tick predicate ([`RenderStateCore::needs_frame_tick`]),
+//! including resting motion.
+//!
+//! Adapters keep only what their windowing system needs: geometry in
+//! [`RenderMap::platform`], arrival waiters, and render-loop scheduling.
+
+use std::collections::HashSet;
+use std::time::Duration;
+
+use indexmap::IndexMap;
+
+use crate::{
+ CursorConfig, CursorKey, KeyedOverlayCommand, OverlayCommand, OverlayMsg, RenderStateCore,
+};
+
+/// Key of the anonymous cursor seeded at startup. It backs one-shot calls
+/// without a session and survives every `session_end`.
+pub const DEFAULT_CURSOR_KEY: &str = "default";
+
+/// Distance between a seeded start point and its first target, per axis.
+/// 140 points reads as motion at the reference peak glide speed.
+pub const SEED_OFFSET: f64 = 140.0;
+
+/// Insertion-ordered cursor collection. Iteration order is the paint order.
+pub type CursorMap<S> = IndexMap<CursorKey, S>;
+
+/// One cursor entry in a [`RenderMap`]. Platforms wrap [`RenderStateCore`]
+/// to add their own state (for example the macOS focus rectangle); a plain
+/// core is itself an entry.
+pub trait RenderEntry {
+ /// Build a cursor from its (already keyed) configuration.
+ fn from_config(config: CursorConfig) -> Self;
+ fn core(&self) -> &RenderStateCore;
+ fn core_mut(&mut self) -> &mut RenderStateCore;
+ /// Apply one render command. Returns whether pixels may have changed.
+ fn apply_command(&mut self, cmd: OverlayCommand) -> bool;
+ /// Advance by `dt` seconds. Returns true on the tick a planned path ends.
+ fn tick(&mut self, dt: f64) -> bool {
+ self.core_mut().tick_motion(dt)
+ }
+ /// Whether the render loop must run at frame cadence for this cursor.
+ /// Overrides must include the shared core predicate.
+ fn needs_frame_tick(&self) -> bool {
+ self.core().needs_frame_tick()
+ }
+}
+
+impl RenderEntry for RenderStateCore {
+ fn from_config(config: CursorConfig) -> Self {
+ RenderStateCore::new(config)
+ }
+
+ fn core(&self) -> &RenderStateCore {
+ self
+ }
+
+ fn core_mut(&mut self) -> &mut RenderStateCore {
+ self
+ }
+
+ fn apply_command(&mut self, cmd: OverlayCommand) -> bool {
+ self.apply_command_base(cmd, false, false)
+ }
+}
+
+/// What one drained [`OverlayMsg`] did to the map.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum MsgOutcome {
+ /// The command reached `key`'s cursor, creating it when absent.
+ Applied { key: CursorKey, dirty: bool },
+ /// The command was dropped because `key`'s session already ended.
+ Dropped(CursorKey),
+ /// `key` was removed and tombstoned. `existed` reports whether a cursor
+ /// was actually removed. Adapters release that key's arrival waiter.
+ Removed { key: CursorKey, existed: bool },
+ /// `key`'s tombstone was cleared; the cursor is recreated lazily.
+ Revived(CursorKey),
+ /// A lifecycle message for the guarded `"default"` cursor, or an empty
+ /// key, was ignored.
+ Ignored,
+}
+
+impl MsgOutcome {
+ /// The cursor a command resolved to, for z-order pinning.
+ pub fn applied_key(&self) -> Option<&CursorKey> {
+ match self {
+ Self::Applied { key, .. } => Some(key),
+ _ => None,
+ }
+ }
+
+ /// Whether the message can have changed rendered pixels.
+ pub fn is_dirty(&self) -> bool {
+ match self {
+ Self::Applied { dirty, .. } => *dirty,
+ Self::Removed { existed, .. } => *existed,
+ _ => false,
+ }
+ }
+}
+
+/// A screen rectangle in the coordinate space of cursor positions.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct ScreenFrame {
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+}
+
+impl ScreenFrame {
+ pub fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
+ Self {
+ x,
+ y,
+ width,
+ height,
+ }
+ }
+
+ /// Smallest frame containing every given frame, or `None` when empty.
+ pub fn union(frames: impl IntoIterator<Item = ScreenFrame>) -> Option<ScreenFrame> {
+ frames.into_iter().reduce(|a, b| {
+ let x0 = a.x.min(b.x);
+ let y0 = a.y.min(b.y);
+ let x1 = (a.x + a.width).max(b.x + b.width);
+ let y1 = (a.y + a.height).max(b.y + b.height);
+ ScreenFrame::new(x0, y0, x1 - x0, y1 - y0)
+ })
+ }
+}
+
+/// Start point for a never-shown cursor whose first action targets
+/// `(target_x, target_y)`: up-left of the target by [`SEED_OFFSET`], clamped
+/// 2 points inside `frame`. When clamping collapses the seed onto the target
+/// (a target in the top-left corner), the seed flips down-right so the glide
+/// stays visible. Without a known frame the seed is only kept off negative
+/// coordinates, which would otherwise read as the off-screen sentinel.
+pub fn seed_position(target_x: f64, target_y: f64, frame: Option<ScreenFrame>) -> (f64, f64) {
+ let mut sx = target_x - SEED_OFFSET;
+ let mut sy = target_y - SEED_OFFSET;
+ match frame.filter(|frame| frame.width > 4.0 && frame.height > 4.0) {
+ Some(frame) => {
+ let (min_x, max_x) = (frame.x + 2.0, frame.x + frame.width - 2.0);
+ let (min_y, max_y) = (frame.y + 2.0, frame.y + frame.height - 2.0);
+ sx = sx.clamp(min_x, max_x);
+ sy = sy.clamp(min_y, max_y);
+ if (sx - target_x).abs() < 8.0 && (sy - target_y).abs() < 8.0 {
+ sx = (target_x + SEED_OFFSET).clamp(min_x, max_x);
+ sy = (target_y + SEED_OFFSET).clamp(min_y, max_y);
+ }
+ }
+ None => {
+ sx = sx.max(2.0);
+ sy = sy.max(2.0);
+ }
+ }
+ (sx, sy)
+}
+
+/// Configuration for a lazily created session cursor: the launch template
+/// with the key as its color identity.
+pub fn keyed_config(template: &CursorConfig, key: &str) -> CursorConfig {
+ let mut config = template.clone();
+ config.cursor_id = key.to_owned();
+ config
+}
+
+/// The keyed render collection plus per-platform state `P` (screen geometry,
+/// timing stamps) that the adapter owns.
+pub struct RenderMap<S, P = ()> {
+ /// Owned cursors in stable paint order.
+ pub cursors: CursorMap<S>,
+ /// Frozen launch-time configuration for lazily created cursors.
+ pub template: CursorConfig,
+ /// Tombstones of ended session keys. Never contains `"default"`.
+ pub ended: HashSet<CursorKey>,
+ /// Most recently commanded cursor, cleared when that cursor is removed.
+ /// A single overlay window can occupy one z-band, so this cursor's target
+ /// wins z-order pinning.
+ pub last_active: Option<CursorKey>,
+ /// Platform-owned state.
+ pub platform: P,
+}
+
+impl<S: RenderEntry, P> RenderMap<S, P> {
+ /// A map holding only the `"default"` cursor, which keeps the template's
+ /// own `cursor_id`.
+ pub fn new(template: CursorConfig, platform: P) -> Self {
+ let mut cursors = CursorMap::new();
+ cursors.insert(
+ DEFAULT_CURSOR_KEY.to_owned(),
+ S::from_config(template.clone()),
+ );
+ Self {
+ cursors,
+ template,
+ ended: HashSet::new(),
+ last_active: None,
+ platform,
+ }
+ }
+
+ /// Build the cursor a new session key would receive.
+ pub fn state_for_key(&self, key: &str) -> S {
+ S::from_config(keyed_config(&self.template, key))
+ }
+
+ /// Get or lazily create `key`'s cursor. `None` for an ended session, so
+ /// no path can resurrect a removed cursor.
+ pub fn cursor_mut(&mut self, key: &str) -> Option<&mut S> {
+ if key.is_empty() || self.ended.contains(key) {
+ return None;
+ }
+ if !self.cursors.contains_key(key) {
+ let state = self.state_for_key(key);
+ self.cursors.insert(key.to_owned(), state);
+ }
+ self.cursors.get_mut(key)
+ }
+
+ /// `key`'s cursor, or the `"default"` cursor when the session has not
+ /// created its own yet.
+ pub fn cursor_or_default(&self, key: &str) -> Option<&S> {
+ self.cursors
+ .get(key)
+ .or_else(|| self.cursors.get(DEFAULT_CURSOR_KEY))
+ }
+
+ /// Apply one drained channel message.
+ pub fn apply_msg(&mut self, msg: OverlayMsg) -> MsgOutcome {
+ match msg {
+ OverlayMsg::Cmd(KeyedOverlayCommand { key, cmd }) => self.apply_command(key, cmd),
+ OverlayMsg::Remove(key) => self.remove(key),
+ OverlayMsg::Revive(key) => self.revive(key),
+ }
+ }
+
+ /// Apply `cmd` to `key`'s cursor unless that session ended.
+ pub fn apply_command(&mut self, key: CursorKey, cmd: OverlayCommand) -> MsgOutcome {
+ let Some(cursor) = self.cursor_mut(&key) else {
+ tracing::debug!(key = %key, cmd = ?cmd, "overlay: command dropped; key was ended");
+ return MsgOutcome::Dropped(key);
+ };
+ let dirty = cursor.apply_command(cmd);
+ self.last_active = Some(key.clone());
+ MsgOutcome::Applied { key, dirty }
+ }
+
+ /// Remove and tombstone `key`. The `"default"` cursor is guarded.
+ pub fn remove(&mut self, key: CursorKey) -> MsgOutcome {
+ if key.is_empty() || key == DEFAULT_CURSOR_KEY {
+ return MsgOutcome::Ignored;
+ }
+ let existed = self.cursors.shift_remove(&key).is_some();
+ if self.last_active.as_deref() == Some(key.as_str()) {
+ self.last_active = None;
+ }
+ self.ended.insert(key.clone());
+ MsgOutcome::Removed { key, existed }
+ }
+
+ /// Clear `key`'s tombstone after an explicit session revival.
+ pub fn revive(&mut self, key: CursorKey) -> MsgOutcome {
+ if key.is_empty() || key == DEFAULT_CURSOR_KEY {
+ return MsgOutcome::Ignored;
+ }
+ self.ended.remove(&key);
+ MsgOutcome::Revived(key)
+ }
+
+ /// Place a never-shown (sentinel) cursor near its first target so the
+ /// following `MoveTo` glides in instead of snapping. Creates the cursor
+ /// when absent. Returns whether a seed was applied; a no-op for an ended
+ /// session, a disabled cursor, or one already on screen.
+ pub fn seed_start_if_sentinel(
+ &mut self,
+ key: &str,
+ target_x: f64,
+ target_y: f64,
+ frame: Option<ScreenFrame>,
+ ) -> bool {
+ let Some(cursor) = self.cursor_mut(key) else {
+ return false;
+ };
+ let core = cursor.core_mut();
+ if !(core.cfg.enabled && core.pos.0 < -50.0) {
+ return false;
+ }
+ core.pos = seed_position(target_x, target_y, frame);
+ true
+ }
+
+ /// Advance every cursor; returns the keys whose planned path just ended.
+ pub fn tick_all(&mut self, dt: f64) -> Vec<CursorKey> {
+ let mut arrived = Vec::new();
+ for (key, cursor) in self.cursors.iter_mut() {
+ if cursor.tick(dt) {
+ arrived.push(key.clone());
+ }
+ }
+ arrived
+ }
+
+ /// Whether any cursor needs frame-cadence ticks.
+ pub fn needs_frame_tick(&self) -> bool {
+ self.cursors.values().any(S::needs_frame_tick)
+ }
+
+ /// Earliest idle-fade start across cursors, for a parked loop's deadline.
+ pub fn idle_fade_wait(&self) -> Option<Duration> {
+ self.cursors
+ .values()
+ .filter_map(|cursor| cursor.core().idle_fade_wait())
+ .min()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ReducedMotion;
+
+ type Map = RenderMap<RenderStateCore>;
+
+ fn map() -> Map {
+ let mut map = Map::new(CursorConfig::default(), ());
+ map.cursors[DEFAULT_CURSOR_KEY].motion.idle_hide_ms = 500.0;
+ map
+ }
+
+ fn move_msg(key: &str, x: f64, y: f64) -> OverlayMsg {
+ OverlayMsg::Cmd(KeyedOverlayCommand {
+ key: key.to_owned(),
+ cmd: OverlayCommand::MoveTo {
+ x,
+ y,
+ end_heading_radians: 0.0,
+ },
+ })
+ }
+
+ fn placed<'a>(map: &'a mut Map, key: &str) -> &'a mut RenderStateCore {
+ let core = map.cursor_mut(key).unwrap();
+ core.pos = (100.0, 100.0);
+ core
+ }
+
+ fn settle(core: &mut RenderStateCore) {
+ for _ in 0..2000 {
+ core.tick_motion(1.0 / 60.0);
+ if core.path.is_none() && core.spring.is_none() && core.click_t.is_none() {
+ break;
+ }
+ }
+ }
+
+ #[test]
+ fn sessions_get_distinct_cursors_that_inherit_the_template() {
+ let mut map = map();
+ map.apply_msg(move_msg("sessA", 10.0, 10.0));
+ map.apply_msg(move_msg("sessB", 20.0, 20.0));
+
+ assert_eq!(map.cursors.len(), 3);
+ assert_eq!(map.cursors["sessA"].cfg.cursor_id, "sessA");
+ assert_eq!(map.cursors["sessB"].cfg.cursor_id, "sessB");
+ // The default slot keeps the launch-time identity.
+ assert_eq!(
+ map.cursors[DEFAULT_CURSOR_KEY].cfg.cursor_id,
+ CursorConfig::default().cursor_id
+ );
+ for key in ["sessA", "sessB"] {
+ assert_eq!(map.cursors[key].cfg.theme_id, map.template.theme_id);
+ assert_eq!(map.cursors[key].motion, map.template.motion);
+ }
+ }
+
+ #[test]
+ fn insertion_order_is_a_stable_z_order() {
+ let mut map = map();
+ map.apply_msg(move_msg("first", 1.0, 1.0));
+ map.apply_msg(move_msg("second", 2.0, 2.0));
+ map.apply_msg(move_msg("first", 3.0, 3.0));
+ let keys: Vec<&str> = map.cursors.keys().map(String::as_str).collect();
+ assert_eq!(keys, ["default", "first", "second"]);
+ }
+
+ #[test]
+ fn applied_commands_track_the_last_active_cursor() {
+ let mut map = map();
+ let outcome = map.apply_msg(move_msg("sessA", 10.0, 10.0));
+ assert_eq!(outcome.applied_key().map(String::as_str), Some("sessA"));
+ assert!(outcome.is_dirty());
+ assert_eq!(map.last_active.as_deref(), Some("sessA"));
+
+ map.apply_msg(move_msg("sessB", 10.0, 10.0));
+ map.apply_msg(OverlayMsg::Remove("sessA".to_owned()));
+ assert_eq!(map.last_active.as_deref(), Some("sessB"));
+ map.apply_msg(OverlayMsg::Remove("sessB".to_owned()));
+ assert_eq!(map.last_active, None);
+ }
+
+ #[test]
+ fn removal_tombstones_only_that_session_and_blocks_resurrection() {
+ let mut map = map();
+ map.apply_msg(move_msg("sessA", 10.0, 10.0));
+ map.apply_msg(move_msg("sessB", 20.0, 20.0));
+
+ assert_eq!(
+ map.apply_msg(OverlayMsg::Remove("sessA".to_owned())),
+ MsgOutcome::Removed {
+ key: "sessA".to_owned(),
+ existed: true
+ }
+ );
+ assert!(!map.cursors.contains_key("sessA"));
+ assert!(map.cursors.contains_key("sessB"));
+ assert!(map.ended.contains("sessA"));
+
+ // A late in-flight command and a seed are both dropped.
+ assert_eq!(
+ map.apply_msg(move_msg("sessA", 99.0, 99.0)),
+ MsgOutcome::Dropped("sessA".to_owned())
+ );
+ assert!(!map.seed_start_if_sentinel("sessA", 60.0, 60.0, None));
+ assert!(!map.cursors.contains_key("sessA"));
+
+ // Removing a session that never drew is a harmless tombstone.
+ assert_eq!(
+ map.apply_msg(OverlayMsg::Remove("never-drew".to_owned())),
+ MsgOutcome::Removed {
+ key: "never-drew".to_owned(),
+ existed: false
+ }
+ );
+ assert_eq!(map.cursors.len(), 2);
+ }
+
+ #[test]
+ fn revival_clears_the_tombstone_and_recreates_lazily() {
+ let mut map = map();
+ map.apply_msg(move_msg("sessA", 10.0, 10.0));
+ map.apply_msg(OverlayMsg::Remove("sessA".to_owned()));
+
+ assert_eq!(
+ map.apply_msg(OverlayMsg::Revive("sessA".to_owned())),
+ MsgOutcome::Revived("sessA".to_owned())
+ );
+ assert!(!map.ended.contains("sessA"));
+ assert!(!map.cursors.contains_key("sessA"));
+
+ let outcome = map.apply_msg(move_msg("sessA", 30.0, 30.0));
+ assert_eq!(outcome.applied_key().map(String::as_str), Some("sessA"));
+ assert!(map.cursors.contains_key("sessA"));
+ }
+
+ #[test]
+ fn default_and_empty_keys_are_guarded() {
+ let mut map = map();
+ for msg in [
+ OverlayMsg::Remove(DEFAULT_CURSOR_KEY.to_owned()),
+ OverlayMsg::Revive(DEFAULT_CURSOR_KEY.to_owned()),
+ OverlayMsg::Remove(String::new()),
+ ] {
+ assert_eq!(map.apply_msg(msg), MsgOutcome::Ignored);
+ }
+ assert!(map.cursors.contains_key(DEFAULT_CURSOR_KEY));
+ assert!(map.ended.is_empty());
+ assert!(map.cursor_mut("").is_none());
+
+ let outcome = map.apply_msg(move_msg(DEFAULT_CURSOR_KEY, 5.0, 5.0));
+ assert_eq!(
+ outcome.applied_key().map(String::as_str),
+ Some(DEFAULT_CURSOR_KEY)
+ );
+ }
+
+ #[test]
+ fn cursor_or_default_falls_back_only_for_absent_keys() {
+ let mut map = map();
+ map.cursors[DEFAULT_CURSOR_KEY].visible = false;
+ assert!(!map.cursor_or_default("sessA").unwrap().visible);
+ map.cursor_mut("sessA");
+ assert!(map.cursor_or_default("sessA").unwrap().visible);
+ }
+
+ #[test]
+ fn seed_places_a_sentinel_cursor_on_screen_once() {
+ let mut map = map();
+ let frame = Some(ScreenFrame::new(0.0, 0.0, 100.0, 100.0));
+ assert!(map.seed_start_if_sentinel("sessA", 60.0, 60.0, frame));
+ let pos = map.cursors["sessA"].pos;
+ assert!(
+ pos.0 > -50.0 && pos.1 > -50.0,
+ "seed must be on screen: {pos:?}"
+ );
+ assert!(
+ (pos.0 - 60.0).abs() > 4.0 || (pos.1 - 60.0).abs() > 4.0,
+ "seed must differ from the target: {pos:?}"
+ );
+
+ map.cursors["sessA"].pos = (30.0, 30.0);
+ assert!(!map.seed_start_if_sentinel("sessA", 80.0, 80.0, frame));
+ assert_eq!(map.cursors["sessA"].pos, (30.0, 30.0));
+
+ map.cursor_mut("disabled").unwrap().cfg.enabled = false;
+ assert!(!map.seed_start_if_sentinel("disabled", 80.0, 80.0, frame));
+ }
+
+ #[test]
+ fn seed_position_clamps_into_the_frame_and_keeps_a_visible_glide() {
+ let frame = ScreenFrame::new(0.0, 0.0, 1920.0, 1080.0);
+ assert_eq!(seed_position(500.0, 400.0, Some(frame)), (360.0, 260.0));
+ // A top-left corner target flips the seed down-right.
+ assert_eq!(seed_position(3.0, 3.0, Some(frame)), (143.0, 143.0));
+ // A secondary monitor left of the primary has negative coordinates.
+ let virtual_screen = ScreenFrame::new(-1920.0, 0.0, 3840.0, 1080.0);
+ assert_eq!(
+ seed_position(-1800.0, 500.0, Some(virtual_screen)),
+ (-1918.0, 360.0)
+ );
+ // Unknown geometry never produces a sentinel-like negative seed.
+ assert_eq!(seed_position(50.0, 500.0, None), (2.0, 360.0));
+ // A degenerate frame is treated as unknown instead of panicking.
+ let tiny = ScreenFrame::new(0.0, 0.0, 1.0, 1.0);
+ assert_eq!(seed_position(50.0, 500.0, Some(tiny)), (2.0, 360.0));
+ }
+
+ #[test]
+ fn screen_frame_union_bounds_every_output() {
+ let union = ScreenFrame::union([
+ ScreenFrame::new(0.0, 0.0, 1920.0, 1080.0),
+ ScreenFrame::new(1920.0, -200.0, 1280.0, 1024.0),
+ ]);
+ assert_eq!(union, Some(ScreenFrame::new(0.0, -200.0, 3200.0, 1280.0)));
+ assert_eq!(ScreenFrame::union([]), None);
+ }
+
+ #[test]
+ fn sentinel_cursor_is_quiescent() {
+ let map = map();
+ assert!(!map.needs_frame_tick());
+ assert_eq!(map.idle_fade_wait(), None);
+ }
+
+ #[test]
+ fn glide_and_click_pulse_require_frame_ticks() {
+ let mut map = map();
+ placed(&mut map, "glide");
+ map.apply_msg(move_msg("glide", 250.0, 150.0));
+ assert!(map.cursors["glide"].needs_frame_tick());
+
+ let mut map = self::map();
+ let core = placed(&mut map, DEFAULT_CURSOR_KEY);
+ core.visual.reduced_motion = ReducedMotion::On;
+ core.motion.idle_hide_ms = 0.0;
+ core.apply_command_base(
+ OverlayCommand::ClickPulse { x: 20.0, y: 30.0 },
+ false,
+ false,
+ );
+ assert!(core.needs_frame_tick());
+ settle(core);
+ for _ in 0..120 {
+ core.tick_motion(1.0 / 60.0);
+ }
+ assert!(!map.needs_frame_tick(), "a finished pulse must park");
+ }
+
+ // The resting bob is painted by every adapter through `paint_cursor`, so a
+ // visible resting cursor must keep receiving frames on every platform
+ // until its idle fade hides it.
+ #[test]
+ fn a_visible_resting_cursor_keeps_ticking_for_its_resting_motion() {
+ let mut map = map();
+ let core = placed(&mut map, DEFAULT_CURSOR_KEY);
+ core.motion.idle_hide_ms = 20_000.0;
+ settle(core);
+ assert!(core.has_resting_motion());
+ assert!(map.needs_frame_tick());
+
+ // The bob actually moves pixels between two resting frames.
+ let paint = |core: &RenderStateCore| {
+ let mut pixmap = tiny_skia::Pixmap::new(200, 200).unwrap();
+ crate::paint_cursor(&mut pixmap, core, 0.0, 0.0, None, 1.0);
+ pixmap.data().to_vec()
+ };
+ let core = &mut map.cursors[DEFAULT_CURSOR_KEY];
+ let before = paint(core);
+ core.tick_motion(0.4);
+ assert_ne!(before, paint(core), "resting frames must differ");
+ }
+
+ #[test]
+ fn resting_motion_stops_for_reduced_motion_hidden_and_faded_cursors() {
+ let mut map = map();
+ let core = placed(&mut map, DEFAULT_CURSOR_KEY);
+ core.motion.idle_hide_ms = 20_000.0;
+ assert!(core.needs_frame_tick());
+
+ core.visual.reduced_motion = ReducedMotion::On;
+ assert!(!core.has_resting_motion());
+ assert!(!core.needs_frame_tick());
+ core.visual.reduced_motion = ReducedMotion::Auto;
+
+ core.visible = false;
+ assert!(!core.needs_frame_tick());
+ core.visible = true;
+
+ core.pinned_target_off_workspace = true;
+ assert!(!core.has_resting_motion());
+ core.pinned_target_off_workspace = false;
+
+ core.idle_alpha = 0.0;
+ assert!(!core.needs_frame_tick());
+ }
+
+ // A never-hiding cursor stays on screen indefinitely, so its resting
+ // motion would keep the overlay rendering forever. It rests still and the
+ // overlay quiesces, which the hosted Wayland CPU certification enforces.
+ #[test]
+ fn a_never_hiding_cursor_rests_still_so_the_overlay_quiesces() {
+ let mut map = map();
+ let core = placed(&mut map, DEFAULT_CURSOR_KEY);
+ core.motion.idle_hide_ms = 0.0;
+ settle(core);
+ for _ in 0..600 {
+ core.tick_motion(1.0 / 60.0);
+ }
+ assert!(core.is_revealed());
+ assert!(!core.has_resting_motion());
+ assert!(!map.needs_frame_tick());
+ assert_eq!(map.idle_fade_wait(), None);
+ }
+
+ #[test]
+ fn a_single_frame_custom_theme_has_no_resting_motion() {
+ let mut theme = (*crate::embedded_default_theme()).clone();
+ theme.id = "example.still".to_owned();
+ let mut map = map();
+ let core = placed(&mut map, DEFAULT_CURSOR_KEY);
+ for animation in theme.actions.values_mut() {
+ animation.frames.truncate(1);
+ animation.still_frame = 0;
+ }
+ core.theme = Some(std::sync::Arc::new(theme));
+ assert!(!core.has_resting_motion());
+
+ let mut looping = (*crate::embedded_default_theme()).clone();
+ looping.id = "example.loop".to_owned();
+ for animation in looping.actions.values_mut() {
+ let first = animation.frames[0].clone();
+ animation.frames = vec![first.clone(), first];
+ }
+ core.theme = Some(std::sync::Arc::new(looping));
+ assert!(core.has_resting_motion());
+ }
+
+ #[test]
+ fn reduced_motion_parks_through_the_opaque_delay_then_ticks_the_fade() {
+ let mut map = map();
+ let core = placed(&mut map, DEFAULT_CURSOR_KEY);
+ core.visual.reduced_motion = ReducedMotion::On;
+ core.apply_command_base(
+ OverlayCommand::MoveTo {
+ x: 250.0,
+ y: 150.0,
+ end_heading_radians: 0.0,
+ },
+ false,
+ false,
+ );
+ for _ in 0..1200 {
+ core.tick_motion(1.0 / 60.0);
+ if !core.needs_frame_tick() {
+ break;
+ }
+ }
+ assert!(!core.needs_frame_tick(), "opaque idle delay must park");
+ assert_eq!(core.idle_alpha, 1.0);
+
+ let wait = map.idle_fade_wait().expect("idle fade deadline");
+ let core = &mut map.cursors[DEFAULT_CURSOR_KEY];
+ assert!(wait > Duration::ZERO && wait <= Duration::from_millis(500));
+ // Wake just past the deadline, as a parked loop's timeout does.
+ core.tick_motion(wait.as_secs_f64() + 0.001);
+ assert!(core.idle_fade_in_progress());
+ assert!(core.needs_frame_tick());
+ assert_eq!(map.idle_fade_wait(), None);
+
+ for _ in 0..60 {
+ map.tick_all(1.0 / 60.0);
+ }
+ assert_eq!(map.cursors[DEFAULT_CURSOR_KEY].idle_alpha, 0.0);
+ assert!(!map.needs_frame_tick(), "a fully faded cursor must park");
+ }
+
+ #[test]
+ fn tick_all_reports_each_arrival_once() {
+ let mut map = map();
+ placed(&mut map, "sessA");
+ map.apply_msg(move_msg("sessA", 120.0, 120.0));
+ let mut arrivals = Vec::new();
+ for _ in 0..600 {
+ arrivals.extend(map.tick_all(1.0 / 60.0));
+ }
+ assert_eq!(arrivals, ["sessA"]);
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs
index e00ca4502c..0774a11bc6 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs
@@ -152,10 +152,92 @@ impl RenderStateCore {
}
}
- fn cursor_is_revealed(&self) -> bool {
+ /// Whether the cursor currently paints pixels: user-visible, placed on
+ /// screen (not the `(-200, -200)` sentinel), and not fully idle-faded.
+ pub fn is_revealed(&self) -> bool {
self.visible && self.pos.0 >= -100.0 && self.idle_alpha >= 0.004
}
+ /// Whether a revealed cursor keeps changing pixels while it rests.
+ ///
+ /// The default theme levitates through the shared float motion (the
+ /// resting "bob"), and a custom theme may loop a multi-frame animation for
+ /// its current action. Both are part of the cursor's visual identity, so
+ /// every platform must keep delivering frames while this holds.
+ ///
+ /// Resting motion is bounded by idle hide: the cursor levitates while its
+ /// idle-hide countdown runs and stops when the fade hides it. A cursor
+ /// configured never to hide (`idle_hide_ms == 0`) rests still, so the
+ /// overlay can stop rendering once activity settles; a full-output
+ /// redraw per frame on Wayland, or a layered-window upload on Windows,
+ /// must not run for as long as the cursor stays on screen. Reduced motion
+ /// freezes both (no bob, still frame), a hidden, unplaced, faded, or
+ /// off-workspace cursor paints nothing, and a single-frame custom theme
+ /// has nothing to animate.
+ pub fn has_resting_motion(&self) -> bool {
+ if !self.is_revealed()
+ || self.motion.idle_hide_ms <= 0.0
+ || self.pinned_target_off_workspace
+ || self.visual.reduced_motion == crate::ReducedMotion::On
+ {
+ return false;
+ }
+ match self.theme.as_deref() {
+ // The defensive no-theme fallback paints the embedded default.
+ None => true,
+ Some(theme) if theme.id == crate::DEFAULT_THEME_ID => true,
+ Some(theme) => theme
+ .animation_for_action(self.visual.resolved_action)
+ .is_some_and(|animation| animation.frames.len() > 1),
+ }
+ }
+
+ /// Whether the idle-hide fade (the 180 ms alpha ramp after
+ /// `motion.idle_hide_ms` of inactivity) is currently animating.
+ pub fn idle_fade_in_progress(&self) -> bool {
+ self.motion.idle_hide_ms > 0.0
+ && self.visible
+ && self.pos.0 >= -100.0
+ && self.idle_secs >= self.motion.idle_hide_ms / 1000.0
+ && self.idle_alpha >= 0.004
+ }
+
+ /// The shared frame-tick predicate: true while the next tick can change
+ /// this cursor's pixels, so the platform render loop must run at frame
+ /// cadence. It covers an in-flight glide, spring settle, click pulse,
+ /// session-badge or semantic-action animation, resting motion
+ /// ([`Self::has_resting_motion`]), and the idle fade. A brand-new sentinel
+ /// cursor, a fully faded cursor, and a reduced-motion cursor waiting out
+ /// its opaque idle-hide delay are quiescent; platforms advance that
+ /// countdown with [`Self::idle_fade_wait`] or their own slow heartbeat.
+ pub fn needs_frame_tick(&self) -> bool {
+ self.path.is_some()
+ || self.spring.is_some()
+ || self.click_t.is_some()
+ || self.session_badge_needs_frame_tick()
+ || self.has_resting_motion()
+ || self.idle_fade_in_progress()
+ }
+
+ /// Time until the idle fade starts for a placed, visible, settled cursor,
+ /// so a parked render loop can wake exactly when pixels begin to change.
+ /// `None` when idle hide is off, the cursor is moving or not shown, or
+ /// the fade has already started.
+ pub fn idle_fade_wait(&self) -> Option<std::time::Duration> {
+ if !self.visible
+ || self.pos.0 < -100.0
+ || self.motion.idle_hide_ms <= 0.0
+ || self.path.is_some()
+ || self.spring.is_some()
+ || self.click_t.is_some()
+ {
+ return None;
+ }
+ let remaining = self.motion.idle_hide_ms / 1000.0 - self.idle_secs;
+ (remaining.is_finite() && remaining > 0.0)
+ .then(|| std::time::Duration::from_secs_f64(remaining))
+ }
+
fn reveal_session_badge(&mut self) {
if self.session_label.is_some() {
self.session_badge_secs = 0.0;
@@ -191,12 +273,12 @@ impl RenderStateCore {
}
pub fn session_badge_is_visible(&self) -> bool {
- self.cursor_is_revealed()
+ self.is_revealed()
&& (self.session_badge_alpha() > 0.001 || self.session_badge_chip_alpha() > 0.001)
}
pub fn session_badge_needs_frame_tick(&self) -> bool {
- self.cursor_is_revealed()
+ self.is_revealed()
&& ((self.session_label.is_some()
&& self.session_badge_secs < SESSION_BADGE_HOLD_SECS + SESSION_BADGE_FADE_SECS)
|| self.badge_modifier_fade_secs.is_some()
@@ -208,7 +290,7 @@ impl RenderStateCore {
/// from [`Self::session_badge_needs_frame_tick`]: a faded badge needs hover
/// hit-testing, not continuous 60 fps repainting.
pub fn session_badge_needs_hover_poll(&self) -> bool {
- self.session_label.is_some() && self.cursor_is_revealed()
+ self.session_label.is_some() && self.is_revealed()
}
/// Update hover state from a platform-native hardware pointer sample.
@@ -561,7 +643,7 @@ impl RenderStateCore {
y,
end_heading_radians,
} => {
- let reveal_badge = !self.cursor_is_revealed();
+ let reveal_badge = !self.is_revealed();
// Apply click offset (16 pt along end_heading) before planning,
// matching Swift `moveTo(point:endAngleRadians:)`:
// tx = clickPoint.x + cos(endAngle) * clickOffset
@@ -605,7 +687,7 @@ impl RenderStateCore {
y,
heading_radians,
} => {
- let reveal_badge = !self.cursor_is_revealed();
+ let reveal_badge = !self.is_revealed();
self.pos = (x, y);
if let Some(heading) = heading_radians {
self.heading = heading;
@@ -630,7 +712,7 @@ impl RenderStateCore {
true
}
OverlayCommand::ClickPulse { x, y } => {
- let reveal_badge = !self.cursor_is_revealed();
+ let reveal_badge = !self.is_revealed();
if click_pulse_sentinel_only {
// macOS: only snap position on first placement (sentinel state).
// After that the cursor stays where the animation landed.
@@ -1012,7 +1094,7 @@ mod session_badge_and_action_tests {
core.tick_motion(2.0);
- assert!(core.cursor_is_revealed());
+ assert!(core.is_revealed());
assert_eq!(core.pos, (40.0, 60.0));
assert_eq!(core.idle_alpha, 1.0);
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs b/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
index b7d4296ec4..8d8ba00d29 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
@@ -35,9 +35,9 @@
//! What stays here is the X11 window plumbing: connection setup,
//! override-redirect visual, ShapeInput passthrough, and the XPutImage paint.
+use std::collections::HashMap;
#[cfg(target_os = "linux")]
use std::collections::VecDeque;
-use std::collections::{HashMap, HashSet};
use std::sync::{Mutex, OnceLock};
#[cfg(target_os = "linux")]
use std::time::{Duration, Instant};
@@ -55,7 +55,8 @@ const X11_COMPOSITOR_POLL_INTERVAL: Duration = Duration::from_secs(1);
#[cfg(target_os = "linux")]
use cursor_overlay::ZOrderEnforcer;
use cursor_overlay::{
- CursorConfig, CursorKey, KeyedOverlayCommand, OverlayCommand, OverlayMsg, RenderStateCore,
+ CursorConfig, CursorKey, KeyedOverlayCommand, MsgOutcome, OverlayCommand, OverlayMsg,
+ RenderEntry, RenderStateCore, ScreenFrame,
};
// ── Global channel ────────────────────────────────────────────────────────
@@ -211,59 +212,24 @@ fn disable_render_map(render: &mut Option<RenderMap>) {
*render = None;
}
-struct RenderMap {
- cursors: HashMap<CursorKey, RenderState>,
+/// X11 root geometry kept beside the shared keyed render map
+/// ([`cursor_overlay::RenderMap`], which owns the per-session lifecycle and the
+/// frame-tick predicate).
+struct X11Screen {
scr_w: u32,
scr_h: u32,
- template: CursorConfig,
- ended: HashSet<CursorKey>,
- last_active: Option<CursorKey>,
}
-fn render_state_for_key(template: &CursorConfig, key: &str) -> RenderState {
- let mut config = template.clone();
- config.cursor_id = key.to_owned();
- RenderState::new(config)
-}
+type RenderMap = cursor_overlay::RenderMap<RenderState, X11Screen>;
+/// Drain one message into the shared map, releasing a removed session's
+/// arrival waiter. Returns the commanded key (also the map's `last_active`).
fn apply_msg(map: &mut RenderMap, msg: OverlayMsg) -> Option<CursorKey> {
- match msg {
- OverlayMsg::Remove(key) => {
- if key != "default" {
- map.cursors.remove(&key);
- if let Ok(mut guard) = ARRIVAL_TX.lock() {
- if let Some(arrivals) = guard.as_mut() {
- arrivals.remove(&key);
- }
- }
- if map.last_active.as_deref() == Some(key.as_str()) {
- map.last_active = None;
- }
- map.ended.insert(key);
- }
- None
- }
- OverlayMsg::Revive(key) => {
- if key != "default" {
- map.ended.remove(&key);
- }
- None
- }
- OverlayMsg::Cmd(KeyedOverlayCommand { key, cmd }) => {
- if map.ended.contains(&key) {
- tracing::debug!(key = %key, cmd = ?cmd, "overlay: command dropped — key was ended");
- return None;
- }
- let template = map.template.clone();
- let k = key.clone();
- let rs = map
- .cursors
- .entry(key)
- .or_insert_with(|| render_state_for_key(&template, &k));
- rs.apply_command(cmd);
- Some(k)
- }
+ let outcome = map.apply_msg(msg);
+ if let MsgOutcome::Removed { key, .. } = &outcome {
+ arrival_cancel(key);
}
+ outcome.applied_key().cloned()
}
pub fn init(cfg: CursorConfig) {
@@ -275,16 +241,13 @@ pub fn init(cfg: CursorConfig) {
.expect("cursor overlay sender is initialized exactly once");
*CMD_RX_CELL.lock().unwrap() = Some(rx);
*ARRIVAL_TX.lock().unwrap() = Some(HashMap::new());
- let mut cursors = HashMap::new();
- cursors.insert("default".to_owned(), RenderState::new(cfg.clone()));
- *RENDER.lock().unwrap() = Some(RenderMap {
- cursors,
- scr_w: 1920,
- scr_h: 1080,
- template: cfg,
- ended: HashSet::new(),
- last_active: None,
- });
+ *RENDER.lock().unwrap() = Some(RenderMap::new(
+ cfg,
+ X11Screen {
+ scr_w: 1920,
+ scr_h: 1080,
+ },
+ ));
});
cua_driver_core::cursor_events::install_cursor_event_sink(std::sync::Arc::new(
|event: cua_driver_core::cursor_events::CursorEvent| {
@@ -435,12 +398,8 @@ pub fn is_enabled_for(key: &str) -> bool {
.lock()
.ok()
.and_then(|g| {
- g.as_ref().and_then(|m| {
- m.cursors
- .get(key)
- .or_else(|| m.cursors.get("default"))
- .map(|rs| rs.core.visible)
- })
+ g.as_ref()
+ .and_then(|m| m.cursor_or_default(key).map(|rs| rs.core.visible))
})
.unwrap_or(false)
}
@@ -487,9 +446,7 @@ pub fn current_motion_for(key: &str) -> cursor_overlay::MotionConfig {
.ok()
.and_then(|guard| {
guard.as_ref().and_then(|map| {
- map.cursors
- .get(key)
- .or_else(|| map.cursors.get("default"))
+ map.cursor_or_default(key)
.map(|state| state.core.motion.clone())
})
})
@@ -507,42 +464,23 @@ pub fn current_theme_state_for(
)> {
let guard = RENDER.lock().ok()?;
let map = guard.as_ref()?;
- let state = map
- .cursors
- .get(key)
- .or_else(|| map.cursors.get("default"))?;
+ let state = map.cursor_or_default(key)?;
let (id, version, profile, fallback) = state.core.active_theme_metadata();
Some((id, version, profile, fallback, state.core.visual.clone()))
}
fn seed_start_if_sentinel(key: &CursorKey, target_x: f64, target_y: f64) -> bool {
- const SEED_OFFSET: f64 = 140.0;
let mut guard = RENDER.lock().unwrap();
let Some(map) = guard.as_mut() else {
return false;
};
- if map.ended.contains(key) {
- return false;
- }
- let template = map.template.clone();
- let k = key.clone();
- let rs = map
- .cursors
- .entry(key.clone())
- .or_insert_with(|| render_state_for_key(&template, &k));
- if !(rs.core.cfg.enabled && rs.core.pos.0 < -50.0) {
- return false;
- }
- let max_x = map.scr_w.max(2) as f64 - 2.0;
- let max_y = map.scr_h.max(2) as f64 - 2.0;
- let mut sx = (target_x - SEED_OFFSET).clamp(2.0, max_x);
- let mut sy = (target_y - SEED_OFFSET).clamp(2.0, max_y);
- if (sx - target_x).abs() < 8.0 && (sy - target_y).abs() < 8.0 {
- sx = (target_x + SEED_OFFSET).clamp(2.0, max_x);
- sy = (target_y + SEED_OFFSET).clamp(2.0, max_y);
- }
- rs.core.pos = (sx, sy);
- true
+ let frame = ScreenFrame::new(
+ 0.0,
+ 0.0,
+ f64::from(map.platform.scr_w),
+ f64::from(map.platform.scr_h),
+ );
+ map.seed_start_if_sentinel(key, target_x, target_y, Some(frame))
}
pub async fn animate_cursor_to(x: f64, y: f64) {
@@ -703,78 +641,40 @@ struct RenderState {
core: RenderStateCore,
}
-impl RenderState {
- fn new(cfg: CursorConfig) -> Self {
+impl RenderEntry for RenderState {
+ fn from_config(cfg: CursorConfig) -> Self {
RenderState {
core: RenderStateCore::new(cfg),
}
}
- fn tick(&mut self, dt: f64) -> bool {
- self.core.tick_motion(dt)
+ fn core(&self) -> &RenderStateCore {
+ &self.core
}
- fn apply_command(&mut self, cmd: OverlayCommand) {
+ fn core_mut(&mut self) -> &mut RenderStateCore {
+ &mut self.core
+ }
+
+ fn apply_command(&mut self, cmd: OverlayCommand) -> bool {
// Linux uses the non-sentinel-snap behaviour for both MoveTo and
// ClickPulse: every command updates `self.pos` unconditionally.
// Custom-shape / gradient / focus-rect commands are not rendered on
// Linux at present; `apply_command_base` consumes SetShape +
// SetGradient and returns false for ShowFocusRect — both cases drop
// the visual update silently so callers don't see an error.
- let _ = self.core.apply_command_base(cmd, false, false);
- }
-
- /// True while the render loop must wake at frame cadence because the next
- /// tick can change pixels. A brand-new sentinel cursor is deliberately
- /// quiescent, so an idle MCP server can park on bounded maintenance waits
- /// instead of rebuilding and repainting X11 cursor tiles at 60 fps.
- #[cfg(target_os = "linux")]
- fn needs_frame_tick(&self) -> bool {
- let fade_start = self.core.motion.idle_hide_ms / 1000.0;
- self.core.path.is_some()
- || self.core.spring.is_some()
- || self.core.click_t.is_some()
- || self.core.session_badge_needs_frame_tick()
- // The resting float bob (`shared_float_motion`) is part of the
- // cursor's visual identity, not a transient animation: it runs
- // whenever the cursor is on screen and reduced motion is off, so
- // a settled cursor must keep receiving frames or the bob freezes
- // mid-swing on Linux while macOS keeps levitating. The term dies
- // with `idle_alpha` once the idle fade completes, returning the
- // parked-overlay fast path to the fully hidden cursor.
- || (self.core.visible
- && self.core.pos.0 >= -100.0
- && self.core.idle_alpha >= 0.004
- && self.core.visual.reduced_motion != cursor_overlay::ReducedMotion::On)
- || (self.core.motion.idle_hide_ms > 0.0
- && self.core.visible
- && self.core.pos.0 >= -100.0
- && self.core.idle_secs >= fade_start
- && self.core.idle_alpha >= 0.004)
+ self.core.apply_command_base(cmd, false, false)
}
-}
-#[cfg(target_os = "linux")]
-fn render_map_needs_frame_tick(map: &RenderMap) -> bool {
- map.cursors.values().any(RenderState::needs_frame_tick)
+ // `tick` and `needs_frame_tick` use the shared defaults. A brand-new
+ // sentinel cursor is quiescent, so an idle MCP server parks on bounded
+ // maintenance waits instead of repainting X11 cursor tiles at 60 fps,
+ // while a revealed cursor with resting motion keeps its float bob alive.
}
#[cfg(target_os = "linux")]
fn render_map_needs_z_order_tick(map: &RenderMap) -> bool {
- map.cursors
- .values()
- .any(|rs| rs.core.visible && rs.core.idle_alpha >= 0.004 && rs.core.pos.0 >= -100.0)
-}
-
-#[cfg(target_os = "linux")]
-fn tick_render_map(map: &mut RenderMap, dt: f64) -> Vec<CursorKey> {
- let mut arrived = Vec::new();
- for (key, rs) in map.cursors.iter_mut() {
- if rs.tick(dt) {
- arrived.push(key.clone());
- }
- }
- arrived
+ map.cursors.values().any(|rs| rs.core.is_revealed())
}
#[cfg(target_os = "linux")]
@@ -788,20 +688,16 @@ fn apply_messages_after_wake(
// mutate it. This preserves each cursor's independent idle clock while
// ensuring newly commanded animations render their initial frame at dt=0.
let arrived = parked_elapsed
- .map(|dt| tick_render_map(map, dt))
+ .map(|dt| map.tick_all(dt))
.unwrap_or_default();
let mut had_msg = false;
if let Some(msg) = first_msg {
had_msg = true;
- if let Some(key) = apply_msg(map, msg) {
- map.last_active = Some(key);
- }
+ apply_msg(map, msg);
}
while let Ok(msg) = rx.try_recv() {
had_msg = true;
- if let Some(key) = apply_msg(map, msg) {
- map.last_active = Some(key);
- }
+ apply_msg(map, msg);
}
(arrived, had_msg)
}
@@ -824,33 +720,11 @@ fn process_render_wake(
let (mut arrived, had_msg) =
apply_messages_after_wake(map, first_msg, rx, parked_wake.then_some(elapsed_dt));
if !parked_wake && (frame_tick_needed || had_msg) {
- arrived.extend(tick_render_map(map, elapsed_dt.min(0.05)));
+ arrived.extend(map.tick_all(elapsed_dt.min(0.05)));
}
(arrived, had_msg)
}
-#[cfg(target_os = "linux")]
-fn render_map_idle_wait_interval(map: &RenderMap) -> Option<Duration> {
- map.cursors
- .values()
- .filter_map(|rs| {
- let core = &rs.core;
- if !core.visible
- || core.pos.0 < -100.0
- || core.motion.idle_hide_ms <= 0.0
- || core.path.is_some()
- || core.spring.is_some()
- || core.click_t.is_some()
- {
- return None;
- }
-
- let remaining = core.motion.idle_hide_ms / 1000.0 - core.idle_secs;
- (remaining.is_finite() && remaining > 0.0).then(|| Duration::from_secs_f64(remaining))
- })
- .min()
-}
-
#[cfg(target_os = "linux")]
fn next_maintenance_deadline(
last_tick: Instant,
@@ -959,8 +833,8 @@ fn classify_x11_overlay_event(
#[cfg(target_os = "linux")]
fn update_render_map_geometry(map: &mut RenderMap, width: u16, height: u16) {
- map.scr_w = u32::from(width);
- map.scr_h = u32::from(height);
+ map.platform.scr_w = u32::from(width);
+ map.platform.scr_h = u32::from(height);
}
#[cfg(target_os = "linux")]
@@ -1140,8 +1014,8 @@ fn run_overlay_thread(cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayMs
{
let mut guard = RENDER.lock().unwrap();
if let Some(map) = guard.as_mut() {
- map.scr_w = scr_w;
- map.scr_h = scr_h;
+ map.platform.scr_w = scr_w;
+ map.platform.scr_h = scr_h;
}
}
@@ -1436,9 +1310,9 @@ fn run_overlay_thread(cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayMs
.as_ref()
.and_then(|key| map.cursors.get(key))
.and_then(|rs| rs.core.pinned_wid);
- let next_frame_tick_needed = render_map_needs_frame_tick(map);
+ let next_frame_tick_needed = map.needs_frame_tick();
let next_z_order_tick_needed = render_map_needs_z_order_tick(map);
- let next_idle_wait_interval = render_map_idle_wait_interval(map);
+ let next_idle_wait_interval = map.idle_fade_wait();
(
arrived,
pinned_wid,
@@ -2197,7 +2071,7 @@ fn cursor_tile_bounds(
fn render_x11_tiles(map: &RenderMap) -> Vec<X11PaintTile> {
let mut bounds = Vec::new();
for rs in map.cursors.values() {
- if let Some(tile) = cursor_tile_bounds(&rs.core, map.scr_w, map.scr_h) {
+ if let Some(tile) = cursor_tile_bounds(&rs.core, map.platform.scr_w, map.platform.scr_h) {
if !bounds.contains(&tile) {
bounds.push(tile);
}
@@ -3218,50 +3092,18 @@ mod tests {
Ok(())
}
- #[test]
- fn keyed_render_state_carries_the_session_color_identity() {
- let state = render_state_for_key(&CursorConfig::default(), "session-blueprint");
- assert_eq!(state.core.cfg.cursor_id, "session-blueprint");
- }
-
+ // The keyed lifecycle (ownership, tombstones, revival, default guard,
+ // z-order), the sentinel seed, and the shared frame-tick predicate are
+ // covered once in `cursor_overlay::render_map`. The tests below cover the
+ // X11 adapter: its scheduler, z-order heartbeat, errors, and tiles.
fn default_render_map() -> RenderMap {
- let cfg = CursorConfig::default();
- let mut cursors = HashMap::new();
- cursors.insert("default".to_owned(), RenderState::new(cfg.clone()));
- RenderMap {
- cursors,
- scr_w: 100,
- scr_h: 100,
- template: cfg,
- ended: HashSet::new(),
- last_active: None,
- }
- }
-
- #[test]
- fn explicit_revival_clears_tombstone_and_recreates_lazily() {
- let move_msg = |x, y| {
- OverlayMsg::Cmd(KeyedOverlayCommand {
- key: "sessA".to_owned(),
- cmd: OverlayCommand::MoveTo {
- x,
- y,
- end_heading_radians: 0.0,
- },
- })
- };
- let mut map = default_render_map();
- apply_msg(&mut map, move_msg(10.0, 10.0));
- apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));
- assert!(apply_msg(&mut map, move_msg(20.0, 20.0)).is_none());
-
- apply_msg(&mut map, OverlayMsg::Revive("sessA".to_owned()));
- assert!(!map.cursors.contains_key("sessA"));
- assert!(!map.ended.contains("sessA"));
-
- let resolved = apply_msg(&mut map, move_msg(30.0, 30.0));
- assert_eq!(resolved.as_deref(), Some("sessA"));
- assert!(map.cursors.contains_key("sessA"));
+ RenderMap::new(
+ CursorConfig::default(),
+ X11Screen {
+ scr_w: 100,
+ scr_h: 100,
+ },
+ )
}
fn test_message() -> OverlayMsg {
@@ -3272,24 +3114,26 @@ mod tests {
}
#[test]
- fn session_removal_drops_the_cursor_and_rejects_late_commands() {
+ fn session_removal_releases_that_arrival_waiter() {
+ let (arrival_tx, mut arrival_rx) = tokio::sync::oneshot::channel();
+ arrival_register("session-removal-waiter".to_owned(), arrival_tx);
let mut map = default_render_map();
- let command = || {
+ apply_msg(
+ &mut map,
OverlayMsg::Cmd(KeyedOverlayCommand {
- key: "session-a".to_owned(),
+ key: "session-removal-waiter".to_owned(),
cmd: OverlayCommand::ClickPulse { x: 12.0, y: 34.0 },
- })
- };
-
- assert_eq!(apply_msg(&mut map, command()).as_deref(), Some("session-a"));
- assert!(map.cursors.contains_key("session-a"));
-
- assert!(apply_msg(&mut map, OverlayMsg::Remove("session-a".to_owned())).is_none());
- assert!(!map.cursors.contains_key("session-a"));
- assert!(map.ended.contains("session-a"));
-
- assert!(apply_msg(&mut map, command()).is_none());
- assert!(!map.cursors.contains_key("session-a"));
+ }),
+ );
+ assert!(apply_msg(
+ &mut map,
+ OverlayMsg::Remove("session-removal-waiter".to_owned())
+ )
+ .is_none());
+ assert!(matches!(
+ arrival_rx.try_recv(),
+ Err(tokio::sync::oneshot::error::TryRecvError::Closed)
+ ));
}
#[test]
@@ -3345,11 +3189,7 @@ mod tests {
{
let mut guard = RENDER.lock().unwrap();
let map = guard.get_or_insert_with(default_render_map);
- let template = map.template.clone();
- let rs = map
- .cursors
- .entry(key.clone())
- .or_insert_with(|| render_state_for_key(&template, &key));
+ let rs = map.cursor_mut(&key).unwrap();
rs.core.cfg.enabled = true;
rs.core.visible = true;
rs.core.pos = (10.0, 10.0);
@@ -3612,43 +3452,23 @@ mod tests {
#[test]
fn geometry_shrink_reclips_cursor_tiles() {
let mut map = default_render_map();
- map.scr_w = 1920;
- map.scr_h = 2160;
+ map.platform.scr_w = 1920;
+ map.platform.scr_h = 2160;
map.cursors.get_mut("default").unwrap().core.pos = (100.0, 2000.0);
assert_eq!(render_x11_tiles(&map).len(), 1);
update_render_map_geometry(&mut map, 1920, 1080);
- assert_eq!((map.scr_w, map.scr_h), (1920, 1080));
+ assert_eq!((map.platform.scr_w, map.platform.scr_h), (1920, 1080));
assert!(render_x11_tiles(&map).is_empty());
}
#[test]
fn sentinel_default_cursor_does_not_require_frame_ticks() {
let map = default_render_map();
- assert!(!render_map_needs_frame_tick(&map));
+ assert!(!map.needs_frame_tick());
assert!(!render_map_needs_z_order_tick(&map));
}
- // The idle-park contract applies to reduced-motion sessions: with the
- // float bob active (the default), a visible cursor keeps ticking so it
- // levitates at rest, and only a hidden or reduced-motion cursor parks.
- #[test]
- fn resting_visible_cursor_keeps_ticking_for_the_float_bob() {
- let mut map = default_render_map();
- let cursor = map.cursors.get_mut("default").unwrap();
- cursor.core.pos = (100.0, 100.0);
- cursor.core.motion.idle_hide_ms = 0.0;
-
- // Default reduced_motion (auto) floats, so frames keep flowing while
- // the cursor is visible…
- assert!(render_map_needs_frame_tick(&map));
-
- // …and stop once the idle fade has fully hidden it.
- let cursor = map.cursors.get_mut("default").unwrap();
- cursor.core.idle_alpha = 0.0;
- assert!(!render_map_needs_frame_tick(&map));
- }
-
#[test]
fn disabling_settled_cursor_clears_once_then_parks() {
let mut map = default_render_map();
@@ -3658,7 +3478,7 @@ mod tests {
cursor.core.visual.reduced_motion = cursor_overlay::ReducedMotion::On;
let (_tx, rx) = std::sync::mpsc::channel();
- assert!(!render_map_needs_frame_tick(&map));
+ assert!(!map.needs_frame_tick());
assert!(render_map_needs_z_order_tick(&map));
let (arrived, had_msg) = process_render_wake(
@@ -3678,22 +3498,10 @@ mod tests {
// one final transparent frame before both scheduler paths park.
assert!(had_msg);
assert!(!map.cursors["default"].core.visible);
- assert!(!render_map_needs_frame_tick(&map));
+ assert!(!map.needs_frame_tick());
assert!(!render_map_needs_z_order_tick(&map));
}
- #[test]
- fn active_cursor_requires_frame_ticks() {
- let mut map = default_render_map();
- let cursor = map.cursors.get_mut("default").unwrap();
- cursor.apply_command(OverlayCommand::MoveTo {
- x: 250.0,
- y: 150.0,
- end_heading_radians: 0.0,
- });
- assert!(render_map_needs_frame_tick(&map));
- }
-
#[test]
fn completed_move_parks_during_opaque_idle_delay() {
let mut map = default_render_map();
@@ -3727,7 +3535,7 @@ mod tests {
cursor.core.pos,
);
assert_eq!(cursor.core.idle_alpha, 1.0);
- assert!(!render_map_needs_frame_tick(&map));
+ assert!(!map.needs_frame_tick());
assert!(render_map_needs_z_order_tick(&map));
}
@@ -3739,7 +3547,7 @@ mod tests {
cursor.core.pos = (10.0, 10.0);
cursor.core.motion.idle_hide_ms = 500.0;
}
- let other = render_state_for_key(&map.template, "other");
+ let other = map.state_for_key("other");
map.cursors.insert("other".to_owned(), other);
let (_tx, rx) = std::sync::mpsc::channel();
@@ -3779,7 +3587,7 @@ mod tests {
cursor.core.pos = (10.0, 10.0);
cursor.core.motion.idle_hide_ms = 500.0;
}
- let mut other = render_state_for_key(&map.template, "other");
+ let mut other = map.state_for_key("other");
other.core.pos = (20.0, 20.0);
map.cursors.insert("other".to_owned(), other);
@@ -3887,7 +3695,7 @@ mod tests {
// Shorten the final maintenance wait to the exact fade deadline rather
// than overshooting by another 80 ms and jumping the first alpha frame.
- let deadline_wait = render_map_idle_wait_interval(&map).unwrap();
+ let deadline_wait = map.idle_fade_wait().unwrap();
assert!(deadline_wait >= Duration::from_millis(19));
assert!(deadline_wait <= Duration::from_millis(21));
@@ -3908,35 +3716,15 @@ mod tests {
assert!(!cursor.needs_frame_tick());
assert_eq!(cursor.core.idle_alpha, 0.0);
- assert!(!render_map_needs_frame_tick(&map));
+ assert!(!map.needs_frame_tick());
assert!(!render_map_needs_z_order_tick(&map));
}
- #[test]
- fn completed_click_pulse_returns_to_quiescence() {
- let mut map = default_render_map();
- let cursor = map.cursors.get_mut("default").unwrap();
- cursor.core.motion.idle_hide_ms = 0.0;
- cursor.core.visual.reduced_motion = cursor_overlay::ReducedMotion::On;
- cursor.apply_command(OverlayCommand::ClickPulse { x: 20.0, y: 30.0 });
- assert!(cursor.needs_frame_tick());
-
- for _ in 0..600 {
- cursor.tick(1.0 / 60.0);
- if !cursor.needs_frame_tick() {
- break;
- }
- }
-
- assert!(!cursor.needs_frame_tick());
- assert!(!render_map_needs_frame_tick(&map));
- }
-
#[test]
fn active_cursor_rendering_is_bounded_by_tile_not_root_size() {
let mut map = default_render_map();
- map.scr_w = 7680;
- map.scr_h = 2160;
+ map.platform.scr_w = 7680;
+ map.platform.scr_h = 2160;
let cursor = map.cursors.get_mut("default").unwrap();
cursor.core.pos = (4000.0, 1000.0);
@@ -3947,14 +3735,14 @@ mod tests {
assert_eq!(tile.bounds.width, 128);
assert_eq!(tile.bounds.height, 128);
assert_eq!(tile.pixmap.data().len(), 128 * 128 * 4);
- assert!(tile.pixmap.data().len() < (map.scr_w * map.scr_h * 4) as usize);
+ assert!(tile.pixmap.data().len() < (map.platform.scr_w * map.platform.scr_h * 4) as usize);
}
#[test]
fn session_badge_expands_only_the_local_cursor_tile() {
let mut map = default_render_map();
- map.scr_w = 7680;
- map.scr_h = 2160;
+ map.platform.scr_w = 7680;
+ map.platform.scr_h = 2160;
let cursor = map.cursors.get_mut("default").unwrap();
cursor.core.pos = (4000.0, 1000.0);
cursor.apply_command(OverlayCommand::SetSessionLabel("research-run".to_owned()));
@@ -3964,14 +3752,16 @@ mod tests {
assert_eq!(tiles.len(), 1);
assert_eq!(tiles[0].bounds.width, 208);
assert_eq!(tiles[0].bounds.height, 128);
- assert!(tiles[0].pixmap.data().len() < (map.scr_w * map.scr_h * 4) as usize);
+ assert!(
+ tiles[0].pixmap.data().len() < (map.platform.scr_w * map.platform.scr_h * 4) as usize
+ );
}
#[test]
fn modifier_only_badge_expands_the_local_cursor_tile() {
let mut map = default_render_map();
- map.scr_w = 7680;
- map.scr_h = 2160;
+ map.platform.scr_w = 7680;
+ map.platform.scr_h = 2160;
let cursor = map.cursors.get_mut("default").unwrap();
cursor.core.pos = (4000.0, 1000.0);
cursor.apply_command(OverlayCommand::BeginAction {
@@ -3990,8 +3780,8 @@ mod tests {
#[test]
fn cursor_tiles_clip_at_screen_edges_and_skip_hidden_cursors() {
let mut map = default_render_map();
- map.scr_w = 1920;
- map.scr_h = 1080;
+ map.platform.scr_w = 1920;
+ map.platform.scr_h = 1080;
let cursor = map.cursors.get_mut("default").unwrap();
cursor.core.pos = (10.0, 12.0);
@@ -4014,10 +3804,10 @@ mod tests {
#[test]
fn distant_cursors_use_independent_small_tiles() {
let mut map = default_render_map();
- map.scr_w = 7680;
- map.scr_h = 2160;
+ map.platform.scr_w = 7680;
+ map.platform.scr_h = 2160;
map.cursors.get_mut("default").unwrap().core.pos = (100.0, 100.0);
- let mut other = render_state_for_key(&map.template, "other");
+ let mut other = map.state_for_key("other");
other.core.pos = (7400.0, 1800.0);
map.cursors.insert("other".to_owned(), other);
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs
index c271faab8e..c900542748 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/overlay.rs
@@ -26,7 +26,10 @@ use std::thread;
use std::time::{Duration, Instant};
use crossbeam_channel::{bounded, Receiver, Sender};
-use cursor_overlay::{CursorConfig, CursorKey, OverlayCommand, OverlayMsg, RenderStateCore};
+use cursor_overlay::{
+ CursorConfig, CursorKey, CursorMap, MsgOutcome, OverlayCommand, OverlayMsg, RenderStateCore,
+ ScreenFrame,
+};
use wayland_client::{
globals::{registry_queue_init, GlobalListContents},
protocol::{
@@ -198,12 +201,11 @@ struct OverlayState {
/// recurring full-output SHM redraws.
initialized_outputs: HashSet<u32>,
topology_dirty: bool,
- /// Keyed render cores mirror the X11 native overlay contract. Removing a
- /// named key records it in `ended`, so already-queued late commands cannot
- /// recreate a cursor after end_session.
- cores: HashMap<CursorKey, RenderStateCore>,
- template: CursorConfig,
- ended: HashSet<CursorKey>,
+ /// The shared keyed render map (`cursor_overlay::RenderMap`) gives this
+ /// backend the same lifecycle as every other platform: removing a named
+ /// key tombstones it, so already-queued late commands cannot recreate a
+ /// cursor after end_session.
+ render: WlRenderMap,
/// In-flight wl_shm buffers awaiting `wl_buffer.release` from the
/// compositor. Keyed by `WlBuffer` object id; value is the
/// `(mmap ptr, mmap size, memfd fd)` triple that must be unmapped +
@@ -332,10 +334,6 @@ impl Drop for OverlayState {
impl OverlayState {
fn new(template: CursorConfig) -> Self {
- let mut cores = HashMap::new();
- // Match the X11 contract: the compatibility/default slot preserves the
- // launch-time cursor id, while lazily-created named slots override it.
- cores.insert("default".to_owned(), RenderStateCore::new(template.clone()));
Self {
compositor: None,
shm: None,
@@ -345,37 +343,25 @@ impl OverlayState {
painted_outputs: HashSet::new(),
initialized_outputs: HashSet::new(),
topology_dirty: false,
- cores,
- template,
- ended: HashSet::new(),
+ // The default slot preserves the launch-time cursor id, while
+ // lazily-created named slots take their key as the id.
+ render: WlRenderMap::new(template, ()),
pending_buffers: HashMap::new(),
}
}
}
-fn render_core_for_key(template: &CursorConfig, key: &str) -> RenderStateCore {
- let mut config = template.clone();
- config.cursor_id = key.to_owned();
- RenderStateCore::new(config)
-}
+type WlRenderMap = cursor_overlay::RenderMap<RenderStateCore>;
+/// Apply one keyed command. A never-shown cursor is first seeded near its
+/// target (clamped into `frame`, the union of the configured outputs) so a
+/// spring animation begins on screen, as on every other platform.
fn apply_keyed_command(
- cores: &mut HashMap<CursorKey, RenderStateCore>,
- template: &CursorConfig,
- ended: &HashSet<CursorKey>,
+ render: &mut WlRenderMap,
+ frame: Option<ScreenFrame>,
key: CursorKey,
cmd: OverlayCommand,
) -> bool {
- if ended.contains(&key) {
- tracing::debug!(key = %key, cmd = ?cmd, "wayland overlay: command dropped — key was ended");
- return false;
- }
-
- let core = cores
- .entry(key.clone())
- .or_insert_with(|| render_core_for_key(template, &key));
- // Seed from the off-screen sentinel near the first targeted action so a
- // spring animation begins on-screen. This mirrors the X11 renderer.
let seed_target = match &cmd {
OverlayCommand::MoveTo { x, y, .. }
| OverlayCommand::SnapTo { x, y, .. }
@@ -383,40 +369,44 @@ fn apply_keyed_command(
_ => None,
};
if let Some((target_x, target_y)) = seed_target {
- if core.pos.0 < -50.0 {
- const SEED_OFFSET: f64 = 140.0;
- core.pos = (
- (target_x - SEED_OFFSET).max(2.0),
- (target_y - SEED_OFFSET).max(2.0),
- );
- }
+ render.seed_start_if_sentinel(&key, target_x, target_y, frame);
}
let disabling = matches!(&cmd, OverlayCommand::SetEnabled(false));
- let dirty = core.apply_command_base(cmd, false, false);
+ let outcome = render.apply_command(key, cmd);
if disabling {
- quiesce_hidden(core);
+ if let Some(key) = outcome.applied_key() {
+ if let Some(core) = render.cursors.get_mut(key) {
+ quiesce_hidden(core);
+ }
+ }
}
- dirty
+ outcome.is_dirty()
}
-fn remove_keyed_core(
- cores: &mut HashMap<CursorKey, RenderStateCore>,
- ended: &mut HashSet<CursorKey>,
- key: CursorKey,
-) -> bool {
- if key == "default" {
- return false;
- }
- let removed = cores.remove(&key).is_some();
- ended.insert(key);
- removed
+fn remove_keyed_core(render: &mut WlRenderMap, key: CursorKey) -> bool {
+ matches!(
+ render.remove(key),
+ MsgOutcome::Removed { existed: true, .. }
+ )
}
-fn revive_key(ended: &mut HashSet<CursorKey>, key: CursorKey) {
- if key != "default" {
- ended.remove(&key);
- }
+fn revive_key(render: &mut WlRenderMap, key: CursorKey) {
+ render.revive(key);
+}
+
+/// Bounding frame of every configured output, for seeding.
+fn output_frame(state: &OverlayState) -> Option<ScreenFrame> {
+ ScreenFrame::union(state.outputs.iter().filter_map(|(&id, output)| {
+ output.layout(id).map(|layout| {
+ ScreenFrame::new(
+ f64::from(layout.origin_x),
+ f64::from(layout.origin_y),
+ f64::from(layout.width),
+ f64::from(layout.height),
+ )
+ })
+ }))
}
fn dbg(msg: &str) {
@@ -478,7 +468,7 @@ fn frame_plan(
}
fn visible_cores_for_output<'a>(
- cores: &'a HashMap<CursorKey, RenderStateCore>,
+ cores: &'a CursorMap<RenderStateCore>,
layouts: &[OutputLayout],
output_id: u32,
) -> Vec<(&'a CursorKey, &'a RenderStateCore)> {
@@ -565,10 +555,10 @@ fn wait_for_renderer_command(
match command {
WlOverlayCmd::Shutdown => return None,
WlOverlayCmd::Remove(key) => {
- remove_keyed_core(&mut state.cores, &mut state.ended, key);
+ remove_keyed_core(&mut state.render, key);
}
- WlOverlayCmd::Revive(key) => revive_key(&mut state.ended, key),
- WlOverlayCmd::Cmd { ref key, ref cmd } if !state.ended.contains(key) => {
+ WlOverlayCmd::Revive(key) => revive_key(&mut state.render, key),
+ WlOverlayCmd::Cmd { ref key, ref cmd } if !state.render.ended.contains(key) => {
if matches!(
cmd,
OverlayCommand::MoveTo { .. }
@@ -577,13 +567,7 @@ fn wait_for_renderer_command(
) {
return Some(command);
}
- apply_keyed_command(
- &mut state.cores,
- &state.template,
- &state.ended,
- key.clone(),
- cmd.clone(),
- );
+ apply_keyed_command(&mut state.render, None, key.clone(), cmd.clone());
}
WlOverlayCmd::Cmd { .. } => {}
}
@@ -665,7 +649,11 @@ fn owner_thread(rx: Receiver<WlOverlayCmd>) -> anyhow::Result<()> {
let mut frame_tick_needed = false;
let mut startup_command = Some(first_command);
loop {
- let wait = next_wait(&state.cores, frame_tick_needed, state.topology_dirty);
+ let wait = next_wait(
+ &state.render.cursors,
+ frame_tick_needed,
+ state.topology_dirty,
+ );
let wake = startup_command
.take()
.map(WlWake::Command)
@@ -683,6 +671,7 @@ fn owner_thread(rx: Receiver<WlOverlayCmd>) -> anyhow::Result<()> {
let mut dirty = false;
let mut shutdown = false;
let mut pending = first_cmd;
+ let frame = output_frame(&state);
loop {
let received = pending.take().map(Ok).unwrap_or_else(|| rx.try_recv());
match received {
@@ -691,19 +680,13 @@ fn owner_thread(rx: Receiver<WlOverlayCmd>) -> anyhow::Result<()> {
break;
}
Ok(WlOverlayCmd::Cmd { key, cmd }) => {
- dirty |= apply_keyed_command(
- &mut state.cores,
- &state.template,
- &state.ended,
- key,
- cmd,
- );
+ dirty |= apply_keyed_command(&mut state.render, frame, key, cmd);
}
Ok(WlOverlayCmd::Remove(key)) => {
- dirty |= remove_keyed_core(&mut state.cores, &mut state.ended, key);
+ dirty |= remove_keyed_core(&mut state.render, key);
}
Ok(WlOverlayCmd::Revive(key)) => {
- revive_key(&mut state.ended, key);
+ revive_key(&mut state.render, key);
}
Err(crossbeam_channel::TryRecvError::Empty) => break,
Err(crossbeam_channel::TryRecvError::Disconnected) => {
@@ -722,21 +705,22 @@ fn owner_thread(rx: Receiver<WlOverlayCmd>) -> anyhow::Result<()> {
if let Some(timeout_kind) = timed_out {
match timeout_kind {
WlWait::Frame => {
- tick_all_cores(&mut state.cores, elapsed.min(0.05));
+ tick_all_cores(&mut state.render.cursors, elapsed.min(0.05));
dirty = true;
}
WlWait::Deadline(_) => {
- tick_all_cores(&mut state.cores, elapsed);
+ tick_all_cores(&mut state.render.cursors, elapsed);
dirty = true;
}
WlWait::Maintenance(_) => {
let before: HashMap<CursorKey, f64> = state
- .cores
+ .render
+ .cursors
.iter()
.map(|(key, core)| (key.clone(), core.idle_alpha))
.collect();
- tick_all_cores(&mut state.cores, elapsed);
- dirty |= state.cores.iter().any(|(key, core)| {
+ tick_all_cores(&mut state.render.cursors, elapsed);
+ dirty |= state.render.cursors.iter().any(|(key, core)| {
before
.get(key)
.is_none_or(|alpha| *alpha != core.idle_alpha)
@@ -752,7 +736,7 @@ fn owner_thread(rx: Receiver<WlOverlayCmd>) -> anyhow::Result<()> {
}
}
}
- let next_frame_tick_needed = any_core_needs_frame_tick(&state.cores);
+ let next_frame_tick_needed = any_core_needs_frame_tick(&state.render.cursors);
if dirty || frame_tick_needed || next_frame_tick_needed {
redraw(&mut state, &shm, &qh)?;
// Flush the committed frame and dispatch wl_buffer.release before
@@ -803,7 +787,7 @@ fn wait_for_work(rx: &Receiver<WlOverlayCmd>, wait: WlWait) -> WlWake {
const TOPOLOGY_MAINTENANCE_INTERVAL: Duration = Duration::from_secs(1);
fn next_wait(
- cores: &HashMap<CursorKey, RenderStateCore>,
+ cores: &CursorMap<RenderStateCore>,
frame_tick_needed: bool,
topology_dirty: bool,
) -> WlWait {
@@ -819,46 +803,28 @@ fn next_wait(
}
}
-fn any_core_needs_frame_tick(cores: &HashMap<CursorKey, RenderStateCore>) -> bool {
+fn any_core_needs_frame_tick(cores: &CursorMap<RenderStateCore>) -> bool {
cores.values().any(needs_frame_tick)
}
-fn earliest_idle_fade_wait(cores: &HashMap<CursorKey, RenderStateCore>) -> Option<Duration> {
- cores.values().filter_map(idle_fade_wait).min()
+fn earliest_idle_fade_wait(cores: &CursorMap<RenderStateCore>) -> Option<Duration> {
+ cores
+ .values()
+ .filter_map(RenderStateCore::idle_fade_wait)
+ .min()
}
-fn tick_all_cores(cores: &mut HashMap<CursorKey, RenderStateCore>, dt: f64) {
+fn tick_all_cores(cores: &mut CursorMap<RenderStateCore>, dt: f64) {
for core in cores.values_mut() {
core.tick_motion(dt);
}
}
+/// The shared frame-tick predicate, including resting motion (the float bob),
+/// gated on a shown, placed cursor: a hidden cursor's motion is quiesced by
+/// [`quiesce_hidden`] and never repaints a layer surface.
fn needs_frame_tick(core: &RenderStateCore) -> bool {
- if !core.visible || core.pos.0 < -100.0 {
- return false;
- }
- let fade_start = core.motion.idle_hide_ms / 1000.0;
- core.path.is_some()
- || core.spring.is_some()
- || core.click_t.is_some()
- || core.session_badge_needs_frame_tick()
- || (core.motion.idle_hide_ms > 0.0
- && core.idle_secs >= fade_start
- && core.idle_alpha >= 0.004)
-}
-
-fn idle_fade_wait(core: &RenderStateCore) -> Option<Duration> {
- if !core.visible
- || core.pos.0 < -100.0
- || core.motion.idle_hide_ms <= 0.0
- || core.path.is_some()
- || core.spring.is_some()
- || core.click_t.is_some()
- {
- return None;
- }
- let remaining = core.motion.idle_hide_ms / 1000.0 - core.idle_secs;
- (remaining.is_finite() && remaining > 0.0).then(|| Duration::from_secs_f64(remaining))
+ core.visible && core.pos.0 >= -100.0 && core.needs_frame_tick()
}
fn quiesce_hidden(core: &mut RenderStateCore) {
@@ -893,7 +859,8 @@ fn redraw(
.filter_map(|(&id, output)| output.layout(id))
.collect();
let cursor_positions = state
- .cores
+ .render
+ .cursors
.values()
.filter(|core| core.visible && core.pos.0 >= -100.0 && core.idle_alpha >= 0.004)
.map(|core| core.pos);
@@ -966,7 +933,7 @@ fn redraw_output(
{
// HashMap iteration is intentionally normalized by key so overlapping
// named cursors composite deterministically from frame to frame.
- for (_, core) in visible_cores_for_output(&state.cores, layouts, target.id) {
+ for (_, core) in visible_cores_for_output(&state.render.cursors, layouts, target.id) {
cursor_overlay::paint_cursor(
&mut pm,
core,
@@ -1458,7 +1425,7 @@ mod tests {
];
let mut core = positioned_core();
core.pos = (400.0, 300.0);
- let cores = HashMap::from([("session".to_owned(), core)]);
+ let cores = CursorMap::from([("session".to_owned(), core)]);
assert_eq!(select_output(&layouts, 400.0, 300.0).unwrap().id, 4);
assert_eq!(visible_cores_for_output(&cores, &layouts, 4).len(), 1);
@@ -1564,7 +1531,7 @@ mod tests {
fn fresh_sentinel_overlay_uses_only_topology_maintenance() {
let layouts = three_monitor_layout();
let core = RenderStateCore::new(CursorConfig::default());
- let cores = HashMap::from([("default".to_owned(), core)]);
+ let cores = CursorMap::from([("default".to_owned(), core)]);
assert_eq!(
next_wait(&cores, false, false),
WlWait::Maintenance(TOPOLOGY_MAINTENANCE_INTERVAL)
@@ -1585,10 +1552,11 @@ mod tests {
}
#[test]
- fn stable_visible_overlay_sleeps_until_idle_fade_deadline() {
+ fn stable_reduced_motion_overlay_sleeps_until_idle_fade_deadline() {
let mut core = positioned_core();
+ core.visual.reduced_motion = cursor_overlay::ReducedMotion::On;
core.idle_secs = 0.25;
- let cores = HashMap::from([("cursor-a".to_owned(), core)]);
+ let cores = CursorMap::from([("cursor-a".to_owned(), core)]);
assert_eq!(
next_wait(&cores, false, false),
WlWait::Deadline(Duration::from_millis(750))
@@ -1596,12 +1564,61 @@ mod tests {
assert!(!any_core_needs_frame_tick(&cores));
}
+ // Before the shared predicate, a settled Wayland cursor slept until its
+ // idle-fade deadline and its resting bob froze mid-swing.
+ #[test]
+ fn stable_visible_overlay_keeps_frame_cadence_for_resting_motion() {
+ let mut core = positioned_core();
+ core.idle_secs = 0.25;
+ assert!(core.has_resting_motion());
+ let mut cores = CursorMap::from([("cursor-a".to_owned(), core)]);
+ assert_eq!(next_wait(&cores, false, false), WlWait::Frame);
+
+ // Hidden cursors never tick, even with resting motion enabled.
+ cores.get_mut("cursor-a").unwrap().visible = false;
+ assert!(!any_core_needs_frame_tick(&cores));
+ }
+
+ // Mirrors the hosted `wayland_overlay_quiesces_and_recovers_after_capture_
+ // and_cursor_activity` certification: a never-hiding cursor rests still,
+ // so the overlay parks on topology maintenance instead of redrawing.
+ #[test]
+ fn never_hiding_resting_overlay_parks_on_maintenance() {
+ let mut core = positioned_core();
+ core.motion.idle_hide_ms = 0.0;
+ let cores = CursorMap::from([("cursor-a".to_owned(), core)]);
+ assert!(!any_core_needs_frame_tick(&cores));
+ assert_eq!(
+ next_wait(&cores, false, false),
+ WlWait::Maintenance(TOPOLOGY_MAINTENANCE_INTERVAL)
+ );
+ }
+
+ #[test]
+ fn first_positioned_command_seeds_inside_the_output_frame() {
+ let mut render = WlRenderMap::new(CursorConfig::default(), ());
+ let frame = Some(ScreenFrame::new(0.0, 0.0, 1920.0, 1080.0));
+ assert!(apply_keyed_command(
+ &mut render,
+ frame,
+ "session-a".to_owned(),
+ OverlayCommand::MoveTo {
+ x: 50.0,
+ y: 50.0,
+ end_heading_radians: 0.0,
+ },
+ ));
+ let core = &render.cursors["session-a"];
+ assert_eq!(core.pos, (2.0, 2.0));
+ assert!(core.path.is_some());
+ }
+
#[test]
fn animation_and_fade_use_frame_cadence() {
let mut core = positioned_core();
core.click_t = Some(0.0);
assert!(needs_frame_tick(&core));
- let mut cores = HashMap::from([("cursor-a".to_owned(), core)]);
+ let mut cores = CursorMap::from([("cursor-a".to_owned(), core)]);
assert_eq!(next_wait(&cores, false, false), WlWait::Frame);
let core = cores.get_mut("cursor-a").unwrap();
@@ -1621,7 +1638,7 @@ mod tests {
assert!(core.click_t.is_none());
assert!(core.path.is_none());
assert!(core.spring.is_none());
- let cores = HashMap::from([("cursor-a".to_owned(), core)]);
+ let cores = CursorMap::from([("cursor-a".to_owned(), core)]);
assert_eq!(
next_wait(&cores, false, false),
WlWait::Maintenance(TOPOLOGY_MAINTENANCE_INTERVAL)
@@ -1672,8 +1689,8 @@ mod tests {
let mut state = OverlayState::new(CursorConfig::default());
assert!(wait_for_renderer_command(&rx, &mut state).is_none());
- assert!(state.ended.contains("session-a"));
- assert!(!state.cores.contains_key("session-a"));
+ assert!(state.render.ended.contains("session-a"));
+ assert!(!state.render.cursors.contains_key("session-a"));
assert!(state.outputs.is_empty());
}
@@ -1741,7 +1758,7 @@ mod tests {
..
})
));
- let core = state.cores.get("session-a").unwrap();
+ let core = state.render.cursors.get("session-a").unwrap();
assert_eq!(core.session_label.as_deref(), Some("Synthetic session"));
assert!(core.pos.0 < -50.0);
assert!(state.outputs.is_empty());
@@ -1772,8 +1789,8 @@ mod tests {
wait_for_renderer_command(&rx, &mut state),
Some(WlOverlayCmd::Cmd { key, .. }) if key == "session-a"
));
- assert!(!state.ended.contains("session-a"));
- assert!(state.ended.contains("session-b"));
+ assert!(!state.render.ended.contains("session-a"));
+ assert!(state.render.ended.contains("session-b"));
// Startup must not consume the later Remove or reorder it behind the
// stale command. The active loop receives both in their original order.
assert!(matches!(
@@ -1801,25 +1818,13 @@ mod tests {
panic!("fresh session should start the renderer");
};
assert_eq!(key, "session-b");
- assert!(apply_keyed_command(
- &mut state.cores,
- &state.template,
- &state.ended,
- key,
- cmd,
- ));
- assert!(state.cores.contains_key("session-b"));
+ assert!(apply_keyed_command(&mut state.render, None, key, cmd,));
+ assert!(state.render.cursors.contains_key("session-b"));
let WlOverlayCmd::Cmd { key, cmd } = snap_command("session-a") else {
unreachable!();
};
- assert!(!apply_keyed_command(
- &mut state.cores,
- &state.template,
- &state.ended,
- key,
- cmd,
- ));
- assert!(!state.cores.contains_key("session-a"));
+ assert!(!apply_keyed_command(&mut state.render, None, key, cmd,));
+ assert!(!state.render.cursors.contains_key("session-a"));
}
#[test]
@@ -1842,13 +1847,10 @@ mod tests {
#[test]
fn named_cursors_render_on_independent_outputs_and_removal_clears_only_one() {
- let template = CursorConfig::default();
- let mut cores = HashMap::new();
- let mut ended = HashSet::new();
+ let mut render = WlRenderMap::new(CursorConfig::default(), ());
assert!(apply_keyed_command(
- &mut cores,
- &template,
- &ended,
+ &mut render,
+ None,
"session-a".to_owned(),
OverlayCommand::SnapTo {
x: 100.0,
@@ -1857,9 +1859,8 @@ mod tests {
},
));
assert!(apply_keyed_command(
- &mut cores,
- &template,
- &ended,
+ &mut render,
+ None,
"session-b".to_owned(),
OverlayCommand::SnapTo {
x: 2500.0,
@@ -1867,19 +1868,19 @@ mod tests {
heading_radians: None,
},
));
- assert_eq!(cores["session-a"].cfg.cursor_id, "session-a");
- assert_eq!(cores["session-b"].cfg.cursor_id, "session-b");
+ assert_eq!(render.cursors["session-a"].cfg.cursor_id, "session-a");
+ assert_eq!(render.cursors["session-b"].cfg.cursor_id, "session-b");
let layouts = three_monitor_layout();
assert_eq!(
- visible_cores_for_output(&cores, &layouts, 1)
+ visible_cores_for_output(&render.cursors, &layouts, 1)
.into_iter()
.map(|(key, _)| key.as_str())
.collect::<Vec<_>>(),
vec!["session-a"]
);
assert_eq!(
- visible_cores_for_output(&cores, &layouts, 2)
+ visible_cores_for_output(&render.cursors, &layouts, 2)
.into_iter()
.map(|(key, _)| key.as_str())
.collect::<Vec<_>>(),
@@ -1889,21 +1890,17 @@ mod tests {
&layouts,
&HashSet::new(),
&initialized(&layouts),
- cores.values().map(|core| core.pos),
+ render.cursors.values().map(|core| core.pos),
);
assert_eq!(painted, HashSet::from([1, 2]));
assert_eq!(targets, vec![FrameTarget { id: 1 }, FrameTarget { id: 2 }]);
- assert!(remove_keyed_core(
- &mut cores,
- &mut ended,
- "session-a".to_owned()
- ));
- assert!(!cores.contains_key("session-a"));
- assert!(cores.contains_key("session-b"));
- assert!(visible_cores_for_output(&cores, &layouts, 1).is_empty());
+ assert!(remove_keyed_core(&mut render, "session-a".to_owned()));
+ assert!(!render.cursors.contains_key("session-a"));
+ assert!(render.cursors.contains_key("session-b"));
+ assert!(visible_cores_for_output(&render.cursors, &layouts, 1).is_empty());
assert_eq!(
- visible_cores_for_output(&cores, &layouts, 2)
+ visible_cores_for_output(&render.cursors, &layouts, 2)
.into_iter()
.map(|(key, _)| key.as_str())
.collect::<Vec<_>>(),
@@ -1913,16 +1910,15 @@ mod tests {
&layouts,
&painted,
&initialized(&layouts),
- cores.values().map(|core| core.pos),
+ render.cursors.values().map(|core| core.pos),
);
assert_eq!(selected, HashSet::from([2]));
assert_eq!(targets, vec![FrameTarget { id: 1 }, FrameTarget { id: 2 }]);
// A queued command cannot resurrect an ended named session.
assert!(!apply_keyed_command(
- &mut cores,
- &template,
- &ended,
+ &mut render,
+ None,
"session-a".to_owned(),
OverlayCommand::SnapTo {
x: 200.0,
@@ -1930,14 +1926,13 @@ mod tests {
heading_radians: None,
},
));
- assert!(!cores.contains_key("session-a"));
+ assert!(!render.cursors.contains_key("session-a"));
- revive_key(&mut ended, "session-a".to_owned());
- assert!(!ended.contains("session-a"));
+ revive_key(&mut render, "session-a".to_owned());
+ assert!(!render.ended.contains("session-a"));
assert!(apply_keyed_command(
- &mut cores,
- &template,
- &ended,
+ &mut render,
+ None,
"session-a".to_owned(),
OverlayCommand::SnapTo {
x: 200.0,
@@ -1945,18 +1940,20 @@ mod tests {
heading_radians: None,
},
));
- assert!(cores.contains_key("session-a"));
+ assert!(render.cursors.contains_key("session-a"));
}
#[test]
fn named_cursors_schedule_animation_and_idle_deadlines_independently() {
let mut idle = positioned_core();
+ idle.visual.reduced_motion = cursor_overlay::ReducedMotion::On;
idle.idle_secs = 0.25;
let mut animated = positioned_core();
+ animated.visual.reduced_motion = cursor_overlay::ReducedMotion::On;
animated.motion.idle_hide_ms = 4_000.0;
animated.click_t = Some(0.0);
let mut cores =
- HashMap::from([("idle".to_owned(), idle), ("animated".to_owned(), animated)]);
+ CursorMap::from([("idle".to_owned(), idle), ("animated".to_owned(), animated)]);
assert_eq!(next_wait(&cores, false, false), WlWait::Frame);
cores.get_mut("animated").unwrap().click_t = None;
@@ -1966,22 +1963,6 @@ mod tests {
);
}
- #[test]
- fn default_cursor_is_not_removed_or_marked_ended() {
- let mut cores = HashMap::from([(
- "default".to_owned(),
- RenderStateCore::new(CursorConfig::default()),
- )]);
- let mut ended = HashSet::new();
- assert!(!remove_keyed_core(
- &mut cores,
- &mut ended,
- "default".to_owned()
- ));
- assert!(cores.contains_key("default"));
- assert!(!ended.contains("default"));
- }
-
#[test]
fn maintenance_scheduler_wakes_immediately_on_command_arrival() {
let (tx, rx) = bounded(1);
diff --git a/libs/cua-driver/rust/crates/platform-macos/Cargo.toml b/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
index 3fa046fc8c..d7f4d4f7c3 100644
--- a/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
@@ -18,7 +18,6 @@ time = { workspace = true }
# Insertion-ordered map for the keyed per-session cursor render collection.
# IndexMap gives deterministic iteration order = stable cursor z-order frame
# to frame (a plain HashMap would flicker overlapping cursors).
-indexmap = "2"
cua-driver-core = { path = "../cua-driver-core" }
cua-driver-contract = { path = "../cua-driver-contract" }
cursor-overlay = { path = "../cursor-overlay" }
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs b/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
index 4159449b9c..6a32feed0e 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
@@ -36,10 +36,9 @@ use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use cursor_overlay::{
- CursorConfig, CursorKey, FocusRect, KeyedOverlayCommand, MotionConfig, OverlayCommand,
- OverlayMsg, RenderStateCore, ZOrderEnforcer,
+ CursorConfig, CursorKey, FocusRect, KeyedOverlayCommand, MotionConfig, MsgOutcome,
+ OverlayCommand, OverlayMsg, RenderEntry, RenderStateCore, ScreenFrame, ZOrderEnforcer,
};
-use indexmap::IndexMap;
// ── Arrival-signal channels (one waiter slot per cursor key) ──────────────
//
@@ -69,6 +68,15 @@ fn arrival_fire(key: &CursorKey) {
}
}
+/// Drop a removed session's waiter; the dropped sender releases its await.
+fn arrival_cancel(key: &CursorKey) {
+ if let Ok(mut guard) = ARRIVAL_TX.lock() {
+ if let Some(map) = guard.as_mut() {
+ map.remove(key);
+ }
+ }
+}
+
// ── Global overlay state ──────────────────────────────────────────────────
static CMD_TX: OnceLock<std::sync::mpsc::SyncSender<OverlayMsg>> = OnceLock::new();
@@ -81,12 +89,11 @@ pub(crate) fn is_overlay_window(window_id: u32) -> bool {
window_id != 0 && OVERLAY_WINDOW_ID.load(Ordering::Acquire) == window_id
}
-/// The keyed, insertion-ordered collection of owned cursors that the render
-/// loop composites every frame. Insertion order = stable z-order (later keys
-/// paint on top). `win_w` / `win_h` are screen-global, hoisted out of the
-/// per-cursor `RenderState` (written once in `run_appkit`).
-struct RenderMap {
- cursors: IndexMap<CursorKey, RenderState>,
+/// Screen-global geometry kept beside the shared keyed render map
+/// ([`cursor_overlay::RenderMap`], which owns the per-session lifecycle:
+/// lazy creation, stable z-order, tombstones, revival, and the default guard).
+/// Written once in `run_appkit`.
+struct MacScreen {
win_w: f64,
win_h: f64,
/// `NSScreen.backingScaleFactor` of the screen the overlay window sits on.
@@ -95,74 +102,18 @@ struct RenderMap {
/// rendered cursor is crisp at native resolution instead of being
/// bilinear-upsampled by Core Animation from a logical-pixel buffer.
backing_scale: f64,
- /// Frozen launch-time config used as the template for lazily-created cursors.
- template: CursorConfig,
- /// Render-side tombstone of ended session cursor keys. A `Cmd`
- /// for a key in here is dropped WITHOUT get-or-create, so an in-flight
- /// click/move from another task that lands AFTER the owning session's
- /// `Remove` can never resurrect the just-removed cursor (the ghost-cursor
- /// resurrection race). An explicit owner-checked `start_session` revival
- /// clears this tombstone before the cursor is reused. "default" is never
- /// tombstoned.
- ended: std::collections::HashSet<CursorKey>,
}
-/// Build the `RenderState` for a lazily-created session cursor from the
-/// process launch template.
-fn render_state_for_key(template: &CursorConfig, key: &str) -> RenderState {
- let mut config = template.clone();
- config.cursor_id = key.to_owned();
- RenderState::new(config)
-}
+type RenderMap = cursor_overlay::RenderMap<RenderState, MacScreen>;
-/// Apply one inbound [`OverlayMsg`] to the render map (drain step). Factored
-/// out as a pure function so the per-session ownership + removal lifecycle is
-/// unit-testable without AppKit.
-///
-/// Returns the resolved cursor key for a `Cmd` (so the caller can track the
-/// last-active key for z-order pinning); `None` for a lifecycle message.
+/// Drain one message into the shared map, releasing a removed session's
+/// arrival waiter. Returns the commanded key for z-order pinning.
fn apply_msg(map: &mut RenderMap, msg: OverlayMsg) -> Option<CursorKey> {
- match msg {
- OverlayMsg::Remove(key) => {
- // The "default" cursor backs the anonymous / one-shot path and
- // must survive every session_end + the daemon lifetime.
- if key != "default" {
- map.cursors.shift_remove(&key);
- if let Ok(mut guard) = ARRIVAL_TX.lock() {
- if let Some(m) = guard.as_mut() {
- m.remove(&key);
- }
- }
- // Tombstone the key so a late in-flight Cmd from another task
- // (an animate/click racing the owning session's death) cannot
- // re-create the just-removed cursor. Never tombstone "default".
- map.ended.insert(key);
- }
- None
- }
- OverlayMsg::Revive(key) => {
- if key != "default" {
- map.ended.remove(&key);
- }
- None
- }
- OverlayMsg::Cmd(KeyedOverlayCommand { key, cmd }) => {
- // Drop a command for an already-ended session WITHOUT get-or-create
- // — this is the resurrection guard. Without it, a ClickPulse/MoveTo
- // landing after Remove would re-insert (and re-leak) the cursor.
- if map.ended.contains(&key) {
- return None;
- }
- let template = map.template.clone();
- let k = key.clone();
- let rs = map
- .cursors
- .entry(key)
- .or_insert_with(|| render_state_for_key(&template, &k));
- rs.apply_command(cmd);
- Some(k)
- }
+ let outcome = map.apply_msg(msg);
+ if let MsgOutcome::Removed { key, .. } = &outcome {
+ arrival_cancel(key);
}
+ outcome.applied_key().cloned()
}
/// Initialise global overlay state (call once, before run_on_main_thread).
@@ -175,16 +126,14 @@ pub fn init(cfg: CursorConfig) {
.expect("cursor overlay sender is initialized exactly once");
*CMD_RX_CELL.lock().unwrap() = Some(rx);
*ARRIVAL_TX.lock().unwrap() = Some(HashMap::new());
- let mut cursors = IndexMap::new();
- cursors.insert("default".to_owned(), RenderState::new(cfg.clone()));
- *RENDER.lock().unwrap() = Some(RenderMap {
- cursors,
- win_w: 0.0,
- win_h: 0.0,
- backing_scale: 1.0, // overwritten in run_appkit() once the NSScreen is known
- template: cfg,
- ended: std::collections::HashSet::new(),
- });
+ *RENDER.lock().unwrap() = Some(RenderMap::new(
+ cfg,
+ MacScreen {
+ win_w: 0.0,
+ win_h: 0.0,
+ backing_scale: 1.0, // overwritten in run_appkit() once the NSScreen is known
+ },
+ ));
});
cua_driver_core::cursor_events::install_cursor_event_sink(std::sync::Arc::new(
|event: cua_driver_core::cursor_events::CursorEvent| {
@@ -292,9 +241,7 @@ pub fn current_motion(key: &str) -> MotionConfig {
let Some(map) = guard.as_ref() else {
return MotionConfig::default();
};
- map.cursors
- .get(key)
- .or_else(|| map.cursors.get("default"))
+ map.cursor_or_default(key)
.map(|rs| rs.core.motion.clone())
.unwrap_or_default()
}
@@ -311,10 +258,7 @@ pub fn current_theme_state(
)> {
let guard = RENDER.lock().unwrap();
let map = guard.as_ref()?;
- let state = map
- .cursors
- .get(key)
- .or_else(|| map.cursors.get("default"))?;
+ let state = map.cursor_or_default(key)?;
let (id, version, profile, fallback) = state.core.active_theme_metadata();
Some((id, version, profile, fallback, state.core.visual.clone()))
}
@@ -336,52 +280,11 @@ fn seed_start_if_sentinel(key: &CursorKey, target_x: f64, target_y: f64) -> bool
let Some(map) = guard.as_mut() else {
return false;
};
- seed_start_in_map(map, key, target_x, target_y)
-}
-
-/// Pure seed step operating on a borrowed [`RenderMap`] — factored out of
-/// `seed_start_if_sentinel` so the get-or-create + clamp logic is unit-testable
-/// without the global `RENDER` static or AppKit.
-fn seed_start_in_map(map: &mut RenderMap, key: &CursorKey, target_x: f64, target_y: f64) -> bool {
- // Offset the start up-left of the target so the Dubins path has room to
- // curve in; 140pt is enough to read as motion at 900pt/s peak speed.
- const SEED_OFFSET: f64 = 140.0;
- let (win_w, win_h) = (map.win_w, map.win_h);
- // Respect the resurrection guard: never seed (and thus re-create) a cursor
- // whose session already ended.
- if map.ended.contains(key) {
- return false;
- }
- // Get-or-create the cursor so the very first AX action seeds + glides even
- // when the lazy render-thread creation hasn't drained the PinAbove yet
- // (the render loop's drain would otherwise win the race and the seed read
- // an absent cursor). Mirrors apply_msg's entry().or_insert_with.
- let template = map.template.clone();
- let k = key.clone();
- let rs = map
- .cursors
- .entry(key.clone())
- .or_insert_with(|| render_state_for_key(&template, &k));
- if !(rs.core.cfg.enabled && rs.core.pos.0 < -50.0) {
- return false;
- }
- let mut sx = target_x - SEED_OFFSET;
- let mut sy = target_y - SEED_OFFSET;
- // Clamp into the screen frame when we know it (win_w/h are 0 until the
- // AppKit window is up; in that headless case the unclamped seed is still
- // on-screen-by-construction for any realistic target).
- if win_w > 0.0 && win_h > 0.0 {
- sx = sx.clamp(2.0, win_w - 2.0);
- sy = sy.clamp(2.0, win_h - 2.0);
- // If clamping collapsed the seed onto the target (target in a corner),
- // nudge it the other way so there is still a visible glide distance.
- if (sx - target_x).abs() < 8.0 && (sy - target_y).abs() < 8.0 {
- sx = (target_x + SEED_OFFSET).min(win_w - 2.0);
- sy = (target_y + SEED_OFFSET).min(win_h - 2.0);
- }
- }
- rs.core.pos = (sx, sy);
- true
+ // `win_w/h` are 0 until the AppKit window is up; the shared seed then only
+ // keeps the start point off negative coordinates.
+ let MacScreen { win_w, win_h, .. } = map.platform;
+ let frame = (win_w > 0.0 && win_h > 0.0).then(|| ScreenFrame::new(0.0, 0.0, win_w, win_h));
+ map.seed_start_if_sentinel(key, target_x, target_y, frame)
}
/// Animate the overlay cursor to `(x, y)` and suspend until the Dubins path
@@ -505,8 +408,8 @@ struct RenderState {
focus_rect_t: f64,
}
-impl RenderState {
- fn new(cfg: CursorConfig) -> Self {
+impl RenderEntry for RenderState {
+ fn from_config(cfg: CursorConfig) -> Self {
RenderState {
core: RenderStateCore::new(cfg),
focus_rect: None,
@@ -514,6 +417,14 @@ impl RenderState {
}
}
+ fn core(&self) -> &RenderStateCore {
+ &self.core
+ }
+
+ fn core_mut(&mut self) -> &mut RenderStateCore {
+ &mut self.core
+ }
+
/// Advance the animation by `dt`. Uses the Swift reference constants
/// (peakSpeed=900, springK=400, overshoot=0.8) — see
/// [`RenderStateCore::tick_swift_constants`]. Returns true if an
@@ -534,7 +445,7 @@ impl RenderState {
fire_arrival
}
- fn apply_command(&mut self, cmd: OverlayCommand) {
+ fn apply_command(&mut self, cmd: OverlayCommand) -> bool {
// macOS uses the sentinel-snap variants of MoveTo / ClickPulse:
// - MoveTo only snaps `self.pos` if the cursor is still at the
// off-screen sentinel `(-200, -200)` (otherwise the path starts
@@ -545,6 +456,7 @@ impl RenderState {
OverlayCommand::ShowFocusRect(rect) => {
self.focus_rect = rect;
self.focus_rect_t = 0.0; // reset fade to fully visible
+ true
}
OverlayCommand::PinAbove(wid) => {
// The overlay window joins every Space, so a target on another
@@ -554,24 +466,20 @@ impl RenderState {
.ok()
.and_then(crate::windows::window_on_current_space_by_id)
== Some(false);
- let _ = self.core.apply_command_base(cmd, true, true);
- }
- other => {
- let _ = self.core.apply_command_base(other, true, true);
+ self.core.apply_command_base(cmd, true, true)
}
+ other => self.core.apply_command_base(other, true, true),
}
}
- /// True while the render loop must wake at frame cadence because the next
- /// tick can change pixels. A brand-new sentinel cursor is deliberately
- /// quiescent, so `serve` with no agent activity can block on the command
- /// channel instead of compositing an empty fullscreen pixmap at 60fps.
+ /// The shared predicate (glide, spring, pulse, badge, resting motion,
+ /// idle fade) plus two macOS terms: the focus-rect fade, and the opaque
+ /// idle-hide countdown. The macOS loop parks on a blocking `recv` with no
+ /// deadline, so a reduced-motion cursor must keep frame ticks through the
+ /// countdown for its idle fade to start on time.
fn needs_frame_tick(&self) -> bool {
- self.core.path.is_some()
- || self.core.spring.is_some()
- || self.core.click_t.is_some()
+ self.core.needs_frame_tick()
|| self.focus_rect.is_some()
- || self.core.session_badge_needs_frame_tick()
|| (self.core.motion.idle_hide_ms > 0.0
&& self.core.visible
&& self.core.pos.0 >= -100.0
@@ -579,10 +487,6 @@ impl RenderState {
}
}
-fn render_map_needs_frame_tick(map: &RenderMap) -> bool {
- map.cursors.values().any(RenderState::needs_frame_tick)
-}
-
// ── AppKit / CGImage plumbing ─────────────────────────────────────────────
unsafe fn run_appkit(_cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayMsg>) {
@@ -686,9 +590,11 @@ unsafe fn run_appkit(_cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayMs
{
let mut guard = RENDER.lock().unwrap();
if let Some(m) = guard.as_mut() {
- m.win_w = win_w;
- m.win_h = win_h;
- m.backing_scale = backing_scale;
+ m.platform = MacScreen {
+ win_w,
+ win_h,
+ backing_scale,
+ };
}
}
@@ -798,11 +704,7 @@ fn render_loop(
// this frame without waiting for the next 16ms tick.
let mut arrived: Vec<CursorKey> = Vec::new();
if frame_tick_needed || had_msg {
- for (k, rs) in map.cursors.iter_mut() {
- if rs.tick(dt) {
- arrived.push(k.clone());
- }
- }
+ arrived = map.tick_all(dt);
}
let pointer = if hover_poll_tick
|| map
@@ -830,7 +732,7 @@ fn render_loop(
.and_then(|k| map.cursors.get(k))
.is_some_and(cursor_is_externally_visible)
&& pinned.is_none();
- let next_frame_tick_needed = render_map_needs_frame_tick(map);
+ let next_frame_tick_needed = map.needs_frame_tick();
let next_hover_poll_needed = map
.cursors
.values()
@@ -839,8 +741,8 @@ fn render_loop(
pinned,
raise_unpinned,
arrived,
- map.win_w,
- map.win_h,
+ map.platform.win_w,
+ map.platform.win_h,
had_msg,
hover_changed,
next_frame_tick_needed,
@@ -891,7 +793,7 @@ fn render_loop(
// The cursor's logical coordinates are scaled into pixmap
// pixels inside `paint_cursor` (it multiplies px/py/sizes
// by `backing_scale`).
- let scale = map.backing_scale.max(1.0);
+ let scale = map.platform.backing_scale.max(1.0);
let w = (win_w * scale).max(1.0) as u32;
let h = (win_h * scale).max(1.0) as u32;
let mut pm = tiny_skia::Pixmap::new(w.max(1), h.max(1))
@@ -1253,11 +1155,10 @@ mod tests {
use super::*;
use std::collections::HashMap;
- #[test]
- fn keyed_render_state_carries_the_session_color_identity() {
- let state = render_state_for_key(&CursorConfig::default(), "session-blueprint");
- assert_eq!(state.core.cfg.cursor_id, "session-blueprint");
- }
+ // The keyed lifecycle, sentinel seed, and shared frame-tick predicate are
+ // covered once in `cursor_overlay::render_map`. These tests cover only the
+ // macOS adapter: window ordering, external visibility, and the macOS
+ // frame-tick terms layered on the shared predicate.
fn window(window_id: u32, pid: i32, z_index: usize) -> crate::windows::WindowInfo {
crate::windows::WindowInfo {
@@ -1281,19 +1182,20 @@ mod tests {
}
fn empty_map() -> RenderMap {
- let mut cursors = IndexMap::new();
- cursors.insert(
- "default".to_owned(),
- RenderState::new(CursorConfig::default()),
- );
- RenderMap {
- cursors,
- win_w: 100.0,
- win_h: 100.0,
- backing_scale: 1.0,
- template: CursorConfig::default(),
- ended: std::collections::HashSet::new(),
- }
+ RenderMap::new(
+ CursorConfig::default(),
+ MacScreen {
+ win_w: 100.0,
+ win_h: 100.0,
+ backing_scale: 1.0,
+ },
+ )
+ }
+
+ fn placed<'a>(map: &'a mut RenderMap, key: &str) -> &'a mut RenderState {
+ let frame = Some(ScreenFrame::new(0.0, 0.0, 100.0, 100.0));
+ assert!(map.seed_start_if_sentinel(key, 60.0, 60.0, frame));
+ map.cursors.get_mut(key).unwrap()
}
#[test]
@@ -1321,243 +1223,73 @@ mod tests {
));
}
- fn move_msg(key: &str, x: f64, y: f64) -> OverlayMsg {
- OverlayMsg::Cmd(KeyedOverlayCommand {
- key: key.to_owned(),
- cmd: OverlayCommand::MoveTo {
- x,
- y,
- end_heading_radians: 0.0,
- },
- })
- }
-
#[test]
- fn two_sessions_produce_two_distinct_render_entries() {
+ fn only_enabled_on_screen_cursor_is_externally_visible() {
let mut map = empty_map();
- apply_msg(
- &mut map,
- OverlayMsg::Cmd(KeyedOverlayCommand {
- key: "sessA".to_owned(),
- cmd: OverlayCommand::SetEnabled(true),
- }),
- );
- apply_msg(&mut map, move_msg("sessB", 42.0, 24.0));
- // default + sessA + sessB = 3 distinct owned cursors (the core
- // regression today is that they would clobber to one).
- assert_eq!(map.cursors.len(), 3);
- assert!(map.cursors.contains_key("sessA"));
- assert!(map.cursors.contains_key("sessB"));
- assert!(map.cursors.contains_key("default"));
- }
+ assert!(!cursor_is_externally_visible(&map.cursors["default"]));
- #[test]
- fn session_end_removes_only_that_session() {
- let mut map = empty_map();
- apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
- apply_msg(&mut map, move_msg("sessB", 20.0, 20.0));
- assert_eq!(map.cursors.len(), 3);
+ placed(&mut map, "sessA");
+ assert!(cursor_is_externally_visible(&map.cursors["sessA"]));
- // session_end(A): A gone, B + default retained.
- apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));
- assert!(!map.cursors.contains_key("sessA"));
- assert!(map.cursors.contains_key("sessB"));
- assert!(map.cursors.contains_key("default"));
- assert_eq!(map.cursors.len(), 2);
-
- // Remove("default") is guarded — default survives.
- apply_msg(&mut map, OverlayMsg::Remove("default".to_owned()));
- assert!(map.cursors.contains_key("default"));
-
- // Remove of an absent key (anonymous session that never created a
- // cursor) is a harmless no-op.
- let before = map.cursors.len();
- apply_msg(&mut map, OverlayMsg::Remove("never-existed".to_owned()));
- assert_eq!(map.cursors.len(), before);
+ map.cursors.get_mut("sessA").unwrap().core.cfg.enabled = false;
+ assert!(!cursor_is_externally_visible(&map.cursors["sessA"]));
}
#[test]
- fn lazily_created_cursors_inherit_the_selected_theme() {
+ fn removal_through_the_adapter_releases_only_that_arrival_waiter() {
let mut map = empty_map();
- apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
- apply_msg(&mut map, move_msg("sessB", 20.0, 20.0));
assert_eq!(
- map.cursors["sessA"].core.cfg.theme_id,
- map.cursors["default"].core.cfg.theme_id
+ apply_msg(
+ &mut map,
+ OverlayMsg::Cmd(KeyedOverlayCommand {
+ key: "sessA".to_owned(),
+ cmd: OverlayCommand::SetEnabled(true),
+ }),
+ )
+ .as_deref(),
+ Some("sessA")
);
assert_eq!(
- map.cursors["sessB"].core.cfg.theme_id,
- map.cursors["default"].core.cfg.theme_id
- );
- }
-
- #[test]
- fn insertion_order_is_stable_z_order() {
- let mut map = empty_map();
- apply_msg(&mut map, move_msg("first", 1.0, 1.0));
- apply_msg(&mut map, move_msg("second", 2.0, 2.0));
- // Re-touching "first" must NOT move it to the back (IndexMap keeps the
- // original insertion slot), so z-order is stable frame to frame.
- apply_msg(&mut map, move_msg("first", 3.0, 3.0));
- let keys: Vec<&String> = map.cursors.keys().collect();
- assert_eq!(keys, vec!["default", "first", "second"]);
- }
-
- #[test]
- fn tombstone_blocks_resurrection_after_remove() {
- // The resurrection race: a Cmd for a session lands AFTER its Remove
- // (an in-flight click from another task as the session dies). The
- // tombstone must drop it so the just-removed cursor is NOT re-created.
- let mut map = empty_map();
- apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
- assert_eq!(map.cursors.len(), 2); // default + sessA
-
- // Session ends → cursor removed, key tombstoned.
- apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));
- assert!(!map.cursors.contains_key("sessA"));
- assert_eq!(map.cursors.len(), 1);
-
- // A late in-flight Cmd for the ended session must be dropped WITHOUT
- // re-inserting (no get-or-create resurrection).
- let resolved = apply_msg(&mut map, move_msg("sessA", 99.0, 99.0));
- assert!(
- resolved.is_none(),
- "ended-session Cmd must be dropped, not resolved"
- );
- assert!(
- !map.cursors.contains_key("sessA"),
- "tombstone must block resurrection"
- );
- assert_eq!(
- map.cursors.len(),
- 1,
- "render map length must stay at default only"
+ apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned())),
+ None
);
- }
-
- #[test]
- fn explicit_revival_clears_tombstone_and_recreates_lazily() {
- let mut map = empty_map();
- apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
- apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));
- assert!(apply_msg(&mut map, move_msg("sessA", 20.0, 20.0)).is_none());
-
- apply_msg(&mut map, OverlayMsg::Revive("sessA".to_owned()));
assert!(!map.cursors.contains_key("sessA"));
- assert!(!map.ended.contains("sessA"));
-
- let resolved = apply_msg(&mut map, move_msg("sessA", 30.0, 30.0));
- assert_eq!(resolved.as_deref(), Some("sessA"));
- assert!(map.cursors.contains_key("sessA"));
}
#[test]
- fn default_is_never_tombstoned() {
- // Remove("default") is guarded, so default is never tombstoned and a
- // subsequent Cmd on default still renders.
+ fn resting_cursor_floats_until_idle_hide_and_never_hide_parks() {
let mut map = empty_map();
- apply_msg(&mut map, OverlayMsg::Remove("default".to_owned()));
- assert!(map.cursors.contains_key("default"));
- assert!(!map.ended.contains("default"));
-
- let resolved = apply_msg(&mut map, move_msg("default", 5.0, 5.0));
- assert_eq!(resolved.as_deref(), Some("default"));
- assert!(map.cursors.contains_key("default"));
- }
-
- #[test]
- fn seed_moves_sentinel_cursor_on_screen_for_first_action() {
- // BUG 2 regression: a brand-new session cursor at the sentinel must be
- // seeded on-screen (pos.0 > -50) so the immediately-following MoveTo
- // glides instead of silently snapping via ClickPulse.
- let mut map = empty_map(); // 100x100 frame
- // No "sessA" cursor exists yet — the seed must get-or-create it.
- let seeded = seed_start_in_map(&mut map, &"sessA".to_owned(), 60.0, 60.0);
- assert!(seeded, "sentinel cursor must be seeded");
- let pos = map.cursors["sessA"].core.pos;
- assert!(
- pos.0 > -50.0 && pos.1 > -50.0,
- "seed must be on-screen, got {pos:?}"
- );
- // And it must be a DIFFERENT point from the target so there is a glide.
- assert!(
- (pos.0 - 60.0).abs() > 4.0 || (pos.1 - 60.0).abs() > 4.0,
- "seed must differ from target to produce a visible glide, got {pos:?}"
- );
+ let cursor = placed(&mut map, "sessA");
+ cursor.core.motion.idle_hide_ms = 20_000.0;
+ assert!(cursor.core.has_resting_motion());
+ assert!(map.needs_frame_tick());
+
+ let cursor = map.cursors.get_mut("sessA").unwrap();
+ cursor.core.motion.idle_hide_ms = 0.0;
+ assert!(!map.needs_frame_tick(), "a never-hiding cursor rests still");
}
#[test]
- fn seed_is_noop_when_cursor_already_on_screen() {
- // A second action: the cursor already landed somewhere on-screen, so the
- // seed must NOT move it (the MoveTo path should start from where it is).
+ fn focus_rect_and_reduced_motion_countdown_keep_macos_frames() {
let mut map = empty_map();
- // Put sessA on-screen first.
- seed_start_in_map(&mut map, &"sessA".to_owned(), 60.0, 60.0);
- map.cursors.get_mut("sessA").unwrap().core.pos = (30.0, 30.0);
- let seeded_again = seed_start_in_map(&mut map, &"sessA".to_owned(), 80.0, 80.0);
- assert!(!seeded_again, "on-screen cursor must not be re-seeded");
- assert_eq!(
- map.cursors["sessA"].core.pos,
- (30.0, 30.0),
- "pos must be untouched"
- );
- }
-
- #[test]
- fn seed_does_not_resurrect_ended_session() {
- // The seed shares the resurrection guard: it must not re-create a cursor
- // whose session already ended.
- let mut map = empty_map();
- map.ended.insert("sessA".to_owned());
- let seeded = seed_start_in_map(&mut map, &"sessA".to_owned(), 60.0, 60.0);
- assert!(!seeded, "ended session must not be seeded");
- assert!(
- !map.cursors.contains_key("sessA"),
- "ended session must not be resurrected"
- );
- }
-
- #[test]
- fn sentinel_default_cursor_does_not_require_frame_ticks() {
- // Regression for idle CPU: a freshly-started serve daemon seeds only the
- // off-screen default cursor. With no commands in flight, the render loop
- // should be able to block on rx.recv() instead of repainting at 60fps.
- let map = empty_map();
- assert!(!render_map_needs_frame_tick(&map));
- }
-
- #[test]
- fn only_enabled_on_screen_cursor_is_externally_visible() {
- let mut map = empty_map();
- assert!(!cursor_is_externally_visible(&map.cursors["default"]));
-
- seed_start_in_map(&mut map, &"sessA".to_owned(), 60.0, 60.0);
- assert!(cursor_is_externally_visible(&map.cursors["sessA"]));
-
- map.cursors.get_mut("sessA").unwrap().core.cfg.enabled = false;
- assert!(!cursor_is_externally_visible(&map.cursors["sessA"]));
- }
-
- #[test]
- fn active_or_fading_cursor_requires_frame_ticks() {
- let mut map = empty_map();
- seed_start_in_map(&mut map, &"sessA".to_owned(), 60.0, 60.0);
- apply_msg(&mut map, move_msg("sessA", 80.0, 80.0));
- assert!(
- render_map_needs_frame_tick(&map),
- "planned path should tick"
- );
+ let cursor = placed(&mut map, "sessA");
+ cursor.core.visual.reduced_motion = cursor_overlay::ReducedMotion::On;
+ cursor.core.motion.idle_hide_ms = 20_000.0;
+ // The macOS loop has no idle deadline, so the opaque countdown ticks.
+ assert!(!cursor.core.needs_frame_tick());
+ assert!(cursor.needs_frame_tick());
+
+ cursor.core.motion.idle_hide_ms = 0.0;
+ assert!(!cursor.needs_frame_tick());
+ cursor.apply_command(OverlayCommand::ShowFocusRect(Some([0.0, 0.0, 10.0, 10.0])));
+ assert!(cursor.needs_frame_tick());
+ for _ in 0..60 {
+ cursor.tick(1.0 / 60.0);
+ }
+ assert!(cursor.focus_rect.is_none());
- let rs = map.cursors.get_mut("sessA").unwrap();
- rs.core.path = None;
- rs.core.spring = None;
- rs.core.click_t = None;
- rs.focus_rect = None;
- rs.core.idle_alpha = 0.0;
- assert!(
- !render_map_needs_frame_tick(&map),
- "fully hidden idle cursor should quiesce"
- );
+ cursor.core.idle_alpha = 0.0;
+ assert!(!map.needs_frame_tick(), "a fully hidden cursor must park");
}
#[test]
diff --git a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml b/libs/cua-driver/rust/crates/platform-windows/Cargo.toml
index e7caf40998..4da06bdcce 100644
--- a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-windows/Cargo.toml
@@ -20,7 +20,6 @@ getrandom = { workspace = true }
# IndexMap gives the keyed cursor render collection deterministic
# insertion-ordered iteration = stable per-session cursor z-order frame to
# frame (mirrors platform-macos's per-session overlay).
-indexmap = "2"
# tiny-skia for cross-platform cursor rendering (used in overlay.rs on all targets)
tiny-skia = { version = "0.11", default-features = false, features = ["std"] }
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs b/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
index 87cdf875cd..800749fd22 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
@@ -13,15 +13,13 @@
//!
//! Before this, the overlay was a process-wide singleton (one `RenderState`),
//! so concurrent MCP sessions clobbered each other last-writer-wins → one
-//! shared cursor. It now keeps a keyed [`RenderMap`] (`IndexMap<CursorKey,
-//! RenderState>`): each declared `session` owns its own cursor with its own
-//! visual state, and the ~125 Hz tick composites them all into the single layered
-//! window. `IndexMap` gives deterministic insertion-ordered iteration = stable
-//! per-session z-order frame to frame. The lifecycle (lazy create, per-key
-//! arrival isolation, `session_end` removal, resurrection tombstone) mirrors
-//! `platform_macos::cursor::overlay` so the two platforms behave identically;
-//! the shared `cursor_overlay::{CursorKey, KeyedOverlayCommand, OverlayMsg}`
-//! types are the same ones macOS uses.
+//! shared cursor. It now keeps the shared keyed [`cursor_overlay::RenderMap`]:
+//! each declared `session` owns its own cursor with its own visual state, and
+//! the ~125 Hz tick composites them all into the single layered window in the
+//! map's stable insertion (z) order. The lifecycle (lazy create, `session_end`
+//! removal, resurrection tombstone, revival, default guard, sentinel seed) and
+//! the frame-tick predicate live in `cursor_overlay` so every platform behaves
+//! identically; this adapter adds per-key arrival waiters and Win32 plumbing.
//!
//! ## Cross-platform note (2026-05 dedup audit)
//!
@@ -32,15 +30,14 @@
#![allow(non_snake_case, non_upper_case_globals)]
-use std::collections::{HashMap, HashSet};
+use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use std::time::Instant;
use cursor_overlay::{
- CursorConfig, CursorKey, KeyedOverlayCommand, MotionConfig, OverlayCommand, OverlayMsg,
- RenderStateCore, ZOrderEnforcer,
+ CursorConfig, CursorKey, KeyedOverlayCommand, MotionConfig, MsgOutcome, OverlayCommand,
+ OverlayMsg, RenderEntry, RenderStateCore, ScreenFrame, ZOrderEnforcer,
};
-use indexmap::IndexMap;
// ── Global channel ────────────────────────────────────────────────────────
@@ -77,17 +74,23 @@ fn arrival_fire(key: &CursorKey) {
}
}
+/// Drop a removed session's waiter; the dropped sender releases its await.
+fn arrival_cancel(key: &CursorKey) {
+ if let Ok(mut guard) = ARRIVAL_TX.lock() {
+ if let Some(map) = guard.as_mut() {
+ map.remove(key);
+ }
+ }
+}
+
// ── Keyed render collection ───────────────────────────────────────────────
-/// The keyed, insertion-ordered collection of owned cursors that the render
-/// loop composites every tick. Insertion order = stable z-order (later keys
-/// paint on top). Virtual-screen geometry + the `WM_TIMER` dt stamp are
-/// hoisted here (screen-global, written once in `run_overlay_thread`).
-struct RenderMap {
- cursors: IndexMap<CursorKey, RenderState>,
- /// Virtual screen dimensions set after window creation (Win32 DIPs).
- /// `virt_x/y` are subtracted from each cursor's `core.pos` when rendering
- /// so the pixmap is laid out in window-local coordinates.
+/// Virtual-screen geometry and timing kept beside the shared keyed render map
+/// (screen-global, written once in `run_overlay_thread`).
+struct WinScreen {
+ /// Virtual screen bounds (Win32 DIPs). `virt_x/y` are subtracted from each
+ /// cursor's `core.pos` when rendering so the pixmap is laid out in
+ /// window-local coordinates.
virt_x: i32,
virt_y: i32,
virt_w: i32,
@@ -96,79 +99,32 @@ struct RenderMap {
/// timer resolution defaults to 15ms so a hardcoded 8ms would run the
/// animation at half speed).
last_tick: Instant,
- /// Frozen launch-time config used as the template for lazily-created cursors.
- template: CursorConfig,
- /// Render-side tombstone of ended session cursor keys. A `Cmd`
- /// for a key in here is dropped WITHOUT get-or-create, so an in-flight
- /// click/move from another task that lands AFTER the owning session's
- /// `Remove` can never resurrect the just-removed cursor. An explicit
- /// owner-checked revival clears the tombstone. "default" is never
- /// tombstoned for legacy direct platform calls.
- ended: HashSet<CursorKey>,
- /// Cursor key whose target the overlay should currently sit above. A single
- /// layered window can occupy only one z-band, so the most-recently-touched
- /// cursor wins (mirrors macOS). `None` until the first PinAbove/Cmd.
- last_active: Option<CursorKey>,
}
-/// Build the `RenderState` for a lazily-created session cursor from the
-/// process launch template.
-fn render_state_for_key(template: &CursorConfig, key: &str) -> RenderState {
- let mut config = template.clone();
- config.cursor_id = key.to_owned();
- RenderState::new(config)
+impl WinScreen {
+ fn frame(&self) -> Option<ScreenFrame> {
+ (self.virt_w > 0 && self.virt_h > 0).then(|| {
+ ScreenFrame::new(
+ f64::from(self.virt_x),
+ f64::from(self.virt_y),
+ f64::from(self.virt_w),
+ f64::from(self.virt_h),
+ )
+ })
+ }
}
-/// Apply one inbound [`OverlayMsg`] to the render map (drain step). Factored
-/// out as a pure function so the per-session ownership + removal lifecycle is
-/// unit-testable without any Win32 window.
-///
-/// Returns the resolved cursor key for a `Cmd` (so the caller can track the
-/// last-active key for z-order pinning); `None` for a lifecycle message.
+type RenderMap = cursor_overlay::RenderMap<RenderState, WinScreen>;
+
+/// Drain one message into the shared map, releasing a removed session's
+/// arrival waiter. Returns the commanded key (also recorded as the map's
+/// `last_active`).
fn apply_msg(map: &mut RenderMap, msg: OverlayMsg) -> Option<CursorKey> {
- match msg {
- OverlayMsg::Remove(key) => {
- // The "default" cursor backs the anonymous / one-shot path and must
- // survive every session_end + the daemon lifetime.
- if key != "default" {
- map.cursors.shift_remove(&key);
- if let Ok(mut guard) = ARRIVAL_TX.lock() {
- if let Some(m) = guard.as_mut() {
- m.remove(&key);
- }
- }
- if map.last_active.as_deref() == Some(key.as_str()) {
- map.last_active = None;
- }
- // Tombstone the key so a late in-flight Cmd from another task
- // cannot re-create the just-removed cursor.
- map.ended.insert(key);
- }
- None
- }
- OverlayMsg::Revive(key) => {
- if key != "default" {
- map.ended.remove(&key);
- }
- None
- }
- OverlayMsg::Cmd(KeyedOverlayCommand { key, cmd }) => {
- // Drop a command for an already-ended session WITHOUT get-or-create
- // — this is the resurrection guard. Without it, a ClickPulse/MoveTo
- // landing after Remove would re-insert (and re-leak) the cursor.
- if map.ended.contains(&key) {
- return None;
- }
- let template = map.template.clone();
- let k = key.clone();
- let rs = map
- .cursors
- .entry(key)
- .or_insert_with(|| render_state_for_key(&template, &k));
- rs.apply_command(cmd);
- Some(k)
- }
+ let outcome = map.apply_msg(msg);
+ if let MsgOutcome::Removed { key, .. } = &outcome {
+ arrival_cancel(key);
}
+ outcome.applied_key().cloned()
}
pub fn init(cfg: CursorConfig) {
@@ -180,19 +136,16 @@ pub fn init(cfg: CursorConfig) {
.expect("cursor overlay sender is initialized exactly once");
*CMD_RX_CELL.lock().unwrap() = Some(rx);
*ARRIVAL_TX.lock().unwrap() = Some(HashMap::new());
- let mut cursors = IndexMap::new();
- cursors.insert("default".to_owned(), RenderState::new(cfg.clone()));
- *RENDER.lock().unwrap() = Some(RenderMap {
- cursors,
- virt_x: 0,
- virt_y: 0,
- virt_w: 1920,
- virt_h: 1080,
- last_tick: Instant::now(),
- template: cfg,
- ended: HashSet::new(),
- last_active: None,
- });
+ *RENDER.lock().unwrap() = Some(RenderMap::new(
+ cfg,
+ WinScreen {
+ virt_x: 0,
+ virt_y: 0,
+ virt_w: 1920,
+ virt_h: 1080,
+ last_tick: Instant::now(),
+ },
+ ));
});
cua_driver_core::cursor_events::install_cursor_event_sink(std::sync::Arc::new(
|event: cua_driver_core::cursor_events::CursorEvent| {
@@ -322,12 +275,8 @@ pub fn is_enabled(key: &str) -> bool {
.lock()
.ok()
.and_then(|g| {
- g.as_ref().and_then(|m| {
- m.cursors
- .get(key)
- .or_else(|| m.cursors.get("default"))
- .map(|rs| rs.core.visible)
- })
+ g.as_ref()
+ .and_then(|m| m.cursor_or_default(key).map(|rs| rs.core.visible))
})
.unwrap_or(false)
}
@@ -360,12 +309,8 @@ pub fn current_motion(key: &str) -> MotionConfig {
.lock()
.ok()
.and_then(|g| {
- g.as_ref().and_then(|m| {
- m.cursors
- .get(key)
- .or_else(|| m.cursors.get("default"))
- .map(|rs| rs.core.motion.clone())
- })
+ g.as_ref()
+ .and_then(|m| m.cursor_or_default(key).map(|rs| rs.core.motion.clone()))
})
.unwrap_or_default()
}
@@ -381,10 +326,7 @@ pub fn current_theme_state(
)> {
let guard = RENDER.lock().ok()?;
let map = guard.as_ref()?;
- let state = map
- .cursors
- .get(key)
- .or_else(|| map.cursors.get("default"))?;
+ let state = map.cursor_or_default(key)?;
let (id, version, profile, fallback) = state.core.active_theme_metadata();
Some((id, version, profile, fallback, state.core.visual.clone()))
}
@@ -414,45 +356,8 @@ fn seed_start_if_sentinel(key: &CursorKey, target_x: f64, target_y: f64) -> bool
let Some(map) = guard.as_mut() else {
return false;
};
- seed_start_in_map(map, key, target_x, target_y)
-}
-
-/// Pure seed step operating on a borrowed [`RenderMap`] — factored out so the
-/// get-or-create + clamp logic is unit-testable without the global `RENDER`
-/// static or a Win32 window.
-fn seed_start_in_map(map: &mut RenderMap, key: &CursorKey, target_x: f64, target_y: f64) -> bool {
- const SEED_OFFSET: f64 = 140.0;
- let (virt_x, virt_y) = (map.virt_x as f64, map.virt_y as f64);
- let (virt_w, virt_h) = (map.virt_w as f64, map.virt_h as f64);
- // Respect the resurrection guard: never seed (and thus re-create) a cursor
- // whose session already ended.
- if map.ended.contains(key) {
- return false;
- }
- let template = map.template.clone();
- let k = key.clone();
- let rs = map
- .cursors
- .entry(key.clone())
- .or_insert_with(|| render_state_for_key(&template, &k));
- if !(rs.core.cfg.enabled && rs.core.pos.0 < -50.0) {
- return false;
- }
- let mut sx = target_x - SEED_OFFSET;
- let mut sy = target_y - SEED_OFFSET;
- // Clamp into the virtual-screen frame so the seed never starts off-display.
- if virt_w > 0.0 && virt_h > 0.0 {
- sx = sx.clamp(virt_x + 2.0, virt_x + virt_w - 2.0);
- sy = sy.clamp(virt_y + 2.0, virt_y + virt_h - 2.0);
- // If clamping collapsed the seed onto the target (target in a corner),
- // nudge the other way so there is still a visible glide distance.
- if (sx - target_x).abs() < 8.0 && (sy - target_y).abs() < 8.0 {
- sx = (target_x + SEED_OFFSET).min(virt_x + virt_w - 2.0);
- sy = (target_y + SEED_OFFSET).min(virt_y + virt_h - 2.0);
- }
- }
- rs.core.pos = (sx, sy);
- true
+ let frame = map.platform.frame();
+ map.seed_start_if_sentinel(key, target_x, target_y, frame)
}
/// Animate the overlay cursor for `key` to `(x, y)` and suspend until the
@@ -538,59 +443,43 @@ pub fn run_on_thread() {
//
// The platform-agnostic fields + tick + apply_command + render pipeline live
// in `cursor_overlay::render_state`. What stays here is just the per-cursor
-// wrapper; the virtual-screen geometry + dt stamp moved up to `RenderMap`.
+// wrapper; the virtual-screen geometry + dt stamp live in `WinScreen`.
struct RenderState {
core: RenderStateCore,
}
-impl RenderState {
- fn new(cfg: CursorConfig) -> Self {
+impl RenderEntry for RenderState {
+ fn from_config(cfg: CursorConfig) -> Self {
RenderState {
core: RenderStateCore::new(cfg),
}
}
- /// Advance the motion state by `dt`. Returns `true` the tick the planned
- /// path completes, so the WM_TIMER handler can fire the arrival oneshot
- /// that unblocks `animate_cursor_to`.
- fn tick(&mut self, dt: f64) -> bool {
- self.core.tick_motion(dt)
+ fn core(&self) -> &RenderStateCore {
+ &self.core
+ }
+
+ fn core_mut(&mut self) -> &mut RenderStateCore {
+ &mut self.core
}
- fn apply_command(&mut self, cmd: OverlayCommand) {
+ fn apply_command(&mut self, cmd: OverlayCommand) -> bool {
// Windows uses the non-sentinel-snap behaviour for both MoveTo and
// ClickPulse: every command updates `self.pos` unconditionally.
// `ShowFocusRect` is not rendered on Windows — `apply_command_base`
// returns `false` for it and we silently drop it here.
- let _ = self.core.apply_command_base(cmd, false, false);
+ self.core.apply_command_base(cmd, false, false)
}
- /// True while the render loop must keep ticking at frame cadence because
- /// the next tick can still change pixels: an in-flight glide path, a
- /// spring-settle, a click pulse, or an idle-fade actively fading
- /// (`0.004 <= idle_alpha < 1.0`). A brand-new sentinel cursor (off-screen
- /// at `(-200, -200)`), a cursor that has already faded to
- /// `idle_alpha ≈ 0`, AND a cursor resting at constant `idle_alpha == 1.0`
- /// waiting out the idle-hide countdown are all non-rendering states: the
- /// countdown phase leaves every frame pixel-identical, so compositing a
- /// full virtual-screen pixmap through it burned ~1 core for the whole
- /// `idle_hide_ms` window after every action (render-gate fix; the
- /// countdown itself is advanced by [`RenderState::in_idle_countdown`]
- /// ticks at the slow cadence).
- #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
- fn needs_frame_tick(&self) -> bool {
- self.core.path.is_some()
- || self.core.spring.is_some()
- || self.core.click_t.is_some()
- || self.core.session_badge_needs_frame_tick()
- || (self.core.motion.idle_hide_ms > 0.0
- && self.core.visible
- && self.core.pos.0 >= -100.0
- && self.core.idle_alpha >= 0.004
- && self.core.idle_alpha < 1.0)
- }
+ // `tick` (arrival on path end) and `needs_frame_tick` use the shared
+ // defaults. The shared predicate keeps a revealed cursor with resting
+ // motion (the float bob) at the ACTIVE cadence, and parks a reduced-motion
+ // cursor through its constant-alpha idle-hide countdown; that countdown is
+ // advanced by [`RenderState::in_idle_countdown`] at the slow IDLE cadence.
+}
+impl RenderState {
/// True while the cursor rests on-screen at full alpha with idle-hide
/// pending: pixels are static (alpha pinned at 1.0) but `idle_secs` must
/// keep accruing wall-clock time so the fade still starts on schedule.
@@ -608,16 +497,6 @@ impl RenderState {
}
}
-/// True if ANY owned cursor still needs frame ticks (animation / fade in
-/// progress). When this is false the render loop is fully quiescent: the last
-/// emitted frame already left the layered window in its resting / cleared
-/// state, so the timer can drop to a slow idle cadence and skip the expensive
-/// composite + `UpdateLayeredWindow` until the next command wakes it.
-#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
-fn render_map_needs_frame_tick(map: &RenderMap) -> bool {
- map.cursors.values().any(RenderState::needs_frame_tick)
-}
-
// ── Win32 message-loop thread ─────────────────────────────────────────────
#[cfg(target_os = "windows")]
@@ -642,11 +521,13 @@ fn run_overlay_thread(cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayMs
{
let mut guard = RENDER.lock().unwrap();
if let Some(map) = guard.as_mut() {
- map.virt_x = virt_x;
- map.virt_y = virt_y;
- map.virt_w = virt_w;
- map.virt_h = virt_h;
- map.last_tick = Instant::now();
+ map.platform = WinScreen {
+ virt_x,
+ virt_y,
+ virt_w,
+ virt_h,
+ last_tick: Instant::now(),
+ };
}
}
@@ -971,13 +852,14 @@ thread_local! {
/// painted and nothing stale to erase — skip the present entirely).
#[cfg(target_os = "windows")]
fn composite_dirty(map: &RenderMap) -> Option<DirtyRect> {
- let (w, h) = (map.virt_w.max(1), map.virt_h.max(1));
+ let screen = &map.platform;
+ let (w, h) = (screen.virt_w.max(1), screen.virt_h.max(1));
SURFACE.with(|cell| {
let mut slot = cell.borrow_mut();
if slot.as_ref().map(|s| (s.virt_x, s.virt_y, s.w, s.h))
- != Some((map.virt_x, map.virt_y, w, h))
+ != Some((screen.virt_x, screen.virt_y, w, h))
{
- *slot = unsafe { WinSurface::create(map.virt_x, map.virt_y, w, h) };
+ *slot = unsafe { WinSurface::create(screen.virt_x, screen.virt_y, w, h) };
FIRST_PRESENT.with(|first| first.set(true));
}
let surf = slot.as_mut()?;
@@ -989,8 +871,8 @@ fn composite_dirty(map: &RenderMap) -> Option<DirtyRect> {
if !rs.core.visible || rs.core.pos.0 < -100.0 || rs.core.idle_alpha < 0.004 {
continue;
}
- let cx = (rs.core.pos.0 - map.virt_x as f64).round() as i32;
- let cy = (rs.core.pos.1 - map.virt_y as f64).round() as i32;
+ let cx = (rs.core.pos.0 - screen.virt_x as f64).round() as i32;
+ let cy = (rs.core.pos.1 - screen.virt_y as f64).round() as i32;
let custom_theme = rs
.core
.theme
@@ -1023,8 +905,8 @@ fn composite_dirty(map: &RenderMap) -> Option<DirtyRect> {
cursor_overlay::paint_cursor(
&mut surf.pixmap,
&rs.core,
- map.virt_x as f64,
- map.virt_y as f64,
+ screen.virt_x as f64,
+ screen.virt_y as f64,
None, // focus-rect is macOS-only
1.0,
);
@@ -1118,7 +1000,7 @@ unsafe fn present_surface(hwnd: windows::Win32::Foundation::HWND, dirty: DirtyRe
// allocated a virtual-screen pixmap, swizzled it pixel-by-pixel, and blitted
// it with UpdateLayeredWindow — burning 60–85% of a core with the cursor
// static (issue #1808). `TIMER_PERIOD_MS` is the cadence the timer is currently
-// armed at; the WM_TIMER handler flips it based on `render_map_needs_frame_tick`.
+// armed at; the WM_TIMER handler flips it based on `RenderMap::needs_frame_tick`.
const TIMER_ID: usize = 1;
const TIMER_MS_ACTIVE: u32 = 8; // ~125 Hz, matches the C# reference render rate
const TIMER_MS_HOVER: u32 = 80; // low-cost hardware-pointer hover sampling
@@ -1206,26 +1088,24 @@ unsafe extern "system" fn wnd_proc(
let (upload, arrived, pinned_wid, needs_tick, needs_hover_poll) = {
let mut guard = RENDER.lock().unwrap();
if let Some(map) = guard.as_mut() {
- // Drain the channel via get-or-create; track the last-touched
- // key so the z-order pin follows the most-recent cursor.
+ // Drain the channel via get-or-create; the shared map
+ // tracks the last-touched key for z-order pinning.
let mut had_msg = false;
if let Ok(rx_guard) = CMD_RX_WIN.try_lock() {
if let Some(ref rx) = *rx_guard {
while let Ok(m) = rx.try_recv() {
had_msg = true;
- if let Some(k) = apply_msg(map, m) {
- map.last_active = Some(k);
- }
+ apply_msg(map, m);
}
}
}
let now = Instant::now();
- let real_dt = now.duration_since(map.last_tick).as_secs_f64();
+ let real_dt = now.duration_since(map.platform.last_tick).as_secs_f64();
// Clamped dt for the motion physics: a large gap between
// ticks must not teleport an in-flight glide.
let dt = real_dt.clamp(0.0, 0.05);
- map.last_tick = now;
+ map.platform.last_tick = now;
// Tick every cursor; record the ones that just arrived.
let mut arrived: Vec<CursorKey> = Vec::new();
@@ -1258,7 +1138,7 @@ unsafe extern "system" fn wnd_proc(
}
// After ticking: does any cursor still need frame ticks?
- let needs_tick = render_map_needs_frame_tick(map);
+ let needs_tick = map.needs_frame_tick();
let needs_hover_poll = map
.cursors
.values()
@@ -1517,40 +1397,30 @@ impl ZOrderEnforcer for WinZOrderEnforcer {
}
}
-// ── Headless unit tests for the keyed render collection ───────────────────
+// ── Headless unit tests for the Windows adapter ───────────────────────────
//
-// These prove the per-session ownership data model, the session_end removal
-// lifecycle, the "default" guard, the resurrection tombstone, and the
-// sentinel seed WITHOUT any Win32 window. The on-screen rendering
-// (UpdateLayeredWindow) still needs a real display and is verified separately.
+// The keyed lifecycle (ownership, removal, default guard, tombstone, revival,
+// stable z-order), the sentinel seed, and the shared frame-tick predicate are
+// covered once in `cursor_overlay::render_map`. These tests cover what this
+// adapter adds: the dirty-rect envelope, virtual-screen seeding, the IDLE
+// cadence countdown, and arrival release on removal. On-screen rendering
+// (UpdateLayeredWindow) needs a real display and is verified separately.
#[cfg(test)]
mod tests {
use super::*;
- #[test]
- fn keyed_render_state_carries_the_session_color_identity() {
- let state = render_state_for_key(&CursorConfig::default(), "session-blueprint");
- assert_eq!(state.core.cfg.cursor_id, "session-blueprint");
- }
-
fn empty_map() -> RenderMap {
- let mut cursors = IndexMap::new();
- cursors.insert(
- "default".to_owned(),
- RenderState::new(CursorConfig::default()),
- );
- RenderMap {
- cursors,
- virt_x: 0,
- virt_y: 0,
- virt_w: 100,
- virt_h: 100,
- last_tick: Instant::now(),
- template: CursorConfig::default(),
- ended: HashSet::new(),
- last_active: None,
- }
+ RenderMap::new(
+ CursorConfig::default(),
+ WinScreen {
+ virt_x: 0,
+ virt_y: 0,
+ virt_w: 100,
+ virt_h: 100,
+ last_tick: Instant::now(),
+ },
+ )
}
fn move_msg(key: &str, x: f64, y: f64) -> OverlayMsg {
@@ -1564,310 +1434,109 @@ mod tests {
})
}
- #[test]
- fn default_dirty_envelope_covers_edge_clamped_session_badges() {
- assert!(
- CURSOR_PAD as f32 >= cursor_overlay::session_badge::BADGE_MAX_WIDTH + 8.0,
- "a cursor at a display edge can have the entire badge on one side"
- );
- }
-
- #[test]
- fn idle_countdown_does_not_request_frame_ticks_but_fade_does() {
- let mut map = empty_map();
- apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
-
- // Run the glide + spring settle to completion.
+ fn settle(map: &mut RenderMap) {
for _ in 0..2000 {
- for rs in map.cursors.values_mut() {
- rs.tick(0.016);
- }
- if !render_map_needs_frame_tick(&map) {
+ map.tick_all(0.016);
+ if map.cursors.values().all(|rs| {
+ rs.core.path.is_none() && rs.core.spring.is_none() && rs.core.click_t.is_none()
+ }) {
break;
}
}
- let rs = &map.cursors["sessA"];
- assert!(
- rs.core.path.is_none() && rs.core.spring.is_none(),
- "glide must have completed"
- );
-
- // Landed cursor at constant alpha 1.0, idle-hide pending: this is the
- // countdown phase. Pixels cannot change, so it must NOT demand frame
- // ticks (the render-gate fix — previously this phase composited the
- // full virtual screen at frame cadence for the whole idle_hide_ms
- // window), but it must still be ticked for wall-clock accrual.
- assert!((rs.core.idle_alpha - 1.0).abs() < f64::EPSILON);
- assert!(
- !render_map_needs_frame_tick(&map),
- "constant-alpha countdown must not request frame ticks"
- );
- assert!(
- rs.in_idle_countdown(),
- "landed cursor with idle-hide pending must report in_idle_countdown"
- );
-
- // Advance idle_secs to the fade window: the fade animates pixels, so
- // frame ticks are required again until alpha reaches ~0.
- let fade_start = map.cursors["sessA"].core.motion.idle_hide_ms / 1000.0;
- for rs in map.cursors.values_mut() {
- rs.core.idle_secs = fade_start;
- }
- for rs in map.cursors.values_mut() {
- rs.tick(0.016);
- }
- let rs = &map.cursors["sessA"];
- assert!(rs.core.idle_alpha < 1.0 && rs.core.idle_alpha >= 0.004);
- assert!(
- rs.needs_frame_tick(),
- "an actively fading cursor must request frame ticks"
- );
- assert!(!rs.in_idle_countdown());
-
- // Run the fade out: fully hidden must be quiescent again.
- for _ in 0..60 {
- for rs in map.cursors.values_mut() {
- rs.tick(0.016);
- }
- }
- assert!(
- !render_map_needs_frame_tick(&map),
- "fully faded cursor must be quiescent"
- );
}
#[test]
- fn two_sessions_produce_two_distinct_render_entries() {
- let mut map = empty_map();
- apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
- apply_msg(&mut map, move_msg("sessB", 42.0, 24.0));
- // default + sessA + sessB = 3 distinct owned cursors. The pre-port
- // regression: a single RenderState would clobber these to one cursor.
- assert_eq!(map.cursors.len(), 3);
- assert!(map.cursors.contains_key("sessA"));
- assert!(map.cursors.contains_key("sessB"));
- assert!(map.cursors.contains_key("default"));
+ fn default_dirty_envelope_covers_edge_clamped_session_badges() {
+ assert!(
+ CURSOR_PAD as f32 >= cursor_overlay::session_badge::BADGE_MAX_WIDTH + 8.0,
+ "a cursor at a display edge can have the entire badge on one side"
+ );
}
#[test]
- fn session_end_removes_only_that_session() {
+ fn seed_clamps_into_a_virtual_screen_left_of_the_primary() {
let mut map = empty_map();
- apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
- apply_msg(&mut map, move_msg("sessB", 20.0, 20.0));
- assert_eq!(map.cursors.len(), 3);
-
- // session_end(A): A gone, B + default retained.
- apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));
- assert!(!map.cursors.contains_key("sessA"));
- assert!(map.cursors.contains_key("sessB"));
- assert!(map.cursors.contains_key("default"));
- assert_eq!(map.cursors.len(), 2);
-
- // Remove("default") is guarded — default survives.
- apply_msg(&mut map, OverlayMsg::Remove("default".to_owned()));
- assert!(map.cursors.contains_key("default"));
-
- // Remove of an absent key is a harmless no-op.
- let before = map.cursors.len();
- apply_msg(&mut map, OverlayMsg::Remove("never-existed".to_owned()));
- assert_eq!(map.cursors.len(), before);
+ map.platform.virt_x = -1920;
+ map.platform.virt_w = 3840;
+ map.platform.virt_h = 1080;
+ let frame = map.platform.frame();
+ assert!(map.seed_start_if_sentinel("sessA", -1800.0, 500.0, frame));
+ assert_eq!(map.cursors["sessA"].core.pos, (-1918.0, 360.0));
+
+ map.platform.virt_w = 0;
+ assert_eq!(map.platform.frame(), None);
}
#[test]
- fn lazily_created_cursors_inherit_the_selected_theme() {
+ fn removal_through_the_adapter_resolves_no_pin_key() {
let mut map = empty_map();
- apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
- apply_msg(&mut map, move_msg("sessB", 20.0, 20.0));
assert_eq!(
- map.cursors["sessA"].core.cfg.theme_id,
- map.cursors["default"].core.cfg.theme_id
+ apply_msg(&mut map, move_msg("sessA", 10.0, 10.0)).as_deref(),
+ Some("sessA")
);
assert_eq!(
- map.cursors["sessB"].core.cfg.theme_id,
- map.cursors["default"].core.cfg.theme_id
+ apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned())),
+ None
);
+ assert_eq!(map.last_active, None);
}
+ // Before the shared predicate, a landed Windows cursor dropped to the IDLE
+ // cadence for the whole idle-hide delay and its resting bob froze.
#[test]
- fn insertion_order_is_stable_z_order() {
- let mut map = empty_map();
- apply_msg(&mut map, move_msg("first", 1.0, 1.0));
- apply_msg(&mut map, move_msg("second", 2.0, 2.0));
- // Re-touching "first" must NOT move it to the back (IndexMap keeps the
- // original slot), so z-order is stable frame to frame.
- apply_msg(&mut map, move_msg("first", 3.0, 3.0));
- let keys: Vec<&String> = map.cursors.keys().collect();
- assert_eq!(keys, vec!["default", "first", "second"]);
- }
-
- #[test]
- fn tombstone_blocks_resurrection_after_remove() {
+ fn resting_cursor_keeps_the_active_cadence_for_its_bob() {
let mut map = empty_map();
+ map.seed_start_if_sentinel("sessA", 60.0, 60.0, map.platform.frame());
apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
- assert_eq!(map.cursors.len(), 2); // default + sessA
-
- apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));
- assert!(!map.cursors.contains_key("sessA"));
- assert_eq!(map.cursors.len(), 1);
-
- // A late in-flight Cmd for the ended session must be dropped WITHOUT
- // re-inserting (no get-or-create resurrection).
- let resolved = apply_msg(&mut map, move_msg("sessA", 99.0, 99.0));
- assert!(
- resolved.is_none(),
- "ended-session Cmd must be dropped, not resolved"
- );
- assert!(
- !map.cursors.contains_key("sessA"),
- "tombstone must block resurrection"
- );
- assert_eq!(map.cursors.len(), 1);
+ settle(&mut map);
+ let rs = &map.cursors["sessA"];
+ assert!(rs.core.path.is_none() && rs.core.spring.is_none());
+ assert_eq!(rs.core.idle_alpha, 1.0);
+ assert!(rs.core.has_resting_motion());
+ assert!(map.needs_frame_tick(), "the resting bob needs frames");
}
#[test]
- fn explicit_revival_clears_tombstone_and_recreates_lazily() {
+ fn reduced_motion_countdown_parks_at_idle_cadence_but_fade_ticks() {
let mut map = empty_map();
+ map.seed_start_if_sentinel("sessA", 60.0, 60.0, map.platform.frame());
+ map.cursors
+ .get_mut("sessA")
+ .unwrap()
+ .core
+ .visual
+ .reduced_motion = cursor_overlay::ReducedMotion::On;
apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
- apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));
- assert!(apply_msg(&mut map, move_msg("sessA", 20.0, 20.0)).is_none());
-
- apply_msg(&mut map, OverlayMsg::Revive("sessA".to_owned()));
- assert!(!map.cursors.contains_key("sessA"));
- assert!(!map.ended.contains("sessA"));
-
- let resolved = apply_msg(&mut map, move_msg("sessA", 30.0, 30.0));
- assert_eq!(resolved.as_deref(), Some("sessA"));
- assert!(map.cursors.contains_key("sessA"));
- }
-
- #[test]
- fn default_is_never_tombstoned() {
- let mut map = empty_map();
- apply_msg(&mut map, OverlayMsg::Remove("default".to_owned()));
- assert!(map.cursors.contains_key("default"));
- assert!(!map.ended.contains("default"));
-
- let resolved = apply_msg(&mut map, move_msg("default", 5.0, 5.0));
- assert_eq!(resolved.as_deref(), Some("default"));
- assert!(map.cursors.contains_key("default"));
- }
-
- #[test]
- fn seed_moves_sentinel_cursor_on_screen_for_first_action() {
- let mut map = empty_map(); // 100x100 frame at origin
- // No "sessA" cursor exists yet — the seed must get-or-create it.
- let seeded = seed_start_in_map(&mut map, &"sessA".to_owned(), 60.0, 60.0);
- assert!(seeded, "sentinel cursor must be seeded");
- let pos = map.cursors["sessA"].core.pos;
- assert!(
- pos.0 > -50.0 && pos.1 > -50.0,
- "seed must be on-screen, got {pos:?}"
- );
- assert!(
- (pos.0 - 60.0).abs() > 4.0 || (pos.1 - 60.0).abs() > 4.0,
- "seed must differ from target to produce a visible glide, got {pos:?}"
- );
- }
-
- #[test]
- fn seed_is_noop_when_cursor_already_on_screen() {
- let mut map = empty_map();
- seed_start_in_map(&mut map, &"sessA".to_owned(), 60.0, 60.0);
- map.cursors.get_mut("sessA").unwrap().core.pos = (30.0, 30.0);
- let seeded_again = seed_start_in_map(&mut map, &"sessA".to_owned(), 80.0, 80.0);
- assert!(!seeded_again, "on-screen cursor must not be re-seeded");
- assert_eq!(
- map.cursors["sessA"].core.pos,
- (30.0, 30.0),
- "pos must be untouched"
- );
- }
-
- #[test]
- fn seed_does_not_resurrect_ended_session() {
- let mut map = empty_map();
- map.ended.insert("sessA".to_owned());
- let seeded = seed_start_in_map(&mut map, &"sessA".to_owned(), 60.0, 60.0);
- assert!(!seeded, "ended session must not be seeded");
- assert!(
- !map.cursors.contains_key("sessA"),
- "ended session must not be resurrected"
- );
- }
-
- #[test]
- fn sentinel_cursor_is_quiescent_no_frame_tick() {
- // A brand-new `mcp`/`serve` with no agent activity holds only the
- // "default" cursor at the off-screen sentinel (-200, -200). It must NOT
- // request frame ticks, so the render timer can drop to the slow idle
- // cadence instead of compositing a full-screen pixmap at ~125 Hz
- // (issue #1808 idle-CPU burn).
- let map = empty_map();
- assert!(
- !render_map_needs_frame_tick(&map),
- "an untouched sentinel-only overlay must be quiescent"
- );
- }
-
- #[test]
- fn animating_cursor_requests_frame_ticks() {
- // After a MoveTo, the cursor has an in-flight path → the loop must keep
- // ticking at frame cadence so the glide actually animates.
- let mut map = empty_map();
- apply_msg(&mut map, move_msg("sessA", 60.0, 60.0));
- assert!(
- render_map_needs_frame_tick(&map),
- "a cursor with an in-flight glide must request frame ticks"
- );
- assert!(
- map.cursors["sessA"].needs_frame_tick(),
- "the animating cursor itself must report needs_frame_tick"
- );
- }
+ for _ in 0..2000 {
+ map.tick_all(0.016);
+ if !map.needs_frame_tick() {
+ break;
+ }
+ }
- #[test]
- fn click_pulse_requests_frame_ticks_then_goes_quiescent() {
- let mut map = empty_map();
- // ClickPulse seeds click_t = Some(0.0) → active.
- apply_msg(
- &mut map,
- OverlayMsg::Cmd(KeyedOverlayCommand {
- key: "sessA".to_owned(),
- cmd: OverlayCommand::ClickPulse { x: 10.0, y: 10.0 },
- }),
- );
- assert!(
- render_map_needs_frame_tick(&map),
- "click pulse must keep ticking"
- );
+ // Landed cursor at constant alpha 1.0, idle-hide pending: pixels
+ // cannot change, so it must NOT demand frame ticks (the render-gate
+ // fix), but it must still be ticked for wall-clock accrual.
+ let rs = &map.cursors["sessA"];
+ assert!(rs.core.path.is_none() && rs.core.spring.is_none());
+ assert_eq!(rs.core.idle_alpha, 1.0);
+ assert!(!map.needs_frame_tick());
+ assert!(rs.in_idle_countdown());
+
+ // The fade animates pixels, so frame ticks return until alpha ~0.
+ let rs = map.cursors.get_mut("sessA").unwrap();
+ rs.core.idle_secs = rs.core.motion.idle_hide_ms / 1000.0;
+ rs.tick(0.016);
+ assert!(rs.core.idle_alpha < 1.0 && rs.core.idle_alpha >= 0.004);
+ assert!(rs.needs_frame_tick());
+ assert!(!rs.in_idle_countdown());
- // Disable idle-hide so the only activity source is the click pulse, then
- // advance time past the pulse: the cursor must fall quiescent so the
- // loop can park.
- for rs in map.cursors.values_mut() {
- rs.core.motion.idle_hide_ms = 0.0;
- }
- for _ in 0..120 {
- for rs in map.cursors.values_mut() {
- rs.tick(0.016);
- }
+ for _ in 0..60 {
+ map.tick_all(0.016);
}
assert!(
- !render_map_needs_frame_tick(&map),
- "after the click pulse finishes the overlay must go quiescent"
- );
- }
-
- #[test]
- fn remove_clears_last_active_for_that_key() {
- let mut map = empty_map();
- let k = apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
- map.last_active = k;
- assert_eq!(map.last_active.as_deref(), Some("sessA"));
- apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));
- assert_eq!(
- map.last_active, None,
- "removing the active cursor must clear last_active"
+ !map.needs_frame_tick(),
+ "fully faded cursor must be quiescent"
);
}
}