cursor.rs

 1use crate::Globals;
 2use util::ResultExt;
 3
 4use wayland_client::protocol::wl_pointer::WlPointer;
 5use wayland_client::protocol::wl_surface::WlSurface;
 6use wayland_client::Connection;
 7use wayland_cursor::{CursorImageBuffer, CursorTheme};
 8
 9pub(crate) struct Cursor {
10    theme: Option<CursorTheme>,
11    current_icon_name: String,
12    surface: WlSurface,
13    serial_id: u32,
14}
15
16impl Drop for Cursor {
17    fn drop(&mut self) {
18        self.theme.take();
19        self.surface.destroy();
20    }
21}
22
23impl Cursor {
24    pub fn new(connection: &Connection, globals: &Globals, size: u32) -> Self {
25        Self {
26            theme: CursorTheme::load(&connection, globals.shm.clone(), size).log_err(),
27            current_icon_name: "default".to_string(),
28            surface: globals.compositor.create_surface(&globals.qh, ()),
29            serial_id: 0,
30        }
31    }
32
33    pub fn set_serial_id(&mut self, serial_id: u32) {
34        self.serial_id = serial_id;
35    }
36
37    pub fn set_icon(&mut self, wl_pointer: &WlPointer, mut cursor_icon_name: Option<&str>) {
38        let mut cursor_icon_name = cursor_icon_name.unwrap_or("default");
39        if self.current_icon_name != cursor_icon_name {
40            if let Some(theme) = &mut self.theme {
41                let mut buffer: Option<&CursorImageBuffer>;
42
43                if let Some(cursor) = theme.get_cursor(&cursor_icon_name) {
44                    buffer = Some(&cursor[0]);
45                } else if let Some(cursor) = theme.get_cursor("default") {
46                    buffer = Some(&cursor[0]);
47                    cursor_icon_name = "default";
48                    log::warn!(
49                        "Linux: Wayland: Unable to get cursor icon: {}. Using default cursor icon",
50                        cursor_icon_name
51                    );
52                } else {
53                    buffer = None;
54                    log::warn!("Linux: Wayland: Unable to get default cursor too!");
55                }
56
57                if let Some(buffer) = &mut buffer {
58                    let (width, height) = buffer.dimensions();
59                    let (hot_x, hot_y) = buffer.hotspot();
60
61                    wl_pointer.set_cursor(
62                        self.serial_id,
63                        Some(&self.surface),
64                        hot_x as i32,
65                        hot_y as i32,
66                    );
67                    self.surface.attach(Some(&buffer), 0, 0);
68                    self.surface.damage(0, 0, width as i32, height as i32);
69                    self.surface.commit();
70
71                    self.current_icon_name = cursor_icon_name.to_string();
72                }
73            } else {
74                log::warn!("Linux: Wayland: Unable to load cursor themes");
75            }
76        }
77    }
78}