368 lines
16 KiB
Rust
368 lines
16 KiB
Rust
// Getting the person's attention when a bot needs them (or finished) while they're away.
|
||
//
|
||
// Behaviour spec:
|
||
// - macOS 10.14+ and a real .app bundle: ask UNUserNotificationCenter, waiting at most 3 s.
|
||
// authorizationStatus 0..4 = notDetermined/denied/authorized/provisional/ephemeral (else "unknown");
|
||
// alertSetting 0..2 = notSupported/disabled/enabled (else "unknown").
|
||
// - authorized/provisional/ephemeral → granted, denied → denied, notDetermined → undetermined.
|
||
// Banners only when authorized and alerts enabled.
|
||
// - The desktop counts as present only when not locked, not idle for 90 s and the window is
|
||
// alive; re-checked every 10 s.
|
||
|
||
use std::process::{Command, Stdio};
|
||
|
||
/// Away after this much keyboard/mouse silence `Z_e=9e4`).
|
||
pub const IDLE_THRESHOLD_SECS: f64 = 90.0;
|
||
/// How often presence is re-read `uBt=1e4`).
|
||
pub const PRESENCE_POLL_SECS: f64 = 10.0;
|
||
|
||
/// Seconds since the last keyboard or mouse input (macOS `HIDIdleTime`, in nanoseconds).
|
||
pub fn parse_hid_idle(ioreg: &str) -> Option<f64> {
|
||
let line = ioreg.lines().find(|l| l.contains("\"HIDIdleTime\""))?;
|
||
let n: f64 = line.rsplit('=').next()?.trim().parse().ok()?;
|
||
Some(n / 1e9)
|
||
}
|
||
|
||
pub fn system_idle_secs() -> Option<f64> {
|
||
#[cfg(target_os = "linux")]
|
||
return crate::desk::idle_secs();
|
||
#[allow(unreachable_code)]
|
||
if !cfg!(target_os = "macos") {
|
||
return None;
|
||
}
|
||
let out = Command::new("ioreg").args(["-c", "IOHIDSystem", "-d", "4"]).stderr(Stdio::null()).output().ok()?;
|
||
parse_hid_idle(&String::from_utf8_lossy(&out.stdout))
|
||
}
|
||
|
||
/// Notify unless the person is looking at AnyBot right now: the window is in front and they
|
||
/// were active within the last 90 s.
|
||
pub fn should_notify(window_focused: bool, idle_secs: Option<f64>) -> bool {
|
||
!window_focused || idle_secs.map(|s| s >= IDLE_THRESHOLD_SECS).unwrap_or(false)
|
||
}
|
||
|
||
// ---------- applying a new version while you're away ----------
|
||
// Behaviour spec: apply when 自動更新 is on (default) and an update is staged, and the machine
|
||
// is idle: (screen locked || screensaver on) and idle for >= 600 s, and no bot work running.
|
||
// Checks: first 30 s after launch, then every 3600 s plus up to 300 s of random jitter.
|
||
|
||
pub const AUTO_UPDATE_IDLE_SECS: f64 = 600.0;
|
||
pub const UPDATE_FIRST_CHECK_SECS: u64 = 30;
|
||
pub const UPDATE_CHECK_INTERVAL_SECS: u64 = 3600;
|
||
pub const UPDATE_CHECK_JITTER_SECS: u64 = 300;
|
||
|
||
/// Every input of the idle-update rule, in one place.
|
||
pub fn should_apply_update_now(enabled: bool, update_ready: bool, screen_locked: bool, screensaver: bool, idle_secs: Option<f64>, bots_idle: bool) -> bool {
|
||
enabled && update_ready && (screen_locked || screensaver) && idle_secs.map(|s| s >= AUTO_UPDATE_IDLE_SECS).unwrap_or(false) && bots_idle
|
||
}
|
||
|
||
/// The screen is locked (Electron's `getSystemIdleState` "locked"; here the session flag).
|
||
pub fn screen_locked() -> bool {
|
||
if !cfg!(target_os = "macos") {
|
||
// systemd-logind knows when the session is locked.
|
||
let id = std::env::var("XDG_SESSION_ID").unwrap_or_default();
|
||
let mut c = Command::new("loginctl");
|
||
c.arg("show-session");
|
||
if !id.is_empty() {
|
||
c.arg(&id);
|
||
}
|
||
return c.args(["-p", "LockedHint"]).stderr(Stdio::null()).output().map(|o| String::from_utf8_lossy(&o.stdout).trim() == "LockedHint=yes").unwrap_or(false);
|
||
}
|
||
Command::new("ioreg").args(["-n", "Root", "-d1"]).stderr(Stdio::null()).output().map(|o| String::from_utf8_lossy(&o.stdout).contains("\"CGSSessionScreenIsLocked\" = Yes")).unwrap_or(false)
|
||
}
|
||
|
||
/// The screensaver is running: the original's `NRn` runs `pgrep -x ScreenSaverEngine` (2 s timeout).
|
||
pub fn screensaver_active() -> bool {
|
||
#[cfg(target_os = "linux")]
|
||
return crate::desk::screensaver_on();
|
||
#[allow(unreachable_code)]
|
||
if !cfg!(target_os = "macos") {
|
||
return false;
|
||
}
|
||
let Ok(mut c) = Command::new("pgrep").args(["-x", "ScreenSaverEngine"]).stdout(Stdio::null()).stderr(Stdio::null()).spawn() else { return false };
|
||
let start = std::time::Instant::now();
|
||
while start.elapsed() < std::time::Duration::from_secs(2) {
|
||
if let Ok(Some(st)) = c.try_wait() {
|
||
return st.success();
|
||
}
|
||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||
}
|
||
let _ = c.kill();
|
||
let _ = c.wait();
|
||
false
|
||
}
|
||
|
||
/// Next periodic check: one hour plus a random part of five minutes.
|
||
pub fn next_update_check_secs(random_0_1: f64) -> u64 {
|
||
UPDATE_CHECK_INTERVAL_SECS + (random_0_1.clamp(0.0, 1.0) * UPDATE_CHECK_JITTER_SECS as f64).floor() as u64
|
||
}
|
||
|
||
fn applescript_quote(s: &str) -> String {
|
||
let clean: String = s.chars().filter(|c| !c.is_control() || *c == ' ').collect();
|
||
format!("\"{}\"", clean.replace('\\', "\\\\").replace('"', "\\\""))
|
||
}
|
||
|
||
/// The AppleScript line for a banner (title + message), with text safely quoted.
|
||
#[cfg(test)]
|
||
pub fn banner_script(title: &str, body: &str) -> String {
|
||
banner_script_with(title, body, true)
|
||
}
|
||
|
||
/// Same, with or without macOS's own sound (none when AnyBot rings its 提示音 itself).
|
||
pub fn banner_script_with(title: &str, body: &str, sound: bool) -> String {
|
||
let body: String = body.chars().take(180).collect();
|
||
let line = format!("display notification {} with title {}", applescript_quote(&body), applescript_quote(title));
|
||
if sound {
|
||
format!("{line} sound name \"Glass\"")
|
||
} else {
|
||
line
|
||
}
|
||
}
|
||
|
||
/// Show a banner, with the system's sound. Doesn't wait.
|
||
pub fn banner(title: &str, body: &str) {
|
||
banner_for(title, body, true, None)
|
||
}
|
||
|
||
/// A banner about one bot: a click on it opens that bot's chat (`take_clicked`).
|
||
///
|
||
/// - macOS, inside AnyBot.app: the app's own banner (`center`), with AnyBot's icon (the cat on
|
||
/// yellow); a click brings AnyBot to the front on that bot. Run from a build folder (no bundle),
|
||
/// macOS's `display notification` instead (that banner shows Script Editor's icon).
|
||
/// - Linux: the desktop's notification service through notify-send, with AnyBot's icon.
|
||
pub fn banner_for(title: &str, body: &str, sound: bool, bot: Option<u64>) {
|
||
let body: String = body.chars().take(180).collect();
|
||
if !cfg!(target_os = "macos") {
|
||
// The desktop's notification service (GNOME, KDE, XFCE…) through notify-send.
|
||
let mut cmd = Command::new("notify-send");
|
||
cmd.args(["-a", "AnyBot"]);
|
||
if let Some(icon) = icon_png() {
|
||
cmd.arg("-i").arg(icon);
|
||
}
|
||
let _ = crate::computer::spawn_reaped(cmd.args([title, &body]).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()));
|
||
return;
|
||
}
|
||
#[cfg(target_os = "macos")]
|
||
if center::post(title, &body, sound, bot) {
|
||
return;
|
||
}
|
||
let _ = bot;
|
||
let _ = crate::computer::spawn_reaped(Command::new("osascript").arg("-e").arg(banner_script_with(title, &body, sound)).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()));
|
||
}
|
||
|
||
/// One banner from a command (`anybot --banner`): sends it and says which way it went.
|
||
pub fn banner_now(title: &str, body: &str) -> String {
|
||
banner_for(title, body, true, None);
|
||
#[cfg(target_os = "macos")]
|
||
{
|
||
if !center::usable() {
|
||
return "不在 AnyBot.app 裡:用 display notification 送出(圖示會是「工序指令編寫程式」)".into();
|
||
}
|
||
// (A moment for the system to take it before the program ends.)
|
||
std::thread::sleep(std::time::Duration::from_secs(1));
|
||
format!("AnyBot 自己的通知,通知中心裡有 {} 則 AnyBot 的通知", center::delivered())
|
||
}
|
||
#[cfg(not(target_os = "macos"))]
|
||
{
|
||
"notify-send".into()
|
||
}
|
||
}
|
||
|
||
/// Get ready to show banners (macOS: hear clicks on them, and show them while AnyBot is in front
|
||
/// but the person is idle). Call once at start, on the main thread.
|
||
pub fn prepare() {
|
||
#[cfg(target_os = "macos")]
|
||
center::prepare();
|
||
}
|
||
|
||
/// Bots whose banner the person clicked since the last call (the app opens that chat).
|
||
pub fn take_clicked() -> Vec<u64> {
|
||
#[cfg(target_os = "macos")]
|
||
{
|
||
center::take_clicked()
|
||
}
|
||
#[cfg(not(target_os = "macos"))]
|
||
{
|
||
vec![]
|
||
}
|
||
}
|
||
|
||
/// The identifier a banner gets: which bot it is about, and a number so each one is its own.
|
||
pub fn banner_id(bot: Option<u64>, n: u64) -> String {
|
||
format!("anybot-{}-{n}", bot.map(|b| b.to_string()).unwrap_or_else(|| "-".into()))
|
||
}
|
||
|
||
/// The bot a banner identifier is about.
|
||
pub fn bot_of_banner(id: &str) -> Option<u64> {
|
||
id.strip_prefix("anybot-")?.split('-').next()?.parse().ok()
|
||
}
|
||
|
||
/// AnyBot's icon as a PNG file for notify-send (drawn once into the data folder).
|
||
#[cfg_attr(target_os = "macos", allow(dead_code))]
|
||
fn icon_png() -> Option<std::path::PathBuf> {
|
||
static PATH: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();
|
||
PATH.get_or_init(|| {
|
||
let path = crate::model::State::path().parent()?.join("anybot-icon.png");
|
||
if path.exists() {
|
||
return Some(path);
|
||
}
|
||
let icon = crate::app_icon_rgba(128);
|
||
image::RgbaImage::from_raw(128, 128, icon)?.save(&path).ok()?;
|
||
Some(path)
|
||
})
|
||
.clone()
|
||
}
|
||
|
||
/// AnyBot.app's own banners: NSUserNotificationCenter. The newer UNUserNotificationCenter only
|
||
/// lets apps signed by an Apple developer team send notifications (it answers "Notifications are
|
||
/// not allowed for this application"); AnyBot signs itself on each Mac (deploy/mac/sign.sh), and
|
||
/// the older center takes its banners, with the app's icon, without asking first. 系統設定 › 通知
|
||
/// › AnyBot still decides whether and how they show.
|
||
#[cfg(target_os = "macos")]
|
||
mod center {
|
||
use objc2::rc::Retained;
|
||
use objc2::runtime::{AnyClass, NSObject, NSObjectProtocol, ProtocolObject};
|
||
use objc2::{define_class, msg_send, ClassType};
|
||
#[allow(deprecated)]
|
||
use objc2_foundation::{NSBundle, NSString, NSUserNotification, NSUserNotificationCenter, NSUserNotificationCenterDelegate};
|
||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||
use std::sync::{Mutex, Once};
|
||
|
||
static PREPARED: Once = Once::new();
|
||
static USABLE: AtomicBool = AtomicBool::new(false);
|
||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||
static CLICKED: Mutex<Vec<u64>> = Mutex::new(Vec::new());
|
||
|
||
define_class!(
|
||
// Shows AnyBot's banners while AnyBot is in front too (they're only sent when the person
|
||
// is away, and idle in front of it counts), and hears which banner was clicked.
|
||
#[unsafe(super(NSObject))]
|
||
#[name = "AnyBotBannerDelegate"]
|
||
struct Delegate;
|
||
|
||
unsafe impl NSObjectProtocol for Delegate {}
|
||
|
||
#[allow(deprecated)]
|
||
unsafe impl NSUserNotificationCenterDelegate for Delegate {
|
||
#[unsafe(method(userNotificationCenter:shouldPresentNotification:))]
|
||
fn should_present(&self, _center: &NSUserNotificationCenter, _n: &NSUserNotification) -> bool {
|
||
true
|
||
}
|
||
|
||
#[unsafe(method(userNotificationCenter:didActivateNotification:))]
|
||
fn did_activate(&self, _center: &NSUserNotificationCenter, n: &NSUserNotification) {
|
||
if let Some(bot) = n.identifier().and_then(|id| super::bot_of_banner(&id.to_string())) {
|
||
if let Ok(mut c) = CLICKED.lock() {
|
||
c.push(bot);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
);
|
||
|
||
/// Inside a real .app with an identifier (the center is nil for a bare program), on a macOS
|
||
/// that still has the center.
|
||
fn in_bundle() -> bool {
|
||
let b = NSBundle::mainBundle();
|
||
AnyClass::get(c"NSUserNotificationCenter").is_some() && b.bundleIdentifier().is_some() && b.bundlePath().to_string().ends_with(".app")
|
||
}
|
||
|
||
pub fn prepare() {
|
||
PREPARED.call_once(|| {
|
||
if !in_bundle() {
|
||
return;
|
||
}
|
||
USABLE.store(true, Ordering::SeqCst);
|
||
let delegate: Retained<Delegate> = unsafe { msg_send![Delegate::class(), new] };
|
||
#[allow(deprecated)]
|
||
unsafe {
|
||
NSUserNotificationCenter::defaultUserNotificationCenter().setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
|
||
}
|
||
// The center keeps only a weak reference: the delegate lives as long as AnyBot.
|
||
std::mem::forget(delegate);
|
||
});
|
||
}
|
||
|
||
pub fn usable() -> bool {
|
||
prepare();
|
||
USABLE.load(Ordering::SeqCst)
|
||
}
|
||
|
||
/// Show the banner. False: not inside AnyBot.app (the caller uses display notification).
|
||
#[allow(deprecated)]
|
||
pub fn post(title: &str, body: &str, sound: bool, bot: Option<u64>) -> bool {
|
||
if !usable() {
|
||
return false;
|
||
}
|
||
let n = NSUserNotification::new();
|
||
n.setTitle(Some(&NSString::from_str(title)));
|
||
n.setInformativeText(Some(&NSString::from_str(body)));
|
||
n.setIdentifier(Some(&NSString::from_str(&super::banner_id(bot, NEXT.fetch_add(1, Ordering::SeqCst)))));
|
||
if sound {
|
||
n.setSoundName(Some(&NSString::from_str("Glass")));
|
||
}
|
||
NSUserNotificationCenter::defaultUserNotificationCenter().deliverNotification(&n);
|
||
true
|
||
}
|
||
|
||
/// How many of AnyBot's banners the system is keeping (`anybot --banner`'s check).
|
||
#[allow(deprecated)]
|
||
pub fn delivered() -> usize {
|
||
if !usable() {
|
||
return 0;
|
||
}
|
||
NSUserNotificationCenter::defaultUserNotificationCenter().deliveredNotifications().count()
|
||
}
|
||
|
||
pub fn take_clicked() -> Vec<u64> {
|
||
CLICKED.lock().map(|mut c| std::mem::take(&mut *c)).unwrap_or_default()
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn presence_rule() {
|
||
assert!(!should_notify(true, Some(5.0)));
|
||
assert!(should_notify(true, Some(90.0)));
|
||
assert!(should_notify(false, Some(1.0)));
|
||
assert!(!should_notify(true, None));
|
||
let sample = " | | \"HIDIdleTime\" = 123000000000\n";
|
||
assert_eq!(parse_hid_idle(sample), Some(123.0));
|
||
}
|
||
|
||
#[test]
|
||
fn update_applies_only_when_truly_away() {
|
||
assert!(should_apply_update_now(true, true, true, false, Some(600.0), true));
|
||
assert!(should_apply_update_now(true, true, false, true, Some(900.0), true));
|
||
assert!(!should_apply_update_now(true, true, false, false, Some(900.0), true), "screen in use");
|
||
assert!(!should_apply_update_now(true, true, true, false, Some(599.0), true), "not idle long enough");
|
||
assert!(!should_apply_update_now(true, true, true, false, Some(900.0), false), "a bot is working");
|
||
assert!(!should_apply_update_now(false, true, true, false, Some(900.0), true), "turned off");
|
||
assert!(!should_apply_update_now(true, false, true, false, Some(900.0), true), "nothing to apply");
|
||
assert_eq!(next_update_check_secs(0.0), 3600);
|
||
assert_eq!(next_update_check_secs(0.999), 3899);
|
||
}
|
||
|
||
#[test]
|
||
fn banner_text_is_quoted() {
|
||
let s = banner_script("電腦助手 需要你允許", "執行 \"rm\" \\ 指令\n下一行");
|
||
assert_eq!(s, "display notification \"執行 \\\"rm\\\" \\\\ 指令下一行\" with title \"電腦助手 需要你允許\" sound name \"Glass\"");
|
||
}
|
||
|
||
#[test]
|
||
fn a_banner_click_finds_its_bot() {
|
||
assert_eq!(bot_of_banner(&banner_id(Some(42), 7)), Some(42));
|
||
assert_eq!(bot_of_banner(&banner_id(None, 7)), None);
|
||
assert_eq!(bot_of_banner("something-else"), None);
|
||
}
|
||
|
||
#[test]
|
||
fn a_banner_can_be_silent() {
|
||
// (When AnyBot plays its own 提示音, the banner doesn't add a second sound.)
|
||
assert_eq!(banner_script_with("標題", "內文", false), "display notification \"內文\" with title \"標題\"");
|
||
assert!(banner_script_with("標題", "內文", true).ends_with("sound name \"Glass\""));
|
||
}
|
||
}
|