🆕 Drive the guest's own mouse from a captured pointer in games

A game that hides the cursor and turns its camera by the mouse's motion got
no motion past the image's edge: the guest's pointer is QEMU's absolute
tablet, held at the edge, and every motion API a game reads (NSEvent and
CGEvent deltas, event taps, GCMouse) stopped with it (measured, lane
gamemouse, m3-max-35167).

The guest now gets a mouse of its own. Feature bit 51, POINTER_MOTION, which
a device with a window offers, makes the kexts (both sets) publish
RgfxPointerDevice, an IOHIDDevice "Reims vGPU Mouse" (0x1234:0x5247), and the
event POINTER_MOTION (0x105) hands it relative motion, wheel notches and
buttons. The device tracks the guest's cursor on each display from
MOVE_CURSOR and owes the motion in order while the ring is held, never
merging a press or a release into a move.

What the guest and host see: captured, once the guest has hidden its cursor
on every display for 50 ms, the window locks the host's pointer (SDL's
relative mode at the device's own counts on Linux, a disassociated cursor
with unaccelerated deltas on macOS) and drives the guest's mouse, until the
guest shows its cursor, where the host's pointer is let go over it. A button
comes up by the route it went down by. A guest without the bit sees no new
device and no event, and the window's pointer is the tablet's as before.
The C API, QEMU and reims-ctl are unchanged.

The kexts compile the SDK's IOHIDDevice.h through two stand-in headers of
our own (guest/kext/src/shim) for the two it includes and the SDK lacks.
This commit is contained in:
Anees Iqbal committed 2026-11-15 23:02:22 -08:00
1 parent 14302647f1
commit 21632b2752
38 files changed
+2424 -85

No files matched your search

