Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

fix(macos): report actual user idle time (#60)

alexfoxtmeb55cbf70344
diff --git a/desktop/app/src/mac/input.rs b/desktop/app/src/mac/input.rs
index 8974f72..f6ad1ab 100644
--- a/desktop/app/src/mac/input.rs
+++ b/desktop/app/src/mac/input.rs
@@ -1,5 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-//! macOS synthetic input stubs.
+//! macOS activity detection and synthetic input stubs.
use nectarlink_core::{ButtonAction, KeyMod, MouseButton, SlideAction, TouchAction};
@@ -14,6 +14,41 @@ pub fn scroll(_dx: f32, _dy: f32) {}
pub fn type_text(_text: &str) {}
pub fn press_key(_key: &str, _mods: &[KeyMod]) {}
pub fn slide(_action: SlideAction) {}
-pub fn is_user_active_within_ms(_max_idle_ms: u32) -> bool {
- true
+// This read-only CoreGraphics function accepts value arguments and has no
+// pointer or thread preconditions. It does not request Accessibility access.
+#[allow(unsafe_code)]
+#[link(name = "CoreGraphics", kind = "framework")]
+unsafe extern "C" {
+ safe fn CGEventSourceSecondsSinceLastEventType(state_id: i32, event_type: u32) -> f64;
+}
+
+/// Whether the session received keyboard, mouse or trackpad input recently.
+pub fn is_user_active_within_ms(max_idle_ms: u32) -> bool {
+ // kCGEventSourceStateCombinedSessionState and kCGAnyInputEventType.
+ let idle_secs = CGEventSourceSecondsSinceLastEventType(0, u32::MAX);
+ active_within_ms(idle_secs, max_idle_ms)
+}
+
+fn active_within_ms(idle_secs: f64, max_idle_ms: u32) -> bool {
+ !idle_secs.is_finite() || idle_secs < 0.0 || idle_secs * 1000.0 <= f64::from(max_idle_ms)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::active_within_ms;
+
+ #[test]
+ fn activity_window_includes_its_boundary() {
+ assert!(active_within_ms(0.0, 0));
+ assert!(active_within_ms(29.999, 30_000));
+ assert!(active_within_ms(30.0, 30_000));
+ assert!(!active_within_ms(30.001, 30_000));
+ }
+
+ #[test]
+ fn invalid_idle_readings_count_as_activity() {
+ for idle in [-1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
+ assert!(active_within_ms(idle, 0));
+ }
+ }
}