Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 118 additions & 2 deletions src/shojiwm_lib/src/handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ use smithay::wayland::image_capture_source::{
OutputCaptureSourceState, ToplevelCaptureSourceHandler, ToplevelCaptureSourceState,
};
use smithay::wayland::image_copy_capture::{
BufferConstraints, CaptureFailureReason, Frame, FrameRef, ImageCopyCaptureHandler,
ImageCopyCaptureState, Session, SessionRef,
BufferConstraints, CaptureFailureReason, CursorSession, CursorSessionRef, Frame, FrameRef,
ImageCopyCaptureHandler, ImageCopyCaptureState, Session, SessionRef,
};
use smithay::output::WeakOutput;
use smithay::{backend::{allocator::dmabuf::Dmabuf, renderer::ImportDma}};
Expand Down Expand Up @@ -486,6 +486,122 @@ impl ImageCopyCaptureHandler for ShojiWM {
}
}
}

fn cursor_capture_constraints(
&mut self,
source: &ImageCaptureSource,
_pointer: &smithay::reexports::wayland_server::protocol::wl_pointer::WlPointer,
) -> Option<BufferConstraints> {
// Smithay keeps a cursor session only when it has constraints, and
// clients want its enter / position events even when they never ask
// for the cursor's image. The image is not rendered yet: its frames
// fail (the trait's default `cursor_frame`).
resolve_source_size(self, source)?;
let scale = source_scale(self, source);
let side = (f64::from(self.cursor_theme.size()) * scale)
.ceil()
.max(1.0) as i32;
Some(BufferConstraints {
size: (side, side).into(),
shm: vec![smithay::reexports::wayland_server::protocol::wl_shm::Format::Argb8888],
dma: None,
})
}

fn new_cursor_session(&mut self, session: CursorSession) {
self.image_copy_cursor_sessions.push(session);
// A client asks where the pointer is now, not at its next motion.
self.update_cursor_capture_sessions();
}

fn cursor_session_destroyed(&mut self, session: CursorSessionRef) {
self.image_copy_cursor_sessions
.retain(|s| s.as_ref() != session);
}
}

impl ShojiWM {
/// Tell every cursor capture session where the pointer is on its source,
/// or that it left it. Call it after the pointer moves and after outputs
/// or windows move; smithay sends events only for changes.
pub fn update_cursor_capture_sessions(&mut self) {
if self.image_copy_cursor_sessions.is_empty() {
return;
}
let Some(pointer) = self.seat.get_pointer() else {
return;
};
let location = pointer.current_location();
for session in &self.image_copy_cursor_sessions {
let position = cursor_position_on_source(self, &session.source(), location);
session.set_cursor_pos(position);
}
}
}

/// The window of a toplevel capture source, if it is still mapped.
fn source_window(state: &ShojiWM, source: &ImageCaptureSource) -> Option<smithay::desktop::Window> {
let weak = source
.user_data()
.get::<smithay::wayland::foreign_toplevel_list::ForeignToplevelWeakHandle>()?;
let handle = weak.upgrade()?;
state
.space
.elements()
.find(|w| {
w.user_data()
.get::<ForeignToplevelHandle>()
.is_some_and(|h| h.matches(&handle))
})
.cloned()
}

/// The scale a source's captures are rendered at: its output's, or for a
/// window the scale of the first output it is on (as `resolve_source_size`).
fn source_scale(state: &ShojiWM, source: &ImageCaptureSource) -> f64 {
if let Some(output) = source
.user_data()
.get::<WeakOutput>()
.and_then(|weak| weak.upgrade())
{
return output.current_scale().fractional_scale();
}
source_window(state, source)
.and_then(|window| state.space.outputs_for_element(&window).into_iter().next())
.map(|output| output.current_scale().fractional_scale())
.unwrap_or(1.0)
}

