Skip to main content

game_cheetah/ui/
process_selection.rs

1use i18n_embed_fl::fl;
2
3use crate::ui::app::{App, AppState};
4
5mod model;
6use model::{ProcessRow, build_rows, process_counts, resolve_process};
7pub use model::{ProcessRowKey, ProcessSelectionState};
8
9#[derive(Debug, Clone, Copy, PartialEq, Default)]
10pub enum ProcessSortColumn {
11    Pid,
12    Name,
13    #[default]
14    Memory,
15    Command,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Default)]
19pub enum SortDirection {
20    Ascending,
21    #[default]
22    Descending,
23}
24
25fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
26    needle.is_empty()
27        || haystack
28            .as_bytes()
29            .windows(needle.len())
30            .any(|window| window.eq_ignore_ascii_case(needle.as_bytes()))
31}
32
33fn cmp_ascii_case_insensitive(a: &str, b: &str) -> std::cmp::Ordering {
34    a.bytes().map(|b| b.to_ascii_lowercase()).cmp(b.bytes().map(|b| b.to_ascii_lowercase()))
35}
36
37/// Highlight ASCII-insensitive matches without changing UTF-8 boundaries.
38fn highlight_job(ui: &egui::Ui, text: &str, filter: &str, color: egui::Color32, monospace: bool) -> egui::text::LayoutJob {
39    let font_id = if monospace { egui::TextStyle::Monospace } else { egui::TextStyle::Body }.resolve(ui.style());
40    let normal = egui::TextFormat {
41        font_id,
42        color,
43        ..Default::default()
44    };
45    let marked = egui::TextFormat {
46        color: ui.visuals().selection.stroke.color,
47        background: ui.ctx().global_style().visuals.selection.bg_fill.gamma_multiply(0.55),
48        ..normal.clone()
49    };
50    let mut job = egui::text::LayoutJob::default();
51    let mut cursor = 0;
52    if !filter.is_empty() {
53        for (start, _) in text.char_indices() {
54            let end = start + filter.len();
55            if start >= cursor && text.is_char_boundary(end) && text.get(start..end).is_some_and(|s| s.eq_ignore_ascii_case(filter)) {
56                job.append(&text[cursor..start], 0.0, normal.clone());
57                job.append(&text[start..end], 0.0, marked.clone());
58                cursor = end;
59            }
60        }
61    }
62    job.append(&text[cursor..], 0.0, normal);
63    job
64}
65
66const ROW_HEIGHT: f32 = 34.0;
67const AVATAR_SIZE: f32 = 22.0;
68const DISCLOSURE_WIDTH: f32 = 18.0;
69/// Auto-refresh indicator; the list really is live, so green reads as "on".
70/// Window heights below this hide the subtitle and keyboard hint.
71const COMPACT_HEIGHT: f32 = 520.0;
72const LIVE_COLOR: egui::Color32 = egui::Color32::from_rgb(88, 204, 128);
73
74/// Stable per-executable hue, so a game keeps its avatar color across launches.
75fn avatar_color(executable: &str) -> egui::Color32 {
76    let hash = executable
77        .bytes()
78        .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3));
79    egui::ecolor::HsvaGamma {
80        h: (hash % 360) as f32 / 360.0,
81        s: 0.6,
82        v: 0.6,
83        a: 1.0,
84    }
85    .into()
86}
87
88/// Rounded tile with the process's initial, like an app launcher icon.
89fn avatar(ui: &mut egui::Ui, process: &crate::ProcessInfo, size: f32) {
90    let (rect, _) = ui.allocate_exact_size(egui::vec2(size, size), egui::Sense::hover());
91    let letter = process
92        .name
93        .chars()
94        .find(|c| c.is_alphanumeric())
95        .and_then(|c| c.to_uppercase().next())
96        .unwrap_or('?');
97    ui.painter()
98        .rect_filled(rect, egui::CornerRadius::same((size * 0.28) as u8), avatar_color(&process.executable));
99    ui.painter().text(
100        rect.center(),
101        egui::Align2::CENTER_CENTER,
102        letter,
103        egui::FontId::proportional((size * 0.62).round()),
104        egui::Color32::WHITE,
105    );
106}
107
108/// Filter field with a search glyph and an inline clear button.
109fn search_field(app: &mut App, ui: &mut egui::Ui) -> egui::Response {
110    let response = ui.add(
111        egui::TextEdit::singleline(&mut app.state.process_filter)
112            .id(egui::Id::new("process-filter"))
113            .hint_text(fl!(crate::LANGUAGE_LOADER, "filter-processes-hint"))
114            .desired_width(ui.available_width())
115            .margin(egui::Margin {
116                left: 36,
117                right: 36,
118                top: 10,
119                bottom: 10,
120            }),
121    );
122    let focus_shortcut = ui.input_mut(|input| input.consume_key(egui::Modifiers::COMMAND, egui::Key::F));
123    if app.state.set_focus || focus_shortcut {
124        response.request_focus();
125        app.state.set_focus = false;
126    }
127    let icon_color = if response.has_focus() {
128        crate::ui::theme::ACCENT_TEXT
129    } else {
130        ui.visuals().weak_text_color()
131    };
132    paint_search_icon(ui.painter(), response.rect.left_center() + egui::vec2(18.0, 0.0), icon_color);
133    if !app.state.process_filter.is_empty() {
134        let clear_rect = egui::Rect::from_center_size(response.rect.right_center() - egui::vec2(19.0, 0.0), egui::vec2(26.0, 26.0));
135        let clear = ui
136            .put(
137                clear_rect,
138                egui::Button::new(egui::RichText::new("×").size(16.0))
139                    .frame(false)
140                    .corner_radius(egui::CornerRadius::same(13)),
141            )
142            .on_hover_text(fl!(crate::LANGUAGE_LOADER, "reset-filter-button"))
143            .on_hover_cursor(egui::CursorIcon::PointingHand);
144        if clear.clicked() {
145            app.state.process_filter.clear();
146            response.request_focus();
147        }
148    }
149    response
150}
151
152/// Magnifier drawn from shapes; emoji fonts do not reliably cover it.
153fn paint_search_icon(painter: &egui::Painter, center: egui::Pos2, color: egui::Color32) {
154    let lens = center - egui::vec2(2.5, 2.5);
155    painter.circle_stroke(lens, 4.5, egui::Stroke::new(1.7, color));
156    let handle = egui::vec2(1.0, 1.0).normalized();
157    painter.line_segment([lens + handle * 5.5, lens + handle * 13.0], egui::Stroke::new(2.4, color));
158}
159
160/// Small rounded count pill shown next to a group's name.
161fn badge(ui: &mut egui::Ui, text: String, color: egui::Color32, fill: egui::Color32) -> egui::Response {
162    let galley = ui.painter().layout_no_wrap(text, egui::FontId::proportional(11.0), color);
163    let (rect, response) = ui.allocate_exact_size(galley.size() + egui::vec2(14.0, 4.0), egui::Sense::hover());
164    ui.painter().rect_filled(rect, egui::CornerRadius::same((rect.height() / 2.0) as u8), fill);
165    ui.painter().galley(rect.center() - galley.size() / 2.0, galley, color);
166    response
167}
168
169pub fn view_process_selection(app: &mut App, ui: &mut egui::Ui) {
170    egui::CentralPanel::default()
171        .frame(egui::Frame::central_panel(ui.style()).inner_margin(egui::Margin::symmetric(20, 16)))
172        .show(ui, |ui| {
173            let full = ui.available_rect_before_wrap();
174            // Short windows drop the subtitle and keyboard hint to keep rows visible.
175            let compact = full.height() < COMPACT_HEIGHT;
176            let footer_height = if compact { 62.0 } else { 84.0 };
177            let content_rect = egui::Rect::from_min_max(full.min, egui::pos2(full.max.x, full.max.y - footer_height - 12.0));
178            let footer_rect = egui::Rect::from_min_max(egui::pos2(full.min.x, full.max.y - footer_height), full.max);
179            let mut content = ui.new_child(egui::UiBuilder::new().max_rect(content_rect).layout(egui::Layout::top_down(egui::Align::Min)));
180            let mut connect = process_content(app, &mut content, compact);
181            let mut footer = ui.new_child(egui::UiBuilder::new().max_rect(footer_rect).layout(egui::Layout::top_down(egui::Align::Min)));
182            connect |= process_footer(app, &mut footer, compact);
183            if connect && app.app_state == AppState::ProcessSelection {
184                app.connect_selected_process();
185            }
186        });
187}
188
189fn process_content(app: &mut App, ui: &mut egui::Ui, compact: bool) -> bool {
190    ui.heading(egui::RichText::new(fl!(crate::LANGUAGE_LOADER, "process-selection-title")).size(24.0).strong());
191    if compact {
192        ui.add_space(8.0);
193    } else {
194        ui.add_space(2.0);
195        ui.label(egui::RichText::new(fl!(crate::LANGUAGE_LOADER, "process-selection-subtitle")).size(13.5).weak());
196        ui.add_space(14.0);
197    }
198
199    let filter_response = search_field(app, ui);
200
201    // Read the edited value, not last frame's copy. Clear stale selection
202    // before drawing the footer so a hidden result cannot be attached to.
203    let filter = app.state.process_filter.trim().to_owned();
204    app.process_selection.update_filter(&filter);
205    let (total, matched, groups) = process_counts(&app.state.processes, &filter);
206    ui.add_space(8.0);
207    egui::Sides::new().shrink_left().truncate().show(
208        ui,
209        |ui| {
210            let count = if filter.is_empty() {
211                fl!(crate::LANGUAGE_LOADER, "process-count-total", total = total)
212            } else {
213                fl!(crate::LANGUAGE_LOADER, "process-count-filtered", shown = matched, total = total)
214            };
215            ui.label(egui::RichText::new(count).size(12.5).weak());
216            ui.label(egui::RichText::new("·").size(12.5).weak());
217            ui.label(
218                egui::RichText::new(fl!(crate::LANGUAGE_LOADER, "process-group-count", groups = groups))
219                    .size(12.5)
220                    .weak(),
221            )
222            .on_hover_text(fl!(crate::LANGUAGE_LOADER, "process-group-count-hint"));
223        },
224        |ui| {
225            ui.label(egui::RichText::new(fl!(crate::LANGUAGE_LOADER, "process-refresh-status")).size(12.5).weak());
226            let (dot, _) = ui.allocate_exact_size(egui::vec2(8.0, 8.0), egui::Sense::hover());
227            ui.painter().circle_filled(dot.center(), 3.5, LIVE_COLOR);
228            ui.painter().circle_filled(dot.center(), 6.0, LIVE_COLOR.gamma_multiply(0.18));
229        },
230    );
231    ui.add_space(8.0);
232
233    let rows = build_rows(
234        &app.state.processes,
235        &filter,
236        app.process_sort_column,
237        app.process_sort_direction,
238        &app.process_selection,
239    );
240    app.process_selection.reconcile(&rows);
241    let filter_focused = filter_response.has_focus();
242    let keyboard_allowed = !egui::Popup::is_any_open(ui.ctx())
243        && (filter_focused || ui.memory(|memory| memory.focused().is_none() || memory.focused() == app.process_selection.row_focus));
244    let mut connect = false;
245    if keyboard_allowed {
246        for (key, backwards) in [(egui::Key::ArrowDown, false), (egui::Key::ArrowUp, true)] {
247            if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, key)) {
248                app.process_selection.move_selection(&rows, backwards);
249            }
250        }
251        if !filter_focused {
252            for (key, last) in [(egui::Key::Home, false), (egui::Key::End, true)] {
253                if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, key)) {
254                    let row = if last { rows.last() } else { rows.first() };
255                    app.process_selection.selected = row.map(|row| row.key.clone());
256                    app.process_selection.scroll_to_selection = true;
257                }
258            }
259        }
260        if let Some(index) = rows.iter().position(|row| Some(&row.key) == app.process_selection.selected.as_ref()) {
261            let row = &rows[index];
262            if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {
263                if row.is_group() {
264                    app.process_selection.toggle_group(&row.process.executable, row.expanded, !filter.is_empty());
265                } else {
266                    connect = true;
267                }
268            }
269            if !filter_focused && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::ArrowRight)) && row.is_group() {
270                if row.expanded {
271                    app.process_selection.move_selection(&rows, false);
272                } else {
273                    app.process_selection.toggle_group(&row.process.executable, false, !filter.is_empty());
274                }
275            }
276            if !filter_focused && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::ArrowLeft)) {
277                if row.is_group() && row.expanded {
278                    app.process_selection.toggle_group(&row.process.executable, true, !filter.is_empty());
279                } else if let Some(parent) = &row.parent {
280                    app.process_selection.selected = Some(ProcessRowKey::Group(parent.clone()));
281                    app.process_selection.scroll_to_selection = true;
282                }
283            }
284        }
285    }
286
287    if rows.is_empty() {
288        ui.add_space(24.0);
289        ui.vertical_centered(|ui| {
290            ui.heading(fl!(crate::LANGUAGE_LOADER, "no-processes-match"));
291            ui.add_space(6.0);
292            ui.label(if total == 0 {
293                fl!(crate::LANGUAGE_LOADER, "no-processes-available-hint")
294            } else {
295                fl!(crate::LANGUAGE_LOADER, "no-processes-match-hint")
296            });
297            if !filter.is_empty() && ui.button(fl!(crate::LANGUAGE_LOADER, "reset-filter-button")).clicked() {
298                app.state.process_filter.clear();
299                app.state.set_focus = true;
300            }
301        });
302    } else {
303        connect |= process_table(
304            ui,
305            &rows,
306            &filter,
307            &mut app.process_selection,
308            &mut app.process_sort_column,
309            &mut app.process_sort_direction,
310        );
311    }
312    connect
313}
314
315fn process_table(
316    ui: &mut egui::Ui,
317    rows: &[ProcessRow<'_>],
318    filter: &str,
319    selection: &mut ProcessSelectionState,
320    sort_column: &mut ProcessSortColumn,
321    sort_direction: &mut SortDirection,
322) -> bool {
323    use egui_extras::{Column, TableBuilder};
324    let mut connect = false;
325    let mut toggle = None;
326    let scroll_to = if std::mem::take(&mut selection.scroll_to_selection) {
327        rows.iter().position(|row| Some(&row.key) == selection.selected.as_ref())
328    } else {
329        None
330    };
331    // Bars are relative to the largest visible entry; sqrt keeps small
332    // processes visible next to a multi-gigabyte game.
333    let max_memory = rows.iter().map(|row| row.process.memory).max().unwrap_or(0).max(1) as f32;
334    let accent = crate::ui::theme::ACCENT_TEXT;
335    let memory_text_width = ui
336        .painter()
337        .layout_no_wrap(
338            "Σ 999.99 MB".to_owned(),
339            egui::TextStyle::Monospace.resolve(ui.style()),
340            egui::Color32::PLACEHOLDER,
341        )
342        .size()
343        .x
344        + 12.0;
345    // Only the body scrolls vertically: the table header stays visible.
346    // At narrow window widths the command column is reached horizontally.
347    egui::ScrollArea::horizontal()
348        .id_salt("process-horizontal")
349        .auto_shrink([false, false])
350        .show(ui, |ui| {
351            // Calmer table chrome: faint column dividers, a tinted (not
352            // saturated) selection and soft hover/stripe fills.
353            let visuals = &mut ui.style_mut().visuals;
354            visuals.widgets.noninteractive.bg_stroke.color = egui::Color32::from_rgb(42, 46, 54);
355            visuals.selection.bg_fill = egui::Color32::from_rgb(19, 72, 96);
356            visuals.widgets.hovered.bg_fill = egui::Color32::from_rgb(35, 40, 47);
357            visuals.faint_bg_color = egui::Color32::from_rgb(23, 26, 31);
358
359            let available_width = ui.available_width();
360            let header_line = ui.cursor().top() + 32.0 + ui.spacing().item_spacing.y * 0.5;
361            ui.painter().hline(
362                ui.max_rect().x_range(),
363                header_line,
364                egui::Stroke::new(1.0, egui::Color32::from_rgb(52, 58, 68)),
365            );
366            let mut table = TableBuilder::new(ui)
367                .id_salt("process-list-v2")
368                .striped(true)
369                .resizable(true)
370                .sense(egui::Sense::click())
371                .cell_layout(egui::Layout::left_to_right(egui::Align::Center))
372                .min_scrolled_height(80.0)
373                .animate_scrolling(false)
374                .column(Column::initial(260.0).at_least(190.0).clip(true))
375                .column(Column::initial(85.0).at_least(70.0))
376                .column(Column::initial(170.0).at_least(110.0))
377                .column(Column::remainder().at_least((available_width - 540.0).max(180.0)));
378            if let Some(index) = scroll_to {
379                table = table.scroll_to_row(index, None);
380            }
381            table
382                .header(32.0, |mut header| {
383                    for (label, column) in [
384                        (fl!(crate::LANGUAGE_LOADER, "name-heading"), ProcessSortColumn::Name),
385                        (fl!(crate::LANGUAGE_LOADER, "pid-heading"), ProcessSortColumn::Pid),
386                        (fl!(crate::LANGUAGE_LOADER, "memory-heading"), ProcessSortColumn::Memory),
387                        (fl!(crate::LANGUAGE_LOADER, "command-heading"), ProcessSortColumn::Command),
388                    ] {
389                        header.col(|ui| {
390                            let active = *sort_column == column;
391                            let mut job = egui::text::LayoutJob::default();
392                            let font = egui::FontId::proportional(13.5);
393                            let color = if active {
394                                ui.visuals().strong_text_color()
395                            } else {
396                                ui.visuals().weak_text_color()
397                            };
398                            job.append(&label, 0.0, egui::TextFormat::simple(font.clone(), color));
399                            if active {
400                                let arrow = if *sort_direction == SortDirection::Ascending { " ⏶" } else { " ⏷" };
401                                job.append(arrow, 0.0, egui::TextFormat::simple(font, accent));
402                            }
403                            if ui
404                                .add(egui::Button::new(job).frame(false))
405                                .on_hover_text(fl!(crate::LANGUAGE_LOADER, "process-sort-hint"))
406                                .on_hover_cursor(egui::CursorIcon::PointingHand)
407                                .clicked()
408                            {
409                                *sort_direction = if active {
410                                    if *sort_direction == SortDirection::Ascending {
411                                        SortDirection::Descending
412                                    } else {
413                                        SortDirection::Ascending
414                                    }
415                                } else if column == ProcessSortColumn::Memory {
416                                    SortDirection::Descending
417                                } else {
418                                    SortDirection::Ascending
419                                };
420                                *sort_column = column;
421                                selection.scroll_to_selection = true;
422                            }
423                        });
424                    }
425                })
426                .body(|body| {
427                    body.rows(ROW_HEIGHT, rows.len(), |mut row| {
428                        let index = row.index();
429                        let item = &rows[index];
430                        let process = item.process;
431                        let selected = selection.selected.as_ref() == Some(&item.key);
432                        row.set_selected(selected);
433                        let text_color = |ui: &egui::Ui, normal| {
434                            if selected { ui.visuals().selection.stroke.color } else { normal }
435                        };
436                        let mut disclosure_clicked = false;
437                        row.col(|ui| {
438                            let cell = ui.max_rect();
439                            if selected {
440                                let bar = egui::Rect::from_min_max(cell.left_top(), egui::pos2(cell.left() + 3.0, cell.bottom()));
441                                ui.painter().rect_filled(bar, egui::CornerRadius::same(1), accent);
442                            }
443                            if item.parent.is_some() {
444                                // Tree guide from the group's disclosure arrow to this instance.
445                                let last = rows.get(index + 1).is_none_or(|next| next.parent != item.parent);
446                                let x = cell.left() + DISCLOSURE_WIDTH * 0.5 + 4.0;
447                                let bottom = if last { cell.center().y } else { cell.bottom() };
448                                let guide = egui::Stroke::new(1.0, egui::Color32::from_rgb(70, 78, 90));
449                                ui.painter().vline(x, cell.top()..=bottom, guide);
450                                ui.painter().hline(x..=x + 12.0, cell.center().y, guide);
451                                ui.add_space(DISCLOSURE_WIDTH + ui.spacing().item_spacing.x + 4.0);
452                            } else if item.is_group() {
453                                ui.add_space(4.0);
454                                let response = ui
455                                    .add(
456                                        egui::Button::new(
457                                            egui::RichText::new(if item.expanded { "⏷" } else { "⏵" }).color(text_color(ui, ui.visuals().text_color())),
458                                        )
459                                        .frame(false)
460                                        .min_size(egui::vec2(DISCLOSURE_WIDTH, 24.0)),
461                                    )
462                                    .on_hover_text(fl!(crate::LANGUAGE_LOADER, "process-expand-hint"));
463                                if response.clicked() {
464                                    disclosure_clicked = true;
465                                    toggle = Some((process.executable.clone(), item.expanded));
466                                    selection.selected = Some(item.key.clone());
467                                }
468                            } else {
469                                // Reserve the disclosure slot so every name
470                                // on a level starts at the same x.
471                                ui.add_space(4.0 + DISCLOSURE_WIDTH + ui.spacing().item_spacing.x);
472                            }
473                            if item.parent.is_none() {
474                                avatar(ui, process, AVATAR_SIZE);
475                            }
476                            let badge_text = item.is_group().then(|| {
477                                if filter.is_empty() {
478                                    fl!(crate::LANGUAGE_LOADER, "process-group-badge", count = item.group_size)
479                                } else {
480                                    fl!(
481                                        crate::LANGUAGE_LOADER,
482                                        "process-group-filtered-badge",
483                                        matched = item.matching_children,
484                                        total = item.group_size
485                                    )
486                                }
487                            });
488                            let badge_width = badge_text.as_ref().map_or(0.0, |text| {
489                                ui.painter()
490                                    .layout_no_wrap(text.clone(), egui::FontId::proportional(11.0), egui::Color32::PLACEHOLDER)
491                                    .size()
492                                    .x
493                                    + 14.0
494                                    + ui.spacing().item_spacing.x
495                            });
496                            let name_width = (ui.available_width() - badge_width).max(32.0);
497                            let name_color = if item.parent.is_some() {
498                                ui.visuals().text_color()
499                            } else {
500                                ui.visuals().strong_text_color()
501                            };
502                            let name = highlight_job(ui, &process.name, filter, text_color(ui, name_color), false);
503                            // Only as wide as the name, so the group badge follows it directly.
504                            ui.allocate_ui_with_layout(egui::vec2(name_width, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {
505                                ui.add(egui::Label::new(name).selectable(false).truncate())
506                                    .on_hover_text(format!("{}\n{}", process.name, process.executable));
507                            });
508                            if let Some(text) = badge_text {
509                                let color = text_color(ui, accent);
510                                let fill = if selected {
511                                    egui::Color32::from_white_alpha(30)
512                                } else {
513                                    accent.gamma_multiply(0.14)
514                                };
515                                badge(ui, text, color, fill);
516                            }
517                        });
518                        row.col(|ui| {
519                            if item.is_group() {
520                                ui.label(egui::RichText::new("—").color(text_color(ui, ui.visuals().weak_text_color())))
521                                    .on_hover_text(fl!(crate::LANGUAGE_LOADER, "process-group-select-hint"));
522                            } else {
523                                let job = highlight_job(ui, &process.pid.to_string(), filter, text_color(ui, ui.visuals().text_color()), true);
524                                ui.add(egui::Label::new(job).selectable(false));
525                            }
526                        });
527                        row.col(|ui| {
528                            // Compact usage bar right of the value, relative to the largest entry.
529                            let cell = ui.max_rect();
530                            let fraction = (process.memory as f32 / max_memory).sqrt().clamp(0.0, 1.0);
531                            let track = egui::Rect::from_min_max(
532                                egui::pos2(cell.left() + memory_text_width, cell.center().y - 2.0),
533                                egui::pos2(cell.right() - 10.0, cell.center().y + 2.0),
534                            );
535                            if track.width() >= 12.0 {
536                                let (track_color, fill_color) = if selected {
537                                    (egui::Color32::from_white_alpha(30), egui::Color32::from_white_alpha(190))
538                                } else {
539                                    (egui::Color32::from_white_alpha(14), accent.gamma_multiply(0.75))
540                                };
541                                ui.painter().rect_filled(track, egui::CornerRadius::same(2), track_color);
542                                let fill = egui::Rect::from_min_size(track.min, egui::vec2((track.width() * fraction).max(2.0), track.height()));
543                                ui.painter().rect_filled(fill, egui::CornerRadius::same(2), fill_color);
544                            }
545                            let memory = gabi::BytesConfig::default().bytes(process.memory as u64).to_string();
546                            let memory = if item.is_group() { format!("Σ {memory}") } else { memory };
547                            let response = ui.add(
548                                egui::Label::new(egui::RichText::new(memory).monospace().color(text_color(ui, ui.visuals().text_color())))
549                                    .selectable(false)
550                                    .truncate(),
551                            );
552                            if item.is_group() {
553                                response.on_hover_text(fl!(crate::LANGUAGE_LOADER, "process-group-memory-hint"));
554                            }
555                        });
556                        row.col(|ui| {
557                            let command = if item.is_group() { &process.executable } else { &process.cmd };
558                            let job = highlight_job(ui, command, filter, text_color(ui, ui.visuals().weak_text_color()), false);
559                            ui.add(egui::Label::new(job).selectable(false).truncate()).on_hover_text(command);
560                        });
561                        let response = row.response().on_hover_cursor(egui::CursorIcon::PointingHand);
562                        response.context_menu(|ui| {
563                            if !item.is_group() && ui.button(fl!(crate::LANGUAGE_LOADER, "process-copy-pid")).clicked() {
564                                ui.ctx().copy_text(process.pid.to_string());
565                                ui.close();
566                            }
567                            if ui.button(fl!(crate::LANGUAGE_LOADER, "process-copy-command")).clicked() {
568                                ui.ctx()
569                                    .copy_text(if item.is_group() { process.executable.clone() } else { process.cmd.clone() });
570                                ui.close();
571                            }
572                        });
573                        if !disclosure_clicked && response.clicked() {
574                            selection.selected = Some(item.key.clone());
575                            selection.message = None;
576                            selection.row_focus = Some(response.id);
577                            response.request_focus();
578                        }
579                        if !disclosure_clicked && response.double_clicked() {
580                            selection.selected = Some(item.key.clone());
581                            if item.is_group() {
582                                toggle = Some((process.executable.clone(), item.expanded));
583                            } else {
584                                connect = true;
585                            }
586                        }
587                    });
588                });
589        });
590    if let Some((key, expanded)) = toggle {
591        selection.toggle_group(&key, expanded, !filter.is_empty());
592    }
593    connect
594}
595
596fn process_footer(app: &mut App, ui: &mut egui::Ui, compact: bool) -> bool {
597    let top = ui.max_rect().top();
598    ui.painter()
599        .hline(ui.max_rect().x_range(), top, egui::Stroke::new(1.0, egui::Color32::from_rgb(46, 51, 60)));
600    ui.add_space(12.0);
601    let selected = app
602        .process_selection
603        .selected
604        .as_ref()
605        .and_then(|key| resolve_process(&app.state.processes, key));
606    let enabled = selected.is_some();
607    let mut connect = false;
608    ui.horizontal(|ui| {
609        let info_width = (ui.available_width() - 258.0).max(80.0);
610        ui.allocate_ui_with_layout(egui::vec2(info_width, 38.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {
611            ui.set_width(info_width);
612            if let Some(process) = selected {
613                avatar(ui, process, 32.0);
614                let memory = gabi::BytesConfig::default().bytes(process.memory as u64).to_string();
615                let details = format!("PID {} · {memory}", process.pid);
616                ui.vertical(|ui| {
617                    ui.spacing_mut().item_spacing.y = 1.0;
618                    ui.add(egui::Label::new(egui::RichText::new(&process.name).size(15.0).strong()).truncate())
619                        .on_hover_text(format!("{}\n{}", process.name, process.executable));
620                    ui.add(egui::Label::new(egui::RichText::new(details).size(12.0).weak()).truncate());
621                });
622            } else {
623                let hint = if matches!(app.process_selection.selected, Some(ProcessRowKey::Group(_))) {
624                    fl!(crate::LANGUAGE_LOADER, "process-group-select-hint")
625                } else {
626                    fl!(crate::LANGUAGE_LOADER, "process-select-hint")
627                };
628                ui.add(egui::Label::new(egui::RichText::new(hint).size(13.5).weak()).truncate());
629            }
630        });
631        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
632            connect = ui
633                .add_enabled(
634                    enabled,
635                    egui::Button::new(
636                        egui::RichText::new(fl!(crate::LANGUAGE_LOADER, "process-connect-button"))
637                            .strong()
638                            .color(egui::Color32::WHITE),
639                    )
640                    .fill(ui.visuals().selection.bg_fill)
641                    .corner_radius(egui::CornerRadius::same(10))
642                    .min_size(egui::vec2(124.0, 36.0)),
643                )
644                .on_hover_cursor(egui::CursorIcon::PointingHand)
645                .clicked();
646            if ui
647                .add(
648                    egui::Button::new(fl!(crate::LANGUAGE_LOADER, "process-cancel-button"))
649                        .corner_radius(egui::CornerRadius::same(10))
650                        .min_size(egui::vec2(110.0, 36.0)),
651                )
652                .clicked()
653            {
654                app.app_state = AppState::MainWindow;
655            }
656        });
657    });
658    ui.add_space(4.0);
659    if let Some(message) = &app.process_selection.message {
660        ui.label(egui::RichText::new(message).size(11.5).color(ui.visuals().warn_fg_color));
661    } else if !compact {
662        ui.label(egui::RichText::new(fl!(crate::LANGUAGE_LOADER, "process-keyboard-hint")).size(11.5).weak());
663    }
664    connect
665}
666
667impl App {
668    /// Re-resolve the chosen identity after refreshing. A vanished/recycled
669    /// PID must never silently turn into a different attachment.
670    pub fn connect_selected_process(&mut self) {
671        let Some(key @ ProcessRowKey::Process { .. }) = self.process_selection.selected.clone() else {
672            return;
673        };
674        self.state.update_process_data();
675        if let Some(process) = resolve_process(&self.state.processes, &key).cloned() {
676            self.select_process(&process);
677        } else {
678            self.process_selection.selected = None;
679            self.process_selection.message = Some(fl!(crate::LANGUAGE_LOADER, "process-selection-gone"));
680        }
681    }
682}
683
684#[cfg(test)]
685mod tests {
686    use super::*;
687    use model::tests::process;
688
689    #[test]
690    fn process_arrow_glyphs_exist_in_the_application_font() {
691        let ctx = egui::Context::default();
692        crate::ui::theme::apply(&ctx);
693        let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
694            for style in [egui::TextStyle::Body, egui::TextStyle::Button, egui::TextStyle::Small] {
695                let font = style.resolve(ui.style());
696                for glyph in ['⏶', '⏷', '⏵', '⏴', '×', 'Σ'] {
697                    assert!(ui.fonts_mut(|fonts| fonts.has_glyph(&font, glyph)), "Missing glyph {glyph} in {font:?}");
698                }
699            }
700        });
701        output.textures_delta.clear();
702    }
703
704    #[test]
705    fn selected_process_rows_use_selection_color_for_every_cell() {
706        for grouped in [false, true] {
707            let mut app = app();
708            let first = app.state.processes[0].clone();
709            let expected = if grouped {
710                app.state.processes = vec![crate::ProcessInfo {
711                    instances: vec![first.clone(), crate::ProcessInfo { pid: 303, ..first.clone() }],
712                    ..first.clone()
713                }];
714                app.process_selection.selected = Some(ProcessRowKey::Group(first.executable.clone()));
715                vec![
716                    first.name.clone(),
717                    "⏵".to_owned(),
718                    fl!(crate::LANGUAGE_LOADER, "process-group-badge", count = 2),
719                    "—".to_owned(),
720                    format!("Σ {}", gabi::BytesConfig::default().bytes(first.memory as u64)),
721                    first.executable.clone(),
722                ]
723            } else {
724                app.process_selection.selected = Some(ProcessRowKey::process(&first));
725                vec![
726                    first.name,
727                    first.pid.to_string(),
728                    gabi::BytesConfig::default().bytes(first.memory as u64).to_string(),
729                    first.cmd,
730                ]
731            };
732            let ctx = egui::Context::default();
733            crate::ui::theme::apply(&ctx);
734            let selected_color = egui::Color32::from_rgb(255, 240, 180);
735            ctx.global_style_mut(|style| style.visuals.selection.stroke.color = selected_color);
736            let size = egui::vec2(1100.0, 720.0);
737            frame(&mut app, &ctx, size, vec![]);
738            let output = frame(&mut app, &ctx, size, vec![]);
739            // The toolbar's total count can have exactly the same text as
740            // the group badge. Check only labels in the selected row.
741            let row_center_y = text_shapes(&output)
742                .iter()
743                .find(|(text, _)| text == &expected[0])
744                .expect("selected process name must be rendered")
745                .1
746                .center()
747                .y;
748            for label in expected {
749                let text = output
750                    .shapes
751                    .iter()
752                    .find_map(|shape| match &shape.shape {
753                        egui::epaint::Shape::Text(text)
754                            if text.galley.job.text == label
755                                && (text.galley.rect.translate(text.pos.to_vec2()).center().y - row_center_y).abs() < ROW_HEIGHT / 2.0 =>
756                        {
757                            Some(text)
758                        }
759                        _ => None,
760                    })
761                    .unwrap_or_else(|| panic!("Missing row label: {label}"));
762                assert!(
763                    text.galley.job.sections.iter().all(|section| {
764                        let color = text.override_text_color.unwrap_or_else(|| {
765                            if section.format.color == egui::Color32::PLACEHOLDER {
766                                text.fallback_color
767                            } else {
768                                section.format.color
769                            }
770                        });
771                        color == selected_color
772                    }),
773                    "Wrong selection color: {label}; expected={selected_color:?}, sections={:?}, override={:?}, fallback={:?}",
774                    text.galley.job.sections,
775                    text.override_text_color,
776                    text.fallback_color
777                );
778            }
779        }
780    }
781
782    fn frame(app: &mut App, ctx: &egui::Context, size: egui::Vec2, events: Vec<egui::Event>) -> egui::FullOutput {
783        let mut output = ctx.run_ui(
784            egui::RawInput {
785                screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)),
786                events,
787                ..Default::default()
788            },
789            |ui| view_process_selection(app, ui),
790        );
791        // Headless tests inspect paint shapes, not GPU texture updates.
792        output.textures_delta.clear();
793        output
794    }
795
796    fn text_shapes(output: &egui::FullOutput) -> Vec<(String, egui::Rect)> {
797        fn collect(shape: &egui::epaint::Shape, out: &mut Vec<(String, egui::Rect)>) {
798            match shape {
799                egui::epaint::Shape::Text(text) => out.push((text.galley.job.text.clone(), text.galley.rect.translate(text.pos.to_vec2()))),
800                egui::epaint::Shape::Vec(shapes) => {
801                    for shape in shapes {
802                        collect(shape, out);
803                    }
804                }
805                _ => {}
806            }
807        }
808        let mut result = Vec::new();
809        for shape in &output.shapes {
810            collect(&shape.shape, &mut result);
811        }
812        result
813    }
814
815    fn app() -> App {
816        let mut app = App::default();
817        app.app_state = AppState::ProcessSelection;
818        app.state.processes = vec![process(101, "TestGame", 1024), process(202, "OtherGame", 512)];
819        app
820    }
821
822    fn click_at(app: &mut App, ctx: &egui::Context, size: egui::Vec2, pos: egui::Pos2) {
823        frame(app, ctx, size, vec![egui::Event::PointerMoved(pos)]);
824        for pressed in [true, false] {
825            frame(
826                app,
827                ctx,
828                size,
829                vec![egui::Event::PointerButton {
830                    pos,
831                    button: egui::PointerButton::Primary,
832                    pressed,
833                    modifiers: egui::Modifiers::NONE,
834                }],
835            );
836        }
837    }
838
839    #[test]
840    fn search_field_clear_button_only_appears_with_a_filter_and_clears_it() {
841        let size = egui::vec2(1100.0, 720.0);
842        let mut app = app();
843        let ctx = egui::Context::default();
844        crate::ui::theme::apply(&ctx);
845        frame(&mut app, &ctx, size, vec![]);
846        let output = frame(&mut app, &ctx, size, vec![]);
847        let texts = text_shapes(&output);
848        assert!(!texts.iter().any(|(text, _)| text == "×"), "No clear button without a filter");
849
850        app.state.process_filter = "Other".to_owned();
851        frame(&mut app, &ctx, size, vec![]);
852        let output = frame(&mut app, &ctx, size, vec![]);
853        let texts = text_shapes(&output);
854        let (_, clear) = texts.iter().find(|(text, _)| text == "×").expect("clear button with a filter");
855        let field = ctx
856            .memory(|memory| memory.area_rect(egui::LayerId::background().id))
857            .unwrap_or(egui::Rect::EVERYTHING);
858        assert!(field.contains_rect(*clear));
859        assert!(!texts.iter().any(|(text, _)| text == "TestGame"), "The filter applies");
860        click_at(&mut app, &ctx, size, clear.center());
861        assert!(app.state.process_filter.is_empty(), "Clicking × clears the filter");
862        assert!(
863            ctx.memory(|memory| memory.has_focus(egui::Id::new("process-filter"))),
864            "Focus returns to the field"
865        );
866        let output = frame(&mut app, &ctx, size, vec![]);
867        assert!(text_shapes(&output).iter().any(|(text, _)| text == "TestGame"));
868    }
869
870    #[test]
871    fn compact_windows_hide_secondary_text_but_keep_rows_and_actions() {
872        let subtitle = fl!(crate::LANGUAGE_LOADER, "process-selection-subtitle");
873        let hint = fl!(crate::LANGUAGE_LOADER, "process-keyboard-hint");
874        for (size, compact) in [(egui::vec2(640.0, 420.0), true), (egui::vec2(1100.0, 720.0), false)] {
875            let mut app = app();
876            let ctx = egui::Context::default();
877            crate::ui::theme::apply(&ctx);
878            frame(&mut app, &ctx, size, vec![]);
879            let texts = text_shapes(&frame(&mut app, &ctx, size, vec![]));
880            for label in [&subtitle, &hint] {
881                assert_eq!(texts.iter().any(|(text, _)| text == label), !compact, "{label} at {size:?}");
882            }
883            for name in ["TestGame", "OtherGame"] {
884                let (_, rect) = texts.iter().find(|(text, _)| text == name).expect("rows stay visible");
885                assert!(rect.bottom() < size.y - 60.0, "{name} must be above the footer at {size:?}");
886            }
887        }
888    }
889
890    #[test]
891    fn footer_summarizes_the_selected_process() {
892        let size = egui::vec2(1100.0, 720.0);
893        let mut app = app();
894        let ctx = egui::Context::default();
895        crate::ui::theme::apply(&ctx);
896        frame(&mut app, &ctx, size, vec![]);
897        let texts = text_shapes(&frame(&mut app, &ctx, size, vec![]));
898        let hint = fl!(crate::LANGUAGE_LOADER, "process-select-hint");
899        assert!(texts.iter().any(|(text, rect)| text == &hint && rect.top() > size.y - 100.0));
900
901        let selected = app.state.processes[1].clone();
902        app.process_selection.selected = Some(ProcessRowKey::process(&selected));
903        let texts = text_shapes(&frame(&mut app, &ctx, size, vec![]));
904        let details = format!("PID {} · {}", selected.pid, gabi::BytesConfig::default().bytes(selected.memory as u64));
905        let (_, name) = texts
906            .iter()
907            .filter(|(text, _)| text == &selected.name)
908            .max_by(|a, b| a.1.top().total_cmp(&b.1.top()))
909            .unwrap();
910        let (_, details) = texts.iter().find(|(text, _)| text == &details).expect("footer details");
911        assert!(name.top() > size.y - 100.0, "The footer shows the selected name");
912        assert!(details.top() > name.top() && (details.left() - name.left()).abs() < 1.0);
913        assert!(!texts.iter().any(|(text, _)| text == &hint));
914    }
915
916    #[test]
917    fn avatar_colors_are_stable_per_executable_and_vary_between_games() {
918        assert_eq!(avatar_color("/games/a"), avatar_color("/games/a"));
919        let colors: std::collections::HashSet<_> = ["/games/a", "/games/b", "/opt/factorio", "/usr/bin/retroarch", "bg3.exe"]
920            .into_iter()
921            .map(avatar_color)
922            .collect();
923        assert!(colors.len() >= 4, "Different executables should get different colors");
924        for color in colors {
925            let [r, g, b, a] = color.to_array();
926            assert_eq!(a, 255);
927            // White initials must stay readable.
928            assert!(r.max(g).max(b) < 190 && r.max(g).max(b) > 70, "{color:?}");
929        }
930    }
931
932    #[test]
933    fn process_selection_layout_keeps_actions_visible_at_supported_sizes() {
934        for size in [egui::vec2(640.0, 420.0), egui::vec2(1100.0, 720.0)] {
935            let mut app = app();
936            let ctx = egui::Context::default();
937            crate::ui::theme::apply(&ctx);
938            frame(&mut app, &ctx, size, vec![]);
939            let output = frame(&mut app, &ctx, size, vec![]);
940            let texts = text_shapes(&output);
941            let connect = fl!(crate::LANGUAGE_LOADER, "process-connect-button");
942            let cancel = fl!(crate::LANGUAGE_LOADER, "process-cancel-button");
943            for label in [connect, cancel] {
944                let (_, rect) = texts.iter().find(|(text, _)| text == &label).expect("action must be rendered");
945                assert!(rect.left() >= 0.0 && rect.right() <= size.x, "{label}: {rect:?}");
946                assert!(rect.top() >= 0.0 && rect.bottom() <= size.y, "{label}: {rect:?}");
947            }
948            assert!(texts.iter().any(|(text, _)| text == "TestGame"));
949        }
950    }
951
952    #[test]
953    fn single_click_selects_without_attaching() {
954        let mut app = app();
955        let ctx = egui::Context::default();
956        let size = egui::vec2(1100.0, 720.0);
957        frame(&mut app, &ctx, size, vec![]);
958        let output = frame(&mut app, &ctx, size, vec![]);
959        let texts = text_shapes(&output);
960        let pos = texts.iter().find(|(text, _)| text == "TestGame").unwrap().1.center();
961        for pressed in [true, false] {
962            frame(
963                &mut app,
964                &ctx,
965                size,
966                vec![
967                    egui::Event::PointerMoved(pos),
968                    egui::Event::PointerButton {
969                        pos,
970                        button: egui::PointerButton::Primary,
971                        pressed,
972                        modifiers: egui::Modifiers::NONE,
973                    },
974                ],
975            );
976        }
977        assert_eq!(app.app_state, AppState::ProcessSelection);
978        assert_eq!(app.state.pid, 0);
979        assert_eq!(app.process_selection.selected, Some(ProcessRowKey::process(&app.state.processes[0])));
980    }
981
982    #[test]
983    fn arrow_keys_select_while_filter_has_focus() {
984        let mut app = app();
985        let ctx = egui::Context::default();
986        let size = egui::vec2(1100.0, 720.0);
987        frame(&mut app, &ctx, size, vec![]);
988        frame(&mut app, &ctx, size, vec![]);
989        assert!(ctx.memory(|memory| memory.has_focus(egui::Id::new("process-filter"))));
990        frame(
991            &mut app,
992            &ctx,
993            size,
994            vec![egui::Event::Key {
995                key: egui::Key::ArrowDown,
996                physical_key: None,
997                pressed: true,
998                repeat: false,
999                modifiers: egui::Modifiers::NONE,
1000            }],
1001        );
1002        assert_eq!(app.process_selection.selected, Some(ProcessRowKey::process(&app.state.processes[0])));
1003        assert_eq!(app.app_state, AppState::ProcessSelection);
1004    }
1005
1006    #[test]
1007    fn entering_group_does_not_attach_to_representative() {
1008        let mut app = app();
1009        let first = app.state.processes[0].clone();
1010        let second = crate::ProcessInfo { pid: 303, ..first.clone() };
1011        app.state.processes = vec![crate::ProcessInfo {
1012            instances: vec![first.clone(), second],
1013            ..first
1014        }];
1015        let key = ProcessRowKey::Group(app.state.processes[0].executable.clone());
1016        app.process_selection.selected = Some(key);
1017        app.connect_selected_process();
1018        assert_eq!(app.app_state, AppState::ProcessSelection);
1019        assert_eq!(app.state.pid, 0);
1020    }
1021
1022    #[test]
1023    fn filter_hides_selection_immediately() {
1024        let mut app = app();
1025        let ctx = egui::Context::default();
1026        let size = egui::vec2(1100.0, 720.0);
1027        frame(&mut app, &ctx, size, vec![]);
1028        app.process_selection.selected = Some(ProcessRowKey::process(&app.state.processes[0]));
1029        frame(&mut app, &ctx, size, vec![egui::Event::Text("OtherGame".to_owned())]);
1030        assert_eq!(app.process_selection.selected, None);
1031        assert_eq!(app.app_state, AppState::ProcessSelection);
1032    }
1033
1034    #[test]
1035    fn confirming_a_vanished_process_does_not_attach() {
1036        let mut app = app();
1037        app.process_selection.selected = Some(ProcessRowKey::Process {
1038            pid: i32::MAX as _,
1039            start_time: 100,
1040        });
1041        app.connect_selected_process();
1042        assert_eq!(app.process_selection.selected, None);
1043        assert!(app.process_selection.message.is_some());
1044        assert_eq!(app.app_state, AppState::ProcessSelection);
1045        assert_eq!(app.state.pid, 0);
1046    }
1047
1048    #[test]
1049    fn reopening_selection_requests_filter_focus() {
1050        let mut app = app();
1051        app.state.set_focus = false;
1052        app.process_selection.selected = Some(ProcessRowKey::process(&app.state.processes[0]));
1053        app.attach_action();
1054        assert!(app.state.set_focus);
1055        assert_eq!(app.process_selection.selected, None);
1056    }
1057
1058    #[test]
1059    fn enter_from_filter_confirms_selected_process() {
1060        let mut app = app();
1061        app.state.processes[0].pid = i32::MAX as _;
1062        let ctx = egui::Context::default();
1063        let size = egui::vec2(1100.0, 720.0);
1064        frame(&mut app, &ctx, size, vec![]);
1065        app.process_selection.selected = Some(ProcessRowKey::process(&app.state.processes[0]));
1066        frame(
1067            &mut app,
1068            &ctx,
1069            size,
1070            vec![egui::Event::Key {
1071                key: egui::Key::Enter,
1072                physical_key: None,
1073                pressed: true,
1074                repeat: false,
1075                modifiers: egui::Modifiers::NONE,
1076            }],
1077        );
1078        // This deliberately nonexistent PID proves that Enter reached the
1079        // confirmation/revalidation path without attaching to a real process.
1080        assert!(app.process_selection.message.is_some());
1081        assert_eq!(app.process_selection.selected, None);
1082        assert_eq!(app.app_state, AppState::ProcessSelection);
1083    }
1084}