From b4e51a58f6d5a83ebdba2838391af908ba2d4486 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20M=C3=A4user?= Date: Thu, 5 Nov 2026 16:17:19 +0100 Subject: [PATCH] Explain locks with a desktop notification after unlock After locking, wait for the session to come back (logind Unlock, ScreenSaver ActiveChanged, or a new session after re-login) and post a notification saying the phone left Bluetooth range and how long ago. On by default, off with unlock_notice = false. Hidden test-notice subcommand exercises the path without a real lock. --- README.md | 1 + config.toml.example | 4 ++ src/config.rs | 6 ++ src/main.rs | 12 ++++ src/scanner/bluez.rs | 6 ++ src/unlock_notice.rs | 160 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 189 insertions(+) create mode 100644 src/unlock_notice.rs diff --git a/README.md b/README.md index 697a6af..ad5284b 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,7 @@ See `config.toml.example`; every knob is documented there. Highlights: | `presence_timeout_secs`| 15 | how fresh an update must be to count | | `rssi_floor` / `rssi_lock` | -90/-80 | discovery floor / out-of-range threshold | | `duty.*` | see file| per-state scan window/interval | +| `unlock_notice` | true | desktop notification after unlock explaining the lock | ## Power notes diff --git a/config.toml.example b/config.toml.example index 4cc9b3a..692c276 100644 --- a/config.toml.example +++ b/config.toml.example @@ -43,5 +43,9 @@ interval_ms = 30000 # Optional: command to run instead of `loginctl lock-session`. #lock_command = "swaylock -f" +# Optional: show a desktop notification after unlocking that explains the +# screen was locked because the phone left Bluetooth range. +#unlock_notice = true + # Optional: log lock actions instead of executing them (for testing). #dry_run = false diff --git a/src/config.rs b/src/config.rs index 1355557..ee4de4a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -9,6 +9,9 @@ fn presence_timeout_secs() -> u64 { fn missing_after_secs() -> u64 { 30 } +fn unlock_notice() -> bool { + true +} fn rssi_floor() -> i16 { -90 } @@ -89,6 +92,9 @@ pub struct Config { /// Log lock actions instead of executing them. #[serde(default)] pub dry_run: bool, + /// Show a desktop notification after unlock explaining the lock. + #[serde(default = "unlock_notice")] + pub unlock_notice: bool, } impl Config { diff --git a/src/main.rs b/src/main.rs index b1b83a9..ec92715 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,6 +2,7 @@ mod config; mod locker; mod policy; mod scanner; +mod unlock_notice; use anyhow::{Context, Result}; use clap::{Parser, Subcommand}; @@ -29,6 +30,10 @@ enum Command { Run, /// List paired Bluetooth devices and exit ListPaired, + /// Wait for the session to unlock and show the lock explanation + /// notification (for testing the unlock notice path) + #[command(hide = true)] + TestNotice, } #[tokio::main] @@ -55,6 +60,13 @@ async fn main() -> Result<()> { Ok(()) } Command::Run => run(cli).await, + Command::TestNotice => { + unlock_notice::notify_after_unlock( + std::time::Instant::now() - std::time::Duration::from_secs(300), + ) + .await; + Ok(()) + } } } diff --git a/src/scanner/bluez.rs b/src/scanner/bluez.rs index b7c2808..1a4c2e8 100644 --- a/src/scanner/bluez.rs +++ b/src/scanner/bluez.rs @@ -163,6 +163,12 @@ pub async fn run(cfg: Config) -> Result<()> { Ok(()) => { info!("screen locked"); policy.mark_locked(); + if cfg.unlock_notice && !cfg.dry_run { + let locked_at = Instant::now(); + tokio::spawn( + crate::unlock_notice::notify_after_unlock(locked_at), + ); + } } Err(e) => error!("locking the screen failed: {e:#}"), } diff --git a/src/unlock_notice.rs b/src/unlock_notice.rs new file mode 100644 index 0000000..f1d4260 --- /dev/null +++ b/src/unlock_notice.rs @@ -0,0 +1,160 @@ +use anyhow::{Context, Result}; +use std::collections::HashMap; +use std::time::{Duration, Instant}; +use tokio_stream::StreamExt; +use tracing::{debug, info}; +use zbus::message::Type as MsgType; +use zbus::zvariant::Value; +use zbus::{MatchRule, MessageStream, Proxy}; + +const NOTIF_SERVICE: &str = "org.freedesktop.Notifications"; +const LOGIN1: &str = "org.freedesktop.login1"; + +/// After locking, wait for the session to become unlocked again and show a +/// desktop notification explaining why the screen was locked. Unlock shows +/// up through several channels depending on desktop and login style; the +/// first one wins: +/// - logind Session.Unlock (loginctl unlock-session, GNOME/KDE unlock) +/// - ScreenSaver ActiveChanged(false) (org.freedesktop + GNOME variants) +/// - logind Manager.SessionNew (the user logged out and back in, in which +/// case the lock screen never had a chance to report an unlock) +pub async fn notify_after_unlock(locked_at: Instant) { + if let Err(e) = run(locked_at).await { + debug!("unlock notice: {e:#}"); + } +} + +async fn run(locked_at: Instant) -> Result<()> { + let session = zbus::Connection::session() + .await + .context("connecting to the session D-Bus")?; + let system = zbus::Connection::system() + .await + .context("connecting to the system D-Bus")?; + + let rule = |path: &'static str, iface: &'static str, + member: &'static str| + -> zbus::Result> { + Ok(MatchRule::builder() + .msg_type(MsgType::Signal) + .path(path)? + .interface(iface)? + .member(member)? + .build()) + }; + let mut freedesktop_unlock = MessageStream::for_match_rule( + rule( + "/org/freedesktop/ScreenSaver", + "org.freedesktop.ScreenSaver", + "ActiveChanged", + )?, + &session, + None, + ) + .await?; + let mut gnome_unlock = MessageStream::for_match_rule( + rule( + "/org/gnome/ScreenSaver", + "org.gnome.ScreenSaver", + "ActiveChanged", + )?, + &session, + None, + ) + .await?; + let mut logind_unlock = MessageStream::for_match_rule( + MatchRule::builder() + .msg_type(MsgType::Signal) + .sender(LOGIN1)? + .path_namespace("/org/freedesktop/login1/session")? + .interface("org.freedesktop.login1.Session")? + .member("Unlock")? + .build(), + &system, + None, + ) + .await?; + let mut new_session = MessageStream::for_match_rule( + MatchRule::builder() + .msg_type(MsgType::Signal) + .sender(LOGIN1)? + .path("/org/freedesktop/login1")? + .interface("org.freedesktop.login1.Manager")? + .member("SessionNew")? + .build(), + &system, + None, + ) + .await?; + + // Lock state can persist for days; wait until an unlock shows up. + let deadline = tokio::time::Instant::now() + Duration::from_secs(24 * 3600); + let unlocked = loop { + tokio::select! { + Some(Ok(m)) = freedesktop_unlock.next() => { + if reports_unlocked(&m) { + break true; + } + } + Some(Ok(m)) = gnome_unlock.next() => { + if reports_unlocked(&m) { + break true; + } + } + Some(Ok(_)) = logind_unlock.next() => break true, + Some(Ok(_)) = new_session.next() => break true, + _ = tokio::time::sleep_until(deadline) => break false, + } + }; + if !unlocked { + return Ok(()); + } + + show(locked_at.elapsed()).await +} + +/// ScreenSaver ActiveChanged carries the new active (locked) state; the +/// unlock notice is what we are waiting for. +fn reports_unlocked(msg: &zbus::Message) -> bool { + matches!(msg.body().deserialize::<(bool,)>(), Ok((false,))) +} + +async fn show(locked_for: Duration) -> Result<()> { + let conn = zbus::Connection::session() + .await + .context("connecting to the session D-Bus")?; + let proxy = Proxy::new(&conn, NOTIF_SERVICE, "/org/freedesktop/Notifications", NOTIF_SERVICE).await?; + let body = format!( + "Your phone left Bluetooth range. The screen was locked {} ago.", + describe(locked_for) + ); + proxy + .call::<_, _, u32>( + "Notify", + &( + "btle-proximity", + 0u32, + "bluetooth", + "Screen locked", + body, + Vec::::new(), + HashMap::::new(), + 15_000i32, + ), + ) + .await + .context("calling org.freedesktop.Notifications.Notify")?; + info!("unlock notice shown"); + Ok(()) +} + +fn describe(d: Duration) -> String { + let mins = d.as_secs() / 60; + if mins < 1 { + "less than a minute".to_owned() + } else if mins < 60 { + format!("{mins} minute{}", if mins == 1 { "" } else { "s" }) + } else { + format!("{} h {} min", mins / 60, mins % 60) + } +}