forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBe259061Ivan Molodetskikh2 years ago424 commits

cursor.rs323 lines, 10.0 KiBHistoryRawDownload
1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::env;
4use std::fs::File;
5use std::io::Read;
6use std::rc::Rc;
7use std::sync::Mutex;
8
9use anyhow::{anyhow, Context};
10use smithay::backend::allocator::Fourcc;
11use smithay::backend::renderer::element::texture::TextureBuffer;
12use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
13use smithay::input::pointer::{CursorIcon, CursorImageAttributes, CursorImageStatus};
14use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
15use smithay::utils::{IsAlive, Logical, Physical, Point, Transform};
16use smithay::wayland::compositor::with_states;
17use xcursor::parser::{parse_xcursor, Image};
18use xcursor::CursorTheme;
19
20/// Some default looking `left_ptr` icon.
21static FALLBACK_CURSOR_DATA: &[u8] = include_bytes!("../resources/cursor.rgba");
22
23type XCursorCache = HashMap<(CursorIcon, i32), Option<Rc<XCursor>>>;
24
25pub struct CursorManager {
26 theme: CursorTheme,
27 size: u8,
28 current_cursor: CursorImageStatus,
29 named_cursor_cache: RefCell<XCursorCache>,
30}
31
32impl 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
115 // Check alternative names to account for non-compliant themes.
116 if cursor.is_err() {
117 for name in icon.alt_names() {
118 cursor = Self::load_xcursor(&self.theme, name, size);
119 if cursor.is_ok() {
120 break;
121 }
122 }
123 }
124
125 if let Err(err) = &cursor {
126 warn!("error loading xcursor {}@{size}: {err:?}", icon.name());
127 }
128
129 // The default cursor must always have a fallback.
130 if *icon == CursorIcon::Default && cursor.is_err() {
131 cursor = Ok(Self::fallback_cursor());
132 }
133
134 cursor.ok().map(Rc::new)
135 })
136 .clone()
137 }
138
139 /// Get default cursor.
140 pub fn get_default_cursor(&self, scale: i32) -> Rc<XCursor> {
141 // The default cursor always has a fallback.
142 self.get_cursor_with_name(CursorIcon::Default, scale)
143 .unwrap()
144 }
145
146 /// Currenly used cursor_image as a cursor provider.
147 pub fn cursor_image(&self) -> &CursorImageStatus {
148 &self.current_cursor
149 }
150
151 /// Set new cursor image provider.
152 pub fn set_cursor_image(&mut self, cursor: CursorImageStatus) {
153 self.current_cursor = cursor;
154 }
155
156 /// Load the cursor with the given `name` from the file system picking the closest
157 /// one to the given `size`.
158 fn load_xcursor(theme: &CursorTheme, name: &str, size: i32) -> anyhow::Result<XCursor> {
159 let _span = tracy_client::span!("load_xcursor");
160
161 let path = theme
162 .load_icon(name)
163 .ok_or_else(|| anyhow!("no default icon"))?;
164
165 let mut file = File::open(path).context("error opening cursor icon file")?;
166 let mut buf = vec![];
167 file.read_to_end(&mut buf)
168 .context("error reading cursor icon file")?;
169
170 let mut images = parse_xcursor(&buf).context("error parsing cursor icon file")?;
171
172 let (width, height) = images
173 .iter()
174 .min_by_key(|image| (size - image.size as i32).abs())
175 .map(|image| (image.width, image.height))
176 .unwrap();
177
178 images.retain(move |image| image.width == width && image.height == height);
179
180 let animation_duration = images.iter().fold(0, |acc, image| acc + image.delay);
181
182 Ok(XCursor {
183 images,
184 animation_duration,
185 })
186 }
187
188 /// Set the common XCURSOR env variables.
189 fn ensure_env(theme: &str, size: u8) {
190 env::set_var("XCURSOR_THEME", theme);
191 env::set_var("XCURSOR_SIZE", size.to_string());
192 }
193
194 fn fallback_cursor() -> XCursor {
195 let images = vec![Image {
196 size: 32,
197 width: 64,
198 height: 64,
199 xhot: 1,
200 yhot: 1,
201 delay: 0,
202 pixels_rgba: Vec::from(FALLBACK_CURSOR_DATA),
203 pixels_argb: vec![],
204 }];
205
206 XCursor {
207 images,
208 animation_duration: 0,
209 }
210 }
211}
212
213/// The cursor prepared for renderer.
214pub enum RenderCursor {
215 Hidden,
216 Surface {
217 hotspot: Point<i32, Logical>,
218 surface: WlSurface,
219 },
220 Named {
221 icon: CursorIcon,
222 scale: i32,
223 cursor: Rc<XCursor>,
224 },
225}
226
227type TextureCache = HashMap<(CursorIcon, i32), Vec<TextureBuffer<GlesTexture>>>;
228
229#[derive(Default)]
230pub struct CursorTextureCache {
231 cache: RefCell<TextureCache>,
232}
233
234impl CursorTextureCache {
235 pub fn clear(&mut self) {
236 self.cache.get_mut().clear();
237 }
238
239 pub fn get(
240 &self,
241 renderer: &mut GlesRenderer,
242 icon: CursorIcon,
243 scale: i32,
244 cursor: &XCursor,
245 idx: usize,
246 ) -> TextureBuffer<GlesTexture> {
247 self.cache
248 .borrow_mut()
249 .entry((icon, scale))
250 .or_insert_with(|| {
251 cursor
252 .frames()
253 .iter()
254 .map(|frame| {
255 let _span = tracy_client::span!("create TextureBuffer");
256
257 TextureBuffer::from_memory(
258 renderer,
259 &frame.pixels_rgba,
260 Fourcc::Abgr8888,
261 (frame.width as i32, frame.height as i32),
262 false,
263 scale,
264 Transform::Normal,
265 None,
266 )
267 .unwrap()
268 })
269 .collect()
270 })[idx]
271 .clone()
272 }
273}
274
275// The XCursorBuffer implementation is inspired by `wayland-rs`, thus provided under MIT license.
276
277/// The state of the `NamedCursor`.
278pub struct XCursor {
279 /// The image for the underlying named cursor.
280 images: Vec<Image>,
281 /// The total duration of the animation.
282 animation_duration: u32,
283}
284
285impl XCursor {
286 /// Given a time, calculate which frame to show, and how much time remains until the next frame.
287 ///
288 /// Time will wrap, so if for instance the cursor has an animation lasting 100ms,
289 /// then calling this function with 5ms and 105ms as input gives the same output.
290 pub fn frame(&self, mut millis: u32) -> (usize, &Image) {
291 if self.animation_duration == 0 {
292 return (0, &self.images[0]);
293 }
294
295 millis %= self.animation_duration;
296
297 let mut res = 0;
298 for (i, img) in self.images.iter().enumerate() {
299 if millis < img.delay {
300 res = i;
301 break;
302 }
303 millis -= img.delay;
304 }
305
306 (res, &self.images[res])
307 }
308
309 /// Get the frames for the given `XCursor`.
310 pub fn frames(&self) -> &[Image] {
311 &self.images
312 }
313
314 /// Check whether the cursor is animated.
315 pub fn is_animated_cursor(&self) -> bool {
316 self.images.len() > 1
317 }
318
319 /// Get hotspot for the given `image`.
320 pub fn hotspot(image: &Image) -> Point<i32, Physical> {
321 (image.xhot as i32, image.yhot as i32).into()
322 }
323}