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.

17.6 KB
Raw Blame
//! The decisions behind pausing media during a talk take, with no Tauri or
//! macOS in them so they can be tested anywhere
//! (`rustc --edition 2021 --test rules.rs`): which players are asked, the
//! AppleScript sent to each, how its answer is read, and whether a player
//! Clipy paused may be resumed.
//!
//! Why AppleScript and these players only: it is the one public way on macOS
//! to ask a player whether it is playing and pause exactly that player.
//! MediaRemote (the system Now Playing service) is private, changes between
//! macOS releases and stopped answering third-party apps in macOS 15.4; a
//! simulated media key toggles blindly, so it would start music that was
//! not playing. Apple Music, Spotify and the TV app are scriptable; a video
//! in a browser tab is not covered.

/// One scriptable player.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Player {
    pub bundle_id: &'static str,
    /// AppleScript for something that identifies the current track.
    track_expr: &'static str,
}

pub const PLAYERS: &[Player] = &[
    Player {
        bundle_id: "com.apple.Music",
        track_expr: "persistent ID of current track",
    },
    Player {
        bundle_id: "com.spotify.client",
        track_expr: "id of current track",
    },
    Player {
        bundle_id: "com.apple.TV",
        track_expr: "persistent ID of current track",
    },
];

pub fn player(bundle_id: &str) -> Option<Player> {
    PLAYERS.iter().copied().find(|p| p.bundle_id == bundle_id)
}

/// Lists which supported players are running, one bundle id per line. It
/// only asks the system, never the players, so it launches nothing and
/// needs no Automation permission. A player that is not installed is
/// skipped by the `try`.
pub fn running_script() -> String {
    let ids = PLAYERS
        .iter()
        .map(|p| format!("\"{}\"", p.bundle_id))
        .collect::<Vec<_>>()
        .join(", ");
    format!(
        "set out to \"\"\n\
         repeat with b in {{{ids}}}\n\
         \ttry\n\
         \t\tif application id (b as text) is running then set out to out & (b as text) & linefeed\n\
         \tend try\n\
         end repeat\n\
         return out"
    )
}

/// Reads `running_script`'s answer, keeping only players this module knows.
pub fn parse_running(output: &str) -> Vec<Player> {
    output
        .lines()
        .filter_map(|line| player(line.trim()))
        .collect()
}

// Every script below checks the player is still running before it says
// anything to it: a `tell` to a player that has quit would launch it.

/// The player's state, current track and position, without changing
/// anything: `<state>\t<track>\t<position ms>`, or `gone`.
pub fn snapshot_script(player: Player) -> String {
    format!(
        "with timeout of 3 seconds\n\
         \tif application id \"{id}\" is not running then return \"gone\"\n\
         \ttell application id \"{id}\"\n\
         \t\tset s to \"other\"\n\
         \t\tif player state is playing then set s to \"playing\"\n\
         \t\tif player state is paused then set s to \"paused\"\n\
         \t\tset t to \"\"\n\
         \t\ttry\n\
         \t\t\tset t to ({track}) as text\n\
         \t\tend try\n\
         \t\tset p to -1\n\
         \t\ttry\n\
         \t\t\tset p to (player position * 1000) as integer\n\
         \t\tend try\n\
         \t\treturn s & tab & t & tab & (p as text)\n\
         \tend tell\n\
         end timeout",
        id = player.bundle_id,
        track = player.track_expr,
    )
}

/// Pauses the player only if it is playing, in one step so nothing can
/// change in between: `paused\t<track>\t<position ms>`, or `idle`.
pub fn pause_script(player: Player) -> String {
    format!(
        "with timeout of 3 seconds\n\
         \tif application id \"{id}\" is not running then return \"idle\"\n\
         \ttell application id \"{id}\"\n\
         \t\tif player state is not playing then return \"idle\"\n\
         \t\tset t to \"\"\n\
         \t\ttry\n\
         \t\t\tset t to ({track}) as text\n\
         \t\tend try\n\
         \t\tset p to -1\n\
         \t\ttry\n\
         \t\t\tset p to (player position * 1000) as integer\n\
         \t\tend try\n\
         \t\tpause\n\
         \t\treturn \"paused\" & tab & t & tab & (p as text)\n\
         \tend tell\n\
         end timeout",
        id = player.bundle_id,
        track = player.track_expr,
    )
}

