pty_info.rs

  1use alacritty_terminal::tty::Pty;
  2use gpui::{Context, Task};
  3use parking_lot::{MappedRwLockReadGuard, Mutex, RwLock, RwLockReadGuard};
  4#[cfg(target_os = "windows")]
  5use std::num::NonZeroU32;
  6#[cfg(unix)]
  7use std::os::fd::AsRawFd;
  8use std::{path::PathBuf, sync::Arc};
  9
 10#[cfg(target_os = "windows")]
 11use windows::Win32::{Foundation::HANDLE, System::Threading::GetProcessId};
 12
 13use sysinfo::{Pid, Process, ProcessRefreshKind, RefreshKind, System, UpdateKind};
 14
 15use crate::{Event, Terminal};
 16
 17#[derive(Clone, Copy)]
 18pub struct ProcessIdGetter {
 19    handle: i32,
 20    fallback_pid: u32,
 21}
 22
 23impl ProcessIdGetter {
 24    pub fn fallback_pid(&self) -> Pid {
 25        Pid::from_u32(self.fallback_pid)
 26    }
 27}
 28
 29#[cfg(unix)]
 30impl ProcessIdGetter {
 31    fn new(pty: &Pty) -> ProcessIdGetter {
 32        ProcessIdGetter {
 33            handle: pty.file().as_raw_fd(),
 34            fallback_pid: pty.child().id(),
 35        }
 36    }
 37
 38    fn pid(&self) -> Option<Pid> {
 39        let pid = unsafe { libc::tcgetpgrp(self.handle) };
 40        if pid < 0 {
 41            return Some(Pid::from_u32(self.fallback_pid));
 42        }
 43        Some(Pid::from_u32(pid as u32))
 44    }
 45}
 46
 47#[cfg(windows)]
 48impl ProcessIdGetter {
 49    fn new(pty: &Pty) -> ProcessIdGetter {
 50        let child = pty.child_watcher();
 51        let handle = child.raw_handle();
 52        let fallback_pid = child.pid().unwrap_or_else(|| unsafe {
 53            NonZeroU32::new_unchecked(GetProcessId(HANDLE(handle as _)))
 54        });
 55
 56        ProcessIdGetter {
 57            handle: handle as i32,
 58            fallback_pid: u32::from(fallback_pid),
 59        }
 60    }
 61
 62    fn pid(&self) -> Option<Pid> {
 63        let pid = unsafe { GetProcessId(HANDLE(self.handle as _)) };
 64        // the GetProcessId may fail and returns zero, which will lead to a stack overflow issue
 65        if pid == 0 {
 66            // in the builder process, there is a small chance, almost negligible,
 67            // that this value could be zero, which means child_watcher returns None,
 68            // GetProcessId returns 0.
 69            if self.fallback_pid == 0 {
 70                return None;
 71            }
 72            return Some(Pid::from_u32(self.fallback_pid));
 73        }
 74        Some(Pid::from_u32(pid))
 75    }
 76}
 77
 78#[derive(Clone, Debug)]
 79pub struct ProcessInfo {
 80    pub name: String,
 81    pub cwd: PathBuf,
 82    pub argv: Vec<String>,
 83}
 84
 85/// Fetches Zed-relevant Pseudo-Terminal (PTY) process information
 86pub struct PtyProcessInfo {
 87    system: RwLock<System>,
 88    refresh_kind: ProcessRefreshKind,
 89    pid_getter: ProcessIdGetter,
 90    pub current: RwLock<Option<ProcessInfo>>,
 91    task: Mutex<Option<Task<()>>>,
 92}
 93
 94impl PtyProcessInfo {
 95    pub fn new(pty: &Pty) -> PtyProcessInfo {
 96        let process_refresh_kind = ProcessRefreshKind::nothing()
 97            .with_cmd(UpdateKind::Always)
 98            .with_cwd(UpdateKind::Always)
 99            .with_exe(UpdateKind::Always);
100        let refresh_kind = RefreshKind::nothing().with_processes(process_refresh_kind);
101        let system = System::new_with_specifics(refresh_kind);
102
103        PtyProcessInfo {
104            system: RwLock::new(system),
105            refresh_kind: process_refresh_kind,
106            pid_getter: ProcessIdGetter::new(pty),
107            current: RwLock::new(None),
108            task: Mutex::new(None),
109        }
110    }
111
112    pub fn pid_getter(&self) -> &ProcessIdGetter {
113        &self.pid_getter
114    }
115
116    fn refresh(&self) -> Option<MappedRwLockReadGuard<'_, Process>> {
117        let pid = self.pid_getter.pid()?;
118        if self.system.write().refresh_processes_specifics(
119            sysinfo::ProcessesToUpdate::Some(&[pid]),
120            true,
121            self.refresh_kind,
122        ) == 1
123        {
124            RwLockReadGuard::try_map(self.system.read(), |system| system.process(pid)).ok()
125        } else {
126            None
127        }
128    }
129
130    fn get_child(&self) -> Option<MappedRwLockReadGuard<'_, Process>> {
131        let pid = self.pid_getter.fallback_pid();
132        RwLockReadGuard::try_map(self.system.read(), |system| system.process(pid)).ok()
133    }
134
135    #[cfg(unix)]
136    pub(crate) fn kill_current_process(&self) -> bool {
137        let Some(pid) = self.pid_getter.pid() else {
138            return false;
139        };
140        unsafe { libc::killpg(pid.as_u32() as i32, libc::SIGKILL) == 0 }
141    }
142
143    #[cfg(not(unix))]
144    pub(crate) fn kill_current_process(&self) -> bool {
145        self.refresh().is_some_and(|process| process.kill())
146    }
147
148    pub(crate) fn kill_child_process(&self) -> bool {
149        self.get_child().is_some_and(|process| process.kill())
150    }
151
152    fn load(&self) -> Option<ProcessInfo> {
153        let process = self.refresh()?;
154        let cwd = process.cwd().map_or(PathBuf::new(), |p| p.to_owned());
155
156        let info = ProcessInfo {
157            name: process.name().to_str()?.to_owned(),
158            cwd,
159            argv: process
160                .cmd()
161                .iter()
162                .filter_map(|s| s.to_str().map(ToOwned::to_owned))
163                .collect(),
164        };
165        *self.current.write() = Some(info.clone());
166        Some(info)
167    }
168
169    /// Updates the cached process info, emitting a [`Event::TitleChanged`] event if the Zed-relevant info has changed
170    pub fn emit_title_changed_if_changed(self: &Arc<Self>, cx: &mut Context<'_, Terminal>) {
171        if self.task.lock().is_some() {
172            return;
173        }
174        let this = self.clone();
175        let has_changed = cx.background_executor().spawn(async move {
176            let current = this.load();
177            let has_changed = match (this.current.read().as_ref(), current.as_ref()) {
178                (None, None) => false,
179                (Some(prev), Some(now)) => prev.cwd != now.cwd || prev.name != now.name,
180                _ => true,
181            };
182            if has_changed {
183                *this.current.write() = current;
184            }
185            has_changed
186        });
187        let this = Arc::downgrade(self);
188        *self.task.lock() = Some(cx.spawn(async move |term, cx| {
189            if has_changed.await {
190                term.update(cx, |_, cx| cx.emit(Event::TitleChanged)).ok();
191            }
192            if let Some(this) = this.upgrade() {
193                this.task.lock().take();
194            }
195        }));
196    }
197
198    pub fn pid(&self) -> Option<Pid> {
199        self.pid_getter.pid()
200    }
201}