mirror of
https://github.com/VallierDev/uu-remote-linux.git
synced 2026-11-16 16:50:41 +01:00
fix(portal): capture the lock screen on locked cold connections (#229)
* fix(portal): capture the lock screen on locked cold connections KWin keeps the Portal screencast alive while the session is locked, but maintain() refused to open a session until unlock, so a cold connection only received synthetic black frames. Allow capture during lock on KDE and keep the black-frame fallback for compositors that close the session. A consent failure behind the lock screen and auto privacy now wait for the local unlock. * docs: document the KDE lock-screen capture default Cover the new default, the UU_LOCKED_CAPTURE opt-out and the desktop-detection fallback in both READMEs, as requested in #229.
This commit is contained in:
1 parent
ff2bd9c582
commit
661263fe37
5 files changed
+245
-31
No files matched your search
+199
-25
@@ -1,6 +1,6 @@
|
||||
//! Portal availability is independent of the authenticated CONTROL transport.
|
||||
use std::future::Future;
|
||||
use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
|
||||
use std::sync::{Arc, OnceLock, atomic::{AtomicBool, Ordering}};
|
||||
use std::time::Instant;
|
||||
use tokio::sync::{watch, Mutex};
|
||||
use crate::{capture::ScreenCapture, input::DesktopInputSession};
|
||||
@@ -29,6 +29,7 @@ pub struct PortalDesktop {
|
||||
state: watch::Sender<State>,
|
||||
opening: Arc<Mutex<()>>,
|
||||
locked: watch::Receiver<Option<bool>>,
|
||||
capture_while_locked: bool,
|
||||
}
|
||||
|
||||
struct CancelOnDrop(Arc<AtomicBool>);
|
||||
@@ -71,6 +72,7 @@ enum AttemptOutcome {
|
||||
Ready(Arc<ScreenCapture>),
|
||||
Retry(String),
|
||||
Terminal(String),
|
||||
Deferred,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
@@ -85,14 +87,52 @@ fn classify(result: Result<Arc<ScreenCapture>, PortalError>) -> AttemptOutcome {
|
||||
}
|
||||
}
|
||||
|
||||
/// A consent dialog opened behind the lock screen cannot be approved, so its denied/timed-out
|
||||
/// error must not end this connection's supervisor: ask again after the local unlock.
|
||||
fn defer_consent(error: &PortalError, state: Option<bool>) -> bool {
|
||||
state == Some(true) && matches!(error.code, 4 | 5)
|
||||
}
|
||||
|
||||
/// True when this iteration sees a lock state it has not attempted under yet. Waking and resetting
|
||||
/// the retry delay must happen once per transition, not once per 200 ms poll: a locked state would
|
||||
/// otherwise re-run wake, inhibitor and publish on every tick and defeat the 5 s retry backoff.
|
||||
fn fresh_state(previous: Option<Option<bool>>, state: Option<bool>) -> bool {
|
||||
previous != Some(state)
|
||||
}
|
||||
|
||||
fn should_prepare_power(healthy: bool, force_wake: bool) -> bool {
|
||||
!healthy || force_wake
|
||||
}
|
||||
|
||||
/// KWin keeps the Portal screencast, including the lock screen, alive while the session is
|
||||
/// locked, so a cold connection can show the real lock screen. Mutter closes the session on
|
||||
/// lock, so other desktops keep the existing black-frame path. `UU_LOCKED_CAPTURE=0` opts out.
|
||||
fn capture_while_locked() -> bool {
|
||||
static ENABLED: OnceLock<bool> = OnceLock::new();
|
||||
*ENABLED.get_or_init(|| {
|
||||
match std::env::var("UU_LOCKED_CAPTURE").ok().filter(|value| !value.is_empty()) {
|
||||
Some(value) => !matches!(value.to_ascii_lowercase().as_str(), "0" | "off" | "false" | "no"),
|
||||
None => ["XDG_CURRENT_DESKTOP", "XDG_SESSION_DESKTOP"].iter().any(|key|
|
||||
std::env::var(key).is_ok_and(|desktop| desktop.split(':')
|
||||
.any(|part| part.eq_ignore_ascii_case("KDE")))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Capture may start and continue in this lock state. An unknown state keeps the old wait on
|
||||
/// desktops whose compositor closes the session on lock.
|
||||
fn attempt_allowed(state: Option<bool>, capture_while_locked: bool) -> bool {
|
||||
match state {
|
||||
Some(false) => true,
|
||||
Some(true) | None => capture_while_locked,
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_attempt<W, I>(
|
||||
cancelled: &AtomicBool,
|
||||
owner: &DesktopInputSession,
|
||||
locked: &watch::Receiver<Option<bool>>,
|
||||
allow_locked: bool,
|
||||
wake: W,
|
||||
inhibit: I,
|
||||
) -> Option<AttemptPrep>
|
||||
@@ -102,7 +142,7 @@ where
|
||||
{
|
||||
let current = || !cancelled.load(Ordering::Acquire)
|
||||
&& owner.is_current()
|
||||
&& *locked.borrow() == Some(false);
|
||||
&& attempt_allowed(*locked.borrow(), allow_locked);
|
||||
if !current() { return None; }
|
||||
let wake = wake();
|
||||
if !current() { return None; }
|
||||
@@ -114,7 +154,8 @@ where
|
||||
impl PortalDesktop {
|
||||
pub fn new(screen: Arc<ScreenCapture>) -> Self {
|
||||
Self { state: watch::channel(State { waiting: screen.init_error.is_some(), screen }).0,
|
||||
opening: Arc::new(Mutex::new(())), locked: crate::session_lock::watch_locked() }
|
||||
opening: Arc::new(Mutex::new(())), locked: crate::session_lock::watch_locked(),
|
||||
capture_while_locked: capture_while_locked() }
|
||||
}
|
||||
pub fn begin(&self) {
|
||||
// GNOME closes the Portal session on lock; a cached screen with a dead session
|
||||
@@ -133,10 +174,21 @@ impl PortalDesktop {
|
||||
}
|
||||
pub fn subscribe(&self) -> watch::Receiver<State> { self.state.subscribe() }
|
||||
pub fn lock_state(&self) -> watch::Receiver<Option<bool>> { self.locked.clone() }
|
||||
/// Whether capture may run in this lock state for this desktop. Shares the rule used by
|
||||
/// maintain(), so capture-setting requests do not stall behind a lock the compositor does
|
||||
/// not honor.
|
||||
pub fn capture_allowed(&self, locked: Option<bool>) -> bool {
|
||||
attempt_allowed(locked, self.capture_while_locked)
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn with_lock_state(screen: Arc<ScreenCapture>, locked: watch::Receiver<Option<bool>>) -> Self {
|
||||
Self::with_lock_state_and_capture(screen, locked, false)
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn with_lock_state_and_capture(screen: Arc<ScreenCapture>, locked: watch::Receiver<Option<bool>>,
|
||||
capture_while_locked: bool) -> Self {
|
||||
Self { state: watch::channel(State { waiting: screen.init_error.is_some(), screen }).0,
|
||||
opening: Arc::new(Mutex::new(())), locked }
|
||||
opening: Arc::new(Mutex::new(())), locked, capture_while_locked }
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn publish_test_screen(&self, screen: Arc<ScreenCapture>) {
|
||||
@@ -204,22 +256,27 @@ impl PortalDesktop {
|
||||
let inhibit = Arc::new(inhibit);
|
||||
let open = Arc::new(open);
|
||||
let mut locked = self.locked.clone();
|
||||
let mut previous = None;
|
||||
let allow_locked = self.capture_while_locked;
|
||||
let mut previous: Option<Option<bool>> = None;
|
||||
let mut defer_until_unlock = false;
|
||||
let mut retry_at = Instant::now();
|
||||
loop {
|
||||
if !owner.is_current() { return Ok(()); }
|
||||
let state = *locked.borrow_and_update();
|
||||
if state != Some(false) {
|
||||
if previous == Some(false) { self.pause(&owner); }
|
||||
} else {
|
||||
// A fresh unlocked transition gets an immediate wake/recovery attempt.
|
||||
let force_wake = previous != Some(false);
|
||||
if state == Some(false) { defer_until_unlock = false; }
|
||||
if state != Some(false) && previous == Some(Some(false)) { self.pause(&owner); }
|
||||
if state == Some(true) && previous != Some(Some(true)) && allow_locked {
|
||||
log::info!("Desktop is locked; opening Portal capture for the lock screen");
|
||||
}
|
||||
if attempt_allowed(state, allow_locked) && !defer_until_unlock {
|
||||
// A fresh transition into an attempted state gets an immediate wake/recovery attempt.
|
||||
let force_wake = fresh_state(previous, state);
|
||||
if force_wake { retry_at = Instant::now(); }
|
||||
let mut attempt_locked = locked.clone();
|
||||
let outcome = tokio::select! {
|
||||
biased;
|
||||
_ = wait_for_lock(&mut locked) => AttemptOutcome::Cancelled,
|
||||
outcome = self.portal_attempt(&owner, &mut attempt_locked, retry_at, force_wake, wake.clone(), inhibit.clone(), open.clone()) => outcome,
|
||||
_ = wait_for_lock(&mut locked, allow_locked) => AttemptOutcome::Cancelled,
|
||||
outcome = self.portal_attempt(&owner, &mut attempt_locked, allow_locked, retry_at, force_wake, wake.clone(), inhibit.clone(), open.clone()) => outcome,
|
||||
};
|
||||
match outcome {
|
||||
AttemptOutcome::Ready(screen) => self.publish(&owner, screen),
|
||||
@@ -228,11 +285,12 @@ impl PortalDesktop {
|
||||
log::warn!("Portal desktop recovery deferred: {error}");
|
||||
retry_at = Instant::now() + std::time::Duration::from_secs(5);
|
||||
}
|
||||
AttemptOutcome::Deferred => { defer_until_unlock = true; }
|
||||
AttemptOutcome::Cancelled => {}
|
||||
}
|
||||
if *locked.borrow_and_update() != Some(false) { self.pause(&owner); }
|
||||
if !attempt_allowed(*locked.borrow_and_update(), allow_locked) { self.pause(&owner); }
|
||||
}
|
||||
previous = *locked.borrow_and_update();
|
||||
previous = Some(*locked.borrow_and_update());
|
||||
tokio::select! {
|
||||
_ = locked.changed() => {},
|
||||
_ = tokio::time::sleep(std::time::Duration::from_millis(200)) => {},
|
||||
@@ -241,20 +299,20 @@ impl PortalDesktop {
|
||||
}
|
||||
|
||||
async fn portal_attempt<W, I, O>(&self, owner: &Arc<DesktopInputSession>,
|
||||
locked: &mut watch::Receiver<Option<bool>>, retry_at: Instant, force_wake: bool,
|
||||
locked: &mut watch::Receiver<Option<bool>>, allow_locked: bool, retry_at: Instant, force_wake: bool,
|
||||
wake: Arc<W>, inhibit: Arc<I>, open: Arc<O>) -> AttemptOutcome
|
||||
where
|
||||
W: Fn() -> Result<(), String> + Send + Sync + 'static,
|
||||
I: Fn() -> IdleGuard + Send + Sync + 'static,
|
||||
O: Fn(Arc<ScreenCapture>, Arc<AtomicBool>) -> Result<Arc<ScreenCapture>, PortalError> + Send + Sync + 'static,
|
||||
{
|
||||
if !owner.is_current() || *locked.borrow() != Some(false) || Instant::now() < retry_at {
|
||||
if !owner.is_current() || !attempt_allowed(*locked.borrow(), allow_locked) || Instant::now() < retry_at {
|
||||
return AttemptOutcome::Cancelled;
|
||||
}
|
||||
let gate = self.opening.clone().lock_owned().await;
|
||||
// The state can change while this attempt waits for an earlier worker
|
||||
// to finish rotating the Portal permission token.
|
||||
if !owner.is_current() || *locked.borrow() != Some(false) {
|
||||
if !owner.is_current() || !attempt_allowed(*locked.borrow(), allow_locked) {
|
||||
return AttemptOutcome::Cancelled;
|
||||
}
|
||||
let screen = self.snapshot().screen;
|
||||
@@ -271,6 +329,7 @@ impl PortalDesktop {
|
||||
&prep_cancel,
|
||||
&prep_owner,
|
||||
&prep_locked,
|
||||
allow_locked,
|
||||
|| (*wake)(),
|
||||
|| (*inhibit)(),
|
||||
)).await {
|
||||
@@ -282,7 +341,7 @@ impl PortalDesktop {
|
||||
// Held by the cancellable async helper, not the blocking worker, so a
|
||||
// lock transition releases it while worker cleanup may still be running.
|
||||
let _inhibitor = prep.inhibitor;
|
||||
if !owner.is_current() || *locked.borrow() != Some(false) {
|
||||
if !owner.is_current() || !attempt_allowed(*locked.borrow(), allow_locked) {
|
||||
return AttemptOutcome::Cancelled;
|
||||
}
|
||||
// A new controller can arrive while the cached Portal handle is alive
|
||||
@@ -298,19 +357,25 @@ impl PortalDesktop {
|
||||
}
|
||||
open(screen, worker_cancel)
|
||||
}).await;
|
||||
if !owner.is_current() || *locked.borrow() != Some(false) {
|
||||
if !owner.is_current() || !attempt_allowed(*locked.borrow(), allow_locked) {
|
||||
return AttemptOutcome::Cancelled;
|
||||
}
|
||||
match result {
|
||||
Ok(Err(error)) if defer_consent(&error, *locked.borrow()) => {
|
||||
// The consent dialog opened behind the lock screen cannot be approved here.
|
||||
// Keep this connection alive and ask again after the local unlock.
|
||||
log::info!("Portal consent is behind the lock screen; waiting for the local unlock");
|
||||
AttemptOutcome::Deferred
|
||||
}
|
||||
Ok(result) => classify(result),
|
||||
Err(_) => AttemptOutcome::Terminal("Portal initialization worker failed".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_lock(locked: &mut watch::Receiver<Option<bool>>) {
|
||||
async fn wait_for_lock(locked: &mut watch::Receiver<Option<bool>>, allow_locked: bool) {
|
||||
while locked.changed().await.is_ok() {
|
||||
if *locked.borrow_and_update() != Some(false) { return; }
|
||||
if !attempt_allowed(*locked.borrow_and_update(), allow_locked) { return; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -441,19 +506,19 @@ mod tests {
|
||||
let wakes = AtomicUsize::new(0);
|
||||
let inhibitors = AtomicUsize::new(0);
|
||||
let cancelled = AtomicBool::new(true);
|
||||
assert!(prepare_attempt(&cancelled, &owner, &locked,
|
||||
assert!(prepare_attempt(&cancelled, &owner, &locked, false,
|
||||
|| { wakes.fetch_add(1, Ordering::Relaxed); Ok(()) },
|
||||
|| { inhibitors.fetch_add(1, Ordering::Relaxed); IdleGuard::default() }).is_none());
|
||||
assert_eq!(wakes.load(Ordering::Relaxed), 0);
|
||||
cancelled.store(false, Ordering::Release);
|
||||
lock.send(Some(true)).unwrap();
|
||||
assert!(prepare_attempt(&cancelled, &owner, &locked,
|
||||
assert!(prepare_attempt(&cancelled, &owner, &locked, false,
|
||||
|| { wakes.fetch_add(1, Ordering::Relaxed); Ok(()) },
|
||||
|| { inhibitors.fetch_add(1, Ordering::Relaxed); IdleGuard::default() }).is_none());
|
||||
assert_eq!(wakes.load(Ordering::Relaxed), 0);
|
||||
lock.send(Some(false)).unwrap();
|
||||
let locked_during_wake = lock.clone();
|
||||
assert!(prepare_attempt(&cancelled, &owner, &locked,
|
||||
assert!(prepare_attempt(&cancelled, &owner, &locked, false,
|
||||
|| {
|
||||
wakes.fetch_add(1, Ordering::Relaxed);
|
||||
locked_during_wake.send(Some(true)).unwrap();
|
||||
@@ -464,7 +529,7 @@ mod tests {
|
||||
assert_eq!(inhibitors.load(Ordering::Relaxed), 0);
|
||||
lock.send(Some(false)).unwrap();
|
||||
let replacement = input.desktop_session();
|
||||
assert!(prepare_attempt(&cancelled, &owner, &locked,
|
||||
assert!(prepare_attempt(&cancelled, &owner, &locked, false,
|
||||
|| { wakes.fetch_add(1, Ordering::Relaxed); Ok(()) },
|
||||
|| { inhibitors.fetch_add(1, Ordering::Relaxed); IdleGuard::default() }).is_none());
|
||||
assert_eq!(wakes.load(Ordering::Relaxed), 1);
|
||||
@@ -479,6 +544,115 @@ mod tests {
|
||||
drop(guard);
|
||||
assert!(flag.load(Ordering::Acquire));
|
||||
}
|
||||
#[test]
|
||||
fn locked_capture_gate_follows_the_compositor_rule() {
|
||||
assert!(attempt_allowed(Some(false), false));
|
||||
assert!(!attempt_allowed(Some(true), false));
|
||||
assert!(!attempt_allowed(None, false));
|
||||
assert!(attempt_allowed(Some(true), true));
|
||||
assert!(attempt_allowed(None, true));
|
||||
}
|
||||
#[test]
|
||||
fn wake_and_retry_reset_once_per_lock_transition() {
|
||||
assert!(fresh_state(None, Some(true)));
|
||||
assert!(!fresh_state(Some(Some(true)), Some(true)));
|
||||
assert!(fresh_state(Some(Some(true)), Some(false)));
|
||||
assert!(!fresh_state(Some(Some(false)), Some(false)));
|
||||
assert!(fresh_state(Some(Some(true)), None));
|
||||
assert!(!fresh_state(Some(None), None));
|
||||
}
|
||||
#[test]
|
||||
fn consent_failures_are_deferred_only_while_locked() {
|
||||
for code in [4, 5] {
|
||||
assert!(defer_consent(&PortalError { code }, Some(true)));
|
||||
assert!(!defer_consent(&PortalError { code }, Some(false)));
|
||||
assert!(!defer_consent(&PortalError { code }, None));
|
||||
}
|
||||
assert!(!defer_consent(&PortalError { code: 8 }, Some(true)));
|
||||
assert!(!defer_consent(&PortalError { code: 13 }, Some(true)));
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn wait_for_lock_ends_on_a_lock_the_compositor_does_not_honor() {
|
||||
use std::time::Duration;
|
||||
let (lock, mut locked) = watch::channel(Some(false));
|
||||
let mut task = tokio::spawn(async move { wait_for_lock(&mut locked, false).await; });
|
||||
lock.send(Some(true)).unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(1), &mut task).await
|
||||
.expect("lock must end the wait").unwrap();
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn wait_for_lock_ignores_lock_changes_when_capture_is_allowed() {
|
||||
use std::time::Duration;
|
||||
let (lock, mut locked) = watch::channel(Some(false));
|
||||
let mut task = tokio::spawn(async move { wait_for_lock(&mut locked, true).await; });
|
||||
lock.send(Some(true)).unwrap();
|
||||
assert!(tokio::time::timeout(Duration::from_millis(100), &mut task).await.is_err(),
|
||||
"lock cancelled an allowed wait");
|
||||
lock.send(None).unwrap();
|
||||
assert!(tokio::time::timeout(Duration::from_millis(100), &mut task).await.is_err(),
|
||||
"unknown lock cancelled an allowed wait");
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
}
|
||||
#[test]
|
||||
fn locked_attempt_is_allowed_when_the_compositor_keeps_the_stream() {
|
||||
let input = Arc::new(crate::input::InputInjector::without_desktop());
|
||||
let owner = input.desktop_session();
|
||||
let (lock, locked) = watch::channel(Some(true));
|
||||
let cancelled = AtomicBool::new(false);
|
||||
let wakes = AtomicUsize::new(0);
|
||||
assert!(prepare_attempt(&cancelled, &owner, &locked, true,
|
||||
|| { wakes.fetch_add(1, Ordering::Relaxed); Ok(()) },
|
||||
|| IdleGuard::default()).is_some());
|
||||
lock.send(None).unwrap();
|
||||
assert!(prepare_attempt(&cancelled, &owner, &locked, true,
|
||||
|| { wakes.fetch_add(1, Ordering::Relaxed); Ok(()) },
|
||||
|| IdleGuard::default()).is_some());
|
||||
assert_eq!(wakes.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn locked_capture_keeps_the_attempt_running() {
|
||||
use std::time::Duration;
|
||||
let (lock, locked) = watch::channel(Some(false));
|
||||
let host = Arc::new(PortalDesktop::with_lock_state_and_capture(
|
||||
Arc::new(ScreenCapture::unavailable("pending".into())), locked, true));
|
||||
let input = Arc::new(crate::input::InputInjector::without_desktop());
|
||||
let owner = input.desktop_session();
|
||||
let releases = Arc::new(AtomicUsize::new(0));
|
||||
let worker_release = Arc::new(AtomicBool::new(false));
|
||||
let (started, mut started_rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
let task = tokio::spawn({
|
||||
let host = host.clone();
|
||||
let owner = owner.clone();
|
||||
let releases = releases.clone();
|
||||
let worker_release = worker_release.clone();
|
||||
async move {
|
||||
host.maintain_with(owner,
|
||||
|| Ok(()),
|
||||
move || IdleGuard(Some(Inhibitor::Fake(DropSignal(releases.clone())))),
|
||||
move |screen, cancel| {
|
||||
let _ = started.send(());
|
||||
while !worker_release.load(Ordering::Acquire) && !cancel.load(Ordering::Acquire) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
if cancel.load(Ordering::Acquire) { return Err(PortalError { code: 13 }); }
|
||||
Ok(screen)
|
||||
}).await
|
||||
}
|
||||
});
|
||||
started_rx.recv().await.unwrap();
|
||||
lock.send(Some(true)).unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
assert_eq!(releases.load(Ordering::Relaxed), 0, "lock released a compositor-backed attempt");
|
||||
worker_release.store(true, Ordering::Release);
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
|
||||
while host.snapshot().waiting {
|
||||
assert!(tokio::time::Instant::now() < deadline, "locked attempt did not publish");
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn lock_transition_cancels_blocked_attempt_and_releases_inhibitor() {
|
||||
let (lock, locked) = watch::channel(Some(false));
|
||||
|
||||
@@ -12,7 +12,7 @@ mod record;
|
||||
mod tool;
|
||||
|
||||
pub use mode::Mode;
|
||||
use std::sync::{atomic::{AtomicBool, Ordering}, Mutex};
|
||||
use std::sync::{atomic::{AtomicBool, AtomicU64, Ordering}, Mutex};
|
||||
|
||||
struct Active { mode: Mode, record: Option<record::Record> }
|
||||
struct State { sessions: usize, active: Option<Active> }
|
||||
@@ -25,6 +25,9 @@ static POINTER: Mutex<Option<[f64; 4]>> = Mutex::new(None);
|
||||
/// ends. An auto-enable never overrides it, including an RPC that arrives after the connection
|
||||
/// opens but before `session_started` bumps the counter.
|
||||
static VIEWER_OVERRIDE: AtomicBool = AtomicBool::new(false);
|
||||
/// Bumped when a new first desktop session spawns its auto-enable thread. A reconnect that beats
|
||||
/// the 500 ms poll would otherwise leave the old waiter running for up to five minutes.
|
||||
static AUTO_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
/// iOS viewers encode "screen off" as `enable=0, type=3`, and Windows viewers carry every request
|
||||
/// in `type` with `enable=0`; see `protocol::Request::normalize_ios_screen_off` and
|
||||
/// `protocol::Request::normalize_windows`.
|
||||
@@ -182,10 +185,42 @@ fn auto_set(mode: Mode) -> Result<bool, String> {
|
||||
if result.is_err() { if let Err(e) = leave(&mut state) { log::warn!("Privacy rollback failed: {e}"); } }
|
||||
result.map(|_| true)
|
||||
}
|
||||
/// The watch is authoritative while it has a value. A None (the logind monitor lost the session)
|
||||
/// must not fail open: ask logind directly before covering a possibly locked desktop.
|
||||
fn currently_locked() -> bool {
|
||||
let locked = crate::session_lock::watch_locked();
|
||||
let state = *locked.borrow();
|
||||
match state {
|
||||
Some(state) => state,
|
||||
None => crate::session_lock::locked_now() == Some(true),
|
||||
}
|
||||
}
|
||||
/// The capture session and the viewer's CONTROL state need a moment after the peer connects;
|
||||
/// retry while the portal session is still missing, and let the viewer's RPC 7 win if it arrives.
|
||||
fn auto_enable(mode: Mode) {
|
||||
fn auto_enable(mode: Mode, generation: u64) {
|
||||
// A locked desktop is already covered. Switching the share to the virtual output would hide
|
||||
// the lock screen the viewer needs to unlock, so wait for the local unlock first. Bounded:
|
||||
// a viewer that never unlocks, or leaves, must not hold this thread forever.
|
||||
let current = || AUTO_GENERATION.load(Ordering::Acquire) == generation;
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300);
|
||||
while currently_locked() {
|
||||
if !current() { return; }
|
||||
if VIEWER_OVERRIDE.load(Ordering::Relaxed) {
|
||||
log::info!("Privacy auto: skipped, the viewer already chose a mode");
|
||||
return;
|
||||
}
|
||||
if STATE.try_lock().is_ok_and(|state| state.sessions == 0) {
|
||||
log::info!("Privacy auto: skipped, the desktop session ended");
|
||||
return;
|
||||
}
|
||||
if std::time::Instant::now() >= deadline {
|
||||
log::info!("Privacy auto: desktop stayed locked; not covering it");
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(500));
|
||||
}
|
||||
for attempt in 1..=5 {
|
||||
if !current() { return; }
|
||||
if VIEWER_OVERRIDE.load(Ordering::Relaxed) {
|
||||
log::info!("Privacy auto: skipped, the viewer already chose a mode");
|
||||
return;
|
||||
@@ -215,9 +250,10 @@ pub fn session_started() {
|
||||
let first = STATE.lock().ok().is_some_and(|mut s| { s.sessions += 1; s.sessions == 1 });
|
||||
let Some(mode) = auto else { return };
|
||||
if !first { return; }
|
||||
let generation = AUTO_GENERATION.fetch_add(1, Ordering::AcqRel) + 1;
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(std::time::Duration::from_millis(1500));
|
||||
auto_enable(mode);
|
||||
auto_enable(mode, generation);
|
||||
});
|
||||
}
|
||||
pub fn session_ended() {
|
||||
|
||||
+1
-1
@@ -712,7 +712,7 @@ impl WebRtcSession {
|
||||
}
|
||||
let live = state.screen.init_error.is_none()
|
||||
&& (cfg!(test) || state.screen.portal.as_ref().is_some_and(|portal| portal.is_alive()))
|
||||
&& *manager.lock_state().borrow() == Some(false);
|
||||
&& manager.capture_allowed(*manager.lock_state().borrow());
|
||||
if live { break Some(state.screen); }
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
if channel.upgrade().is_none_or(|channel| channel.ready_state() != webrtc::data_channel::data_channel_state::RTCDataChannelState::Open) { return; }
|
||||
|
||||
Reference in new issue
Block a user