/// Resumes the player's current track.
pub fn play_script(player: Player) -> String {
    format!(
        "with timeout of 3 seconds\n\
         \tif application id \"{id}\" is not running then return \"gone\"\n\
         \ttell application id \"{id}\" to play\n\
         \treturn \"resumed\"\n\
         end timeout",
        id = player.bundle_id,
    )
}

/// A player Clipy paused, and what it was playing at that moment.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Paused {
    pub player: Player,
    pub track: String,
    /// `None` when the player did not report a position.
    pub position_ms: Option<i64>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum State {
    Playing,
    Paused,
    Other,
}

/// What a player reports now.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Snapshot {
    pub state: State,
    pub track: String,
    pub position_ms: Option<i64>,
}

fn position(value: &str) -> Option<i64> {
    value.trim().parse::<i64>().ok().filter(|p| *p >= 0)
}

/// Reads `pause_script`'s answer. `None` when Clipy paused nothing.
pub fn parse_pause(player: Player, output: &str) -> Option<Paused> {
    let mut parts = output.trim_end_matches(['\n', '\r']).split('\t');
    if parts.next()? != "paused" {
        return None;
    }
    Some(Paused {
        player,
        track: parts.next().unwrap_or("").to_string(),
        position_ms: parts.next().and_then(position),
    })
}

/// Reads `snapshot_script`'s answer. `None` when the player is gone or the
/// answer is unreadable.
pub fn parse_snapshot(output: &str) -> Option<Snapshot> {
    let mut parts = output.trim_end_matches(['\n', '\r']).split('\t');
    let state = match parts.next()? {
        "playing" => State::Playing,
        "paused" => State::Paused,
        "other" => State::Other,
        _ => return None,
    };
    Some(Snapshot {
        state,
        track: parts.next().unwrap_or("").to_string(),
        position_ms: parts.next().and_then(position),
    })
}

/// How far the position may drift while paused before it counts as the
/// user having played meanwhile. Players report a paused position with a
/// little jitter; anything past this means it played.
pub const POSITION_TOLERANCE_MS: i64 = 1_500;

/// Whether a player Clipy paused may be resumed: only if it is still
/// paused, on the same track, at the same place. Anything else means the
/// user (or something else) touched it, and Clipy leaves it alone.
pub fn should_resume(paused: &Paused, now: Option<&Snapshot>) -> bool {
    let Some(now) = now else {
        return false;
    };
    if now.state != State::Paused || now.track != paused.track {
        return false;
    }
    match (paused.position_ms, now.position_ms) {
        (Some(before), Some(after)) => (after - before).abs() <= POSITION_TOLERANCE_MS,
        // A player that reported no position at pause is judged on state
        // and track alone; one that stopped reporting it is not resumed.
        (None, _) => true,
        (Some(_), None) => false,
    }
}

/// The jobs the media worker runs, strictly one after another, in the order
/// takes asked for them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Job {
    /// A take started: pause what is playing.
    Pause,
    /// A take ended: resume what Clipy paused.
    Resume,
}

/// What the worker needs from the outside world, so the ordering can be
/// tested without players.
pub trait Players {
    /// Pauses every supported player that is playing, returning those paused.
    fn pause_playing(&mut self) -> Vec<Paused>;
    /// Reads a paused player's state now.
    fn snapshot(&mut self, paused: &Paused) -> Option<Snapshot>;
    /// Tells a player to play.
    fn play(&mut self, paused: &Paused);
}

/// The players Clipy has paused and not yet given back. Owned by the one
/// worker that runs every pause and restore, so a restore can never race
/// the next take's pause: a new take's pause runs only after the previous
/// restore has finished or handed its players over.
#[derive(Debug, Default)]
pub struct Ledger {
    held: Vec<Paused>,
}

impl Ledger {
    pub fn held(&self) -> &[Paused] {
        &self.held
    }

