forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBdde9214Ivan Molodetskikh1 year ago1835 commits

cursor.rs315 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
79 .get_cursor_with_name(icon, scale)
80 .map(|cursor| RenderCursor::Named {
81 icon,
82 scale,
83 cursor,
84 })
85 .unwrap_or_else(|| RenderCursor::Named {
86 icon: Default::default(),
87 scale,
88 cursor: self.get_default_cursor(scale),
89 }),
90 }
91 }
92
93 pub fn is_current_cursor_animated(&self, scale: i32) -> bool {
94 match &self.current_cursor {
95 CursorImageStatus::Hidden => false,
96 CursorImageStatus::Surface(_) => false,
97 CursorImageStatus::Named(icon) => self
98 .get_cursor_with_name(*icon, scale)
99 .unwrap_or_else(|| self.get_default_cursor(scale))
100 .is_animated_cursor(),
101 }
102 }
103
104 /// Get named cursor for the given `icon` and `scale`.
105 pub fn get_cursor_with_name(&self, icon: CursorIcon, scale: i32) -> Option<Rc<XCursor>> {
106 self.named_cursor_cache
107 .borrow_mut()
108 .entry((icon, scale))
109 .or_insert_with_key(|(icon, scale)| {
110 let size = self.size as i32 * scale;
111 let mut cursor = Self::load_xcursor(&self.theme, icon.name(), size);
112
113 // Check alternative names to account for non-compliant themes.
114 if cursor.is_err() {
115 for name in icon.alt_names() {
116 cursor = Self::load_xcursor(&self.theme, name, size);
117 if cursor.is_ok() {
118 break;
119 }
120 }
121 }
122
123 if let Err(err) = &cursor {
124 warn!("error loading xcursor {}@{size}: {err:?}", icon.name());
125 }
126
127 // The default cursor must always have a fallback.
128 if *icon == CursorIcon::Default && cursor.is_err() {
129 cursor = Ok(Self::fallback_cursor());
130 }
131
132 cursor.ok().map(Rc::new)
133 })
134 .clone()
135 }
136
137 /// Get default cursor.
138 pub fn get_default_cursor(&self, scale: i32) -> Rc<XCursor> {
139 // The default cursor always has a fallback.
140 self.get_cursor_with_name(CursorIcon::Default, scale)
141 .unwrap()
142 }
143
144 /// Currently used cursor_image as a cursor provider.
145 pub fn cursor_image(&self) -> &CursorImageStatus {
146 &self.current_cursor
147 }
148
149 /// Set new cursor image provider.
150 pub fn set_cursor_image(&mut self, cursor: CursorImageStatus) {
151 self.current_cursor = cursor;
152 }
153
154 /// Load the cursor with the given `name` from the file system picking the closest
155 /// one to the given `size`.
156 fn load_xcursor(theme: &CursorTheme, name: &str, size: i32) -> anyhow::Result<XCursor> {
157 let _span = tracy_client::span!("load_xcursor");
158
159 let path = theme
160 .load_icon(name)
161 .ok_or_else(|| anyhow!("no default icon"))?;
162
163 let mut file = File::open(path).context("error opening cursor icon file")?;
164 let mut buf = vec![];
165 file.read_to_end(&mut buf)
166 .context("error reading cursor icon file")?;
167
168 let mut images = parse_xcursor(&buf).context("error parsing cursor icon file")?;
169
170 let (width, height) = images
171 .iter()
172 .min_by_key(|image| (size - image.size as i32).abs())
173 .map(|image| (image.width, image.height))
174 .unwrap();
175
176 images.retain(move |image| image.width == width && image.height == height);
177
178 let animation_duration = images.iter().fold(0, |acc, image| acc + image.delay);
179
180 Ok(XCursor {
181 images,
182 animation_duration,
183 })
184 }
185
186 /// Set the common XCURSOR env variables.
187 fn ensure_env(theme: &str, size: u8) {
188 env::set_var("XCURSOR_THEME", theme);
189 env::set_var("XCURSOR_SIZE", size.to_string());
190 }
191
192 fn fallback_cursor() -> XCursor {
193 let images = vec![Image {
194 size: 32,
195 width: 64,
196 height: 64,
197 xhot: 1,
198 yhot: 1,
199 delay: 0,
200 pixels_rgba: Vec::from(FALLBACK_CURSOR_DATA),
201 pixels_argb: vec![],
202 }];
203
204 XCursor {
205 images,
206 animation_duration: 0,
207 }
208 }
209}
210
211/// The cursor prepared for renderer.
212pub enum RenderCursor {
213 Hidden,
214 Surface {
215 hotspot: Point<i32, Logical>,
216 surface: WlSurface,
217 },
218 Named {
219 icon: CursorIcon,
220 scale: i32,
221 cursor: Rc<XCursor>,
222 },
223}
224
225type TextureCache = HashMap<(CursorIcon, i32), Vec<MemoryRenderBuffer>>;
226
227#[derive(Default)]
228pub struct CursorTextureCache {
229 cache: RefCell<TextureCache>,
230}
231
232impl CursorTextureCache {
233 pub fn clear(&mut self) {
234 self.cache.get_mut().clear();
235 }
236
237 pub fn get(
238 &self,
239 icon: CursorIcon,
240 scale: i32,
241 cursor: &XCursor,
242 idx: usize,
243 ) -> MemoryRenderBuffer {
244 self.cache
245 .borrow_mut()
246 .entry((icon, scale))
247 .or_insert_with(|| {
248 cursor
249 .frames()
250 .iter()
251 .map(|frame| {
252 MemoryRenderBuffer::from_slice(
253 &frame.pixels_rgba,
254 Fourcc::Argb8888,
255 (frame.width as i32, frame.height as i32),
256 scale,
257 Transform::Normal,
258 None,
259 )
260 })
261 .collect()
262 })[idx]
263 .clone()
264 }
265}
266
267// The XCursorBuffer implementation is inspired by `wayland-rs`, thus provided under MIT license.
268
269/// The state of the `NamedCursor`.
270pub struct XCursor {
271 /// The image for the underlying named cursor.
272 images: Vec<Image>,
273 /// The total duration of the animation.
274 animation_duration: u32,
275}
276
277impl XCursor {
278 /// Given a time, calculate which frame to show, and how much time remains until the next frame.
279 ///
280 /// Time will wrap, so if for instance the cursor has an animation lasting 100ms,
281 /// then calling this function with 5ms and 105ms as input gives the same output.
282 pub fn frame(&self, mut millis: u32) -> (usize, &Image) {
283 if self.animation_duration == 0 {
284 return (0, &self.images[0]);
285 }
286
287 millis %= self.animation_duration;
288
289 let mut res = 0;
290 for (i, img) in self.images.iter().enumerate() {
291 if millis < img.delay {
292 res = i;
293 break;
294 }
295 millis -= img.delay;
296 }
297
298 (res, &self.images[res])
299 }
300
301 /// Get the frames for the given `XCursor`.
302 pub fn frames(&self) -> &[Image] {
303 &self.images
304 }
305
306 /// Check whether the cursor is animated.
307 pub fn is_animated_cursor(&self) -> bool {
308 self.images.len() > 1
309 }
310
311 /// Get hotspot for the given `image`.
312 pub fn hotspot(image: &Image) -> Point<i32, Physical> {
313 (image.xhot as i32, image.yhot as i32).into()
314 }
315}