tuigram-cli 1.10.0

Telegram in your terminal: a fast, vim-style Telegram client built on TDLib
//! The one tmux setting tuigram's image library changes, put back on the way
//! out. ratatui-image switches the pane's `allow-passthrough` on whenever it
//! runs inside tmux, so images can reach the outer terminal. Left on, it
//! would let anything printed in that pane later (a file shown with `cat`,
//! an SSH session) send escape codes past tmux too.

use std::collections::BTreeSet;
use std::process::{Command, Stdio};
use std::sync::OnceLock;

/// The pane tuigram runs in, and the value it had of its own before (`None`:
/// it took the window's or the server's).
struct Saved {
    pane: String,
    value: Option<String>,
}

static SAVED: OnceLock<Saved> = OnceLock::new();

/// The pane whose setting ratatui-image is about to change: it does when
/// `TERM` or `TERM_PROGRAM` says tmux. Only a pane tmux names for us
/// (`TMUX` and `TMUX_PANE`) can be put back afterwards.
fn pane(env: impl Fn(&str) -> Option<String>) -> Option<String> {
    let set = |name: &str| env(name).filter(|v| !v.is_empty());
    let in_tmux = set("TERM").is_some_and(|t| t.starts_with("tmux"))
        || set("TERM_PROGRAM").is_some_and(|p| p == "tmux");
    let pane = set("TMUX_PANE")?;
    (in_tmux && set("TMUX").is_some()).then_some(pane)
}

/// Remembers the pane's own value. Call before the image picker is made.
pub fn save() {
    let Some(pane) = pane(|name| std::env::var(name).ok()) else {
        return;
    };
    let Ok(out) = Command::new("tmux")
        .args(["show-options", "-pqv", "-t", &pane, "allow-passthrough"])
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output()
    else {
        return;
    };
    if out.status.success() {
        let value = String::from_utf8_lossy(&out.stdout).trim().to_string();
        let value = (!value.is_empty()).then_some(value);
        let _ = SAVED.set(Saved { pane, value });
    }
}

