Skip to main content

game_cheetah/ui/process_selection/
model.rs

1use std::{cmp::Ordering, collections::HashSet};
2
3use crate::ProcessInfo;
4
5use super::{ProcessSortColumn, SortDirection, cmp_ascii_case_insensitive, contains_ignore_ascii_case};
6
7#[derive(Debug, Clone, PartialEq, Eq, Hash)]
8pub enum ProcessRowKey {
9    Group(String),
10    Process { pid: process_memory::Pid, start_time: u64 },
11}
12
13impl ProcessRowKey {
14    pub fn process(process: &ProcessInfo) -> Self {
15        Self::Process {
16            pid: process.pid,
17            start_time: process.start_time,
18        }
19    }
20}
21
22#[derive(Default)]
23pub struct ProcessSelectionState {
24    pub selected: Option<ProcessRowKey>,
25    pub expanded: HashSet<String>,
26    /// Explicit collapses override automatic expansion for this filter only.
27    pub collapsed_matches: HashSet<String>,
28    pub last_filter: String,
29    pub scroll_to_selection: bool,
30    pub row_focus: Option<egui::Id>,
31    pub message: Option<String>,
32}
33
34pub(super) struct ProcessRow<'a> {
35    pub key: ProcessRowKey,
36    pub process: &'a ProcessInfo,
37    pub group_size: usize,
38    pub matching_children: usize,
39    pub expanded: bool,
40    pub parent: Option<String>,
41}
42
43impl ProcessRow<'_> {
44    pub fn is_group(&self) -> bool {
45        self.group_size > 1
46    }
47}
48
49pub(super) fn matches_filter(process: &ProcessInfo, filter: &str) -> bool {
50    contains_ignore_ascii_case(&process.name, filter) || contains_ignore_ascii_case(&process.cmd, filter) || process.pid.to_string().contains(filter)
51}
52
53fn compare(a: &ProcessInfo, b: &ProcessInfo, column: ProcessSortColumn, direction: SortDirection) -> Ordering {
54    let order = match column {
55        ProcessSortColumn::Pid => a.pid.cmp(&b.pid),
56        ProcessSortColumn::Name => cmp_ascii_case_insensitive(&a.name, &b.name),
57        ProcessSortColumn::Memory => a.memory.cmp(&b.memory),
58        ProcessSortColumn::Command => cmp_ascii_case_insensitive(&a.cmd, &b.cmd),
59    };
60    let order = if direction == SortDirection::Descending { order.reverse() } else { order };
61    order.then_with(|| a.pid.cmp(&b.pid)).then_with(|| a.start_time.cmp(&b.start_time))
62}
63
64/// Filter actual instances, not representative/group metadata. A matching
65/// child is always reachable, even when the group was previously collapsed.
66pub(super) fn build_rows<'a>(
67    processes: &'a [ProcessInfo],
68    filter: &str,
69    column: ProcessSortColumn,
70    direction: SortDirection,
71    state: &ProcessSelectionState,
72) -> Vec<ProcessRow<'a>> {
73    let mut top: Vec<_> = processes
74        .iter()
75        .filter(|process| {
76            if process.instances.len() > 1 {
77                process.instances.iter().any(|child| matches_filter(child, filter))
78            } else {
79                matches_filter(process, filter)
80            }
81        })
82        .collect();
83    top.sort_by(|a, b| compare(a, b, column, direction));
84    let mut rows = Vec::new();
85    for process in top {
86        let group_size = process.instances.len();
87        let is_group = group_size > 1;
88        let mut children: Vec<_> = process.instances.iter().filter(|child| matches_filter(child, filter)).collect();
89        let expanded = is_group
90            && if filter.is_empty() {
91                state.expanded.contains(&process.executable)
92            } else {
93                !state.collapsed_matches.contains(&process.executable)
94            };
95        rows.push(ProcessRow {
96            key: if is_group {
97                ProcessRowKey::Group(process.executable.clone())
98            } else {
99                ProcessRowKey::process(process)
100            },
101            process,
102            group_size,
103            matching_children: children.len(),
104            expanded,
105            parent: None,
106        });
107        if expanded {
108            children.sort_by(|a, b| compare(a, b, column, direction));
109            for child in children {
110                rows.push(ProcessRow {
111                    key: ProcessRowKey::process(child),
112                    process: child,
113                    group_size: 0,
114                    matching_children: 0,
115                    expanded: false,
116                    parent: Some(process.executable.clone()),
117                });
118            }
119        }
120    }
121    rows
122}
123
124pub(super) fn process_counts(processes: &[ProcessInfo], filter: &str) -> (usize, usize, usize) {
125    let mut total = 0;
126    let mut matched = 0;
127    let mut groups = 0;
128    for process in processes {
129        if process.instances.len() > 1 {
130            groups += 1;
131            total += process.instances.len();
132            matched += process.instances.iter().filter(|child| matches_filter(child, filter)).count();
133        } else {
134            total += 1;
135            matched += usize::from(matches_filter(process, filter));
136        }
137    }
138    (total, matched, groups)
139}
140
141impl ProcessSelectionState {
142    pub(super) fn update_filter(&mut self, filter: &str) {
143        if self.last_filter != filter {
144            self.last_filter = filter.to_owned();
145            self.collapsed_matches.clear();
146            self.message = None;
147        }
148    }
149
150    pub(super) fn toggle_group(&mut self, key: &str, expanded: bool, filtered: bool) {
151        if expanded {
152            self.expanded.remove(key);
153            if filtered {
154                self.collapsed_matches.insert(key.to_owned());
155            }
156        } else {
157            self.expanded.insert(key.to_owned());
158            self.collapsed_matches.remove(key);
159        }
160    }
161
162    pub(super) fn reconcile(&mut self, rows: &[ProcessRow<'_>]) {
163        if self.selected.as_ref().is_some_and(|key| !rows.iter().any(|row| &row.key == key)) {
164            self.selected = None;
165        }
166    }
167
168    pub(super) fn move_selection(&mut self, rows: &[ProcessRow<'_>], backwards: bool) {
169        if rows.is_empty() {
170            return;
171        }
172        let current = self.selected.as_ref().and_then(|key| rows.iter().position(|row| &row.key == key));
173        let next = match current {
174            Some(i) if backwards => i.saturating_sub(1),
175            Some(i) => (i + 1).min(rows.len() - 1),
176            None if backwards => rows.len() - 1,
177            None => 0,
178        };
179        self.selected = Some(rows[next].key.clone());
180        self.scroll_to_selection = true;
181        self.message = None;
182    }
183}
184
185pub(super) fn resolve_process<'a>(processes: &'a [ProcessInfo], key: &ProcessRowKey) -> Option<&'a ProcessInfo> {
186    processes
187        .iter()
188        .flat_map(|process| {
189            if process.instances.len() > 1 {
190                process.instances.as_slice()
191            } else {
192                std::slice::from_ref(process)
193            }
194        })
195        .find(|process| ProcessRowKey::process(process) == *key)
196}
197
198#[cfg(test)]
199pub(super) mod tests {
200    use super::*;
201
202    pub(crate) fn process(pid: process_memory::Pid, name: &str, memory: usize) -> ProcessInfo {
203        ProcessInfo {
204            pid,
205            start_time: 100,
206            executable: format!("/games/{name}"),
207            name: name.to_owned(),
208            cmd: format!("/games/{name} --instance={pid}"),
209            user: "test".to_owned(),
210            memory,
211            instances: Vec::new(),
212        }
213    }
214
215    fn group() -> ProcessInfo {
216        let a = process(10, "game", 10);
217        let b = process(20, "game", 20);
218        ProcessInfo {
219            memory: 30,
220            instances: vec![a.clone(), b],
221            ..a
222        }
223    }
224
225    #[test]
226    fn pid_filter_expands_only_matching_child_and_counts_instances() {
227        let processes = vec![group(), process(30, "other", 5)];
228        let state = ProcessSelectionState::default();
229        let rows = build_rows(&processes, "20", ProcessSortColumn::Memory, SortDirection::Descending, &state);
230        assert_eq!(rows.len(), 2);
231        assert!(rows[0].is_group());
232        assert!(rows[0].expanded);
233        assert_eq!(rows[0].matching_children, 1);
234        assert_eq!(rows[1].process.pid, 20);
235        assert_eq!(process_counts(&processes, ""), (3, 3, 1));
236        assert_eq!(process_counts(&processes, "20"), (3, 1, 1));
237        assert_eq!(process_counts(&processes, "/GAMES/GAME"), (3, 2, 1));
238    }
239
240    #[test]
241    fn collapsed_filter_matches_can_be_reopened() {
242        let processes = vec![group()];
243        let mut state = ProcessSelectionState::default();
244        state.update_filter("20");
245        state.toggle_group("/games/game", true, true);
246        assert_eq!(build_rows(&processes, "20", ProcessSortColumn::Pid, SortDirection::Ascending, &state).len(), 1);
247        state.toggle_group("/games/game", false, true);
248        assert_eq!(build_rows(&processes, "20", ProcessSortColumn::Pid, SortDirection::Ascending, &state).len(), 2);
249        state.toggle_group("/games/game", true, true);
250        state.update_filter("game");
251        assert_eq!(
252            build_rows(&processes, "game", ProcessSortColumn::Pid, SortDirection::Ascending, &state).len(),
253            3
254        );
255    }
256
257    #[test]
258    fn stable_sort_preserves_identity_and_rejects_recycled_pid() {
259        let mut processes = vec![process(20, "game", 10), process(10, "game", 10)];
260        let key = ProcessRowKey::process(&processes[0]);
261        let mut state = ProcessSelectionState {
262            selected: Some(key.clone()),
263            ..Default::default()
264        };
265        for direction in [SortDirection::Ascending, SortDirection::Descending] {
266            let rows = build_rows(&processes, "", ProcessSortColumn::Memory, direction, &state);
267            assert_eq!(rows[0].process.pid, 10);
268            state.reconcile(&rows);
269            assert_eq!(state.selected, Some(key.clone()));
270        }
271        processes[0].memory = 100;
272        let rows = build_rows(&processes, "", ProcessSortColumn::Memory, SortDirection::Descending, &state);
273        state.reconcile(&rows);
274        assert_eq!(state.selected, Some(key.clone()));
275        processes[0].start_time += 1;
276        assert!(resolve_process(&processes, &key).is_none());
277        let rows = build_rows(&processes, "", ProcessSortColumn::Memory, SortDirection::Descending, &state);
278        state.reconcile(&rows);
279        assert_eq!(state.selected, None);
280    }
281
282    #[test]
283    fn groups_keep_expansion_when_representative_changes_and_children_follow_sort() {
284        let mut processes = vec![group()];
285        let mut state = ProcessSelectionState::default();
286        state.expanded.insert("/games/game".to_owned());
287        processes[0].pid = 99;
288        let rows = build_rows(&processes, "", ProcessSortColumn::Memory, SortDirection::Descending, &state);
289        assert_eq!(rows.len(), 3);
290        assert_eq!(rows[1].process.pid, 20);
291        assert!(resolve_process(&processes, &rows[0].key).is_none());
292        assert_eq!(resolve_process(&processes, &rows[1].key).unwrap().pid, 20);
293    }
294
295    #[test]
296    fn keyboard_selection_clamps_and_filtered_selection_is_cleared() {
297        let processes = vec![process(1, "alpha", 10), process(2, "beta", 20)];
298        let mut state = ProcessSelectionState::default();
299        let rows = build_rows(&processes, "", ProcessSortColumn::Name, SortDirection::Ascending, &state);
300        state.move_selection(&rows, false);
301        assert_eq!(state.selected, Some(rows[0].key.clone()));
302        state.move_selection(&rows, false);
303        state.move_selection(&rows, false);
304        assert_eq!(state.selected, Some(rows[1].key.clone()));
305        let rows = build_rows(&processes, "alpha", ProcessSortColumn::Name, SortDirection::Ascending, &state);
306        state.reconcile(&rows);
307        assert_eq!(state.selected, None);
308    }
309}