forge
Explore
Log in

Don't you dare go Hollow

Add cursor-shape protocol

Browse files at this commit

088877889d738e7d539243a239441bd82eb44a2cIvan MolodetskikhParent: 5c24754
src/cursor.rsmodified+270 -76
@@ -3,116 +3,310 @@ use std::collections::HashMap;
33 use std::env;
44 use std::fs::File;
55 use std::io::Read;
6+use std::rc::Rc;
7+use std::sync::Mutex;
68
79 use anyhow::{anyhow, Context};
810 use smithay::backend::allocator::Fourcc;
911 use smithay::backend::renderer::element::texture::TextureBuffer;
1012 use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
11-use smithay::utils::{Physical, Point, Transform};
13+use smithay::input::pointer::{CursorIcon, CursorImageAttributes, CursorImageStatus};
14+use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
15+use smithay::utils::{IsAlive, Logical, Physical, Point, Transform};
16+use smithay::wayland::compositor::with_states;
1217 use xcursor::parser::{parse_xcursor, Image};
1318 use xcursor::CursorTheme;
1419
20+/// Some default looking `left_ptr` icon.
1521 static FALLBACK_CURSOR_DATA: &[u8] = include_bytes!("../resources/cursor.rgba");
1622
17-type CursorCache = HashMap<i32, (TextureBuffer<GlesTexture>, Point<i32, Physical>)>;
23+type XCursorCache = HashMap<(CursorIcon, i32), Option<Rc<XCursor>>>;
1824
19-pub struct Cursor {
20- images: Vec<Image>,
21- size: i32,
22- cache: RefCell<CursorCache>,
25+pub struct CursorManager {
26+ theme: CursorTheme,
27+ size: u8,
28+ current_cursor: CursorImageStatus,
29+ named_cursor_cache: RefCell<XCursorCache>,
2330 }
2431
25-impl Cursor {
26- /// Load the said theme as well as set the `XCURSOR_THEME` and `XCURSOR_SIZE`
27- /// env variables.
28- pub fn load(theme: &str, size: u8) -> Self {
32+impl CursorManager {
33+ pub fn new(theme: &str, size: u8) -> Self {
34+ Self::ensure_env(theme, size);
35+
36+ let theme = CursorTheme::load(theme);
37+
38+ Self {
39+ theme,
40+ size,
41+ current_cursor: CursorImageStatus::default_named(),
42+ named_cursor_cache: Default::default(),
43+ }
44+ }
45+
46+ /// Reload the cursor theme.
47+ pub fn reload(&mut self, theme: &str, size: u8) {
48+ Self::ensure_env(theme, size);
49+ self.theme = CursorTheme::load(theme);
50+ self.size = size;
51+ self.named_cursor_cache.get_mut().clear();
52+ }
53+
54+ /// Checks if the cursor WlSurface is alive, and if not, cleans it up.
55+ pub fn check_cursor_image_surface_alive(&mut self) {
56+ if let CursorImageStatus::Surface(surface) = &self.current_cursor {
57+ if !surface.alive() {
58+ self.current_cursor = CursorImageStatus::default_named();
59+ }
60+ }
61+ }
62+
63+ /// Get the current rendering cursor.
64+ pub fn get_render_cursor(&self, scale: i32) -> RenderCursor {
65+ match self.current_cursor.clone() {
66+ CursorImageStatus::Hidden => RenderCursor::Hidden,
67+ CursorImageStatus::Surface(surface) => {
68+ let hotspot = with_states(&surface, |states| {
69+ states
70+ .data_map
71+ .get::<Mutex<CursorImageAttributes>>()
72+ .unwrap()
73+ .lock()
74+ .unwrap()
75+ .hotspot
76+ });
77+
78+ RenderCursor::Surface { hotspot, surface }
79+ }
80+ CursorImageStatus::Named(icon) => self
81+ .get_cursor_with_name(icon, scale)
82+ .map(|cursor| RenderCursor::Named {
83+ icon,
84+ scale,
85+ cursor,
86+ })
87+ .unwrap_or_else(|| RenderCursor::Named {
88+ icon: Default::default(),
89+ scale,
90+ cursor: self.get_default_cursor(scale),
91+ }),
92+ }
93+ }
94+
95+ pub fn is_current_cursor_animated(&self, scale: i32) -> bool {
96+ match &self.current_cursor {
97+ CursorImageStatus::Hidden => false,
98+ CursorImageStatus::Surface(_) => false,
99+ CursorImageStatus::Named(icon) => self
100+ .get_cursor_with_name(*icon, scale)
101+ .unwrap_or_else(|| self.get_default_cursor(scale))
102+ .is_animated_cursor(),
103+ }
104+ }
105+
106+ /// Get named cursor for the given `icon` and `scale`.
107+ pub fn get_cursor_with_name(&self, icon: CursorIcon, scale: i32) -> Option<Rc<XCursor>> {
108+ self.named_cursor_cache
109+ .borrow_mut()
110+ .entry((icon, scale))
111+ .or_insert_with_key(|(icon, scale)| {
112+ let size = self.size as i32 * scale;
113+ let mut cursor = Self::load_xcursor(&self.theme, icon.name(), size);
114+ if let Err(err) = &cursor {
115+ warn!("error loading xcursor {}@{size}: {err:?}", icon.name());
116+ }
117+
118+ // The default cursor must always have a fallback.
119+ if *icon == CursorIcon::Default && cursor.is_err() {
120+ cursor = Ok(Self::fallback_cursor());
121+ }
122+
123+ cursor.ok().map(Rc::new)
124+ })
125+ .clone()
126+ }
127+
128+ /// Get default cursor.
129+ pub fn get_default_cursor(&self, scale: i32) -> Rc<XCursor> {
130+ // The default cursor always has a fallback.
131+ self.get_cursor_with_name(CursorIcon::Default, scale)
132+ .unwrap()
133+ }
134+
135+ /// Currenly used cursor_image as a cursor provider.
136+ pub fn cursor_image(&self) -> &CursorImageStatus {
137+ &self.current_cursor
138+ }
139+
140+ /// Set new cursor image provider.
141+ pub fn set_cursor_image(&mut self, cursor: CursorImageStatus) {
142+ self.current_cursor = cursor;
143+ }
144+
145+ /// Load the cursor with the given `name` from the file system picking the closest
146+ /// one to the given `size`.
147+ fn load_xcursor(theme: &CursorTheme, name: &str, size: i32) -> anyhow::Result<XCursor> {
148+ let _span = tracy_client::span!("load_xcursor");
149+
150+ let path = theme
151+ .load_icon(name)
152+ .ok_or_else(|| anyhow!("no default icon"))?;
153+
154+ let mut file = File::open(path).context("error opening cursor icon file")?;
155+ let mut buf = vec![];
156+ file.read_to_end(&mut buf)
157+ .context("error reading cursor icon file")?;
158+
159+ let mut images = parse_xcursor(&buf).context("error parsing cursor icon file")?;
160+
161+ let (width, height) = images
162+ .iter()
163+ .min_by_key(|image| (size - image.size as i32).abs())
164+ .map(|image| (image.width, image.height))
165+ .unwrap();
166+
167+ images.retain(move |image| image.width == width && image.height == height);
168+
169+ let animation_duration = images.iter().fold(0, |acc, image| acc + image.delay);
170+
171+ Ok(XCursor {
172+ images,
173+ animation_duration,
174+ })
175+ }
176+
177+ /// Set the common XCURSOR env variables.
178+ fn ensure_env(theme: &str, size: u8) {
29179 env::set_var("XCURSOR_THEME", theme);
30180 env::set_var("XCURSOR_SIZE", size.to_string());
181+ }
31182
32- let images = match load_xcursor(theme) {
33- Ok(images) => images,
34- Err(err) => {
35- warn!("error loading xcursor default cursor: {err:?}");
36-
37- vec![Image {
38- size: 32,
39- width: 64,
40- height: 64,
41- xhot: 1,
42- yhot: 1,
43- delay: 1,
44- pixels_rgba: Vec::from(FALLBACK_CURSOR_DATA),
45- pixels_argb: vec![],
46- }]
47- }
48- };
183+ fn fallback_cursor() -> XCursor {
184+ let images = vec![Image {
185+ size: 32,
186+ width: 64,
187+ height: 64,
188+ xhot: 1,
189+ yhot: 1,
190+ delay: 0,
191+ pixels_rgba: Vec::from(FALLBACK_CURSOR_DATA),
192+ pixels_argb: vec![],
193+ }];
49194
50- Self {
195+ XCursor {
51196 images,
52- size: size as i32,
53- cache: Default::default(),
197+ animation_duration: 0,
54198 }
55199 }
200+}
201+
202+/// The cursor prepared for renderer.
203+pub enum RenderCursor {
204+ Hidden,
205+ Surface {
206+ hotspot: Point<i32, Logical>,
207+ surface: WlSurface,
208+ },
209+ Named {
210+ icon: CursorIcon,
211+ scale: i32,
212+ cursor: Rc<XCursor>,
213+ },
214+}
215+
216+type TextureCache = HashMap<(CursorIcon, i32), Vec<TextureBuffer<GlesTexture>>>;
217+
218+#[derive(Default)]
219+pub struct CursorTextureCache {
220+ cache: RefCell<TextureCache>,
221+}
222+
223+impl CursorTextureCache {
224+ pub fn clear(&mut self) {
225+ self.cache.get_mut().clear();
226+ }
56227
57228 pub fn get(
58229 &self,
59230 renderer: &mut GlesRenderer,
231+ icon: CursorIcon,
60232 scale: i32,
61- ) -> (TextureBuffer<GlesTexture>, Point<i32, Physical>) {
233+ cursor: &XCursor,
234+ idx: usize,
235+ ) -> TextureBuffer<GlesTexture> {
62236 self.cache
63237 .borrow_mut()
64- .entry(scale)
65- .or_insert_with_key(|scale| {
66- let _span = tracy_client::span!("create cursor texture");
67-
68- let size = self.size * scale;
69-
70- let nearest_image = self
71- .images
72- .iter()
73- .min_by_key(|image| (size - image.size as i32).abs())
74- .unwrap();
75- let frame = self
76- .images
238+ .entry((icon, scale))
239+ .or_insert_with(|| {
240+ cursor
241+ .frames()
77242 .iter()
78- .find(move |image| {
79- image.width == nearest_image.width && image.height == nearest_image.height
243+ .map(|frame| {
244+ let _span = tracy_client::span!("create TextureBuffer");
245+
246+ TextureBuffer::from_memory(
247+ renderer,
248+ &frame.pixels_rgba,
249+ Fourcc::Abgr8888,
250+ (frame.width as i32, frame.height as i32),
251+ false,
252+ scale,
253+ Transform::Normal,
254+ None,
255+ )
256+ .unwrap()
80257 })
81- .unwrap();
82-
83- let texture = TextureBuffer::from_memory(
84- renderer,
85- &frame.pixels_rgba,
86- Fourcc::Abgr8888,
87- (frame.width as i32, frame.height as i32),
88- false,
89- *scale,
90- Transform::Normal,
91- None,
92- )
93- .unwrap();
94- (texture, (frame.xhot as i32, frame.yhot as i32).into())
95- })
258+ .collect()
259+ })[idx]
96260 .clone()
97261 }
262+}
98263
99- pub fn get_cached_hotspot(&self, scale: i32) -> Option<Point<i32, Physical>> {
100- self.cache.borrow().get(&scale).map(|(_, hotspot)| *hotspot)
101- }
264+// The XCursorBuffer implementation is inspired by `wayland-rs`, thus provided under MIT license.
265+
266+/// The state of the `NamedCursor`.
267+pub struct XCursor {
268+ /// The image for the underlying named cursor.
269+ images: Vec<Image>,
270+ /// The total duration of the animation.
271+ animation_duration: u32,
102272 }
103273
104-fn load_xcursor(theme: &str) -> anyhow::Result<Vec<Image>> {
105- let _span = tracy_client::span!();
274+impl XCursor {
275+ /// Given a time, calculate which frame to show, and how much time remains until the next frame.
276+ ///
277+ /// Time will wrap, so if for instance the cursor has an animation lasting 100ms,
278+ /// then calling this function with 5ms and 105ms as input gives the same output.
279+ pub fn frame(&self, mut millis: u32) -> (usize, &Image) {
280+ if self.animation_duration == 0 {
281+ return (0, &self.images[0]);
282+ }
106283
107- let theme = CursorTheme::load(theme);
108- let path = theme
109- .load_icon("default")
110- .ok_or_else(|| anyhow!("no default icon"))?;
111- let mut file = File::open(path).context("error opening cursor icon file")?;
112- let mut buf = vec![];
113- file.read_to_end(&mut buf)
114- .context("error reading cursor icon file")?;
115- let images = parse_xcursor(&buf).context("error parsing cursor icon file")?;
284+ millis %= self.animation_duration;
116285
117- Ok(images)
286+ let mut res = 0;
287+ for (i, img) in self.images.iter().enumerate() {
288+ if millis < img.delay {
289+ res = i;
290+ break;
291+ }
292+ millis -= img.delay;
293+ }
294+
295+ (res, &self.images[res])
296+ }
297+
298+ /// Get the frames for the given `XCursor`.
299+ pub fn frames(&self) -> &[Image] {
300+ &self.images
301+ }
302+
303+ /// Check whether the cursor is animated.
304+ pub fn is_animated_cursor(&self) -> bool {
305+ self.images.len() > 1
306+ }
307+
308+ /// Get hotspot for the given `image`.
309+ pub fn hotspot(image: &Image) -> Point<i32, Physical> {
310+ (image.xhot as i32, image.yhot as i32).into()
311+ }
118312 }
src/handlers/compositor.rsmodified+2 -1
@@ -161,7 +161,8 @@ impl CompositorHandler for State {
161161 self.layer_shell_handle_commit(surface);
162162
163163 // This might be a cursor surface.
164- if matches!(&self.niri.cursor_image, CursorImageStatus::Surface(s) if s == surface) {
164+ if matches!(&self.niri.cursor_manager.cursor_image(), CursorImageStatus::Surface(s) if s == surface)
165+ {
165166 // FIXME: granular redraws for cursors.
166167 self.niri.queue_redraw_all();
167168 }
src/handlers/mod.rsmodified+6 -5
@@ -35,10 +35,10 @@ use smithay::wayland::session_lock::{
3535 LockSurface, SessionLockHandler, SessionLockManagerState, SessionLocker,
3636 };
3737 use smithay::{
38- delegate_data_control, delegate_data_device, delegate_dmabuf, delegate_input_method_manager,
39- delegate_output, delegate_pointer_gestures, delegate_presentation, delegate_primary_selection,
40- delegate_seat, delegate_session_lock, delegate_tablet_manager, delegate_text_input_manager,
41- delegate_virtual_keyboard_manager,
38+ delegate_cursor_shape, delegate_data_control, delegate_data_device, delegate_dmabuf,
39+ delegate_input_method_manager, delegate_output, delegate_pointer_gestures,
40+ delegate_presentation, delegate_primary_selection, delegate_seat, delegate_session_lock,
41+ delegate_tablet_manager, delegate_text_input_manager, delegate_virtual_keyboard_manager,
4242 };
4343
4444 use crate::layout::output_size;
@@ -53,7 +53,7 @@ impl SeatHandler for State {
5353 }
5454
5555 fn cursor_image(&mut self, _seat: &Seat<Self>, image: CursorImageStatus) {
56- self.niri.cursor_image = image;
56+ self.niri.cursor_manager.set_cursor_image(image);
5757 // FIXME: more granular
5858 self.niri.queue_redraw_all();
5959 }
@@ -66,6 +66,7 @@ impl SeatHandler for State {
6666 }
6767 }
6868 delegate_seat!(State);
69+delegate_cursor_shape!(State);
6970 delegate_tablet_manager!(State);
7071 delegate_pointer_gestures!(State);
7172 delegate_text_input_manager!(State);
src/niri.rsmodified+130 -106
@@ -4,7 +4,7 @@ use std::ffi::OsString;
44 use std::path::PathBuf;
55 use std::rc::Rc;
66 use std::sync::{Arc, Mutex};
7-use std::time::Duration;
7+use std::time::{Duration, Instant};
88 use std::{env, mem, thread};
99
1010 use _server_decoration::server::org_kde_kwin_server_decoration_manager::Mode as KdeDecorationsMode;
@@ -45,13 +45,14 @@ use smithay::reexports::wayland_server::backend::{
4545 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
4646 use smithay::reexports::wayland_server::{Display, DisplayHandle};
4747 use smithay::utils::{
48- ClockSource, IsAlive, Logical, Monotonic, Physical, Point, Rectangle, Scale, Size, Transform,
48+ ClockSource, Logical, Monotonic, Physical, Point, Rectangle, Scale, Size, Transform,
4949 SERIAL_COUNTER,
5050 };
5151 use smithay::wayland::compositor::{
5252 send_surface_state, with_states, with_surface_tree_downward, CompositorClientState,
5353 CompositorState, SurfaceData, TraversalAction,
5454 };
55+use smithay::wayland::cursor_shape::CursorShapeManagerState;
5556 use smithay::wayland::dmabuf::DmabufFeedback;
5657 use smithay::wayland::input_method::InputMethodManagerState;
5758 use smithay::wayland::output::OutputManagerState;
@@ -75,7 +76,7 @@ use smithay::wayland::virtual_keyboard::VirtualKeyboardManagerState;
7576
7677 use crate::backend::{Backend, RenderResult, Tty, Winit};
7778 use crate::config::Config;
78-use crate::cursor::Cursor;
79+use crate::cursor::{CursorManager, CursorTextureCache, RenderCursor, XCursor};
7980 #[cfg(feature = "dbus")]
8081 use crate::dbus::gnome_shell_screenshot::{NiriToScreenshot, ScreenshotToNiri};
8182 #[cfg(feature = "xdp-gnome-screencast")]
@@ -97,6 +98,8 @@ pub struct Niri {
9798 pub display_handle: DisplayHandle,
9899 pub socket_name: OsString,
99100
101+ pub start_time: Instant,
102+
100103 // Each workspace corresponds to a Space. Each workspace generally has one Output mapped to it,
101104 // however it may have none (when there are no outputs connected) or mutiple (when mirroring).
102105 pub layout: Layout<Window>,
@@ -139,8 +142,9 @@ pub struct Niri {
139142 /// Scancodes of the keys to suppress.
140143 pub suppressed_keys: HashSet<u32>,
141144
142- pub default_cursor: Cursor,
143- pub cursor_image: CursorImageStatus,
145+ pub cursor_manager: CursorManager,
146+ pub cursor_texture_cache: CursorTextureCache,
147+ pub cursor_shape_manager_state: CursorShapeManagerState,
144148 pub dnd_icon: Option<WlSurface>,
145149 pub pointer_focus: Option<PointerFocus>,
146150
@@ -268,7 +272,7 @@ impl State {
268272
269273 // These should be called periodically, before flushing the clients.
270274 self.niri.layout.refresh();
271- self.niri.check_cursor_image_surface_alive();
275+ self.niri.cursor_manager.check_cursor_image_surface_alive();
272276 self.niri.refresh_pointer_outputs();
273277 self.niri.popups.cleanup();
274278 self.update_focus();
@@ -393,8 +397,10 @@ impl State {
393397 let mut old_config = self.niri.config.borrow_mut();
394398
395399 if config.cursor != old_config.cursor {
396- self.niri.default_cursor =
397- Cursor::load(&config.cursor.xcursor_theme, config.cursor.xcursor_size);
400+ self.niri
401+ .cursor_manager
402+ .reload(&config.cursor.xcursor_theme, config.cursor.xcursor_size);
403+ self.niri.cursor_texture_cache.clear();
398404 }
399405
400406 *old_config = config;
@@ -568,8 +574,9 @@ impl Niri {
568574 .unwrap();
569575 seat.add_pointer();
570576
571- let default_cursor =
572- Cursor::load(&config_.cursor.xcursor_theme, config_.cursor.xcursor_size);
577+ let cursor_shape_manager_state = CursorShapeManagerState::new::<State>(&display_handle);
578+ let cursor_manager =
579+ CursorManager::new(&config_.cursor.xcursor_theme, config_.cursor.xcursor_size);
573580
574581 let socket_source = ListeningSocketSource::new_auto().unwrap();
575582 let socket_name = socket_source.socket_name().to_os_string();
@@ -607,8 +614,9 @@ impl Niri {
607614
608615 event_loop,
609616 stop_signal,
610- display_handle,
611617 socket_name,
618+ display_handle,
619+ start_time: Instant::now(),
612620
613621 layout,
614622 global_space: Space::default(),
@@ -639,8 +647,9 @@ impl Niri {
639647 presentation_state,
640648
641649 seat,
642- default_cursor,
643- cursor_image: CursorImageStatus::default_named(),
650+ cursor_manager,
651+ cursor_texture_cache: Default::default(),
652+ cursor_shape_manager_state,
644653 dnd_icon: None,
645654 pointer_focus: None,
646655
@@ -1085,51 +1094,60 @@ impl Niri {
10851094 output: &Output,
10861095 ) -> Vec<OutputRenderElements<GlesRenderer>> {
10871096 let _span = tracy_client::span!("Niri::pointer_element");
1088-
1089- let output_scale = Scale::from(output.current_scale().fractional_scale());
1097+ let output_scale = output.current_scale();
10901098 let output_pos = self.global_space.output_geometry(output).unwrap().loc;
10911099 let pointer_pos = self.seat.get_pointer().unwrap().current_location() - output_pos.to_f64();
10921100
1093- let output_scale_int = output.current_scale().integer_scale();
1094- let (default_buffer, default_hotspot) = self.default_cursor.get(renderer, output_scale_int);
1095- let default_hotspot = default_hotspot.to_logical(output_scale_int);
1096-
1097- let hotspot = if let CursorImageStatus::Surface(surface) = &self.cursor_image {
1098- with_states(surface, |states| {
1099- states
1100- .data_map
1101- .get::<Mutex<CursorImageAttributes>>()
1102- .unwrap()
1103- .lock()
1104- .unwrap()
1105- .hotspot
1106- })
1107- } else {
1108- default_hotspot
1109- };
1110- let pointer_pos = (pointer_pos - hotspot.to_f64()).to_physical_precise_round(output_scale);
1101+ // Get the render cursor to draw.
1102+ let cursor_scale = output_scale.integer_scale();
1103+ let render_cursor = self.cursor_manager.get_render_cursor(cursor_scale);
11111104
1112- let mut pointer_elements = match &self.cursor_image {
1113- CursorImageStatus::Hidden => vec![],
1114- CursorImageStatus::Surface(surface) => render_elements_from_surface_tree(
1115- renderer,
1116- surface,
1117- pointer_pos,
1118- output_scale,
1119- 1.,
1120- Kind::Cursor,
1121- ),
1122- // Default shape catch-all
1123- _ => vec![OutputRenderElements::DefaultPointer(
1124- TextureRenderElement::from_texture_buffer(
1125- pointer_pos.to_f64(),
1126- &default_buffer,
1127- None,
1128- None,
1129- None,
1105+ let output_scale = Scale::from(output.current_scale().fractional_scale());
1106+
1107+ let (mut pointer_elements, pointer_pos) = match render_cursor {
1108+ RenderCursor::Hidden => (vec![], pointer_pos.to_physical_precise_round(output_scale)),
1109+ RenderCursor::Surface { surface, hotspot } => {
1110+ let pointer_pos =
1111+ (pointer_pos - hotspot.to_f64()).to_physical_precise_round(output_scale);
1112+
1113+ let pointer_elements = render_elements_from_surface_tree(
1114+ renderer,
1115+ &surface,
1116+ pointer_pos,
1117+ output_scale,
1118+ 1.,
11301119 Kind::Cursor,
1131- ),
1132- )],
1120+ );
1121+
1122+ (pointer_elements, pointer_pos)
1123+ }
1124+ RenderCursor::Named {
1125+ icon,
1126+ scale,
1127+ cursor,
1128+ } => {
1129+ let (idx, frame) = cursor.frame(self.start_time.elapsed().as_millis() as u32);
1130+ let hotspot = XCursor::hotspot(frame).to_logical(scale);
1131+ let pointer_pos =
1132+ (pointer_pos - hotspot.to_f64()).to_physical_precise_round(output_scale);
1133+
1134+ let texture = self
1135+ .cursor_texture_cache
1136+ .get(renderer, icon, scale, &cursor, idx);
1137+
1138+ let pointer_elements = vec![OutputRenderElements::NamedPointer(
1139+ TextureRenderElement::from_texture_buffer(
1140+ pointer_pos.to_f64(),
1141+ &texture,
1142+ None,
1143+ None,
1144+ None,
1145+ Kind::Cursor,
1146+ ),
1147+ )];
1148+
1149+ (pointer_elements, pointer_pos)
1150+ }
11331151 };
11341152
11351153 if let Some(dnd_icon) = &self.dnd_icon {
@@ -1146,56 +1164,11 @@ impl Niri {
11461164 pointer_elements
11471165 }
11481166
1149- pub fn check_cursor_image_surface_alive(&mut self) {
1150- if let CursorImageStatus::Surface(surface) = &self.cursor_image {
1151- if !surface.alive() {
1152- self.cursor_image = CursorImageStatus::default_named();
1153- }
1154- }
1155- }
1156-
1157- pub fn refresh_pointer_outputs(&self) {
1167+ pub fn refresh_pointer_outputs(&mut self) {
11581168 let _span = tracy_client::span!("Niri::refresh_pointer_outputs");
11591169
1160- match &self.cursor_image {
1161- CursorImageStatus::Hidden | CursorImageStatus::Named(_) => {
1162- // There's no cursor surface, but there might be a DnD icon.
1163- let Some(surface) = &self.dnd_icon else {
1164- return;
1165- };
1166-
1167- let pointer_pos = self.seat.get_pointer().unwrap().current_location();
1168-
1169- let mut dnd_scale = 1;
1170- for output in self.global_space.outputs() {
1171- let geo = self.global_space.output_geometry(output).unwrap();
1172-
1173- // The default cursor is rendered at the right scale for each output, which
1174- // means that it may have a different hotspot for each output.
1175- let output_scale = output.current_scale().integer_scale();
1176- let Some(hotspot) = self.default_cursor.get_cached_hotspot(output_scale) else {
1177- // Oh well; it'll get cached next time we render.
1178- continue;
1179- };
1180- let hotspot = hotspot.to_logical(output_scale);
1181-
1182- let surface_pos = pointer_pos.to_i32_round() - hotspot;
1183- let bbox = bbox_from_surface_tree(surface, surface_pos);
1184-
1185- if let Some(mut overlap) = geo.intersection(bbox) {
1186- overlap.loc -= surface_pos;
1187- dnd_scale = dnd_scale.max(output.current_scale().integer_scale());
1188- output_update(output, Some(overlap), surface);
1189- } else {
1190- output_update(output, None, surface);
1191- }
1192-
1193- with_states(surface, |data| {
1194- send_surface_state(surface, data, dnd_scale, Transform::Normal);
1195- });
1196- }
1197- }
1198- CursorImageStatus::Surface(surface) => {
1170+ match self.cursor_manager.cursor_image().clone() {
1171+ CursorImageStatus::Surface(ref surface) => {
11991172 let hotspot = with_states(surface, |states| {
12001173 states
12011174 .data_map
@@ -1252,6 +1225,52 @@ impl Niri {
12521225 });
12531226 }
12541227 }
1228+ cursor_image => {
1229+ // There's no cursor surface, but there might be a DnD icon.
1230+ let Some(surface) = &self.dnd_icon else {
1231+ return;
1232+ };
1233+
1234+ let icon = if let CursorImageStatus::Named(icon) = cursor_image {
1235+ icon
1236+ } else {
1237+ Default::default()
1238+ };
1239+
1240+ let pointer_pos = self.seat.get_pointer().unwrap().current_location();
1241+
1242+ let mut dnd_scale = 1;
1243+ for output in self.global_space.outputs() {
1244+ let geo = self.global_space.output_geometry(output).unwrap();
1245+
1246+ // The default cursor is rendered at the right scale for each output, which
1247+ // means that it may have a different hotspot for each output.
1248+ let output_scale = output.current_scale().integer_scale();
1249+ let cursor = self
1250+ .cursor_manager
1251+ .get_cursor_with_name(icon, output_scale)
1252+ .unwrap_or_else(|| self.cursor_manager.get_default_cursor(output_scale));
1253+
1254+ // For simplicity, we always use frame 0 for this computation. Let's hope the
1255+ // hotspot doesn't change between frames.
1256+ let hotspot = XCursor::hotspot(&cursor.frames()[0]).to_logical(output_scale);
1257+
1258+ let surface_pos = pointer_pos.to_i32_round() - hotspot;
1259+ let bbox = bbox_from_surface_tree(surface, surface_pos);
1260+
1261+ if let Some(mut overlap) = geo.intersection(bbox) {
1262+ overlap.loc -= surface_pos;
1263+ dnd_scale = dnd_scale.max(output.current_scale().integer_scale());
1264+ output_update(output, Some(overlap), surface);
1265+ } else {
1266+ output_update(output, None, surface);
1267+ }
1268+
1269+ with_states(surface, |data| {
1270+ send_surface_state(surface, data, dnd_scale, Transform::Normal);
1271+ });
1272+ }
1273+ }
12551274 }
12561275 }
12571276
@@ -1414,6 +1433,11 @@ impl Niri {
14141433 .unwrap()
14151434 .are_animations_ongoing();
14161435
1436+ // Also keep redrawing if the current cursor is animated.
1437+ state.unfinished_animations_remain |= self
1438+ .cursor_manager
1439+ .is_current_cursor_animated(output.current_scale().integer_scale());
1440+
14171441 // Render the elements.
14181442 let elements = self.render(renderer, output, true);
14191443
@@ -1495,7 +1519,7 @@ impl Niri {
14951519 //
14961520 // While we only have cursors and DnD icons crossing output boundaries though, it doesn't
14971521 // matter all that much.
1498- if let CursorImageStatus::Surface(surface) = &self.cursor_image {
1522+ if let CursorImageStatus::Surface(surface) = &self.cursor_manager.cursor_image() {
14991523 with_surface_tree_downward(
15001524 surface,
15011525 (),
@@ -1614,7 +1638,7 @@ impl Niri {
16141638 );
16151639 }
16161640
1617- if let CursorImageStatus::Surface(surface) = &self.cursor_image {
1641+ if let CursorImageStatus::Surface(surface) = &self.cursor_manager.cursor_image() {
16181642 send_dmabuf_feedback_surface_tree(
16191643 surface,
16201644 output,
@@ -1690,7 +1714,7 @@ impl Niri {
16901714 send_frames_surface_tree(surface, output, frame_callback_time, None, should_send);
16911715 }
16921716
1693- if let CursorImageStatus::Surface(surface) = &self.cursor_image {
1717+ if let CursorImageStatus::Surface(surface) = self.cursor_manager.cursor_image() {
16941718 send_frames_surface_tree(surface, output, frame_callback_time, None, should_send);
16951719 }
16961720 }
@@ -1702,7 +1726,7 @@ impl Niri {
17021726 ) -> OutputPresentationFeedback {
17031727 let mut feedback = OutputPresentationFeedback::new(output);
17041728
1705- if let CursorImageStatus::Surface(surface) = &self.cursor_image {
1729+ if let CursorImageStatus::Surface(surface) = &self.cursor_manager.cursor_image() {
17061730 take_presentation_feedback_surface_tree(
17071731 surface,
17081732 &mut feedback,
@@ -2037,7 +2061,7 @@ render_elements! {
20372061 pub OutputRenderElements<R> where R: ImportAll;
20382062 Monitor = MonitorRenderElement<R>,
20392063 Wayland = WaylandSurfaceRenderElement<R>,
2040- DefaultPointer = TextureRenderElement<<R as Renderer>::TextureId>,
2064+ NamedPointer = TextureRenderElement<<R as Renderer>::TextureId>,
20412065 SolidColor = SolidColorRenderElement,
20422066 }
20432067