use std::process::{Command, Stdio};
const ACTIVE_FLAG: &str = "@tango_active";
const BINDING_COND: &str =
"[ \"$(tmux show-options -v -t '#{session_name}' @tango_active 2>/dev/null)\" = 1 ]";
const BINDING_THEN: &str = "detach-client";
const BINDINGS: &[(&str, &str)] = &[
("M-Left", "send-keys M-Left"),
("M-b", "send-keys M-b"),
];
fn run_tmux(args: &[&str]) {
let _ = Command::new("tmux")
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
fn run_tmux_capture(args: &[&str]) -> Option<String> {
let output = Command::new("tmux")
.args(args)
.stdin(Stdio::null())
.stderr(Stdio::null())
.output()
.ok()?;
if !output.status.success() {
return None;
}
Some(String::from_utf8_lossy(&output.stdout).to_string())
}
fn any_session_active() -> bool {
let Some(sessions) = run_tmux_capture(&["list-sessions", "-F", "#{session_name}"]) else {
return false;
};
sessions.lines().filter(|name| !name.is_empty()).any(|session| {
run_tmux_capture(&["show-options", "-v", "-t", session, ACTIVE_FLAG])
.map(|value| value.trim() == "1")
.unwrap_or(false)
})
}
pub fn install_binding() {
for (key, passthrough) in BINDINGS {
run_tmux(&[
"bind-key", "-n", key,
"if-shell", BINDING_COND,
BINDING_THEN, passthrough,
]);
}
}
pub fn unbind_binding() {
for (key, _) in BINDINGS {
run_tmux(&["unbind-key", "-n", key]);
}
}
pub fn set_active(session: &str) {
run_tmux(&["set-option", "-t", session, ACTIVE_FLAG, "1"]);
}
pub fn clear_active(session: &str) {
run_tmux(&["set-option", "-t", session, ACTIVE_FLAG, "0"]);
}
pub struct BindingGuard;
impl BindingGuard {
pub fn new() -> Self {
install_binding();
BindingGuard
}
}
impl Drop for BindingGuard {
fn drop(&mut self) {
if !any_session_active() {
unbind_binding();
}
}
}