/// The pointer's place in the buffer a capture of `source` produces, or
/// `None` when the pointer is not on it. Captures are rendered upright (see
/// `image_copy_capture_render`), so the place is the logical offset scaled to
/// the buffer's size, with no transform.
fn cursor_position_on_source(
state: &ShojiWM,
source: &ImageCaptureSource,
location: smithay::utils::Point<f64, smithay::utils::Logical>,
) -> Option<smithay::utils::Point<i32, smithay::utils::Buffer>> {
let size = resolve_source_size(state, source)?;
let area = if let Some(output) = source
.user_data()
.get::<WeakOutput>()
.and_then(|weak| weak.upgrade())
{
state.space.output_geometry(&output)?
} else {
let window = source_window(state, source)?;
state.space.element_geometry(&window)?
};
if area.size.w <= 0 || area.size.h <= 0 {
return None;
}
let x = (location.x - f64::from(area.loc.x)) * f64::from(size.w) / f64::from(area.size.w);
let y = (location.y - f64::from(area.loc.y)) * f64::from(size.h) / f64::from(area.size.h);
let (x, y) = (x.floor() as i32, y.floor() as i32);
if x < 0 || y < 0 || x >= size.w || y >= size.h {
return None;
}
Some((x, y).into())
}

/// Resolve an `ImageCaptureSource` to its natural buffer size. Returns `None`
Expand Down
2 changes: 2 additions & 0 deletions src/shojiwm_lib/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ impl ShojiWM {
fn request_redraw_for_pointer_motion(&mut self) {
self.last_pointer_motion_at = Some(std::time::Instant::now());
self.sync_drag_state();
self.update_cursor_capture_sessions();
// A drag view following the pointer is drawn with the scene, not on
// the cursor plane: moving it takes a full frame.
if self.dnd.has_pointer_anchored_views() {
Expand Down Expand Up @@ -516,6 +517,7 @@ impl ShojiWM {
},
);
pointer.frame(self);
self.update_cursor_capture_sessions();
self.schedule_redraw();
}

Expand Down
7 changes: 7 additions & 0 deletions src/shojiwm_lib/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,9 @@ pub struct ShojiWM {
/// `stopped` to clients. Keyed by source id.
pub image_copy_capture_sessions:
std::collections::HashMap<usize, Vec<smithay::wayland::image_copy_capture::Session>>,
/// Live cursor capture sessions, kept for the same reason: dropping one
/// stops it. Each is told where the pointer is on its source.
pub image_copy_cursor_sessions: Vec<smithay::wayland::image_copy_capture::CursorSession>,
/// Capture frames the client has requested, waiting to be rendered into
/// during the next backend frame. Drained per-output / per-toplevel by
/// the render path.
Expand Down Expand Up @@ -850,6 +853,7 @@ impl ShojiWM {
},
);
pointer.frame(self);
self.update_cursor_capture_sessions();
}

