1use std::path::Path;
19use std::process::{Command, Stdio};
20
21use crate::model::{Icon, Item, ItemKey, Source};
22
23const RESULTS: usize = 12;
25
26#[derive(Debug, Clone)]
28struct Process {
29 pid: u32,
30 name: String,
32 cmdline: String,
34 rss: u64,
36}
37
38#[must_use]
44pub fn matching(needle: &str) -> Vec<Item> {
45 let needle = needle.to_lowercase();
46 let tokens: Vec<&str> = needle.split_whitespace().collect();
47
48 let mut processes: Vec<Process> = list()
49 .into_iter()
50 .filter(|process| {
51 let haystack = format!(
52 "{} {} {}",
53 process.name.to_lowercase(),
54 process.cmdline.to_lowercase(),
55 process.pid
56 );
57 tokens.iter().all(|token| haystack.contains(token))
58 })
59 .collect();
60
61 processes.sort_by_key(|process| std::cmp::Reverse(process.rss));
65 processes.truncate(RESULTS);
66
67 processes
68 .into_iter()
69 .map(|process| Item {
70 key: ItemKey(format!("process:{}", process.name)),
74 id: 0,
75 title: process.name,
76 subtitle: format!(
77 "PID {} · {} · {}",
78 process.pid,
79 human_bytes(process.rss),
80 truncate(&process.cmdline, 80),
81 ),
82 icon: Some(Icon::Name("utilities-system-monitor-symbolic".to_owned())),
83 category_icon: None,
84 window: None,
85 source: Source::Process { pid: process.pid },
86 autocomplete: None,
87 score: 0.0,
88 })
89 .collect()
90}
91
92pub fn terminate(pid: u32, force: bool) {
99 let signal = if force { "-KILL" } else { "-TERM" };
100 let result = Command::new("kill")
101 .arg(signal)
102 .arg(pid.to_string())
103 .stdin(Stdio::null())
104 .stdout(Stdio::null())
105 .stderr(Stdio::null())
106 .status();
107
108 match result {
109 Ok(status) if status.success() => {}
110 Ok(status) => tracing::warn!(pid, ?status, "kill refused; process may have exited"),
111 Err(error) => tracing::error!(pid, %error, "could not run kill"),
112 }
113}
114
115fn list() -> Vec<Process> {
117 use std::os::unix::fs::MetadataExt;
118
119 let uid = effective_uid();
120 let own_pid = std::process::id();
121
122 let Ok(entries) = std::fs::read_dir("/proc") else {
123 return Vec::new();
124 };
125
126 entries
127 .flatten()
128 .filter_map(|entry| {
129 let pid: u32 = entry.file_name().to_str()?.parse().ok()?;
130 if pid == own_pid {
131 return None;
132 }
133
134 let metadata = entry.metadata().ok()?;
137 if u64::from(metadata.uid()) != uid {
138 return None;
139 }
140
141 let path = entry.path();
142 read_process(&path, pid)
143 })
144 .collect()
145}
146
147fn read_process(path: &Path, pid: u32) -> Option<Process> {
149 let cmdline_raw = std::fs::read(path.join("cmdline")).ok()?;
150 if cmdline_raw.is_empty() {
152 return None;
153 }
154 let cmdline: String = cmdline_raw
155 .split(|byte| *byte == 0)
156 .filter(|part| !part.is_empty())
157 .map(|part| String::from_utf8_lossy(part).into_owned())
158 .collect::<Vec<_>>()
159 .join(" ");
160
161 let name = std::fs::read_to_string(path.join("comm"))
162 .ok()?
163 .trim()
164 .to_owned();
165
166 let rss = std::fs::read_to_string(path.join("statm"))
168 .ok()
169 .and_then(|statm| {
170 statm
171 .split_whitespace()
172 .nth(1)
173 .and_then(|pages| pages.parse::<u64>().ok())
174 })
175 .map_or(0, |pages| pages * 4096);
176
177 Some(Process {
178 pid,
179 name,
180 cmdline,
181 rss,
182 })
183}
184
185fn effective_uid() -> u64 {
188 std::fs::read_to_string("/proc/self/status")
189 .ok()
190 .and_then(|status| {
191 status.lines().find_map(|line| {
192 let rest = line.strip_prefix("Uid:")?;
193 rest.split_whitespace().nth(1)?.parse().ok()
195 })
196 })
197 .unwrap_or(u64::MAX)
198}
199
200fn human_bytes(bytes: u64) -> String {
201 const MB: u64 = 1024 * 1024;
202 const GB: u64 = 1024 * MB;
203 if bytes >= GB {
204 format!("{:.1} GB", bytes as f64 / GB as f64)
205 } else {
206 format!("{} MB", bytes / MB)
207 }
208}
209
210fn truncate(text: &str, limit: usize) -> String {
211 if text.chars().count() <= limit {
212 text.to_owned()
213 } else {
214 let cut: String = text.chars().take(limit).collect();
215 format!("{cut}…")
216 }
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222 use std::time::{Duration, Instant};
223
224 #[test]
225 fn finds_and_terminates_a_real_process() {
226 let mut child = Command::new("sleep")
227 .arg("300")
228 .stdin(Stdio::null())
229 .stdout(Stdio::null())
230 .spawn()
231 .expect("spawn sleep");
232 let pid = child.id();
233
234 std::thread::sleep(Duration::from_millis(50));
236
237 let items = matching(&pid.to_string());
238 assert!(
239 items
240 .iter()
241 .any(|item| item.source == Source::Process { pid }),
242 "spawned process appears in the listing"
243 );
244
245 terminate(pid, false);
246
247 let deadline = Instant::now() + Duration::from_secs(5);
248 loop {
249 match child.try_wait().expect("try_wait") {
250 Some(_) => break,
251 None if Instant::now() > deadline => panic!("process survived SIGTERM"),
252 None => std::thread::sleep(Duration::from_millis(20)),
253 }
254 }
255 }
256
257 #[test]
258 fn all_tokens_must_match() {
259 let mut child = Command::new("sleep")
260 .arg("300")
261 .stdin(Stdio::null())
262 .stdout(Stdio::null())
263 .spawn()
264 .expect("spawn sleep");
265 let pid = child.id();
266 std::thread::sleep(Duration::from_millis(50));
267
268 let items = matching(&format!("sleep no-such-token-{pid}"));
269 assert!(items.is_empty());
270
271 terminate(pid, true);
272 let _ = child.wait();
273 }
274
275 #[test]
276 fn other_processes_do_not_leak_into_a_pid_query() {
277 assert!(matching("zzqx-definitely-not-a-process").is_empty());
279 }
280
281 #[test]
282 fn bytes_render_for_humans() {
283 assert_eq!(human_bytes(512 * 1024 * 1024), "512 MB");
284 assert_eq!(human_bytes(3 * 1024 * 1024 * 1024), "3.0 GB");
285 }
286}