+3 -2
View File
@@ -287,9 +287,10 @@ pub(crate) fn window_callbacks(t: &Arc<Table>, c: &RvgWindowCallbacks) -> Window
});
c
}),
// The C API's host has no guest desktop to carry a captured pointer across: the library
// gives a graphics device's own windows theirs.
// The C API's host has no guest desktop to carry a captured pointer across, nor a guest's
// mouse to drive: the library gives a graphics device's own windows theirs.
beyond: None,
motion: None,
}
}
+1
View File
@@ -280,6 +280,7 @@ include = [
"RgfxPipelineAnswersQuery",
"RgfxPipelineLibrary",
"RgfxPipelineReflection",
"RgfxPointerMotion",
"RgfxPointerOver",
"RgfxPresentSurface",
"RgfxPresentSurfaceGen",
@@ -1514,6 +1514,15 @@
// guest that took all three and sent the displays' rectangles.
#define RGFX_FEATURE_DISPLAY_BOUNDS 1125899906842624
// `FEATURES_HI` bit 19, feature bit 51, `POINTER_MOTION`: the guest's driver publishes a
// relative pointing device of its own, a mouse, which [`RGFX_EVT_POINTER_MOTION`] moves and
// clicks, beside the host's absolute one (QEMU's USB tablet). The device offers it where its
// host made it with a window, and sends `POINTER_MOTION` only to a guest that took it, while the
// window's captured pointer drives a game's hidden cursor (docs/graphics-kext/design.md, "A
// pointer for games"): a guest that did not take it (a kext built before this bit, the option ROM,
// Ambrosia's module) publishes no device and is never sent it.
#define RGFX_FEATURE_POINTER_MOTION 2251799813685248
// `STATUS`, RW: writing [`RGFX_STATUS_RESET`] resets the device; the guest writes
// [`RGFX_STATUS_DRIVER_READY`] once it has read the rings' headers.
#define RGFX_REG_STATUS 16
@@ -1768,6 +1777,11 @@
// display the guest's cursor is not on, and the guest moves its cursor there.
#define RGFX_EVT_POINTER_OVER 260
// Event `POINTER_MOTION` ([`RgfxPointerMotion`]), sent only to a guest that took
// [`RGFX_FEATURE_POINTER_MOTION`]: the host's pointing device moved, turned its wheel or pressed
// or let go of a button, and the guest's relative pointing device does the same.
#define RGFX_EVT_POINTER_MOTION 261
// `COMPLETE`'s status: the command was done.
#define RGFX_STATUS_OK 0
@@ -6571,6 +6585,27 @@ typedef struct {
uint32_t flags;
} RgfxPipelineReflection;
// `POINTER_MOTION`: the host's pointing device moved by (`dx`, `dy`), right and down, in its own
// counts, as no acceleration has changed them, turned its wheel `wheel` notches up (away from the
// person), and holds the `RGFX_POINTER_BUTTON_*` `buttons` after it. The guest's driver hands it
// to its relative pointing device as one report of a USB mouse, so the guest accelerates the
// motion as its own settings say, once, and a game that reads the device's counts gets the
// host's. Only a guest that took [`RGFX_FEATURE_POINTER_MOTION`] is sent it; motion that finds
// the ring held or full is added to the next event of the same buttons, so a press or a release
// is never lost.
typedef struct {
// [`RGFX_EVT_POINTER_MOTION`], `seqno` 0.
RgfxMsgHeader header;
// The motion to the right, in the device's counts.
int32_t dx;
// The motion down, in the device's counts.
int32_t dy;
// Wheel notches, above 0 up (away from the person).
int32_t wheel;
// The buttons held after it: `RGFX_POINTER_BUTTON_*` bits.
uint32_t buttons;
} RgfxPointerMotion;
// `POINTER_OVER`: the host's pointer is over display `display`, at (`x`, `y`) in the display's
// pixels of its mode, and the guest's cursor shows on another display. The guest moves its
// cursor onto display `display` at that point, so the host's pointer positions that follow, the
@@ -30,6 +30,9 @@ pub(crate) fn answer(shared: &Shared, message: &Message) -> Option<Vec<u8>> {
if let Some(command) = read::<RgfxMoveCursor>(message)
&& let Some(display) = shared.seen_display(command.display)
{
// The device knows first, so a window the move reaches asks it of a cursor
// shown or hidden already.
shared.cursor_visible(command.display, command.visible != 0);
display
.screen
.cursor_moved(command.x, command.y, command.visible != 0);
+154 -3
View File
@@ -331,7 +331,7 @@ impl Room {
const MIN_QUEUE_RING_DATA: u64 = 4096;
/// The feature bits whose meaning the host knows, which a `DRIVER_FEATURES` write may take:
/// `RGFX_FEATURE_*`, bits 0 to 8 and 11 to 50.
/// `RGFX_FEATURE_*`, bits 0 to 8 and 11 to 51.
const KNOWN_FEATURES: u64 = (RGFX_FEATURE_SURFACE_PAGES
| RGFX_FEATURE_SURFACE_CACHE
| RGFX_FEATURE_CB_SUBMITTED
@@ -379,7 +379,8 @@ const KNOWN_FEATURES: u64 = (RGFX_FEATURE_SURFACE_PAGES
| RGFX_FEATURE_PIPELINE_ANSWERS
| RGFX_FEATURE_MULTI_DISPLAY
| RGFX_FEATURE_POINTER_OVER
| RGFX_FEATURE_DISPLAY_BOUNDS;
| RGFX_FEATURE_DISPLAY_BOUNDS
| RGFX_FEATURE_POINTER_MOTION;
/// The `RGFX_QUEUE_*` flags the host carries out, each with the feature the guest's driver must
/// take for a `QUEUE_CREATE` to ask for it: [`RGFX_QUEUE_UNSHARED`] alone, so a create that asks
@@ -926,6 +927,9 @@ pub(crate) struct Shared {
control_handing: AtomicBool,
/// Where the host's pointer and the guest's cursor are, for `POINTER_OVER` ([`Pointer`]).
pointer: Mutex<Pointer>,
/// Held by the thread that posts the owed `POINTER_MOTION`s ([`Shared::post_motion`]), so
/// they go out in their order; a thread that finds it held leaves them to its holder.
motion_posting: Mutex<()>,
/// The control submission ring's count through the last message the control thread has
/// carried out, handed to the host or handed to a lane: a command buffer waits for it to pass
/// the last message published before it that is its context's or every buffer's
@@ -1016,6 +1020,12 @@ impl Queues {
/// it (a hidden cursor) or be slow to.
const CROSSING_HOLD_NS: u64 = 100_000_000;
/// The most `POINTER_MOTION`s owed at once ([`Pointer::motion`]): each press or release makes
/// one, and motion joins the last. A guest that takes none for that long has the last take the
/// next buttons too, so that what it is sent once it takes them again ends where the host's
/// buttons are.
const MOTION_OWED_MAX: usize = 64;
/// What `POINTER_OVER` follows ([`Shared::pointer_at`]): the display the guest's cursor last
/// showed on, what the guest was told, the displays' places in the guest's desktop, and where a
/// captured pointer that went past its window's edge is ([`Away`]), each of one reset count. A
@@ -1042,6 +1052,16 @@ struct Pointer {
bounds: [Option<Bounds>; RGFX_DISPLAYS_MAX as usize],
/// The captured pointer gone past its window's edge, while it is.
away: Option<Away>,
/// Each display's cursor as the guest's last `MOVE_CURSOR` of it left it: shown, hidden, or
/// `None` before the guest moved it ([`Shared::cursor_hidden_for`]).
shown: [Option<bool>; RGFX_DISPLAYS_MAX as usize],
/// Since when, on the device's clock, the guest has hidden its cursor on every display it
/// sees, while it has.
hidden_since: Option<u64>,
/// The `POINTER_MOTION`s not posted yet, oldest first: one that found the ring held by
/// another thread, full, or behind answers handed over goes at the next motion or the next
/// refresh of any display ([`Shared::pointer_motion`]).
motion: VecDeque<RgfxPointerMotion>,
}
/// A window's captured pointer gone past the image's edge onto the guest's desktop
@@ -1160,6 +1180,29 @@ impl PointerLink {
shared.come_back();
}
}
/// How long, in nanoseconds, the guest has hidden its cursor on every display it sees (its
/// last `MOVE_CURSOR` of each that it moved said hidden), where it took
/// [`RGFX_FEATURE_POINTER_MOTION`]: a window's captured pointer then drives the guest's
/// relative pointing device ([`Self::motion`]), as a game that hides the cursor reads its
/// motion. `None` where the cursor shows on a display, the guest has yet to move it since its
/// start, did not take the feature or is not started, and once the device has ended.
pub fn cursor_hidden_for(&self) -> Option<u64> {
self.shared.upgrade()?.cursor_hidden_for()
}
/// The host's pointing device moved by (`dx`, `dy`) of its counts, turned its wheel `wheel`
/// notches up, and holds the `RGFX_POINTER_BUTTON_*` `buttons` after it: where the guest took
/// [`RGFX_FEATURE_POINTER_MOTION`], it is sent `POINTER_MOTION` ([`RgfxPointerMotion`]).
/// Waits for no other thread: motion that finds the ring held or full joins the next of the
/// same buttons, and goes with it, or at the next refresh. Whether the guest takes it: false,
/// and nothing sent, where the guest did not take the feature or is not started, and once the
/// device has ended.
pub fn motion(&self, dx: i32, dy: i32, wheel: i32, buttons: u32) -> bool {
self.shared
.upgrade()
.is_some_and(|shared| shared.pointer_motion(dx, dy, wheel, buttons))
}
}
/// One command queue's own rings, shared by its service thread and its completion poster.
@@ -1458,6 +1501,7 @@ impl Device {
control_handed: Mutex::new(Handed::default()),
control_handing: AtomicBool::new(false),
pointer: Mutex::new(Pointer::default()),
motion_posting: Mutex::new(()),
control_done: AtomicU64::new(0),
gate: Gate::default(),
lanes: Arc::new(lanes),
@@ -2255,6 +2299,112 @@ impl Shared {
self.pointer.lock().at(epoch).away = None;
}
/// The guest's `MOVE_CURSOR` showed (`visible`) or hid its cursor on display `id`, one it
/// sees: where that leaves it hidden on every display it moved it on, and shown on none, the
/// cursor is hidden from now ([`Self::cursor_hidden_for`]).
pub(crate) fn cursor_visible(&self, id: u32, visible: bool) {
let epoch = self.epoch.load(Ordering::Acquire);
let seen = self.displays_seen() as usize;
let mut pointer = self.pointer.lock();
let pointer = pointer.at(epoch);
let Some(slot) = pointer.shown.get_mut(id as usize) else {
return;
};
*slot = Some(visible);
let hidden = pointer.shown[..seen.min(pointer.shown.len())]
.iter()
.all(|shown| *shown != Some(true));
if !hidden {
pointer.hidden_since = None;
} else if pointer.hidden_since.is_none() {
pointer.hidden_since = Some(now_ns());
}
}
/// [`PointerLink::cursor_hidden_for`].
pub(crate) fn cursor_hidden_for(&self) -> Option<u64> {
if !self.driver_took(RGFX_FEATURE_POINTER_MOTION) || !self.started() {
return None;
}
let epoch = self.epoch.load(Ordering::Acquire);
let since = self.pointer.lock().at(epoch).hidden_since?;
Some(now_ns().saturating_sub(since))
}
/// [`PointerLink::motion`]: the motion joins the last owed `POINTER_MOTION` where that holds
/// the same buttons, else is owed after it, and the owed go out in order. Whether the guest
/// takes it.
pub(crate) fn pointer_motion(&self, dx: i32, dy: i32, wheel: i32, buttons: u32) -> bool {
if !self.driver_took(RGFX_FEATURE_POINTER_MOTION) || !self.started() {
return false;
}
let epoch = self.epoch.load(Ordering::Acquire);
{
let mut pointer = self.pointer.lock();
let owed = &mut pointer.at(epoch).motion;
let full = owed.len() >= MOTION_OWED_MAX;
match owed.back_mut() {
Some(last) if last.buttons == buttons || full => {
last.dx = last.dx.saturating_add(dx);
last.dy = last.dy.saturating_add(dy);
last.wheel = last.wheel.saturating_add(wheel);
last.buttons = buttons;
}
_ => {
owed.push_back(RgfxPointerMotion {
header: event_header(RGFX_EVT_POINTER_MOTION),
dx,
dy,
wheel,
buttons,
});
}
}
}
self.post_motion(epoch, false);
true
}
/// Posts the `POINTER_MOTION`s owed at reset count `epoch`, oldest first, waiting for the
/// ring held elsewhere and for room where `wait`; stops at the first not posted, which stays
/// owed with those after it, as does one that finds answers handed over before it. Where
/// another thread posts them, it leaves them to it: that thread posts all it finds, and the
/// next refresh any it did not.
fn post_motion(&self, epoch: u64, wait: bool) {
let Some(_posting) = self.motion_posting.try_lock() else {
return;
};
loop {
let Some(event) = self.pointer.lock().at(epoch).motion.front().copied() else {
return;
};
if self.control_handing.load(Ordering::Acquire) {
return;
}
if !matches!(
self.post_on(&sized(&event), epoch, wait),
Post::Done | Post::Dropped
) {
return;
}
let mut pointer = self.pointer.lock();
let owed = &mut pointer.at(epoch).motion;
let Some(front) = owed.front_mut() else {
return;
};
if *front == event {
owed.pop_front();
} else {
// Motion joined it while it was posted, the only change to the first owed while
// this thread posts: the guest has the event as it was, and what joined stays
// owed.
front.dx = front.dx.saturating_sub(event.dx);
front.dy = front.dy.saturating_sub(event.dy);
front.wheel = front.wheel.saturating_sub(event.wheel);
}
}
}
/// [`PointerLink::pointer_at`]: the host's pointer is over display `id` at (`x`, `y`), with
/// `buttons` held. Whether the position goes on to the guest's pointing device now.
pub(crate) fn pointer_at(&self, id: u32, x: i32, y: i32, buttons: u32) -> bool {
@@ -4087,8 +4237,9 @@ impl Shared {
display.state.lock().changed = false;
}
}
// A POINTER_OVER the window's thread could not post.
// A POINTER_OVER the window's thread could not post, and the motion.
self.post_pointer(epoch, true);
self.post_motion(epoch, true);
self.host.refreshed(id);
}
}
@@ -12,6 +12,7 @@ use super::*;
use crate::display::CursorImage;
mod displays;
mod motion;
mod posting;
/// How many times [`eventually`] polls, a millisecond's sleep apart, for a state the device's own
@@ -0,0 +1,223 @@
//! A pointer for games (docs/graphics-kext/design.md, "A pointer for games"): the offer of
//! `POINTER_MOTION`, the guest's cursor hidden on every display it sees, and the
//! `POINTER_MOTION`s a window's captured pointer sends, in their order, joined while the ring has
//! no room, a press or a release never lost.
use super::*;
/// A host that offers `POINTER_MOTION`, as one with a window does, and records what the device
/// told it of the control completion ring.
struct MotionHost(Arc<Mutex<Vec<RingDegradation>>>);
impl Host for MotionHost {
fn raise_interrupt(&self, _vector: u32) {}
fn features(&self) -> u64 {
RGFX_FEATURE_POINTER_MOTION
}
fn ring_degraded(&self, kind: RingDegradation) {
self.0.lock().push(kind);
}
}
/// A rig of `count` displays whose host offers `POINTER_MOTION`.
fn motion_rig(count: usize) -> Rig {
let degraded = Arc::new(Mutex::new(Vec::new()));
let host = MotionHost(Arc::clone(&degraded));
let mut rig = Rig::with_displays(Box::new(host), Lanes::default(), count);
rig.degraded = degraded;
rig
}
/// The guest's driver takes the bits `bits` of `FEATURES_HI` and starts the device.
fn take_and_start(rig: &Rig, bits: u64) {
rig.device
.mmio_write(RGFX_REG_DRIVER_FEATURES_HI.into(), (bits >> 32) as u32);
rig.start();
}
/// A `MOVE_CURSOR` of `display` to (`x`, `y`), shown or hidden.
fn cursor_of(display: u32, x: i32, y: i32, visible: bool) -> Vec<u8> {
RgfxMoveCursor {
header: RgfxMsgHeader {
r#type: RGFX_CMD_MOVE_CURSOR,
..Default::default()
},
display,
x,
y,
visible: u32::from(visible),
}
.as_bytes()
.to_vec()
}
/// Sends `command`, a `MOVE_CURSOR`, and waits for the control thread to have carried it out: it
/// carries out the answered `GET_DISPLAYS` after it.
fn moved(rig: &mut Rig, command: Vec<u8>) {
rig.send(command);
rig.send(get_displays());
rig.event().expect("DISPLAYS");
}
/// The next event, as a `POINTER_MOTION`: its motion, wheel and buttons.
fn motion(rig: &mut Rig) -> (i32, i32, i32, u32) {
let m = RgfxPointerMotion::read_from_bytes(&rig.event().expect("a POINTER_MOTION")).unwrap();
assert_eq!(
(m.header.r#type, m.header.size, m.header.seqno),
(RGFX_EVT_POINTER_MOTION, 32, 0)
);
(m.dx, m.dy, m.wheel, m.buttons)
}
/// `POINTER_MOTION` (`FEATURES_HI` bit 19) is offered where the host offers it, on a device of one
/// display as of several, and only there can the guest take it
#[test]
fn pointer_motion_is_offered_where_the_host_offers_it() {
let rig = motion_rig(1);
let hi = rig.device.mmio_read(RGFX_REG_FEATURES_HI.into());
assert_eq!(hi, (RGFX_FEATURE_POINTER_MOTION >> 32) as u32);
let plain = Rig::new();
assert_eq!(plain.device.mmio_read(RGFX_REG_FEATURES_HI.into()), 0);
take_and_start(&plain, RGFX_FEATURE_POINTER_MOTION);
assert_eq!(
plain.device.mmio_read(RGFX_REG_DRIVER_FEATURES_HI.into()),
0,
"a host that does not offer it gives it to no guest"
);
}
/// A guest that did not take `POINTER_MOTION` (a kext built before it, the option ROM,
/// Ambrosia's module) is sent no `POINTER_MOTION`, and its hidden cursor drives nothing: the
/// window's pointer stays the tablet's, as before
#[test]
fn a_guest_that_did_not_take_pointer_motion_gets_none() {
let mut rig = motion_rig(1);
rig.start();
let link = rig.device.pointer_link();
moved(&mut rig, cursor_of(0, 10, 10, false));
assert_eq!(link.cursor_hidden_for(), None);
assert!(!link.motion(5, 6, 0, 0), "the guest takes no motion");
assert!(rig.quiet_for(200), "nothing sent");
}
/// The guest's hidden cursor drives the motion only once it hides it on every display it sees:
/// not before it has moved it, not while any display shows it, and from the first show on, a
/// hide starts the count again, so a hide and show in a row (WindowServer at its start, or the
/// cursor going from one display to the next) never holds for long
#[test]
fn the_cursor_is_hidden_once_every_display_it_sees_hides_it() {
let mut rig = motion_rig(2);
take_and_start(
&rig,
RGFX_FEATURE_POINTER_MOTION | RGFX_FEATURE_MULTI_DISPLAY,
);
let link = rig.device.pointer_link();
assert_eq!(link.cursor_hidden_for(), None, "never moved");
moved(&mut rig, cursor_of(0, 10, 10, true));
assert_eq!(link.cursor_hidden_for(), None, "shown on display 0");
// Onto display 1: hidden on 0, shown on 1.
moved(&mut rig, cursor_of(0, 10, 10, false));
let flicker = link.cursor_hidden_for();
assert!(flicker.is_some(), "hidden between the two");
moved(&mut rig, cursor_of(1, 5, 5, true));
assert_eq!(link.cursor_hidden_for(), None, "shown on display 1");
// A game hides it.
moved(&mut rig, cursor_of(1, 5, 5, false));
std::thread::sleep(Duration::from_millis(60));
let hidden = link.cursor_hidden_for().expect("hidden on both");
assert!(hidden >= 60_000_000, "counted from the hide: {hidden} ns");
// Hidden again on display 1 keeps the count.
moved(&mut rig, cursor_of(1, 6, 6, false));
assert!(link.cursor_hidden_for().unwrap() >= hidden);
moved(&mut rig, cursor_of(0, 1, 1, true));
assert_eq!(link.cursor_hidden_for(), None, "shown on display 0");
// Hidden again after the show: counted from this hide.
moved(&mut rig, cursor_of(0, 1, 1, false));
let again = link.cursor_hidden_for().expect("hidden on both again");
assert!(again < hidden, "counted from the new hide: {again} ns");
}
/// A guest that sees display 0 alone (it did not take `MULTI_DISPLAY`) hides its cursor where
/// display 0 hides it
#[test]
fn a_guest_that_sees_one_display_hides_its_cursor_there() {
let mut rig = motion_rig(2);
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
let link = rig.device.pointer_link();
moved(&mut rig, cursor_of(0, 10, 10, false));
assert!(link.cursor_hidden_for().is_some());
}
/// Each `POINTER_MOTION` the window sends reaches the guest that took it as it was sent: motion,
/// wheel and buttons
#[test]
fn motion_reaches_a_guest_that_took_it() {
let mut rig = motion_rig(1);
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
let link = rig.device.pointer_link();
assert!(link.motion(5, -6, 0, 0));
assert_eq!(motion(&mut rig), (5, -6, 0, 0));
assert!(link.motion(0, 0, 0, RGFX_POINTER_BUTTON_LEFT));
assert_eq!(motion(&mut rig), (0, 0, 0, RGFX_POINTER_BUTTON_LEFT));
assert!(link.motion(-3, 2, 1, RGFX_POINTER_BUTTON_LEFT));
assert_eq!(motion(&mut rig), (-3, 2, 1, RGFX_POINTER_BUTTON_LEFT));
assert!(link.motion(0, 0, -2, 0));
assert_eq!(motion(&mut rig), (0, 0, -2, 0));
}
/// Motion that finds the control completion ring full is owed: motion of the same buttons joins
/// the last owed, a press or a release is owed after it, and the next refresh, once the guest has
/// taken room, sends them in their order, so no press or release is lost
#[test]
fn owed_motion_joins_and_a_press_never_does() {
let mut rig = motion_rig(1);
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
// 24-byte answers: the 32 KiB ring holds 1365 of them.
let count = 1400u64;
for _ in 0..count {
rig.send(vblank(0));
}
assert!(
eventually(|| !rig.degraded.lock().is_empty()),
"the ring never filled"
);
let link = rig.device.pointer_link();
assert!(link.motion(1, 2, 0, 0));
assert!(link.motion(3, 4, 1, 0));
assert!(link.motion(0, 0, 0, RGFX_POINTER_BUTTON_LEFT));
assert!(link.motion(5, 0, 0, RGFX_POINTER_BUTTON_LEFT));
assert!(link.motion(0, 0, 0, 0));
assert!(link.motion(0, 7, 0, 0));
for seqno in 1..=count {
assert_eq!(rig.complete(), (seqno, RGFX_STATUS_OK));
}
rig.refresh();
assert_eq!(motion(&mut rig), (4, 6, 1, 0));
assert_eq!(motion(&mut rig), (5, 0, 0, RGFX_POINTER_BUTTON_LEFT));
assert_eq!(motion(&mut rig), (0, 7, 0, 0));
assert!(rig.quiet_for(100), "nothing more");
}
/// A reset forgets the hidden cursor and the owed motion, and sends the next driver none until it
/// takes `POINTER_MOTION` again
#[test]
fn a_reset_forgets_the_hidden_cursor_and_the_motion() {
let mut rig = motion_rig(1);
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
let link = rig.device.pointer_link();
moved(&mut rig, cursor_of(0, 1, 1, false));
assert!(link.cursor_hidden_for().is_some());
rig.device
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_RESET);
(rig.produced, rig.consumed, rig.seqno) = (0, 0, 0);
assert_eq!(link.cursor_hidden_for(), None);
rig.start();
assert!(!link.motion(1, 1, 0, 0), "not taken since the reset");
assert!(rig.quiet_for(100));
rig.device
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_RESET);
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
assert_eq!(link.cursor_hidden_for(), None, "never moved since");
assert!(link.motion(2, 3, 0, 0));
assert_eq!(motion(&mut rig), (2, 3, 0, 0));
}
@@ -801,13 +801,13 @@ fn a_producer_waiting_for_room_gets_a_record_after_the_host_s_take() {
/// its own, and a later write before the driver is ready replaces what an earlier one took.
#[test]
fn driver_features_take_what_is_written_offered_and_known() {
// Bits 3 and 5 of the new ones, bit 45 of the high half, bit 9 (reserved) and bit 51, which
// Bits 3 and 5 of the new ones, bit 45 of the high half, bit 9 (reserved) and bit 52, which
// the host does not know.
let offered = PEER_FEATURES
| u64::from(RGFX_FEATURE_QUIET_SCHEDULED | RGFX_FEATURE_QUEUE_BARRIER)
| RGFX_FEATURE_READ_ONLY_PAGES
| (1 << 9)
| (1 << 51);
| (1 << 52);
let mut guest = FakeGuest::offered(offered);
assert_eq!(guest.driver_features(), 0, "unwritten, it reads 0");
guest.write(RGFX_REG_STATUS, RGFX_STATUS_RESET);
+42 -1
View File
@@ -465,6 +465,14 @@ pub const RGFX_FEATURE_POINTER_OVER: u64 = 0x2_0000_0000_0000;
/// made it with two displays or more, and carries the pointer past a display's edge only for a
/// guest that took all three and sent the displays' rectangles.
pub const RGFX_FEATURE_DISPLAY_BOUNDS: u64 = 0x4_0000_0000_0000;
/// `FEATURES_HI` bit 19, feature bit 51, `POINTER_MOTION`: the guest's driver publishes a
/// relative pointing device of its own, a mouse, which [`RGFX_EVT_POINTER_MOTION`] moves and
/// clicks, beside the host's absolute one (QEMU's USB tablet). The device offers it where its
/// host made it with a window, and sends `POINTER_MOTION` only to a guest that took it, while the
/// window's captured pointer drives a game's hidden cursor (docs/graphics-kext/design.md, "A
/// pointer for games"): a guest that did not take it (a kext built before this bit, the option ROM,
/// Ambrosia's module) publishes no device and is never sent it.
pub const RGFX_FEATURE_POINTER_MOTION: u64 = 0x8_0000_0000_0000;
/// `STATUS`, RW: writing [`RGFX_STATUS_RESET`] resets the device; the guest writes
/// [`RGFX_STATUS_DRIVER_READY`] once it has read the rings' headers.
pub const RGFX_REG_STATUS: u32 = 0x010;
@@ -726,6 +734,10 @@ pub const RGFX_EVT_VBLANK: u32 = 0x103;
/// [`RGFX_FEATURE_POINTER_OVER`] and [`RGFX_FEATURE_MULTI_DISPLAY`]: the host's pointer is over a
/// display the guest's cursor is not on, and the guest moves its cursor there.
pub const RGFX_EVT_POINTER_OVER: u32 = 0x104;
/// Event `POINTER_MOTION` ([`RgfxPointerMotion`]), sent only to a guest that took
/// [`RGFX_FEATURE_POINTER_MOTION`]: the host's pointing device moved, turned its wheel or pressed
/// or let go of a button, and the guest's relative pointing device does the same.
pub const RGFX_EVT_POINTER_MOTION: u32 = 0x105;
/// `COMPLETE`'s status: the command was done.
pub const RGFX_STATUS_OK: u32 = 0;
@@ -1675,6 +1687,31 @@ pub struct RgfxPointerOver {
pub buttons: u32,
}
/// `POINTER_MOTION`: the host's pointing device moved by (`dx`, `dy`), right and down, in its own
/// counts, as no acceleration has changed them, turned its wheel `wheel` notches up (away from the
/// person), and holds the `RGFX_POINTER_BUTTON_*` `buttons` after it. The guest's driver hands it
/// to its relative pointing device as one report of a USB mouse, so the guest accelerates the
/// motion as its own settings say, once, and a game that reads the device's counts gets the
/// host's. Only a guest that took [`RGFX_FEATURE_POINTER_MOTION`] is sent it; motion that finds
/// the ring held or full is added to the next event of the same buttons, so a press or a release
/// is never lost.
#[repr(C)]
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
)]
pub struct RgfxPointerMotion {
/// [`RGFX_EVT_POINTER_MOTION`], `seqno` 0.
pub header: RgfxMsgHeader,
/// The motion to the right, in the device's counts.
pub dx: i32,
/// The motion down, in the device's counts.
pub dy: i32,
/// Wheel notches, above 0 up (away from the person).
pub wheel: i32,
/// The buttons held after it: `RGFX_POINTER_BUTTON_*` bits.
pub buttons: u32,
}
/// [`RgfxPointerOver`]'s `buttons`: the left button held.
pub const RGFX_POINTER_BUTTON_LEFT: u32 = 1 << 0;
/// [`RgfxPointerOver`]'s `buttons`: the right button held.
@@ -1715,6 +1752,9 @@ const _: () = {
assert!(size_of::<RgfxDisplayChanged>() == 24);
assert!(size_of::<RgfxVblank>() == 40);
assert!(size_of::<RgfxPointerOver>() == 32);
assert!(size_of::<RgfxPointerMotion>() == 32);
assert!(offset_of!(RgfxPointerMotion, wheel) == 24);
assert!(offset_of!(RgfxPointerMotion, buttons) == 28);
assert!(size_of::<RgfxDisplayBounds>() == 40);
assert!(RGFX_CONTROL_RING_DATA_SIZE.is_power_of_two());
assert!(
@@ -5001,7 +5041,8 @@ const _: () = {
assert!(size_of::<RgfxMeshPipelineReflection>() == 24);
// Each exact size above is a multiple of 8, as a ring message must be.
// The stage-3 opcodes do not collide with the stage-2 ones or each other.
assert!(RGFX_CMD_QUEUE_CREATE > RGFX_EVT_POINTER_OVER);
assert!(RGFX_CMD_QUEUE_CREATE > RGFX_EVT_POINTER_MOTION);
assert!(RGFX_EVT_POINTER_MOTION > RGFX_EVT_POINTER_OVER);
assert!(RGFX_CMD_COMMAND_BUFFER > RGFX_CMD_FENCE_CREATE);
assert!(RGFX_EVT_CB_COMPLETE > RGFX_CMD_COMMAND_BUFFER_IN_REGION);
assert!(RGFX_CMD_COMMAND_BUFFER_IN_REGION > RGFX_CMD_COMMAND_BUFFER);
@@ -48,6 +48,11 @@ CHECK(sizeof(RgfxPointerOver) == 32);
CHECK(offsetof(RgfxPointerOver, y) == 24);
CHECK(offsetof(RgfxPointerOver, buttons) == 28);
CHECK(RGFX_EVT_POINTER_OVER == 0x104);
CHECK(sizeof(RgfxPointerMotion) == 32);
CHECK(offsetof(RgfxPointerMotion, wheel) == 24);
CHECK(offsetof(RgfxPointerMotion, buttons) == 28);
CHECK(RGFX_EVT_POINTER_MOTION == 0x105);
CHECK(RGFX_FEATURE_POINTER_MOTION == (1ULL << 51));
CHECK(RGFX_POINTER_BUTTON_LEFT == 1 && RGFX_POINTER_BUTTON_EXTRA == 16);
CHECK(sizeof(RgfxDisplayBounds) == 40);
CHECK(offsetof(RgfxDisplayBounds, min_x) == 20);
+57 -2
View File
@@ -210,6 +210,40 @@ Unset or unparsable values give the defaults below.
`test: reims-vgpu-graphics::device::tests::displays::the_pointer_over_another_display_tells_the_guest_once`,
`test: reims-vgpu-graphics::device::tests::displays::a_crossing_holds_the_pointer_until_the_guest_s_cursor_is_there`,
`manual` (a VM with two displays)
- In a game: captured, once the guest has hidden its cursor on every display
for 50 ms, as a game does that turns its camera by the mouse's motion, the
pointer drives the guest's own mouse (`POINTER_MOTION`,
docs/graphics-kext/design.md, "A pointer for games"), so the camera turns
however far the mouse moves, past the image's edge. The window holds the
host's pointer still (`CGAssociateMouseAndMouseCursorPosition`) and hands
the guest's mouse its unaccelerated motion, the buttons pressed meanwhile
and a mouse wheel's notches; the guest accelerates the motion once, as its
own mouse settings say. Once the guest shows its cursor again (the game's
menu, or the next move after typing hid it), the pointer is the absolute
one again, the host's pointer let go over the guest's cursor where it shows
on the window's display, else where it was held. A button comes up by the
route it went down by, so one held across either switch is never left
down. Releasing capture, losing the keyboard and closing let the pointer go
where it was held. On the desktop, and with a guest whose kext does not
take `POINTER_MOTION` (one built before it, the option ROM, Ambrosia's
module), the pointer is the absolute one only.
`test: game::the_guest_s_mouse_is_driven_once_its_cursor_stays_hidden`,
`test: game::moves_go_to_the_guest_s_mouse_until_it_shows_its_cursor`,
`test: game::a_button_comes_up_by_the_route_it_went_down_by`,
`test: game::the_wheel_goes_to_the_driven_mouse`,
`test: game::capture_s_end_and_a_refused_lock_give_the_pointer_back_where_held`,
`test: native::macos::input::the_tablet_s_events_are_unchanged_outside_a_game`,
`test: native::macos::input::a_hidden_cursor_s_motion_drives_the_guest_s_mouse_until_it_shows`,
`test: native::macos::input::a_button_held_across_the_switch_comes_up_by_its_own_route`,
`test: native::macos::input::letting_go_of_a_game_gives_the_pointer_back_where_it_was_held`,
`test: reims-vgpu::graphics::tests::displays::a_window_s_device_offers_pointer_motion_and_drives_the_guest_s_mouse`,
`test: reims-vgpu-graphics::device::tests::motion::a_guest_that_did_not_take_pointer_motion_gets_none`,
`test: reims-vgpu-graphics::device::tests::motion::the_cursor_is_hidden_once_every_display_it_sees_hides_it`,
`test: reims-vgpu-graphics::device::tests::motion::owed_motion_joins_and_a_press_never_does`,
`manual` (a game, or a probe that hides the cursor and reads its deltas:
the camera turns past the image's edge; a drag on the desktop lands where
the pointer is; typing in TextEdit hides the cursor, and the next move
shows it where the guest moved it, the host's pointer over it)
## Keyboard
@@ -254,7 +288,10 @@ Unset or unparsable values give the defaults below.
too, never a resize of the window. Released, the pointer goes where the
person moves it, and the window resizes again. In native full screen an
image that reaches the screen's top or bottom edge takes the pointer there,
where macOS slides its own menu bar or Dock in.
where macOS slides its own menu bar or Dock in. While the pointer drives
the guest's mouse in a game (Pointer), the host's pointer is held still
instead, and capture's end lets it go where it was held.
`test: native::macos::input::letting_go_of_a_game_gives_the_pointer_back_where_it_was_held`,
`test: capture::captured_input_holds_the_pointer_over_the_image`,
`test: capture::a_captured_window_cannot_be_resized`,
`test: native::macos::shell::a_windowed_window_is_not_resizable_while_captured`,
@@ -486,6 +523,23 @@ runtime's own device. The switches above apply, and `resolution=` too.
`test: handle::a_pointer_from_beyond_reaches_the_host_and_the_window_draws_the_cursor`,
`manual` (a VM with two displays: a Finder window dragged across and back,
display 1 right of display 0 and left of it)
- In a game, as on macOS (Pointer): the window locks the host's pointer
(SDL's relative mode, the compositor's pointer lock on Wayland) and hands
the guest's mouse its unaccelerated motion (`SDL_MOUSE_RELATIVE_SYSTEM_SCALE`
0 while it does: relative-pointer's unaccelerated motion on Wayland, XInput2's
raw motion on X11), its buttons pressed meanwhile and the wheel's notches,
until the guest shows its cursor, where the host's pointer is let go over
it; a button comes up by the route it went down by; releasing capture
(Ctrl+Alt+Super), losing the keyboard and closing let it go where it was
held. Gone past a shared edge when the guest hides its cursor, the pointer
drives the guest's mouse from there. Where the compositor refuses the lock,
the pointer stays the absolute one until capture changes.
`test: native::sdl_thread::input::the_tablet_s_events_are_unchanged_outside_a_game`,
`test: native::sdl_thread::input::a_hidden_cursor_s_motion_drives_the_guest_s_mouse_until_it_shows`,
`test: native::sdl_thread::input::a_button_held_across_the_switch_comes_up_by_its_own_route`,
`test: native::sdl_thread::input::letting_go_of_a_game_gives_the_pointer_back_where_it_was_held`,
`test: reims-vgpu-graphics::device::tests::motion::motion_reaches_a_guest_that_took_it`,
`manual` (as on macOS, on a Linux host's guest boot)
- Keys by position, as evdev reports them, so the guest's layout applies and
ISO keys arrive as on a real ISO keyboard; media keys are dropped.
`test: native::sdl_thread::keymap::scancodes_are_usb_usages`,
@@ -504,7 +558,8 @@ runtime's own device. The switches above apply, and `resolution=` too.
compositor's pointer constraints keep on Wayland and XFixes barriers on
X11 (where SDL has no mouse rect, its mouse grab holds the pointer in the
whole window), except past an edge where the guest placed another display
(Pointer, above); the window stays resizable, its resize edges being the
and while it drives the guest's mouse in a game (Pointer, above); the
window stays resizable, its resize edges being the
compositor's, outside its surface and beyond the hold; Ctrl+Alt+Super
releases both; losing the keyboard releases; the window's end releases
both, and the grab and the hold go with the capture before it hides; the
+11 -2
View File
@@ -25,8 +25,12 @@ use crate::geometry::{self, Rect};
/// What the window does with the host's pointer as it leaves and comes back.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Hold {
/// Holds it still where it is, hidden, its moves reported as motion alone.
/// Holds it still where it is, hidden, its moves reported as motion alone, as the desktop
/// accelerates them.
Lock,
/// Holds it still where it is, hidden, its moves reported as the device's own counts, as no
/// acceleration has changed them: the pointer for games ([`crate::game`]).
Raw,
/// Lets it go at the window's point (in points), over the image.
Unlock((f64, f64)),
}
@@ -117,7 +121,7 @@ pub fn at_shared_edge(
}
/// The window's point at the centre of guest pixel `at` of `mode`, over `image`.
fn point_of(at: (u16, u16), image: Rect, mode: (u16, u16)) -> (f64, f64) {
pub(crate) fn point_of(at: (u16, u16), image: Rect, mode: (u16, u16)) -> (f64, f64) {
(
image.x + (f64::from(at.0) + 0.5) * image.width / f64::from(mode.0.max(1)),
image.y + (f64::from(at.1) + 0.5) * image.height / f64::from(mode.1.max(1)),
@@ -219,6 +223,11 @@ impl Beyond {
}
}
/// Where the host's pointer was held when it went past the edge, while it is away.
pub fn held(&self) -> Option<(f64, f64)> {
self.away.map(|away| away.held)
}
/// A button went down or up while away: the pointer's new `buttons`, where it is.
pub fn buttons(&self, beyond: &dyn PointerBeyond, buttons: u32) {
if self.away.is_some() {
+25
View File
@@ -110,6 +110,26 @@ pub trait PointerBeyond: Send + Sync {
fn come_back(&self);
}
/// The guest's own relative pointing device, a mouse, which a window's captured pointer drives
/// while the guest hides its cursor, as a game does that turns its camera by the mouse's motion
/// ([`WindowCallbacks::motion`], [`crate::game`]): the reims-graphics device's `POINTER_MOTION`.
/// Its calls run on the window's UI thread, as the callbacks do.
pub trait PointerMotion: Send + Sync {
/// How long, in nanoseconds, the guest has hidden its cursor on every display it sees,
/// where it takes motion; `None` where it shows it on one, or takes none.
fn hidden_for(&self) -> Option<u64>;
/// The host's pointing device moved by `by` of its counts, unaccelerated, right then down,
/// turned its wheel `wheel` notches up, and holds the `BUTTON_*` `buttons` after it: the
/// guest's mouse does the same. Whether the guest took it.
fn moved(&self, by: (i32, i32), wheel: i32, buttons: u32) -> bool;
}
impl std::fmt::Debug for dyn PointerMotion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("PointerMotion")
}
}
/// Where a captured pointer gone past the image's edge landed ([`PointerBeyond::moved`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Landed {
@@ -146,6 +166,10 @@ pub struct WindowCallbacks {
/// Without it, it is held at the image's edges. Taken by the SDL window on Linux and Windows
/// alone: on macOS the window holds the pointer at its edges whatever this is.
pub beyond: Option<Arc<dyn PointerBeyond>>,
/// The guest's own mouse, which the captured pointer drives while the guest hides its cursor
/// ([`crate::game`]). Without it, the pointer stays the host's absolute one. Taken by the SDL
/// window on Linux and Windows and by the macOS window.
pub motion: Option<Arc<dyn PointerMotion>>,
}
impl std::fmt::Debug for WindowCallbacks {
@@ -157,6 +181,7 @@ impl std::fmt::Debug for WindowCallbacks {
.field("close", &self.close.is_some())
.field("scroll", &self.scroll.is_some())
.field("beyond", &self.beyond.is_some())
.field("motion", &self.motion.is_some())
.finish()
}
}
+345
View File
@@ -0,0 +1,345 @@
//! A pointer for games: what a window decides of its captured pointer while the guest hides its
//! cursor, with no OS in it (the SDL window's input, `native/sdl_thread/input.rs`, drives it on
//! Linux and Windows, and the macOS window's input on macOS).
//!
//! The guest's pointer is the host's absolute one (QEMU's USB tablet), held at the image's edge
//! outside it, and captured, the host's pointer is held over the image (`capture`). A game that
//! hides the cursor and turns its camera by the mouse's motion (a disassociated cursor's deltas,
//! GCMouse) then gets no motion past the edge: the tablet stays where it is. Where the guest has
//! its own mouse ([`PointerMotion`], the reims-graphics device's `POINTER_MOTION`), the window,
//! captured, with the guest's cursor hidden on every display for [`SETTLE_NS`], holds the host's
//! pointer still where it is ([`Hold::Raw`]: the OS's pointer lock, which hides it and reports
//! its moves as the device's own counts) and hands each move to the guest's mouse
//! ([`Game::moved`]), which the guest accelerates once, as its own settings say: the camera turns
//! as far as the mouse moves. Once the guest shows its cursor again ([`Game::shown`]), the pointer
//! is the window's again, the host's pointer let go over the guest's cursor where it shows on the
//! window's display, else where it was held; letting go of capture (the release chord, the
//! keyboard lost, the window's end) lets it go where it was held ([`Game::end`]). On the desktop,
//! where the guest shows its cursor, the pointer stays the absolute one, exact.
//!
//! A button goes up by the route it went down by: one pressed while the guest's mouse is driven
//! goes down and up through it, one pressed before through the tablet, whenever each comes up
//! ([`Game::release`]), so a button held across either switch is never left down. The wheel's
//! notches go to the guest's mouse while it is driven ([`Game::wheel`]).
use crate::beyond::Hold;
use crate::config::PointerMotion;
/// How long the guest's cursor stays hidden on every display it sees before the captured
/// pointer drives the guest's mouse: past a hide and a show in a row. WindowServer hides and
/// shows the cursor a dozen times as it starts (lane gamemouse, potluck job m3-max-35167), and the
/// cursor going from one display to the next is hidden on the one before it shows on the other.
pub const SETTLE_NS: u64 = 50_000_000;
/// The captured pointer driving the guest's mouse, or not (the module doc).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Game {
/// Where the host's pointer was held as it began, in the window's points, while it drives the
/// guest's mouse.
held: Option<(f64, f64)>,
/// The `BUTTON_*` buttons that went down through the guest's mouse and have not come up.
buttons: u32,
/// The motion's parts below a count, not sent yet.
rest: (f64, f64),
/// The OS refused to lock the host's pointer: no new start until capture changes.
refused: bool,
}
impl Game {
/// Not driving the guest's mouse.
pub fn new() -> Game {
Game::default()
}
/// Whether the captured pointer drives the guest's mouse: the window reports its moves as
/// motion alone ([`Self::moved`]).
pub fn is_on(&self) -> bool {
self.held.is_some()
}
/// The buttons held through the guest's mouse.
pub fn buttons(&self) -> u32 {
self.buttons
}
/// Whether the captured pointer at `point`, in the window's points, begins to drive the
/// guest's mouse `motion`: the guest has hidden its cursor on every display for
/// [`SETTLE_NS`], and the OS did not refuse the lock since capture last changed. Where it
/// does, the host's pointer is held there ([`Hold::Raw`]).
pub fn begin(&mut self, motion: &dyn PointerMotion, point: (f64, f64)) -> Option<Hold> {
if self.held.is_some() || self.refused {
return None;
}
if !motion.hidden_for().is_some_and(|ns| ns >= SETTLE_NS) {
return None;
}
self.held = Some(point);
self.rest = (0.0, 0.0);
Some(Hold::Raw)
}
/// The host's pointer moved by `by`, its device's counts: the guest's mouse moves by the whole
/// counts, the parts below a count kept for the next. Where the guest shows its cursor again,
/// the pointer is the window's again ([`Self::shown`]). `None` while it drives the mouse, or
/// did not.
pub fn moved(
&mut self,
motion: &dyn PointerMotion,
by: (f64, f64),
cursor: Option<(f64, f64)>,
) -> Option<Hold> {
self.held?;
let whole = |rest: &mut f64, by: f64| -> i32 {
let total = *rest + if by.is_finite() { by } else { 0.0 };
let counts = total.trunc();
*rest = total - counts;
counts.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32
};
let counts = (whole(&mut self.rest.0, by.0), whole(&mut self.rest.1, by.1));
if counts != (0, 0) {
motion.moved(counts, 0, self.buttons);
}
self.shown(motion, cursor)
}
/// Whether the guest shows its cursor again: the pointer is then the window's again, the
/// host's pointer let go at `cursor`, the window's point over the guest's cursor where it
/// shows on the window's display, else where it was held. `None` while the guest hides it,
/// or where the pointer did not drive the mouse.
pub fn shown(
&mut self,
motion: &dyn PointerMotion,
cursor: Option<(f64, f64)>,
) -> Option<Hold> {
let held = self.held?;
if motion.hidden_for().is_some() {
return None;
}
self.held = None;
Some(Hold::Unlock(cursor.unwrap_or(held)))
}
/// Button `bit` went down: where the pointer drives the guest's mouse, it goes down there.
/// Whether it did; else it is the tablet's.
pub fn press(&mut self, motion: Option<&dyn PointerMotion>, bit: u32) -> bool {
let Some(motion) = motion.filter(|_| self.held.is_some()) else {
return false;
};
if bit != 0 && self.buttons & bit == 0 {
self.buttons |= bit;
motion.moved((0, 0), 0, self.buttons);
}
true
}
/// Button `bit` went up: where it went down through the guest's mouse, it comes up there,
/// whether or not the pointer still drives it. Whether it did; else it is the tablet's.
pub fn release(&mut self, motion: Option<&dyn PointerMotion>, bit: u32) -> bool {
if bit == 0 || self.buttons & bit == 0 {
return false;
}
self.buttons &= !bit;
if let Some(motion) = motion {
motion.moved((0, 0), 0, self.buttons);
}
true
}
/// The wheel turned `notches` up: where the pointer drives the guest's mouse, they go there.
/// Whether they did.
pub fn wheel(&mut self, motion: Option<&dyn PointerMotion>, notches: i32) -> bool {
let Some(motion) = motion.filter(|_| self.held.is_some()) else {
return false;
};
if notches != 0 {
motion.moved((0, 0), notches, self.buttons);
}
true
}
/// Every button held through the guest's mouse comes up (the keyboard lost, the window's
/// end).
pub fn lift(&mut self, motion: Option<&dyn PointerMotion>) {
if self.buttons == 0 {
return;
}
self.buttons = 0;
if let Some(motion) = motion {
motion.moved((0, 0), 0, 0);
}
}
/// Capture changed (released, the keyboard lost, the window's end): the pointer is the
/// window's again, the host's pointer let go where it was held, and a refused lock may be
/// tried again at the next capture. `None` where it did not drive the mouse.
pub fn end(&mut self) -> Option<Hold> {
self.refused = false;
let held = self.held.take()?;
Some(Hold::Unlock(held))
}
/// The OS refused to lock the host's pointer: the pointer is the window's again, where it
/// was held, and it does not try again until capture changes.
pub fn refused(&mut self) -> Option<Hold> {
let held = self.held.take()?;
self.refused = true;
Some(Hold::Unlock(held))
}
}
#[cfg(test)]
pub(crate) mod tests {
use reims_vgpu_vulkan::core::sync::Mutex;
use super::*;
/// What a guest's mouse was sent, in order: each motion, wheel and buttons.
pub(crate) type Sent = Vec<((i32, i32), i32, u32)>;
/// A guest's mouse: how long its cursor is hidden, and what it was sent.
#[derive(Debug, Default)]
pub(crate) struct Mouse {
pub(crate) hidden: Mutex<Option<u64>>,
pub(crate) sent: Mutex<Sent>,
}
impl PointerMotion for Mouse {
fn hidden_for(&self) -> Option<u64> {
*self.hidden.lock()
}
fn moved(&self, by: (i32, i32), wheel: i32, buttons: u32) -> bool {
self.sent.lock().push((by, wheel, buttons));
true
}
}
impl Mouse {
pub(crate) fn hide_for(&self, ns: u64) {
*self.hidden.lock() = Some(ns);
}
pub(crate) fn show(&self) {
*self.hidden.lock() = None;
}
pub(crate) fn take(&self) -> Sent {
std::mem::take(&mut *self.sent.lock())
}
}
/// The captured pointer drives the guest's mouse only once the guest has hidden its cursor
/// for the settle: not while it shows it, not over a hide and a show in a row
#[test]
fn the_guest_s_mouse_is_driven_once_its_cursor_stays_hidden() {
let mouse = Mouse::default();
let mut game = Game::new();
assert_eq!(game.begin(&mouse, (5.0, 5.0)), None, "shown");
mouse.hide_for(SETTLE_NS - 1);
assert_eq!(
game.begin(&mouse, (5.0, 5.0)),
None,
"hidden for less than the settle"
);
mouse.show();
assert_eq!(
game.begin(&mouse, (5.0, 5.0)),
None,
"shown again: the count starts over"
);
mouse.hide_for(SETTLE_NS);
assert_eq!(game.begin(&mouse, (5.0, 5.0)), Some(Hold::Raw));
assert!(game.is_on());
assert_eq!(game.begin(&mouse, (6.0, 6.0)), None, "begun once");
}
/// Each move goes to the guest's mouse in whole counts, the parts below one carried on, and
/// the guest's show of its cursor gives the pointer back over its cursor, or where it was held
#[test]
fn moves_go_to_the_guest_s_mouse_until_it_shows_its_cursor() {
let mouse = Mouse::default();
let mut game = Game::new();
mouse.hide_for(SETTLE_NS);
game.begin(&mouse, (5.0, 6.0));
assert_eq!(game.moved(&mouse, (2.5, -1.25), Some((9.0, 9.0))), None);
assert_eq!(game.moved(&mouse, (0.75, -0.75), None), None);
assert_eq!(game.moved(&mouse, (0.25, 0.0), None), None);
assert_eq!(mouse.take(), vec![((2, -1), 0, 0), ((1, -1), 0, 0)]);
mouse.show();
assert_eq!(
game.moved(&mouse, (1.0, 0.0), Some((40.0, 30.0))),
Some(Hold::Unlock((40.0, 30.0))),
"let go over the guest's cursor"
);
assert!(!game.is_on());
assert_eq!(
mouse.take(),
vec![((1, 0), 0, 0)],
"the move before the show goes"
);
assert_eq!(game.moved(&mouse, (1.0, 0.0), None), None, "not driven now");
assert_eq!(mouse.take(), vec![]);
// Shown elsewhere: let go where it was held.
mouse.hide_for(SETTLE_NS);
game.begin(&mouse, (7.0, 8.0));
mouse.show();
assert_eq!(game.shown(&mouse, None), Some(Hold::Unlock((7.0, 8.0))));
}
/// A button goes up by the route it went down by, whichever way the pointer switched while it
/// was held: one pressed through the tablet comes up there while the guest's mouse is driven,
/// and one pressed through the guest's mouse comes up there once the pointer is the window's
/// again
#[test]
fn a_button_comes_up_by_the_route_it_went_down_by() {
let mouse = Mouse::default();
let mut game = Game::new();
// Pressed through the tablet, before: not the mouse's, then or after the switch.
assert!(!game.press(Some(&mouse), 2));
mouse.hide_for(SETTLE_NS);
game.begin(&mouse, (0.0, 0.0));
assert!(!game.release(Some(&mouse), 2), "the tablet's to lift");
// Pressed through the mouse, released after the switch back: the mouse's.
assert!(game.press(Some(&mouse), 1));
mouse.show();
assert!(game.shown(&mouse, None).is_some());
assert!(!game.press(Some(&mouse), 4), "pressed now: the tablet's");
assert!(game.release(Some(&mouse), 1), "the mouse's to lift");
assert!(!game.release(Some(&mouse), 1), "once");
assert_eq!(mouse.take(), vec![((0, 0), 0, 1), ((0, 0), 0, 0)]);
}
/// The wheel goes to the guest's mouse while it is driven, with the buttons held there
#[test]
fn the_wheel_goes_to_the_driven_mouse() {
let mouse = Mouse::default();
let mut game = Game::new();
assert!(!game.wheel(Some(&mouse), 1), "not driven");
mouse.hide_for(SETTLE_NS);
game.begin(&mouse, (0.0, 0.0));
game.press(Some(&mouse), 1);
assert!(game.wheel(Some(&mouse), -2));
assert_eq!(mouse.take(), vec![((0, 0), 0, 1), ((0, 0), -2, 1)]);
}
/// Capture's end lets the host's pointer go where it was held, and a refused lock is tried
/// again only once capture changed; the keyboard lost lifts the mouse's buttons
#[test]
fn capture_s_end_and_a_refused_lock_give_the_pointer_back_where_held() {
let mouse = Mouse::default();
let mut game = Game::new();
mouse.hide_for(SETTLE_NS);
game.begin(&mouse, (3.0, 4.0));
game.press(Some(&mouse), 1);
game.lift(Some(&mouse));
assert_eq!(game.end(), Some(Hold::Unlock((3.0, 4.0))));
assert_eq!(game.end(), None);
assert_eq!(mouse.take(), vec![((0, 0), 0, 1), ((0, 0), 0, 0)]);
game.begin(&mouse, (1.0, 1.0));
assert_eq!(game.refused(), Some(Hold::Unlock((1.0, 1.0))));
assert_eq!(
game.begin(&mouse, (1.0, 1.0)),
None,
"refused until capture changes"
);
assert_eq!(game.end(), None);
assert_eq!(game.begin(&mouse, (1.0, 1.0)), Some(Hold::Raw));
}
}
+7
View File
@@ -548,6 +548,13 @@ impl Window {
})
}
/// The guest's cursor's hot spot, in its mode's pixels, where the guest shows it on the
/// window's display.
pub(crate) fn shown_cursor_at(&self) -> Option<(u16, u16)> {
let guest = self.guest.lock();
guest.cursor_visible.then(|| guest.lead.at()).flatten()
}
/// What the guest last reported.
pub(crate) fn guest(&self) -> GuestState {
self.guest.lock().clone()
+3 -2
View File
@@ -47,6 +47,7 @@ pub mod beyond;
pub mod capture;
pub mod config;
pub mod env;
pub mod game;
pub mod geometry;
pub mod handle;
pub mod keymap;
@@ -63,8 +64,8 @@ mod sdl;
pub use config::{
BUTTON_EXTRA, BUTTON_LEFT, BUTTON_MIDDLE, BUTTON_RIGHT, BUTTON_SIDE, CloseFn, KeyFn, Landed,
MomentumPhase, PointerBeyond, PointerFn, ScrollEvent, ScrollFn, ScrollPhase, WheelFn,
WindowCallbacks, WindowConfig,
MomentumPhase, PointerBeyond, PointerFn, PointerMotion, ScrollEvent, ScrollFn, ScrollPhase,
WheelFn, WindowCallbacks, WindowConfig,
};
pub use handle::{DrawnCursor, FrameSink, Glyph, PixelRect, Window};
pub use present::{Drawn, Presenter, VulkanTarget};
@@ -32,6 +32,14 @@
//! releases capture.
//! - **No stuck keys**: losing the keyboard, releasing capture and closing send an up for every
//! key held; losing the keyboard and closing lift the buttons held too.
//! - **For games**, where the guest has its own mouse ([`crate::PointerMotion`]): captured, while
//! the guest hides its cursor on every display, the window holds the host's pointer still
//! (`CGAssociateMouseAndMouseCursorPosition(false)`, which the view applies) and hands its
//! unaccelerated motion (the events' `kCGEventUnacceleratedPointerMovementX` and `Y`, else
//! their deltas), its buttons pressed meanwhile and a mouse wheel's notches to the guest's
//! mouse ([`crate::game`]), until the guest shows its cursor again, where the host's pointer
//! is let go over it; a button comes up by the route it went down by. Releasing capture,
//! losing the keyboard and closing let the pointer go where it was held.
//!
//! While captured, the window holds the system's hot keys off ([`super::hotkeys`]), the host's
//! pointer over the image ([`InputState::pointer_confinement`], which the view applies), and its
@@ -40,18 +48,35 @@
use std::sync::Arc;
use objc2_app_kit::{NSEvent, NSEventPhase, NSEventType};
use objc2_core_graphics::{CGEvent, CGEventField};
use objc2_core_foundation::CGPoint;
use objc2_core_graphics::{CGError, CGEvent, CGEventField, CGWarpMouseCursorPosition};
use reims_vgpu_vulkan::os::msg;
use super::hotkeys;
use crate::beyond::{Hold, point_of};
use crate::capture::{Capture, Route};
use crate::config::{MomentumPhase, ScrollEvent, ScrollPhase, WindowCallbacks};
use crate::config::{MomentumPhase, PointerMotion, ScrollEvent, ScrollPhase, WindowCallbacks};
use crate::game::Game;
use crate::geometry::{self, Rect};
use crate::handle::Window;
use crate::keymap;
use crate::keys::{FLAG_COMMAND, KeyEvent, KeyState};
use crate::scroll::{self, Gesture, Scroll, ScrollInput};
// CoreGraphics' own, which objc2-core-graphics binds only with its `libc` feature.
#[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C-unwind" {
fn CGAssociateMouseAndMouseCursorPosition(connected: libc::boolean_t) -> CGError;
}
/// Joins the host's pointer to the mouse again (`true`), or holds it still while the mouse's
/// events go on reporting its motion: whether CoreGraphics did.
fn associate_mouse(connected: bool) -> bool {
// SAFETY: CoreGraphics' function takes a boolean and returns its error, on any thread.
let error = unsafe { CGAssociateMouseAndMouseCursorPosition(libc::boolean_t::from(connected)) };
error == CGError::Success
}
/// What the view knows when an event reaches it.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct ViewContext {
@@ -64,6 +89,8 @@ pub(crate) struct ViewContext {
pub(crate) guest: Option<(u16, u16)>,
/// Whether the window was key when the event arrived.
pub(crate) window_is_key: bool,
/// The guest's cursor, in its mode's pixels, where it shows over the window's display.
pub(crate) cursor: Option<(u16, u16)>,
}
/// What the view does after an event.
@@ -125,6 +152,14 @@ struct KeyInput {
repeat: bool,
}
/// The view's point over the guest's cursor in `cx`, where it shows over the window's display.
fn cursor_point(cx: &ViewContext) -> Option<(f64, f64)> {
let mode = guest_mode(cx)?;
let cursor = cx.cursor?;
let inside = (cursor.0.min(mode.0 - 1), cursor.1.min(mode.1 - 1));
Some(point_of(inside, cx.image, mode))
}
/// The guest's mode in `cx`, where it has one with pixels: the pointer is sent only then, since
/// the host scales it by the mode.
fn guest_mode(cx: &ViewContext) -> Option<(u16, u16)> {
@@ -193,6 +228,12 @@ struct InputLogic {
last: Option<PointerAt>,
/// What to send, in order, since the host's callbacks last took it.
out: Vec<ToHost>,
/// The guest's own mouse, where the host gives it.
motion: Option<Arc<dyn PointerMotion>>,
/// Whether the captured pointer drives it.
game: Game,
/// What the view does with the host's pointer next, since it last took it.
hold: Option<Hold>,
}
impl InputLogic {
@@ -265,8 +306,11 @@ impl InputLogic {
}
/// A button went down: `bit` its `BUTTON_*` bit, 0 for one past the guest tablet's five,
/// `flags` the event's `modifierFlags`.
/// `flags` the event's `modifierFlags`. Driving the guest's mouse, it goes down there.
fn button_down(&mut self, bit: u32, flags: u64, cx: &ViewContext) -> Reaction {
if self.game.press(self.motion.as_deref(), bit) {
return Reaction::default();
}
let (Some(mode), Some(point)) = (guest_mode(cx), cx.point) else {
return Reaction::default();
};
@@ -286,14 +330,20 @@ impl InputLogic {
}
/// A button went up: `bit` its `BUTTON_*` bit. Sent only for a button the guest was told
/// is down, wherever the pointer is.
/// is down, wherever the pointer is, by the route it went down by (the guest's mouse, or the
/// tablet, where it last was while the pointer drives the mouse).
fn button_up(&mut self, bit: u32, cx: &ViewContext) -> Reaction {
if self.game.release(self.motion.as_deref(), bit) {
return Reaction::default();
}
if bit == 0 || self.buttons & bit == 0 {
return Reaction::default();
}
self.buttons &= !bit;
match (guest_mode(cx), cx.point) {
(Some(mode), Some(point)) => self.send_pointer(point, cx.image, mode),
(Some(mode), Some(point)) if !self.game.is_on() => {
self.send_pointer(point, cx.image, mode);
}
_ => {
if let Some(last) = self.last {
self.send_pointer_at(last.at, last.mode);
@@ -303,17 +353,70 @@ impl InputLogic {
Reaction::default()
}
/// The pointer moved, or dragged.
fn moved(&mut self, cx: &ViewContext) -> Reaction {
/// The pointer moved, or dragged, by `by`, its device's unaccelerated counts. Captured,
/// with the guest's cursor hidden, it drives the guest's mouse ([`crate::game`]); else the
/// tablet goes where it is.
fn moved(&mut self, by: (f64, f64), cx: &ViewContext) -> Reaction {
if let Some(motion) = self.motion.clone() {
if self.game.is_on() {
let cursor = cursor_point(cx);
if let Some(hold) = self.game.moved(motion.as_ref(), by, cursor) {
self.hold = Some(hold);
}
return Reaction::default();
}
if self.capture.is_captured()
&& guest_mode(cx).is_some()
&& let Some(point) = cx.point
&& let Some(hold) = self.game.begin(motion.as_ref(), point)
{
self.hold = Some(hold);
return Reaction::default();
}
}
if let (Some(mode), Some(point)) = (guest_mode(cx), cx.point) {
self.move_pointer(point, cx.image, mode);
}
Reaction::default()
}
/// The guest showed or hid its cursor: driving the guest's mouse, the pointer is the
/// window's again once the guest shows it, the host's pointer let go over it.
fn cursor_changed(&mut self, cx: &ViewContext) {
if let Some(motion) = self.motion.clone()
&& let Some(hold) = self.game.shown(motion.as_ref(), cursor_point(cx))
{
self.hold = Some(hold);
}
}
/// The OS would not hold the host's pointer still: the pointer is the window's again, where
/// it was held.
fn lock_refused(&mut self) {
if let Some(hold) = self.game.refused() {
self.hold = Some(hold);
}
}
/// Capture ended (released, the keyboard lost, the window's end): the pointer driving the
/// guest's mouse is the window's again, where it was held.
fn end_game(&mut self) {
if let Some(hold) = self.game.end() {
self.hold = Some(hold);
}
}
/// The wheel or a trackpad scrolled: as smooth scrolling when `smooth` (the host takes
/// it), else as notches.
fn scrolled(&mut self, input: ScrollInput, smooth: bool, cx: &ViewContext) -> Reaction {
if self.game.is_on() && !input.precise {
// A mouse's wheel, while the pointer drives the guest's mouse: its notches go there.
let (dy, _dx) = self.scroll.feed(input);
if dy != 0 {
self.game.wheel(self.motion.as_deref(), dy);
return Reaction::default();
}
}
let over = match (guest_mode(cx), cx.point) {
(Some(mode), Some(point)) if geometry::contains(cx.image, point) => Some((point, mode)),
_ => None,
@@ -411,6 +514,7 @@ impl InputLogic {
return Reaction::default();
}
self.lift_keys();
self.end_game();
Reaction::capture(self.capture.release())
}
@@ -433,6 +537,8 @@ impl InputLogic {
let was = self.capture.resign_key();
self.lift_keys();
self.lift_buttons();
self.game.lift(self.motion.as_deref());
self.end_game();
Reaction::capture(was)
}
@@ -440,6 +546,7 @@ impl InputLogic {
fn release_capture(&mut self) -> Reaction {
let was = self.capture.release();
self.lift_keys();
self.end_game();
Reaction::capture(was)
}
@@ -447,6 +554,8 @@ impl InputLogic {
fn window_closing(&mut self) {
self.lift_keys();
self.lift_buttons();
self.game.lift(self.motion.as_deref());
self.end_game();
self.capture.release();
}
}
@@ -502,6 +611,28 @@ fn key_input(event: &NSEvent, repeat: bool) -> KeyInput {
}
}
/// A pointer event's motion, unaccelerated: its device's counts
/// (`kCGEventUnacceleratedPointerMovementX` and `Y`), else, for an event with none, its deltas.
fn unaccelerated_motion(event: &NSEvent) -> (f64, f64) {
let cg_event = msg::get("CGEvent", || event.CGEvent());
let field = |field: CGEventField| {
cg_event
.as_deref()
.map_or(0.0, |e| CGEvent::double_value_field(Some(e), field))
};
let raw = (
field(CGEventField::EventUnacceleratedPointerMovementX),
field(CGEventField::EventUnacceleratedPointerMovementY),
);
if raw != (0.0, 0.0) {
return raw;
}
(
msg::get("deltaX", || event.deltaX()),
msg::get("deltaY", || event.deltaY()),
)
}
/// A scroll event's values ([`ScrollInput`]).
fn scroll_input(event: &NSEvent) -> ScrollInput {
let cg_event = msg::get("CGEvent", || event.CGEvent());
@@ -542,11 +673,14 @@ pub(crate) struct InputState {
}
impl InputState {
/// The input state of `window`, made on the main thread.
/// The input state of `window`, made on the main thread, driving the guest's mouse where the
/// host gives it.
pub(crate) fn new(window: Arc<Window>) -> InputState {
let mut logic = InputLogic::new(crate::native::is_iso_keyboard());
logic.motion = window.callbacks().and_then(|callbacks| callbacks.motion);
InputState {
window,
logic: InputLogic::new(crate::native::is_iso_keyboard()),
logic,
holds_hotkeys: false,
}
}
@@ -592,11 +726,51 @@ impl InputState {
}
/// The pointer moved, with or without a button held (`mouseMoved:`, `*MouseDragged:`).
pub(crate) fn mouse_moved(&mut self, _event: &NSEvent, cx: &ViewContext) -> Reaction {
let reaction = self.logic.moved(cx);
pub(crate) fn mouse_moved(&mut self, event: &NSEvent, cx: &ViewContext) -> Reaction {
let reaction = self.logic.moved(unaccelerated_motion(event), cx);
self.finish(reaction)
}
/// The guest showed or hid its cursor (the module doc).
pub(crate) fn cursor_changed(&mut self, cx: &ViewContext) {
self.logic.cursor_changed(cx);
}
/// Holds the host's pointer still while it drives the guest's mouse, or lets it go at a
/// point in the view's points, which `global` places in the displays' global coordinates, as
/// the logic asks: `CGAssociateMouseAndMouseCursorPosition`, whose events go on reporting the
/// mouse's motion with the pointer still. Letting go warps the pointer to the point and
/// joins it to the mouse again, which also ends the warp's pause of the mouse's events. A
/// hold the OS refuses gives the pointer back to the window, where it was held.
pub(crate) fn apply_hold(&mut self, global: impl Fn((f64, f64)) -> Option<CGPoint>) {
while let Some(hold) = self.logic.hold.take() {
let title = self.window.title();
match hold {
Hold::Raw | Hold::Lock => {
let held = associate_mouse(false);
log::debug!(
"window {title:?}: the captured pointer drives the guest's mouse \
(held: {held})"
);
if !held {
log::warn!(
"window {title:?}: the pointer cannot be held still, so a game's \
mouse stops at the image's edge"
);
self.logic.lock_refused();
}
}
Hold::Unlock(point) => {
if let Some(at) = global(point) {
CGWarpMouseCursorPosition(at);
}
associate_mouse(true);
log::debug!("window {title:?}: the pointer is back at {point:?}");
}
}
}
}
/// The wheel or a trackpad scrolled (`scrollWheel:`): smoothly where the host's callbacks
/// take it.
pub(crate) fn scroll_wheel(&mut self, event: &NSEvent, cx: &ViewContext) -> Reaction {
@@ -708,7 +882,9 @@ mod tests {
use reims_vgpu_vulkan::core::sync::Mutex;
use super::*;
use crate::config::{BUTTON_LEFT, BUTTON_RIGHT};
use crate::config::{BUTTON_LEFT, BUTTON_MIDDLE, BUTTON_RIGHT};
use crate::game::SETTLE_NS;
use crate::game::tests::Mouse;
use crate::keys::{FLAG_CONTROL, FLAG_OPTION, FLAG_SHIFT};
/// Left Shift, Control, Option and Command as `modifierFlags` carries them.
@@ -750,6 +926,7 @@ mod tests {
image: IMAGE,
guest: Some(MODE),
window_is_key: true,
cursor: None,
}
}
@@ -915,7 +1092,7 @@ mod tests {
..at((500.0, 300.0))
};
assert_eq!(logic.button_down(BUTTON_LEFT, 0, &cx), Reaction::default());
logic.moved(&cx);
logic.moved((0.0, 0.0), &cx);
for smooth in [false, true] {
logic.scrolled(
ScrollInput {
@@ -939,8 +1116,8 @@ mod tests {
fn a_drag_keeps_going_outside_the_window() {
let mut logic = captured();
logic.button_down(BUTTON_LEFT, 0, &at((580.0, 350.0)));
logic.moved(&at((5000.0, 350.0)));
logic.moved(&at((5000.0, -40.0)));
logic.moved((0.0, 0.0), &at((5000.0, 350.0)));
logic.moved((0.0, 0.0), &at((5000.0, -40.0)));
logic.button_up(BUTTON_LEFT, &at((6000.0, -80.0)));
assert_eq!(
sent(&mut logic),
@@ -957,10 +1134,10 @@ mod tests {
#[test]
fn moves_are_sent_where_the_guest_pixel_changes() {
let mut logic = InputLogic::new(false);
logic.moved(&at((580.0, 350.0)));
logic.moved(&at((580.2, 350.2)));
logic.moved(&at((580.5, 350.0)));
logic.moved(&at((20.0, 350.0)));
logic.moved((0.0, 0.0), &at((580.0, 350.0)));
logic.moved((0.0, 0.0), &at((580.2, 350.2)));
logic.moved((0.0, 0.0), &at((580.5, 350.0)));
logic.moved((0.0, 0.0), &at((20.0, 350.0)));
assert_eq!(
sent(&mut logic),
vec![
@@ -1297,6 +1474,172 @@ mod tests {
assert_eq!(sent(&mut logic), vec![up(A), pointer(0, 0, 0)]);
}
/// A captured logic driving `mouse` once the guest hides its cursor.
fn captured_with(mouse: &Arc<Mouse>) -> InputLogic {
let mut logic = captured();
logic.motion = Some(Arc::clone(mouse) as Arc<dyn PointerMotion>);
logic
}
/// Outside a game the tablet hears exactly what it hears with no guest's mouse, and the
/// guest's mouse nothing: captured while the guest shows its cursor or has hidden it for less
/// than the settle
#[test]
fn the_tablet_s_events_are_unchanged_outside_a_game() {
let desk_work = |logic: &mut InputLogic| {
logic.moved((3.0, 0.0), &at((580.0, 350.0)));
logic.button_down(BUTTON_RIGHT, 0, &at((600.0, 350.0)));
logic.moved((3.0, 0.0), &at((5000.0, 350.0)));
logic.button_up(BUTTON_RIGHT, &at((5000.0, 350.0)));
logic.scrolled(
ScrollInput {
lines: (0, 2),
..ScrollInput::default()
},
false,
&at((580.0, 350.0)),
);
sent(logic)
};
let plain = desk_work(&mut captured());
assert!(!plain.is_empty());
for hidden in [None, Some(SETTLE_NS - 1)] {
let mouse = Arc::new(Mouse::default());
*mouse.hidden.lock() = hidden;
let mut logic = captured_with(&mouse);
assert_eq!(desk_work(&mut logic), plain, "hidden for {hidden:?}");
assert_eq!(logic.hold, None);
assert_eq!(mouse.take(), vec![]);
}
}
/// Captured, once the guest has hidden its cursor for the settle, the pointer is held still
/// and its unaccelerated motion, by whole counts, and a mouse wheel's notches drive the
/// guest's mouse; the tablet hears nothing. Once the guest shows its cursor, the pointer is
/// the window's again, let go over the guest's cursor, else where it was held
#[test]
fn a_hidden_cursor_s_motion_drives_the_guest_s_mouse_until_it_shows() {
let mouse = Arc::new(Mouse::default());
let mut logic = captured_with(&mouse);
mouse.hide_for(SETTLE_NS);
logic.moved((1.0, 0.0), &at((1000.0, 350.0)));
assert_eq!(logic.hold.take(), Some(Hold::Raw));
logic.moved((700.0, 0.0), &at((1000.0, 350.0)));
logic.moved((0.5, -3.5), &at((1000.0, 350.0)));
logic.moved((0.5, 0.5), &at((1000.0, 350.0)));
logic.scrolled(
ScrollInput {
lines: (0, -1),
..ScrollInput::default()
},
false,
&at((1000.0, 350.0)),
);
assert_eq!(
mouse.take(),
vec![
((700, 0), 0, 0),
((0, -3), 0, 0),
((1, 0), 0, 0),
((0, 0), -1, 0)
]
);
assert_eq!(sent(&mut logic), vec![], "the tablet hears nothing");
mouse.show();
logic.cursor_changed(&ViewContext {
cursor: Some((100, 60)),
..at((1000.0, 350.0))
});
assert_eq!(logic.hold.take(), Some(Hold::Unlock((150.25, 80.25))));
logic.moved((0.0, 0.0), &at((150.25, 80.25)));
assert_eq!(sent(&mut logic), vec![pointer(100, 60, 0)]);
mouse.hide_for(SETTLE_NS);
logic.moved((1.0, 0.0), &at((150.0, 80.0)));
assert_eq!(logic.hold.take(), Some(Hold::Raw));
mouse.show();
logic.moved((2.0, 0.0), &at((150.0, 80.0)));
assert_eq!(mouse.take(), vec![((2, 0), 0, 0)]);
assert_eq!(logic.hold.take(), Some(Hold::Unlock((150.0, 80.0))));
}
/// A button comes up by the route it went down by, held across either switch
#[test]
fn a_button_held_across_the_switch_comes_up_by_its_own_route() {
let mouse = Arc::new(Mouse::default());
let mut logic = captured_with(&mouse);
logic.button_down(BUTTON_RIGHT, 0, &at((600.0, 350.0)));
assert_eq!(sent(&mut logic), vec![pointer(1000, 600, BUTTON_RIGHT)]);
mouse.hide_for(SETTLE_NS);
logic.moved((1.0, 0.0), &at((600.0, 350.0)));
assert_eq!(logic.hold.take(), Some(Hold::Raw));
logic.button_down(BUTTON_LEFT, 0, &at((600.0, 350.0)));
logic.button_up(BUTTON_RIGHT, &at((600.0, 350.0)));
assert_eq!(mouse.take(), vec![((0, 0), 0, BUTTON_LEFT)]);
assert_eq!(sent(&mut logic), vec![pointer(1000, 600, 0)]);
mouse.show();
logic.cursor_changed(&at((600.0, 350.0)));
assert_eq!(logic.hold.take(), Some(Hold::Unlock((600.0, 350.0))));
logic.button_up(BUTTON_LEFT, &at((600.0, 350.0)));
assert_eq!(mouse.take(), vec![((0, 0), 0, 0)]);
assert_eq!(sent(&mut logic), vec![]);
}
/// The release chord, Release Input, losing the keyboard and closing give the window back
/// the pointer driving the guest's mouse where it was held, a button held through the mouse
/// lifted on the keyboard's loss and the close; a hold the OS refuses gives it back too, and
/// is not tried again until capture changes
#[test]
fn letting_go_of_a_game_gives_the_pointer_back_where_it_was_held() {
let mouse = Arc::new(Mouse::default());
mouse.hide_for(SETTLE_NS);
let in_game = || {
let mut logic = captured_with(&mouse);
logic.moved((1.0, 0.0), &at((600.0, 350.0)));
assert_eq!(logic.hold.take(), Some(Hold::Raw));
logic
};
let mut logic = in_game();
logic.flags_changed(key(KVK_CONTROL, L_CONTROL));
logic.flags_changed(key(KVK_OPTION, L_CONTROL | L_OPTION));
logic.flags_changed(key(KVK_COMMAND, L_CONTROL | L_OPTION | L_COMMAND));
assert!(!logic.capture.is_captured());
assert_eq!(logic.hold.take(), Some(Hold::Unlock((600.0, 350.0))));
let mut logic = in_game();
logic.release_capture();
assert_eq!(logic.hold.take(), Some(Hold::Unlock((600.0, 350.0))));
let mut logic = in_game();
logic.button_down(BUTTON_LEFT, 0, &at((600.0, 350.0)));
mouse.take();
logic.focus_lost();
assert_eq!(mouse.take(), vec![((0, 0), 0, 0)]);
assert_eq!(logic.hold.take(), Some(Hold::Unlock((600.0, 350.0))));
let mut logic = in_game();
logic.button_down(BUTTON_MIDDLE, 0, &at((600.0, 350.0)));
mouse.take();
logic.window_closing();
assert_eq!(mouse.take(), vec![((0, 0), 0, 0)]);
assert_eq!(logic.hold.take(), Some(Hold::Unlock((600.0, 350.0))));
let mut logic = in_game();
logic.lock_refused();
assert_eq!(logic.hold.take(), Some(Hold::Unlock((600.0, 350.0))));
logic.moved((1.0, 0.0), &at((602.0, 350.0)));
assert_eq!(logic.hold.take(), None, "not tried again while captured");
assert_eq!(sent(&mut logic), vec![pointer(1004, 600, 0)]);
logic.release_capture();
logic.button_down(BUTTON_LEFT, 0, &at((602.0, 350.0)));
logic.moved((1.0, 0.0), &at((604.0, 350.0)));
assert_eq!(
logic.hold.take(),
Some(Hold::Raw),
"tried again at the next capture"
);
assert_eq!(mouse.take(), vec![]);
}
/// The window's end, while the host's callback for the first key-up of a lift runs, drops
/// the other key-ups: no callback of the host's starts after the end has returned
#[test]
@@ -1357,6 +1700,7 @@ mod tests {
));
})),
beyond: None,
motion: None,
};
call_host(&callbacks, pointer(3, 4, BUTTON_RIGHT));
call_host(&callbacks, ToHost::Wheel { dy: -1, dx: 2 });
@@ -298,6 +298,12 @@ pub(crate) fn grab_keyboard(_shell: &Shell, _captured: bool) {}
/// past them (`crate::beyond` is the SDL window's on Linux and Windows).
pub(crate) fn apply_hold(_shell: &mut Shell) {}
/// The guest showed or hid its cursor: AppKit's window's input follows it
/// ([`input::cursor_changed`]).
pub(crate) fn cursor_changed(shell: &mut Shell) {
input::cursor_changed(shell);
}
/// Makes a windowed window not resizable while its input is captured, and resizable again when
/// not, as AppKit's window does (`super::shell::resizable_change`): SDL's resizable flag, which
/// SDL's Cocoa code makes the window's style. A borderless window keeps its style, which SDL would
@@ -23,14 +23,17 @@
use std::sync::Arc;
use objc2::MainThreadMarker;
use objc2::Message;
use objc2::rc::Retained;
use objc2_app_kit::{NSEvent, NSEventType, NSWindow};
use objc2_foundation::NSPoint;
use reims_vgpu_vulkan::os::msg;
use crate::geometry::Rect;
use crate::handle::Window;
use crate::native::macos::input::{InputState, Reaction, ViewContext};
use crate::native::macos::main_thread::shared_app;
use crate::native::macos::view::global_of;
use crate::sdl::shell::{self, Shell};
/// A window's input: AppKit's window's ([`InputState`]), which calls the host's callbacks as each
@@ -118,9 +121,38 @@ fn context(shell: &Shell, event: &NSEvent, located: bool) -> ViewContext {
image: shell.layout.image,
guest: shell.window.mode(),
window_is_key: msg::get("isKeyWindow", || window.isKeyWindow()),
cursor: shell.window.shown_cursor_at(),
}
}
/// The guest showed or hid its cursor: a pointer driving the guest's mouse may be the window's
/// again ([`InputState::cursor_changed`]).
pub(crate) fn cursor_changed(shell: &mut Shell) {
let cx = ViewContext {
point: None,
image: shell.layout.image,
guest: shell.window.mode(),
window_is_key: msg::get("isKeyWindow", || shell.os.ns_window().isKeyWindow()),
cursor: shell.window.shown_cursor_at(),
};
shell.input.0.cursor_changed(&cx);
apply_hold(shell);
}
/// Holds the host's pointer still, or lets it go, as the input asks
/// ([`InputState::apply_hold`]): points in the content's points, y down.
fn apply_hold(shell: &mut Shell) {
let window = shell.os.ns_window().retain();
shell.input.0.apply_hold(|point| {
let content = msg::get("contentView", || window.contentView())?;
let height = msg::get("bounds", || content.bounds()).size.height;
let in_window = msg::get("convertPoint:toView:", || {
content.convertPoint_toView(NSPoint::new(point.0, height - point.1), None)
});
Some(global_of(&window, in_window))
});
}
/// Whether `point` is over `shell`'s content, in its points.
fn over_content(shell: &Shell, point: (f64, f64)) -> bool {
let Some(content) = msg::get("contentView", || shell.os.ns_window().contentView()) else {
@@ -136,6 +168,7 @@ fn react(shell: &mut Shell, reaction: Reaction) {
if reaction.capture_changed {
shell.capture_changed();
}
apply_hold(shell);
}
/// The application saw `event`, before AppKit dispatches it: true where one of SDL's windows'
@@ -71,7 +71,8 @@ use objc2_app_kit::{
NSEvent, NSEventType, NSResponder, NSTrackingArea, NSTrackingAreaOptions, NSView, NSWindow,
NSWindowOcclusionState, NSWindowStyleMask,
};
use objc2_core_foundation::CGFloat;
use objc2_core_foundation::{CGFloat, CGPoint};
use objc2_core_graphics::{CGDisplayBounds, CGMainDisplayID};
use objc2_foundation::{NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize};
use objc2_quartz_core::CAMetalLayer;
use reims_vgpu_vulkan::core::rt::BlockEnv;
@@ -482,10 +483,34 @@ impl DisplayView {
}
}
/// The guest's cursor or its visibility changed.
/// The guest's cursor or its visibility changed: a pointer driving the guest's mouse may be
/// the window's again (`input`'s module doc).
pub(crate) fn cursor_changed(&self) {
self.ivars().window.take_cursor_refresh();
self.invalidate_cursor();
let cx = self.context_now();
if let Ok(mut input) = self.ivars().input.try_borrow_mut() {
input.cursor_changed(&cx);
}
self.apply_hold();
}
/// Holds the host's pointer still while it drives the guest's mouse, or lets it go, as the
/// input asks ([`InputState::apply_hold`]).
fn apply_hold(&self) {
if let Ok(mut input) = self.ivars().input.try_borrow_mut() {
input.apply_hold(|point| self.global_point(point));
}
}
/// `point`, in the view's flipped points, in the displays' global coordinates (the main
/// display's top left the origin, y down), where the view is in a window.
fn global_point(&self, point: (f64, f64)) -> Option<CGPoint> {
let window = msg::get("window", || self.window())?;
let in_window = msg::get("convertPoint:toView:", || {
self.convertPoint_toView(NSPoint::new(point.0, point.1), None)
});
Some(global_of(&window, in_window))
}
/// The cursor rectangle over the image, with the guest's cursor, invisible while the window
@@ -527,6 +552,20 @@ impl DisplayView {
image: self.ivars().layout.get().image,
guest: self.ivars().window.mode(),
window_is_key,
cursor: self.ivars().window.shown_cursor_at(),
}
}
/// What the view knows with no event: no point.
fn context_now(&self) -> ViewContext {
let window_is_key = msg::get("window", || self.window())
.is_some_and(|w| msg::get("isKeyWindow", || w.isKeyWindow()));
ViewContext {
point: None,
image: self.ivars().layout.get().image,
guest: self.ivars().window.mode(),
window_is_key,
cursor: self.ivars().window.shown_cursor_at(),
}
}
@@ -563,6 +602,7 @@ impl DisplayView {
self.confine_pointer();
self.hold_size();
}
self.apply_hold();
reaction.pass_on
}
@@ -773,6 +813,16 @@ fn set_mouse_confinement(window: &NSWindow, rect: NSRect) {
});
}
/// `in_window`, a point in `window`'s coordinates, in the displays' global coordinates: the main
/// display's top left the origin, y down.
pub(crate) fn global_of(window: &NSWindow, in_window: NSPoint) -> CGPoint {
let on_screen = msg::get("convertPointToScreen:", || {
window.convertPointToScreen(in_window)
});
let main = CGDisplayBounds(CGMainDisplayID());
CGPoint::new(on_screen.x, main.size.height - on_screen.y)
}
/// `rect` as an NSRect in the flipped view's points.
fn ns_rect(rect: Rect) -> NSRect {
NSRect::new(
@@ -30,6 +30,13 @@
//! - **No stuck keys**: losing the keyboard, releasing capture and closing send an up for every
//! key held; losing the keyboard and closing lift the buttons held too.
//!
//! - **For games**, where the guest has its own mouse ([`crate::PointerMotion`]): captured, while
//! the guest hides its cursor on every display, the window locks the host's pointer (SDL's
//! relative mode, its motion the device's own counts) and hands its motion, its buttons
//! pressed meanwhile and its wheel to the guest's mouse ([`crate::game`]), until the guest shows
//! its cursor again, where the host's pointer is let go over it; a button comes up by the route
//! it went down by. Releasing capture, losing the keyboard and closing let the pointer go where
//! it was held.
//! - **Past the image's edge**, where the host gives the window the guest's other displays
//! ([`crate::PointerBeyond`]): the captured pointer moving toward an edge another display meets,
//! within reach of it, goes on onto it ([`crate::beyond`]). The window locks the host's pointer
@@ -46,12 +53,13 @@
use std::sync::Arc;
use crate::beyond::{Back, Beyond, Hold};
use crate::beyond::{Back, Beyond, Hold, point_of};
use crate::capture::{Capture, UNCAPTURED_SUFFIX};
use crate::config::{
BUTTON_EXTRA, BUTTON_LEFT, BUTTON_MIDDLE, BUTTON_RIGHT, BUTTON_SIDE, PointerBeyond,
ScrollEvent, WindowCallbacks,
PointerMotion, ScrollEvent, WindowCallbacks,
};
use crate::game::Game;
use crate::geometry::{self, Rect};
use crate::keys::{KeyEvent, KeyState};
use crate::scroll::POINTS_PER_LINE;
@@ -72,6 +80,8 @@ pub(crate) struct At {
pub(crate) image: Rect,
/// The guest's mode, once it has set one.
pub(crate) guest: Option<(u16, u16)>,
/// The guest's cursor, in its mode's pixels, where it shows over the window's display.
pub(crate) cursor: Option<(u16, u16)>,
}
/// What the window does after an event.
@@ -134,6 +144,14 @@ fn guest_mode(at: &At) -> Option<(u16, u16)> {
at.guest.filter(|&(width, height)| width > 0 && height > 0)
}
/// The window's point over the guest's cursor in `at`, where it shows over the window's display.
fn cursor_point(at: &At) -> Option<(f64, f64)> {
let mode = guest_mode(at)?;
let cursor = at.cursor?;
let inside = (cursor.0.min(mode.0 - 1), cursor.1.min(mode.1 - 1));
Some(point_of(inside, at.image, mode))
}
/// `points` in 1/256 point, rounded; 0 for what is not a number.
fn fixed(points: f64) -> i32 {
if points.is_finite() {
@@ -168,6 +186,10 @@ pub(crate) struct Input {
away: Beyond,
/// What the window does with the host's pointer next, since [`Self::take_hold`] last took it.
hold: Option<Hold>,
/// The guest's own mouse, where the host gives it.
motion: Option<Arc<dyn PointerMotion>>,
/// Whether the captured pointer drives it.
game: Game,
}
impl std::fmt::Debug for Input {
@@ -176,6 +198,7 @@ impl std::fmt::Debug for Input {
.field("capture", &self.capture)
.field("buttons", &self.buttons)
.field("away", &self.away)
.field("game", &self.game)
.finish_non_exhaustive()
}
}
@@ -187,21 +210,38 @@ impl Input {
Input::default()
}
/// [`Self::new`], its captured pointer going past the image's edge through `beyond`, where
/// the host gives it.
pub(crate) fn with_beyond(beyond: Option<Arc<dyn PointerBeyond>>) -> Input {
/// [`Self::new`], its captured pointer going past the image's edge through `beyond`, and
/// driving the guest's own mouse `motion` while the guest hides its cursor, where the host
/// gives each.
pub(crate) fn with_links(
beyond: Option<Arc<dyn PointerBeyond>>,
motion: Option<Arc<dyn PointerMotion>>,
) -> Input {
Input {
beyond,
motion,
..Input::default()
}
}
/// Whether the captured pointer has gone past the image's edge: SDL reports its moves as
/// motion alone ([`Self::moved_by`]).
/// Whether the captured pointer has gone past the image's edge.
#[cfg(test)]
pub(crate) fn is_away(&self) -> bool {
self.away.is_away()
}
/// Whether the host's pointer is locked: gone past the image's edge, or driving the guest's
/// mouse. SDL reports its moves as motion alone ([`Self::moved_by`]).
pub(crate) fn is_locked(&self) -> bool {
self.away.is_away() || self.game.is_on()
}
/// Whether the captured pointer drives the guest's own mouse.
#[cfg(test)]
pub(crate) fn drives_the_guest_s_mouse(&self) -> bool {
self.game.is_on()
}
/// What the window does with the host's pointer next, taken: lock it as it goes past the
/// edge, or let it go where it comes back.
pub(crate) fn take_hold(&mut self) -> Option<Hold> {
@@ -211,6 +251,10 @@ impl Input {
/// The window could not lock the host's pointer: the pointer is the window's again, where it
/// was held.
pub(crate) fn lock_refused(&mut self) {
if let Some(hold) = self.game.refused() {
self.hold = Some(hold);
return;
}
let beyond = self.beyond.clone();
if let Some(back) = self.away.let_go(beyond.as_deref()) {
self.came_back(back);
@@ -269,14 +313,22 @@ impl Input {
}
}
/// The pointer moved. Captured, moving toward an edge another display meets and within reach
/// of it, it goes past it ([`crate::beyond`]). A place SDL reports while the pointer is away
/// is SDL's own (the lock's warp): the pointer's moves are [`Self::moved_by`]'s.
/// The pointer moved. Captured, with the guest's cursor hidden, it drives the guest's mouse
/// ([`crate::game`]); moving toward an edge another display meets and within reach of it, it
/// goes past it ([`crate::beyond`]). A place SDL reports while the pointer is locked is SDL's
/// own (the lock's warp): the pointer's moves are [`Self::moved_by`]'s.
pub(crate) fn moved(&mut self, at: &At) {
if self.away.is_away() {
if self.is_locked() {
return;
}
if let (Some(point), Some(mode)) = (at.point, guest_mode(at)) {
if self.capture.is_captured()
&& let Some(motion) = self.motion.clone()
&& let Some(hold) = self.game.begin(motion.as_ref(), point)
{
self.hold = Some(hold);
return;
}
let from = match self.last {
Some(ToHost::Pointer { at, .. }) => Some(at),
_ => None,
@@ -294,10 +346,30 @@ impl Input {
}
}
/// The pointer gone past the edge moved by `by`, in the window's points (SDL's relative
/// motion): it goes on, and comes back where it lands on the window's display, away from the
/// edge.
/// The locked pointer moved by `by` (SDL's relative motion): driving the guest's mouse, by
/// the device's counts, until the guest shows its cursor; gone past the edge, by the window's
/// points, on, coming back where it lands on the window's display, away from the edge, or
/// driving the guest's mouse from where it is once the guest hides its cursor.
pub(crate) fn moved_by(&mut self, by: (f64, f64), at: &At) {
if let Some(motion) = self.motion.clone() {
if self.game.is_on() {
let cursor = cursor_point(at);
if let Some(hold) = self.game.moved(motion.as_ref(), by, cursor) {
self.hold = Some(hold);
}
return;
}
if self.away.is_away()
&& let Some(back) = self.away.held()
&& let Some(hold) = self.game.begin(motion.as_ref(), back)
{
// Away, the guest hid its cursor: the lock stays, its motion now raw.
let beyond = self.beyond.clone();
self.away.let_go(beyond.as_deref());
self.hold = Some(hold);
return;
}
}
let Some(beyond) = self.beyond.clone() else {
return;
};
@@ -324,6 +396,9 @@ impl Input {
/// Button `bit` went down at `timestamp` (SDL's event clock).
pub(crate) fn button_down(&mut self, bit: u32, timestamp: u64, at: &At) -> Reaction {
if self.game.press(self.motion.as_deref(), bit) {
return Reaction::default();
}
if self.away.is_away() {
// Captured: the button goes where the pointer is.
if bit != 0 {
@@ -357,8 +432,12 @@ impl Input {
}
}
/// Button `bit` went up: sent where the guest was told it is down, wherever the pointer is.
/// Button `bit` went up: sent where the guest was told it is down, wherever the pointer is,
/// by the route it went down by (the guest's mouse, or the tablet).
pub(crate) fn button_up(&mut self, bit: u32, at: &At) {
if self.game.release(self.motion.as_deref(), bit) {
return;
}
if self.buttons & bit == 0 {
return;
}
@@ -367,6 +446,12 @@ impl Input {
self.away_buttons();
return;
}
if self.game.is_on() {
// The tablet's button, pressed before the guest's mouse was driven: up where the
// tablet is.
self.resend_buttons();
return;
}
if let (Some(point), Some(mode)) = (at.point, guest_mode(at)) {
self.pointer(point, at.image, mode, true);
}
@@ -377,7 +462,14 @@ impl Input {
let (Some(point), Some(_)) = (at.point, guest_mode(at)) else {
return;
};
if !self.away.is_away() {
if self.game.is_on() {
let sign = if wheel.flipped { -1 } else { 1 };
let up = wheel.notches.1.saturating_mul(sign);
if up != 0 {
self.game.wheel(self.motion.as_deref(), up);
return;
}
} else if !self.away.is_away() {
if !geometry::contains(at.image, point) {
return;
}
@@ -430,6 +522,7 @@ impl Input {
self.focused = false;
self.lift_keys();
self.lift_buttons();
self.let_go_game();
self.let_go_away();
Reaction {
capture_changed: self.capture.resign_key(),
@@ -439,6 +532,7 @@ impl Input {
/// Releases capture, lifting every key held.
pub(crate) fn release_capture(&mut self) -> Reaction {
self.lift_keys();
self.end_game();
self.let_go_away();
Reaction {
capture_changed: self.capture.release(),
@@ -449,6 +543,7 @@ impl Input {
pub(crate) fn closing(&mut self) {
self.lift_keys();
self.lift_buttons();
self.let_go_game();
self.let_go_away();
self.capture.release();
}
@@ -459,6 +554,45 @@ impl Input {
self.out.extend(ups.into_iter().map(ToHost::Key));
}
/// The guest showed or hid its cursor: driving the guest's mouse, the pointer is the
/// window's again once the guest shows it, the host's pointer let go over it.
pub(crate) fn cursor_changed(&mut self, at: &At) {
if let Some(motion) = self.motion.clone()
&& let Some(hold) = self.game.shown(motion.as_ref(), cursor_point(at))
{
self.hold = Some(hold);
}
}
/// Lifts the buttons held through the guest's mouse, and lets go of the pointer driving it
/// where it was held.
fn let_go_game(&mut self) {
self.game.lift(self.motion.as_deref());
self.end_game();
}
/// The pointer driving the guest's mouse is the window's again, where it was held; a refused
/// lock may be tried again.
fn end_game(&mut self) {
if let Some(hold) = self.game.end() {
self.hold = Some(hold);
}
}
/// The tablet's buttons changed while the pointer drives the guest's mouse: the last
/// pointer's pixel with them.
fn resend_buttons(&mut self) {
if let Some(ToHost::Pointer { at, mode, .. }) = self.last {
let event = ToHost::Pointer {
at,
mode,
buttons: self.buttons,
};
self.last = Some(event);
self.out.push(event);
}
}
/// A pointer event with no button, where one is held, at the last pointer's pixel.
fn lift_buttons(&mut self) {
if self.buttons == 0 {
@@ -517,6 +651,8 @@ mod tests {
use reims_vgpu_vulkan::core::sync::Mutex;
use super::*;
use crate::game::SETTLE_NS;
use crate::game::tests::Mouse;
/// A 100×50 image at the window's origin, a 200×100 guest mode, the pointer at `point`.
fn at(point: (f64, f64)) -> At {
@@ -529,6 +665,7 @@ mod tests {
height: 50.0,
},
guest: Some((200, 100)),
cursor: None,
}
}
@@ -780,7 +917,7 @@ mod tests {
/// A captured input with `desktop` beyond its image's edges.
fn captured_beside(desktop: &Arc<RightOfIt>) -> Input {
let beyond: Arc<dyn PointerBeyond> = desktop.clone();
let mut input = Input::with_beyond(Some(beyond));
let mut input = Input::with_links(Some(beyond), None);
input.focus_gained(0);
input.button_down(BUTTON_LEFT, 1_000_000_000, &at((10.0, 10.0)));
input.button_up(BUTTON_LEFT, &at((10.0, 10.0)));
@@ -882,12 +1019,229 @@ mod tests {
alone.button_down(BUTTON_LEFT, 1_000_000_000, &at((10.0, 10.0)));
alone.moved(&at((99.9, 10.0)));
assert_eq!(alone.take_hold(), None);
let mut uncaptured = Input::with_beyond(Some(desktop.clone() as Arc<dyn PointerBeyond>));
let mut uncaptured =
Input::with_links(Some(desktop.clone() as Arc<dyn PointerBeyond>), None);
uncaptured.moved(&at((99.9, 10.0)));
assert_eq!(uncaptured.take_hold(), None);
assert_eq!(uncaptured.take(), vec![pointer(199, 20, 0)]);
}
/// An input captured by a click, driving the guest's mouse `motion` where it is given.
fn captured_by(motion: Option<Arc<Mouse>>) -> Input {
let mut input = Input::with_links(None, motion.map(|m| m as Arc<dyn PointerMotion>));
input.focus_gained(0);
input.button_down(BUTTON_LEFT, 1_000_000_000, &at((10.0, 10.0)));
input.button_up(BUTTON_LEFT, &at((10.0, 10.0)));
input.take();
input
}
/// Moves, a drag past the image's edge and the wheel, as the tablet hears them.
fn desk_work(input: &mut Input) -> Vec<ToHost> {
input.moved(&at((20.0, 10.0)));
input.moved(&at((40.0, 20.0)));
input.button_down(BUTTON_RIGHT, 2_000_000_000, &at((40.0, 20.0)));
input.moved(&at((150.0, 10.0)));
input.button_up(BUTTON_RIGHT, &at((150.0, 10.0)));
input.moved(&at((60.0, 30.0)));
input.wheel(
Wheel {
notches: (0, 1),
lines: (0.0, 1.0),
flipped: false,
},
&at((60.0, 30.0)),
);
input.take()
}
/// Outside a game the tablet hears exactly what it hears with no guest's mouse, and the
/// guest's mouse nothing: captured while the guest shows its cursor, or has hidden it for
/// less than the settle, and uncaptured however long it hides it
#[test]
fn the_tablet_s_events_are_unchanged_outside_a_game() {
let plain = desk_work(&mut captured_by(None));
assert!(!plain.is_empty());
for hidden in [None, Some(SETTLE_NS - 1)] {
let mouse = Arc::new(Mouse::default());
*mouse.hidden.lock() = hidden;
let mut input = captured_by(Some(Arc::clone(&mouse)));
assert_eq!(desk_work(&mut input), plain, "hidden for {hidden:?}");
assert_eq!(input.take_hold(), None);
assert_eq!(mouse.take(), vec![]);
}
// Uncaptured: moves alone, since a click in the image captures.
let roam = |input: &mut Input| {
input.moved(&at((20.0, 10.0)));
input.moved(&at((150.0, 10.0)));
input.moved(&at((60.0, 30.0)));
input.take()
};
let uncaptured = roam(&mut focused());
let mouse = Arc::new(Mouse::default());
mouse.hide_for(SETTLE_NS);
let mut input = Input::with_links(None, Some(Arc::clone(&mouse) as Arc<dyn PointerMotion>));
input.focus_gained(0);
assert_eq!(roam(&mut input), uncaptured);
assert_eq!(input.take_hold(), None);
assert_eq!(mouse.take(), vec![]);
}
/// Captured, once the guest has hidden its cursor for the settle, the host's pointer is
/// locked where it is, and its motion, by whole counts, and the wheel's notches drive the
/// guest's mouse, however far: the tablet hears nothing. Once the guest shows its cursor the
/// pointer is the window's again, let go over the guest's cursor on the window's display, else
/// where it was held
#[test]
fn a_hidden_cursor_s_motion_drives_the_guest_s_mouse_until_it_shows() {
let mouse = Arc::new(Mouse::default());
let mut input = captured_by(Some(Arc::clone(&mouse)));
mouse.hide_for(SETTLE_NS);
input.moved(&at((99.0, 10.0)));
assert_eq!(input.take_hold(), Some(Hold::Raw));
assert!(input.is_locked() && input.drives_the_guest_s_mouse());
input.moved_by((500.0, 0.0), &at((99.0, 10.0)));
input.moved_by((300.5, -2.0), &at((99.0, 10.0)));
input.moved_by((0.5, 0.0), &at((99.0, 10.0)));
input.moved(&at((10.0, 10.0)));
input.wheel(
Wheel {
notches: (0, 2),
lines: (0.0, 2.0),
flipped: true,
},
&at((99.0, 10.0)),
);
assert_eq!(
mouse.take(),
vec![
((500, 0), 0, 0),
((300, -2), 0, 0),
((1, 0), 0, 0),
((0, 0), -2, 0)
]
);
assert_eq!(input.take(), vec![], "the tablet hears nothing");
// The guest shows its cursor at pixel (50, 40) of the window's display.
mouse.show();
input.cursor_changed(&At {
cursor: Some((50, 40)),
..at((99.0, 10.0))
});
assert_eq!(input.take_hold(), Some(Hold::Unlock((25.25, 20.25))));
assert!(!input.is_locked());
input.moved(&at((25.25, 20.25)));
input.moved(&at((30.0, 20.25)));
assert_eq!(input.take(), vec![pointer(50, 40, 0), pointer(60, 40, 0)]);
// Hidden again, then shown on another display, seen at the next motion.
mouse.hide_for(SETTLE_NS);
input.moved(&at((30.0, 20.0)));
assert_eq!(input.take_hold(), Some(Hold::Raw));
mouse.show();
input.moved_by((3.0, 0.0), &at((30.0, 20.0)));
assert_eq!(mouse.take(), vec![((3, 0), 0, 0)]);
assert_eq!(input.take_hold(), Some(Hold::Unlock((30.0, 20.0))));
assert!(!input.drives_the_guest_s_mouse());
}
/// A button comes up by the route it went down by, held across either switch: one pressed on
/// the tablet before the guest's mouse is driven comes up on the tablet where it last was; one
/// pressed through the guest's mouse comes up through it after the guest shows its cursor
#[test]
fn a_button_held_across_the_switch_comes_up_by_its_own_route() {
let mouse = Arc::new(Mouse::default());
let mut input = captured_by(Some(Arc::clone(&mouse)));
input.button_down(BUTTON_RIGHT, 2_000_000_000, &at((20.0, 10.0)));
assert_eq!(input.take(), vec![pointer(40, 20, BUTTON_RIGHT)]);
mouse.hide_for(SETTLE_NS);
input.moved(&at((21.0, 10.0)));
assert_eq!(input.take_hold(), Some(Hold::Raw));
input.moved_by((4.0, 0.0), &at((21.0, 10.0)));
input.button_down(BUTTON_LEFT, 3_000_000_000, &at((21.0, 10.0)));
input.moved_by((1.0, 1.0), &at((21.0, 10.0)));
input.button_up(BUTTON_RIGHT, &at((21.0, 10.0)));
assert_eq!(
mouse.take(),
vec![
((4, 0), 0, 0),
((0, 0), 0, BUTTON_LEFT),
((1, 1), 0, BUTTON_LEFT)
]
);
assert_eq!(
input.take(),
vec![pointer(40, 20, 0)],
"the tablet's comes up there"
);
mouse.show();
input.cursor_changed(&at((21.0, 10.0)));
assert_eq!(input.take_hold(), Some(Hold::Unlock((21.0, 10.0))));
input.button_up(BUTTON_LEFT, &at((21.0, 10.0)));
assert_eq!(
mouse.take(),
vec![((0, 0), 0, 0)],
"the mouse's comes up there"
);
assert_eq!(input.take(), vec![]);
input.button_down(BUTTON_LEFT, 4_000_000_000, &at((21.0, 10.0)));
assert_eq!(input.take(), vec![pointer(42, 20, BUTTON_LEFT)]);
assert_eq!(mouse.take(), vec![]);
}
/// Releasing capture (the chord), losing the keyboard and closing give the window back the
/// pointer driving the guest's mouse where it was held, a button held through the mouse lifted
/// on the keyboard's loss and the close; a lock the OS refuses gives it back too, and is not
/// tried again until capture changes
#[test]
fn letting_go_of_a_game_gives_the_pointer_back_where_it_was_held() {
let mouse = Arc::new(Mouse::default());
mouse.hide_for(SETTLE_NS);
let in_game = || {
let mut input = captured_by(Some(Arc::clone(&mouse)));
input.moved(&at((30.0, 10.0)));
assert_eq!(input.take_hold(), Some(Hold::Raw));
input
};
let mut input = in_game();
for usage in [0xE0, 0xE2, 0xE3] {
input.key(usage, true, false);
}
assert!(!input.is_captured() && !input.is_locked());
assert_eq!(input.take_hold(), Some(Hold::Unlock((30.0, 10.0))));
let mut input = in_game();
input.button_down(BUTTON_LEFT, 2_000_000_000, &at((30.0, 10.0)));
mouse.take();
input.focus_lost();
assert_eq!(mouse.take(), vec![((0, 0), 0, 0)]);
assert!(!input.is_locked());
assert_eq!(input.take_hold(), Some(Hold::Unlock((30.0, 10.0))));
let mut input = in_game();
input.button_down(BUTTON_MIDDLE, 2_000_000_000, &at((30.0, 10.0)));
mouse.take();
input.closing();
assert_eq!(mouse.take(), vec![((0, 0), 0, 0)]);
assert_eq!(input.take_hold(), Some(Hold::Unlock((30.0, 10.0))));
let mut input = in_game();
input.lock_refused();
assert_eq!(input.take_hold(), Some(Hold::Unlock((30.0, 10.0))));
assert!(!input.is_locked());
input.moved(&at((31.0, 10.0)));
assert_eq!(input.take_hold(), None, "not tried again while captured");
assert_eq!(input.take(), vec![pointer(62, 20, 0)]);
input.release_capture();
input.button_down(BUTTON_LEFT, 5_000_000_000, &at((31.0, 10.0)));
input.moved(&at((32.0, 10.0)));
assert_eq!(
input.take_hold(),
Some(Hold::Raw),
"tried again at the next capture"
);
assert_eq!(mouse.take(), vec![]);
}
/// SDL's buttons to the host's bits
#[test]
fn sdl_buttons_are_the_hosts_bits() {
@@ -188,11 +188,15 @@ pub(crate) fn open(window: &Arc<Window>, borderless: bool, _taken: &[Frame]) ->
window.title(),
display.0
);
let callbacks = window.callbacks();
Some(Opened {
sdl,
asked: size,
input: Input(input::Input::with_beyond(
window.callbacks().and_then(|callbacks| callbacks.beyond),
input: Input(input::Input::with_links(
callbacks
.as_ref()
.and_then(|callbacks| callbacks.beyond.clone()),
callbacks.and_then(|callbacks| callbacks.motion),
)),
state: State { display },
})
@@ -236,11 +240,28 @@ pub(crate) fn screens_changed(_shell: &mut Shell) {}
fn at(shell: &Shell, point: (f32, f32)) -> At {
At {
point: Some((f64::from(point.0), f64::from(point.1))),
..at_no_point(shell)
}
}
/// What the window knows, with no pointer event.
fn at_no_point(shell: &Shell) -> At {
At {
point: None,
image: shell.layout.image,
guest: shell.window.mode(),
cursor: shell.window.shown_cursor_at(),
}
}
/// The guest showed or hid its cursor: the input may let go of the pointer driving the guest's
/// mouse ([`input::Input::cursor_changed`]).
pub(crate) fn cursor_changed(shell: &mut Shell) {
let at = at_no_point(shell);
shell.input.0.cursor_changed(&at);
apply_hold(shell);
}
/// An input event of type `kind` for the window: the pointer, a button, the wheel or a key, to
/// the window's input. Whether capture changed.
pub(crate) fn input_event(shell: &mut Shell, kind: u32, event: &SDL_Event) -> bool {
@@ -250,7 +271,7 @@ pub(crate) fn input_event(shell: &mut Shell, kind: u32, event: &SDL_Event) -> bo
let motion = unsafe { event.motion };
let point = (motion.x, motion.y);
let at = at(shell, point);
if shell.input.0.is_away() {
if shell.input.0.is_locked() {
// The pointer is locked: SDL reports its motion alone.
let by = (f64::from(motion.xrel), f64::from(motion.yrel));
shell.input.0.moved_by(by, &at);
@@ -310,22 +331,42 @@ pub(crate) fn input_event(shell: &mut Shell, kind: u32, event: &SDL_Event) -> bo
/// motion. Letting go warps the pointer to the point first, so SDL puts it there as the lock
/// ends (on Wayland the lock's cursor position hint, or pointer-warp). A lock SDL refuses gives
/// the pointer back to the window, where it was held.
///
/// Gone past the edge, the motion is the host's pointer's, in the window's points, scaled as
/// the host moves its pointer (`SDL_MOUSE_RELATIVE_SYSTEM_SCALE` 1); driving the guest's mouse,
/// it is the device's own counts (0: on Wayland relative-pointer's unaccelerated motion), which
/// the guest scales as it scales a mouse's.
pub(crate) fn apply_hold(shell: &mut Shell) {
let Some(hold) = shell.input.0.take_hold() else {
return;
};
match hold {
Hold::Lock => {
// SAFETY: the window is SDL's, on this thread.
let locked = unsafe { SDL_SetWindowRelativeMouseMode(shell.sdl, true) };
Hold::Lock | Hold::Raw => {
let raw = hold == Hold::Raw;
let scale = if raw { c"0" } else { c"1" };
// SAFETY: the window is SDL's, on this thread; both strings are NUL-terminated, and
// SDL copies them.
let locked = unsafe {
SDL_SetHint(c"SDL_MOUSE_RELATIVE_SYSTEM_SCALE".as_ptr(), scale.as_ptr());
SDL_SetWindowRelativeMouseMode(shell.sdl, true)
};
log::debug!(
target: "reims_vgpu_window",
"window {:?}: the captured pointer goes past the image's edge (locked: {locked})",
shell.window.title()
"window {:?}: the captured pointer {} (locked: {locked})",
shell.window.title(),
if raw {
"drives the guest's mouse"
} else {
"goes past the image's edge"
}
);
if !locked {
shell::refused(
"no pointer lock, so the pointer stays at the image's edge",
if raw {
"no pointer lock, so a game's mouse stops at the image's edge"
} else {
"no pointer lock, so the pointer stays at the image's edge"
},
shell.window.title(),
);
shell.input.0.lock_refused();
@@ -434,6 +475,7 @@ mod tests {
height: 50.0,
},
guest: Some((200, 100)),
cursor: None,
};
input
.0
@@ -328,6 +328,7 @@ pub(crate) fn guest_mode_changed(id: u64) {
/// The guest of window `id` changed its cursor or showed or hid it.
pub(crate) fn cursor_changed(id: u64) {
with_shell(id, |shell| {
os::cursor_changed(shell);
shell.window.take_cursor_refresh();
shell.refresh_cursor();
});
+14 -5
View File
@@ -77,10 +77,10 @@ use reims_vgpu_graphics::wire::{
RGFX_FEATURE_MANAGED_AT_OFFSET, RGFX_FEATURE_MANAGED_BUFFER_SLABS,
RGFX_FEATURE_MANAGED_TEXTURE_SLABS, RGFX_FEATURE_MESH_PIPELINES, RGFX_FEATURE_OPENCL_MODE,
RGFX_FEATURE_PAGES_16K, RGFX_FEATURE_PAGES_BUFFERS, RGFX_FEATURE_PIPELINE_ANSWERS,
RGFX_FEATURE_PIPELINE_KEYS, RGFX_FEATURE_PRIVATE_RENDER_STATE, RGFX_FEATURE_RATE_MAPS,
RGFX_FEATURE_READ_ONLY_PAGES, RGFX_FEATURE_SCHEDULED_ASK, RGFX_FEATURE_SHARED_EVENT_NAMES,
RGFX_FEATURE_SMALL_ID_CHUNKS, RGFX_FEATURE_SUBMIT_ROOM, RGFX_FEATURE_SURFACE_CACHE,
RGFX_FEATURE_SURFACE_CACHE_REFUSED, RGFX_FEATURE_SURFACE_DEFERRED,
RGFX_FEATURE_PIPELINE_KEYS, RGFX_FEATURE_POINTER_MOTION, RGFX_FEATURE_PRIVATE_RENDER_STATE,
RGFX_FEATURE_RATE_MAPS, RGFX_FEATURE_READ_ONLY_PAGES, RGFX_FEATURE_SCHEDULED_ASK,
RGFX_FEATURE_SHARED_EVENT_NAMES, RGFX_FEATURE_SMALL_ID_CHUNKS, RGFX_FEATURE_SUBMIT_ROOM,
RGFX_FEATURE_SURFACE_CACHE, RGFX_FEATURE_SURFACE_CACHE_REFUSED, RGFX_FEATURE_SURFACE_DEFERRED,
RGFX_FEATURE_SURFACE_DEFERRED_ASK, RGFX_FEATURE_SURFACE_DEFERRED_CARRY,
RGFX_FEATURE_SURFACE_ORDER, RGFX_FEATURE_SURFACE_PAGES, RGFX_FEATURE_TEXTURE_DID_MODIFY_DATA,
RGFX_FEATURE_UNSHARED_QUEUES, RGFX_RESOURCE_ID_CHUNK, RGFX_RESOURCE_ID_CHUNKS,
@@ -574,6 +574,13 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
0
} else {
u64::from(RGFX_FEATURE_MANAGED_AT_OFFSET)
}
// A window's captured pointer drives the guest's own mouse while a game hides
// the cursor ([`crate::window`]); a device with no window has no pointer to.
| if config.window.is_some() {
RGFX_FEATURE_POINTER_MOTION
} else {
0
};
let pages_features = match (decoder.surface_pages_available(), unified_memory) {
(false, _) => 0,
@@ -703,7 +710,8 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
};
let displays = u32::try_from(count).unwrap_or(u32::MAX);
// Where several displays' windows tell the guest which one the pointer is over, and
// carry a captured pointer past their edges: the device's link, once it is made.
// carry a captured pointer past their edges, and where each window's captured pointer
// drives the guest's mouse: the device's link, once it is made.
let pointer = Arc::new(OnceLock::new());
let desktop = crate::window::Desktop::new(Arc::clone(&pointer));
let mut by_display = Vec::with_capacity(count);
@@ -714,6 +722,7 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
for (display, window_config) in window_configs.into_iter().enumerate() {
let (screen, shown): (Arc<dyn Screen>, Arc<Shown>) = match window_config {
Some(mut window_config) => {
crate::window::give_motion(&mut window_config, &pointer);
if displays > 1 {
let id = u32::try_from(display).unwrap_or(u32::MAX);
crate::window::tell_pointer(&mut window_config, id, &pointer);
@@ -1,5 +1,6 @@
//! A device of several displays ([`GraphicsConfig::display_count`]): the counts and windows it
//! takes, each display's read-back, and each display's cursor at the host's callbacks.
//! takes, each display's read-back, and each display's cursor at the host's callbacks; and a
//! window's captured pointer driving the guest's own mouse (`POINTER_MOTION`).
use reims_vgpu_window::Landed;
@@ -416,3 +417,70 @@ fn a_captured_pointer_past_the_shared_edge_goes_on_through_the_other_display_s_w
"the window's again"
);
}
/// A device with a window offers `POINTER_MOTION`, and a headless one does not; a window the
/// device gives the guest's mouse ([`crate::window::give_motion`]), one with a pointer callback,
/// is told how long the guest has hidden its cursor, and its motion reaches a guest that took
/// `POINTER_MOTION` as the event; a window with no pointer callback is given no mouse
#[test]
fn a_window_s_device_offers_pointer_motion_and_drives_the_guest_s_mouse() {
let offers = |device: &GraphicsDevice<FakePlatform>| {
let hi = u64::from(device.mmio_read(RGFX_REG_FEATURES_HI.into())) << 32;
hi & RGFX_FEATURE_POINTER_MOTION != 0
};
assert!(!offers(&headless_of(1, GraphicsCallbacks::default())));
let with_pointer = || {
let mut config = WindowConfig::default();
config.callbacks.pointer = Some(Arc::new(|_x, _y, _width, _height, _buttons| {}));
config
};
let config = GraphicsConfig {
window: Some(with_pointer()),
..GraphicsConfig::default()
};
let device = GraphicsDevice::with_platform(Arc::new(FakePlatform::new()), config).unwrap();
assert!(offers(&device));
device.mmio_write(
RGFX_REG_DRIVER_FEATURES_HI.into(),
(RGFX_FEATURE_POINTER_MOTION >> 32) as u32,
);
device.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_DRIVER_READY);
let mut guest = Guest::new(&device);
let link = Arc::new(OnceLock::new());
let _ = link.set(device.device.pointer_link());
let mut no_pointer = WindowConfig::default();
crate::window::give_motion(&mut no_pointer, &link);
assert!(
no_pointer.callbacks.motion.is_none(),
"no pointer, no mouse"
);
let mut config = with_pointer();
crate::window::give_motion(&mut config, &link);
let mouse = config.callbacks.motion.unwrap();
assert_eq!(
mouse.hidden_for(),
None,
"the guest has not hidden its cursor"
);
let hide = RgfxMoveCursor {
header: RgfxMsgHeader {
r#type: RGFX_CMD_MOVE_CURSOR,
size: 0,
seqno: 0,
},
display: 0,
x: 10,
y: 10,
visible: 0,
};
carried(&device, &mut guest, hide.as_bytes().to_vec());
assert!(mouse.hidden_for().is_some(), "hidden on its one display");
assert!(mouse.moved((5, -3), 1, reims_vgpu_window::BUTTON_LEFT));
let m = RgfxPointerMotion::read_from_bytes(&guest.event().unwrap()).unwrap();
assert_eq!(
(m.header.r#type, m.dx, m.dy, m.wheel, m.buttons),
(RGFX_EVT_POINTER_MOTION, 5, -3, 1, RGFX_POINTER_BUTTON_LEFT)
);
carried(&device, &mut guest, move_cursor(0, 10, 10));
assert_eq!(mouse.hidden_for(), None, "shown again");
}
+35 -3
View File
@@ -1,6 +1,7 @@
//! A graphics device's window, as the device's last reference ends it ([`WindowLink`]), its
//! pointer as it tells the guest which display it is over ([`tell_pointer`]), and its captured
//! pointer as it goes past the image's edge onto the guest's other displays ([`Desktop`]).
//! pointer as it tells the guest which display it is over ([`tell_pointer`]), its captured
//! pointer as it goes past the image's edge onto the guest's other displays ([`Desktop`]), and as
//! it drives the guest's own mouse while the guest hides its cursor ([`give_motion`]).
use std::sync::{Arc, OnceLock, Weak};
@@ -11,7 +12,7 @@ use reims_vgpu_graphics::wire::{
};
use reims_vgpu_window::{
BUTTON_EXTRA, BUTTON_LEFT, BUTTON_MIDDLE, BUTTON_RIGHT, BUTTON_SIDE, Landed, PointerBeyond,
Window, WindowConfig,
PointerMotion, Window, WindowConfig,
};
use crate::entry;
@@ -54,6 +55,37 @@ pub(crate) fn tell_pointer(
}));
}
/// Has a window, `config`'s, drive the guest's own mouse with its captured pointer while the guest
/// hides its cursor (docs/graphics-kext/design.md, "A pointer for games"): through `link`, once
/// the device is made, the device's `POINTER_MOTION`, which a guest that took it hands its mouse.
/// A window with no pointer callback gives the guest no pointer, and so no mouse either.
pub(crate) fn give_motion(config: &mut WindowConfig, link: &Arc<OnceLock<PointerLink>>) {
if config.callbacks.pointer.is_none() {
return;
}
config.callbacks.motion = Some(Arc::new(GuestMouse {
link: Arc::clone(link),
}));
}
/// The guest's own mouse, through the device's link once it is made ([`give_motion`]).
struct GuestMouse {
/// The device's link.
link: Arc<OnceLock<PointerLink>>,
}
impl PointerMotion for GuestMouse {
fn hidden_for(&self) -> Option<u64> {
self.link.get()?.cursor_hidden_for()
}
fn moved(&self, by: (i32, i32), wheel: i32, buttons: u32) -> bool {
self.link
.get()
.is_some_and(|link| link.motion(by.0, by.1, wheel, buttons))
}
}
/// The guest's desktop, as a device of several displays' windows carry a captured pointer across
/// it (docs/graphics-kext/design.md, "Multiple displays", "A drag across displays"): the device,
/// which knows where the guest placed each display (`DISPLAY_BOUNDS`) and where the pointer is on
+11 -5
View File
@@ -67,7 +67,10 @@ GRAFT_INC = -I$(GRAFT_SDK)/include
GUEST_FLAGS = -DRGFX_GUEST_ARM64=1
endif
FLAGS = $(ARCH) $(GRAFT_INC) $(GUEST_FLAGS) -mkernel -nostdinc -isystem $(KERNEL) -I../../crates/reims-vgpu-graphics/include \
# src/shim: our own stand-ins for the two headers the SDK's IOHIDDevice.h includes and the SDK
# does not ship (RgfxPointerDevice.hpp).
FLAGS = $(ARCH) $(GRAFT_INC) $(GUEST_FLAGS) -mkernel -nostdinc -isystem $(KERNEL) -Isrc/shim \
-I../../crates/reims-vgpu-graphics/include \
-DKERNEL -DBUNDLE_VERSION='"$(VERSION)"' -DRGFX_FB_TRACE=$(TRACE) \
-Os -Wall -Wextra -Wshadow-all -Werror -Wno-unused-parameter \
-Wno-deprecated-declarations
@@ -75,11 +78,12 @@ FLAGS = $(ARCH) $(GRAFT_INC) $(GUEST_FLAGS) -mkernel -nostdinc -isystem $(KERNEL
CXXFLAGS = $(FLAGS) -std=c++17 -fapple-kext -fno-rtti -fno-exceptions
CFLAGS = $(FLAGS) -std=c11
HEADERS = $(wildcard src/*.hpp)
HEADERS = $(wildcard src/*.hpp src/shim/*/*.h src/shim/*/*/*.h)
# The Stage-2 framebuffer (ReimsGraphics), the Stage-3 Metal accelerator
# (RgfxAccelerator) and its region-map + doorbell user client, and on x86-64 the device
# control (RgfxDeviceControl) and the pointer's moves (ReimsGraphicsPointer), all one kext:
# (RgfxAccelerator) and its region-map + doorbell user client, the guest's own mouse for
# POINTER_MOTION (RgfxPointerDevice), and on x86-64 the device control (RgfxDeviceControl)
# and the pointer's moves (ReimsGraphicsPointer), all one kext:
# the objects both architectures build, with each architecture's own (OBJECTS_x86_64,
# OBJECTS_arm64e) third in the link.
OBJECTS_x86_64 = $(BUILD)/obj/RgfxDeviceControl.o $(BUILD)/obj/ReimsGraphicsPointer.o
@@ -87,6 +91,7 @@ OBJECTS_arm64e = $(BUILD)/obj/ReimsGraphicsMobile.o
OBJECTS = $(BUILD)/obj/ReimsGraphics.o \
$(BUILD)/obj/RgfxAccelerator.o \
$(OBJECTS_$(ARCH_NAME)) \
$(BUILD)/obj/RgfxPointerDevice.o \
$(BUILD)/obj/RgfxAcceleratorUserClient.o \
$(BUILD)/obj/RgfxDisplayPipeUserClient.o \
$(BUILD)/obj/kmod_info.o \
@@ -152,7 +157,8 @@ TESTS = $(BUILD)/tests/spans_test $(BUILD)/tests/blocks_test $(BUILD)/tests/surf
$(BUILD)/tests/completion_arm_test $(BUILD)/tests/kept_service_test \
$(BUILD)/tests/queue_publish_test $(BUILD)/tests/doorbell_pages_test $(BUILD)/tests/top_down_test \
$(BUILD)/tests/display_table_test $(BUILD)/tests/agdc_displays_test \
$(BUILD)/tests/pointer_over_test $(BUILD)/tests/display_bounds_test
$(BUILD)/tests/pointer_over_test $(BUILD)/tests/display_bounds_test \
$(BUILD)/tests/pointer_motion_test
$(BUILD)/tests/%: tests/%.cpp $(HEADERS) ../../crates/reims-vgpu-graphics/include/reims_graphics_wire.h Makefile
@mkdir -p $(@D)
+2
View File
@@ -63,6 +63,8 @@
<string>1.0.0</string>
<key>com.apple.iokit.IOGraphicsFamily</key>
<string>1.0.0b1</string>
<key>com.apple.iokit.IOHIDFamily</key>
<string>2.0.0</string>
<key>com.apple.iokit.IOMobileGraphicsFamily</key>
<string>1.0.0</string>
<key>com.apple.iokit.IOPCIFamily</key>
+49
View File
@@ -12,6 +12,7 @@
#include "RgfxDisplayPower.hpp"
#include "RgfxFeatures.hpp"
#include "RgfxPipeColor.hpp"
#include "RgfxPointerDevice.hpp"
#include "RgfxRegionMapping.hpp"
#include <IOKit/IOLib.h>
@@ -1134,6 +1135,10 @@ void ReimsGraphics::handleEvent(UInt32 type, UInt64 seqno, const volatile UInt8
fb->release();
return;
}
case RGFX_EVT_POINTER_MOTION:
// The host's pointer drives the guest's own mouse (RgfxPointerDevice.hpp).
pointerMotion(payload, size);
return;
#if defined(__x86_64__)
case RGFX_EVT_POINTER_OVER:
// The host's pointer is over another display: the cursor goes there
@@ -1146,6 +1151,46 @@ void ReimsGraphics::handleEvent(UInt32 type, UInt64 seqno, const volatile UInt8
}
}
// Display 0's, once its start is done: the guest's own mouse, where the host took
// POINTER_MOTION and none is up yet (a start after a reset keeps the one it has).
void ReimsGraphics::startPointerDevice()
{
if (!pointerMotionTaken || __atomic_load_n(&pointerDevice, __ATOMIC_ACQUIRE))
return;
RgfxPointerDevice *made = RgfxPointerDevice::withProvider(this);
if (!made) {
IOLog("ReimsGraphics: the guest's mouse for POINTER_MOTION did not start\n");
return;
}
__atomic_store_n(&pointerDevice, made, __ATOMIC_RELEASE);
IOLog("ReimsGraphics: the guest's mouse for POINTER_MOTION is up\n");
}
// Display 0's stop, once the work loop hands the device nothing more: the device stops and goes.
void ReimsGraphics::stopPointerDevice()
{
RgfxPointerDevice *mouse = __atomic_exchange_n(&pointerDevice, nullptr, __ATOMIC_ACQ_REL);
if (!mouse)
return;
mouse->terminate();
mouse->release();
}
// handleEvent's POINTER_MOTION, on the device's work loop: its reports to the guest's mouse.
void ReimsGraphics::pointerMotion(const volatile UInt8 *payload, UInt32 size)
{
RgfxMotion motion = {};
RgfxPointerDevice *mouse = __atomic_load_n(&pointerDevice, __ATOMIC_ACQUIRE);
if (!mouse || !rgfxPointerMotionRead(payload, size, &motion)) {
static char unread;
if (rgfxFirstCalls(&unread, size, 1))
IOLog("ReimsGraphics: a POINTER_MOTION of %u bytes moves nothing%s\n", size,
mouse ? "" : " (no mouse is up)");
return;
}
mouse->post(motion);
}
// Hands a lifecycle message's answer to its waiting thread, or keeps a deferred create's for its
// process: false where neither waits for an answer of this type to `seqno`.
bool ReimsGraphics::answerLifecycle(UInt32 type, UInt64 seqno, const volatile UInt8 *payload,
@@ -1596,6 +1641,7 @@ bool ReimsGraphics::start(IOService *provider)
displayPowerTaken = false;
pipelineAnswersTaken = false;
multiDisplayTaken = false;
pointerMotionTaken = false;
#if defined(__x86_64__)
displayBoundsTaken = false;
boundsTold = {};
@@ -1765,6 +1811,7 @@ bool ReimsGraphics::start(IOService *provider)
(took & (RGFX_FEATURE_PIPELINE_KEYS | RGFX_FEATURE_PIPELINE_ANSWERS)) ==
(RGFX_FEATURE_PIPELINE_KEYS | RGFX_FEATURE_PIPELINE_ANSWERS);
multiDisplayTaken = (took & RGFX_FEATURE_MULTI_DISPLAY) != 0;
pointerMotionTaken = (took & RGFX_FEATURE_POINTER_MOTION) != 0;
#if defined(__x86_64__)
constexpr uint64_t kCarriesPast = RGFX_FEATURE_MULTI_DISPLAY | RGFX_FEATURE_POINTER_OVER |
RGFX_FEATURE_DISPLAY_BOUNDS;
@@ -1820,6 +1867,7 @@ bool ReimsGraphics::start(IOService *provider)
if (super::start(provider)) {
// The other displays' framebuffers, registered after this one.
startHeads();
startPointerDevice();
return true;
}
fail:
@@ -1851,6 +1899,7 @@ void ReimsGraphics::stop(IOService *provider)
stopMobile();
#endif
quiesce();
stopPointerDevice();
#if defined(__arm64e__)
freeMobileChanges();
#else
+14
View File
@@ -69,6 +69,7 @@ typedef graft_iomfb_word RgfxIOMFBWord;
#include "reims_graphics_wire.h"
class RgfxAccelerator;
class RgfxPointerDevice;
// The display front end each architecture's WindowServer drives: an IOFramebuffer on x86-64, and
// on arm64, where WindowServer opens no IOFramebuffer, an IOMobileFramebuffer, the subclass of
@@ -706,6 +707,19 @@ private:
bool multiDisplayTaken;
IOLock *cursorLock;
// The guest's own mouse, which the host's POINTER_MOTION drives (RgfxPointerDevice.hpp),
// display 0's alone: whether the host took POINTER_MOTION, set at the start's features; the
// device, made once the framebuffer has started where it took it (startPointerDevice) and
// stopped and let go in the stop once the work loop hands it nothing more
// (stopPointerDevice); and handleEvent's POINTER_MOTION, which hands it the event's reports
// on the work loop. The device is stored and read atomically: the work loop may take an
// event while the start makes it.
bool pointerMotionTaken;
RgfxPointerDevice *pointerDevice;
void startPointerDevice();
void stopPointerDevice();
void pointerMotion(const volatile UInt8 *payload, UInt32 size);
// The boot screen the scanout holds until clearBootScreen: the boot framebuffer the OS had at
// the start (publishBootConsole); the largest span a mode's scanout has had (setScanout, under
// stateLock); the seqno of the latest present of a surface before the clear, which tryPost
+5 -1
View File
@@ -157,7 +157,10 @@
// framebuffer's move of the cursor tells the host every display's rectangle in WindowServer's
// global space that changed (RgfxDisplayBounds.hpp), by which the host carries its captured
// pointer past one display's edge onto the display the guest placed there, which needs
// nothing of the bundle.
// nothing of the bundle;
// - POINTER_MOTION (bit 51), both kexts: the framebuffer publishes the guest's own mouse
// (RgfxPointerDevice.hpp) and hands it each POINTER_MOTION's reports
// (RgfxPointerMotion.hpp), which needs nothing of the bundle.
//
// The accelerator answers the bundle's Features call with the feature word (rgfxFeatureWord), and
// grants a queue's flags (kRgfxAccelMethodQueueCreate's seventh input) only where their feature
@@ -198,6 +201,7 @@ constexpr uint64_t kRgfxCarriedFeatures =
RGFX_FEATURE_FUNCTION_POINTERS | RGFX_FEATURE_DYNAMIC_LIBRARIES | RGFX_FEATURE_PIPELINE_KEYS |
RGFX_FEATURE_ICB_SLOTS_IN_PAGES | RGFX_FEATURE_DOORBELL_ASKS | RGFX_FEATURE_GUEST_TIMES |
RGFX_FEATURE_READ_ONLY_PAGES | RGFX_FEATURE_DOORBELL_PAGES | RGFX_FEATURE_PIPELINE_ANSWERS |
RGFX_FEATURE_POINTER_MOTION |
(RGFX_GUEST_ARM64 ? RGFX_FEATURE_PAGES_16K
: RGFX_FEATURE_DISPLAY_POWER | RGFX_FEATURE_MULTI_DISPLAY |
RGFX_FEATURE_POINTER_OVER | RGFX_FEATURE_DISPLAY_BOUNDS);
+94
View File
@@ -0,0 +1,94 @@
/*
* RgfxPointerDevice: the guest's own mouse, which POINTER_MOTION drives (RgfxPointerDevice.hpp).
*/
#include "RgfxPointerDevice.hpp"
#include <IOKit/IOLib.h>
#include <IOKit/hid/IOHIDUsageTables.h>
OSDefineMetaClassAndFinalStructors(RgfxPointerDevice, IOHIDDevice);
RgfxPointerDevice *RgfxPointerDevice::withProvider(IOService *provider)
{
RgfxPointerDevice *device = OSTypeAlloc(RgfxPointerDevice);
if (!device)
return nullptr;
device->reportBuffer = nullptr;
if (!device->init(nullptr)) {
device->release();
return nullptr;
}
device->reportBuffer =
IOBufferMemoryDescriptor::withCapacity(kRgfxMouseReportBytes, kIODirectionOutIn);
if (!device->reportBuffer || !device->attach(provider)) {
device->release();
return nullptr;
}
if (!device->start(provider)) {
device->detach(provider);
device->release();
return nullptr;
}
return device;
}
void RgfxPointerDevice::post(const RgfxMotion &motion)
{
uint8_t reports[kRgfxMouseReportsMax][kRgfxMouseReportBytes];
const uint32_t n = rgfxMouseReports(motion, reports);
for (uint32_t i = 0; i < n; i++) {
reportBuffer->writeBytes(0, reports[i], kRgfxMouseReportBytes);
reportBuffer->setLength(kRgfxMouseReportBytes);
handleReport(reportBuffer, kIOHIDReportTypeInput, 0);
}
}
IOReturn RgfxPointerDevice::newReportDescriptor(IOMemoryDescriptor **descriptor) const
{
IOBufferMemoryDescriptor *buffer = IOBufferMemoryDescriptor::withBytes(
kRgfxMouseReportDescriptor, sizeof(kRgfxMouseReportDescriptor), kIODirectionOutIn);
if (!buffer)
return kIOReturnNoResources;
*descriptor = buffer;
return kIOReturnSuccess;
}
OSString *RgfxPointerDevice::newManufacturerString() const
{
return OSString::withCString("Reims vGPU");
}
OSString *RgfxPointerDevice::newProductString() const
{
return OSString::withCString("Reims vGPU Mouse");
}
OSNumber *RgfxPointerDevice::newVendorIDNumber() const
{
return OSNumber::withNumber(0x1234ULL, 32);
}
OSNumber *RgfxPointerDevice::newProductIDNumber() const
{
return OSNumber::withNumber(0x5247ULL, 32);
}
OSNumber *RgfxPointerDevice::newPrimaryUsageNumber() const
{
return OSNumber::withNumber(static_cast<unsigned long long>(kHIDUsage_GD_Mouse), 32);
}
OSNumber *RgfxPointerDevice::newPrimaryUsagePageNumber() const
{
return OSNumber::withNumber(static_cast<unsigned long long>(kHIDPage_GenericDesktop), 32);
}
void RgfxPointerDevice::free()
{
if (reportBuffer) {
reportBuffer->release();
reportBuffer = nullptr;
}
IOHIDDevice::free();
}
+47
View File
@@ -0,0 +1,47 @@
// RgfxPointerDevice: the guest's own relative pointing device, a HID mouse with no bus under it,
// which the framebuffer publishes where the guest took POINTER_MOTION and hands each
// POINTER_MOTION as reports (RgfxPointerMotion.hpp, design.md "A pointer for games"). macOS's
// HID stack drives it as any USB mouse: IOHIDEventDriver turns its reports into pointer events,
// which WindowServer accelerates and moves the cursor by, and GCMouse and IOHIDManager list it.
//
// Its name and numbers are ours: "Reims vGPU Mouse" of "Reims vGPU", vendor 0x1234 and product
// 0x5247, the PCI IDs of the device it belongs to. It is a child of display 0's framebuffer,
// started by it once the guest took the feature and stopped with it.
//
// Our own code.
#ifndef RGFX_POINTER_DEVICE_HPP_
#define RGFX_POINTER_DEVICE_HPP_
#include <IOKit/IOBufferMemoryDescriptor.h>
#include <IOKit/hid/IOHIDDevice.h>
#include "RgfxPointerMotion.hpp"
class RgfxPointerDevice final : public IOHIDDevice
{
OSDeclareFinalStructors(RgfxPointerDevice);
public:
// The device, attached to `provider` and started: nullptr where it does not start.
static RgfxPointerDevice *withProvider(IOService *provider);
// Hands the HID stack the reports of one POINTER_MOTION, in order. On the framebuffer's work
// loop, one call at a time.
void post(const RgfxMotion &motion);
IOReturn newReportDescriptor(IOMemoryDescriptor **descriptor) const override;
OSString *newManufacturerString() const override;
OSString *newProductString() const override;
OSNumber *newVendorIDNumber() const override;
OSNumber *newProductIDNumber() const override;
OSNumber *newPrimaryUsageNumber() const override;
OSNumber *newPrimaryUsagePageNumber() const override;
private:
void free() override;
// The buffer each report is written into before the HID stack reads it.
IOBufferMemoryDescriptor *reportBuffer;
};
#endif // RGFX_POINTER_DEVICE_HPP_
+135
View File
@@ -0,0 +1,135 @@
// RgfxPointerMotion: the guest's own relative pointing device, a mouse, which the host's
// POINTER_MOTION moves and clicks (design.md, "A pointer for games"; RgfxPointerDevice.hpp
// publishes it). The host's pointing device reaches the guest through QEMU's USB tablet, an
// absolute pointer, which holds at the image's edge: a game that hides the cursor and turns its
// camera by the mouse's motion gets none past it. While a game hides the cursor, the host's window
// sends its pointer's motion here instead, in the host device's own counts, unaccelerated, and
// this device hands it to macOS as a USB mouse's reports, so macOS accelerates it once, as its
// settings say, and a game that reads the device's counts (GCMouse, IOHIDManager) gets the host's.
//
// The device is a HID mouse of five buttons, 16-bit relative X and Y and an 8-bit wheel, in one
// input report of 6 bytes and no report ID: the buttons in bits 0 to 4 of byte 0 (left, right,
// middle, then the side buttons, the order of RGFX_POINTER_BUTTON_*), X and Y little-endian in
// bytes 1 to 4, the wheel in byte 5, above 0 up. It declares no resolution, as most USB mice
// declare none. A POINTER_MOTION past what one report holds goes as several, each with the
// buttons it leaves held: the host sends a press or a release in an event of its own, which the
// device joins to no motion of other buttons, so the guest takes it where the host made it.
//
// Header-only and free of the kernel's headers, so its native test (tests/pointer_motion_test.cpp)
// builds it as the kext does.
//
// Our own code; it depends only on the committed wire header.
#ifndef RGFX_POINTER_MOTION_HPP_
#define RGFX_POINTER_MOTION_HPP_
#include <stddef.h>
#include <stdint.h>
#include "RgfxDisplayTable.hpp"
#include "reims_graphics_wire.h"
// The device's HID report descriptor.
constexpr uint8_t kRgfxMouseReportDescriptor[] = {
0x05, 0x01, // Usage Page (Generic Desktop)
0x09, 0x02, // Usage (Mouse)
0xa1, 0x01, // Collection (Application)
0x09, 0x01, // Usage (Pointer)
0xa1, 0x00, // Collection (Physical)
0x05, 0x09, // Usage Page (Button)
0x19, 0x01, // Usage Minimum (1)
0x29, 0x05, // Usage Maximum (5)
0x15, 0x00, // Logical Minimum (0)
0x25, 0x01, // Logical Maximum (1)
0x95, 0x05, // Report Count (5)
0x75, 0x01, // Report Size (1)
0x81, 0x02, // Input (Data, Variable, Absolute)
0x95, 0x01, // Report Count (1)
0x75, 0x03, // Report Size (3)
0x81, 0x01, // Input (Constant)
0x05, 0x01, // Usage Page (Generic Desktop)
0x09, 0x30, // Usage (X)
0x09, 0x31, // Usage (Y)
0x16, 0x01, 0x80, // Logical Minimum (-32767)
0x26, 0xff, 0x7f, // Logical Maximum (32767)
0x75, 0x10, // Report Size (16)
0x95, 0x02, // Report Count (2)
0x81, 0x06, // Input (Data, Variable, Relative)
0x09, 0x38, // Usage (Wheel)
0x15, 0x81, // Logical Minimum (-127)
0x25, 0x7f, // Logical Maximum (127)
0x75, 0x08, // Report Size (8)
0x95, 0x01, // Report Count (1)
0x81, 0x06, // Input (Data, Variable, Relative)
0xc0, // End Collection
0xc0, // End Collection
};
// The size of one report.
constexpr size_t kRgfxMouseReportBytes = 6;
// The most one report moves on an axis, and turns the wheel.
constexpr int32_t kRgfxMouseReportMotionMax = 32767;
constexpr int32_t kRgfxMouseReportWheelMax = 127;
// The most reports one POINTER_MOTION makes: a motion of i32's range on an axis takes 65538 of
// 32767, more than any host sends; the device sends at most this many, the motion past them
// dropped.
constexpr uint32_t kRgfxMouseReportsMax = 8;
// POINTER_MOTION's motion, wheel and buttons (RgfxPointerMotion past its header).
struct RgfxMotion {
int32_t dx;
int32_t dy;
int32_t wheel;
uint32_t buttons;
};
// The motion, wheel and buttons of a POINTER_MOTION whose payload (past its header) is `size`
// bytes at `payload`: false where it is too short to hold them.
inline bool rgfxPointerMotionRead(const volatile uint8_t *payload, uint32_t size, RgfxMotion *motion)
{
if (size < 4 * sizeof(uint32_t))
return false;
motion->dx = static_cast<int32_t>(rgfxPayload32(payload, 0));
motion->dy = static_cast<int32_t>(rgfxPayload32(payload, 4));
motion->wheel = static_cast<int32_t>(rgfxPayload32(payload, 8));
motion->buttons = rgfxPayload32(payload, 12);
return true;
}
namespace rgfx_pointer_motion_detail {
// The part of `*left` one report carries, at most `max` either way, taken off `*left`.
inline int32_t take(int32_t *left, int32_t max)
{
const int32_t part = *left > max ? max : (*left < -max ? -max : *left);
*left -= part;
return part;
}
} // namespace rgfx_pointer_motion_detail
// The reports that carry `motion`, written to `reports` (kRgfxMouseReportBytes each, room for
// kRgfxMouseReportsMax): how many. At least one, so a POINTER_MOTION that only presses or lets go
// of a button is a report; every report holds its buttons, as the buttons stay held through it.
inline uint32_t rgfxMouseReports(const RgfxMotion &motion,
uint8_t reports[kRgfxMouseReportsMax][kRgfxMouseReportBytes])
{
using rgfx_pointer_motion_detail::take;
int32_t dx = motion.dx, dy = motion.dy, wheel = motion.wheel;
const uint8_t buttons = static_cast<uint8_t>(motion.buttons & 0x1f);
uint32_t n = 0;
do {
const int32_t x = take(&dx, kRgfxMouseReportMotionMax);
const int32_t y = take(&dy, kRgfxMouseReportMotionMax);
const int32_t w = take(&wheel, kRgfxMouseReportWheelMax);
uint8_t *r = reports[n++];
r[0] = buttons;
r[1] = static_cast<uint8_t>(static_cast<uint16_t>(x) & 0xff);
r[2] = static_cast<uint8_t>(static_cast<uint16_t>(x) >> 8);
r[3] = static_cast<uint8_t>(static_cast<uint16_t>(y) & 0xff);
r[4] = static_cast<uint8_t>(static_cast<uint16_t>(y) >> 8);
r[5] = static_cast<uint8_t>(static_cast<int8_t>(w));
} while ((dx || dy || wheel) && n < kRgfxMouseReportsMax);
return n;
}
#endif // RGFX_POINTER_MOTION_HPP_
@@ -0,0 +1,18 @@
/*
* Ours: the macOS SDK's Kernel.framework IOHIDDevice.h includes HIDDriverKit's IOHIDDevice.h for
* the two method lists its class declaration expands (OSDeclareDefaultStructorsWithDispatch:
* IOHIDDevice_Methods and IOHIDDevice_KernelMethods), and the SDK does not ship that header. Of
* those lists only Dispatch is virtual, an override of OSObject's that takes no new slot; the rest
* are plain members that RgfxPointerDevice never calls. So the class keeps its layout with
* Dispatch alone declared here.
*/
#ifndef RGFX_SHIM_HIDDRIVERKIT_IOHIDDEVICE_H
#define RGFX_SHIM_HIDDRIVERKIT_IOHIDDEVICE_H
#define IOHIDDevice_Methods \
public: \
virtual kern_return_t Dispatch(const IORPC rpc) APPLE_KEXT_OVERRIDE;
#define IOHIDDevice_KernelMethods
#endif
@@ -0,0 +1,8 @@
/*
* Ours, empty: the macOS SDK's Kernel.framework IOHIDDevice.h includes this header, which the SDK
* does not ship (Xcode 27.2's MacOSX27.2.sdk). IOHIDDevice.h's declarations use none of its keys,
* and RgfxPointerDevice uses none either.
*/
#ifndef RGFX_SHIM_IOHIDPRIVATEKEYS_H
#define RGFX_SHIM_IOHIDPRIVATEKEYS_H
#endif
+15 -8
View File
@@ -90,6 +90,8 @@ constexpr uint64_t kPointerOverCarried = RGFX_GUEST_ARM64 ? 0 : kPointerOver;
// WindowServer's global space, and the arm64e kext does not.
constexpr uint64_t kDisplayBounds = RGFX_FEATURE_DISPLAY_BOUNDS;
constexpr uint64_t kDisplayBoundsCarried = RGFX_GUEST_ARM64 ? 0 : kDisplayBounds;
// POINTER_MOTION, which both kexts carry, publishing the guest's own mouse for it.
constexpr uint64_t kPointerMotion = RGFX_FEATURE_POINTER_MOTION;
// Every bit the wire names from bit 3 that the kext does not carry out yet.
constexpr uint64_t kNotCarried = RGFX_FEATURE_QUIET_SCHEDULED | RGFX_FEATURE_CONSUMED_DOORBELL |
RGFX_FEATURE_QUEUE_BARRIER | RGFX_FEATURE_CB_PARTS |
@@ -172,7 +174,7 @@ constexpr uint64_t kCarried = kPages | kOrder | kIcb | kUnshared | kManaged | kH
kSlotsInPages | kDoorbellAsks | kGuestTimes | kReadOnlyPages |
kDoorbellPages | kPipelineAnswers | kDisplayPowerCarried |
kMultiDisplayCarried | kPointerOverCarried | kDisplayBoundsCarried |
k16KCarried;
kPointerMotion | k16KCarried;
// Every bit the wire names from bit 3.
constexpr uint64_t kNew = kNotCarried | kCarried;
} // namespace
@@ -187,8 +189,8 @@ int main()
// SURFACE_DEFERRED_ASK, SURFACE_DEFERRED_CARRY, SCHEDULED_ASK, DISPLAY_SCALE,
// TEXTURE_DID_MODIFY_DATA, RATE_MAPS, FUNCTION_POINTERS, DYNAMIC_LIBRARIES, PIPELINE_KEYS,
// ICB_SLOTS_IN_PAGES, DOORBELL_ASKS, GUEST_TIMES, READ_ONLY_PAGES, DOORBELL_PAGES,
// PIPELINE_ANSWERS and, the x86-64 kext, DISPLAY_POWER, MULTI_DISPLAY, POINTER_OVER and
// DISPLAY_BOUNDS, and writes each only where offered.
// PIPELINE_ANSWERS, POINTER_MOTION and, the x86-64 kext, DISPLAY_POWER, MULTI_DISPLAY,
// POINTER_OVER and DISPLAY_BOUNDS, and writes each only where offered.
check(kRgfxCarriedFeatures == kCarried,
"the kext takes PAGES_BUFFERS, SURFACE_ORDER, ICBs, UNSHARED_QUEUES, MANAGED_AT_OFFSET, "
"HEAP_OVER_PAGES, SUBMIT_ROOM, ICB slots, COMMIT_ORDER, SURFACE_DEFERRED, HOST_TIME, "
@@ -197,8 +199,8 @@ int main()
"SURFACE_CACHE_REFUSED, SURFACE_DEFERRED_ASK, SURFACE_DEFERRED_CARRY, SCHEDULED_ASK, "
"DISPLAY_SCALE, TEXTURE_DID_MODIFY_DATA, RATE_MAPS, FUNCTION_POINTERS, DYNAMIC_LIBRARIES, "
"PIPELINE_KEYS, ICB_SLOTS_IN_PAGES, DOORBELL_ASKS, GUEST_TIMES, READ_ONLY_PAGES, "
"DOORBELL_PAGES, PIPELINE_ANSWERS and, on x86-64, DISPLAY_POWER, MULTI_DISPLAY, "
"POINTER_OVER and DISPLAY_BOUNDS from bit 3");
"DOORBELL_PAGES, PIPELINE_ANSWERS, POINTER_MOTION and, on x86-64, DISPLAY_POWER, "
"MULTI_DISPLAY, POINTER_OVER and DISPLAY_BOUNDS from bit 3");
check(RGFX_FEATURE_PAGES_BUFFERS == (1u << 7), "PAGES_BUFFERS is bit 7");
check(RGFX_FEATURE_SURFACE_ORDER == (1u << 11), "SURFACE_ORDER is bit 11");
check(RGFX_FEATURE_INDIRECT_COMMAND_BUFFERS == (1u << 12), "INDIRECT_COMMAND_BUFFERS is bit 12");
@@ -404,6 +406,11 @@ int main()
check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNotCarried | kDisplayBounds) ==
kDisplayBoundsCarried,
"DISPLAY_BOUNDS offered, written by the x86-64 kext alone");
check(RGFX_FEATURE_POINTER_MOTION == (1ull << 51), "POINTER_MOTION is bit 51");
check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNotCarried | kPointerMotion) == kPointerMotion,
"POINTER_MOTION offered, written by both kexts");
check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNotCarried) == 0,
"POINTER_MOTION not offered, not written: the guest publishes no mouse");
// PAGES_16K: the arm64e kext writes it first where offered, and then with the rest; the
// x86-64 kext never writes it, and writes nothing first.
check(rgfxDriverFeaturesFirst(~0ull) == k16KCarried, "PAGES_16K first where carried");
@@ -414,9 +421,9 @@ int main()
check(rgfxFeatureWord(kRgfxOfferedFeatures | k16K, k16K) == (kRgfxOfferedFeatures | k16KCarried),
"PAGES_16K taken is in the word where carried");
check(rgfxDriverFeatures(0) == 0, "nothing offered, nothing written");
check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNotCarried | (1ull << 51)) == 0,
check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNotCarried | (1ull << 52)) == 0,
"every other bit offered, none written");
check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNew | (1ull << 51)) == kCarried,
check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNew | (1ull << 52)) == kCarried,
"every bit offered, the carried bits written");
check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNotCarried | kPages) == kPages,
"PAGES_BUFFERS offered, written");
@@ -457,7 +464,7 @@ int main()
"SUBMIT_ROOM offered but not taken is not");
// A read-back of bits the kext never wrote, or of bits 0 to 2 the host does not offer, adds
// nothing.
check(rgfxFeatureWord(kRgfxOfferedFeatures, kNotCarried | (1ull << 51)) ==
check(rgfxFeatureWord(kRgfxOfferedFeatures, kNotCarried | (1ull << 52)) ==
kRgfxOfferedFeatures,
"taken bits the kext does not carry out are dropped");
check(rgfxFeatureWord(kRgfxOfferedFeatures | kNew, kNew) == (kRgfxOfferedFeatures | kCarried),
+113
View File
@@ -0,0 +1,113 @@
// The native test of RgfxPointerMotion.hpp: a POINTER_MOTION's motion, wheel and buttons, the
// reports that carry it (one for a press alone, several for motion past one report's range, each
// with its buttons), and the report descriptor's shape: a mouse of five buttons, relative 16-bit
// X and Y and an 8-bit wheel, six bytes a report.
#include "RgfxPointerMotion.hpp"
#include <cstdio>
#include <cstdlib>
#include <cstring>
namespace {
int checks = 0;
void check(bool ok, const char *what)
{
checks++;
if (!ok) {
std::fprintf(stderr, "pointer_motion_test: FAILED: %s\n", what);
std::exit(1);
}
}
int16_t axis(const uint8_t *r, int at)
{
return static_cast<int16_t>(static_cast<uint16_t>(r[at] | (r[at + 1] << 8)));
}
} // namespace
int main()
{
// The event's layout: the motion, the wheel, then the buttons, past its 16-byte header.
{
RgfxPointerMotion event = {};
event.header.type = RGFX_EVT_POINTER_MOTION;
event.dx = -300;
event.dy = 7;
event.wheel = -2;
event.buttons = RGFX_POINTER_BUTTON_RIGHT;
uint8_t bytes[sizeof(event)];
std::memcpy(bytes, &event, sizeof(event));
RgfxMotion m = {};
check(rgfxPointerMotionRead(bytes + sizeof(RgfxMsgHeader), sizeof(event) - sizeof(RgfxMsgHeader), &m),
"a whole POINTER_MOTION reads");
check(m.dx == -300 && m.dy == 7 && m.wheel == -2 && m.buttons == RGFX_POINTER_BUTTON_RIGHT,
"its fields in order");
check(!rgfxPointerMotionRead(bytes + 16, 12, &m), "a short one reads nothing");
}
uint8_t r[kRgfxMouseReportsMax][kRgfxMouseReportBytes];
// A press alone is one report of no motion.
{
const uint32_t n = rgfxMouseReports({0, 0, 0, RGFX_POINTER_BUTTON_LEFT}, r);
check(n == 1, "a press alone is one report");
check(r[0][0] == 1 && axis(r[0], 1) == 0 && axis(r[0], 3) == 0 && r[0][5] == 0,
"the left button, no motion");
}
// Motion and the wheel in range: one report, little-endian, the wheel signed.
{
const uint32_t n = rgfxMouseReports({-5, 1234, -3, RGFX_POINTER_BUTTON_EXTRA}, r);
check(n == 1, "motion in range is one report");
check(r[0][0] == 0x10, "the extra button is HID button 5");
check(axis(r[0], 1) == -5 && axis(r[0], 3) == 1234, "X and Y");
check(static_cast<int8_t>(r[0][5]) == -3, "the wheel, down");
}
// Every button maps to its HID button, nothing past the five.
{
rgfxMouseReports({0, 0, 0, 0xffffffffu}, r);
check(r[0][0] == 0x1f, "five buttons and no more");
}
// Motion past a report's range goes as several, each with the buttons, the sum the motion.
{
const uint32_t n = rgfxMouseReports({70000, -40000, 300, RGFX_POINTER_BUTTON_LEFT}, r);
check(n == 3, "70000 across takes three reports");
long x = 0, y = 0, w = 0;
for (uint32_t i = 0; i < n; i++) {
check(r[i][0] == 1, "each report holds the button");
x += axis(r[i], 1);
y += axis(r[i], 3);
w += static_cast<int8_t>(r[i][5]);
}
check(x == 70000 && y == -40000 && w == 300, "the reports sum to the motion");
check(axis(r[0], 1) == 32767 && axis(r[0], 3) == -32767, "each axis's first is its most");
}
// Past every report the device sends, the rest is dropped.
{
const uint32_t n = rgfxMouseReports({INT32_MAX, 0, 0, 0}, r);
check(n == kRgfxMouseReportsMax, "at most the reports the device sends");
}
// The descriptor: a mouse's application collection, its 6-byte input report's fields.
{
check(kRgfxMouseReportDescriptor[0] == 0x05 && kRgfxMouseReportDescriptor[1] == 0x01 &&
kRgfxMouseReportDescriptor[2] == 0x09 && kRgfxMouseReportDescriptor[3] == 0x02,
"Generic Desktop, Mouse");
// The input items' bits: 5 + 3 + 2 x 16 + 8 = 48, six bytes.
int bits = 0, size = 0, count = 0;
for (size_t i = 0; i < sizeof(kRgfxMouseReportDescriptor);) {
const uint8_t item = kRgfxMouseReportDescriptor[i];
const int len = (item & 3) == 3 ? 4 : (item & 3);
int value = 0;
for (int b = 0; b < len; b++)
value |= kRgfxMouseReportDescriptor[i + 1 + b] << (8 * b);
if ((item & 0xfc) == 0x74)
size = value;
else if ((item & 0xfc) == 0x94)
count = value;
else if ((item & 0xfc) == 0x80)
bits += size * count;
i += 1 + len;
}
check(bits == 8 * static_cast<int>(kRgfxMouseReportBytes), "the report is six bytes");
}
std::printf("pointer_motion_test: %d checks passed\n", checks);
return 0;
}