forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB6c9705dIvan Molodetskikh1 year ago2085 commits

cursor.rs318 lines, 9.7 KiBHistoryRawDownload
1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::env;
4use std::fs::File;
5use std::io::Read;
6use std::rc::Rc;
7
8use anyhow::{anyhow, Context};
9use smithay::backend::allocator::Fourcc;
10use smithay::backend::renderer::element::memory::MemoryRenderBuffer;
11use smithay::input::pointer::{CursorIcon, CursorImageStatus, CursorImageSurfaceData};
12use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
13use smithay::utils::{IsAlive, Logical, Physical, Point, Transform};
14use smithay::wayland::compositor::with_states;
15use xcursor::parser::{parse_xcursor, Image};
16use xcursor::CursorTheme;
17
18/// Some default looking `left_ptr` icon.
19static FALLBACK_CURSOR_DATA: &[u8] = include_bytes!("../resources/cursor.rgba");
20
21type XCursorCache = HashMap<(CursorIcon, i32), Option<Rc<XCursor>>>;
22
23pub struct CursorManager {
24 theme: CursorTheme,
25 size: u8,
26 current_cursor: CursorImageStatus,
27 named_cursor_cache: RefCell<XCursorCache>,
28}
29
30impl CursorManager {
31 pub fn new(theme: &str, size: u8) -> Self {
32 Self::ensure_env(theme, size);
33
34 let theme = CursorTheme::load(theme);
35
36 Self {
37 theme,
38 size,
39 current_cursor: CursorImageStatus::default_named(),
40 named_cursor_cache: Default::default(),
41 }
42 }
43
44 /// Reload the cursor theme.
45 pub fn reload(&mut self, theme: &str, size: u8) {
46 Self::ensure_env(theme, size);
47 self.theme = CursorTheme::load(theme);
48 self.size = size;
49 self.named_cursor_cache.get_mut().clear();
50 }
51
52 /// Checks if the cursor WlSurface is alive, and if not, cleans it up.
53 pub fn check_cursor_image_surface_alive(&mut self) {
54 if let CursorImageStatus::Surface(surface) = &self.current_cursor {
55 if !surface.alive() {
56 self.current_cursor = CursorImageStatus::default_named();
57 }
58 }
59 }
60
61 /// Get the current rendering cursor.
62 pub fn get_render_cursor(&self, scale: i32) -> RenderCursor {
63 match self.current_cursor.clone() {
64 CursorImageStatus::Hidden => RenderCursor::Hidden,
65 CursorImageStatus::Surface(surface) => {
66 let hotspot = with_states(&surface, |states| {
67 states
68 .data_map
69 .get::<CursorImageSurfaceData>()
70 .unwrap()
71 .lock()
72 .unwrap()
73 .hotspot
74 });
75
76 RenderCursor::Surface { hotspot, surface }
77 }
78 CursorImageStatus::Named(icon) => self.get_render_cursor_named(icon, scale),
79 }
80 }
81
82 fn get_render_cursor_named(&self, icon: CursorIcon, scale: i32) -> RenderCursor {
83 self.get_cursor_with_name(icon, scale)
84 .map(|cursor| RenderCursor::Named {
85 icon,
86 scale,
87 cursor,
88 })
89 .unwrap_or_else(|| RenderCursor::Named {
90 icon: Default::default(),
91 scale,
92 cursor: self.get_default_cursor(scale),
93 })
94 }
95
96 pub fn is_current_cursor_animated(&self, scale: i32) -> bool {
97 match &self.current_cursor {
98 CursorImageStatus::Hidden => false,
99 CursorImageStatus::Surface(_) => false,
100 CursorImageStatus::Named(icon) => self
101 .get_cursor_with_name(*icon, scale)
102 .unwrap_or_else(|| self.get_default_cursor(scale))
103 .is_animated_cursor(),
104 }
105 }
106
107 /// Get named cursor for the given `icon` and `scale`.
108 pub fn get_cursor_with_name(&self, icon: CursorIcon, scale: i32) -> Option<Rc<XCursor>> {
109 self.named_cursor_cache
110 .borrow_mut()
111 .entry((icon, scale))
112 .or_insert_with_key(|(icon, scale)| {
113 let size = self.size as i32 * scale;
114 let mut cursor = Self::load_xcursor(&self.theme, icon.name(), size);
115
116 // Check alternative names to account for non-compliant themes.
117 if cursor.is_err() {
118 for name in icon.alt_names() {
119 cursor = Self::load_xcursor(&self.theme, name, size);
120 if cursor.is_ok() {
121 break;
122 }
123 }
124 }
125
126 if let Err(err) = &cursor {
127 warn!("error loading xcursor {}@{size}: {err:?}", icon.name());
128 }
129
130 // The default cursor must always have a fallback.
131 if *icon == CursorIcon::Default && cursor.is_err() {
132 cursor = Ok(Self::fallback_cursor());
133 }
134
135 cursor.ok().map(Rc::new)
136 })
137 .clone()
138 }
139
140 /// Get default cursor.
141 pub fn get_default_cursor(&self, scale: i32) -> Rc<XCursor> {
142 // The default cursor always has a fallback.
143 self.get_cursor_with_name(CursorIcon::Default, scale)
144 .unwrap()
145 }
146
147 /// Currently used cursor_image as a cursor provider.
148 pub fn cursor_image(&self) -> &CursorImageStatus {
149 &self.current_cursor
150 }
151
152 /// Set new cursor image provider.
153 pub fn set_cursor_image(&mut self, cursor: CursorImageStatus) {
154 self.current_cursor = cursor;
155 }
156
157 /// Load the cursor with the given `name` from the file system picking the closest
158 /// one to the given `size`.
159 fn load_xcursor(theme: &CursorTheme, name: &str, size: i32) -> anyhow::Result<XCursor> {
160 let _span = tracy_client::span!("load_xcursor");
161
162 let path = theme
163 .load_icon(name)
164 .ok_or_else(|| anyhow!("no default icon"))?;
165
166 let mut file = File::open(path).context("error opening cursor icon file")?;
167 let mut buf = vec![];
168 file.read_to_end(&mut buf)
169 .context("error reading cursor icon file")?;
170
171 let mut images = parse_xcursor(&buf).context("error parsing cursor icon file")?;
172
173 let (width, height) = images
174 .iter()
175 .min_by_key(|image| (size - image.size as i32).abs())
176 .map(|image| (image.width, image.height))
177 .unwrap();
178
179 images.retain(move |image| image.width == width && image.height == height);
180
181 let animation_duration = images.iter().fold(0, |acc, image| acc + image.delay);
182
183 Ok(XCursor {
184 images,
185 animation_duration,
186 })
187 }
188
189 /// Set the common XCURSOR env variables.
190 fn ensure_env(theme: &str, size: u8) {
191 env::set_var("XCURSOR_THEME", theme);
192 env::set_var("XCURSOR_SIZE", size.to_string());
193 }
194
195 fn fallback_cursor() -> XCursor {
196 let images = vec![Image {
197 size: 32,
198 width: 64,
199 height: 64,
200 xhot: 1,
201 yhot: 1,
202 delay: 0,
203 pixels_rgba: Vec::from(FALLBACK_CURSOR_DATA),
204 pixels_argb: vec![],
205 }];
206
207 XCursor {
208 images,
209 animation_duration: 0,
210 }
211 }
212}
213
214/// The cursor prepared for renderer.
215pub enum RenderCursor {
216 Hidden,
217 Surface {
218 hotspot: Point<i32, Logical>,
219 surface: WlSurface,
220 },
221 Named {
222 icon: CursorIcon,
223 scale: i32,
224 cursor: Rc<XCursor>,
225 },
226}
227
228type TextureCache = HashMap<(CursorIcon, i32), Vec<MemoryRenderBuffer>>;
229
230#[derive(Default)]
231pub struct CursorTextureCache {
232 cache: RefCell<TextureCache>,
233}
234
235impl CursorTextureCache {
236 pub fn clear(&mut self) {
237 self.cache.get_mut().clear();
238 }
239
240 pub fn get(
241 &self,
242 icon: CursorIcon,
243 scale: i32,
244 cursor: &XCursor,
245 idx: usize,
246 ) -> MemoryRenderBuffer {
247 self.cache
248 .borrow_mut()
249 .entry((icon, scale))
250 .or_insert_with(|| {
251 cursor
252 .frames()
253 .iter()
254 .map(|frame| {
255 MemoryRenderBuffer::from_slice(
256 &frame.pixels_rgba,
257 Fourcc::Argb8888,
258 (frame.width as i32, frame.height as i32),
259 scale,
260 Transform::Normal,
261 None,
262 )
263 })
264 .collect()
265 })[idx]
266 .clone()
267 }
268}
269
270// The XCursorBuffer implementation is inspired by `wayland-rs`, thus provided under MIT license.
271
272/// The state of the `NamedCursor`.
273pub struct XCursor {
274 /// The image for the underlying named cursor.
275 images: Vec<Image>,
276 /// The total duration of the animation.
277 animation_duration: u32,
278}
279
280impl XCursor {
281 /// Given a time, calculate which frame to show, and how much time remains until the next frame.
282 ///
283 /// Time will wrap, so if for instance the cursor has an animation lasting 100ms,
284 /// then calling this function with 5ms and 105ms as input gives the same output.
285 pub fn frame(&self, mut millis: u32) -> (usize, &Image) {
286 if self.animation_duration == 0 {
287 return (0, &self.images[0]);
288 }
289
290 millis %= self.animation_duration;
291
292 let mut res = 0;
293 for (i, img) in self.images.iter().enumerate() {
294 if millis < img.delay {
295 res = i;
296 break;
297 }
298 millis -= img.delay;
299 }
300
301 (res, &self.images[res])
302 }
303
304 /// Get the frames for the given `XCursor`.
305 pub fn frames(&self) -> &[Image] {
306 &self.images
307 }
308
309 /// Check whether the cursor is animated.
310 pub fn is_animated_cursor(&self) -> bool {
311 self.images.len() > 1
312 }
313
314 /// Get hotspot for the given `image`.
315 pub fn hotspot(image: &Image) -> Point<i32, Physical> {
316 (image.xhot as i32, image.yhot as i32).into()
317 }
318}