use super::*;
impl PtyTerminal {
pub fn shell_cwd(&self) -> Option<std::path::PathBuf> {
self.osc7_cwd.lock().unwrap().clone()
}
pub fn kernel_shell_cwd(&self) -> Option<std::path::PathBuf> {
cwd_of_pid(u32::try_from(self.shell_pid?).ok()?)
}
pub fn foreground_pid(&self) -> Option<i32> {
self.backend.process_group_leader()
}
pub fn shell_pid(&self) -> Option<i32> {
self.shell_pid
}
pub fn local_shell_cwd(&self) -> Option<std::path::PathBuf> {
let host = self.shell_host().unwrap_or_default();
if !crate::command_history::is_local_host(&host) {
return None;
}
let claim = self.shell_cwd()?;
let real = cwd_of_pid(self.pid()?)?;
(claim.canonicalize().ok()? == real.canonicalize().ok()?).then_some(claim)
}
pub fn pid(&self) -> Option<u32> {
self.backend.pid().filter(|_| self.exit.is_none())
}
pub fn change_cwd(&mut self, path: &std::path::Path) {
self.write_input(&format_cd_command(path));
}
pub fn foreground_is_shell(&self) -> bool {
if self.exit.is_some() {
return false;
}
match (self.backend.process_group_leader(), self.shell_pid) {
(Some(fg), Some(pid)) => fg == pid,
_ if self.input_seen => {
std::thread::sleep(std::time::Duration::from_millis(5));
match (self.backend.process_group_leader(), self.shell_pid) {
(Some(fg), Some(pid)) => fg == pid,
_ => false,
}
}
_ => true,
}
}
pub fn cwd_seed_is_safe(&self) -> bool {
self.foreground_is_shell() || (!self.input_seen && self.marks.lock().unwrap().is_empty())
}
#[cfg(test)]
pub fn foreground_resolved_for_test(&self) -> Option<bool> {
match (self.backend.process_group_leader(), self.shell_pid) {
(Some(fg), Some(pid)) => Some(fg == pid),
_ => None,
}
}
}
pub const CLEAR_TYPED_LINE: &str = "\x05x\x15";
pub fn format_cd_command(path: &std::path::Path) -> Vec<u8> {
let s = path.to_string_lossy();
let mut out = Vec::with_capacity(s.len() + 8);
out.extend_from_slice(CLEAR_TYPED_LINE.as_bytes());
out.extend_from_slice(b"cd '");
for c in s.chars() {
if c == '\'' {
out.extend_from_slice(b"'\\''");
} else {
let mut buf = [0u8; 4];
out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
}
}
out.extend_from_slice(b"'\n");
out
}