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