capri-perception: add awareness module
This commit is contained in:
1 file changed
+379
@@ -0,0 +1,379 @@
|
||||
//! Metadata-only desktop awareness (`capri_linux/awareness.py`): foreground app
|
||||
//! (process name, pid, fullscreen), idle/return, lock, suspend and session end. Never titles,
|
||||
//! screenshots, accessible text or audio; Capri's own pid is ignored; nothing is persisted.
|
||||
//!
|
||||
//! Sources: KDE — a persistent KWin script (`windowActivated`, `fullScreenChanged`) +
|
||||
//! `org.freedesktop.ScreenSaver` (lock, idle ms); i3/X11 — i3 IPC `window` events and a 1 s
|
||||
//! `_NET_ACTIVE_WINDOW` poll, MIT-SCREEN-SAVER idle, logind `Lock`/`Unlock`; both — logind
|
||||
//! `PrepareForSleep`/`PrepareForShutdown`.
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use futures::StreamExt;
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{json, Value};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use x11rb::protocol::xproto::{AtomEnum, ConnectionExt as _};
|
||||
|
||||
use crate::i3::{self, I3};
|
||||
use crate::platform::{process, Desktop, X11};
|
||||
|
||||
pub const IDLE_MS: u64 = 300_000;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Kind {
|
||||
AppForeground { process_name: String, process_id: u32, fullscreen: bool },
|
||||
UserIdle,
|
||||
UserReturn,
|
||||
SessionLock,
|
||||
SessionUnlock,
|
||||
PowerSuspend,
|
||||
PowerResume,
|
||||
SessionEnding,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
Self::AppForeground { .. } => "app.foreground",
|
||||
Self::UserIdle => "user.idle",
|
||||
Self::UserReturn => "user.return",
|
||||
Self::SessionLock => "session.lock",
|
||||
Self::SessionUnlock => "session.unlock",
|
||||
Self::PowerSuspend => "power.suspend",
|
||||
Self::PowerResume => "power.resume",
|
||||
Self::SessionEnding => "session.ending",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Event {
|
||||
pub id: String,
|
||||
pub timestamp: i64,
|
||||
pub kind: Kind,
|
||||
}
|
||||
|
||||
impl Event {
|
||||
pub fn new(kind: Kind) -> Self {
|
||||
Self { id: uuid::Uuid::new_v4().to_string(), timestamp: crate::now_ms(), kind }
|
||||
}
|
||||
|
||||
/// Capri envelope (schema v1). The process name is lower-cased, <= 80, no control chars.
|
||||
pub fn to_json(&self) -> Value {
|
||||
let mut v = json!({"schemaVersion": 1, "source": "windows-events", "id": self.id, "timestamp": self.timestamp, "confidence": 1, "kind": self.kind.name()});
|
||||
if let Kind::AppForeground { process_name, process_id, fullscreen } = &self.kind {
|
||||
v["processName"] = json!(process_name);
|
||||
v["processId"] = json!(process_id);
|
||||
v["fullscreen"] = json!(fullscreen);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// `validateObservation`: fresh (<= 30 s), bounded id and name.
|
||||
pub fn valid(&self, now: i64) -> bool {
|
||||
let name_ok = match &self.kind {
|
||||
Kind::AppForeground { process_name, .. } => process_name.len() <= 80 && !process_name.chars().any(char::is_control),
|
||||
_ => true,
|
||||
};
|
||||
self.id.len() <= 80 && (now - self.timestamp).abs() <= 30_000 && name_ok
|
||||
}
|
||||
}
|
||||
|
||||
pub fn foreground_event(pid: u32, fullscreen: bool) -> Event {
|
||||
let name: String = process::name(pid).to_lowercase().chars().filter(|c| !c.is_control()).take(80).collect();
|
||||
Event::new(Kind::AppForeground { process_name: name, process_id: pid, fullscreen })
|
||||
}
|
||||
|
||||
/// Deduplicates foreground changes: only a new window or fullscreen flag emits.
|
||||
#[derive(Default)]
|
||||
pub struct ForegroundFilter {
|
||||
last: Option<(String, bool)>,
|
||||
ignored: Vec<u32>,
|
||||
}
|
||||
|
||||
impl ForegroundFilter {
|
||||
pub fn new(ignored: Vec<u32>) -> Self {
|
||||
Self { last: None, ignored }
|
||||
}
|
||||
|
||||
pub fn update(&mut self, window: &str, pid: u32, fullscreen: bool) -> Option<Event> {
|
||||
if pid == 0 || pid == std::process::id() || self.ignored.contains(&pid) {
|
||||
return None;
|
||||
}
|
||||
let key = (window.to_string(), fullscreen);
|
||||
if self.last.as_ref() == Some(&key) {
|
||||
return None;
|
||||
}
|
||||
self.last = Some(key);
|
||||
Some(foreground_event(pid, fullscreen))
|
||||
}
|
||||
|
||||
/// Unlock and resume re-emit the current foreground.
|
||||
pub fn reset(&mut self) {
|
||||
self.last = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Idle edge detector at 300 s.
|
||||
#[derive(Default)]
|
||||
pub struct IdleEdge(bool);
|
||||
|
||||
impl IdleEdge {
|
||||
pub fn update(&mut self, idle_ms: u64) -> Option<Event> {
|
||||
let idle = idle_ms >= IDLE_MS;
|
||||
(idle != self.0).then(|| {
|
||||
self.0 = idle;
|
||||
Event::new(if idle { Kind::UserIdle } else { Kind::UserReturn })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Persistent KWin script: pid, id and fullscreen of the active window, never its caption.
|
||||
pub const AWARENESS_SCRIPT: &str = r#"
|
||||
function report(w){ if(!w) return;
|
||||
callDBus("%NAME%","/","org.capri.Report","Report","%TAG%\n" + JSON.stringify({type:"foreground",
|
||||
pid:w.pid, id:String(w.internalId), fullScreen:w.fullScreen})); }
|
||||
workspace.windowActivated.connect(w=>{ report(w); if(w){ w.fullScreenChanged.connect(()=>{ if(workspace.activeWindow===w) report(w); }); } });
|
||||
workspace.screensChanged.connect(()=>callDBus("%NAME%","/","org.capri.Report","Report","%TAG%\n" + '{"type":"topology"}'));
|
||||
report(workspace.activeWindow);
|
||||
"#;
|
||||
const AWARENESS_PLUGIN: &str = "capri-awareness";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Status {
|
||||
Off,
|
||||
Starting,
|
||||
Active,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// Running awareness: events arrive on the receiver given by [`Awareness::start`].
|
||||
pub struct Awareness {
|
||||
cancel: CancellationToken,
|
||||
status: Arc<Mutex<Status>>,
|
||||
foreground: Arc<Mutex<Option<(String, bool)>>>,
|
||||
desktop: Desktop,
|
||||
}
|
||||
|
||||
impl Awareness {
|
||||
/// Starts all sources (15 s startup bound). `ignored`: extra pids to ignore (<= 10).
|
||||
/// Topology changes arrive as `None` (screen policy must call `topology_changed`).
|
||||
pub async fn start(desktop: Desktop, ignored: Vec<u32>) -> Result<(Self, mpsc::UnboundedReceiver<Option<Event>>)> {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let me = Self { cancel: CancellationToken::new(), status: Arc::new(Mutex::new(Status::Starting)), foreground: Arc::default(), desktop: desktop.clone() };
|
||||
let filter = Arc::new(Mutex::new(ForegroundFilter::new(ignored.into_iter().take(10).collect())));
|
||||
let started = tokio::time::timeout(Duration::from_secs(15), me.spawn_sources(tx, filter)).await;
|
||||
match started {
|
||||
Ok(Ok(())) => *me.status.lock() = Status::Active,
|
||||
_ => {
|
||||
*me.status.lock() = Status::Failed;
|
||||
me.cancel.cancel();
|
||||
bail!("Desktop event observation stopped. Basic conversation is still available.");
|
||||
}
|
||||
}
|
||||
Ok((me, rx))
|
||||
}
|
||||
|
||||
pub fn status(&self) -> Value {
|
||||
json!({"status": *self.status.lock(), "active": *self.status.lock() == Status::Active, "capturesImages": false, "capturesTitles": false})
|
||||
}
|
||||
|
||||
/// Latest foreground process name and fullscreen flag (metadata only).
|
||||
pub fn foreground(&self) -> Option<(String, bool)> {
|
||||
self.foreground.lock().clone()
|
||||
}
|
||||
|
||||
pub async fn stop(&self) {
|
||||
self.cancel.cancel();
|
||||
*self.status.lock() = Status::Off;
|
||||
if let Desktop::Kde(k) = &self.desktop {
|
||||
k.unload(AWARENESS_PLUGIN).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn spawn_sources(&self, tx: mpsc::UnboundedSender<Option<Event>>, filter: Arc<Mutex<ForegroundFilter>>) -> Result<()> {
|
||||
let cancel = self.cancel.clone();
|
||||
let fg = self.foreground.clone();
|
||||
let emit = {
|
||||
let tx = tx.clone();
|
||||
move |e: Event| {
|
||||
if let Kind::AppForeground { process_name, fullscreen, .. } = &e.kind {
|
||||
*fg.lock() = Some((process_name.clone(), *fullscreen));
|
||||
}
|
||||
let _ = tx.send(Some(e));
|
||||
}
|
||||
};
|
||||
let emit = Arc::new(emit);
|
||||
session_signals(cancel.clone(), emit.clone(), filter.clone()).await?;
|
||||
match &self.desktop {
|
||||
Desktop::Kde(kwin) => {
|
||||
let mut reports = kwin.persistent(AWARENESS_PLUGIN, AWARENESS_SCRIPT).await?;
|
||||
let (filter, emit2, tx, cancel2) = (filter.clone(), emit.clone(), tx.clone(), cancel.clone());
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let report = tokio::select! { _ = cancel2.cancelled() => break, r = reports.recv() => r };
|
||||
let Some(report) = report else { break };
|
||||
let Ok(v) = serde_json::from_str::<Value>(&report) else { continue };
|
||||
if v["type"] == "topology" {
|
||||
let _ = tx.send(None);
|
||||
} else if let Some(e) = filter.lock().update(v["id"].as_str().unwrap_or(""), v["pid"].as_u64().unwrap_or(0) as u32, v["fullScreen"] == true) {
|
||||
emit2(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
let conn = kwin.connection().clone();
|
||||
spawn_idle(cancel.clone(), emit, move || {
|
||||
let conn = conn.clone();
|
||||
async move {
|
||||
let ms: u32 = conn.call_method(Some("org.freedesktop.ScreenSaver"), "/ScreenSaver", Some("org.freedesktop.ScreenSaver"), "GetSessionIdleTime", &()).await.ok()?.body().deserialize().ok()?;
|
||||
Some(ms as u64) // KDE reports milliseconds
|
||||
}
|
||||
});
|
||||
}
|
||||
Desktop::X11(x) => {
|
||||
let (x, filter2, emit2, cancel2) = (x.clone(), filter.clone(), emit.clone(), cancel.clone());
|
||||
tokio::spawn(async move {
|
||||
while !cancel2.is_cancelled() {
|
||||
if let Some((w, pid, full)) = active_window(&x)
|
||||
&& let Some(e) = filter2.lock().update(&w.to_string(), pid, full)
|
||||
{
|
||||
emit2(e);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
});
|
||||
if let Ok(mut ipc) = I3::connect().await
|
||||
&& ipc.subscribe(&["window", "output"]).await.is_ok()
|
||||
{
|
||||
let (x, filter, emit3, tx, cancel3) = (self.x11().unwrap(), filter.clone(), emit.clone(), tx.clone(), cancel.clone());
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let ev = tokio::select! { _ = cancel3.cancelled() => break, e = ipc.next_event() => e };
|
||||
let Ok((kind, v)) = ev else { break };
|
||||
if kind == i3::EVENT_OUTPUT {
|
||||
let _ = tx.send(None);
|
||||
} else if kind == i3::EVENT_WINDOW && matches!(v["change"].as_str(), Some("focus" | "fullscreen_mode")) {
|
||||
let window = v["container"]["window"].as_u64().unwrap_or(0) as u32;
|
||||
if v["container"]["focused"] == true
|
||||
&& let Some(e) = filter.lock().update(&window.to_string(), x.pid_of(window), v["container"]["fullscreen_mode"].as_i64().unwrap_or(0) != 0)
|
||||
{
|
||||
emit3(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let x = self.x11().unwrap();
|
||||
spawn_idle(cancel.clone(), emit, move || {
|
||||
let x = x.clone();
|
||||
async move {
|
||||
use x11rb::protocol::screensaver::ConnectionExt as _;
|
||||
Some(x.conn.screensaver_query_info(x.root).ok()?.reply().ok()?.ms_since_user_input as u64)
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn x11(&self) -> Option<Arc<X11>> {
|
||||
match &self.desktop {
|
||||
Desktop::X11(x) => Some(x.clone()),
|
||||
Desktop::Kde(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `_NET_ACTIVE_WINDOW` → (window, pid, fullscreen).
|
||||
fn active_window(x: &X11) -> Option<(u32, u32, bool)> {
|
||||
let active = x.atom("_NET_ACTIVE_WINDOW").ok()?;
|
||||
let window = x.conn.get_property(false, x.root, active, AtomEnum::WINDOW, 0, 1).ok()?.reply().ok()?.value32()?.next().filter(|w| *w != 0)?;
|
||||
let state = x.atom("_NET_WM_STATE").ok()?;
|
||||
let full = x.atom("_NET_WM_STATE_FULLSCREEN").ok()?;
|
||||
let fullscreen = x.conn.get_property(false, window, state, AtomEnum::ATOM, 0, 32).ok()?.reply().ok()?.value32().is_some_and(|mut v| v.any(|a| a == full));
|
||||
Some((window, x.pid_of(window), fullscreen))
|
||||
}
|
||||
|
||||
fn spawn_idle<F, Fut>(cancel: CancellationToken, emit: Arc<impl Fn(Event) + Send + Sync + 'static>, probe: F)
|
||||
where
|
||||
F: Fn() -> Fut + Send + 'static,
|
||||
Fut: std::future::Future<Output = Option<u64>> + Send,
|
||||
{
|
||||
tokio::spawn(async move {
|
||||
let mut edge = IdleEdge::default();
|
||||
while !cancel.is_cancelled() {
|
||||
if let Some(e) = probe().await.and_then(|ms| edge.update(ms)) {
|
||||
emit(e);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn session_signals(cancel: CancellationToken, emit: Arc<impl Fn(Event) + Send + Sync + 'static>, filter: Arc<Mutex<ForegroundFilter>>) -> Result<()> {
|
||||
let session = zbus::Connection::session().await?;
|
||||
let system = zbus::Connection::system().await?;
|
||||
let rule = |iface: &'static str, member: &'static str| -> Result<zbus::MatchRule<'static>> { Ok(zbus::MatchRule::builder().msg_type(zbus::message::Type::Signal).interface(iface)?.member(member)?.build()) };
|
||||
let streams = [
|
||||
(zbus::MessageStream::for_match_rule(rule("org.freedesktop.ScreenSaver", "ActiveChanged")?, &session, None).await?, "lock"),
|
||||
(zbus::MessageStream::for_match_rule(rule("org.freedesktop.login1.Manager", "PrepareForSleep")?, &system, None).await?, "sleep"),
|
||||
(zbus::MessageStream::for_match_rule(rule("org.freedesktop.login1.Manager", "PrepareForShutdown")?, &system, None).await?, "shutdown"),
|
||||
(zbus::MessageStream::for_match_rule(rule("org.freedesktop.login1.Session", "Lock")?, &system, None).await?, "l1lock"),
|
||||
(zbus::MessageStream::for_match_rule(rule("org.freedesktop.login1.Session", "Unlock")?, &system, None).await?, "l1unlock"),
|
||||
];
|
||||
for (mut stream, what) in streams {
|
||||
let (cancel, emit, filter) = (cancel.clone(), emit.clone(), filter.clone());
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let msg = tokio::select! { _ = cancel.cancelled() => break, m = stream.next() => m };
|
||||
let Some(Ok(msg)) = msg else { break };
|
||||
let flag = msg.body().deserialize::<bool>().unwrap_or(true);
|
||||
let kind = match (what, flag) {
|
||||
("lock", true) | ("l1lock", _) => Kind::SessionLock,
|
||||
("lock", false) | ("l1unlock", _) => Kind::SessionUnlock,
|
||||
("sleep", true) => Kind::PowerSuspend,
|
||||
("sleep", false) => Kind::PowerResume,
|
||||
("shutdown", true) => Kind::SessionEnding,
|
||||
_ => continue,
|
||||
};
|
||||
if matches!(kind, Kind::SessionUnlock | Kind::PowerResume) {
|
||||
filter.lock().reset();
|
||||
}
|
||||
emit(Event::new(kind));
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn filters_and_edges() {
|
||||
let mut f = ForegroundFilter::new(vec![42]);
|
||||
let me = std::process::id();
|
||||
assert!(f.update("1", me, false).is_none(), "own pid ignored");
|
||||
assert!(f.update("1", 42, false).is_none(), "configured pid ignored");
|
||||
let e = f.update("1", 1, false).unwrap();
|
||||
assert!(matches!(e.kind, Kind::AppForeground { process_id: 1, fullscreen: false, .. }));
|
||||
assert!(f.update("1", 1, false).is_none());
|
||||
assert!(f.update("1", 1, true).is_some(), "fullscreen change emits");
|
||||
f.reset();
|
||||
assert!(f.update("1", 1, true).is_some());
|
||||
let j = e.to_json();
|
||||
assert_eq!((j["schemaVersion"].clone(), j["kind"].clone(), j.get("title")), (json!(1), json!("app.foreground"), None));
|
||||
assert!(e.valid(e.timestamp + 1000) && !e.valid(e.timestamp + 31_000));
|
||||
let mut idle = IdleEdge::default();
|
||||
assert!(idle.update(1000).is_none());
|
||||
assert_eq!(idle.update(IDLE_MS).unwrap().kind, Kind::UserIdle);
|
||||
assert!(idle.update(IDLE_MS + 5).is_none());
|
||||
assert_eq!(idle.update(10).unwrap().kind, Kind::UserReturn);
|
||||
assert!(!AWARENESS_SCRIPT.contains("caption"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user