Skip to main content

strata_platform/
cursor_theme.rs

1//! System Cursor Theme and Xcursor parser.
2//!
3//! Loads native cursor themes (defaulting to the host's active GNOME/Yaru cursor pack)
4//! and provides rasterization utilities for the emulated MCP cursor.
5
6use crate::window::CursorIcon;
7use std::collections::HashMap;
8use std::fs::File;
9use std::io::Read;
10use std::path::{Path, PathBuf};
11
12/// Decoded 32-bit ARGB/BGRA cursor bitmap with hotspot coordinates.
13#[derive(Debug, Clone)]
14pub struct CursorBitmap {
15    pub width: u32,
16    pub height: u32,
17    pub xhot: u32,
18    pub yhot: u32,
19    pub pixels: Vec<u8>, // 4 bytes per pixel: [B, G, R, A]
20}
21
22impl CursorBitmap {
23    /// Creates a cursor bitmap from raw pixel buffer with explicit hotspot.
24    pub fn new(width: u32, height: u32, xhot: u32, yhot: u32, pixels: Vec<u8>) -> Self {
25        Self {
26            width,
27            height,
28            xhot,
29            yhot,
30            pixels,
31        }
32    }
33
34    /// Parses an Xcursor binary image from a byte slice.
35    pub fn parse_xcursor(data: &[u8], target_size: u32) -> Option<Self> {
36        if data.len() < 16 {
37            return None;
38        }
39        let magic = u32::from_le_bytes(data[0..4].try_into().ok()?);
40        if magic != 0x72756358 {
41            // Magic 'Xcur' in little endian
42            return None;
43        }
44
45        let ntoc = u32::from_le_bytes(data[12..16].try_into().ok()?);
46        let mut best_pos = None;
47        let mut best_diff = u32::MAX;
48
49        for i in 0..ntoc as usize {
50            let offset = 16 + i * 12;
51            if offset + 12 > data.len() {
52                break;
53            }
54            let ctype = u32::from_le_bytes(data[offset..offset + 4].try_into().ok()?);
55            let subtype = u32::from_le_bytes(data[offset + 4..offset + 8].try_into().ok()?);
56            let pos = u32::from_le_bytes(data[offset + 8..offset + 12].try_into().ok()?);
57
58            if ctype == 0xfffd0002 {
59                // Image chunk
60                let diff = subtype.abs_diff(target_size);
61                if diff < best_diff {
62                    best_diff = diff;
63                    best_pos = Some(pos as usize);
64                    if diff == 0 {
65                        break;
66                    }
67                }
68            }
69        }
70
71        let pos = best_pos?;
72        if pos + 36 > data.len() {
73            return None;
74        }
75
76        let width = u32::from_le_bytes(data[pos + 16..pos + 20].try_into().ok()?);
77        let height = u32::from_le_bytes(data[pos + 20..pos + 24].try_into().ok()?);
78        let xhot = u32::from_le_bytes(data[pos + 24..pos + 28].try_into().ok()?);
79        let yhot = u32::from_le_bytes(data[pos + 28..pos + 32].try_into().ok()?);
80
81        let pixel_bytes = (width as usize) * (height as usize) * 4;
82        let pixel_start = pos + 36;
83        if pixel_start + pixel_bytes > data.len() {
84            return None;
85        }
86
87        let pixels = data[pixel_start..pixel_start + pixel_bytes].to_vec();
88
89        Some(Self {
90            width,
91            height,
92            xhot,
93            yhot,
94            pixels,
95        })
96    }
97
98    /// Loads an Xcursor binary file from disk.
99    pub fn from_file<P: AsRef<Path>>(path: P, target_size: u32) -> Option<Self> {
100        let mut file = File::open(path).ok()?;
101        let mut buffer = Vec::new();
102        file.read_to_end(&mut buffer).ok()?;
103        Self::parse_xcursor(&buffer, target_size)
104    }
105}
106
107/// Active Cursor Theme holding loaded native and fallback cursor shapes.
108#[derive(Debug, Clone)]
109pub struct CursorTheme {
110    pub name: String,
111    pub size: u32,
112    cursors: HashMap<CursorIcon, CursorBitmap>,
113}
114
115impl Default for CursorTheme {
116    fn default() -> Self {
117        Self::load_active()
118    }
119}
120
121impl CursorTheme {
122    /// Detects the host window manager cursor theme (e.g. Yaru) and loads standard sizes.
123    pub fn load_active() -> Self {
124        let theme_name = detect_host_cursor_theme().unwrap_or_else(|| "Yaru".to_string());
125        Self::load(&theme_name, 24)
126    }
127
128    /// Loads a cursor theme by name and size.
129    pub fn load(theme_name: &str, size: u32) -> Self {
130        let mut cursors = HashMap::new();
131
132        // 1. Try loading from host theme directories
133        let search_dirs = [
134            PathBuf::from(format!("/usr/share/icons/{}/cursors", theme_name)),
135            dirs_icon_theme(theme_name),
136            PathBuf::from("/usr/share/icons/Yaru/cursors"),
137            PathBuf::from("/usr/share/icons/default/cursors"),
138        ];
139
140        let icon_mappings = [
141            (CursorIcon::Default, &["default", "arrow", "left_ptr"][..]),
142            (
143                CursorIcon::Pointer,
144                &["pointer", "pointing_hand", "hand2", "hand"][..],
145            ),
146            (CursorIcon::Text, &["text", "xterm", "ibeam"][..]),
147            (CursorIcon::Crosshair, &["crosshair", "cross"][..]),
148            (CursorIcon::Move, &["move", "pointer-move", "size_all"][..]),
149            (
150                CursorIcon::NotAllowed,
151                &["not-allowed", "forbidden", "crossed_circle"][..],
152            ),
153            (CursorIcon::Grab, &["grab", "openhand"][..]),
154            (CursorIcon::Grabbing, &["grabbing", "closedhand"][..]),
155            (CursorIcon::Wait, &["wait", "watch"][..]),
156        ];
157
158        for (icon, filenames) in icon_mappings {
159            let mut loaded = None;
160            for dir in &search_dirs {
161                if !dir.exists() {
162                    continue;
163                }
164                for fname in filenames {
165                    let path = dir.join(fname);
166                    if path.exists() {
167                        if let Some(bmp) = CursorBitmap::from_file(&path, size) {
168                            loaded = Some(bmp);
169                            break;
170                        }
171                    }
172                }
173                if loaded.is_some() {
174                    break;
175                }
176            }
177
178            // If not found on disk, use embedded authentic Yaru fallback
179            let final_bmp = loaded.unwrap_or_else(|| Self::embedded_fallback(icon));
180            cursors.insert(icon, final_bmp);
181        }
182
183        Self {
184            name: theme_name.to_string(),
185            size,
186            cursors,
187        }
188    }
189
190    /// Returns the cursor bitmap for a specific icon style.
191    pub fn get(&self, icon: CursorIcon) -> &CursorBitmap {
192        if let Some(bmp) = self.cursors.get(&icon) {
193            bmp
194        } else {
195            self.cursors
196                .get(&CursorIcon::Default)
197                .expect("Default cursor must exist")
198        }
199    }
200
201    /// Renders the cursor into a Cairo graphics context with opacity and press indicator.
202    #[cfg(all(target_os = "linux", feature = "gtk-compat"))]
203    pub fn render_cairo(
204        &self,
205        cr: &cairo::Context,
206        icon: CursorIcon,
207        x: f32,
208        y: f32,
209        opacity: f32,
210        is_down: bool,
211    ) {
212        if opacity <= 0.001 {
213            return;
214        }
215
216        let bmp = self.get(icon);
217        let draw_x = (x - bmp.xhot as f32) as f64;
218        let draw_y = (y - bmp.yhot as f32) as f64;
219
220        if let Ok(mut surface) =
221            cairo::ImageSurface::create(cairo::Format::ARgb32, bmp.width as i32, bmp.height as i32)
222        {
223            if let Ok(mut data) = surface.data() {
224                if data.len() == bmp.pixels.len() {
225                    data.copy_from_slice(&bmp.pixels);
226                }
227            }
228
229            let _ = cr.save();
230
231            // When mouse is pressed down, draw subtle touch feedback ring
232            if is_down {
233                cr.set_source_rgba(0.23, 0.51, 0.96, 0.45 * opacity as f64);
234                cr.arc(x as f64, y as f64, 7.0, 0.0, 2.0 * std::f64::consts::PI);
235                let _ = cr.fill();
236
237                cr.set_source_rgba(1.0, 1.0, 1.0, 0.8 * opacity as f64);
238                cr.set_line_width(1.5);
239                cr.arc(x as f64, y as f64, 7.0, 0.0, 2.0 * std::f64::consts::PI);
240                let _ = cr.stroke();
241            }
242
243            let _ = cr.set_source_surface(&surface, draw_x, draw_y);
244            if (opacity - 1.0).abs() < 0.001 {
245                let _ = cr.paint();
246            } else {
247                let _ = cr.paint_with_alpha(opacity as f64);
248            }
249
250            let _ = cr.restore();
251        }
252    }
253
254    /// Renders the cursor into a software BGRA32 pixel buffer with alpha blending.
255    pub fn render_software(
256        &self,
257        buffer: &mut [u32],
258        buf_width: usize,
259        buf_height: usize,
260        icon: CursorIcon,
261        x: f32,
262        y: f32,
263        opacity: f32,
264        is_down: bool,
265    ) {
266        if opacity <= 0.001 {
267            return;
268        }
269
270        let bmp = self.get(icon);
271        let start_x = (x as i32) - (bmp.xhot as i32);
272        let start_y = (y as i32) - (bmp.yhot as i32);
273
274        // Render touch indicator ring if mouse down
275        if is_down {
276            let cx = x as i32;
277            let cy = y as i32;
278            let r_sq = 49; // 7px radius squared
279            for dy in -7..=7 {
280                for dx in -7..=7 {
281                    let d = dx * dx + dy * dy;
282                    if d <= r_sq {
283                        let px = cx + dx;
284                        let py = cy + dy;
285                        if px >= 0 && px < buf_width as i32 && py >= 0 && py < buf_height as i32 {
286                            let idx = (py as usize) * buf_width + (px as usize);
287                            if let Some(target) = buffer.get_mut(idx) {
288                                // Blend translucent blue touch highlight
289                                let ring_alpha = if d > 25 {
290                                    0.8 * opacity
291                                } else {
292                                    0.45 * opacity
293                                };
294                                *target = blend_pixel_bgra(*target, 0x3b82f6, ring_alpha);
295                            }
296                        }
297                    }
298                }
299            }
300        }
301
302        for cy in 0..bmp.height as i32 {
303            for cx in 0..bmp.width as i32 {
304                let target_x = start_x + cx;
305                let target_y = start_y + cy;
306
307                if target_x >= 0
308                    && target_x < buf_width as i32
309                    && target_y >= 0
310                    && target_y < buf_height as i32
311                {
312                    let src_idx = ((cy as usize) * (bmp.width as usize) + (cx as usize)) * 4;
313                    let b = bmp.pixels[src_idx] as u32;
314                    let g = bmp.pixels[src_idx + 1] as u32;
315                    let r = bmp.pixels[src_idx + 2] as u32;
316                    let a = bmp.pixels[src_idx + 3] as f32 / 255.0;
317
318                    let final_alpha = (a * opacity).clamp(0.0, 1.0);
319                    if final_alpha > 0.001 {
320                        let dst_idx = (target_y as usize) * buf_width + (target_x as usize);
321                        if let Some(dst) = buffer.get_mut(dst_idx) {
322                            let src_color = (r << 16) | (g << 8) | b;
323                            *dst = blend_pixel_bgra(*dst, src_color, final_alpha);
324                        }
325                    }
326                }
327            }
328        }
329    }
330
331    /// Authentic embedded Yaru cursor pixel data fallback.
332    fn embedded_fallback(icon: CursorIcon) -> CursorBitmap {
333        match icon {
334            CursorIcon::Pointer => CursorBitmap::new(
335                24,
336                24,
337                8,
338                5,
339                include_bytes!("../assets/yaru/pointer.bin").to_vec(),
340            ),
341            CursorIcon::Text => CursorBitmap::new(
342                24,
343                24,
344                11,
345                12,
346                include_bytes!("../assets/yaru/text.bin").to_vec(),
347            ),
348            CursorIcon::Crosshair => CursorBitmap::new(
349                24,
350                24,
351                11,
352                11,
353                include_bytes!("../assets/yaru/crosshair.bin").to_vec(),
354            ),
355            CursorIcon::NotAllowed => CursorBitmap::new(
356                24,
357                24,
358                12,
359                12,
360                include_bytes!("../assets/yaru/not-allowed.bin").to_vec(),
361            ),
362            CursorIcon::Grab => CursorBitmap::new(
363                24,
364                24,
365                11,
366                7,
367                include_bytes!("../assets/yaru/grab.bin").to_vec(),
368            ),
369            CursorIcon::Grabbing => CursorBitmap::new(
370                24,
371                24,
372                12,
373                11,
374                include_bytes!("../assets/yaru/grabbing.bin").to_vec(),
375            ),
376            _ => CursorBitmap::new(
377                24,
378                24,
379                4,
380                4,
381                include_bytes!("../assets/yaru/default.bin").to_vec(),
382            ),
383        }
384    }
385}
386
387/// Blends a source RGB color onto a destination BGRA/ARGB 32-bit pixel.
388#[inline]
389fn blend_pixel_bgra(dst: u32, src_rgb: u32, alpha: f32) -> u32 {
390    let dst_r = ((dst >> 16) & 0xFF) as f32;
391    let dst_g = ((dst >> 8) & 0xFF) as f32;
392    let dst_b = (dst & 0xFF) as f32;
393
394    let src_r = ((src_rgb >> 16) & 0xFF) as f32;
395    let src_g = ((src_rgb >> 8) & 0xFF) as f32;
396    let src_b = (src_rgb & 0xFF) as f32;
397
398    let out_r = (src_r * alpha + dst_r * (1.0 - alpha)).clamp(0.0, 255.0) as u32;
399    let out_g = (src_g * alpha + dst_g * (1.0 - alpha)).clamp(0.0, 255.0) as u32;
400    let out_b = (src_b * alpha + dst_b * (1.0 - alpha)).clamp(0.0, 255.0) as u32;
401
402    0xFF000000 | (out_r << 16) | (out_g << 8) | out_b
403}
404
405fn dirs_icon_theme(theme_name: &str) -> PathBuf {
406    if let Ok(home) = std::env::var("HOME") {
407        PathBuf::from(home)
408            .join(".icons")
409            .join(theme_name)
410            .join("cursors")
411    } else {
412        PathBuf::from("/tmp")
413    }
414}
415
416fn detect_host_cursor_theme() -> Option<String> {
417    if let Ok(theme) = std::env::var("XCURSOR_THEME") {
418        if !theme.is_empty() {
419            return Some(theme);
420        }
421    }
422
423    #[cfg(target_os = "linux")]
424    {
425        // Try reading gsettings if available
426        if let Ok(output) = std::process::Command::new("gsettings")
427            .args(["get", "org.gnome.desktop.interface", "cursor-theme"])
428            .output()
429        {
430            if output.status.success() {
431                let s = String::from_utf8_lossy(&output.stdout);
432                let cleaned = s.trim().trim_matches('\'').trim_matches('"');
433                if !cleaned.is_empty() {
434                    return Some(cleaned.to_string());
435                }
436            }
437        }
438    }
439
440    None
441}