    /// Runs one job. `take_active` says whether a take is running right now;
    /// it is read again right before each play, and once a new take owns the
    /// microphone the rest of the players stay paused for that take to give
    /// back when it ends.
    pub fn run(&mut self, job: Job, players: &mut impl Players, take_active: impl Fn() -> bool) {
        match job {
            Job::Pause => {
                let paused = players.pause_playing();
                for player in paused {
                    // A player paused again keeps its newest state.
                    self.held.retain(|held| held.player != player.player);
                    self.held.push(player);
                }
            }
            Job::Resume => {
                while !self.held.is_empty() {
                    if take_active() {
                        return;
                    }
                    let paused = self.held[0].clone();
                    let now = players.snapshot(&paused);
                    // Ownership is checked again just before playing: the
                    // snapshot takes time, and a take may have started.
                    if take_active() {
                        return;
                    }
                    self.held.remove(0);
                    if should_resume(&paused, now.as_ref()) {
                        players.play(&paused);
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn music() -> Player {
        player("com.apple.Music").unwrap()
    }

    fn paused_at(position: Option<i64>) -> Paused {
        Paused {
            player: music(),
            track: "ABC123".into(),
            position_ms: position,
        }
    }

    fn snap(state: State, track: &str, position: Option<i64>) -> Snapshot {
        Snapshot {
            state,
            track: track.into(),
            position_ms: position,
        }
    }

    #[test]
    fn running_output_keeps_known_players() {
        assert_eq!(
            parse_running("com.spotify.client\ncom.example.Other\n\ncom.apple.Music\n"),
            vec![player("com.spotify.client").unwrap(), music()]
        );
        assert!(parse_running("").is_empty());
    }

    #[test]
    fn pause_answers_are_read() {
        assert_eq!(
            parse_pause(music(), "paused\tABC123\t61234\n"),
            Some(paused_at(Some(61234)))
        );
        assert_eq!(
            parse_pause(music(), "paused\tABC123\t-1"),
            Some(paused_at(None))
        );
        assert_eq!(parse_pause(music(), "idle\n"), None);
        assert_eq!(parse_pause(music(), ""), None);
    }

    #[test]
    fn snapshot_answers_are_read() {
        assert_eq!(
            parse_snapshot("paused\tABC123\t61300\n"),
            Some(snap(State::Paused, "ABC123", Some(61300)))
        );
        assert_eq!(
            parse_snapshot("other\t\t-1"),
            Some(snap(State::Other, "", None))
        );
        assert_eq!(parse_snapshot("gone"), None);
        assert_eq!(parse_snapshot("execution error: Not authorized"), None);
    }

    #[test]
    fn resumes_only_what_is_still_as_clipy_left_it() {
        let paused = paused_at(Some(61_234));
        assert!(should_resume(
            &paused,
            Some(&snap(State::Paused, "ABC123", Some(61_300)))
        ));
        // The user pressed play during the take.
        assert!(!should_resume(
            &paused,
            Some(&snap(State::Playing, "ABC123", Some(70_000)))
        ));
        // Played, then paused again: the position moved.
        assert!(!should_resume(
            &paused,
            Some(&snap(State::Paused, "ABC123", Some(95_000)))
        ));
        // Another track was picked.
        assert!(!should_resume(
            &paused,
            Some(&snap(State::Paused, "XYZ", Some(61_234)))
        ));
        // Stopped, quit, or the answer could not be read.
        assert!(!should_resume(
            &paused,
            Some(&snap(State::Other, "ABC123", Some(61_234)))
        ));
        assert!(!should_resume(&paused, None));
        assert!(!should_resume(
            &paused,
            Some(&snap(State::Paused, "ABC123", None))
        ));
        // No position at pause: state and track decide.
        assert!(should_resume(
            &paused_at(None),
            Some(&snap(State::Paused, "ABC123", Some(5)))
        ));
    }

    #[test]
    fn every_script_checks_the_player_is_running_before_telling_it() {
        for p in PLAYERS {
            for script in [snapshot_script(*p), pause_script(*p), play_script(*p)] {
                let check = script.find("is not running").expect("running check");
                let tell = script.find("tell application id").expect("tell");
                assert!(check < tell, "{script}");
                assert!(script.contains(p.bundle_id));
            }
        }
        let running = running_script();
        assert!(!running.contains("tell "));
        for p in PLAYERS {
            assert!(running.contains(p.bundle_id));
        }
    }

    /// Players that remember their state, with a hook that runs inside a
    /// snapshot so a test can start a take at the worst moment.
    struct Fake {
        playing: Vec<Player>,
        paused: Vec<Player>,
        plays: Vec<&'static str>,
        during_snapshot: Option<Box<dyn FnMut()>>,
    }

    impl Fake {
        fn playing(players: &[Player]) -> Self {
            Fake {
                playing: players.to_vec(),
                paused: Vec::new(),
                plays: Vec::new(),
                during_snapshot: None,
            }
        }
    }

    impl Players for Fake {
        fn pause_playing(&mut self) -> Vec<Paused> {
            let now: Vec<Player> = std::mem::take(&mut self.playing);
            self.paused.extend(now.iter().copied());
            now.into_iter()
                .map(|player| Paused {
                    player,
                    track: "T".into(),
                    position_ms: Some(1_000),
                })
                .collect()
        }
        fn snapshot(&mut self, paused: &Paused) -> Option<Snapshot> {
            if let Some(hook) = self.during_snapshot.as_mut() {
                hook();
            }
            let state = if self.paused.contains(&paused.player) {
                State::Paused
            } else if self.playing.contains(&paused.player) {
                State::Playing
            } else {
                State::Other
            };
            Some(snap(state, "T", Some(1_000)))
        }
        fn play(&mut self, paused: &Paused) {
            self.paused.retain(|p| *p != paused.player);
            self.playing.push(paused.player);
            self.plays.push(paused.player.bundle_id);
        }
    }

    #[test]
    fn a_take_that_starts_before_the_restore_runs_inherits_the_players() {
        let spotify = player("com.spotify.client").unwrap();
        let mut fake = Fake::playing(&[spotify]);
        let mut ledger = Ledger::default();
        ledger.run(Job::Pause, &mut fake, || true);
        // Take 1 ended and take 2 started before the worker got to the
        // restore: the queue holds Resume (take 1), then Pause (take 2).
        ledger.run(Job::Resume, &mut fake, || true);
        assert!(fake.plays.is_empty(), "music must not play into take 2");
        ledger.run(Job::Pause, &mut fake, || true);
        assert_eq!(ledger.held().len(), 1, "take 2 still owes Spotify back");
        ledger.run(Job::Resume, &mut fake, || false);
        assert_eq!(fake.plays, vec!["com.spotify.client"]);
        assert!(ledger.held().is_empty());
    }

    #[test]
    fn a_take_that_starts_during_the_restore_stops_it_before_play() {
        use std::cell::Cell;
        use std::rc::Rc;
        let spotify = player("com.spotify.client").unwrap();
        let mut fake = Fake::playing(&[music(), spotify]);
        let mut ledger = Ledger::default();
        ledger.run(Job::Pause, &mut fake, || true);
        let active = Rc::new(Cell::new(false));
        // Take 2 starts while the restore is reading Music's state.
        let flip = active.clone();
        fake.during_snapshot = Some(Box::new(move || flip.set(true)));
        let seen = active.clone();
        ledger.run(Job::Resume, &mut fake, move || seen.get());
        assert!(
            fake.plays.is_empty(),
            "nothing plays once take 2 owns the mic"
        );
        assert_eq!(ledger.held().len(), 2);
        fake.during_snapshot = None;
        // Take 2's pause finds nothing playing and loses nothing.
        ledger.run(Job::Pause, &mut fake, || true);
        assert_eq!(ledger.held().len(), 2);
        active.set(false);
        let seen = active.clone();
        ledger.run(Job::Resume, &mut fake, move || seen.get());
        assert_eq!(fake.plays, vec!["com.apple.Music", "com.spotify.client"]);
    }

    #[test]
    fn a_player_the_user_restarted_is_dropped_not_played() {
        let mut fake = Fake::playing(&[music()]);
        let mut ledger = Ledger::default();
        ledger.run(Job::Pause, &mut fake, || true);
        // The user pressed play during the take.
        fake.paused.clear();
        fake.playing.push(music());
        ledger.run(Job::Resume, &mut fake, || false);
        assert!(fake.plays.is_empty());
        assert!(ledger.held().is_empty());
    }
}