mirror of
https://github.com/VallierDev/uu-remote-linux.git
synced 2026-11-16 16:50:41 +01:00
GNOME Portal:多显示器切换、精确触控、断开后停止共享 (#128)
* portal: switch monitors on GNOME, precise touch, stop sharing when idle GNOME grants one monitor per portal consent and refuses multi-select, so each Mutter monitor gets its own saved consent (gnome@<connector>). The monitors are advertised as screens; a switch opens that monitor's session (silently once consented, GNOME asks on the host the first time) and swaps it into the shared PortalSession, whose frame size follows the monitor. Absolute motion and clicks go through the portal session: a uinput tablet spans every monitor, and clicks on the separate uinput queue could land before the compositor moved the pointer. An idle watch ends the portal session (screen-share indicator off) once no desktop controller is left for two checks; the next one reopens it with the saved consent. Co-Authored-By: Claude Opus 5.5 <[email protected]> * portal: stop screen sharing as soon as the last controller leaves The idle watch stays as the fallback for controllers that vanish without a release event. Co-Authored-By: Claude Opus 5.5 <[email protected]> * portal test: accept the runtime-engine message in portal builds Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
e503041dac
commit
47c7728822
11 files changed
+279
-27
No files matched your search
+3
-1
@@ -82,8 +82,10 @@ pub struct ScreenCapture {
|
||||
impl ScreenCapture {
|
||||
pub fn open_portal(cancelled: &std::sync::atomic::AtomicBool) -> Result<Self, crate::portal::PortalError> {
|
||||
let session = std::sync::Arc::new(crate::portal::PortalSession::open_cancellable(cancelled)?);
|
||||
crate::portal::register(&session);
|
||||
let (width, height) = session.size();
|
||||
Ok(Self { backend: crate::desktop_backend::DesktopBackend::Portal, init_error: None,
|
||||
display: "wayland:portal".into(), width: session.width, height: session.height,
|
||||
display: "wayland:portal".into(), width, height,
|
||||
portal: Some(session), kms: None, buffer: Mutex::new(Vec::new()) })
|
||||
}
|
||||
pub fn new() -> Result<Self, String> {
|
||||
|
||||
@@ -123,6 +123,14 @@ impl PortalDesktop {
|
||||
|| state.screen.portal.as_ref().is_some_and(|portal| !portal.is_alive()));
|
||||
}
|
||||
pub fn snapshot(&self) -> State { self.state.borrow().clone() }
|
||||
/// No desktop controller left: stop sharing the screen. begin() then sees the dead
|
||||
/// session and the next controller's maintain() reopens it with the saved consent.
|
||||
pub fn end_idle(&self) {
|
||||
if let Some(portal) = self.snapshot().screen.portal.as_ref().filter(|portal| portal.is_alive()) {
|
||||
portal.end();
|
||||
log::info!("Portal screen sharing ended: no desktop controller");
|
||||
}
|
||||
}
|
||||
pub fn subscribe(&self) -> watch::Receiver<State> { self.state.subscribe() }
|
||||
pub fn lock_state(&self) -> watch::Receiver<Option<bool>> { self.locked.clone() }
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -87,6 +87,7 @@ pub use native::symbol;
|
||||
pub trait Missing { fn missing() -> Self; }
|
||||
impl Missing for () { fn missing() -> Self {} }
|
||||
impl Missing for i32 { fn missing() -> Self { -1 } }
|
||||
impl Missing for usize { fn missing() -> Self { 0 } }
|
||||
impl<T> Missing for *mut T { fn missing() -> Self { std::ptr::null_mut() } }
|
||||
|
||||
/// Declares engine C functions: an `extern "C"` block when linked statically, or dlsym-resolved
|
||||
|
||||
@@ -334,6 +334,11 @@ impl InputInjector {
|
||||
let result=crate::wayland::move_pointer(x,y,false);
|
||||
if result!=-2 { return result; }
|
||||
}
|
||||
// Portal (GNOME/KDE): absolute motion is addressed to the shared stream, i.e. the captured
|
||||
// monitor; a uinput tablet would stretch the point across every monitor of the desktop.
|
||||
if !relative && self.backend==crate::desktop_backend::DesktopBackend::Portal {
|
||||
if let Some(portal)=self.portal.lock().unwrap().as_ref() { return self.portal_result("motion", portal.move_pointer(f64::from(x),f64::from(y),false)); }
|
||||
}
|
||||
// X11 multi-screen: the point is inside the selected monitor; XTest and uinput span the root.
|
||||
let placement=if relative || self.backend!=crate::desktop_backend::DesktopBackend::X11 {None} else {crate::wayland::x11_placement()};
|
||||
let (x,y)=placement.map_or((x,y),|(ox,oy)|(x+ox,y+oy));
|
||||
@@ -352,6 +357,11 @@ impl InputInjector {
|
||||
else if relative { unsafe { x11_mouse_relative(x,y) } } else { unsafe { x11_mouse_move(x,y) } }
|
||||
}
|
||||
fn inject_button(&self,button:i32,pressed:bool)->i32 {
|
||||
// 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.backend==crate::desktop_backend::DesktopBackend::Portal {
|
||||
if let Some(portal)=self.portal.lock().unwrap().as_ref() { return self.portal_result("button", portal.button(button,pressed)); }
|
||||
}
|
||||
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)); }
|
||||
|
||||
+19
@@ -70,6 +70,8 @@ use webrtc::WebRtcSession;
|
||||
/// Set before a normal return when the host must come back in the other mode (signed in / out).
|
||||
static RESTART: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
struct AbortOnDrop(tokio::task::AbortHandle);
|
||||
impl Drop for AbortOnDrop { fn drop(&mut self) { self.0.abort(); } }
|
||||
fn superseded_peer_ids(sessions: &HashMap<String, WebRtcSession>, ice: &str, desktop: bool) -> Vec<String> {
|
||||
sessions.iter().filter(|(id, peer)| id.as_str() == ice || (desktop && peer.desktop))
|
||||
.map(|(id, _)| id.clone()).collect()
|
||||
@@ -713,6 +715,21 @@ async fn serve(mut capture: Arc<ScreenCapture>, input: Arc<InputInjector>, shutd
|
||||
assist: &mut Option<assist::Assist>, commands: &mut mpsc::Receiver<assist::Command>, webrtc_sessions: Arc<Mutex<HashMap<String, WebRtcSession>>>) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let portal_desktop = (capture.backend == desktop_backend::DesktopBackend::Portal && !desktop_backend::headless())
|
||||
.then(|| Arc::new(desktop_session::PortalDesktop::new(capture.clone())));
|
||||
// Stop sharing the screen once no desktop controller is left. Viewers send stop_capture
|
||||
// before leaving and phones reconnect within seconds, so require two idle checks in a row.
|
||||
let idle_watch = portal_desktop.clone().map(|portal| {
|
||||
let sessions = webrtc_sessions.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut idle = 0u8;
|
||||
loop {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
|
||||
if sessions.lock().await.values().any(|s| s.role.is_desktop()) { idle = 0; continue; }
|
||||
idle = idle.saturating_add(1);
|
||||
if idle >= 2 { portal.end_idle(); }
|
||||
}
|
||||
})
|
||||
});
|
||||
let _idle_watch = idle_watch.map(|task| AbortOnDrop(task.abort_handle()));
|
||||
let mut auth = if let Some(session) = assist.as_ref() { session.client.clone() } else {
|
||||
let creds = match config::file().and_then(Credentials::load) {
|
||||
Ok(creds) => creds,
|
||||
@@ -870,6 +887,8 @@ async fn serve(mut capture: Arc<ScreenCapture>, input: Arc<InputInjector>, shutd
|
||||
let mut desktop_ended = false;
|
||||
for id in ended { if let Some(s) = sessions.remove(&id) { desktop_ended |= s.role.is_desktop(); close_peer(&s.pc).await; } }
|
||||
if desktop_ended && !sessions.values().any(|s| s.role.is_desktop()) { if let Some(s) = assist.as_mut() { s.session_ended()?; } }
|
||||
// The controller left: stop sharing now; reconnecting reopens silently with the saved consent.
|
||||
if !sessions.values().any(|s| s.role.is_desktop()) { if let Some(portal) = &portal_desktop { portal.end_idle(); } }
|
||||
if let Some(s) = assist.as_mut() { s.tick()?; }
|
||||
}
|
||||
SignalingEvent::Connected => {
|
||||
|
||||
+125
-19
@@ -38,8 +38,12 @@ mod native {
|
||||
fn uu_portal_move(portal: *mut c_void, x: f64, y: f64, relative: i32) -> i32;
|
||||
fn uu_portal_button(portal: *mut c_void, button: i32, pressed: i32) -> i32;
|
||||
fn uu_portal_key(portal: *mut c_void, keysym: u32, keycode: i32, pressed: i32) -> i32;
|
||||
fn uu_portal_stream_position(portal: *mut c_void, x: *mut i32, y: *mut i32) -> i32;
|
||||
fn uu_portal_monitors(out: *mut libc::c_char, length: usize) -> i32;
|
||||
fn uu_portal_end(portal: *mut c_void);
|
||||
}
|
||||
struct Handle(NonNull<c_void>);
|
||||
fn pack(width: u32, height: u32) -> u64 { (u64::from(width) << 32) | u64::from(height) }
|
||||
// The engine owns callback threads; public calls are serialized by Mutex.
|
||||
unsafe impl Send for Handle {}
|
||||
impl Drop for Handle { fn drop(&mut self) { unsafe { uu_portal_close(self.0.as_ptr()) } } }
|
||||
@@ -84,7 +88,7 @@ mod native {
|
||||
was_locked.store(false, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
}
|
||||
pub struct Session { handle: Mutex<Handle>, locked: tokio::sync::watch::Receiver<Option<bool>>, was_locked: std::sync::atomic::AtomicBool, recovery: Mutex<Recovery>, pub width: u32, pub height: u32 }
|
||||
pub struct Session { handle: Mutex<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>> }
|
||||
impl Session {
|
||||
fn take_lock_observation(&self) -> Result<bool, String> {
|
||||
// A recovery in progress must see the lock even if another capture
|
||||
@@ -99,7 +103,7 @@ mod native {
|
||||
fn check_geometry(&self, replacement: &Self) -> Result<(), super::PortalError> {
|
||||
// Encoder buffers use frame pixels. Logical geometry and EIS regions
|
||||
// belong to the replacement handle and may change with scaling (#25).
|
||||
if (self.width, self.height) != (replacement.width, replacement.height) {
|
||||
if self.size() != replacement.size() {
|
||||
Err(super::PortalError { code: 14 })
|
||||
} else {
|
||||
Ok(())
|
||||
@@ -108,7 +112,9 @@ mod native {
|
||||
pub fn is_alive(&self) -> bool {
|
||||
self.handle.lock().is_ok_and(|handle| unsafe { uu_portal_alive(handle.0.as_ptr()) != 0 })
|
||||
}
|
||||
fn open_inner(cancelled: Option<&std::sync::atomic::AtomicBool>) -> Result<Self, super::PortalError> {
|
||||
/// Opens a session for `monitor` (a Mutter connector) with that monitor's saved consent;
|
||||
/// None means the screen currently selected, or the only monitor.
|
||||
fn open_inner(cancelled: Option<&std::sync::atomic::AtomicBool>, monitor: Option<&str>) -> Result<Self, super::PortalError> {
|
||||
extern "C" fn is_cancelled(data: *mut c_void) -> i32 {
|
||||
let cancelled = unsafe { &*(data as *const std::sync::atomic::AtomicBool) };
|
||||
i32::from(cancelled.load(std::sync::atomic::Ordering::Acquire))
|
||||
@@ -121,16 +127,19 @@ mod native {
|
||||
let (mut error, mut width, mut height) = (0, 0, 0);
|
||||
let directory = super::permissions::directory();
|
||||
let key = super::permissions::desktop_key();
|
||||
let token = directory.as_deref().and_then(|dir| super::permissions::take(dir, key))
|
||||
.and_then(|value| std::ffi::CString::new(value).ok());
|
||||
let mut cache = (directory, key);
|
||||
let wanted = monitor.map(str::to_owned).or_else(crate::wayland::portal_monitor);
|
||||
// Each monitor has its own consent; the desktop-wide key is the single-monitor one.
|
||||
let token = directory.as_deref().and_then(|dir| {
|
||||
wanted.as_deref().and_then(|name| super::permissions::take(dir, &super::permissions::monitor_key(name)))
|
||||
.or_else(|| super::permissions::take(dir, key))
|
||||
}).and_then(|value| std::ffi::CString::new(value).ok());
|
||||
// The new token is saved once the granted monitor is known (after open).
|
||||
let mut cache: Option<String> = None;
|
||||
extern "C" fn save_token(token: *const libc::c_char, data: *mut c_void) {
|
||||
// Callback is synchronous during open; cache lives through the call.
|
||||
let result = std::panic::catch_unwind(|| unsafe {
|
||||
let cache = &*(data as *const (Option<std::path::PathBuf>, &'static str));
|
||||
if let (Some(dir), Ok(value)) = (cache.0.as_deref(), std::ffi::CStr::from_ptr(token).to_str()) {
|
||||
if super::permissions::save(dir, cache.1, value).is_err() { log::warn!("Portal permission cache could not be saved"); }
|
||||
}
|
||||
let cache = &mut *(data as *mut Option<String>);
|
||||
*cache = std::ffi::CStr::from_ptr(token).to_str().ok().map(str::to_owned);
|
||||
});
|
||||
if result.is_err() { log::warn!("Portal permission cache callback failed"); }
|
||||
}
|
||||
@@ -147,16 +156,58 @@ mod native {
|
||||
}
|
||||
};
|
||||
let handle = NonNull::new(pointer).ok_or(super::PortalError { code: error })?;
|
||||
let (mut x, mut y) = (0, 0);
|
||||
let granted = (unsafe { uu_portal_stream_position(handle.as_ptr(), &mut x, &mut y) } == 0)
|
||||
.then(|| crate::wayland::portal_monitor_at(x, y)).flatten();
|
||||
if let (Some(dir), Some(token)) = (directory.as_deref(), cache.take()) {
|
||||
let saved = match &granted {
|
||||
Some(name) => super::permissions::monitor_key(name),
|
||||
None => key.to_owned(),
|
||||
};
|
||||
if super::permissions::save(dir, &saved, &token).is_err() { log::warn!("Portal permission cache could not be saved"); }
|
||||
}
|
||||
if wanted.is_some() && granted != wanted { log::warn!("Portal granted a different monitor than requested"); }
|
||||
// A freshly opened session holds no lock-screen frame: only an observed lock (or a
|
||||
// closed stream) must discard the cached frame. Starting "locked" cleared the first
|
||||
// valid frame, and a static desktop sends no new one, so the viewer stayed black (#2).
|
||||
Ok(Self { handle: Mutex::new(Handle(handle)), locked: crate::session_lock::watch_locked(), was_locked: std::sync::atomic::AtomicBool::new(false), recovery: Mutex::new(Recovery::default()), width, height })
|
||||
Ok(Self { handle: Mutex::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) })
|
||||
}
|
||||
/// Frame pixels of the monitor the stream currently follows.
|
||||
pub fn size(&self) -> (u32, u32) {
|
||||
let packed = self.size.load(std::sync::atomic::Ordering::Acquire);
|
||||
((packed >> 32) as u32, packed as u32)
|
||||
}
|
||||
/// End the compositor session (screen-share indicator off); the next desktop
|
||||
/// connection reopens it with the saved consent.
|
||||
pub fn end(&self) {
|
||||
if let Ok(handle) = self.handle.lock() { unsafe { uu_portal_end(handle.0.as_ptr()) }; }
|
||||
}
|
||||
/// 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()) }
|
||||
/// Capture another monitor: open its own session (silently with saved consent; the first
|
||||
/// 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(()); }
|
||||
let replacement = Self::open_inner(None, Some(connector)).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)
|
||||
};
|
||||
if let Ok(mut monitor) = self.monitor.lock() { *monitor = Some(connector.to_owned()); }
|
||||
drop(previous);
|
||||
Ok(())
|
||||
}
|
||||
pub fn open() -> Result<Self, String> {
|
||||
Self::open_inner(None).map_err(|error| error.to_string())
|
||||
Self::open_inner(None, None).map_err(|error| error.to_string())
|
||||
}
|
||||
pub fn open_cancellable(cancelled: &std::sync::atomic::AtomicBool) -> Result<Self, super::PortalError> {
|
||||
Self::open_inner(Some(cancelled))
|
||||
Self::open_inner(Some(cancelled), None)
|
||||
}
|
||||
pub fn recover(&self, cancelled: &std::sync::atomic::AtomicBool) -> Result<bool, super::PortalError> {
|
||||
use std::sync::atomic::Ordering;
|
||||
@@ -211,7 +262,9 @@ mod native {
|
||||
self.capture_changed(frame, &mut None).map(|_| ())
|
||||
}
|
||||
pub fn capture_changed(&self, frame: &mut [u8], version: &mut Option<super::FrameVersion>) -> Result<bool, String> {
|
||||
if frame.len() != self.width as usize * self.height as usize * 4 { return Err(super::error(11)); }
|
||||
let (width, height) = self.size();
|
||||
// A buffer sized for the previous monitor belongs to an encoder that a switch is replacing.
|
||||
if frame.len() != width as usize * height as usize * 4 { return Ok(blank_changed(frame, version)); }
|
||||
let handle = self.handle.lock().map_err(|_| "Portal session lock poisoned")?;
|
||||
// Drain EIS even on a static desktop so pause/disconnect and sync
|
||||
// events are processed without waiting for remote input.
|
||||
@@ -252,7 +305,7 @@ mod native {
|
||||
self.was_locked.store(true, std::sync::atomic::Ordering::Release);
|
||||
false
|
||||
}) { return Ok(None); }
|
||||
let replacement = match Self::open_inner(None) {
|
||||
let replacement = match Self::open_inner(None, self.monitor().as_deref()) {
|
||||
Ok(value) => value,
|
||||
Err(error) => {
|
||||
log::warn!("Portal capture recovery deferred: {error}");
|
||||
@@ -328,6 +381,14 @@ mod native {
|
||||
}
|
||||
}
|
||||
|
||||
/// Mutter's monitors (GNOME); empty elsewhere.
|
||||
pub fn monitors() -> Vec<super::Monitor> {
|
||||
if crate::engine_plugin::load(crate::engine_plugin::Engine::Portal).is_err() { return Vec::new(); }
|
||||
let mut text = vec![0u8; 8192];
|
||||
if unsafe { uu_portal_monitors(text.as_mut_ptr() as *mut libc::c_char, text.len()) } <= 0 { return Vec::new(); }
|
||||
let end = text.iter().position(|&b| b == 0).unwrap_or(text.len());
|
||||
super::parse_monitors(&String::from_utf8_lossy(&text[..end]))
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -342,8 +403,8 @@ mod native {
|
||||
locked,
|
||||
was_locked: std::sync::atomic::AtomicBool::new(false),
|
||||
recovery: Mutex::new(Recovery::default()),
|
||||
width: physical.0,
|
||||
height: physical.1,
|
||||
size: pack(physical.0, physical.1).into(),
|
||||
monitor: Mutex::new(None),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -605,6 +666,13 @@ pub use native::Session as PortalSession;
|
||||
#[cfg(not(all(target_os = "linux", feature = "portal")))]
|
||||
pub struct PortalSession { pub width: u32, pub height: u32 }
|
||||
#[cfg(not(all(target_os = "linux", feature = "portal")))]
|
||||
impl PortalSession {
|
||||
pub fn size(&self) -> (u32, u32) { (self.width, self.height) }
|
||||
pub fn monitor(&self) -> Option<String> { None }
|
||||
pub fn end(&self) {}
|
||||
pub fn switch_to(&self, _: &str) -> Result<(), String> { Err(error(15)) }
|
||||
}
|
||||
#[cfg(not(all(target_os = "linux", feature = "portal")))]
|
||||
impl PortalSession {
|
||||
pub fn clipboard_supported(&self) -> bool { false }
|
||||
pub fn clipboard_ready(&self) -> bool { false }
|
||||
@@ -628,10 +696,40 @@ impl PortalSession {
|
||||
pub fn key(&self, _: u64, _: bool) -> Result<(), String> { Err(error(15)) }
|
||||
}
|
||||
|
||||
/// The portal session that monitor switches act on: one per host, reused by reconnects.
|
||||
static ACTIVE: std::sync::Mutex<Option<std::sync::Weak<PortalSession>>> = std::sync::Mutex::new(None);
|
||||
pub fn permissions_directory() -> Option<std::path::PathBuf> { permissions::directory() }
|
||||
pub fn monitor_key(connector: &str) -> String { permissions::monitor_key(connector) }
|
||||
pub fn register(session: &Arc<PortalSession>) {
|
||||
*ACTIVE.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::downgrade(session));
|
||||
}
|
||||
pub fn switch_active(connector: &str) -> Result<(), 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.switch_to(connector)
|
||||
}
|
||||
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;
|
||||
#[cfg(not(all(target_os = "linux", feature = "portal")))]
|
||||
pub fn monitors() -> Vec<Monitor> { Vec::new() }
|
||||
/// `connector\twidth\theight\tx\ty\tprimary` lines from the engine.
|
||||
fn parse_monitors(text: &str) -> Vec<Monitor> {
|
||||
text.lines().filter_map(|line| {
|
||||
let mut f = line.split('\t');
|
||||
let connector = f.next()?.to_owned();
|
||||
let (width, height) = (f.next()?.parse().ok()?, f.next()?.parse().ok()?);
|
||||
let (x, y, primary) = (f.next()?.parse().ok()?, f.next()?.parse().ok()?, f.next()? == "1");
|
||||
(!connector.is_empty() && connector.len() <= 64 && connector.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))
|
||||
.then_some(Monitor { connector, width, height, x, y, primary })
|
||||
}).collect()
|
||||
}
|
||||
|
||||
/// Forward frames in-process into encoder stdin. Cancellation drops the Arc;
|
||||
/// the caller keeps one owning Arc for all subsequent desktop reconnects.
|
||||
pub fn write_frames(session: Arc<PortalSession>, mut output: impl std::io::Write, cancelled: &std::sync::atomic::AtomicBool) -> Result<(), String> {
|
||||
let length = (session.width as usize).checked_mul(session.height as usize).and_then(|n| n.checked_mul(4)).ok_or("Portal frame too large")?;
|
||||
let (width, height) = session.size();
|
||||
let length = (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(4)).ok_or("Portal frame too large")?;
|
||||
let mut frame = vec![0; length];
|
||||
let interval = std::time::Duration::from_nanos(1_000_000_000 / crate::video::FPS);
|
||||
while !cancelled.load(std::sync::atomic::Ordering::Acquire) {
|
||||
@@ -645,13 +743,21 @@ pub fn write_frames(session: Arc<PortalSession>, mut output: impl std::io::Write
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn monitor_lines_parse_and_reject_unsafe_connectors() {
|
||||
let m = super::parse_monitors("eDP-1\t2880\t1800\t0\t0\t1\nHDMI-1\t2560\t1440\t1920\t0\t0\n../x\t1\t1\t0\t0\t0\n");
|
||||
assert_eq!(m.len(), 2);
|
||||
assert!(m[0].primary && m[0].connector == "eDP-1" && (m[1].width, m[1].x) == (2560, 1920));
|
||||
}
|
||||
#[test]
|
||||
fn locked_frames_hide_old_content() { let mut frame = [42; 8]; super::blank(&mut frame); assert_eq!(frame, [0,0,0,255,0,0,0,255]); }
|
||||
#[test]
|
||||
fn errors_never_include_remote_messages_or_identifiers() {
|
||||
assert!(super::check(4).unwrap_err().contains("cancelled or denied"));
|
||||
assert!(super::check(9).unwrap_err().contains("closed or stream lost"));
|
||||
assert!(super::check(15).unwrap_err().contains("--features wayland,portal"));
|
||||
// Portal builds name the missing runtime engine; other builds say how to get one.
|
||||
let unavailable = super::check(15).unwrap_err();
|
||||
assert!(unavailable.contains("--features wayland,portal") || (cfg!(feature = "portal") && unavailable.contains("engine unavailable")));
|
||||
}
|
||||
#[test]
|
||||
fn portal_error_display_is_fixed_and_sanitized() {
|
||||
|
||||
@@ -23,6 +23,9 @@ pub fn desktop_key() -> &'static str {
|
||||
if desktop.split(':').any(|v| v == "kde") { "kde" } else { "gnome" }
|
||||
}
|
||||
|
||||
/// Consent for one monitor (Mutter connector); connectors are checked to be file-name safe.
|
||||
pub fn monitor_key(connector: &str) -> String { format!("{}@{}", desktop_key(), connector) }
|
||||
|
||||
pub fn take(dir: &Path, key: &str) -> Option<String> {
|
||||
let path = dir.join(key);
|
||||
let mut file = OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW).open(&path).ok()?;
|
||||
|
||||
+4
-2
@@ -816,7 +816,8 @@ async fn read_encoder_with(
|
||||
selection: crate::video_select::Selection,
|
||||
)->Result<(),String>{
|
||||
let selected_output=crate::wayland::capture_source(&display,portal.is_some(),settings.source_id);
|
||||
let size=selected_output.map_or(size,|s|(s.width,s.height));
|
||||
// Portal frames come from the session's current monitor, whatever the advertised mode says.
|
||||
let size=portal.as_ref().map(|p|p.size()).or(selected_output.map(|s|(s.width,s.height))).unwrap_or(size);
|
||||
let kms=display.starts_with("kms:");
|
||||
let wayland=kms || display.starts_with("wayland:");
|
||||
// X11 multi-screen: x11grab reads only the selected monitor's region of the root.
|
||||
@@ -929,7 +930,8 @@ async fn read_encoder_with(
|
||||
let interval=Duration::from_nanos(1_000_000_000/u64::from(settings.fps));
|
||||
let mut tick=tokio::time::interval(interval);
|
||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let mut frame=vec![0;(session.width as usize)*(session.height as usize)*4];
|
||||
let (width,height)=session.size();
|
||||
let mut frame=vec![0;(width as usize)*(height as usize)*4];
|
||||
let mut version=None;
|
||||
loop {
|
||||
tick.tick().await;
|
||||
|
||||
+41
-4
@@ -210,7 +210,7 @@ pub fn text_probe()->Result<(),String> {
|
||||
// root to the selected monitor. No compositor layout or user credentials are modified.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Output { pub name:String, pub width:u32, pub height:u32, pub fps:i32, pub x:i32, pub y:i32 }
|
||||
struct Inventory { outputs:Vec<Output>, x11:bool }
|
||||
struct Inventory { outputs:Vec<Output>, x11:bool, portal:bool }
|
||||
static OUTPUTS: std::sync::OnceLock<Inventory> = std::sync::OnceLock::new();
|
||||
#[derive(Default)]
|
||||
struct Selection { id:usize, generation:u64, presented:Option<u64>, failed:bool }
|
||||
@@ -230,11 +230,15 @@ fn inventory() -> &'static Inventory {
|
||||
if backend==Some(crate::desktop_backend::DesktopBackend::X11) && !crate::desktop_backend::headless()
|
||||
&& std::env::var("UU_X11_MULTISCREEN").ok().as_deref()==Some("1") {
|
||||
let outputs=x11_outputs();
|
||||
return Inventory {x11:!outputs.is_empty(),outputs};
|
||||
return Inventory {x11:!outputs.is_empty(),outputs,portal:false};
|
||||
}
|
||||
if backend==Some(crate::desktop_backend::DesktopBackend::Portal) && !crate::desktop_backend::headless() {
|
||||
let outputs=portal_outputs();
|
||||
return Inventory {portal:!outputs.is_empty(),outputs,x11:false};
|
||||
}
|
||||
if !cfg!(all(target_os="linux",feature="wayland"))
|
||||
|| std::env::var("UU_WAYLAND_MULTISCREEN").ok().as_deref()!=Some("1")
|
||||
|| backend!=Some(crate::desktop_backend::DesktopBackend::Wayland) {return Inventory {outputs:Vec::new(),x11:false};}
|
||||
|| backend!=Some(crate::desktop_backend::DesktopBackend::Wayland) {return Inventory {outputs:Vec::new(),x11:false,portal:false};}
|
||||
let niri=std::env::var_os("NIRI_SOCKET").is_some();
|
||||
let output=if niri {std::process::Command::new("niri").args(["msg","--json","outputs"]).output()}
|
||||
else {std::process::Command::new("hyprctl").args(["monitors","-j"]).output()};
|
||||
@@ -244,10 +248,36 @@ fn inventory() -> &'static Inventory {
|
||||
if niri {parse_niri_outputs(&output.stdout,&preferred)} else {parse_outputs(&output.stdout,&preferred)}
|
||||
});
|
||||
let outputs=match result {Ok(outputs)=>outputs,Err(reason)=>{log::warn!("Wayland multi-screen disabled: {}",reason);Vec::new()}};
|
||||
Inventory {outputs,x11:false}
|
||||
Inventory {outputs,x11:false,portal:false}
|
||||
})
|
||||
}
|
||||
pub fn outputs() -> &'static [Output] {&inventory().outputs}
|
||||
/// GNOME portal grants one monitor per consent (multi-select is refused), so each monitor
|
||||
/// gets its own saved consent and a switch opens that monitor's session. Read once.
|
||||
fn portal_outputs()->Vec<Output> {
|
||||
let monitors=crate::portal::monitors();
|
||||
if monitors.len()<2 {return Vec::new();}
|
||||
let fps=crate::video::display_fps() as i32;
|
||||
let mut outputs:Vec<Output>=monitors.iter().map(|m|Output {name:m.connector.clone(),width:m.width,height:m.height,fps,x:m.x,y:m.y}).collect();
|
||||
// Screen 0 is the one opened first: the monitor whose consent is already saved, else the primary.
|
||||
let dir=crate::portal::permissions_directory();
|
||||
let granted=|name:&str|dir.as_deref().is_some_and(|d|d.join(crate::portal::monitor_key(name)).exists());
|
||||
let primary=monitors.iter().find(|m|m.primary).map(|m|m.connector.clone()).unwrap_or_default();
|
||||
outputs.sort_by_key(|o|(!granted(&o.name),o.name!=primary,o.x,o.y));
|
||||
outputs.truncate(16);
|
||||
log::info!("Portal multi-screen: {} monitors",outputs.len());
|
||||
outputs
|
||||
}
|
||||
/// Connector of the selected screen when the portal advertises several monitors.
|
||||
pub fn portal_monitor()->Option<String> {
|
||||
if !inventory().portal {return None;}
|
||||
source(selected()).map(|o|o.name.clone())
|
||||
}
|
||||
/// Monitor at a portal stream's logical position (Mutter logical layout).
|
||||
pub fn portal_monitor_at(x:i32,y:i32)->Option<String> {
|
||||
if !inventory().portal {return None;}
|
||||
outputs().iter().find(|o|(o.x,o.y)==(x,y)).map(|o|o.name.clone())
|
||||
}
|
||||
/// X11 monitors are advertised: the stream captures the selected monitor's region of the root.
|
||||
pub fn x11_multiscreen()->bool {inventory().x11}
|
||||
/// Read once, like the Hyprland inventory: a changed monitor layout needs a host restart.
|
||||
@@ -371,6 +401,13 @@ pub fn failed(id:usize,generation:u64) {
|
||||
}
|
||||
pub fn select(id:usize)->Result<(),String> {
|
||||
let output=source(id).ok_or("Unknown screen")?;
|
||||
if inventory().portal {
|
||||
let mut state=SELECTION.lock().unwrap();
|
||||
crate::portal::switch_active(&output.name)?;
|
||||
state.begin(id);
|
||||
log::info!("Portal screen selected: id={} source={}x{}",id,output.width,output.height);
|
||||
return Ok(());
|
||||
}
|
||||
if x11_multiscreen() {
|
||||
SELECTION.lock().unwrap().begin(id);
|
||||
log::info!("X11 screen selected: id={} source={}x{}+{}+{}",id,output.width,output.height,output.x,output.y);
|
||||
|
||||
Reference in new issue
Block a user