Skip to main content

focus_tracker/
focus_tracker.rs

1use bon::bon;
2
3use crate::{FocusTrackerConfig, FocusTrackerResult, FocusedWindow, platform};
4use std::future::Future;
5use std::sync::atomic::AtomicBool;
6
7#[derive(Debug, Clone)]
8pub struct FocusTracker {
9    config: FocusTrackerConfig,
10}
11
12impl Default for FocusTracker {
13    fn default() -> Self {
14        Self::builder().build()
15    }
16}
17
18#[bon]
19impl FocusTracker {
20    #[builder]
21    #[must_use]
22    pub fn new(#[builder(default)] config: FocusTrackerConfig) -> Self {
23        Self { config }
24    }
25
26    /// Tracks focus changes, calling `on_focus` each time the focused window changes.
27    ///
28    /// A focus event is only emitted when the `(process_id, window_title)` pair
29    /// differs from the previously reported one.
30    ///
31    /// # Errors
32    ///
33    /// Returns an error if the platform API fails or the callback returns an error.
34    #[builder]
35    pub async fn track_focus<F, Fut>(
36        &self,
37        on_focus: F,
38        stop_signal: Option<&AtomicBool>,
39    ) -> FocusTrackerResult<()>
40    where
41        F: FnMut(FocusedWindow) -> Fut,
42        Fut: Future<Output = FocusTrackerResult<()>>,
43    {
44        platform::track_focus(on_focus, stop_signal, &self.config).await
45    }
46}