Skip to content

Commit

Permalink
Add cursor-shape protocol
Browse files Browse the repository at this point in the history
  • Loading branch information
kchibisov committed Oct 28, 2023
1 parent 345428b commit 80318ee
Show file tree
Hide file tree
Showing 4 changed files with 383 additions and 185 deletions.
295 changes: 212 additions & 83 deletions src/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,113 +2,242 @@ use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::Read;
use std::sync::Mutex;

use anyhow::{anyhow, Context};
use smithay::backend::allocator::Fourcc;
use smithay::backend::renderer::element::texture::TextureBuffer;
use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
use smithay::utils::{Physical, Point, Transform};
use smithay::backend::renderer::gles::GlesTexture;
use smithay::input::pointer::{CursorIcon, CursorImageAttributes, CursorImageStatus};
use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
use smithay::reexports::wayland_server::Resource;
use smithay::utils::{Logical, Point};
use smithay::wayland::compositor::with_states;
use xcursor::parser::{parse_xcursor, Image};
use xcursor::CursorTheme;

/// Some default looking `left_ptr` icon.
static FALLBACK_CURSOR_DATA: &[u8] = include_bytes!("../resources/cursor.rgba");

pub struct Cursor {
images: Vec<Image>,
size: i32,
cache: HashMap<i32, (TextureBuffer<GlesTexture>, Point<i32, Physical>)>,
pub struct CursorManager {
theme: CursorTheme,
size: u8,
current_cursor: CursorImageStatus,
named_cursor_cache: HashMap<(CursorIcon, i32), Option<XCursor>>,
}

impl Cursor {
/// Load the said theme as well as set the `XCURSOR_THEME` and `XCURSOR_SIZE`
/// env variables.
pub fn load(theme: &str, size: u8) -> Self {
env::set_var("XCURSOR_THEME", theme);
env::set_var("XCURSOR_SIZE", size.to_string());
impl CursorManager {
pub fn new(theme: &str, size: u8) -> Self {
Self::ensure_env(theme, size);

let images = match load_xcursor(theme) {
Ok(images) => images,
Err(err) => {
warn!("error loading xcursor default cursor: {err:?}");

vec![Image {
size: 32,
width: 64,
height: 64,
xhot: 1,
yhot: 1,
delay: 1,
pixels_rgba: Vec::from(FALLBACK_CURSOR_DATA),
pixels_argb: vec![],
}]
}
};
let theme = CursorTheme::load(theme);

Self {
images,
size: size as i32,
cache: HashMap::new(),
theme,
size,
current_cursor: CursorImageStatus::default_named(),
named_cursor_cache: Default::default(),
}
}

pub fn get(
&mut self,
renderer: &mut GlesRenderer,
scale: i32,
) -> (TextureBuffer<GlesTexture>, Point<i32, Physical>) {
self.cache
.entry(scale)
.or_insert_with_key(|scale| {
let _span = tracy_client::span!("create cursor texture");

let size = self.size * scale;

let nearest_image = self
.images
.iter()
.min_by_key(|image| (size - image.size as i32).abs())
.unwrap();
let frame = self
.images
.iter()
.find(move |image| {
image.width == nearest_image.width && image.height == nearest_image.height
/// Reload the cursor theme.
pub fn reload(&mut self, theme: &str, size: u8) {
Self::ensure_env(theme, size);
self.theme = CursorTheme::load(theme);
self.size = size;
self.named_cursor_cache.shrink_to(0);
}

/// Get the current rendering cursor.
pub fn get_render_cursor(&mut self, scale: i32) -> Option<RenderCursor<'_>> {
match self.current_cursor.clone() {
CursorImageStatus::Hidden => Some(RenderCursor::Hidden),
CursorImageStatus::Surface(surface) if surface.is_alive() => {
let hotspot = with_states(&surface, |states| {
states
.data_map
.get::<Mutex<CursorImageAttributes>>()
.unwrap()
.lock()
.unwrap()
.hotspot
});

Some(RenderCursor::Surface { hotspot, surface })
}
CursorImageStatus::Surface(_) => {
self.current_cursor = CursorImageStatus::default_named();
None
}
CursorImageStatus::Named(icon) => {
self.get_cursor_with_name(icon, scale)
.map(|cursor_buffer| RenderCursor::Named {
icon,
scale,
cursor: cursor_buffer,
})
.unwrap();

let texture = TextureBuffer::from_memory(
renderer,
&frame.pixels_rgba,
Fourcc::Abgr8888,
(frame.width as i32, frame.height as i32),
false,
*scale,
Transform::Normal,
None,
}
}
}

/// Get named cursor for the given `icon` and `scale`.
pub fn get_cursor_with_name(&mut self, icon: CursorIcon, scale: i32) -> Option<&XCursor> {
self.named_cursor_cache
.entry((icon, scale))
.or_insert_with_key(|(icon, scale)| {
Self::load_xcursor(&self.theme, icon.name(), self.size as i32 * scale).ok()
})
.as_ref()
}

/// Get default cursor.
///
/// This function will automatically use fallback when theme misses one.
pub fn get_default_cursor(&mut self, scale: i32) -> &XCursor {
let icon = CursorIcon::Default;
self.named_cursor_cache
.entry((icon, scale))
.or_insert_with_key(|(icon, scale)| {
Some(
Self::load_xcursor(&self.theme, icon.name(), self.size as i32 * scale)
.ok()
.unwrap_or_else(Self::fallback_cursor),
)
.unwrap();
(texture, (frame.xhot as i32, frame.yhot as i32).into())
})
.clone()
.as_ref()
.unwrap()
}

/// Currenly used cursor_image as a cursor provider.
pub fn cursor_image(&self) -> &CursorImageStatus {
&self.current_cursor
}

/// Set new cursor image provider.
pub fn set_cursor_image(&mut self, cursor: CursorImageStatus) {
self.current_cursor = cursor;
}

/// Load the cursor with the given `name` from the file system picking the closest
/// one to the given `size`.
fn load_xcursor(theme: &CursorTheme, name: &str, size: i32) -> anyhow::Result<XCursor> {
let path = theme
.load_icon(name)
.ok_or_else(|| anyhow!("no default icon"))?;

let mut file = File::open(path).context("error opening cursor icon file")?;
let mut buf = vec![];
file.read_to_end(&mut buf)
.context("error reading cursor icon file")?;

let mut images = parse_xcursor(&buf).context("error parsing cursor icon file")?;

let (width, height) = images
.iter()
.min_by_key(|image| (size - image.size as i32).abs())
.map(|image| (image.width, image.height))
.unwrap();

images.retain(move |image| image.width == width && image.height == height);

let animation_duration = images.iter().fold(0, |acc, image| acc + image.delay);

Ok(XCursor {
images,
animation_duration,
})
}

/// Set the common XCURSOR env variables.
fn ensure_env(theme: &str, size: u8) {
env::set_var("XCURSOR_THEME", theme);
env::set_var("XCURSOR_SIZE", size.to_string());
}

pub fn get_cached_hotspot(&self, scale: i32) -> Option<Point<i32, Physical>> {
self.cache.get(&scale).map(|(_, hotspot)| *hotspot)
fn fallback_cursor() -> XCursor {
let images = vec![Image {
size: 32,
width: 64,
height: 64,
xhot: 1,
yhot: 1,
delay: 0,
pixels_rgba: Vec::from(FALLBACK_CURSOR_DATA),
pixels_argb: vec![],
}];

XCursor {
images,
animation_duration: 0,
}
}
}

fn load_xcursor(theme: &str) -> anyhow::Result<Vec<Image>> {
let _span = tracy_client::span!();
/// The cursor prepared for renderer.
pub enum RenderCursor<'a> {
Hidden,
Surface {
hotspot: Point<i32, Logical>,
surface: WlSurface,
},
Named {
icon: CursorIcon,
scale: i32,
cursor: &'a XCursor,
},
}

/// Cached cursor buffer.
pub struct CachedCursorBuffer {
/// The icon used for cache.
pub icon: CursorIcon,
/// Scale of the given icon.
pub scale: i32,
/// Textures.
pub textures: Vec<TextureBuffer<GlesTexture>>,
}

// The XCursorBuffer implementation is inspired by `wayland-rs`, thus provided under MIT license.

/// The state of the `NamedCursor`.
pub struct XCursor {
/// The image for the underlying named cursor.
images: Vec<Image>,
/// The total duration of the animation.
animation_duration: u32,
}

impl XCursor {
/// Given a time, calculate which frame to show, and how much time remains until the next frame.
///
/// Time will wrap, so if for instance the cursor has an animation lasting 100ms,
/// then calling this function with 5ms and 105ms as input gives the same output.
pub fn frame(&self, mut millis: u32) -> (usize, &Image) {
millis %= self.animation_duration;

let mut res = 0;
for (i, img) in self.images.iter().enumerate() {
if millis < img.delay {
res = i;
break;
}
millis -= img.delay;
}

(res, &self.images[res])
}

let theme = CursorTheme::load(theme);
let path = theme
.load_icon("default")
.ok_or_else(|| anyhow!("no default icon"))?;
let mut file = File::open(path).context("error opening cursor icon file")?;
let mut buf = vec![];
file.read_to_end(&mut buf)
.context("error reading cursor icon file")?;
let images = parse_xcursor(&buf).context("error parsing cursor icon file")?;
/// Get the frames for the given `XCursor`.
pub fn frames(&self) -> &[Image] {
&self.images
}

Ok(images)
/// Check whether the cursor is animated.
pub fn is_animated_cursor(&self) -> bool {
self.images.len() > 1
}

/// Get hotspot for the given `image`.
pub fn hotspot(image: &Image) -> Point<i32, Logical> {
(image.xhot as i32, image.yhot as i32).into()
}
}
3 changes: 2 additions & 1 deletion src/handlers/compositor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,8 @@ impl CompositorHandler for State {
self.layer_shell_handle_commit(surface);

// This might be a cursor surface.
if matches!(&self.niri.cursor_image, CursorImageStatus::Surface(s) if s == surface) {
if matches!(&self.niri.cursor_manager.cursor_image(), CursorImageStatus::Surface(s) if s == surface)
{
// FIXME: granular redraws for cursors.
self.niri.queue_redraw_all();
}
Expand Down
11 changes: 6 additions & 5 deletions src/handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ use smithay::wayland::session_lock::{
LockSurface, SessionLockHandler, SessionLockManagerState, SessionLocker,
};
use smithay::{
delegate_data_control, delegate_data_device, delegate_dmabuf, delegate_input_method_manager,
delegate_output, delegate_pointer_gestures, delegate_presentation, delegate_primary_selection,
delegate_seat, delegate_session_lock, delegate_tablet_manager, delegate_text_input_manager,
delegate_virtual_keyboard_manager,
delegate_cursor_shape, delegate_data_control, delegate_data_device, delegate_dmabuf,
delegate_input_method_manager, delegate_output, delegate_pointer_gestures,
delegate_presentation, delegate_primary_selection, delegate_seat, delegate_session_lock,
delegate_tablet_manager, delegate_text_input_manager, delegate_virtual_keyboard_manager,
};

use crate::layout::output_size;
Expand All @@ -52,7 +52,7 @@ impl SeatHandler for State {
}

fn cursor_image(&mut self, _seat: &Seat<Self>, image: CursorImageStatus) {
self.niri.cursor_image = image;
self.niri.cursor_manager.set_cursor_image(image);
// FIXME: more granular
self.niri.queue_redraw_all();
}
Expand All @@ -65,6 +65,7 @@ impl SeatHandler for State {
}
}
delegate_seat!(State);
delegate_cursor_shape!(State);
delegate_tablet_manager!(State);
delegate_pointer_gestures!(State);
delegate_text_input_manager!(State);
Expand Down
Loading

0 comments on commit 80318ee

Please sign in to comment.