/// Puts the pane's value back. Harmless to call more than once.
pub fn restore() {
    if let Some(saved) = SAVED.get() {
        let _ = Command::new("tmux")
            .args(restore_args(&saved.pane, saved.value.as_deref()))
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
}

fn restore_args(pane: &str, value: Option<&str>) -> Vec<String> {
    let mut args = vec!["set-option".to_string(), "-p".into()];
    if value.is_none() {
        args.push("-u".into());
    }
    args.extend(["-t".into(), pane.into(), "allow-passthrough".into()]);
    args.extend(value.map(String::from));
    args
}

/// Whether the tmux session tuigram runs in has a client attached: with
/// none, no terminal window shows the session, so escape codes would reach
/// no one. Anything odd (tmux gone, the call failed, odd output) counts as
/// attached, and notifications keep going to the terminal as before.
pub fn any_client_attached() -> bool {
    let Ok(out) = Command::new("tmux")
        .args(["display-message", "-p", "#{session_attached}"])
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output()
    else {
        return true;
    };
    if !out.status.success() {
        return true;
    }
    attached(&out.stdout)
}

/// The tmux clients showing tuigram's pane's window, in any session (a
/// grouped one shares it), by process: a terminal attaching again is a
/// new one, though its tty is the same. `None` when tmux can't say.
pub fn clients() -> Option<BTreeSet<String>> {
    let pane = std::env::var("TMUX_PANE").ok()?;
    let out = Command::new("tmux")
        .args(["display-message", "-p", "-t", &pane, "#{window_id}", ";"])
        .args(["list-clients", "-F", "#{client_pid} #{window_id}"])
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output()
        .ok()?;
    out.status.success().then(|| showing(&out.stdout)).flatten()
}

/// The clients in `output` whose window is the pane's, on its first line.
fn showing(output: &[u8]) -> Option<BTreeSet<String>> {
    let output = String::from_utf8_lossy(output);
    let mut lines = output.lines();
    let window = lines.next().filter(|w| w.starts_with('@'))?;
    let showing = lines
        .filter_map(|line| line.split_once(' '))
        .filter(|(_, shown)| *shown == window)
        .map(|(pid, _)| pid.to_string());
    Some(showing.collect())
}

/// A client among `now` that wasn't among those `before` is a terminal
/// that has none of the pictures sent: tmux's passthrough reaches only the
/// clients showing the pane, so one sent while none did reached nobody.
pub fn newcomer(before: Option<&BTreeSet<String>>, now: &BTreeSet<String>) -> bool {
    before.is_some_and(|before| !now.is_subset(before))
}

/// `#{session_attached}` is tmux's count of clients on the session: the
/// session is watched when it's over zero. Output that doesn't parse
/// counts as watched.
fn attached(output: &[u8]) -> bool {
    match String::from_utf8_lossy(output).trim().parse::<u32>() {
        Ok(clients) => clients > 0,
        Err(_) => true,
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;

    fn pane_with(vars: &[(&str, &str)]) -> Option<String> {
        let vars: HashMap<String, String> = vars
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        pane(|name| vars.get(name).cloned())
    }

    #[test]
    fn only_a_pane_tmux_names_is_put_back() {
        let tmux = ("TMUX", "/tmp/tmux-501/default,1,0");
        assert_eq!(
            pane_with(&[("TERM_PROGRAM", "tmux"), tmux, ("TMUX_PANE", "%3")]).as_deref(),
            Some("%3")
        );
        assert_eq!(
            pane_with(&[("TERM", "tmux-256color"), tmux, ("TMUX_PANE", "%3")]).as_deref(),
            Some("%3")
        );
        assert_eq!(pane_with(&[("TERM", "tmux-256color")]), None, "over SSH");
        assert_eq!(
            pane_with(&[("TERM", "xterm-256color"), tmux, ("TMUX_PANE", "%3")]),
            None,
            "the image library leaves this one alone"
        );
    }

    #[test]
    fn only_a_client_that_wasnt_showing_the_pane_lacks_its_pictures() {
        let set = |pids: &[&str]| pids.iter().map(|n| n.to_string()).collect();
        // The pane's window, then each client's, in any session.
        assert_eq!(
            showing(b"@3\n4012 @3\n977 @5\n5120 @3\n"),
            Some(set(&["4012", "5120"]))
        );
        assert_eq!(showing(b"@3\n977 @5\n"), Some(set(&[])), "hidden from all");
        assert_eq!(showing(b"@3\n"), Some(set(&[])), "none attached");
        assert_eq!(showing(b""), None, "tmux said nothing");

        let both = set(&["4012", "977"]);
        // Two terminals on the pane: tmux's passthrough reached both.
        assert!(!newcomer(Some(&both), &both), "switching between them");
        assert!(!newcomer(Some(&both), &set(&["977"])), "one left");
        assert!(newcomer(Some(&set(&["977"])), &both), "one came");
        assert!(
            newcomer(Some(&set(&["977"])), &set(&["5120"])),
            "another, or the same tab again"
        );
        assert!(
            newcomer(Some(&set(&[])), &set(&["977"])),
            "its window shown again: what was sent meanwhile reached nobody"
        );
        assert!(!newcomer(None, &both), "nothing known before");
    }

    #[test]
    fn the_session_is_watched_when_tmux_counts_a_client() {
        assert!(attached(b"1\n"));
        assert!(attached(b"2\n"));
        assert!(!attached(b"0\n"));
        assert!(attached(b""), "tmux said nothing: assume someone watches");
        assert!(attached(b"junk"), "odd output: assume someone watches");
    }

    #[test]
    fn the_pane_gets_its_own_value_back_or_none() {
        assert_eq!(
            restore_args("%3", None),
            ["set-option", "-p", "-u", "-t", "%3", "allow-passthrough"]
        );
        assert_eq!(
            restore_args("%3", Some("off")),
            ["set-option", "-p", "-t", "%3", "allow-passthrough", "off"]
        );
    }
}