pub fn warp_cursor_to_initial_output_center(&mut self) {
Expand Down Expand Up @@ -1914,6 +1918,7 @@ impl ShojiWM {
initial_config_enabled: false,
session_lock_surfaces: HashMap::new(),
image_copy_capture_sessions: std::collections::HashMap::new(),
image_copy_cursor_sessions: Vec::new(),
image_copy_capture_pending: Vec::new(),
hyprland_toplevel_export_state,
single_pixel_buffer_state,
Expand Down Expand Up @@ -4044,6 +4049,8 @@ impl ShojiWM {
}
}
self.configure_session_lock_surfaces();
// An output that moved or changed scale moves the pointer on it.
self.update_cursor_capture_sessions();
// Outputs this configuration disabled go dark (and enabled ones come back).
crate::backend::tty::sync_output_power(self);
self.schedule_redraw();
Expand Down
133 changes: 133 additions & 0 deletions src/shojiwm_rs/tests/cursor_capture_session.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
//! A cursor capture session (ext-image-copy-capture-v1) tells its client
//! where the pointer is on the captured output: `enter` and `position` when
//! the pointer comes onto it, `leave` when it goes off.

mod common;

use std::cell::RefCell;

use smithay::{input::pointer::MotionEvent, utils::SERIAL_COUNTER};
use wayland_client::{
Connection, Dispatch, QueueHandle,
protocol::{wl_output, wl_pointer, wl_seat},
};
use wayland_protocols::ext::{
image_capture_source::v1::client::{
ext_image_capture_source_v1, ext_output_image_capture_source_manager_v1,
},
image_copy_capture::v1::client::{
ext_image_copy_capture_cursor_session_v1, ext_image_copy_capture_manager_v1,
},
};

thread_local! {
static EVENTS: RefCell<Vec<Seen>> = const { RefCell::new(Vec::new()) };
}

#[derive(Debug, Clone, PartialEq)]
enum Seen {
Enter,
Leave,
Position(i32, i32),
}

fn seen() -> Vec<Seen> {
EVENTS.with(|events| events.borrow().clone())
}

fn clear() {
EVENTS.with(|events| events.borrow_mut().clear());
}

fn setup() {}

/// What the input path does on motion: move the pointer, then tell the
/// cursor sessions.
fn move_pointer(session: &mut common::Session, x: f64, y: f64) {
let state = &mut session.state;
let pointer = state.seat.get_pointer().unwrap();
let location = (x, y).into();
state.pointer_contents = state.pointer_contents_at(location);
let under = state.pointer_contents.surface.clone();
pointer.motion(
state,
under,
&MotionEvent {
location,
serial: SERIAL_COUNTER.next_serial(),
time: 0,
},
);
pointer.frame(state);
state.update_cursor_capture_sessions();
session.roundtrip();
}

#[test]
fn cursor_session_follows_the_pointer_on_its_output() {
let mut session = common::Session::new(setup);
let qh = session.queue.handle();
let seat: wl_seat::WlSeat = session.bind("wl_seat", 1);
let pointer = seat.get_pointer(&qh, ());
let output: wl_output::WlOutput = session.bind("wl_output", 1);
let sources: ext_output_image_capture_source_manager_v1::ExtOutputImageCaptureSourceManagerV1 =
session.bind("ext_output_image_capture_source_manager_v1", 1);
let captures: ext_image_copy_capture_manager_v1::ExtImageCopyCaptureManagerV1 =
session.bind("ext_image_copy_capture_manager_v1", 1);
let source = sources.create_source(&output, &qh, ());
move_pointer(&mut session, 2000.0, 100.0);
captures.create_pointer_cursor_session(&source, &pointer, &qh, ());
session.roundtrip();
// The pointer is off the only output: the session says nothing yet.
assert_eq!(seen(), vec![]);

// The test output is 1024x768 at scale 1: buffer pixels are logical ones.
move_pointer(&mut session, 100.5, 200.25);
assert_eq!(seen(), vec![Seen::Enter, Seen::Position(100, 200)]);

clear();
move_pointer(&mut session, 300.0, 400.0);
assert_eq!(seen(), vec![Seen::Position(300, 400)]);

clear();
move_pointer(&mut session, 2000.0, 100.0);
assert_eq!(seen(), vec![Seen::Leave]);
}

impl Dispatch<ext_image_copy_capture_cursor_session_v1::ExtImageCopyCaptureCursorSessionV1, ()>
for common::Client
{
fn event(
_: &mut Self,
_: &ext_image_copy_capture_cursor_session_v1::ExtImageCopyCaptureCursorSessionV1,
event: ext_image_copy_capture_cursor_session_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
let seen = match event {
ext_image_copy_capture_cursor_session_v1::Event::Enter => Seen::Enter,
ext_image_copy_capture_cursor_session_v1::Event::Leave => Seen::Leave,
ext_image_copy_capture_cursor_session_v1::Event::Position { x, y } => {
Seen::Position(x, y)
}
_ => return,
};
EVENTS.with(|events| events.borrow_mut().push(seen));
}
}

macro_rules! ignore_events {
($($proxy:ty),*) => {$(
impl Dispatch<$proxy, ()> for common::Client {
fn event(_: &mut Self, _: &$proxy, _: <$proxy as wayland_client::Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {}
}
)*};
}

ignore_events!(
wl_pointer::WlPointer,
ext_image_capture_source_v1::ExtImageCaptureSourceV1,
ext_output_image_capture_source_manager_v1::ExtOutputImageCaptureSourceManagerV1,
ext_image_copy_capture_manager_v1::ExtImageCopyCaptureManagerV1
);