feat(portal): follow the viewer's mouse mode with the embedded cursor (#203)

* feat(portal): follow the viewer's mouse mode with the embedded cursor

The portal stream hides the compositor cursor. A viewer that drives the pointer
with relative motion (UU's controlled-end mouse, also the Mac trackpad mode)
has no absolute position to draw its own pointer at, and the game's cursor
never reaches the picture, so the mouse can be moved and clicked but not seen.

Request cursor_mode=embedded while relative motion arrives, and keep it hidden
while absolute motion arrives: there the viewer draws its own pointer and an
embedded copy would trail it. The portal reads cursor_mode only when the
session is created, so switch by rebuilding the session with the saved consent,
the same path the privacy screen uses. A run has to last five events and 200 ms
before it counts, so a burst at connect or an alternating controller does not
rebuild; a failed rebuild backs off for five seconds.

The rebuilt session is checked against the monitor the previous one captured,
so a restored consent cannot silently move the share. The engine keeps the mode
for later opens (recovery, privacy, monitor switches) and skips the switch when
an older libuu-portal.so lacks uu_portal_set_cursor_mode.

UU_PORTAL_CURSOR_MODE=embedded sets the startup default.

* fix(portal): keep the cursor rebuild off locks and held input

Do not rebuild while the desktop is locked, and cancel an open that is already
waiting when it locks: GNOME closes the portal session on lock, so the request
would wait for consent that cannot be answered while holding `recovery`
against the post-unlock recovery.

Keys and buttons held through the portal input path are dropped when the
session is replaced, so wait for their release. Monitor selection takes the
same `recovery` lock, so it cannot install a stale source over the cursor
rebuild or the other way round, and the rebuilt session is revalidated against
the source it started from.

* fix(portal): carry the clipboard across cursor rebuilds

The engine keeps the viewer's text only in the session that provided it, and
the host re-sends it only for a new viewer update. A replacement session
therefore had no clipboard ownership, so changing the mouse mode made
previously synchronized text unpasteable until the viewer sent it again.

Offer the text to the replacement before the old session closes, but only
while that session still owns the selection: a local copy that has taken the
clipboard since is left alone. Touch consent upgrades replace the handle too,
so they take the same `recovery` lock as recovery, monitor selection and the
cursor rebuild and cannot install a handle opened under an older cursor mode.

* fix(portal): serialize clipboard writes with the cursor swap

The clipboard bridge calls clipboard_set from its own thread. Installing the
replacement handle and then carrying the old text over left a window where an
update could land on the new session and be overwritten by the older text,
with no pending update left to restore it.

Take a clipboard write lock before the handle is installed and hold it until
the carry-over finishes; clipboard_set takes the same lock. A write that
starts before the swap is included in the text carried over, a write that
starts after waits and wins.

* fix(portal): cancel a waiting rebuild when the desktop ends

The desktop ends its share when the last controller leaves (end_idle), but an
open that is still waiting for consent is not the installed handle, so it
survived that shutdown and installed a live share afterwards.

Bump an end generation in Session::end(), snapshot it before the open, and
cancel the request when it moves. The generation is checked again under the
handle lock before installing, so an end that races the swap either aborts
the rebuild or ends the handle it just installed.

* fix(portal): keep session swaps consistent with the viewer's state

Addresses the ownership race reported on the previous commit and the paths
that share its failure mode.

uu_portal_clipboard_set publishes the new text before SetSelection so a
transfer during the call serves it, restores the old text when the call fails,
and ignores a stale revision so a newer owner wins. The engine reports the
cursor mode it actually requested and the modes the backend advertised; the
host follows that instead of assuming the request was applied and stops
retrying where an embedded cursor is unavailable. The end generation is
sampled before the rebuild queues for `recovery`, a rebuild refuses to start
while the session is no longer alive, and cancellation now covers virtual
output opens.

Portal-bound keys and buttons are tracked separately, so an input held through
the portal defers the swap on every routing path, and the check is repeated
after the open. Every handle replacement (privacy screen, monitor switch,
touch consent, recovery after lock or stream loss) carries the viewer's
clipboard under the clipboard write lock, and the rebuilt session is checked
against the captured geometry.

* fix(portal): stop the swap bookkeeping from outliving a deferred rebuild

open_inner publishes the replacement's cursor mode before the swap. When held
input defers the rebuild, that session is never installed, so the host belief
described the discarded handle and later motion looked like it already matched.
Restore the belief from the installed session on every abort path.

The extra portal releases in release_held now stop at the first failure like
the sweep above; with a dead portal bus each remaining input waited out the
three-second timeout while the input and desktop-owner locks were held.

* fix(portal): invalidate clipboard ownership when a session ends

A closed session stops receiving owner changes, so a cached clipboard_owns
survived into the recovery paths and could republish old viewer text over a
newer local copy. Clear the claim in uu_portal_end and the Closed handler, and
let uu_portal_clipboard_copy refuse a source that is no longer alive.

Mark the embedded cursor unavailable when the engine did not apply it: with
AvailableCursorModes unreadable the session opens hidden, and retrying on every
motion run rebuilt it every 200 ms without changing the mode.

* fix(portal): retire held portal input when the devices are replaced

A key or button held through the native portal path is recorded when its
injection succeeds. If the session dies first, the key-up fails and the record
survives; recovery then installs new devices while the tracker still says an
input is held, so pointer-mode detection keeps deferring.

Keep the tracker in module state and clear it whenever the portal replaces or
ends its devices: the rebuild, both recovery paths and Session::end.

* fix(portal): scope held-input retirement to the retired handle

A press delivered to the replacement after the swap could be recorded while
the old handle was still being retired, and the unconditional reset then
deleted it. Hold the recording lock from before the swap until the reset
finishes, so only inputs sent to the retired devices are dropped.

A portal touchscreen contact was not tracked at all: the swap retired the
active contact while TouchDrag stayed down, so the following move reached a
session that never saw the press. Track contact down/up and include it in the
deferral state.

* fix(portal): serialize touch injection with handle replacement

inject_touch wrote the contact state outside the recording lock the handle
swap holds, so a contact delivered to the replacement between the swap and the
reset could be cleared, and the following phase-1 would fail on new devices
that never saw the press. Take the same lock across the injection and the
state update.

* fix(portal): decide the swap under the held-input lock

The final held-input check ran before install_replacement() took the serial
lock, so an input could be injected and recorded against the old handle while
the install waited for the clipboard lock. The install then retired the
records and swapped, destroying a contact the new devices never saw. Repeat
the check under the serial lock that recording uses, and defer the rebuild
when it hits.

* fix(portal): hold the input lock across native injection, refresh privacy geometry

inject_button and inject_key injected through the portal and only took the
recording lock afterwards, so a swap could take the lock, see no held input
and replace the devices that had just received the press. Take the serial lock
across the injection and its record, as the touch path does; the record
helpers no longer take it themselves.

A cursor rebuild that replaces the privacy virtual output invalidates the
cached pointer region: recompute it from the settled layout so absolute input
keeps landing inside the captured share.
This commit is contained in:
Mr. Error authored and GitHub committed 2026-11-09 08:36:37 +08:00
1 parent c489f3056f
commit 21e9e690ae
11 files changed
+592 -38

No files matched your search

+79 -4
View File
@@ -43,6 +43,28 @@ struct PendingPointer {
unsafe fn x11_pointer_state(_: *mut libc::c_int,_:*mut libc::c_int,_:*mut libc::c_uint)->libc::c_int {-1}
#[derive(Default)]
struct HeldInput { buttons: std::collections::BTreeSet<i32>, keys: std::collections::BTreeSet<u64> }
/// Inputs held through the portal session are dropped when that session is replaced; the
/// cursor-mode rebuild waits until they are released. uinput devices survive the swap.
static PORTAL_INPUT_HELD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// An active contact on the portal touchscreen is also lost when the session is replaced.
static PORTAL_TOUCH_HELD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn portal_input_held() -> bool {
PORTAL_INPUT_HELD.load(std::sync::atomic::Ordering::Relaxed) || PORTAL_TOUCH_HELD.load(std::sync::atomic::Ordering::Relaxed)
}
/// Inputs currently bound to the portal session; a replacement tears those devices down.
static PORTAL_HELD: std::sync::Mutex<HeldInput> = std::sync::Mutex::new(HeldInput { buttons: std::collections::BTreeSet::new(), keys: std::collections::BTreeSet::new() });
/// Serializes recording an input with retiring the records of a replaced handle.
static PORTAL_HELD_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
pub fn lock_portal_held() -> std::sync::MutexGuard<'static, ()> {
PORTAL_HELD_SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// The portal replaced its native devices: records of held portal inputs no longer apply.
/// The caller holds `lock_portal_held()`, so an input recorded against the new handle stays.
pub fn portal_session_replaced() {
if let Ok(mut held)=PORTAL_HELD.lock() { *held=HeldInput::default(); }
PORTAL_INPUT_HELD.store(false, std::sync::atomic::Ordering::Relaxed);
PORTAL_TOUCH_HELD.store(false, std::sync::atomic::Ordering::Relaxed);
}
/// Held modifier VKs (bit 0 Ctrl, 1 Shift, 2 Alt, 3 Win) and keys that got a synthetic Shift.
#[derive(Default)]
struct Shortcuts { modifiers: u8, shifted: std::collections::BTreeSet<i32> }
@@ -388,8 +410,20 @@ impl InputInjector {
});
}
fn inject_touch(&self, phase: i32, x: i32, y: i32) -> i32 {
// Serialize the contact with handle replacement: a contact sent to the new devices
let Some(portal) = self.portal.lock().unwrap().clone() else { return -1 };
self.portal_result("touch", portal.touch(phase, f64::from(x), f64::from(y)))
// Serialize with handle replacement while the contact is sent; portal then recording
// lock, the same order the button and key recorders use.
let _serial = lock_portal_held();
let result = self.portal_result("touch", portal.touch(phase, f64::from(x), f64::from(y)));
if result == 0 {
match phase {
0 => PORTAL_TOUCH_HELD.store(true, std::sync::atomic::Ordering::Relaxed),
2 => PORTAL_TOUCH_HELD.store(false, std::sync::atomic::Ordering::Relaxed),
_ => {}
}
}
result
}
fn terminal_focused(&self) -> bool {
@@ -504,6 +538,16 @@ impl InputInjector {
if !keys_ok {log::warn!("Desktop input reset incomplete: backend unavailable");}
}
*held=HeldInput::default();
// Inputs bound to the portal session are not covered by the uinput release above.
let (portal_buttons, portal_keys) = {
let _serial=lock_portal_held();
let mut pending=PORTAL_HELD.lock().unwrap();
(std::mem::take(&mut pending.buttons), std::mem::take(&mut pending.keys))
};
// Stop on the first failure like the sweep above: each call can wait out the portal timeout.
let buttons_ok = portal_buttons.into_iter().all(|button| self.inject_button(button,false)==0);
if buttons_ok { for key in portal_keys { if self.inject_key(key,false)!=0 { break; } } }
PORTAL_INPUT_HELD.store(false,std::sync::atomic::Ordering::Relaxed);
*self.shortcuts.lock().unwrap()=Shortcuts::default();
*self.cmd.lock().unwrap()=CmdState::default();
}
@@ -537,7 +581,22 @@ impl InputInjector {
}
}
}
/// Inputs bound to the portal session are dropped when that session is replaced.
fn record_portal_button(&self, button: i32, pressed: bool) {
// Callers hold the serial lock across the injection they are recording.
let mut held = PORTAL_HELD.lock().unwrap();
if pressed { held.buttons.insert(button); } else { held.buttons.remove(&button); }
PORTAL_INPUT_HELD.store(!held.buttons.is_empty() || !held.keys.is_empty(), std::sync::atomic::Ordering::Relaxed);
}
fn record_portal_key(&self, symbol: u64, pressed: bool) {
let mut held = PORTAL_HELD.lock().unwrap();
if pressed { held.keys.insert(symbol); } else { held.keys.remove(&symbol); }
PORTAL_INPUT_HELD.store(!held.buttons.is_empty() || !held.keys.is_empty(), std::sync::atomic::Ordering::Relaxed);
}
fn inject_move(&self,x:i32,y:i32,relative:bool)->i32 {
// The viewer's mouse mode decides whether the stream must carry the pointer (see
// portal::note_pointer_motion); only the portal backend can change that.
if self.backend==crate::desktop_backend::DesktopBackend::Portal { crate::portal::note_pointer_motion(relative); }
if self.uinput_pointer && self.backend != crate::desktop_backend::DesktopBackend::X11 {
if let Some(uinput) = &self.uinput {
if relative { return Self::uinput_result(uinput.move_relative(x,y)); }
@@ -607,14 +666,25 @@ impl InputInjector {
// Portal: clicks follow absolute motion on the same session, so a tap cannot land
// before the compositor has moved the pointer there (uinput is a separate queue).
if !self.uinput_pointer && self.backend==crate::desktop_backend::DesktopBackend::Portal && !self.virtual_uinput() {
if let Some(portal)=self.portal.lock().unwrap().as_ref() { return self.portal_result("button", portal.button(button,pressed)); }
if let Some(portal)=self.portal.lock().unwrap().as_ref() {
// The injection and its record must both predate or both postdate a swap.
let _serial=lock_portal_held();
let result=self.portal_result("button", portal.button(button,pressed));
if result==0 { self.record_portal_button(button,pressed); }
return result;
}
}
if let Some(uinput)=&self.uinput {
if let Some((v,h))=crate::uinput::wheel_step(button) { return if pressed { Self::uinput_result(uinput.wheel(v,h)) } else { 0 }; }
if let Some(code)=crate::uinput::button_code(button) { return Self::uinput_result(uinput.button(code,pressed)); }
}
if self.backend==crate::desktop_backend::DesktopBackend::Kms { return -1; }
if let Some(portal)=self.portal.lock().unwrap().as_ref() { return self.portal_result("button", portal.button(button,pressed)); }
if let Some(portal)=self.portal.lock().unwrap().as_ref() {
let _serial=lock_portal_held();
let result=self.portal_result("button", portal.button(button,pressed));
if result==0 { self.record_portal_button(button,pressed); }
return result;
}
if self.backend==crate::desktop_backend::DesktopBackend::Portal {return self.portal_result("button", Err("Portal input session is not bound".into()));}
if self.backend==crate::desktop_backend::DesktopBackend::Wayland { crate::wayland::button(button,pressed) }
else { unsafe { x11_mouse_button(button,i32::from(pressed)) } }
@@ -624,7 +694,12 @@ impl InputInjector {
if let Some(code)=crate::uinput::keysym_to_evdev(symbol) { return Self::uinput_result(uinput.key(code,pressed)); }
}
if self.backend==crate::desktop_backend::DesktopBackend::Kms { return -1; }
if let Some(portal)=self.portal.lock().unwrap().as_ref() { return self.portal_result("keyboard", portal.key(symbol,pressed)); }
if let Some(portal)=self.portal.lock().unwrap().as_ref() {
let _serial=lock_portal_held();
let result=self.portal_result("keyboard", portal.key(symbol,pressed));
if result==0 { self.record_portal_key(symbol,pressed); }
return result;
}
if self.backend==crate::desktop_backend::DesktopBackend::Portal {return self.portal_result("keyboard", Err("Portal input session is not bound".into()));}
if self.backend==crate::desktop_backend::DesktopBackend::Wayland { crate::wayland::key(symbol,pressed) }
else { unsafe { x11_key_symbol(symbol as libc::c_ulong,i32::from(pressed)) } }
+406 -25
View File
@@ -42,9 +42,13 @@ mod native {
fn uu_portal_open_persist_cancellable(restore: *const libc::c_char, save: extern "C" fn(*const libc::c_char, *mut c_void), save_data: *mut c_void, cancelled: extern "C" fn(*mut c_void) -> i32, cancel_data: *mut c_void, error: *mut i32, width: *mut u32, height: *mut u32) -> *mut c_void;
fn uu_portal_open_persist_capture(restore: *const libc::c_char, save: extern "C" fn(*const libc::c_char, *mut c_void), save_data: *mut c_void, cancelled: Option<extern "C" fn(*mut c_void) -> i32>, cancel_data: *mut c_void, prefer_dmabuf: i32, error: *mut i32, width: *mut u32, height: *mut u32) -> *mut c_void;
fn uu_portal_open_detailed(restore: *const libc::c_char, save: extern "C" fn(*const libc::c_char, *mut c_void, i32, i32, i32), save_data: *mut c_void, cancelled: Option<extern "C" fn(*mut c_void) -> i32>, cancel_data: *mut c_void, prefer_dmabuf: i32, source_types: u32, error: *mut i32, width: *mut u32, height: *mut u32) -> *mut c_void;
fn uu_portal_set_cursor_mode(mode: i32);
fn uu_portal_cursor_mode(portal: *mut c_void) -> i32;
fn uu_portal_cursor_modes(portal: *mut c_void) -> i32;
fn uu_portal_clipboard_supported(portal: *mut c_void) -> i32;
fn uu_portal_clipboard_ready(portal: *mut c_void) -> i32;
fn uu_portal_clipboard_set(portal: *mut c_void, text: *const u8, length: usize) -> i32;
fn uu_portal_clipboard_copy(from: *mut c_void, to: *mut c_void) -> i32;
fn uu_portal_clipboard_poll(portal: *mut c_void, text: *mut u8, capacity: usize) -> i32;
fn uu_portal_close(portal: *mut c_void);
fn uu_portal_alive(portal: *mut c_void) -> i32;
@@ -83,6 +87,8 @@ mod native {
}
// Portal preparation and native teardown can wait for consent or D-Bus.
// Only the swap may hold the mutex shared with input and clipboard.
// Only the unit tests swap a test handle now; production swaps carry the clipboard.
#[cfg(test)]
fn replace_handle<T>(current: &Mutex<T>, locked: MutexGuard<'_, T>, prepare: impl FnOnce() -> Result<Option<T>, String>) -> Result<bool, String> {
drop(locked);
let Some(replacement) = prepare()? else { return Ok(false); };
@@ -93,6 +99,24 @@ mod native {
drop(old);
Ok(true)
}
/// Like `replace_handle`, but carries the viewer's clipboard text before the old session
/// closes. Clipboard writers wait from before the swap until the carry-over finishes.
fn replace_handle_carrying(current: &Mutex<Arc<Handle>>, clipboard_write: &Mutex<()>, locked: MutexGuard<'_, Arc<Handle>>, prepare: impl FnOnce() -> Result<Option<Arc<Handle>>, String>) -> Result<bool, String> {
drop(locked);
let Some(replacement) = prepare()? else { return Ok(false); };
let _clipboard = clipboard_write.lock().map_err(|_| "Portal clipboard lock poisoned")?;
let _serial = crate::input::lock_portal_held();
let (old, installed) = {
let mut handle = current.lock().map_err(|_| "Portal session lock poisoned")?;
let old = std::mem::replace(&mut *handle, replacement);
(old, Arc::clone(&*handle))
};
unsafe { uu_portal_clipboard_copy(old.0.as_ptr(), installed.0.as_ptr()) };
drop(old);
// The replaced devices took any held portal input with them.
crate::input::portal_session_replaced();
Ok(true)
}
#[derive(Default)]
struct Recovery { retry_at: Option<std::time::Instant>, failed_until: Option<std::time::Instant>, denied: bool }
impl Recovery {
@@ -118,7 +142,7 @@ mod native {
was_locked.store(false, std::sync::atomic::Ordering::Release);
}
}
pub struct Session { handle: Mutex<Arc<Handle>>, locked: tokio::sync::watch::Receiver<Option<bool>>, was_locked: std::sync::atomic::AtomicBool, recovery: Mutex<Recovery>, size: std::sync::atomic::AtomicU64, monitor: Mutex<Option<String>>, virtual_output: std::sync::atomic::AtomicBool }
pub struct Session { handle: Mutex<Arc<Handle>>, locked: tokio::sync::watch::Receiver<Option<bool>>, was_locked: std::sync::atomic::AtomicBool, recovery: Mutex<Recovery>, size: std::sync::atomic::AtomicU64, monitor: Mutex<Option<String>>, virtual_output: std::sync::atomic::AtomicBool, clipboard_write: Mutex<()>, end_generation: Arc<std::sync::atomic::AtomicU64> }
impl Session {
fn take_lock_observation(&self) -> Result<bool, String> {
// A recovery in progress must see the lock even if another capture
@@ -139,6 +163,44 @@ mod native {
Ok(())
}
}
/// Swap `replacement` in, carrying the viewer's clipboard text before the old session
/// closes. `expected` rejects a desktop end that raced the open.
fn install_replacement(&self, replacement: Self, expected: Option<u64>, defer_held: bool, refresh_privacy: bool) -> Result<(u32, u32), String> {
let size = replacement.size();
let next = replacement.handle.into_inner().map_err(|_| "Portal session lock poisoned".to_string())?;
let clipboard = self.clipboard_write.lock().map_err(|_| "Portal clipboard lock poisoned".to_string())?;
// Records made against the new handle must postdate the reset below.
let serial = crate::input::lock_portal_held();
// Checked under the serial lock: an input recorded after an earlier check would
// otherwise be destroyed with the session it was sent to.
if defer_held && crate::input::portal_input_held() { return Err("input held during the swap".into()); }
let mut handle = self.handle.lock().map_err(|_| "Portal session lock poisoned".to_string())?;
if expected.is_some_and(|generation| self.end_generation.load(std::sync::atomic::Ordering::Acquire) != generation) {
return Err("desktop session ended during the rebuild".into());
}
self.size.store(pack(size.0, size.1), std::sync::atomic::Ordering::Release);
let previous_handle = std::mem::replace(&mut *handle, next);
let installed = Arc::clone(&*handle);
drop(handle);
if unsafe { uu_portal_clipboard_copy(previous_handle.0.as_ptr(), installed.0.as_ptr()) } < 0 {
log::warn!("Portal clipboard ownership could not be carried over");
}
drop(clipboard);
drop(previous_handle);
// The replaced devices took any held portal input with them.
crate::input::portal_session_replaced();
drop(serial);
// A replaced virtual output can move in the layout; absolute input needs its new share.
if refresh_privacy { crate::privacy_screen::refresh_pointer_region(); }
Ok(size)
}
/// Point the host and the engine at the cursor mode the installed session really has.
fn restore_installed_cursor_mode(&self, fallback: bool) {
let installed = self.handle.lock().ok().map(|handle| unsafe { uu_portal_cursor_mode(handle.0.as_ptr()) }).unwrap_or(0);
let embedded = if installed > 0 { installed == 2 } else { fallback };
unsafe { uu_portal_set_cursor_mode(if embedded { 2 } else { 1 }); }
super::CURSOR_MODE.store(if embedded { 2 } else { 1 }, std::sync::atomic::Ordering::Release);
}
pub fn is_alive(&self) -> bool {
self.handle.lock().is_ok_and(|handle| unsafe { uu_portal_alive(handle.0.as_ptr()) != 0 })
}
@@ -218,7 +280,8 @@ mod native {
prefer_dmabuf = true;
}
let pointer = if detailed {
let cancel = cancelled.filter(|_| !virtual_output);
// Virtual shares can wait for consent too; cancel them like monitor opens.
let cancel = cancelled;
let callback = cancel.map(|_| is_cancelled as extern "C" fn(*mut c_void) -> i32);
let cancel_data = cancel.map_or(std::ptr::null_mut(), |value| value as *const _ as *mut c_void);
unsafe { uu_portal_open_detailed(
@@ -266,7 +329,14 @@ mod native {
if wanted.is_some() && granted != wanted { log::warn!("Portal granted a different monitor than requested"); }
// Keep a freshly granted compositor frame regardless of lock state. Discarding it
// before new damage can leave a static desktop permanently blank (#2).
Ok(Self { handle: Mutex::new(Arc::new(Handle(handle))), locked: crate::session_lock::watch_locked(), was_locked: std::sync::atomic::AtomicBool::new(false), recovery: Mutex::new(Recovery::default()), size: pack(width, height).into(), monitor: Mutex::new(granted), virtual_output: virtual_output.into() })
let handle = Arc::new(Handle(handle));
// The engine records what it actually requested; a backend can refuse the mode the
// environment or a runtime switch asked for.
let available = unsafe { uu_portal_cursor_modes(handle.0.as_ptr()) };
let applied = unsafe { uu_portal_cursor_mode(handle.0.as_ptr()) };
if applied > 0 { super::CURSOR_MODE.store(if applied == 2 { 2 } else { 1 }, std::sync::atomic::Ordering::Release); }
if available > 0 { super::CURSOR_EMBED.store(if available & 2 != 0 { 2 } else { 1 }, std::sync::atomic::Ordering::Release); }
Ok(Self { handle: Mutex::new(handle), locked: crate::session_lock::watch_locked(), was_locked: std::sync::atomic::AtomicBool::new(false), recovery: Mutex::new(Recovery::default()), size: pack(width, height).into(), monitor: Mutex::new(granted), virtual_output: virtual_output.into(), clipboard_write: Mutex::new(()), end_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)) })
}
/// Frame pixels of the monitor the stream currently follows.
pub fn size(&self) -> (u32, u32) {
@@ -276,7 +346,13 @@ mod native {
/// End the compositor session (screen-share indicator off); the next desktop
/// connection reopens it with the saved consent.
pub fn end(&self) {
// Invalidate an open that is still waiting for consent: it must not install a share
// after the desktop was ended (viewer disconnect, idle shutdown, capture teardown).
self.end_generation.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
if let Ok(handle) = self.handle.lock() { unsafe { uu_portal_end(handle.0.as_ptr()) }; }
// The ended session's native devices are gone; forget the inputs bound to them.
let _serial = crate::input::lock_portal_held();
crate::input::portal_session_replaced();
}
/// Mutter connector of the monitor this session captures, when several are advertised.
pub fn monitor(&self) -> Option<String> { self.monitor.lock().ok().and_then(|m| m.clone()) }
@@ -284,19 +360,15 @@ mod native {
/// time GNOME asks on the host) and swap it in, so every holder of this Arc follows.
pub fn switch_to(&self, connector: &str) -> Result<(), String> {
if self.monitor().as_deref() == Some(connector) { return Ok(()); }
// Both this and the cursor-mode rebuild replace the handle: serialize them so the
// later open cannot install a stale source over the other.
let _recovery = self.recovery.lock().map_err(|_| "Portal recovery lock poisoned")?;
let replacement = Self::open_inner(None, Some(connector), false, false).map_err(|error| error.to_string())?;
if replacement.monitor().as_deref() != Some(connector) {
return Err("Another monitor was shared; choose this monitor in the host dialog".into());
}
let size = replacement.size();
let next = replacement.handle.into_inner().map_err(|_| "Portal session lock poisoned")?;
let previous = {
let mut handle = self.handle.lock().map_err(|_| "Portal session lock poisoned")?;
self.size.store(pack(size.0, size.1), std::sync::atomic::Ordering::Release);
std::mem::replace(&mut *handle, next)
};
self.install_replacement(replacement, None, false, false)?;
if let Ok(mut monitor) = self.monitor.lock() { *monitor = Some(connector.to_owned()); }
drop(previous);
Ok(())
}
pub fn is_virtual(&self) -> bool { self.virtual_output.load(std::sync::atomic::Ordering::Acquire) }
@@ -311,18 +383,116 @@ mod native {
// exists (seen live: 3968x1280 = panel + virtual), so end the virtual share first.
if !on { self.end(); }
let replacement = Self::open_inner(None, monitor.as_deref(), false, on).map_err(|error| error.to_string())?;
let size = replacement.size();
let next = replacement.handle.into_inner().map_err(|_| "Portal session lock poisoned")?;
let previous = {
let mut handle = self.handle.lock().map_err(|_| "Portal session lock poisoned")?;
self.size.store(pack(size.0, size.1), std::sync::atomic::Ordering::Release);
self.virtual_output.store(on, std::sync::atomic::Ordering::Release);
std::mem::replace(&mut *handle, next)
};
drop(previous);
let size = self.install_replacement(replacement, None, false, false)?;
self.virtual_output.store(on, std::sync::atomic::Ordering::Release);
log::info!("Portal capture source: virtual={on} size={}x{}", size.0, size.1);
Ok(())
}
/// Ask the compositor to draw the pointer into the stream (embedded) or keep it out
/// (hidden). The portal only reads this when the session is created, so swap in a fresh
/// session with the saved consent; every holder of this Arc follows the new handle.
/// Ok(true): the mode changed. Ok(false): nothing to do, or the desktop is locked and the
/// next unlocked motion retries.
pub fn set_cursor_embedded(&self, embedded: bool) -> Result<bool, String> {
use std::sync::atomic::{AtomicBool, Ordering};
if super::cursor_embedded() == embedded { return Ok(false); }
// Sample before waiting for `recovery`: an end that happens while this worker is
// queued must invalidate the rebuild below.
let generation = self.end_generation.load(Ordering::Acquire);
if *self.locked.borrow() != Some(false) { return Ok(false); }
// A backend without the embedded cursor mode never applies the request; remember it
// so motion does not spawn a rebuild every few events.
let modes = self.handle.lock().map(|handle| unsafe { uu_portal_cursor_modes(handle.0.as_ptr()) }).unwrap_or(0);
if modes > 0 && modes & 2 == 0 { super::CURSOR_EMBED.store(1, Ordering::Release); return Ok(false); }
if modes & 2 != 0 { super::CURSOR_EMBED.store(2, Ordering::Release); }
let _recovery = self.recovery.lock().map_err(|_| "Portal recovery lock poisoned")?;
if super::cursor_embedded() == embedded { return Ok(false); }
if *self.locked.borrow() != Some(false) { return Ok(false); }
// The session this rebuild replaces must still be running: a viewer that left or an
// idle shutdown ends it, and a replacement opened afterwards would share with nobody.
if !self.is_alive() { return Ok(false); }
if crate::input::portal_input_held() { return Ok(false); }
let previous = super::cursor_embedded();
let virtual_output = self.is_virtual();
let monitor = self.monitor();
// A lock or desktop end during the open must cancel the consent request, not wait
// out its timeout.
let cancel = Arc::new(AtomicBool::new(false));
let stop = Arc::new(AtomicBool::new(false));
let watcher = {
let locked = self.locked.clone();
let end_generation = self.end_generation.clone();
let cancel = cancel.clone();
let stop = stop.clone();
std::thread::Builder::new().name("portal-cursor-lock".into()).spawn(move || {
while !stop.load(Ordering::Acquire) {
if *locked.borrow() != Some(false) || end_generation.load(Ordering::Acquire) != generation {
cancel.store(true, Ordering::Release);
return;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
}).ok()
};
unsafe { uu_portal_set_cursor_mode(if embedded { 2 } else { 1 }); }
let result = (|| -> Result<Option<((u32, u32), i32)>, String> {
let replacement = Self::open_inner(Some(&cancel), monitor.as_deref(), false, virtual_output)
.map_err(|error| error.to_string())?;
if *self.locked.borrow() != Some(false) { return Err("desktop locked during the rebuild".into()); }
if self.end_generation.load(Ordering::Acquire) != generation {
return Err("desktop session ended during the rebuild".into());
}
// A source change that finished meanwhile must not be undone by this swap.
if self.is_virtual() != virtual_output || (!virtual_output && self.monitor() != monitor) {
return Err("capture source changed during the rebuild".into());
}
// A restored consent must not silently move the share to another monitor.
if !virtual_output && monitor.is_some() && replacement.monitor() != monitor {
return Err("another monitor was shared; choose this monitor in the host dialog".into());
}
// KDE does not report the connector, so a size change is the signal that the
// replacement follows another output.
self.check_geometry(&replacement).map_err(|error| error.to_string())?;
// A key or button can go down while the open waits for consent.
if crate::input::portal_input_held() { return Ok(None); }
let size = match self.install_replacement(replacement, Some(generation), true, virtual_output) {
Ok(size) => size,
Err(error) if error == "input held during the swap" => return Ok(None),
Err(error) => return Err(error),
};
let applied = self.handle.lock().ok().map(|handle| unsafe { uu_portal_cursor_mode(handle.0.as_ptr()) }).unwrap_or(0);
Ok(Some((size, applied)))
})();
stop.store(true, Ordering::Release);
drop(watcher);
match result {
Ok(Some(((width, height), applied))) => {
let applied_embedded = applied == 2;
super::CURSOR_MODE.store(if applied_embedded { 2 } else { 1 }, Ordering::Release);
if applied_embedded != embedded {
// The backend refused the mode (or cannot report support); retrying would
// rebuild the session every motion run without changing anything.
super::CURSOR_EMBED.store(1, Ordering::Release);
unsafe { uu_portal_set_cursor_mode(applied) };
log::info!("Portal backend did not apply the embedded cursor");
return Ok(false);
}
log::info!("Portal cursor mode: embedded={embedded} size={width}x{height}");
Ok(true)
}
Ok(None) => {
// Deferred (input went down during the open): open_inner published the
// replacement's mode, but that session is never installed.
self.restore_installed_cursor_mode(previous);
Ok(false)
}
Err(error) => {
// Leave the engine on the mode the installed session actually has.
self.restore_installed_cursor_mode(previous);
Err(error)
}
}
}
pub fn open() -> Result<Self, String> {
Self::open_inner(None, None, false, false).map_err(|error| error.to_string())
}
@@ -337,6 +507,8 @@ mod native {
pub fn upgrade_touch(&self) -> Result<bool, String> {
let available = self.handle.lock().is_ok_and(|handle| unsafe { uu_portal_touch_available(handle.0.as_ptr()) } != 0);
if !available || self.touch_supported() { return Ok(false); }
// Serialize with recovery and the cursor-mode rebuild: all replace the handle.
let _recovery = self.recovery.lock().map_err(|_| "Portal recovery lock poisoned")?;
log::info!("Portal touch consent: asking the host again for the touchscreen");
let monitor = self.monitor();
let replacement = Self::open_inner(None, monitor.as_deref(), true, self.is_virtual()).map_err(|error| error.to_string())?;
@@ -344,9 +516,7 @@ mod native {
if replacement.monitor() != monitor { return Err("another monitor was shared".into()); }
if !replacement.touch_supported() { return Err("the touchscreen was not granted".into()); }
self.check_geometry(&replacement).map_err(|error| error.to_string())?;
let next = replacement.handle.into_inner().map_err(|_| "Portal session lock poisoned")?;
let previous = std::mem::replace(&mut *self.handle.lock().map_err(|_| "Portal session lock poisoned")?, next);
drop(previous);
self.install_replacement(replacement, None, false, self.is_virtual())?;
Ok(true)
}
pub fn open_cancellable(cancelled: &std::sync::atomic::AtomicBool) -> Result<Self, super::PortalError> {
@@ -381,9 +551,19 @@ mod native {
let result = super::open_then_install(cancelled, || Self::open_inner(Some(cancelled), monitor.as_deref(), false, virtual_output), |replacement| {
self.check_geometry(&replacement)?;
let replacement_handle = replacement.handle.into_inner().map_err(|_| super::PortalError { code: 3 })?;
let clipboard = self.clipboard_write.lock().map_err(|_| super::PortalError { code: 3 })?;
let serial = crate::input::lock_portal_held();
let mut handle = self.handle.lock().map_err(|_| super::PortalError { code: 3 })?;
if cancelled.load(Ordering::Acquire) { return Err(super::PortalError { code: 13 }); }
*handle = replacement_handle;
let previous_handle = std::mem::replace(&mut *handle, replacement_handle);
let installed = Arc::clone(&*handle);
drop(handle);
unsafe { uu_portal_clipboard_copy(previous_handle.0.as_ptr(), installed.0.as_ptr()) };
drop(clipboard);
drop(previous_handle);
// The replaced devices took any held portal input with them.
crate::input::portal_session_replaced();
drop(serial);
clear_pause_for_unlocked_replacement(&self.was_locked, *self.locked.borrow());
log::info!("Portal capture session restored after closure");
Ok(())
@@ -474,7 +654,7 @@ mod native {
Err(TryLockError::WouldBlock) => return Ok(blank_changed(frame, version)),
Err(TryLockError::Poisoned(_)) => return Err("Portal recovery lock poisoned".into()),
};
if replace_handle(&self.handle, handle, || {
if replace_handle_carrying(&self.handle, &self.clipboard_write, handle, || {
{
let handle = self.handle.lock().map_err(|_| "Portal session lock poisoned")?;
if unsafe { uu_portal_capture_alive(handle.0.as_ptr()) } != 0 {
@@ -546,6 +726,9 @@ mod native {
}
pub fn clipboard_set(&self, text: &str) -> Result<(), String> {
if text.len()>crate::clipboard::MAX_TEXT || *self.locked.borrow()!=Some(false) { return Err("Portal clipboard unavailable".into()); }
// Serialize with the cursor-session swap: it carries the old text over before
// releasing this lock, so a update that arrives during the swap wins afterwards.
let _write=self.clipboard_write.lock().map_err(|_| "Portal clipboard lock poisoned")?;
let handle=self.handle.lock().map_err(|_| "Portal session lock poisoned")?;
if unsafe { uu_portal_clipboard_set(handle.0.as_ptr(),text.as_ptr(),text.len()) }==0 {Ok(())} else {Err("Portal clipboard ownership failed".into())}
}
@@ -624,6 +807,8 @@ mod native {
recovery: Mutex::new(Recovery::default()),
size: pack(physical.0, physical.1).into(),
monitor: Mutex::new(None), virtual_output: false.into(),
clipboard_write: Mutex::new(()),
end_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)),
}))
}
@@ -920,6 +1105,7 @@ impl PortalSession {
pub fn end(&self) {}
pub fn switch_to(&self, _: &str) -> Result<(), String> { Err(error(15)) }
pub fn set_virtual(&self, _: bool) -> Result<(), String> { Err(error(15)) }
pub fn set_cursor_embedded(&self, _: bool) -> Result<bool, String> { Err(error(15)) }
pub fn is_virtual(&self) -> bool { false }
}
#[cfg(not(all(target_os = "linux", feature = "portal")))]
@@ -980,6 +1166,128 @@ pub fn switch_active(connector: &str) -> Result<(), String> {
.ok_or("Portal desktop unavailable")?;
session.switch_to(connector)
}
/// Whether the capture stream carries the compositor's pointer. 0 is "not asked yet"; the
/// startup answer has to match what the engine reads from UU_PORTAL_CURSOR_MODE.
static CURSOR_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
/// Embedded cursor support reported by a session: 0 unknown, 1 unavailable, 2 available.
static CURSOR_EMBED: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
fn cursor_embedded() -> bool {
use std::sync::atomic::Ordering;
match CURSOR_MODE.load(Ordering::Acquire) {
0 => {
let embedded = std::env::var("UU_PORTAL_CURSOR_MODE").is_ok_and(|value| value.eq_ignore_ascii_case("embedded"));
CURSOR_MODE.store(if embedded { 2 } else { 1 }, Ordering::Release);
embedded
}
mode => mode == 2,
}
}
/// Ask the running session for a stream with (or without) the compositor cursor.
pub fn set_cursor_embedded(embedded: bool) -> Result<bool, String> {
let session = ACTIVE.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref().and_then(std::sync::Weak::upgrade)
.ok_or("Portal desktop unavailable")?;
session.set_cursor_embedded(embedded)
}
/// A release package can carry an older libuu-portal.so without the runtime cursor switch;
/// rebuilding the session would be wasted work there.
fn cursor_switch_available() -> bool {
#[cfg(all(target_os = "linux", feature = "portal", feature = "engine-plugins"))]
{
static AVAILABLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*AVAILABLE.get_or_init(|| crate::engine_plugin::symbol(crate::engine_plugin::Engine::Portal, "uu_portal_set_cursor_mode\0") != 0)
}
#[cfg(not(all(target_os = "linux", feature = "portal", feature = "engine-plugins")))]
{ cfg!(all(target_os = "linux", feature = "portal")) }
}
/// Relative motion has no position the viewer could draw a cursor at, so the stream has to carry
/// one. Absolute motion means the viewer draws its own and an embedded copy would trail it. Both
/// need a fresh portal session, so wait for a run of the same kind before rebuilding it.
struct PointerMode {
candidate: Option<bool>,
streak: u32,
first: Option<std::time::Instant>,
switching: bool,
blocked_until: Option<std::time::Instant>,
}
static POINTER_MODE: std::sync::Mutex<PointerMode> = std::sync::Mutex::new(PointerMode {
candidate: None, streak: 0, first: None, switching: false, blocked_until: None,
});
const POINTER_STREAK: u32 = 5;
/// A burst at connect must not rebuild the session, so the run has to span time as well.
const POINTER_WINDOW: std::time::Duration = std::time::Duration::from_millis(200);
/// After a failed rebuild the consent may be gone; do not retry on the next few events.
const POINTER_COOLDOWN: std::time::Duration = std::time::Duration::from_secs(5);
fn pointer_decision(state: &mut PointerMode, current: bool, relative: bool, now: std::time::Instant) -> Option<bool> {
if current == relative {
state.candidate = None;
state.streak = 0;
state.first = None;
return None;
}
if state.switching || state.blocked_until.is_some_and(|until| now < until) { return None; }
match state.candidate {
Some(candidate) if candidate == relative => {
state.streak += 1;
if state.streak >= POINTER_STREAK
&& state.first.is_some_and(|first| now.duration_since(first) >= POINTER_WINDOW) {
return Some(relative);
}
}
_ => {
state.candidate = Some(relative);
state.streak = 1;
state.first = Some(now);
}
}
None
}
pub fn note_pointer_motion(relative: bool) {
if !cursor_switch_available() { return; }
// The backend does not advertise an embedded cursor: nothing to switch to.
if CURSOR_EMBED.load(std::sync::atomic::Ordering::Acquire) == 1 { return; }
// A swap closes the portal input devices; do not drop keys or buttons the viewer holds.
if crate::input::portal_input_held() { return; }
let decision = {
let Ok(mut state) = POINTER_MODE.lock() else { return; };
let decision = pointer_decision(&mut state, cursor_embedded(), relative, std::time::Instant::now());
if decision.is_some() {
state.switching = true;
state.candidate = None;
state.streak = 0;
state.first = None;
}
decision
};
let Some(target) = decision else { return; };
let spawned = std::thread::Builder::new().name("portal-cursor".into()).spawn(move || {
let result = set_cursor_embedded(target);
let mut state = POINTER_MODE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
state.switching = false;
state.candidate = None;
state.streak = 0;
state.first = None;
match result {
Ok(true) => {
state.blocked_until = None;
drop(state);
log::info!("Cursor mode follows the pointer: embedded={target}");
}
Ok(false) => {
// Locked, or something else changed the mode first; the next motion retries.
state.blocked_until = None;
drop(state);
}
Err(error) => {
state.blocked_until = Some(std::time::Instant::now() + POINTER_COOLDOWN);
drop(state);
log::warn!("Portal cursor switch failed: {error}");
}
}
});
if spawned.is_err() {
if let Ok(mut state) = POINTER_MODE.lock() { state.switching = false; }
}
}
pub struct Monitor { pub connector: String, pub width: u32, pub height: u32, pub x: i32, pub y: i32, pub primary: bool }
#[cfg(all(target_os = "linux", feature = "portal"))]
pub use native::monitors;
@@ -1065,3 +1373,76 @@ mod tests {
assert_eq!(*handle.lock().unwrap(), 11);
}
}
#[cfg(test)]
mod pointer_mode_tests {
use super::{pointer_decision, PointerMode, POINTER_COOLDOWN, POINTER_WINDOW};
use std::time::{Duration, Instant};
fn state() -> PointerMode {
PointerMode { candidate: None, streak: 0, first: None, switching: false, blocked_until: None }
}
#[test]
fn a_connect_burst_does_not_rebuild_the_session() {
let mut state = state();
let start = Instant::now();
for step in 0..20 {
assert_eq!(pointer_decision(&mut state, true, false, start + Duration::from_millis(step)), None);
}
}
#[test]
fn a_sustained_change_decides_once_the_run_spans_the_window() {
let mut state = state();
let start = Instant::now();
let mut decided = None;
for step in 0..40 {
let now = start + Duration::from_millis(step * 10);
if let Some(value) = pointer_decision(&mut state, true, false, now) {
assert!(now.duration_since(start) >= POINTER_WINDOW);
decided = Some(value);
break;
}
}
assert_eq!(decided, Some(false));
}
#[test]
fn an_opposite_event_restarts_the_run() {
let mut state = state();
let start = Instant::now();
for step in 0..10 { pointer_decision(&mut state, true, false, start + Duration::from_millis(step)); }
pointer_decision(&mut state, true, true, start + Duration::from_millis(10));
for step in 11..19 {
assert_eq!(pointer_decision(&mut state, true, false, start + Duration::from_millis(step)), None);
}
}
#[test]
fn a_failed_switch_waits_out_the_cooldown() {
let mut state = state();
let start = Instant::now();
state.blocked_until = Some(start + POINTER_COOLDOWN);
for step in 0..40 {
assert_eq!(pointer_decision(&mut state, true, false, start + Duration::from_millis(step * 10)), None);
}
let after = start + POINTER_COOLDOWN + Duration::from_millis(1);
let mut decided = None;
for step in 0..30 {
let now = after + Duration::from_millis(step * 10);
if let Some(value) = pointer_decision(&mut state, true, false, now) { decided = Some(value); break; }
}
assert_eq!(decided, Some(false));
}
#[test]
fn a_switch_in_flight_ignores_more_events() {
let mut state = state();
let start = Instant::now();
state.switching = true;
for step in 0..40 {
assert_eq!(pointer_decision(&mut state, true, false, start + Duration::from_millis(step * 10)), None);
}
}
}
+3
View File
@@ -20,6 +20,9 @@ pub trait Backend: Send + Sync {
fn enter(&self, mode: Mode, journal: &mut Journal) -> Result<Entered, String>;
/// Undo `data` from `enter`. Also used for crash recovery, where no desktop stream exists.
fn leave(&self, data: &serde_json::Value) -> Result<(), String>;
/// Recompute `Entered::pointer_region` after the virtual output was recreated. None keeps
/// the stored region (backends without a virtual output, or a layout not settled yet).
fn refresh_pointer_region(&self) -> Option<[f64; 4]> { None }
}
/// The backend for this session, if the desktop has one.
+8
View File
@@ -88,6 +88,14 @@ impl Backend for Kde {
log::info!("Privacy KDE: outputs={} input_devices={}", data.outputs.len(), data.devices.len());
Ok(entered)
}
fn refresh_pointer_region(&self) -> Option<[f64; 4]> {
// The old virtual output disappears with the replaced session; wait for the layout to
// settle on the new one before taking its share of the bounding box.
let layout = outputs::layout().ok()?;
let virtuals: Vec<_> = layout.iter().filter(|o| o.name.starts_with("Virtual")).collect();
let target = match virtuals.as_slice() { [only] => *only, _ => return None };
outputs::region(&layout, &target.name)
}
fn leave(&self, data: &serde_json::Value) -> Result<(), String> {
let data: Data = serde_json::from_value(data.clone()).map_err(|_| "invalid KDE recovery data")?;
// KWin persists the device flag: a failure is returned (after restoring the outputs) so the
+12
View File
@@ -48,6 +48,18 @@ pub fn state_message(seq: u64, timestamp: u64) -> Vec<u8> {
}
/// See `backend::Entered::pointer_region`.
pub fn pointer_region() -> Option<[f64; 4]> { *POINTER.lock().ok()? }
/// A session rebuild replaced the virtual output: refresh the region absolute input maps into.
pub fn refresh_pointer_region() {
if !active() { return; }
for _ in 0..10 {
if let Some(region) = backend::detect().and_then(backend::Backend::refresh_pointer_region) {
if let Ok(mut pointer) = POINTER.lock() { *pointer = Some(region); }
return;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
log::warn!("Privacy pointer region not refreshed: virtual output layout did not settle");
}
fn publish(active: Option<&Active>) {
ACTIVE.store(active.is_some(), Ordering::Relaxed);