Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

7.3 KB
Raw Blame
//! Pause media during a talk take (Settings → Talk to your agent, off unless
//! the user turns it on, macOS only).
//!
//! When a take starts, every supported player that is playing (Apple Music,
//! Spotify, the TV app; see `rules` for why only these) is paused. When the
//! take ends, each one Clipy paused is resumed, but only if it is still
//! paused on the same track at the same place: if the user pressed play,
//! picked another track or quit the player meanwhile, Clipy leaves it alone.
//! A player that was not playing is never touched, so nothing ever starts
//! that was not already playing.
//!
//! Every pause and restore runs on one worker thread, in the order takes
//! asked for them, so a restore can never play music after the next take's
//! pause has looked. Before each play the worker checks again that no take
//! has started; if one has, the remaining players stay paused and that take
//! gives them back when it ends (`rules::Ledger`).
//!
//! The worker runs `/usr/bin/osascript`, so nothing here touches AppKit
//! (background threads never may) or waits on the capture path. Every
//! failure (no Automation permission, a player that does not answer) means
//! "do nothing": music that keeps playing is better than music Clipy cannot
//! give back.

#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub mod rules;

/// Pauses whatever supported player is playing, without waiting. Called
/// when a talk take starts and the switch is on.
pub fn pause_for_take() {
    #[cfg(target_os = "macos")]
    mac::pause_for_take();
}

/// Resumes what `pause_for_take` paused, without waiting. Safe to call more
/// than once and when nothing was paused.
pub fn resume_after_take() {
    #[cfg(target_os = "macos")]
    mac::resume_after_take();
}

/// Asks each running player for its state once, so macOS shows its
/// Automation prompt ("Clipy wants to control Spotify") when the switch is
/// turned on rather than in the middle of the first take.
pub fn request_permission() {
    #[cfg(target_os = "macos")]
    mac::request_permission();
}

#[cfg(target_os = "macos")]
mod mac {
    use std::io::Read;
    use std::process::{Command, Stdio};
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::mpsc::{self, Sender};
    use std::sync::OnceLock;
    use std::time::{Duration, Instant};

    use parking_lot::Mutex;

    use super::rules::{self, Job, Ledger, Paused, Players, Snapshot};

    /// How long one script may run during a take. A player that does not
    /// answer in time is left as it is.
    const SCRIPT_TIMEOUT: Duration = Duration::from_secs(4);
    /// The permission probe waits for the user to answer macOS's prompt.
    const PROBE_TIMEOUT: Duration = Duration::from_secs(60);

    /// A take is between `pause_for_take` and `resume_after_take`. Set and
    /// cleared on the caller's thread before the job is queued, so the worker
    /// sees a new take the moment it starts, even mid-restore.
    static TAKE_ACTIVE: AtomicBool = AtomicBool::new(false);

    /// The one worker that runs every pause and restore, in order. Pause and
    /// restore never overlap, so a restore cannot play music after the next
    /// take's pause has already looked.
    static WORKER: OnceLock<Mutex<Sender<Job>>> = OnceLock::new();

    fn queue(job: Job) {
        let sender = WORKER.get_or_init(|| {
            let (tx, rx) = mpsc::channel::<Job>();
            let spawned = std::thread::Builder::new()
                .name("clipy-media-pause".into())
                .spawn(move || {
                    let mut ledger = Ledger::default();
                    let mut players = Osascript;
                    for job in rx {
                        ledger.run(job, &mut players, || TAKE_ACTIVE.load(Ordering::SeqCst));
                    }
                });
            if let Err(err) = spawned {
                tracing::warn!("talk take: media pause worker did not start: {err}");
            }
            Mutex::new(tx)
        });
        if sender.lock().send(job).is_err() {
            tracing::warn!("talk take: media pause worker is not running");
        }
    }

    /// Runs one AppleScript and returns its stdout, or `None` on an error,
    /// a refusal (no Automation permission is error -1743) or a timeout.
    fn osascript(script: &str, timeout: Duration) -> Option<String> {
        let mut child = Command::new("/usr/bin/osascript")
            .arg("-e")
            .arg(script)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()
            .ok()?;
        let deadline = Instant::now() + timeout;
        loop {
            match child.try_wait() {
                Ok(Some(status)) => {
                    if !status.success() {
                        return None;
                    }
                    let mut out = String::new();
                    child.stdout.take()?.read_to_string(&mut out).ok()?;
                    return Some(out);
                }
                Ok(None) if Instant::now() < deadline => {
                    std::thread::sleep(Duration::from_millis(20));
                }
                _ => {
                    let _ = child.kill();
                    let _ = child.wait();
                    return None;
                }
            }
        }
    }

    fn running_players() -> Vec<rules::Player> {
        osascript(&rules::running_script(), SCRIPT_TIMEOUT)
            .map(|out| rules::parse_running(&out))
            .unwrap_or_default()
    }

    /// The real players, over AppleScript.
    struct Osascript;

    impl Players for Osascript {
        fn pause_playing(&mut self) -> Vec<Paused> {
            running_players()
                .into_iter()
                .filter_map(|player| {
                    let out = osascript(&rules::pause_script(player), SCRIPT_TIMEOUT)?;
                    rules::parse_pause(player, &out)
                })
                .collect()
        }

        fn snapshot(&mut self, paused: &Paused) -> Option<Snapshot> {
            let now = osascript(&rules::snapshot_script(paused.player), SCRIPT_TIMEOUT)
                .and_then(|out| rules::parse_snapshot(&out));
            if !rules::should_resume(paused, now.as_ref()) {
                tracing::info!(
                    player = paused.player.bundle_id,
                    "talk take: media was changed while paused, leaving it alone"
                );
            }
            now
        }

        fn play(&mut self, paused: &Paused) {
            if osascript(&rules::play_script(paused.player), SCRIPT_TIMEOUT).is_none() {
                tracing::warn!(
                    player = paused.player.bundle_id,
                    "talk take: media did not resume"
                );
            }
        }
    }

    pub(super) fn pause_for_take() {
        if TAKE_ACTIVE.swap(true, Ordering::SeqCst) {
            return;
        }
        queue(Job::Pause);
    }

    pub(super) fn resume_after_take() {
        if !TAKE_ACTIVE.swap(false, Ordering::SeqCst) {
            return;
        }
        queue(Job::Resume);
    }

    pub(super) fn request_permission() {
        let _ = std::thread::Builder::new()
            .name("clipy-media-permission".into())
            .spawn(|| {
                for player in running_players() {
                    let _ = osascript(&rules::snapshot_script(player), PROBE_TIMEOUT);
                }
            });
    }
}