feat(capture): support consented multi-monitor desktops with recovery (#32)
This commit is contained in:
1 parent
6d0e733cd7
commit
98af6fce28
19 files changed
+2175
-271
No files matched your search
+27
-5
@@ -156,25 +156,48 @@ pub fn serve() -> Result<()> {
|
||||
let backend_handle = backend.clone();
|
||||
let addr = format!("127.0.0.1:{}", config.bridge_port);
|
||||
let listener = TcpListener::bind(&addr).with_context(|| format!("binding {addr}"))?;
|
||||
listener.set_nonblocking(true)?;
|
||||
println!("{}", t!("bridge.listening", port = config.bridge_port));
|
||||
|
||||
// The service process hooks itself too, so multiple authenticated
|
||||
// connections coexist; each gets its own thread. Injection is
|
||||
// serialized through the single backend.
|
||||
for stream in listener.incoming() {
|
||||
let stream = match stream {
|
||||
Ok(s) => s,
|
||||
Err(_) => continue,
|
||||
loop {
|
||||
backend.lock().unwrap().backend.check_health()?;
|
||||
let stream = match listener.accept() {
|
||||
Ok((stream, _)) => stream,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
thread::sleep(std::time::Duration::from_millis(50));
|
||||
continue;
|
||||
}
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::Interrupted | std::io::ErrorKind::ConnectionAborted
|
||||
) =>
|
||||
{
|
||||
continue
|
||||
}
|
||||
Err(error) => return Err(error).context("accepting hook connection"),
|
||||
};
|
||||
let config = config.clone();
|
||||
let backend_handle = backend_handle.clone();
|
||||
thread::spawn(move || {
|
||||
let mut stream = stream;
|
||||
if stream
|
||||
.set_read_timeout(Some(std::time::Duration::from_secs(5)))
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
match authenticate(&mut stream, &config) {
|
||||
Ok(true) => {}
|
||||
Ok(false) => return,
|
||||
Err(_) => return,
|
||||
}
|
||||
if stream.set_read_timeout(None).is_err() {
|
||||
return;
|
||||
}
|
||||
use input::InputBackend;
|
||||
// Read sockets without holding the shared desktop input lock.
|
||||
let mut connection = ConnectionInput {
|
||||
@@ -199,7 +222,6 @@ pub fn serve() -> Result<()> {
|
||||
let _ = connection.release_all();
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn authenticate(stream: &mut TcpStream, config: &Config) -> Result<bool> {
|
||||
|
||||
+137
-28
@@ -1,9 +1,9 @@
|
||||
//! Portal side of the capture path.
|
||||
//!
|
||||
//! Negotiates an xdg-desktop-portal ScreenCast session, obtains a private
|
||||
//! PipeWire file descriptor and the video node id, then hands both to the
|
||||
//! C capture helper (`uur-pw-capture`) which runs the PipeWire stream and
|
||||
//! publishes frames into a private XDG runtime file (see
|
||||
//! PipeWire file descriptor and the consented video nodes, then hands them to
|
||||
//! the C capture helper (`uur-pw-capture`) which runs the PipeWire streams and
|
||||
//! composites their frames into a private XDG runtime file (see
|
||||
//! docs/capture-protocol.md).
|
||||
//!
|
||||
//! Consent: the first run shows the compositor's share dialog once. The
|
||||
@@ -25,17 +25,28 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use crate::config::Config;
|
||||
|
||||
const FRAME_PROTOCOL_VERSION: u32 = 3;
|
||||
|
||||
type PortalSession =
|
||||
ashpd::desktop::Session<'static, ashpd::desktop::screencast::Screencast<'static>>;
|
||||
|
||||
struct PortalCapture {
|
||||
fd: OwnedFd,
|
||||
node: u32,
|
||||
streams: Vec<CaptureStream>,
|
||||
restore_token: Option<String>,
|
||||
session: PortalSession,
|
||||
closed: zbus::proxy::SignalStream<'static>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct CaptureStream {
|
||||
pub(crate) node: u32,
|
||||
pub(crate) x: i32,
|
||||
pub(crate) y: i32,
|
||||
pub(crate) width: u32,
|
||||
pub(crate) height: u32,
|
||||
}
|
||||
|
||||
/// Run the capture path until interrupted.
|
||||
pub fn run_standalone() -> Result<()> {
|
||||
// Public capture uses the same lifecycle lock as run/setup so stop and
|
||||
@@ -93,13 +104,13 @@ pub fn run() -> Result<()> {
|
||||
};
|
||||
let PortalCapture {
|
||||
fd: pw_fd,
|
||||
node,
|
||||
streams,
|
||||
session,
|
||||
mut closed,
|
||||
..
|
||||
} = match opened {
|
||||
Ok(opened) => opened,
|
||||
Err(error) if !initial_session && failures < 3 => {
|
||||
Err(error) if !initial_session && failures < 3 && !user_cancelled(&error) => {
|
||||
failures += 1;
|
||||
eprintln!("capture reconnect {failures}/3 failed: {error:#}");
|
||||
tokio::select! {
|
||||
@@ -110,13 +121,18 @@ pub fn run() -> Result<()> {
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
initial_session = false;
|
||||
println!("{}", t!("capture.session_ready", node = node));
|
||||
let nodes = streams
|
||||
.iter()
|
||||
.map(|stream| stream.node.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
println!("{}", t!("capture.session_ready", node = nodes));
|
||||
match std::fs::remove_file(&frames) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error).context("retiring the previous capture transport"),
|
||||
}
|
||||
let mut helper = CaptureHelper(spawn_helper(pw_fd, node)?);
|
||||
let mut helper = CaptureHelper(spawn_capture_helper(pw_fd, &streams)?);
|
||||
let mut healthy_since = None;
|
||||
let mut portal_closed = false;
|
||||
let mut reconfigure = false;
|
||||
@@ -143,6 +159,10 @@ pub fn run() -> Result<()> {
|
||||
if has_frame(&frames) && healthy_since.is_none() {
|
||||
healthy_since = Some(Instant::now());
|
||||
}
|
||||
if helper_stalled(&frames) {
|
||||
eprintln!("capture helper heartbeat expired; reconnecting");
|
||||
break None;
|
||||
}
|
||||
if let Some(status) = helper.0.try_wait()
|
||||
.context("waiting for capture helper")? {
|
||||
break Some(status);
|
||||
@@ -175,14 +195,16 @@ pub fn run() -> Result<()> {
|
||||
"capture recovery failed repeatedly; restart uur run to share again"
|
||||
);
|
||||
}
|
||||
let status = status.context("capture helper stopped without an exit status")?;
|
||||
if !matches!(status.code(), Some(0 | 75) | None) {
|
||||
if status
|
||||
.as_ref()
|
||||
.is_some_and(|status| !matches!(status.code(), Some(0 | 75) | None))
|
||||
{
|
||||
anyhow::bail!(
|
||||
"{} ({status}); capture recovery stopped",
|
||||
"{} ({status:?}); capture recovery stopped",
|
||||
t!("capture.helper_failed")
|
||||
);
|
||||
}
|
||||
eprintln!("capture stream interrupted ({status}); reconnecting {failures}/3");
|
||||
eprintln!("capture stream interrupted ({status:?}); reconnecting {failures}/3");
|
||||
}
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(Duration::from_secs(1)) => {},
|
||||
@@ -206,7 +228,7 @@ pub fn run() -> Result<()> {
|
||||
})
|
||||
}
|
||||
|
||||
async fn watch_display_changes() -> Option<zbus::proxy::SignalStream<'static>> {
|
||||
pub(crate) async fn watch_display_changes() -> Option<zbus::proxy::SignalStream<'static>> {
|
||||
let connection = zbus::Connection::session().await.ok()?;
|
||||
let bus = zbus::fdo::DBusProxy::new(&connection).await.ok()?;
|
||||
let name = "org.gnome.Mutter.DisplayConfig".try_into().ok()?;
|
||||
@@ -225,7 +247,7 @@ async fn watch_display_changes() -> Option<zbus::proxy::SignalStream<'static>> {
|
||||
proxy.receive_signal("MonitorsChanged").await.ok()
|
||||
}
|
||||
|
||||
async fn next_display_change(changes: &mut Option<zbus::proxy::SignalStream<'static>>) {
|
||||
pub(crate) async fn next_display_change(changes: &mut Option<zbus::proxy::SignalStream<'static>>) {
|
||||
loop {
|
||||
match changes.as_mut() {
|
||||
Some(stream) => {
|
||||
@@ -245,7 +267,7 @@ async fn wait_for_stop(stopping: &AtomicBool) {
|
||||
}
|
||||
}
|
||||
|
||||
struct CaptureHelper(Child);
|
||||
pub(crate) struct CaptureHelper(pub(crate) Child);
|
||||
|
||||
impl Drop for CaptureHelper {
|
||||
fn drop(&mut self) {
|
||||
@@ -276,17 +298,48 @@ pub(crate) fn has_frame(path: &Path) -> bool {
|
||||
}
|
||||
let field = |offset| u32::from_le_bytes(header[offset..offset + 4].try_into().unwrap());
|
||||
field(0) == 0x4652_5555
|
||||
&& field(4) == 1
|
||||
&& field(4) == FRAME_PROTOCOL_VERSION
|
||||
&& field(8) > 0
|
||||
&& field(12) > 0
|
||||
&& field(16) >= field(8).saturating_mul(4)
|
||||
&& field(20) == 1
|
||||
&& (1..=16).contains(&field(36))
|
||||
&& u64::from_le_bytes(header[24..32].try_into().unwrap()) > 0
|
||||
}
|
||||
|
||||
/// The producer heartbeat advances even when the desktop is static. A zero
|
||||
/// value belongs to a producer without heartbeat support, never a stale frame.
|
||||
pub(crate) fn helper_stalled(path: &Path) -> bool {
|
||||
let mut header = [0u8; 48];
|
||||
let Ok(mut file) = std::fs::File::open(path) else {
|
||||
return false;
|
||||
};
|
||||
if file.read_exact(&mut header).is_err()
|
||||
|| u32::from_le_bytes(header[4..8].try_into().unwrap()) != FRAME_PROTOCOL_VERSION
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let heartbeat = u64::from_le_bytes(header[40..48].try_into().unwrap());
|
||||
let mut now: libc::timespec = unsafe { std::mem::zeroed() };
|
||||
if heartbeat == 0 || unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now) } != 0 {
|
||||
return false;
|
||||
}
|
||||
let milliseconds = (now.tv_sec as u64).saturating_mul(1000) + now.tv_nsec as u64 / 1_000_000;
|
||||
milliseconds.saturating_sub(heartbeat) > 10_000
|
||||
}
|
||||
|
||||
/// Start the native PipeWire consumer with a portal-owned descriptor. The
|
||||
/// descriptor remains private to the child and is never reopened by path.
|
||||
pub(crate) fn spawn_helper(pw_fd: OwnedFd, node: u32) -> Result<Child> {
|
||||
pub(crate) fn spawn_helper(pw_fd: OwnedFd, streams: &[CaptureStream]) -> Result<Child> {
|
||||
spawn_capture_helper(pw_fd, streams)
|
||||
}
|
||||
|
||||
fn spawn_capture_helper(pw_fd: OwnedFd, streams: &[CaptureStream]) -> Result<Child> {
|
||||
anyhow::ensure!(!streams.is_empty(), "ScreenCast returned no streams");
|
||||
anyhow::ensure!(
|
||||
streams.len() <= 16,
|
||||
"too many ScreenCast streams (maximum 16)"
|
||||
);
|
||||
// The helper inherits this descriptor: strip close-on-exec and keep the
|
||||
// OwnedFd alive across the spawn (closing it would invalidate the number
|
||||
// the child receives).
|
||||
@@ -303,9 +356,19 @@ pub(crate) fn spawn_helper(pw_fd: OwnedFd, node: u32) -> Result<Child> {
|
||||
|
||||
let helper = find_helper("uur-pw-capture")?;
|
||||
let mut command = Command::new(&helper);
|
||||
let stream_specs = streams
|
||||
.iter()
|
||||
.map(|stream| {
|
||||
format!(
|
||||
"{},{},{},{},{}",
|
||||
stream.node, stream.x, stream.y, stream.width, stream.height
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(";");
|
||||
command
|
||||
.env("UUR_PW_FD", raw.to_string())
|
||||
.env("UUR_PW_NODE", node.to_string())
|
||||
.env("UUR_PW_STREAMS", stream_specs)
|
||||
.env("UUR_FRAME_PATH", frame_path()?);
|
||||
if let Ok(debug) = std::env::var("UUR_PW_DEBUG") {
|
||||
command.env("PIPEWIRE_DEBUG", debug);
|
||||
@@ -316,14 +379,14 @@ pub(crate) fn spawn_helper(pw_fd: OwnedFd, node: u32) -> Result<Child> {
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
fn frame_path() -> Result<PathBuf> {
|
||||
pub(crate) fn frame_path() -> Result<PathBuf> {
|
||||
if let Some(path) = std::env::var_os("UUR_FRAME_PATH") {
|
||||
return Ok(PathBuf::from(path));
|
||||
}
|
||||
Ok(crate::config::runtime_dir()?.join("frames.v1"))
|
||||
Ok(crate::config::runtime_dir()?.join("frames.v3"))
|
||||
}
|
||||
|
||||
/// Open the portal session and return (inherited fd number, node id).
|
||||
/// Open the portal session and return its PipeWire streams and node ids.
|
||||
/// First attempt reuses the stored restore token; if that fails (stale
|
||||
/// token, monitor changed, compositor restart) fall back to one
|
||||
/// interactive attempt and store the fresh token.
|
||||
@@ -341,15 +404,33 @@ async fn portal_session(config: &mut Config, interactive: bool) -> Result<Portal
|
||||
.into_iter()
|
||||
.chain(interactive.then_some(None))
|
||||
{
|
||||
match negotiate(&screencast, source, token.as_deref()).await {
|
||||
match negotiate(
|
||||
&screencast,
|
||||
source,
|
||||
config.capture_multiple,
|
||||
token.as_deref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(capture) => {
|
||||
if capture.restore_token != saved_token {
|
||||
config.capture_restore_token = capture.restore_token.clone();
|
||||
config.store().context("storing the new restore token")?;
|
||||
Config::update(|stored| {
|
||||
if stored.capture_source == config.capture_source
|
||||
&& stored.capture_multiple == config.capture_multiple
|
||||
&& stored.capture_backend == config.capture_backend
|
||||
{
|
||||
stored.capture_restore_token = capture.restore_token.clone();
|
||||
}
|
||||
})
|
||||
.context("storing the new restore token")?;
|
||||
}
|
||||
return Ok(capture);
|
||||
}
|
||||
Err(error) => {
|
||||
if user_cancelled(&error) {
|
||||
return Err(error);
|
||||
}
|
||||
last_error = Some(error);
|
||||
}
|
||||
}
|
||||
@@ -359,6 +440,20 @@ async fn portal_session(config: &mut Config, interactive: bool) -> Result<Portal
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn user_cancelled(error: &anyhow::Error) -> bool {
|
||||
error.chain().any(|source| {
|
||||
matches!(
|
||||
source.downcast_ref::<ashpd::Error>(),
|
||||
Some(ashpd::Error::Response(
|
||||
ashpd::desktop::ResponseError::Cancelled
|
||||
))
|
||||
) || matches!(
|
||||
source.downcast_ref::<ashpd::desktop::ResponseError>(),
|
||||
Some(ashpd::desktop::ResponseError::Cancelled)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Choose a cursor mode from the flags the portal advertises.
|
||||
///
|
||||
/// `Embedded` is what the capture path wants (the hook composites the cursor
|
||||
@@ -412,6 +507,7 @@ pub(crate) async fn preferred_cursor_mode(
|
||||
async fn negotiate(
|
||||
screencast: &ashpd::desktop::screencast::Screencast<'static>,
|
||||
source: ashpd::desktop::screencast::SourceType,
|
||||
multiple: bool,
|
||||
restore_token: Option<&str>,
|
||||
) -> Result<PortalCapture> {
|
||||
use ashpd::desktop::PersistMode;
|
||||
@@ -440,7 +536,7 @@ async fn negotiate(
|
||||
&session,
|
||||
cursor_mode,
|
||||
source.into(),
|
||||
false,
|
||||
multiple && matches!(source, ashpd::desktop::screencast::SourceType::Monitor),
|
||||
restore_token,
|
||||
PersistMode::ExplicitlyRevoked,
|
||||
)
|
||||
@@ -449,9 +545,22 @@ async fn negotiate(
|
||||
|
||||
let response = screencast.start(&session, None).await?;
|
||||
let streams_response = response.response()?;
|
||||
let streams = streams_response.streams();
|
||||
let stream = streams.first().context("no monitor selected")?;
|
||||
let node = stream.pipe_wire_node_id();
|
||||
let streams = streams_response
|
||||
.streams()
|
||||
.iter()
|
||||
.map(|stream| {
|
||||
let (x, y) = stream.position().unwrap_or((i32::MIN, i32::MIN));
|
||||
let (width, height) = stream.size().unwrap_or((0, 0));
|
||||
CaptureStream {
|
||||
node: stream.pipe_wire_node_id(),
|
||||
x,
|
||||
y,
|
||||
width: u32::try_from(width).unwrap_or(0),
|
||||
height: u32::try_from(height).unwrap_or(0),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
anyhow::ensure!(!streams.is_empty(), "no monitor selected");
|
||||
let fresh_token = streams_response.restore_token().map(String::from);
|
||||
|
||||
let fd = screencast
|
||||
@@ -460,7 +569,7 @@ async fn negotiate(
|
||||
.context("opening the PipeWire remote")?;
|
||||
Ok(PortalCapture {
|
||||
fd,
|
||||
node,
|
||||
streams,
|
||||
restore_token: fresh_token,
|
||||
session,
|
||||
closed,
|
||||
|
||||
+101
-13
@@ -1,6 +1,10 @@
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io::Write;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Persistent user configuration. Everything lives under the XDG state and
|
||||
/// config directories; the managed Wine prefix lives under data.
|
||||
@@ -24,6 +28,8 @@ pub struct Config {
|
||||
pub remote_desktop_restore_token: Option<String>,
|
||||
/// Portal source type: monitor, window, or virtual.
|
||||
pub capture_source: String,
|
||||
/// Multiple consented monitors are opt-in; existing grants stay intact.
|
||||
pub capture_multiple: bool,
|
||||
/// "portal" uses system consent; "wayland" is explicitly enabled direct monitor capture.
|
||||
pub capture_backend: String,
|
||||
/// Named Wayland output for direct capture; a single-output session needs no name.
|
||||
@@ -49,6 +55,7 @@ impl Default for Config {
|
||||
capture_restore_token: None,
|
||||
remote_desktop_restore_token: None,
|
||||
capture_source: "monitor".into(),
|
||||
capture_multiple: false,
|
||||
capture_backend: "portal".into(),
|
||||
capture_output: None,
|
||||
strip_lock_mods: Some("auto".into()),
|
||||
@@ -125,24 +132,104 @@ pub fn runtime_dir() -> Result<PathBuf> {
|
||||
impl Config {
|
||||
pub fn load() -> Result<Self> {
|
||||
let path = config_path()?;
|
||||
if !path.exists() {
|
||||
let config = Self::default();
|
||||
config.store()?;
|
||||
return Ok(config);
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(raw) => toml::from_str(&raw).context("parsing config.toml"),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Self::update(|_| {}),
|
||||
Err(error) => Err(error).with_context(|| format!("reading {}", path.display())),
|
||||
}
|
||||
let raw = std::fs::read_to_string(&path)
|
||||
.with_context(|| format!("reading {}", path.display()))?;
|
||||
toml::from_str(&raw).context("parsing config.toml")
|
||||
}
|
||||
|
||||
pub fn store(&self) -> Result<()> {
|
||||
let path = config_path()?;
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.with_context(|| format!("creating {}", parent.display()))?;
|
||||
let (path, _lock) = Self::write_lock()?;
|
||||
self.store_locked(&path)
|
||||
}
|
||||
|
||||
/// Serialize read/modify/write across the capture, input and frontend
|
||||
/// processes. Background token saves must not overwrite other fields.
|
||||
pub fn update(change: impl FnOnce(&mut Self)) -> Result<Self> {
|
||||
let (path, _lock) = Self::write_lock()?;
|
||||
let mut config = match std::fs::read_to_string(&path) {
|
||||
Ok(raw) => toml::from_str(&raw).context("parsing config.toml")?,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Self::default(),
|
||||
Err(error) => return Err(error).context("reading configuration for update"),
|
||||
};
|
||||
change(&mut config);
|
||||
config.store_locked(&path)?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
fn write_lock() -> Result<(PathBuf, std::fs::File)> {
|
||||
let mut path = config_path()?;
|
||||
// Do not replace a user-created symlink to declarative configuration.
|
||||
if std::fs::symlink_metadata(&path).is_ok_and(|meta| meta.file_type().is_symlink()) {
|
||||
path = std::fs::canonicalize(&path).context("resolving configuration symlink")?;
|
||||
}
|
||||
std::fs::write(&path, toml::to_string_pretty(self)?)
|
||||
.with_context(|| format!("writing {}", path.display()))
|
||||
let parent = path.parent().context("configuration has no parent")?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let lock = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.write(true)
|
||||
.mode(0o600)
|
||||
.open(path.with_extension("toml.lock"))?;
|
||||
loop {
|
||||
if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX) } == 0 {
|
||||
break;
|
||||
}
|
||||
let error = std::io::Error::last_os_error();
|
||||
if error.kind() != std::io::ErrorKind::Interrupted {
|
||||
return Err(error).context("locking configuration");
|
||||
}
|
||||
}
|
||||
Ok((path, lock))
|
||||
}
|
||||
|
||||
fn store_locked(&self, path: &std::path::Path) -> Result<()> {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let parent = path.parent().context("configuration has no parent")?;
|
||||
let mut document = match std::fs::read_to_string(path) {
|
||||
Ok(raw) => {
|
||||
toml::from_str::<toml::Table>(&raw).context("parsing existing configuration")?
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => toml::Table::new(),
|
||||
Err(error) => return Err(error).context("reading existing configuration"),
|
||||
};
|
||||
// Keep keys belonging to newer versions. JSON includes None fields,
|
||||
// allowing explicitly cleared optional fields to remove old values.
|
||||
for name in serde_json::to_value(self)?.as_object().unwrap().keys() {
|
||||
document.remove(name);
|
||||
}
|
||||
document.extend(toml::Value::try_from(self)?.as_table().unwrap().clone());
|
||||
let text = toml::to_string_pretty(&document)?;
|
||||
for _ in 0..32 {
|
||||
let temporary = parent.join(format!(
|
||||
".uur-config-{}-{}.tmp",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let mut file = match std::fs::OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.mode(0o600)
|
||||
.open(&temporary)
|
||||
{
|
||||
Ok(file) => file,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error).context("creating configuration temporary file"),
|
||||
};
|
||||
let result = (|| -> Result<()> {
|
||||
file.write_all(text.as_bytes())?;
|
||||
file.sync_all()?;
|
||||
std::fs::rename(&temporary, path)?;
|
||||
std::fs::File::open(parent)?.sync_all()?;
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
}
|
||||
return result.with_context(|| format!("writing {}", path.display()));
|
||||
}
|
||||
anyhow::bail!("could not create a configuration temporary file")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,5 +260,6 @@ input_backend = "auto"
|
||||
assert!(config.remote_desktop_restore_token.is_none());
|
||||
assert!(config.capture_restore_token.is_none());
|
||||
assert_eq!(config.capture_source, "monitor");
|
||||
assert!(!config.capture_multiple);
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -374,12 +374,13 @@ pub fn report() -> Result<()> {
|
||||
"info",
|
||||
"capture backend",
|
||||
&format!(
|
||||
"{} ({})",
|
||||
"{} ({}; multiple={})",
|
||||
configured.capture_backend,
|
||||
configured
|
||||
.capture_output
|
||||
.as_deref()
|
||||
.unwrap_or("selected/default output")
|
||||
.unwrap_or("selected/default output"),
|
||||
configured.capture_multiple
|
||||
),
|
||||
);
|
||||
let mut preferred = std::env::var("UUR_INPUT_BACKEND").unwrap_or(configured.input_backend);
|
||||
|
||||
@@ -7,6 +7,9 @@ use anyhow::Result;
|
||||
/// A desktop input sink. Records arrive already normalized by `protocol`.
|
||||
pub trait InputBackend: Send {
|
||||
fn name(&self) -> &'static str;
|
||||
fn check_health(&self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn key(&mut self, vkey: u16, down: bool) -> Result<()>;
|
||||
fn button(&mut self, button: u16, down: bool) -> Result<()>;
|
||||
|
||||
+386
-43
@@ -2,11 +2,13 @@ use anyhow::{anyhow, Context, Result};
|
||||
use ashpd::desktop::remote_desktop::{Axis, DeviceType, KeyState, RemoteDesktop};
|
||||
use ashpd::desktop::screencast::Screencast;
|
||||
use ashpd::desktop::PersistMode;
|
||||
use futures::StreamExt;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{self, SyncSender};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
|
||||
|
||||
use super::InputBackend;
|
||||
@@ -28,15 +30,103 @@ struct Motion {
|
||||
y: f64,
|
||||
}
|
||||
|
||||
struct CaptureGuard(std::process::Child);
|
||||
|
||||
impl Drop for CaptureGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
/// Select a consented stream in the same logical layout used by the compositor.
|
||||
/// A point in a monitor gap is clamped to the closest selected monitor.
|
||||
fn absolute_target(
|
||||
streams: &[crate::capture::CaptureStream],
|
||||
x: f64,
|
||||
y: f64,
|
||||
) -> Result<(u32, f64, f64)> {
|
||||
anyhow::ensure!(
|
||||
x.is_finite() && y.is_finite(),
|
||||
"invalid absolute pointer position"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
!streams.is_empty() && streams.len() <= 16,
|
||||
"invalid input stream count"
|
||||
);
|
||||
let mut streams = streams.to_vec();
|
||||
if streams
|
||||
.iter()
|
||||
.any(|stream| stream.width == 0 || stream.height == 0)
|
||||
{
|
||||
use std::io::Read;
|
||||
let mut header = [0u8; 704];
|
||||
std::fs::File::open(crate::capture::frame_path()?)?.read_exact(&mut header)?;
|
||||
let field = |offset| u32::from_le_bytes(header[offset..offset + 4].try_into().unwrap());
|
||||
anyhow::ensure!(
|
||||
field(0) == 0x4652_5555
|
||||
&& field(4) == 3
|
||||
&& field(36) as usize == streams.len()
|
||||
&& u64::from_le_bytes(header[24..32].try_into().unwrap()) > 0,
|
||||
"capture layout is not ready for pointer routing"
|
||||
);
|
||||
for (index, stream) in streams.iter_mut().enumerate() {
|
||||
let offset = 64 + index * 40;
|
||||
stream.x = field(offset) as i32;
|
||||
stream.y = field(offset + 4) as i32;
|
||||
stream.width = field(offset + 8);
|
||||
stream.height = field(offset + 12);
|
||||
}
|
||||
}
|
||||
anyhow::ensure!(
|
||||
streams
|
||||
.iter()
|
||||
.all(|stream| stream.width > 0 && stream.height > 0),
|
||||
"missing pointer stream dimensions"
|
||||
);
|
||||
if streams
|
||||
.iter()
|
||||
.any(|stream| stream.x == i32::MIN || stream.y == i32::MIN)
|
||||
{
|
||||
let mut next_x = 0i64;
|
||||
for stream in &mut streams {
|
||||
stream.x = i32::try_from(next_x).context("input stream layout is too wide")?;
|
||||
stream.y = 0;
|
||||
next_x += i64::from(stream.width);
|
||||
}
|
||||
}
|
||||
let left = streams
|
||||
.iter()
|
||||
.map(|stream| i64::from(stream.x))
|
||||
.min()
|
||||
.unwrap();
|
||||
let top = streams
|
||||
.iter()
|
||||
.map(|stream| i64::from(stream.y))
|
||||
.min()
|
||||
.unwrap();
|
||||
let right = streams
|
||||
.iter()
|
||||
.map(|stream| i64::from(stream.x) + i64::from(stream.width))
|
||||
.max()
|
||||
.unwrap();
|
||||
let bottom = streams
|
||||
.iter()
|
||||
.map(|stream| i64::from(stream.y) + i64::from(stream.height))
|
||||
.max()
|
||||
.unwrap();
|
||||
let global_x = left as f64 + x.clamp(0.0, 65535.0) * (right - left - 1) as f64 / 65535.0;
|
||||
let global_y = top as f64 + y.clamp(0.0, 65535.0) * (bottom - top - 1) as f64 / 65535.0;
|
||||
let mut best = None;
|
||||
let mut distance = f64::INFINITY;
|
||||
for stream in &streams {
|
||||
let local_x = (global_x - f64::from(stream.x)).clamp(0.0, f64::from(stream.width - 1));
|
||||
let local_y = (global_y - f64::from(stream.y)).clamp(0.0, f64::from(stream.height - 1));
|
||||
let dx = global_x - f64::from(stream.x) - local_x;
|
||||
let dy = global_y - f64::from(stream.y) - local_y;
|
||||
let current = dx * dx + dy * dy;
|
||||
// The producer draws later streams last when rectangles overlap.
|
||||
if current <= distance {
|
||||
best = Some((stream.node, local_x, local_y));
|
||||
distance = current;
|
||||
}
|
||||
}
|
||||
best.context("no input stream matches the pointer position")
|
||||
}
|
||||
|
||||
use crate::capture::CaptureHelper as CaptureGuard;
|
||||
|
||||
/// Wayland input through the freedesktop RemoteDesktop portal. The actual
|
||||
/// backend can be GNOME, KDE, COSMIC, or any future implementation; uur never
|
||||
/// branches on a desktop name.
|
||||
@@ -46,18 +136,21 @@ pub struct PortalBackend {
|
||||
motion_queued: Arc<AtomicBool>,
|
||||
held_keys: HashSet<i32>,
|
||||
held_buttons: HashSet<i32>,
|
||||
failure: Arc<Mutex<Option<String>>>,
|
||||
}
|
||||
|
||||
impl PortalBackend {
|
||||
pub fn connect() -> Result<Self> {
|
||||
let mut config = crate::config::Config::load()?;
|
||||
let restore_token = config.remote_desktop_restore_token.clone();
|
||||
let (sender, receiver) = unbounded_channel();
|
||||
let (ready_sender, ready_receiver) = mpsc::sync_channel(1);
|
||||
let pending_motion = Arc::new(Mutex::new(None));
|
||||
let motion_queued = Arc::new(AtomicBool::new(false));
|
||||
let worker_motion = pending_motion.clone();
|
||||
let worker_queued = motion_queued.clone();
|
||||
let failure = Arc::new(Mutex::new(None));
|
||||
let worker_failure = failure.clone();
|
||||
let worker_config = config.clone();
|
||||
|
||||
std::thread::Builder::new()
|
||||
.name("uur-portal-input".into())
|
||||
@@ -70,12 +163,15 @@ impl PortalBackend {
|
||||
runtime.block_on(portal_worker(
|
||||
receiver,
|
||||
ready_sender.clone(),
|
||||
restore_token,
|
||||
worker_config,
|
||||
worker_motion,
|
||||
worker_queued,
|
||||
worker_failure.clone(),
|
||||
))
|
||||
});
|
||||
if let Err(error) = result {
|
||||
*worker_failure.lock().unwrap() = Some(error.to_string());
|
||||
eprintln!("portal input worker stopped: {error:#}");
|
||||
let _ = ready_sender.send(Err(error.to_string()));
|
||||
}
|
||||
})
|
||||
@@ -87,7 +183,15 @@ impl PortalBackend {
|
||||
.map_err(|error| anyhow!(error))?;
|
||||
if fresh_token != config.remote_desktop_restore_token {
|
||||
config.remote_desktop_restore_token = fresh_token;
|
||||
config.store()?;
|
||||
crate::config::Config::update(|stored| {
|
||||
if stored.capture_source == config.capture_source
|
||||
&& stored.capture_multiple == config.capture_multiple
|
||||
&& stored.capture_backend == config.capture_backend
|
||||
{
|
||||
stored.remote_desktop_restore_token =
|
||||
config.remote_desktop_restore_token.clone();
|
||||
}
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
@@ -96,6 +200,7 @@ impl PortalBackend {
|
||||
motion_queued,
|
||||
held_keys: HashSet::new(),
|
||||
held_buttons: HashSet::new(),
|
||||
failure,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -104,23 +209,125 @@ impl PortalBackend {
|
||||
self.sender
|
||||
.send(event(reply_sender))
|
||||
.map_err(|_| anyhow!("portal input session closed"))?;
|
||||
reply_receiver
|
||||
let result = reply_receiver
|
||||
.recv_timeout(Duration::from_secs(3))
|
||||
.context("portal input request timed out")?
|
||||
.map_err(|error| anyhow!(error))
|
||||
.context("portal input request timed out")
|
||||
.and_then(|result| result.map_err(|error| anyhow!(error)));
|
||||
if let Err(error) = &result {
|
||||
*self.failure.lock().unwrap() = Some(error.to_string());
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
async fn portal_worker(
|
||||
mut receiver: UnboundedReceiver<Event>,
|
||||
receiver: UnboundedReceiver<Event>,
|
||||
ready: SyncSender<std::result::Result<Option<String>, String>>,
|
||||
configured: crate::config::Config,
|
||||
pending_motion: Arc<Mutex<Option<Motion>>>,
|
||||
motion_queued: Arc<AtomicBool>,
|
||||
failure: Arc<Mutex<Option<String>>>,
|
||||
) -> Result<()> {
|
||||
let mut worker = PortalWorker {
|
||||
restore_token: configured.remote_desktop_restore_token.clone(),
|
||||
configured,
|
||||
receiver,
|
||||
ready,
|
||||
pending_motion,
|
||||
motion_queued,
|
||||
failure,
|
||||
initial: true,
|
||||
opened: false,
|
||||
held_keys: HashSet::new(),
|
||||
held_buttons: HashSet::new(),
|
||||
};
|
||||
let mut display_changes = crate::capture::watch_display_changes().await;
|
||||
let mut failures = 0u8;
|
||||
loop {
|
||||
worker.opened = false;
|
||||
match portal_session_worker(&mut worker, &mut display_changes).await {
|
||||
Ok(SessionExit::Shutdown) => return Ok(()),
|
||||
Ok(SessionExit::Reconnect { layout, healthy }) => {
|
||||
if healthy {
|
||||
failures = 0;
|
||||
}
|
||||
if !layout {
|
||||
failures += 1;
|
||||
}
|
||||
anyhow::ensure!(failures <= 3, "portal capture recovery exhausted");
|
||||
anyhow::ensure!(worker.restore_token.is_some(),
|
||||
"portal capture changed without a restorable grant; restart uur run to share again");
|
||||
eprintln!(
|
||||
"restoring the consented RemoteDesktop session after {}",
|
||||
if layout {
|
||||
"a display change"
|
||||
} else {
|
||||
"a capture failure"
|
||||
}
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(if layout { 250 } else { 1000 })).await;
|
||||
while tokio::time::timeout(
|
||||
Duration::from_millis(100),
|
||||
crate::capture::next_display_change(&mut display_changes),
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{}
|
||||
}
|
||||
Err(error)
|
||||
if !worker.initial
|
||||
&& !worker.opened
|
||||
&& failures < 3
|
||||
&& worker.restore_token.is_some()
|
||||
&& !crate::capture::user_cancelled(&error) =>
|
||||
{
|
||||
failures += 1;
|
||||
eprintln!("portal restore {failures}/3 failed: {error:#}");
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PortalWorker {
|
||||
receiver: UnboundedReceiver<Event>,
|
||||
ready: SyncSender<std::result::Result<Option<String>, String>>,
|
||||
configured: crate::config::Config,
|
||||
restore_token: Option<String>,
|
||||
pending_motion: Arc<Mutex<Option<Motion>>>,
|
||||
motion_queued: Arc<AtomicBool>,
|
||||
) -> Result<()> {
|
||||
failure: Arc<Mutex<Option<String>>>,
|
||||
initial: bool,
|
||||
opened: bool,
|
||||
held_keys: HashSet<i32>,
|
||||
held_buttons: HashSet<i32>,
|
||||
}
|
||||
|
||||
enum SessionExit {
|
||||
Shutdown,
|
||||
Reconnect { layout: bool, healthy: bool },
|
||||
}
|
||||
|
||||
async fn portal_session_worker(
|
||||
worker: &mut PortalWorker,
|
||||
display_changes: &mut Option<zbus::proxy::SignalStream<'static>>,
|
||||
) -> Result<SessionExit> {
|
||||
let PortalWorker {
|
||||
receiver,
|
||||
ready,
|
||||
configured,
|
||||
restore_token,
|
||||
pending_motion,
|
||||
motion_queued,
|
||||
failure,
|
||||
initial,
|
||||
opened,
|
||||
held_keys,
|
||||
held_buttons,
|
||||
} = worker;
|
||||
let portal = RemoteDesktop::new().await?;
|
||||
let screencast = Screencast::new().await?;
|
||||
let configured = crate::config::Config::load()?;
|
||||
let source = crate::capture::source_type(&configured.capture_source);
|
||||
let available = portal.available_device_types().await?;
|
||||
if !available.contains(DeviceType::Keyboard) || !available.contains(DeviceType::Pointer) {
|
||||
@@ -128,6 +335,18 @@ async fn portal_worker(
|
||||
}
|
||||
|
||||
let session = portal.create_session().await?;
|
||||
let serialized = serde_json::to_value(&session)?;
|
||||
let session_proxy = zbus::Proxy::new_owned(
|
||||
portal.connection().clone(),
|
||||
"org.freedesktop.portal.Desktop",
|
||||
serialized
|
||||
.as_str()
|
||||
.context("invalid portal session path")?
|
||||
.to_owned(),
|
||||
"org.freedesktop.portal.Session",
|
||||
)
|
||||
.await?;
|
||||
let mut closed = session_proxy.receive_signal("Closed").await?;
|
||||
portal
|
||||
.select_devices(
|
||||
&session,
|
||||
@@ -142,27 +361,110 @@ async fn portal_worker(
|
||||
&session,
|
||||
crate::capture::preferred_cursor_mode(&screencast).await?,
|
||||
source.into(),
|
||||
false,
|
||||
configured.capture_multiple && configured.capture_source == "monitor",
|
||||
None,
|
||||
PersistMode::DoNot,
|
||||
)
|
||||
.await?
|
||||
.response()?;
|
||||
let selection = portal.start(&session, None).await?.response()?;
|
||||
let stream = selection
|
||||
*opened = true;
|
||||
anyhow::ensure!(
|
||||
selection.devices().contains(DeviceType::Keyboard)
|
||||
&& selection.devices().contains(DeviceType::Pointer),
|
||||
"RemoteDesktop grant did not include keyboard and pointer"
|
||||
);
|
||||
let selected_streams = selection
|
||||
.streams()
|
||||
.and_then(|streams| streams.first())
|
||||
.context("RemoteDesktop portal returned no screen stream")?;
|
||||
let stream_id = stream.pipe_wire_node_id();
|
||||
let (logical_width, logical_height) = stream.size().unwrap_or((65535, 65535));
|
||||
.context("RemoteDesktop portal returned no screen streams")?;
|
||||
anyhow::ensure!(
|
||||
!selected_streams.is_empty(),
|
||||
"RemoteDesktop portal returned no screen streams"
|
||||
);
|
||||
let streams = selected_streams
|
||||
.iter()
|
||||
.map(|stream| {
|
||||
let (x, y) = stream.position().unwrap_or((i32::MIN, i32::MIN));
|
||||
let (width, height) = stream.size().unwrap_or((0, 0));
|
||||
crate::capture::CaptureStream {
|
||||
node: stream.pipe_wire_node_id(),
|
||||
x,
|
||||
y,
|
||||
width: u32::try_from(width).unwrap_or(0),
|
||||
height: u32::try_from(height).unwrap_or(0),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let pipewire = screencast.open_pipe_wire_remote(&session).await?;
|
||||
let _capture = CaptureGuard(crate::capture::spawn_helper(pipewire, stream_id)?);
|
||||
let mut capture = CaptureGuard(crate::capture::spawn_helper(pipewire, &streams)?);
|
||||
let token = selection.restore_token().map(ToOwned::to_owned);
|
||||
ready
|
||||
.send(Ok(token))
|
||||
.map_err(|_| anyhow!("portal setup receiver closed"))?;
|
||||
|
||||
while let Some(event) = receiver.recv().await {
|
||||
*restore_token = token.clone();
|
||||
if *initial {
|
||||
ready
|
||||
.send(Ok(token))
|
||||
.map_err(|_| anyhow!("portal setup receiver closed"))?;
|
||||
*initial = false;
|
||||
} else {
|
||||
crate::config::Config::update(|stored| {
|
||||
if stored.capture_source == configured.capture_source
|
||||
&& stored.capture_multiple == configured.capture_multiple
|
||||
&& stored.capture_backend == configured.capture_backend
|
||||
{
|
||||
stored.remote_desktop_restore_token = token;
|
||||
}
|
||||
})?;
|
||||
for key in held_keys.iter().copied() {
|
||||
portal
|
||||
.notify_keyboard_keycode(&session, key, KeyState::Pressed)
|
||||
.await?;
|
||||
}
|
||||
for button in held_buttons.iter().copied() {
|
||||
portal
|
||||
.notify_pointer_button(&session, button, KeyState::Pressed)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
let mut healthy_since = None;
|
||||
let mut health_tick = tokio::time::interval(Duration::from_millis(50));
|
||||
let outcome: Result<SessionExit> = async {
|
||||
loop {
|
||||
if let Some(error) = failure.lock().unwrap().clone() {
|
||||
anyhow::bail!("portal input session failed: {error}");
|
||||
}
|
||||
let event = tokio::select! {
|
||||
biased;
|
||||
_ = closed.next() => {
|
||||
let layout = tokio::time::timeout(Duration::from_millis(250),
|
||||
crate::capture::next_display_change(display_changes)).await.is_ok();
|
||||
anyhow::ensure!(layout, "screen sharing was closed by the portal; restart uur run to share again");
|
||||
break Ok(SessionExit::Reconnect { layout: true,
|
||||
healthy: healthy_since.is_some_and(|since: Instant| since.elapsed() >= Duration::from_secs(30)) });
|
||||
},
|
||||
_ = crate::capture::next_display_change(display_changes) => {
|
||||
break Ok(SessionExit::Reconnect { layout: true,
|
||||
healthy: healthy_since.is_some_and(|since: Instant| since.elapsed() >= Duration::from_secs(30)) });
|
||||
},
|
||||
_ = health_tick.tick() => {
|
||||
if crate::capture::helper_stalled(&crate::capture::frame_path()?) {
|
||||
eprintln!("portal capture helper heartbeat expired; reconnecting");
|
||||
break Ok(SessionExit::Reconnect { layout: false,
|
||||
healthy: healthy_since.is_some_and(|since: Instant| since.elapsed() >= Duration::from_secs(30)) });
|
||||
}
|
||||
if crate::capture::has_frame(&crate::capture::frame_path()?) && healthy_since.is_none() {
|
||||
healthy_since = Some(Instant::now());
|
||||
}
|
||||
if let Some(status) = capture.0.try_wait()? {
|
||||
anyhow::ensure!(status.code() == Some(75), "portal capture helper exited ({status})");
|
||||
break Ok(SessionExit::Reconnect { layout: false,
|
||||
healthy: healthy_since.is_some_and(|since: Instant| since.elapsed() >= Duration::from_secs(30)) });
|
||||
}
|
||||
continue;
|
||||
},
|
||||
event = receiver.recv() => match event {
|
||||
Some(event) => event,
|
||||
None => break Ok(SessionExit::Shutdown),
|
||||
},
|
||||
};
|
||||
match event {
|
||||
Event::Key(code, down, reply) => {
|
||||
let result = portal
|
||||
@@ -176,6 +478,9 @@ async fn portal_worker(
|
||||
},
|
||||
)
|
||||
.await;
|
||||
if result.is_ok() {
|
||||
if down { held_keys.insert(code); } else { held_keys.remove(&code); }
|
||||
}
|
||||
answer(reply, result)?;
|
||||
}
|
||||
Event::Button(button, down, reply) => {
|
||||
@@ -190,25 +495,22 @@ async fn portal_worker(
|
||||
},
|
||||
)
|
||||
.await;
|
||||
if result.is_ok() {
|
||||
if down { held_buttons.insert(button); } else { held_buttons.remove(&button); }
|
||||
}
|
||||
answer(reply, result)?;
|
||||
}
|
||||
Event::FlushMotion => loop {
|
||||
Event::FlushMotion => {
|
||||
motion_queued.store(false, Ordering::Release);
|
||||
let motion = pending_motion.lock().unwrap().take();
|
||||
let Some(motion) = motion else {
|
||||
motion_queued.store(false, Ordering::Release);
|
||||
let has_new_motion = pending_motion.lock().unwrap().is_some();
|
||||
if has_new_motion
|
||||
&& motion_queued
|
||||
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
|
||||
.is_ok()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
continue;
|
||||
};
|
||||
let result = if motion.absolute {
|
||||
let logical_x = motion.x.clamp(0.0, 65535.0) * logical_width as f64 / 65535.0;
|
||||
let logical_y = motion.y.clamp(0.0, 65535.0) * logical_height as f64 / 65535.0;
|
||||
let (stream_id, logical_x, logical_y) = match absolute_target(&streams, motion.x, motion.y) {
|
||||
Ok(target) => target,
|
||||
Err(error) => { eprintln!("portal pointer layout not ready: {error}"); continue; }
|
||||
};
|
||||
portal
|
||||
.notify_pointer_motion_absolute(&session, stream_id, logical_x, logical_y)
|
||||
.await
|
||||
@@ -229,10 +531,14 @@ async fn portal_worker(
|
||||
.await,
|
||||
)?;
|
||||
}
|
||||
Event::Shutdown => break,
|
||||
Event::Shutdown => break Ok(SessionExit::Shutdown),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}.await;
|
||||
drop(closed);
|
||||
drop(capture);
|
||||
let _ = tokio::time::timeout(Duration::from_secs(2), session.close()).await;
|
||||
outcome
|
||||
}
|
||||
|
||||
fn answer<T>(reply: Reply, result: std::result::Result<T, ashpd::Error>) -> Result<()> {
|
||||
@@ -246,6 +552,14 @@ impl InputBackend for PortalBackend {
|
||||
"portal"
|
||||
}
|
||||
|
||||
fn check_health(&self) -> Result<()> {
|
||||
if let Some(error) = self.failure.lock().unwrap().clone() {
|
||||
anyhow::bail!("portal input worker failed: {error}");
|
||||
}
|
||||
anyhow::ensure!(!self.sender.is_closed(), "portal input worker stopped");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn key(&mut self, vkey: u16, down: bool) -> Result<()> {
|
||||
let code = super::uinput::vk_to_linux_key(vkey) as i32;
|
||||
if code == 0 {
|
||||
@@ -342,7 +656,7 @@ impl Drop for PortalBackend {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{merge_motion, Motion};
|
||||
use super::{absolute_target, merge_motion, Motion};
|
||||
|
||||
#[test]
|
||||
fn absolute_motion_keeps_only_the_latest_position() {
|
||||
@@ -358,6 +672,35 @@ mod tests {
|
||||
};
|
||||
merge_motion(&mut pending, latest);
|
||||
assert_eq!(pending, Some(latest));
|
||||
let streams = [
|
||||
crate::capture::CaptureStream {
|
||||
node: 41,
|
||||
x: -1280,
|
||||
y: 0,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
},
|
||||
crate::capture::CaptureStream {
|
||||
node: 42,
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
},
|
||||
];
|
||||
assert_eq!(absolute_target(&streams, 0.0, 0.0).unwrap(), (41, 0.0, 0.0));
|
||||
assert_eq!(
|
||||
absolute_target(&streams, 65535.0, 65535.0).unwrap(),
|
||||
(42, 1919.0, 1079.0)
|
||||
);
|
||||
let target = absolute_target(&streams, 1280.0 * 65535.0 / 3199.0, 0.0).unwrap();
|
||||
assert_eq!(target.0, 42);
|
||||
assert!(target.1.abs() < 1e-6);
|
||||
assert!(absolute_target(&streams, f64::NAN, 0.0).is_err());
|
||||
let mut gap = streams;
|
||||
gap[1].x = 200;
|
||||
let target = absolute_target(&gap, 1280.0 * 65535.0 / 3399.0, 0.0).unwrap();
|
||||
assert_eq!(target, (41, 1279.0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+38
-17
@@ -157,7 +157,12 @@ enum DisplayAction {
|
||||
/// Show the configured source type.
|
||||
Status,
|
||||
/// Use a monitor, one window, or a portal-provided virtual display.
|
||||
Source { source: DisplaySource },
|
||||
Source {
|
||||
source: DisplaySource,
|
||||
/// Allow selecting several monitors in the next portal consent dialog.
|
||||
#[arg(long)]
|
||||
multiple: bool,
|
||||
},
|
||||
/// Choose portal capture, or explicitly enable direct Wayland monitor capture.
|
||||
Backend {
|
||||
backend: CaptureBackend,
|
||||
@@ -228,29 +233,32 @@ fn main() -> Result<()> {
|
||||
if matches!(action, DisplayAction::Outputs) {
|
||||
return capture::list_wayland_outputs();
|
||||
}
|
||||
let mut config = config::Config::load()?;
|
||||
let config = config::Config::load()?;
|
||||
match action {
|
||||
DisplayAction::Status => {
|
||||
println!("{}", t!("display.status", source = config.capture_source));
|
||||
println!("capture backend: {}", config.capture_backend);
|
||||
println!("multiple monitors: {}", config.capture_multiple);
|
||||
if let Some(output) = &config.capture_output {
|
||||
println!("output: {output}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
DisplayAction::Backend { backend, output } => {
|
||||
config.capture_backend = match backend {
|
||||
let backend = match backend {
|
||||
CaptureBackend::Portal => "portal",
|
||||
CaptureBackend::Wayland => "wayland",
|
||||
}
|
||||
.into();
|
||||
config.capture_output = output;
|
||||
if config.capture_backend == "wayland" {
|
||||
config.capture_source = "monitor".into();
|
||||
}
|
||||
config.capture_restore_token = None;
|
||||
config.remote_desktop_restore_token = None;
|
||||
config.store()?;
|
||||
};
|
||||
let config = config::Config::update(|stored| {
|
||||
stored.capture_backend = backend.into();
|
||||
stored.capture_output = output;
|
||||
if backend == "wayland" {
|
||||
stored.capture_source = "monitor".into();
|
||||
stored.capture_multiple = false;
|
||||
}
|
||||
stored.capture_restore_token = None;
|
||||
stored.remote_desktop_restore_token = None;
|
||||
})?;
|
||||
println!(
|
||||
"{}",
|
||||
if config.capture_backend == "wayland" {
|
||||
@@ -262,12 +270,25 @@ fn main() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
DisplayAction::Outputs => unreachable!(),
|
||||
DisplayAction::Source { source } => {
|
||||
config.capture_source = source.as_str().to_string();
|
||||
config.capture_restore_token = None;
|
||||
config.remote_desktop_restore_token = None;
|
||||
config.store()?;
|
||||
DisplayAction::Source { source, multiple } => {
|
||||
anyhow::ensure!(
|
||||
!multiple || matches!(&source, DisplaySource::Monitor),
|
||||
"--multiple is supported only for monitor sources"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
!multiple || config.capture_backend == "portal",
|
||||
"multi-monitor selection requires the portal capture backend"
|
||||
);
|
||||
config::Config::update(|stored| {
|
||||
stored.capture_source = source.as_str().to_string();
|
||||
stored.capture_multiple = multiple;
|
||||
stored.capture_restore_token = None;
|
||||
stored.remote_desktop_restore_token = None;
|
||||
})?;
|
||||
println!("{}", t!("display.changed", source = source.as_str()));
|
||||
println!(
|
||||
"multiple monitors: {multiple}; selection applies on the next session"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -973,7 +973,7 @@ fn process_start_time(pid: u32) -> Result<u64> {
|
||||
}
|
||||
|
||||
fn frame_path() -> Result<PathBuf> {
|
||||
Ok(crate::config::runtime_dir()?.join("frames.v1"))
|
||||
Ok(crate::config::runtime_dir()?.join("frames.v3"))
|
||||
}
|
||||
|
||||
fn unix_path_to_wine(path: &Path) -> String {
|
||||
@@ -1370,8 +1370,8 @@ mod tests {
|
||||
#[test]
|
||||
fn runtime_path_converts_to_a_wine_z_path() {
|
||||
assert_eq!(
|
||||
unix_path_to_wine(Path::new("/run/user/1000/uur/frames.v1")),
|
||||
r"Z:\run\user\1000\uur\frames.v1"
|
||||
unix_path_to_wine(Path::new("/run/user/1000/uur/frames.v3")),
|
||||
r"Z:\run\user\1000\uur\frames.v3"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user