Debian Codegraph @

src/canvas/dialogs/process_kill_dialog.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 //! A dialog box to handle killing processes.
2
3 use std::time::Instant;
4
5 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
6 use ratatui::widgets::ListState;
7 use ratatui::{
8 Frame,
9 layout::{Alignment, Constraint, Flex, Layout, Position, Rect},
10 text::{Line, Span, Text},
11 widgets::{Paragraph, Wrap},
12 };
13
14 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
15 use crate::canvas::components::scroll_bar::{
16 ScrollBarArgs, dialog_scroll_bar_area, draw_scroll_bar,
17 };
18 use crate::{
19 canvas::drawing_utils::dialog_block, collection::processes::Pid, options::config::style::Styles,
20 };
21
22 // Configure signal text based on the target OS.
23 cfg_select! {
24 target_os = "linux" => {
25 const DEFAULT_KILL_SIGNAL: usize = 15;
26 const SIGNAL_TEXT: [&str; 63] = [
27 "0: Cancel",
28 "1: HUP",
29 "2: INT",
30 "3: QUIT",
31 "4: ILL",
32 "5: TRAP",
33 "6: ABRT",
34 "7: BUS",
35 "8: FPE",
36 "9: KILL",
37 "10: USR1",
38 "11: SEGV",
39 "12: USR2",
40 "13: PIPE",
41 "14: ALRM",
42 "15: TERM",
43 "16: STKFLT",
44 "17: CHLD",
45 "18: CONT",
46 "19: STOP",
47 "20: TSTP",
48 "21: TTIN",
49 "22: TTOU",
50 "23: URG",
51 "24: XCPU",
52 "25: XFSZ",
53 "26: VTALRM",
54 "27: PROF",
55 "28: WINCH",
56 "29: IO",
57 "30: PWR",
58 "31: SYS",
59 "34: RTMIN",
60 "35: RTMIN+1",
61 "36: RTMIN+2",
62 "37: RTMIN+3",
63 "38: RTMIN+4",
64 "39: RTMIN+5",
65 "40: RTMIN+6",
66 "41: RTMIN+7",
67 "42: RTMIN+8",
68 "43: RTMIN+9",
69 "44: RTMIN+10",
70 "45: RTMIN+11",
71 "46: RTMIN+12",
72 "47: RTMIN+13",
73 "48: RTMIN+14",
74 "49: RTMIN+15",
75 "50: RTMAX-14",
76 "51: RTMAX-13",
77 "52: RTMAX-12",
78 "53: RTMAX-11",
79 "54: RTMAX-10",
80 "55: RTMAX-9",
81 "56: RTMAX-8",
82 "57: RTMAX-7",
83 "58: RTMAX-6",
84 "59: RTMAX-5",
85 "60: RTMAX-4",
86 "61: RTMAX-3",
87 "62: RTMAX-2",
88 "63: RTMAX-1",
89 "64: RTMAX",
90 ];
91 }
92 target_os = "macos" => {
93 const DEFAULT_KILL_SIGNAL: usize = 15;
94 const SIGNAL_TEXT: [&str; 32] = [
95 "0: Cancel",
96 "1: HUP",
97 "2: INT",
98 "3: QUIT",
99 "4: ILL",
100 "5: TRAP",
101 "6: ABRT",
102 "7: EMT",
103 "8: FPE",
104 "9: KILL",
105 "10: BUS",
106 "11: SEGV",
107 "12: SYS",
108 "13: PIPE",
109 "14: ALRM",
110 "15: TERM",
111 "16: URG",
112 "17: STOP",
113 "18: TSTP",
114 "19: CONT",
115 "20: CHLD",
116 "21: TTIN",
117 "22: TTOU",
118 "23: IO",
119 "24: XCPU",
120 "25: XFSZ",
121 "26: VTALRM",
122 "27: PROF",
123 "28: WINCH",
124 "29: INFO",
125 "30: USR1",
126 "31: USR2",
127 ];
128 }
129 target_os = "freebsd" => {
130 const DEFAULT_KILL_SIGNAL: usize = 15;
131 const SIGNAL_TEXT: [&str; 34] = [
132 "0: Cancel",
133 "1: HUP",
134 "2: INT",
135 "3: QUIT",
136 "4: ILL",
137 "5: TRAP",
138 "6: ABRT",
139 "7: EMT",
140 "8: FPE",
141 "9: KILL",
142 "10: BUS",
143 "11: SEGV",
144 "12: SYS",
145 "13: PIPE",
146 "14: ALRM",
147 "15: TERM",
148 "16: URG",
149 "17: STOP",
150 "18: TSTP",
151 "19: CONT",
152 "20: CHLD",
153 "21: TTIN",
154 "22: TTOU",
155 "23: IO",
156 "24: XCPU",
157 "25: XFSZ",
158 "26: VTALRM",
159 "27: PROF",
160 "28: WINCH",
161 "29: INFO",
162 "30: USR1",
163 "31: USR2",
164 "32: THR",
165 "33: LIBRT",
166 ];
167 }
168 _ => {}
169 }
170
171 /// Button state type for a [`ProcessKillDialog`].
172 ///
173 /// Simple only has two buttons (yes/no), while signals (AKA advanced) are
174 /// a list of signals to send.
175 ///
176 /// Note that signals are not available for Windows.
177 #[derive(Debug)]
178 pub(crate) enum ButtonState {
179 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
180 Signals {
181 state: ListState,
182 last_button_draw_area: Rect,
183 },
184 Simple {
185 yes: bool,
186 last_yes_button_area: Rect,
187 last_no_button_area: Rect,
188 },
189 }
190
191 #[derive(Debug)]
192 struct ProcessKillSelectingInner {
193 process_name: String,
194 pids: Vec<Pid>,
195 button_state: ButtonState,
196 }
197
198 /// The current state of the process kill dialog.
199 #[derive(Default, Debug)]
200 enum ProcessKillDialogState {
201 #[default]
202 NotEnabled,
203 Selecting(ProcessKillSelectingInner),
204 Error {
205 process_name: String,
206 pid: Option<Pid>,
207 err: String,
208 },
209 }
210
211 /// Process kill dialog.
212 #[derive(Default, Debug)]
213 pub(crate) struct ProcessKillDialog {
214 state: ProcessKillDialogState,
215 last_char: Option<(char, Instant)>,
216 }
217
218 impl ProcessKillDialog {
219 pub fn reset(&mut self) {
220 *self = Self::default();
221 }
222
223 #[inline]
224 pub fn is_open(&self) -> bool {
225 !(matches!(self.state, ProcessKillDialogState::NotEnabled))
226 }
227
228 pub fn on_esc(&mut self) {
229 self.reset();
230 }
231
232 pub fn on_enter(&mut self) {
233 // We do this to get around borrow issues.
234 let mut current = ProcessKillDialogState::NotEnabled;
235 std::mem::swap(&mut self.state, &mut current);
236
237 if let ProcessKillDialogState::Selecting(state) = current {
238 let process_name = state.process_name;
239 let button_state = state.button_state;
240 let pids = state.pids;
241
242 match button_state {
243 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
244 ButtonState::Signals { state, .. } => {
245 use crate::utils::process_killer;
246
247 if let Some(selected) = state.selected()
248 && selected != 0
249 {
250 let signal = get_signal_from_index(selected);
251
252 for pid in pids {
253 if let Err(err) = process_killer::kill_process_given_pid(pid, signal) {
254 self.state = ProcessKillDialogState::Error {
255 process_name,
256 pid: Some(pid),
257 err: err.to_string(),
258 };
259 return;
260 }
261 }
262 }
263 }
264 ButtonState::Simple { yes, .. } => {
265 if yes {
266 cfg_select! {
267 target_os = "windows" => {
268 use crate::utils::process_killer;
269
270 for pid in pids {
271 if let Err(err) = process_killer::kill_process_given_pid(pid) {
272 self.state = ProcessKillDialogState::Error { process_name, pid: Some(pid), err: err.to_string() };
273 break;
274 }
275 }
276 }
277 any(target_os = "linux", target_os = "macos", target_os = "freebsd") => {
278 use crate::utils::process_killer;
279
280 for pid in pids {
281 // Send a SIGTERM by default.
282 if let Err(err) = process_killer::kill_process_given_pid(pid, DEFAULT_KILL_SIGNAL) {
283 self.state = ProcessKillDialogState::Error { process_name, pid: Some(pid), err: err.to_string() };
284 break;
285 }
286 }
287 }
288 _ => {
289 self.state = ProcessKillDialogState::Error { process_name, pid: None, err: "Killing processes is not supported on this platform.".into() };
290
291 }
292 }
293 }
294 }
295 }
296 }
297
298 // Fall through behaviour is just to close the dialog.
299 self.last_char = None;
300 }
301
302 pub fn on_char(&mut self, c: char) {
303 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
304 const MAX_KEY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1);
305
306 match c {
307 'h' => self.on_left_key(),
308 'j' => self.on_down_key(),
309 'k' => self.on_up_key(),
310 'l' => self.on_right_key(),
311 '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => {
312 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
313 if let Some(value) = c.to_digit(10)
314 && let ProcessKillDialogState::Selecting(ProcessKillSelectingInner {
315 button_state: ButtonState::Signals { state, .. },
316 ..
317 }) = &mut self.state
318 {
319 if let Some((prev, last_press)) = self.last_char {
320 if prev.is_ascii_digit() && last_press.elapsed() <= MAX_KEY_TIMEOUT {
321 let current = state.selected().unwrap_or(0);
322 let new = {
323 let new = current * 10 + value as usize;
324
325 // Note that 32 and 33 are skipped on linux.
326 if cfg!(target_os = "linux") {
327 if new == 32 || new == 33 {
328 value as usize
329 } else if new >= 34 {
330 new - 2
331 } else {
332 new
333 }
334 } else {
335 new
336 }
337 };
338
339 if new >= SIGNAL_TEXT.len() {
340 // If the new value is too large, then just assume we instead
341 // want the value itself.
342 state.select(Some(value as usize));
343 self.last_char = Some((c, Instant::now()));
344 } else {
345 state.select(Some(new));
346 self.last_char = None;
347 }
348 } else {
349 state.select(Some(value as usize));
350 self.last_char = Some((c, Instant::now()));
351 }
352 } else {
353 state.select(Some(value as usize));
354 self.last_char = Some((c, Instant::now()));
355 }
356
357 return; // Needed to avoid accidentally clearing last_char.
358 }
359 }
360 'g' => {
361 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
362 {
363 if let Some(('g', last_press)) = self.last_char {
364 if last_press.elapsed() <= MAX_KEY_TIMEOUT {
365 self.go_to_first();
366 self.last_char = None;
367 } else {
368 self.last_char = Some(('g', Instant::now()));
369 }
370 } else {
371 self.last_char = Some(('g', Instant::now()));
372 }
373 return;
374 }
375 }
376 'G' => {
377 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
378 self.go_to_last();
379 }
380 _ => {}
381 }
382
383 self.last_char = None;
384 }
385
386 /// Handle a click at the given coordinates. Returns true if the click was
387 /// handled, false otherwise.
388 pub fn on_click(&mut self, x: u16, y: u16) -> bool {
389 if let ProcessKillDialogState::Selecting(state) = &mut self.state {
390 match &mut state.button_state {
391 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
392 ButtonState::Signals {
393 state,
394 last_button_draw_area,
395 } => {
396 if last_button_draw_area.contains(Position { x, y }) {
397 let relative_y =
398 y.saturating_sub(last_button_draw_area.y) as usize + state.offset();
399 if relative_y < SIGNAL_TEXT.len() {
400 state.select(Some(relative_y));
401 }
402 }
403 }
404 ButtonState::Simple {
405 yes,
406 last_yes_button_area,
407 last_no_button_area,
408 } => {
409 if last_yes_button_area.contains(Position { x, y }) {
410 *yes = true;
411 } else if last_no_button_area.contains(Position { x, y }) {
412 *yes = false;
413 }
414 }
415 }
416 }
417
418 false
419 }
420
421 /// Scroll up in the signal list.
422 pub fn on_scroll_up(&mut self) {
423 self.on_up_key();
424 }
425
426 /// Scroll down in the signal list.
427 pub fn on_scroll_down(&mut self) {
428 self.on_down_key();
429 }
430
431 /// Handle a left key press.
432 pub fn on_left_key(&mut self) {
433 self.last_char = None;
434
435 if let ProcessKillDialogState::Selecting(ProcessKillSelectingInner {
436 button_state: ButtonState::Simple { yes, .. },
437 ..
438 }) = &mut self.state
439 {
440 *yes = true;
441 }
442 }
443
444 /// Handle a right key press.
445 pub fn on_right_key(&mut self) {
446 self.last_char = None;
447
448 if let ProcessKillDialogState::Selecting(ProcessKillSelectingInner {
449 button_state: ButtonState::Simple { yes, .. },
450 ..
451 }) = &mut self.state
452 {
453 *yes = false;
454 }
455 }
456
457 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
458 fn scroll_up_by(state: &mut ListState, amount: usize) {
459 if let Some(selected) = state.selected() {
460 if let Some(new_position) = selected.checked_sub(amount) {
461 state.select(Some(new_position));
462 } else {
463 state.select(Some(0));
464 }
465 }
466 }
467
468 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
469 fn scroll_down_by(state: &mut ListState, amount: usize) {
470 if let Some(selected) = state.selected() {
471 let new_position = selected + amount;
472 if new_position < SIGNAL_TEXT.len() {
473 state.select(Some(new_position));
474 } else {
475 state.select(Some(SIGNAL_TEXT.len() - 1));
476 }
477 }
478 }
479
480 /// Handle an up key press.
481 pub fn on_up_key(&mut self) {
482 self.last_char = None;
483
484 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
485 if let ProcessKillDialogState::Selecting(ProcessKillSelectingInner {
486 button_state: ButtonState::Signals { state, .. },
487 ..
488 }) = &mut self.state
489 {
490 Self::scroll_up_by(state, 1);
491 }
492 }
493
494 /// Handle a down key press.
495 pub fn on_down_key(&mut self) {
496 self.last_char = None;
497
498 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
499 if let ProcessKillDialogState::Selecting(ProcessKillSelectingInner {
500 button_state: ButtonState::Signals { state, .. },
501 ..
502 }) = &mut self.state
503 {
504 Self::scroll_down_by(state, 1);
505 }
506 }
507
508 // Handle page up.
509 pub fn on_page_up(&mut self) {
510 self.last_char = None;
511
512 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
513 if let ProcessKillDialogState::Selecting(ProcessKillSelectingInner {
514 button_state:
515 ButtonState::Signals {
516 state,
517 last_button_draw_area,
518 ..
519 },
520 ..
521 }) = &mut self.state
522 {
523 Self::scroll_up_by(state, last_button_draw_area.height as usize);
524 }
525 }
526
527 /// Handle page down.
528 pub fn on_page_down(&mut self) {
529 self.last_char = None;
530
531 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
532 if let ProcessKillDialogState::Selecting(ProcessKillSelectingInner {
533 button_state:
534 ButtonState::Signals {
535 state,
536 last_button_draw_area,
537 ..
538 },
539 ..
540 }) = &mut self.state
541 {
542 Self::scroll_down_by(state, last_button_draw_area.height as usize);
543 }
544 }
545
546 pub fn go_to_first(&mut self) {
547 self.last_char = None;
548
549 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
550 if let ProcessKillDialogState::Selecting(ProcessKillSelectingInner {
551 button_state: ButtonState::Signals { state, .. },
552 ..
553 }) = &mut self.state
554 {
555 state.select(Some(0));
556 }
557 }
558
559 pub fn go_to_last(&mut self) {
560 self.last_char = None;
561
562 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
563 if let ProcessKillDialogState::Selecting(ProcessKillSelectingInner {
564 button_state: ButtonState::Signals { state, .. },
565 ..
566 }) = &mut self.state
567 {
568 state.select(Some(SIGNAL_TEXT.len() - 1));
569 }
570 }
571
572 /// Enable the process kill process.
573 pub fn start_process_kill(
574 &mut self, process_name: String, pids: Vec<Pid>, use_simple_selection: bool,
575 ) {
576 let button_state = if use_simple_selection {
577 ButtonState::Simple {
578 yes: false,
579 last_yes_button_area: Rect::default(),
580 last_no_button_area: Rect::default(),
581 }
582 } else {
583 cfg_select! {
584 any(target_os = "linux", target_os = "macos", target_os = "freebsd") => {
585 ButtonState::Signals { state: ListState::default().with_selected(Some(DEFAULT_KILL_SIGNAL)), last_button_draw_area: Rect::default() }
586 }
587 _ => {
588 ButtonState::Simple { yes: false, last_yes_button_area: Rect::default(), last_no_button_area: Rect::default()}
589 }
590 }
591 };
592
593 if pids.is_empty() {
594 self.state = ProcessKillDialogState::Error {
595 process_name,
596 pid: None,
597 err: "No PIDs found for the given process name.".into(),
598 };
599 return;
600 }
601
602 self.state = ProcessKillDialogState::Selecting(ProcessKillSelectingInner {
603 process_name,
604 pids,
605 button_state,
606 });
607 }
608
609 pub fn handle_redraw(&mut self) {
610 // FIXME: Not sure if we need this. We can probably handle this better in the
611 // draw function later.
612
613 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
614 {
615 if let ProcessKillDialogState::Selecting(ProcessKillSelectingInner {
616 button_state: ButtonState::Signals { state, .. },
617 ..
618 }) = &mut self.state
619 {
620 // Fix the button offset state when we do things like resize.
621 *state.offset_mut() = 0;
622 }
623 }
624 }
625
626 #[inline]
627 fn draw_selecting(
628 f: &mut Frame<'_>, draw_area: Rect, styles: &Styles, state: &mut ProcessKillSelectingInner,
629 ) {
630 let ProcessKillSelectingInner {
631 process_name,
632 pids,
633 button_state,
634 ..
635 } = state;
636
637 // FIXME: Add some colour to this!
638 let text = {
639 const MAX_PROCESS_NAME_WIDTH: usize = 20;
640
641 if let Some(first_pid) = pids.first() {
642 let truncated_process_name =
643 unicode_ellipsis::truncate_str(process_name, MAX_PROCESS_NAME_WIDTH);
644
645 let text = if pids.len() > 1 {
646 Line::from(format!(
647 "Kill {} processes with the name '{}'? Press ENTER to confirm.",
648 pids.len(),
649 truncated_process_name
650 ))
651 } else {
652 Line::from(format!(
653 "Kill process '{truncated_process_name}' with PID {first_pid}? Press ENTER to confirm."
654 ))
655 };
656
657 Text::from(vec![text])
658 } else {
659 Text::from(vec![
660 "Could not find process to kill.".into(),
661 "Please press ENTER or ESC to close this dialog.".into(),
662 ])
663 }
664 };
665
666 let text: Paragraph<'_> = Paragraph::new(text)
667 .style(styles.text_style)
668 .alignment(Alignment::Center)
669 .wrap(Wrap { trim: true });
670
671 let title = match button_state {
672 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
673 ButtonState::Signals { .. } => {
674 Line::styled(" Select Signal ", styles.widget_title_style)
675 }
676 ButtonState::Simple { .. } => {
677 Line::styled(" Confirm Kill Process ", styles.widget_title_style)
678 }
679 };
680
681 let block = dialog_block(styles.border_type, styles.border_style)
682 .title_top(title)
683 .title_top(Line::styled(" Esc to close ", styles.widget_title_style).right_aligned());
684
685 let num_lines = text.line_count(block.inner(draw_area).width) as u16;
686
687 match button_state {
688 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
689 ButtonState::Signals {
690 state,
691 last_button_draw_area,
692 } => {
693 use ratatui::widgets::List;
694
695 // A list of options, displayed vertically.
696 const SIGNAL_TEXT_LEN: u16 = SIGNAL_TEXT.len() as u16;
697
698 // Make the rect only as big as it needs to be, which is the height of the text,
699 // the buttons, and up to 2 spaces (margin and space between), and the size of
700 // the block.
701 let [draw_area] =
702 Layout::vertical([Constraint::Max(num_lines + SIGNAL_TEXT_LEN + 2 + 3)])
703 .flex(Flex::Center)
704 .areas(draw_area);
705
706 // Now we need to divide the block into one area for the paragraph,
707 // and one for the buttons.
708 let [text_draw_area, button_draw_area] = Layout::vertical([
709 Constraint::Max(num_lines),
710 Constraint::Max(SIGNAL_TEXT_LEN),
711 ])
712 .flex(Flex::SpaceEvenly)
713 .areas(block.inner(draw_area));
714
715 // Render the block.
716 f.render_widget(block, draw_area);
717
718 // Now render the text.
719 f.render_widget(text, text_draw_area);
720
721 // And the tricky part, rendering the buttons.
722 let selected = state
723 .selected()
724 .expect("the list state should always be initialized with a selection!");
725
726 let buttons = List::new(SIGNAL_TEXT.iter().enumerate().map(|(index, &signal)| {
727 let style = if index == selected {
728 styles.selected_text_style
729 } else {
730 styles.text_style
731 };
732
733 Span::styled(signal, style)
734 }));
735
736 // This is kinda dumb how you have to set the constraint, but ok.
737 const LONGEST_SIGNAL_TEXT_LENGTH: u16 = const {
738 let mut i = 0;
739 let mut max = 0;
740 while i < SIGNAL_TEXT.len() {
741 if SIGNAL_TEXT[i].len() > max {
742 max = SIGNAL_TEXT[i].len();
743 }
744 i += 1;
745 }
746
747 max as u16
748 };
749
750 let [list_area] =
751 Layout::horizontal([Constraint::Length(LONGEST_SIGNAL_TEXT_LENGTH)])
752 .flex(Flex::Center)
753 .areas(button_draw_area);
754
755 *last_button_draw_area = list_area;
756 f.render_stateful_widget(buttons, list_area, state);
757
758 draw_scroll_bar(
759 f,
760 dialog_scroll_bar_area(draw_area),
761 ScrollBarArgs {
762 content_length: SIGNAL_TEXT.len(),
763 viewport_length: list_area.height as usize,
764 position: state.selected().unwrap_or(0),
765 style: styles.text_style,
766 },
767 );
768 }
769 ButtonState::Simple {
770 yes,
771 last_yes_button_area,
772 last_no_button_area,
773 } => {
774 // Make the rect only as big as it needs to be, which is the height of the text,
775 // the buttons, and up to 3 spaces (margin and space between) + 2 for block.
776 let [draw_area] = Layout::vertical([Constraint::Max(num_lines + 1 + 3 + 2)])
777 .flex(Flex::Center)
778 .areas(draw_area);
779
780 // Now we need to divide the block into one area for the paragraph,
781 // and one for the buttons.
782 let [text_area, button_area] =
783 Layout::vertical([Constraint::Max(num_lines), Constraint::Length(1)])
784 .flex(Flex::SpaceEvenly)
785 .areas(block.inner(draw_area));
786
787 // Render things, starting from the block.
788 f.render_widget(block, draw_area);
789 f.render_widget(text, text_area);
790
791 let (yes, no) = {
792 let (yes_style, no_style) = if *yes {
793 (styles.selected_text_style, styles.text_style)
794 } else {
795 (styles.text_style, styles.selected_text_style)
796 };
797
798 (
799 Paragraph::new(Span::styled("Yes", yes_style)),
800 Paragraph::new(Span::styled("No", no_style)),
801 )
802 };
803
804 let [yes_area, no_area] = Layout::horizontal([Constraint::Length(3); 2])
805 .flex(Flex::SpaceEvenly)
806 .areas(button_area);
807
808 *last_yes_button_area = yes_area;
809 *last_no_button_area = no_area;
810
811 f.render_widget(yes, yes_area);
812 f.render_widget(no, no_area);
813 }
814 }
815 }
816
817 #[inline]
818 fn draw_no_button_dialog(
819 &self, f: &mut Frame<'_>, draw_area: Rect, styles: &Styles, text: Text<'_>, title: Line<'_>,
820 ) {
821 let text = Paragraph::new(text)
822 .style(styles.text_style)
823 .alignment(Alignment::Center)
824 .wrap(Wrap { trim: true });
825
826 let block = dialog_block(styles.border_type, styles.border_style)
827 .title_top(title)
828 .title_top(Line::styled(" Esc to close ", styles.widget_title_style).right_aligned());
829
830 let num_lines = text.line_count(block.inner(draw_area).width) as u16;
831
832 // Also calculate how big of a draw loc we actually need. For this
833 // one, we want it to be shorter if possible.
834 //
835 // Note the +2 is for the margin, and another +2 for border.
836 let [draw_area] = Layout::vertical([Constraint::Max(num_lines + 2 + 2)])
837 .flex(Flex::Center)
838 .areas(draw_area);
839
840 let [text_draw_area] = Layout::vertical([Constraint::Length(num_lines)])
841 .flex(Flex::Center)
842 .areas(block.inner(draw_area));
843
844 f.render_widget(block, draw_area);
845 f.render_widget(text, text_draw_area);
846 }
847
848 /// Draw the [`ProcessKillDialog`].
849 pub fn draw(&mut self, f: &mut Frame<'_>, draw_area: Rect, styles: &Styles) {
850 // The idea is:
851 // - Use as big of a dialog box as needed (within the maximal draw loc)
852 // - So the non-button ones are going to be smaller... probably whatever the
853 // height of the text is.
854 // - Meanwhile for the button one, it'll likely be full height if it's
855 // "advanced" kill.
856
857 const MAX_DIALOG_WIDTH: u16 = 100;
858 let [draw_area] = Layout::horizontal([Constraint::Max(MAX_DIALOG_WIDTH)])
859 .flex(Flex::Center)
860 .areas(draw_area);
861
862 // FIXME: Add some colour to this!
863 match &mut self.state {
864 ProcessKillDialogState::NotEnabled => {}
865 ProcessKillDialogState::Selecting(state) => {
866 // Draw a text box. If buttons are yes/no, fit it, otherwise, use max space.
867 Self::draw_selecting(f, draw_area, styles, state);
868 }
869 ProcessKillDialogState::Error {
870 process_name,
871 pid,
872 err,
873 } => {
874 let text = Text::from(vec![
875 if let Some(pid) = pid {
876 format!("Failed to kill process {process_name} ({pid}):").into()
877 } else {
878 format!("Failed to kill process '{process_name}':").into()
879 },
880 err.to_owned().into(),
881 "Please press ENTER or ESC to close this dialog.".into(),
882 ])
883 .alignment(Alignment::Center);
884 let title = Line::styled(" Error ", styles.widget_title_style);
885
886 self.draw_no_button_dialog(f, draw_area, styles, text, title);
887 }
888 }
889 }
890 }
891
892 /// Return the signal number to send given the index on a list.
893 ///
894 /// On Linux, we need to skip 32 and 33, so we add 2 to the index if it's >= 32.
895 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
896 fn get_signal_from_index(index: usize) -> usize {
897 if cfg!(target_os = "linux") && index >= 32 {
898 index + 2
899 } else {
900 index
901 }
902 }
903
904 #[cfg(test)]
905 mod tests {
906 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
907 use super::*;
908
909 #[test]
910 #[cfg(target_os = "linux")]
911 fn test_getting_signal_from_index_on_linux() {
912 assert_eq!(get_signal_from_index(0), 0);
913 assert_eq!(get_signal_from_index(31), 31);
914 assert_eq!(get_signal_from_index(32), 34);
915 assert_eq!(get_signal_from_index(33), 35);
916 assert_eq!(get_signal_from_index(34), 36);
917 }
918
919 #[test]
920 #[cfg(any(target_os = "macos", target_os = "freebsd"))]
921 fn test_getting_signal_from_index_not_on_linux() {
922 assert_eq!(get_signal_from_index(0), 0);
923 assert_eq!(get_signal_from_index(31), 31);
924 assert_eq!(get_signal_from_index(32), 32);
925 assert_eq!(get_signal_from_index(33), 33);
926 assert_eq!(get_signal_from_index(34), 34);
927 }
928 }