From 1bac16c1f71cf748885085aada8e40c657be2a1f Mon Sep 17 00:00:00 2001 From: FacuM Date: Tue, 17 Nov 2026 13:23:51 -0300 Subject: [PATCH 1/6] Tell the tablet when the GNOME screen is locked GNOME Shell inhibits screen casts while its lock screen is shown: Mutter closes the session and refuses new ones. The capture then failed with a raw error and the tablet reconnected every few seconds, failing each time. The GNOME provider now asks org.gnome.ScreenSaver whether the screen is locked, before opening a session and when the capture fails, and reports SourceError::ScreenLocked. The session ends with the well-known Bye reason "screen-locked". The Android client shows that the computer's screen is locked, keeps that message up while it retries every five seconds, and takes a new stream for real only once a frame arrives. --- .../com/librestatic/ezdisplay/HostLock.kt | 19 ++++++ .../com/librestatic/ezdisplay/MainActivity.kt | 47 +++++++++++--- .../app/src/main/res/values-de/strings.xml | 1 + .../app/src/main/res/values-es/strings.xml | 1 + .../app/src/main/res/values-fr/strings.xml | 1 + .../app/src/main/res/values-it/strings.xml | 1 + .../app/src/main/res/values-pt/strings.xml | 1 + android/app/src/main/res/values/strings.xml | 1 + .../com/librestatic/ezdisplay/HostLockTest.kt | 28 ++++++++ crates/ezd-android/src/session.rs | 23 ++++--- crates/ezd-android/src/status.rs | 29 +++++++++ crates/ezd-host-core/src/session.rs | 65 +++++++++++++++++++ crates/ezd-host-core/src/source.rs | 3 + crates/ezd-host-linux/src/gnome.rs | 61 ++++++++++++++++- crates/ezd-host-linux/src/provider.rs | 5 ++ crates/ezd-host-linux/src/source.rs | 20 +++++- crates/ezd-proto/src/msg.rs | 4 ++ docs/architecture.md | 2 +- docs/protocol.md | 6 ++ 19 files changed, 295 insertions(+), 23 deletions(-) create mode 100644 android/app/src/main/kotlin/com/librestatic/ezdisplay/HostLock.kt create mode 100644 android/app/src/test/kotlin/com/librestatic/ezdisplay/HostLockTest.kt diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/HostLock.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/HostLock.kt new file mode 100644 index 0000000..dde5244 --- /dev/null +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/HostLock.kt @@ -0,0 +1,19 @@ +package com.librestatic.ezdisplay + +/** Pure rules for a host whose screen is locked (the native layer reports the code `screen_locked`). */ +object HostLock { + /** Status code the native layer sets when the host ends the session because its screen is locked. */ + const val CODE = "screen_locked" + + /** Fixed delay between reconnection attempts while the host is locked. */ + const val RETRY_MS = 5000L + + /** Whether an ended session carrying [code] means the host's screen is locked. */ + fun isLocked(code: String?): Boolean = code == CODE + + /** Whether a negotiated stream shows that the host was unlocked: only once a frame has arrived. */ + fun confirmsUnlock(framesReceived: Long): Boolean = framesReceived > 0 + + /** Whether the connecting and handshake texts may replace the status; the locked message stays up. */ + fun showsProgress(hostLocked: Boolean): Boolean = !hostLocked +} diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index ef5582f..c445d97 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -99,6 +99,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. const val LAST_WIFI_HOST = "wifi_last_host" const val BACKOFF_MIN_MS = 1000L const val BACKOFF_MAX_MS = 5000L + const val LOCKED_RETRY_MS = HostLock.RETRY_MS const val STATS_INTERVAL_MS = 250L const val STATUS_HIDE_MS = 3000L const val NOTE_SHOW_MS = 6000L @@ -136,6 +137,9 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. private var surfaceReady = false private var sessionActive = false // NativeBridge.start succeeded and was not stopped private var backoffMs = BACKOFF_MIN_MS + + /** The host said its screen is locked: keep that message up and retry slowly until it streams again. */ + private var hostLocked = false private var wasStreaming = false private var lastStatsPoll = 0L private var streamW = 0 @@ -488,6 +492,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. if (shouldSwitchToAccessory(true, sessionActive, activeAccessory)) { if (sessionActive) stopSession() backoffMs = BACKOFF_MIN_MS + hostLocked = false scheduleConnect(0) } } @@ -502,6 +507,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. if (!activeAccessory) return stopSession() backoffMs = BACKOFF_MIN_MS + hostLocked = false tryWifiNext = false setStatus(getString(R.string.status_waiting, "$HOST:$PORT")) scheduleConnect(0) @@ -530,6 +536,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. if (routedAway) return started = true backoffMs = BACKOFF_MIN_MS + hostLocked = false tryWifiNext = false setStatus(getString(R.string.status_waiting, "$HOST:$PORT")) Choreographer.getInstance().postFrameCallback(this) @@ -832,15 +839,19 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. val usb = activeAccessory if (j.optString("phase") != "streaming") hideOsd(false) val addr = if (wifiChoice != null) hostLabel(wifiChoice) else "$HOST:$PORT" - when (j.optString("phase")) { - "connecting" -> setStatus( + // The native layer reports "streaming" once the stream is negotiated, before the host opens its + // capture: while the host is locked that is not a stream yet, so the locked message stays up. + val phase = j.optString("phase") + val pending = hostLocked && phase == "streaming" && !HostLock.confirmsUnlock(j.optLong("frames_received")) + when (if (pending) "" else phase) { + "connecting" -> if (HostLock.showsProgress(hostLocked)) setStatus( when { usb -> getString(R.string.status_usb_connecting) wifiChoice != null -> getString(R.string.status_wifi_connecting, addr) else -> getString(R.string.status_waiting, addr) }, ) - "handshaking" -> setStatus( + "handshaking" -> if (HostLock.showsProgress(hostLocked)) setStatus( when { usb -> getString(R.string.status_usb_handshake) wifiChoice != null -> getString(R.string.status_wifi_handshake, addr) @@ -861,6 +872,7 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. if (!wasStreaming) { wasStreaming = true pairingLost = null + hostLocked = false updateChrome() backoffMs = BACKOFF_MIN_MS streamW = j.optInt("width") @@ -885,12 +897,22 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. statusView.visibility = View.GONE } } - "ended" -> disconnected( - if (usb) getString(R.string.status_ended_usb, j.optString("detail")) - else getString(R.string.status_ended, j.optString("detail"), addr), - false, - ) + "ended" -> { + val code = if (j.isNull("code")) null else j.optString("code") + if (HostLock.isLocked(code)) { + hostLocked = true + disconnected(getString(R.string.status_host_locked), false, locked = true) + } else { + hostLocked = false + disconnected( + if (usb) getString(R.string.status_ended_usb, j.optString("detail")) + else getString(R.string.status_ended, j.optString("detail"), addr), + false, + ) + } + } "failed" -> { + hostLocked = false // A Wi-Fi failure carries a stable code; the detail is English text for the log. val code = if (j.isNull("code")) null else j.optString("code") val message = if (code != null && activeWifi != null) { @@ -936,12 +958,19 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. statusHideAt = SystemClock.uptimeMillis() + ms } - private fun disconnected(message: String, failed: Boolean) { + private fun disconnected(message: String, failed: Boolean, locked: Boolean = false) { Log.i(TAG, "disconnected: $message") val wasWifi = activeWifi != null // Any failure over Wi-Fi demotes that address, so the next attempt tries another candidate. if (failed) activeWifi?.let { wifiFailures.record(it.host.fingerprint, it.addr, SystemClock.elapsedRealtime()) } stopSession() + if (locked) { + // The host is fine, only its screen is locked: retry at a fixed, slow pace and leave the + // Wi-Fi record and the backoff alone. + setStatus(message) + scheduleConnect(LOCKED_RETRY_MS) + return + } // Keep telling the user why Wi-Fi stopped until a host is paired again. if (wifiTarget() != null) pairingLost = null setStatus(message) diff --git a/android/app/src/main/res/values-de/strings.xml b/android/app/src/main/res/values-de/strings.xml index 124e9df..b6bd37b 100644 --- a/android/app/src/main/res/values-de/strings.xml +++ b/android/app/src/main/res/values-de/strings.xml @@ -6,6 +6,7 @@ Verbunden: %1$d×%2$d@%3$s %4$s %5$s %1$s. Neuer Versuch… Verbindung getrennt (%1$s). Warte auf den Host unter %2$s… + Der Bildschirm des Computers ist gesperrt. Das Bild kommt zurück, sobald du ihn entsperrst. Start nicht möglich: %1$s %1$s fps · %2$s Mbit/s\nDekodierung %3$s / %4$s ms (p50 / p95)\nEnde zu Ende %5$s / %6$s ms (p50 / p95)\nRTT %7$s ms · verworfen %8$d\n%9$s Eingabe: %1$s diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml index 9369093..d642329 100644 --- a/android/app/src/main/res/values-es/strings.xml +++ b/android/app/src/main/res/values-es/strings.xml @@ -6,6 +6,7 @@ Conectado: %1$d×%2$d@%3$s %4$s %5$s %1$s. Reintentando… Desconectado (%1$s). Esperando al host en %2$s… + La pantalla de la computadora está bloqueada. La imagen vuelve cuando la desbloqueás. No se puede iniciar: %1$s %1$s fps · %2$s Mbit/s\ndecodificación %3$s / %4$s ms (p50 / p95)\nextremo a extremo %5$s / %6$s ms (p50 / p95)\nRTT %7$s ms · descartados %8$d\n%9$s Entrada: %1$s diff --git a/android/app/src/main/res/values-fr/strings.xml b/android/app/src/main/res/values-fr/strings.xml index 3b9cde1..a85247c 100644 --- a/android/app/src/main/res/values-fr/strings.xml +++ b/android/app/src/main/res/values-fr/strings.xml @@ -6,6 +6,7 @@ Connecté : %1$d×%2$d@%3$s %4$s %5$s %1$s. Nouvelle tentative… Déconnecté (%1$s). En attente de l\'hôte à %2$s… + L\'écran de l\'ordinateur est verrouillé. L\'image revient quand vous le déverrouillez. Démarrage impossible : %1$s %1$s fps · %2$s Mbit/s\ndécodage %3$s / %4$s ms (p50 / p95)\nde bout en bout %5$s / %6$s ms (p50 / p95)\nRTT %7$s ms · perdues %8$d\n%9$s Entrée : %1$s diff --git a/android/app/src/main/res/values-it/strings.xml b/android/app/src/main/res/values-it/strings.xml index 3d0dd3b..13712ca 100644 --- a/android/app/src/main/res/values-it/strings.xml +++ b/android/app/src/main/res/values-it/strings.xml @@ -6,6 +6,7 @@ Connesso: %1$d×%2$d@%3$s %4$s %5$s %1$s. Nuovo tentativo… Disconnesso (%1$s). In attesa dell\'host su %2$s… + Lo schermo del computer è bloccato. L\'immagine torna quando lo sblocchi. Impossibile avviare: %1$s %1$s fps · %2$s Mbit/s\ndecodifica %3$s / %4$s ms (p50 / p95)\nend-to-end %5$s / %6$s ms (p50 / p95)\nRTT %7$s ms · scartati %8$d\n%9$s Input: %1$s diff --git a/android/app/src/main/res/values-pt/strings.xml b/android/app/src/main/res/values-pt/strings.xml index 6863e8d..20980be 100644 --- a/android/app/src/main/res/values-pt/strings.xml +++ b/android/app/src/main/res/values-pt/strings.xml @@ -6,6 +6,7 @@ Conectado: %1$d×%2$d@%3$s %4$s %5$s %1$s. Tentando novamente… Desconectado (%1$s). Aguardando o host em %2$s… + A tela do computador está bloqueada. A imagem volta quando você a desbloqueia. Não foi possível iniciar: %1$s %1$s fps · %2$s Mbit/s\ndecodificação %3$s / %4$s ms (p50 / p95)\nponta a ponta %5$s / %6$s ms (p50 / p95)\nRTT %7$s ms · descartados %8$d\n%9$s Entrada: %1$s diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index ffa7725..88fd6da 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -6,6 +6,7 @@ Connected: %1$d×%2$d@%3$s %4$s %5$s %1$s. Retrying… Disconnected (%1$s). Waiting for the host at %2$s… + The computer\'s screen is locked. The picture comes back when you unlock it. Cannot start: %1$s %1$s fps · %2$s Mbit/s\ndecode %3$s / %4$s ms (p50 / p95)\nend to end %5$s / %6$s ms (p50 / p95)\nRTT %7$s ms · dropped %8$d\n%9$s Input: %1$s diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/HostLockTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/HostLockTest.kt new file mode 100644 index 0000000..3806003 --- /dev/null +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/HostLockTest.kt @@ -0,0 +1,28 @@ +package com.librestatic.ezdisplay + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class HostLockTest { + @Test fun onlyTheScreenLockedCodeMeansLocked() { + assertTrue(HostLock.isLocked("screen_locked")) + assertFalse(HostLock.isLocked(null)) + assertFalse(HostLock.isLocked("not_paired")) + } + + @Test fun connectingTextsDoNotReplaceTheLockedMessage() { + assertFalse(HostLock.showsProgress(true)) + assertTrue(HostLock.showsProgress(false)) + } + + @Test fun aNegotiatedStreamCountsOnlyOnceAFrameArrives() { + assertFalse(HostLock.confirmsUnlock(0)) + assertTrue(HostLock.confirmsUnlock(1)) + } + + @Test fun retriesAreSlowAndFixed() { + assertEquals(5000L, HostLock.RETRY_MS) + } +} diff --git a/crates/ezd-android/src/session.rs b/crates/ezd-android/src/session.rs index 8473bac..5e866c0 100644 --- a/crates/ezd-android/src/session.rs +++ b/crates/ezd-android/src/session.rs @@ -495,14 +495,21 @@ fn run( match run_client(link, cfg, &handle, &mut handler).await { Ok(o) => { tracing::info!("session ended: {:?}", o.end); - let detail = match o.end { - ClientEnd::Stopped => "stopped".to_string(), - ClientEnd::HostBye(r) => format!("host: {r}"), - ClientEnd::HostEof => "host closed the connection".to_string(), - ClientEnd::TimedOut => "timed out".to_string(), - ClientEnd::HostSilent => "host stopped responding".to_string(), - }; - shared.set_phase(Phase::Ended, detail); + match o.end { + ClientEnd::HostBye(r) if r == ezd_proto::BYE_SCREEN_LOCKED => { + shared.set_ended_code("host: screen-locked", "screen_locked"); + } + end => { + let detail = match end { + ClientEnd::Stopped => "stopped".to_string(), + ClientEnd::HostBye(r) => format!("host: {r}"), + ClientEnd::HostEof => "host closed the connection".to_string(), + ClientEnd::TimedOut => "timed out".to_string(), + ClientEnd::HostSilent => "host stopped responding".to_string(), + }; + shared.set_phase(Phase::Ended, detail); + } + } } Err(e) => { tracing::warn!("session failed: {e}"); diff --git a/crates/ezd-android/src/status.rs b/crates/ezd-android/src/status.rs index 47c0b67..14ea571 100644 --- a/crates/ezd-android/src/status.rs +++ b/crates/ezd-android/src/status.rs @@ -86,6 +86,20 @@ impl Shared { }); } + /// Ends with `detail` and a stable `code` for Kotlin. A failure is sticky, as in + /// [`set_phase`](Self::set_phase). + pub fn set_ended_code(&self, detail: impl Into, code: &'static str) { + let detail = detail.into(); + self.with(|s| { + if s.phase == Phase::Failed { + return; + } + s.phase = Phase::Ended; + s.detail = detail; + s.code = Some(code); + }); + } + /// Records the negotiated stream. pub fn set_stream(&self, stream: StreamConfig) { self.with(|s| { @@ -347,6 +361,21 @@ mod tests { assert!(j["code"].is_null()); } + #[test] + fn an_ended_code_is_reported_and_a_failure_stays_sticky() { + let sh = Shared::default(); + let snap = ClientSnapshot::default(); + sh.set_ended_code("host: screen-locked", "screen_locked"); + let j: serde_json::Value = serde_json::from_str(&sh.to_json(&snap)).unwrap(); + assert_eq!( + (j["phase"].as_str(), j["code"].as_str()), + (Some("ended"), Some("screen_locked")) + ); + sh.set_phase(Phase::Failed, "boom"); + sh.set_ended_code("host: screen-locked", "screen_locked"); + assert_eq!(sh.phase(), Phase::Failed); + } + #[test] fn failure_is_sticky() { let sh = Shared::default(); diff --git a/crates/ezd-host-core/src/session.rs b/crates/ezd-host-core/src/session.rs index 8884e38..fac2e75 100644 --- a/crates/ezd-host-core/src/session.rs +++ b/crates/ezd-host-core/src/session.rs @@ -161,6 +161,9 @@ pub enum EndReason { SourceFailed(String), /// The video source stopped producing frames; the client was sent `Bye`. SourceStopped, + /// The desktop is locked and cannot be captured; the client was sent `Bye` with + /// [`ezd_proto::BYE_SCREEN_LOCKED`]. + ScreenLocked, /// [`SessionOptions::shutdown`] was set; the client was sent `Bye`. HostShutdown, /// The client sent a new `Hello`: its app was restarted and opened the link again. An @@ -628,6 +631,7 @@ pub async fn run_host_session_with( video_done = true; break match r { Ok(Ok(())) => EndReason::SourceStopped, + Ok(Err(SourceError::ScreenLocked)) => EndReason::ScreenLocked, Ok(Err(e)) => EndReason::SourceFailed(e.to_string()), Err(_) => EndReason::SourceFailed("video thread terminated unexpectedly".into()), }; @@ -645,6 +649,11 @@ pub async fn run_host_session_with( EndReason::SourceFailed(r) => { let _ = tx.send_control(Message::Bye(Bye { reason: r.clone() })); } + EndReason::ScreenLocked => { + let _ = tx.send_control(Message::Bye(Bye { + reason: ezd_proto::BYE_SCREEN_LOCKED.into(), + })); + } EndReason::SourceStopped => { let _ = tx.send_control(Message::Bye(Bye { reason: "video source stopped".into(), @@ -2024,6 +2033,62 @@ mod tests { ); } + /// A source whose capture fails because the desktop got locked. + struct LockedSource(ScriptedSource); + impl VideoSource for LockedSource { + fn encoders(&self) -> Vec { + self.0.encoders() + } + fn start(&mut self, cfg: &StreamConfig, cursor: CursorSink) -> Result<(), SourceError> { + self.0.start(cfg, cursor) + } + fn next_frame(&mut self, _t: Duration) -> Result, SourceError> { + Err(SourceError::ScreenLocked) + } + fn request_keyframe(&mut self) {} + fn stop(&mut self) { + self.0.stop(); + } + } + + #[tokio::test] + async fn locked_screen_ends_session_with_the_well_known_bye() { + let (host_link, client_link) = Link::duplex_pair(1 << 20); + let src = LockedSource(ScriptedSource::new(Duration::from_millis(5), 100)); + let host = tokio::spawn(run_host_session_with( + host_link, + Box::new(src), + Prefs::default(), + fast_opts(), + )); + let (tx, mut rx, _t) = client_link.into_mux(1024); + tx.send_control(Message::Hello(Hello::new(Role::Client, "t", "c"))) + .unwrap(); + tx.send_control(Message::ClientCaps(caps())).unwrap(); + tx.send_control(Message::ClientHdr(ClientHdr::none())) + .unwrap(); + tx.send_control(Message::ClientAudio(ClientAudio::none())) + .unwrap(); + tx.send_control(Message::ClientPrefs(ClientPrefs::auto())) + .unwrap(); + for _ in 0..4 { + recv(&mut rx).await; + } + tx.send_control(Message::ConfigAck).unwrap(); + let bye = loop { + if let Message::Bye(b) = recv(&mut rx).await { + break b; + } + }; + assert_eq!(bye.reason, ezd_proto::BYE_SCREEN_LOCKED); + let s = timeout(Duration::from_secs(5), host) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(s.end, EndReason::ScreenLocked); + } + #[tokio::test] async fn client_eof_ends_session() { let (host_link, client_link) = Link::duplex_pair(1 << 20); diff --git a/crates/ezd-host-core/src/source.rs b/crates/ezd-host-core/src/source.rs index 855e8a6..cce8aa3 100644 --- a/crates/ezd-host-core/src/source.rs +++ b/crates/ezd-host-core/src/source.rs @@ -13,6 +13,9 @@ use std::time::Duration; /// implementations. #[derive(Debug, thiserror::Error)] pub enum SourceError { + /// The desktop is locked and refuses screen capture until it is unlocked. + #[error("the screen is locked")] + ScreenLocked, /// Free-form failure description. #[error("{0}")] Msg(String), diff --git a/crates/ezd-host-linux/src/gnome.rs b/crates/ezd-host-linux/src/gnome.rs index 8a6ea7d..2420d41 100644 --- a/crates/ezd-host-linux/src/gnome.rs +++ b/crates/ezd-host-linux/src/gnome.rs @@ -97,12 +97,52 @@ fn map_zbus(what: &str, r: zbus::Result) -> Result { r.map_err(|e| SourceError::msg(format!("Mutter ScreenCast {what}: {e}"))) } +/// Whether Mutter's refusal text says the session was inhibited (the lock screen is up). +fn is_inhibited(text: &str) -> bool { + text.to_ascii_lowercase().contains("inhibited") +} + +/// Whether GNOME Shell's screen shield is active, which is exactly when it inhibits capture. +/// Any error counts as not locked. +fn screen_locked(conn: &Connection) -> bool { + Proxy::new( + conn, + "org.gnome.ScreenSaver", + "/org/gnome/ScreenSaver", + "org.gnome.ScreenSaver", + ) + .and_then(|p| p.call::<_, _, bool>("GetActive", &())) + .unwrap_or(false) +} + +/// Like [`map_zbus`] for the calls that open a session: a refusal while the screen is locked +/// becomes [`SourceError::ScreenLocked`]. +fn map_open(conn: &Connection, what: &str, r: zbus::Result) -> Result { + r.map_err(|e| { + if is_inhibited(&e.to_string()) || screen_locked(conn) { + log_locked(); + SourceError::ScreenLocked + } else { + SourceError::msg(format!("Mutter ScreenCast {what}: {e}")) + } + }) +} + +fn log_locked() { + tracing::info!("the screen is locked: Mutter refuses screen casts until it is unlocked"); +} + impl GnomeProvider { fn open_mutter(&mut self) -> Result { let conn = map_zbus("connect", Connection::session())?; + if screen_locked(&conn) { + log_locked(); + return Err(SourceError::ScreenLocked); + } let before = gnome_dc::get_state(&conn).ok(); let sc = map_zbus("proxy", Proxy::new(&conn, SERVICE, ROOT, SERVICE))?; - let path: OwnedObjectPath = map_zbus( + let path: OwnedObjectPath = map_open( + &conn, "CreateSession", sc.call("CreateSession", &(HashMap::<&str, Value>::new(),)), )?; @@ -117,7 +157,8 @@ impl GnomeProvider { conn: conn.clone(), connector: self.connector.clone(), }; - let stream_path: OwnedObjectPath = map_zbus( + let stream_path: OwnedObjectPath = map_open( + &conn, "RecordVirtual", session.call("RecordVirtual", &(record_virtual_args(),)), )?; @@ -139,7 +180,7 @@ impl GnomeProvider { } }) .map_err(|e| SourceError::msg(format!("cannot start the signal thread: {e}")))?; - map_zbus("Start", session.call::<_, _, ()>("Start", &()))?; + map_open(&conn, "Start", session.call::<_, _, ()>("Start", &()))?; let node = rx.recv_timeout(STREAM_TIMEOUT).map_err(|_| { SourceError::msg("Mutter did not report a PipeWire node for the virtual monitor") })?; @@ -196,6 +237,13 @@ impl VirtualOutputProvider for GnomeProvider { } } + fn screen_locked(&self) -> bool { + match &self.watch { + Some((conn, _)) => screen_locked(conn), + None => Connection::session().is_ok_and(|c| screen_locked(&c)), + } + } + fn settle(&mut self, negotiated: (u32, u32)) -> Option { let (conn, before) = self.watch.as_ref()?; let Some(before) = before else { @@ -285,6 +333,13 @@ mod tests { use ezd_host_core::{CursorSink, PlatformOptions, VideoSource}; use ezd_proto::{Codec, StreamConfig}; + #[test] + fn inhibited_refusals_are_recognised() { + assert!(is_inhibited("Session creation inhibited")); + assert!(is_inhibited("org.freedesktop.DBus.Error.Failed: INHIBITED")); + assert!(!is_inhibited("Mutter ScreenCast Start: no such object")); + } + #[test] fn record_virtual_requests_cursor_metadata_on_a_platform_monitor() { let a = record_virtual_args(); diff --git a/crates/ezd-host-linux/src/provider.rs b/crates/ezd-host-linux/src/provider.rs index bdcc6e9..1b97a9c 100644 --- a/crates/ezd-host-linux/src/provider.rs +++ b/crates/ezd-host-linux/src/provider.rs @@ -71,6 +71,11 @@ pub trait VirtualOutputProvider: Send { fn settle(&mut self, _negotiated: (u32, u32)) -> Option { None } + + /// Whether the desktop is locked and refuses capture. + fn screen_locked(&self) -> bool { + false + } } /// Refresh rate as compositor mode strings take it (`60`, `59.94`): whole hertz without a diff --git a/crates/ezd-host-linux/src/source.rs b/crates/ezd-host-linux/src/source.rs index 6ea845e..3827ea0 100644 --- a/crates/ezd-host-linux/src/source.rs +++ b/crates/ezd-host-linux/src/source.rs @@ -79,6 +79,20 @@ fn hdr_mismatch(expected: bool, actual: bool) -> Option<&'static str> { } } +/// The error for a capture that failed: [`SourceError::ScreenLocked`] when the desktop is locked, +/// which closes the stream. The stream can close a moment before the screen saver reports +/// active, so a negative answer is checked once more. Only called on the error path. +fn capture_error(provider: &dyn VirtualOutputProvider, e: String) -> SourceError { + if provider.screen_locked() { + return SourceError::ScreenLocked; + } + std::thread::sleep(Duration::from_millis(300)); + if provider.screen_locked() { + return SourceError::ScreenLocked; + } + SourceError::msg(e) +} + /// Linux capture + encode source, generic over the compositor's output provider. pub struct LinuxSource { provider: Box, @@ -466,7 +480,7 @@ impl VideoSource for LinuxSource { }; let frame = match r.capture.next(wait) { Ok(f) => f, - Err(e) => return Err(SourceError::msg(e)), + Err(e) => return Err(capture_error(self.provider.as_ref(), e)), }; match frame { Some(frame) => { @@ -522,7 +536,9 @@ impl VideoSource for LinuxSource { (result, start_us, capture_us, seq, dma) } Some(Item::Failed { dma, error }) => (Err(error), 0, 0, 0, dma), - Some(Item::Closed(e)) => return Err(SourceError::msg(e)), + Some(Item::Closed(e)) => { + return Err(capture_error(self.provider.as_ref(), e)); + } } } }; diff --git a/crates/ezd-proto/src/msg.rs b/crates/ezd-proto/src/msg.rs index 83ba458..d26c6be 100644 --- a/crates/ezd-proto/src/msg.rs +++ b/crates/ezd-proto/src/msg.rs @@ -275,6 +275,10 @@ pub struct Reject { pub reason: String, } +/// Well-known [`Bye::reason`]: the host's desktop is locked and cannot be captured until it is +/// unlocked. A client should say so and retry slowly. +pub const BYE_SCREEN_LOCKED: &str = "screen-locked"; + /// Orderly shutdown. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Bye { diff --git a/docs/architecture.md b/docs/architecture.md index 964e47e..52a1d47 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -108,7 +108,7 @@ flowchart TB ### Linux - KDE Plasma: the ScreenCast portal source type `VIRTUAL` creates a KWin virtual output. The user picks its size in the portal dialog, default 1920×1080, and `restore_token` skips the dialog afterwards. KWin virtual outputs start at 60 Hz but support custom modes, so the host adds the stream-size mode (the tablet's native size, or the `--scale`d one) with `kscreen-doctor output..addCustomMode....reduced` and switches to it. It uses the numeric id: the output is named after the app that asked the portal (`Virtual-virtual-xdp-kde-`), the app id has dots, and kscreen-doctor splits its arguments on dots, so a name never matches and the output would stay at 60 Hz. -- GNOME: Mutter's own `org.gnome.Mutter.ScreenCast` service. The host calls `CreateSession`, `RecordVirtual` (`cursor-mode` 2 = metadata, `is-platform`) and `Start`, waits for the `PipeWireStreamAdded` signal and captures that node from the user's PipeWire daemon (no portal, no dialog). Mutter sizes the virtual monitor from the PipeWire format negotiation, so the capture offers exactly the wanted size and a fixed maximum frame rate (`maxFramerate`, which becomes the refresh rate of the monitor) instead of ranges (`fixed_mode` in `pw.rs`; `framerate` itself stays a range), and the host reads the result back from `org.gnome.Mutter.DisplayConfig.GetCurrentState` once the format is known. The monitor appears in `DisplayConfig` only after the stream connects, and Mutter places it to the right of the existing ones. Mutter does not remember the layout of a virtual monitor (it stores layouts by physical monitor, and each virtual one has a new serial), so `gnome_layout.rs` saves the layout to `$XDG_STATE_HOME/ezdisplay/gnome-layouts.json` when the session ends and applies it again with `ApplyMonitorsConfig` when the monitor comes back with the same mode next to the same physical monitors. Without the ScreenCast service on the bus (or to capture an existing monitor) the host falls back to the portal. +- GNOME: Mutter's own `org.gnome.Mutter.ScreenCast` service. The host calls `CreateSession`, `RecordVirtual` (`cursor-mode` 2 = metadata, `is-platform`) and `Start`, waits for the `PipeWireStreamAdded` signal and captures that node from the user's PipeWire daemon (no portal, no dialog). Mutter sizes the virtual monitor from the PipeWire format negotiation, so the capture offers exactly the wanted size and a fixed maximum frame rate (`maxFramerate`, which becomes the refresh rate of the monitor) instead of ranges (`fixed_mode` in `pw.rs`; `framerate` itself stays a range), and the host reads the result back from `org.gnome.Mutter.DisplayConfig.GetCurrentState` once the format is known. The monitor appears in `DisplayConfig` only after the stream connects, and Mutter places it to the right of the existing ones. Mutter does not remember the layout of a virtual monitor (it stores layouts by physical monitor, and each virtual one has a new serial), so `gnome_layout.rs` saves the layout to `$XDG_STATE_HOME/ezdisplay/gnome-layouts.json` when the session ends and applies it again with `ApplyMonitorsConfig` when the monitor comes back with the same mode next to the same physical monitors. Without the ScreenCast service on the bus (or to capture an existing monitor) the host falls back to the portal. While the lock screen is shown GNOME Shell closes every screen cast and refuses new ones (`Session creation inhibited`); the host asks `org.gnome.ScreenSaver.GetActive` before opening a session and when a capture fails, and ends the session with `Bye` reason `screen-locked` (`SourceError::ScreenLocked`) so the client can wait for the unlock. - Sway: `sway.rs` speaks i3-ipc over `$SWAYSOCK` (a 6-byte magic, the payload length, the message type, both native-endian `u32`, then the payload). It runs `create_output`, finds the new output by diffing `GET_OUTPUTS`, sets `mode --custom WxH@HzHz` and reads the geometry back; dropping the guard runs `output NAME unplug`. The host sets no `position`: an explicit position marks the output as configured and sway moves the user's unconfigured outputs behind it, whereas the new output is placed to the right on its own. The monitor kind captures an existing output. - Hyprland: `hyprland.rs` sends one command per connection to `$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/.socket.sock` and reads the reply to EOF. It picks a free name, runs `output create headless ezdisplay-N`, applies `keyword monitor NAME,WxH@HZ,auto,1`, reads `j/monitors` and removes the output with `output remove` on drop. Only the JSON parsing and command building are tested; Hyprland could not be run headless. - wlroots capture (`wl_capture.rs`): direct Wayland capture instead of PipeWire, as `FrameSource::Wayland { output }`. It prefers `ext-image-copy-capture-v1` with `ext-output-image-capture-source-v1` and a second session on the pointer (`create_pointer_cursor_session`) that feeds the `CursorSink`, so the cursor is drawn locally like on KDE and GNOME. It falls back to `zwlr_screencopy_manager_v1` with `overlay_cursor=1`, which paints the cursor into the frames (no cursor data is sent). `EZD_WL_CAPTURE=ext|wlr|auto` forces a choice. Buffers are `wl_shm` only; DMA-BUF import is not implemented, so frames are copied once and encoded through the shared-memory path. The thread publishes into the same one-slot mailbox as `pw.rs` (`pw::Shared`), so `LinuxSource` treats both through one `Capture` enum. diff --git a/docs/protocol.md b/docs/protocol.md index 96666e9..c97c9ee 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -367,6 +367,12 @@ Cursor messages may arrive any time after `StreamConfig`; a client must tolerate before its first video frame. Handshake messages are answered within a few seconds or the peer gives up (the host uses 10 s per step). +`Bye.reason` is free text, except for one well-known value: `screen-locked` +(`ezd_proto::BYE_SCREEN_LOCKED`). The host sends it when its desktop is locked and cannot be captured +until it is unlocked (GNOME Shell closes every screen cast while the lock screen is shown). A client +should say so and retry slowly instead of reconnecting at once; a client that does not know the value +just shows the text. + ### Negotiation (`ezd_proto::negotiate`) * Codec: H.264 unless the preferences ask for another codec and both sides support it From 9f08af16114838a71d19921d16521a6a4361d55d Mon Sep 17 00:00:00 2001 From: FacuM Date: Tue, 17 Nov 2026 13:40:31 -0300 Subject: [PATCH 2/6] Wait for the lock to be reported and keep the locked message on retries The lock check now runs before both the Mutter and the portal path, and a failed capture waits up to three seconds for GNOME to report the lock, because the shell inhibits capture before its screen saver turns active. Other providers answer at once. On the tablet a retry no longer replaces the locked message with the connecting text, and a session that ran over Wi-Fi retries over Wi-Fi. --- .../com/librestatic/ezdisplay/MainActivity.kt | 5 ++- crates/ezd-host-linux/src/gnome.rs | 34 ++++++++++++++----- crates/ezd-host-linux/src/provider.rs | 5 +-- crates/ezd-host-linux/src/source.rs | 18 +++++----- 4 files changed, 42 insertions(+), 20 deletions(-) diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index c445d97..becb704 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -650,7 +650,8 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. bufH = 0 fitSurface() frameRateSet = 0 - setStatus( + // A retry while the host is locked keeps the locked message up. + if (HostLock.showsProgress(hostLocked)) setStatus( when (route) { Route.ACCESSORY -> getString(R.string.status_usb_connecting) Route.WIFI -> getString(R.string.status_wifi_connecting, hostLabel(choice!!)) @@ -968,6 +969,8 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. // The host is fine, only its screen is locked: retry at a fixed, slow pace and leave the // Wi-Fi record and the backoff alone. setStatus(message) + // The retry goes over the same route: without this a Wi-Fi session would retry on loopback. + tryWifiNext = wasWifi scheduleConnect(LOCKED_RETRY_MS) return } diff --git a/crates/ezd-host-linux/src/gnome.rs b/crates/ezd-host-linux/src/gnome.rs index 2420d41..d80194f 100644 --- a/crates/ezd-host-linux/src/gnome.rs +++ b/crates/ezd-host-linux/src/gnome.rs @@ -30,6 +30,8 @@ const STREAM_IFACE: &str = "org.gnome.Mutter.ScreenCast.Stream"; const CURSOR_METADATA: u32 = 2; const STREAM_TIMEOUT: Duration = Duration::from_secs(10); const SETTLE_TIMEOUT: Duration = Duration::from_secs(3); +/// How often the lock state is asked again while waiting for it. +const LOCK_POLL: Duration = Duration::from_millis(150); /// Provider for Mutter. #[derive(Default)] @@ -135,10 +137,6 @@ fn log_locked() { impl GnomeProvider { fn open_mutter(&mut self) -> Result { let conn = map_zbus("connect", Connection::session())?; - if screen_locked(&conn) { - log_locked(); - return Err(SourceError::ScreenLocked); - } let before = gnome_dc::get_state(&conn).ok(); let sc = map_zbus("proxy", Proxy::new(&conn, SERVICE, ROOT, SERVICE))?; let path: OwnedObjectPath = map_open( @@ -227,6 +225,11 @@ impl VirtualOutputProvider for GnomeProvider { fn open(&mut self, req: &OutputRequest) -> Result { self.watch = None; + // Both paths are refused while the screen is locked: say so before asking for a session. + if self.screen_locked(Duration::ZERO) { + log_locked(); + return Err(SourceError::ScreenLocked); + } if req.kind == SourceKind::Virtual && backend::probe_bus().mutter { self.open_mutter() } else { @@ -237,10 +240,25 @@ impl VirtualOutputProvider for GnomeProvider { } } - fn screen_locked(&self) -> bool { - match &self.watch { - Some((conn, _)) => screen_locked(conn), - None => Connection::session().is_ok_and(|c| screen_locked(&c)), + fn screen_locked(&self, wait: Duration) -> bool { + let conn = match &self.watch { + Some((conn, _)) => conn.clone(), + None => match Connection::session() { + Ok(conn) => conn, + Err(_) => return false, + }, + }; + // GNOME Shell inhibits capture when the lock screen starts to appear and reports the + // screen saver active only after its animation, so a negative answer is asked again. + let deadline = Instant::now() + wait; + loop { + if screen_locked(&conn) { + return true; + } + if Instant::now() >= deadline { + return false; + } + std::thread::sleep(LOCK_POLL); } } diff --git a/crates/ezd-host-linux/src/provider.rs b/crates/ezd-host-linux/src/provider.rs index 1b97a9c..bc52d55 100644 --- a/crates/ezd-host-linux/src/provider.rs +++ b/crates/ezd-host-linux/src/provider.rs @@ -72,8 +72,9 @@ pub trait VirtualOutputProvider: Send { None } - /// Whether the desktop is locked and refuses capture. - fn screen_locked(&self) -> bool { + /// Whether the desktop is locked and refuses capture. A desktop that reports the lock a + /// moment after it closes the capture waits up to `wait` for it; the others answer at once. + fn screen_locked(&self, _wait: std::time::Duration) -> bool { false } } diff --git a/crates/ezd-host-linux/src/source.rs b/crates/ezd-host-linux/src/source.rs index 3827ea0..4ae360b 100644 --- a/crates/ezd-host-linux/src/source.rs +++ b/crates/ezd-host-linux/src/source.rs @@ -80,19 +80,19 @@ fn hdr_mismatch(expected: bool, actual: bool) -> Option<&'static str> { } /// The error for a capture that failed: [`SourceError::ScreenLocked`] when the desktop is locked, -/// which closes the stream. The stream can close a moment before the screen saver reports -/// active, so a negative answer is checked once more. Only called on the error path. +/// which closes the stream. The stream can close before the desktop reports the lock, so the +/// provider may wait for it. Only called on the error path. fn capture_error(provider: &dyn VirtualOutputProvider, e: String) -> SourceError { - if provider.screen_locked() { - return SourceError::ScreenLocked; + if provider.screen_locked(LOCK_SETTLE) { + SourceError::ScreenLocked + } else { + SourceError::msg(e) } - std::thread::sleep(Duration::from_millis(300)); - if provider.screen_locked() { - return SourceError::ScreenLocked; - } - SourceError::msg(e) } +/// How long a failed capture waits for the desktop to report that it is locked. +const LOCK_SETTLE: Duration = Duration::from_secs(3); + /// Linux capture + encode source, generic over the compositor's output provider. pub struct LinuxSource { provider: Box, From 11f0259f54b90d35e351d336d4e848978b03efa3 Mon Sep 17 00:00:00 2001 From: FacuM Date: Tue, 17 Nov 2026 13:56:11 -0300 Subject: [PATCH 3/6] Bound the lock probe and keep the locked message over other notices The lock probe runs on its own thread with a one-second limit, connection included, so a shell that does not answer cannot hold up the capture error. On the tablet a successful start during a locked retry puts the locked message back, and input notices wait until the host is unlocked. --- .../com/librestatic/ezdisplay/MainActivity.kt | 15 ++++++---- crates/ezd-host-linux/src/gnome.rs | 30 +++++++++++++------ 2 files changed, 30 insertions(+), 15 deletions(-) diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index becb704..bace849 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -650,12 +650,13 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. bufH = 0 fitSurface() frameRateSet = 0 - // A retry while the host is locked keeps the locked message up. - if (HostLock.showsProgress(hostLocked)) setStatus( - when (route) { - Route.ACCESSORY -> getString(R.string.status_usb_connecting) - Route.WIFI -> getString(R.string.status_wifi_connecting, hostLabel(choice!!)) - Route.TCP -> getString(R.string.status_waiting, "$HOST:$PORT") + // A retry while the host is locked keeps the locked message up (and puts it back after a failed start). + setStatus( + when { + !HostLock.showsProgress(hostLocked) -> getString(R.string.status_host_locked) + route == Route.ACCESSORY -> getString(R.string.status_usb_connecting) + route == Route.WIFI -> getString(R.string.status_wifi_connecting, hostLabel(choice!!)) + else -> getString(R.string.status_waiting, "$HOST:$PORT") }, ) } @@ -932,6 +933,8 @@ class MainActivity : ComponentActivity(), SurfaceHolder.Callback, Choreographer. telemetryView.visibility = if (telemetryOn) View.VISIBLE else View.GONE if (telemetryOn) showTelemetry(j) hostLacksKeys = !j.isNull("input_caps") && (j.optInt("input_caps") and 8) == 0 + // Input notices wait until the host is unlocked: the locked message stays up. + if (!HostLock.showsProgress(hostLocked)) return val note = if (j.isNull("input_note")) "" else j.optString("input_note") if (note != lastInputNote) { lastInputNote = note diff --git a/crates/ezd-host-linux/src/gnome.rs b/crates/ezd-host-linux/src/gnome.rs index d80194f..7276bdc 100644 --- a/crates/ezd-host-linux/src/gnome.rs +++ b/crates/ezd-host-linux/src/gnome.rs @@ -32,6 +32,8 @@ const STREAM_TIMEOUT: Duration = Duration::from_secs(10); const SETTLE_TIMEOUT: Duration = Duration::from_secs(3); /// How often the lock state is asked again while waiting for it. const LOCK_POLL: Duration = Duration::from_millis(150); +/// How long one lock probe may take, connection included. +const LOCK_PROBE_TIMEOUT: Duration = Duration::from_secs(1); /// Provider for Mutter. #[derive(Default)] @@ -117,11 +119,27 @@ fn screen_locked(conn: &Connection) -> bool { .unwrap_or(false) } +/// [`screen_locked`] on `conn` (or a new session connection) with a bound on the whole probe: +/// a shell that does not answer in time counts as not locked, so the caller is never held up. +fn probe_locked(conn: Option) -> bool { + let (tx, rx) = std::sync::mpsc::channel(); + let spawned = std::thread::Builder::new() + .name("lock-probe".into()) + .spawn(move || { + let locked = match conn { + Some(conn) => screen_locked(&conn), + None => Connection::session().is_ok_and(|c| screen_locked(&c)), + }; + let _ = tx.send(locked); + }); + spawned.is_ok() && rx.recv_timeout(LOCK_PROBE_TIMEOUT).unwrap_or(false) +} + /// Like [`map_zbus`] for the calls that open a session: a refusal while the screen is locked /// becomes [`SourceError::ScreenLocked`]. fn map_open(conn: &Connection, what: &str, r: zbus::Result) -> Result { r.map_err(|e| { - if is_inhibited(&e.to_string()) || screen_locked(conn) { + if is_inhibited(&e.to_string()) || probe_locked(Some(conn.clone())) { log_locked(); SourceError::ScreenLocked } else { @@ -241,18 +259,12 @@ impl VirtualOutputProvider for GnomeProvider { } fn screen_locked(&self, wait: Duration) -> bool { - let conn = match &self.watch { - Some((conn, _)) => conn.clone(), - None => match Connection::session() { - Ok(conn) => conn, - Err(_) => return false, - }, - }; + let conn = self.watch.as_ref().map(|(conn, _)| conn.clone()); // GNOME Shell inhibits capture when the lock screen starts to appear and reports the // screen saver active only after its animation, so a negative answer is asked again. let deadline = Instant::now() + wait; loop { - if screen_locked(&conn) { + if probe_locked(conn.clone()) { return true; } if Instant::now() >= deadline { From 2e27702686f4abe25f72cc32ecfa4570d9a668b7 Mon Sep 17 00:00:00 2001 From: FacuM Date: Tue, 17 Nov 2026 14:11:45 -0300 Subject: [PATCH 4/6] Keep the lock wait inside its deadline and stop after an unanswered probe Each probe is now limited to the time left before the deadline, the pause between probes too, and a probe the shell does not answer ends the wait instead of starting another worker behind it. --- crates/ezd-host-linux/src/gnome.rs | 31 ++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/crates/ezd-host-linux/src/gnome.rs b/crates/ezd-host-linux/src/gnome.rs index 7276bdc..9ff357c 100644 --- a/crates/ezd-host-linux/src/gnome.rs +++ b/crates/ezd-host-linux/src/gnome.rs @@ -120,8 +120,9 @@ fn screen_locked(conn: &Connection) -> bool { } /// [`screen_locked`] on `conn` (or a new session connection) with a bound on the whole probe: -/// a shell that does not answer in time counts as not locked, so the caller is never held up. -fn probe_locked(conn: Option) -> bool { +/// `None` when the shell does not answer within `limit`, so the caller is never held up. The +/// worker of an unanswered probe lives until the call returns; callers stop probing after one. +fn probe_locked(conn: Option, limit: Duration) -> Option { let (tx, rx) = std::sync::mpsc::channel(); let spawned = std::thread::Builder::new() .name("lock-probe".into()) @@ -132,14 +133,17 @@ fn probe_locked(conn: Option) -> bool { }; let _ = tx.send(locked); }); - spawned.is_ok() && rx.recv_timeout(LOCK_PROBE_TIMEOUT).unwrap_or(false) + spawned.ok()?; + rx.recv_timeout(limit).ok() } /// Like [`map_zbus`] for the calls that open a session: a refusal while the screen is locked /// becomes [`SourceError::ScreenLocked`]. fn map_open(conn: &Connection, what: &str, r: zbus::Result) -> Result { r.map_err(|e| { - if is_inhibited(&e.to_string()) || probe_locked(Some(conn.clone())) { + if is_inhibited(&e.to_string()) + || probe_locked(Some(conn.clone()), LOCK_PROBE_TIMEOUT) == Some(true) + { log_locked(); SourceError::ScreenLocked } else { @@ -264,13 +268,24 @@ impl VirtualOutputProvider for GnomeProvider { // screen saver active only after its animation, so a negative answer is asked again. let deadline = Instant::now() + wait; loop { - if probe_locked(conn.clone()) { - return true; + // The first probe gets its full limit; later ones only the time that is left. + let left = deadline.saturating_duration_since(Instant::now()); + let limit = if wait.is_zero() { + LOCK_PROBE_TIMEOUT + } else { + left.min(LOCK_PROBE_TIMEOUT) + }; + match probe_locked(conn.clone(), limit) { + Some(true) => return true, + // An unanswered probe: do not stack more of them behind it. + None => return false, + Some(false) => {} } - if Instant::now() >= deadline { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { return false; } - std::thread::sleep(LOCK_POLL); + std::thread::sleep(LOCK_POLL.min(left)); } } From 12e89fd08a46e19e3294b0d41b26dd9a9d939dd8 Mon Sep 17 00:00:00 2001 From: FacuM Date: Tue, 17 Nov 2026 14:27:19 -0300 Subject: [PATCH 5/6] Keep at most one lock probe outstanding A probe that the shell has not answered yet blocks new ones, so repeated connection attempts against an unresponsive D-Bus do not accumulate worker threads. --- crates/ezd-host-linux/src/gnome.rs | 71 +++++++++++++++++++++++++----- 1 file changed, 61 insertions(+), 10 deletions(-) diff --git a/crates/ezd-host-linux/src/gnome.rs b/crates/ezd-host-linux/src/gnome.rs index 9ff357c..89f8479 100644 --- a/crates/ezd-host-linux/src/gnome.rs +++ b/crates/ezd-host-linux/src/gnome.rs @@ -17,6 +17,7 @@ use crate::provider::{FrameSource, OpenedOutput, OutputRequest, VirtualOutputPro use crate::pw::Target; use ezd_host_core::{DisplayMode, OutputInfo, SourceError}; use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, mpsc}; use std::time::{Duration, Instant}; use zbus::blocking::{Connection, Proxy}; @@ -119,24 +120,44 @@ fn screen_locked(conn: &Connection) -> bool { .unwrap_or(false) } -/// [`screen_locked`] on `conn` (or a new session connection) with a bound on the whole probe: -/// `None` when the shell does not answer within `limit`, so the caller is never held up. The -/// worker of an unanswered probe lives until the call returns; callers stop probing after one. -fn probe_locked(conn: Option, limit: Duration) -> Option { +/// Set while a lock probe has not returned yet, so unanswered probes never pile up. +static LOCK_PROBE_BUSY: AtomicBool = AtomicBool::new(false); + +/// Runs `call` on a worker thread and waits up to `limit` for its answer. `None` when it does not +/// answer in time, or when an earlier call guarded by `busy` is still unanswered: then no new +/// worker is started, so at most one is ever outstanding per flag. +fn bounded( + busy: &'static AtomicBool, + limit: Duration, + call: impl FnOnce() -> T + Send + 'static, +) -> Option { + if busy.swap(true, Ordering::AcqRel) { + return None; + } let (tx, rx) = std::sync::mpsc::channel(); let spawned = std::thread::Builder::new() .name("lock-probe".into()) .spawn(move || { - let locked = match conn { - Some(conn) => screen_locked(&conn), - None => Connection::session().is_ok_and(|c| screen_locked(&c)), - }; - let _ = tx.send(locked); + let answer = call(); + busy.store(false, Ordering::Release); + let _ = tx.send(answer); }); - spawned.ok()?; + if spawned.is_err() { + busy.store(false, Ordering::Release); + return None; + } rx.recv_timeout(limit).ok() } +/// [`screen_locked`] on `conn` (or a new session connection) with a bound on the whole probe: +/// `None` when the shell does not answer within `limit`, so the caller is never held up. +fn probe_locked(conn: Option, limit: Duration) -> Option { + bounded(&LOCK_PROBE_BUSY, limit, move || match conn { + Some(conn) => screen_locked(&conn), + None => Connection::session().is_ok_and(|c| screen_locked(&c)), + }) +} + /// Like [`map_zbus`] for the calls that open a session: a refusal while the screen is locked /// becomes [`SourceError::ScreenLocked`]. fn map_open(conn: &Connection, what: &str, r: zbus::Result) -> Result { @@ -378,6 +399,36 @@ mod tests { use ezd_host_core::{CursorSink, PlatformOptions, VideoSource}; use ezd_proto::{Codec, StreamConfig}; + #[test] + fn unanswered_probes_do_not_pile_up() { + static BUSY: AtomicBool = AtomicBool::new(false); + static STARTED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let (release, held) = mpsc::channel::<()>(); + let stuck = move || { + STARTED.fetch_add(1, Ordering::SeqCst); + let _ = held.recv(); + true + }; + assert_eq!(bounded(&BUSY, Duration::from_millis(20), stuck), None); + // While the first call is unanswered, further probes start no worker. + for _ in 0..5 { + let probe = || { + STARTED.fetch_add(1, Ordering::SeqCst); + true + }; + assert_eq!(bounded(&BUSY, Duration::from_millis(20), probe), None); + } + assert_eq!(STARTED.load(Ordering::SeqCst), 1); + + // Once it returns, probing works again. + release.send(()).unwrap(); + let deadline = Instant::now() + Duration::from_secs(5); + while BUSY.load(Ordering::Acquire) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(bounded(&BUSY, Duration::from_secs(5), || true), Some(true)); + } + #[test] fn inhibited_refusals_are_recognised() { assert!(is_inhibited("Session creation inhibited")); From 2509bc5478af6ec3838d911687cc31c5e4814f5b Mon Sep 17 00:00:00 2001 From: FacuM Date: Tue, 17 Nov 2026 14:41:41 -0300 Subject: [PATCH 6/6] Wait for the stuck probe to start before counting workers in the test --- crates/ezd-host-linux/src/gnome.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/ezd-host-linux/src/gnome.rs b/crates/ezd-host-linux/src/gnome.rs index 89f8479..e4ecdd9 100644 --- a/crates/ezd-host-linux/src/gnome.rs +++ b/crates/ezd-host-linux/src/gnome.rs @@ -404,12 +404,16 @@ mod tests { static BUSY: AtomicBool = AtomicBool::new(false); static STARTED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); let (release, held) = mpsc::channel::<()>(); + let (running, started) = mpsc::channel::<()>(); let stuck = move || { STARTED.fetch_add(1, Ordering::SeqCst); + let _ = running.send(()); let _ = held.recv(); true }; assert_eq!(bounded(&BUSY, Duration::from_millis(20), stuck), None); + // The worker may be scheduled late: wait until it runs before counting. + started.recv_timeout(Duration::from_secs(5)).unwrap(); // While the first call is unanswered, further probes start no worker. for _ in 0..5 { let probe = || {