//! Which processes are running, and where their executable lives. //! //! The audio sources name a process (`Discord.exe`); the settings screen wants to say whether //! that process is up and draw its icon. One snapshot of the process table answers both. use std::collections::HashMap; /// What the settings screen knows about one named process. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Found { pub running: bool, /// The executable to read the icon from, when the snapshot could open the process. pub path: Option, } /// Running processes by normalised name: lowercase, without the `.exe`. pub type Processes = HashMap; /// `Discord.exe` and `discord` are the same process. pub fn normalize(name: &str) -> String { let name = name.trim().to_ascii_lowercase(); name.strip_suffix(".exe").unwrap_or(&name).to_string() } /// One pass over the process table, keeping only `names`. /// /// A name that is not running maps to a `Found` with `running: false`, so the screen can tell /// "not running" from "not asked about yet". pub fn snapshot(names: impl IntoIterator) -> Processes { let wanted: HashMap = names .into_iter() .map(|name| (normalize(&name), Found::default())) .collect(); if wanted.is_empty() { return wanted; } #[cfg(windows)] { windows_snapshot(wanted) } #[cfg(not(windows))] { wanted } } #[cfg(windows)] fn windows_snapshot(mut wanted: Processes) -> Processes { use windows::Win32::Foundation::CloseHandle; use windows::Win32::System::Diagnostics::ToolHelp::{ CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS, }; // SAFETY: the snapshot handle is closed below, and `entry` is a plain struct the calls fill. unsafe { let Ok(snapshot) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) else { return wanted; }; let mut entry = PROCESSENTRY32W { dwSize: std::mem::size_of::() as u32, ..Default::default() }; let mut more = Process32FirstW(snapshot, &mut entry).is_ok(); while more { if let Some(found) = wanted.get_mut(&normalize(&exe_name(&entry))) { found.running = true; if found.path.is_none() { found.path = exe_path(entry.th32ProcessID); } } // A process can exit mid-walk, which ends the enumeration early on some builds. more = Process32NextW(snapshot, &mut entry).is_ok(); } let _ = CloseHandle(snapshot); } // A program that is not open has no process to read its icon from, so look where Windows // keeps it. for (name, found) in wanted.iter_mut() { if found.path.is_none() { found.path = locate(name); } } wanted } #[cfg(windows)] fn exe_name(entry: &windows::Win32::System::Diagnostics::ToolHelp::PROCESSENTRY32W) -> String { let len = entry .szExeFile .iter() .position(|&c| c == 0) .unwrap_or(entry.szExeFile.len()); String::from_utf16_lossy(&entry.szExeFile[..len]) } /// The full path of a process's executable, when it can be opened. #[cfg(windows)] fn exe_path(pid: u32) -> Option { use windows::Win32::Foundation::CloseHandle; use windows::Win32::System::Threading::{ OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW, }; use windows::core::PWSTR; let mut buffer = [0u16; 512]; let mut len = buffer.len() as u32; // SAFETY: `buffer` outlives the call, and `len` carries its capacity in and the written // length out. unsafe { let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?; let query = QueryFullProcessImageNameW( handle, PROCESS_NAME_WIN32, PWSTR(buffer.as_mut_ptr()), &mut len, ); let _ = CloseHandle(handle); query.ok()?; } Some(std::path::PathBuf::from(String::from_utf16_lossy( &buffer[..len as usize], ))) } /// Where a program that is not running might be installed, so its icon can still be drawn. /// /// The search is bounded (a few thousand directories, five levels) and remembers its misses, so /// a name costs at most one walk per run of the app. fn locate(name: &str) -> Option { use std::sync::{Mutex, OnceLock}; static CACHE: OnceLock>>> = OnceLock::new(); let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); if let Some(hit) = cache.lock().ok()?.get(name) { return hit.clone(); } let file = format!("{name}.exe"); let roots = [ "ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA", "APPDATA", "ProgramData", ]; let mut budget = 20_000usize; let found = roots .iter() .filter_map(|var| std::env::var_os(var).map(std::path::PathBuf::from)) .find_map(|root| walk(&root, &file, 5, &mut budget)); if let Ok(mut cache) = cache.lock() { cache.insert(name.to_string(), found.clone()); } found } fn walk( dir: &std::path::Path, file: &str, depth: u32, budget: &mut usize, ) -> Option { if depth == 0 || *budget == 0 { return None; } let mut below = Vec::new(); for entry in std::fs::read_dir(dir).ok()?.flatten() { *budget = budget.saturating_sub(1); if *budget == 0 { break; } let name = entry.file_name().to_string_lossy().to_ascii_lowercase(); let path = entry.path(); if name == file { return Some(path); } if entry.file_type().is_ok_and(|kind| kind.is_dir()) { below.push(path); } } below .into_iter() .find_map(|dir| walk(&dir, file, depth - 1, budget)) } #[cfg(test)] mod tests { use super::*; #[test] fn a_process_name_ignores_case_and_the_exe_suffix() { assert_eq!(normalize("Discord.exe"), "discord"); assert_eq!(normalize(" discord.EXE "), "discord"); assert_eq!(normalize("chrome"), "chrome"); assert_eq!(normalize(""), ""); } #[test] fn names_that_are_not_asked_about_are_not_in_the_snapshot() { let found = snapshot(Vec::new()); assert!(found.is_empty()); } #[cfg(windows)] #[test] fn the_process_table_finds_this_test_binary() { let exe = std::env::current_exe().expect("the test binary's path"); let name = exe .file_name() .expect("the test binary's name") .to_string_lossy() .to_string(); let found = snapshot(vec![name.clone()]); let found = found .get(&normalize(&name)) .expect("the name was asked about"); assert!(found.running, "{name} runs: this test is it"); assert!( found.path.as_ref().is_some_and(|path| path.is_file()), "{name} resolves to its executable" ); } #[cfg(windows)] #[test] fn a_process_that_is_not_running_is_not_found() { let found = snapshot(vec!["definitely-not-a-process-1f3a.exe".to_string()]); let found = found.values().next().expect("the name was asked about"); assert!(!found.running); assert!(found.path.is_none()); } }