Debian Codegraph @

src/canvas/dialogs/process_kill_dialog.rs

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