use std::path::Path;
use anyhow::Result;
use super::{Env, TabToOpen, TerminalAdapter, launch};
use crate::engine::rules::TerminalShape;
use crate::procs::ProcInfo;
pub struct Kitty;
impl TerminalAdapter for Kitty {
fn id(&self) -> &'static str {
"kitty"
}
fn name(&self) -> &'static str {
"kitty"
}
fn shape(&self) -> TerminalShape {
TerminalShape::Tabs
}
fn find(&self, env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
if cfg!(target_os = "linux") {
kitty_of(env, lineage)
} else {
None
}
}
fn reopen(&self, exe: Option<&Path>, tabs: &[TabToOpen]) -> Result<()> {
let program = exe.unwrap_or(Path::new("kitty"));
for tab in tabs {
launch::start(program, &new_window_arguments(tab))?;
}
Ok(())
}
}
fn kitty_of(env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
let kitty: u32 = env.get("KITTY_PID")?.parse().ok()?;
lineage
.get(1)
.filter(|parent| parent.pid == kitty && parent.name == "kitty")
.cloned()
}
fn new_window_arguments(tab: &TabToOpen) -> Vec<String> {
let mut args = vec![format!("--directory={}", tab.cwd)];
args.extend(launch::command(tab));
args
}
#[cfg(test)]
mod tests {
use super::*;
use crate::procs::{fake::FakeTable, lineage};
const ID: &str = "00000000-0000-4000-8000-000000000001";
fn tab_env() -> Env {
Env::from([("KITTY_PID".to_string(), "20".to_string())])
}
fn tab_table() -> FakeTable {
FakeTable::new(&[
(50, Some(40), "bash", Some(500)),
(40, Some(20), "bash", Some(400)),
(20, Some(1), "kitty", Some(200)),
])
}
#[test]
fn the_kitty_that_started_a_tab_s_shell_is_the_terminal() {
let found = kitty_of(&tab_env(), &lineage(&tab_table(), 40));
assert_eq!(found.map(|process| process.pid), Some(20));
let tracked = Kitty.find(&tab_env(), &lineage(&tab_table(), 40)).is_some();
assert_eq!(tracked, cfg!(target_os = "linux"));
}
#[test]
fn a_shell_inside_a_tab_or_of_another_kitty_is_not_a_tab() {
assert!(kitty_of(&tab_env(), &lineage(&tab_table(), 50)).is_none());
let other = Env::from([("KITTY_PID".to_string(), "30".to_string())]);
assert!(kitty_of(&other, &lineage(&tab_table(), 40)).is_none());
assert!(kitty_of(&Env::new(), &lineage(&tab_table(), 40)).is_none());
}
#[test]
fn a_tab_opens_as_a_window_in_its_folder_with_its_agent_session() {
let tab = |run: &[&str]| TabToOpen {
title: "web-ui".into(),
cwd: "/home/demo/code/web ui".into(),
shell: Some("fish".into()),
run: run.iter().map(|word| word.to_string()).collect(),
..TabToOpen::default()
};
assert_eq!(
new_window_arguments(&tab(&[])),
["--directory=/home/demo/code/web ui"]
);
assert_eq!(
new_window_arguments(&tab(&["codex", "resume", ID])),
[
"--directory=/home/demo/code/web ui".to_string(),
"env".into(),
format!("KAERU_RUN=cd -- '/home/demo/code/web ui' && codex resume {ID}"),
"fish".into(),
]
);
}
}