xtop 0.3.7

System monitor written in Rust using terminal user interface (TUI). Fast, efficient, informative, and easy to use.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
use crossterm::{
    event::{self, DisableMouseCapture, Event, KeyCode, KeyEventKind},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};

use ratatui::{
    backend::{Backend, CrosstermBackend},
    layout::{Constraint, Direction, Layout, Rect},
    prelude::{Line, Style},
    style::Color,
    symbols,
    text::Span,
    widgets::{Block, BorderType, Borders, Cell, Clear, LineGauge, Paragraph, Row, Table, TableState},
    Frame, Terminal,
};

use std::io;
use std::time::Duration;
use ratatui::prelude::Stylize;
use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System, Users};

/// Application state
struct App {
    s: System,
    update_freq: u64,
    table_state: TableState,
    filter_text: String,
    sort_col: u8,
    current_col: u8,
    reverse: bool,
    editing: bool,
    show_popup: bool,
    process_info: u8,
}


impl App {
    fn new() -> Self {
        let mut table_state = TableState::default();
        table_state.select(Some(0)); // Start with first row selected

        Self {
            s: System::new_all(),
            update_freq: 1000,
            table_state,
            filter_text: String::new(),
            sort_col: 2,
            current_col: 2,
            reverse: false,
            editing: false,
            show_popup: false,
            process_info: 0,
        }
    }
}


fn main() -> Result<(), io::Error> {
    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, DisableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // Create app state and run the main loop
    let mut app = App::new();
    let res = main_loop(&mut terminal, &mut app);

    // Restore terminal
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    if let Err(err) = res {
        println!("{:?}", err);
    }

    Ok(())
}


fn main_loop <B: Backend>(terminal: &mut Terminal<B>, app: &mut App) -> io::Result<()> {
    loop {
        // Refresh system data before drawing
        app.s.refresh_cpu_usage();
        app.s.refresh_memory();
        app.s.refresh_processes_specifics(
            ProcessesToUpdate::All,
            true,
            ProcessRefreshKind::everything().without_tasks(),
        );

        terminal.draw(|f| ui(f, app)).expect("xtop panic");

        // Input handling
        if event::poll(Duration::from_millis(app.update_freq))? {
            if let Event::Key(key) = event::read()? {
                if key.kind == KeyEventKind::Press {
                    match app.editing {
                        false => match key.code {
                            KeyCode::Char('q') => return Ok(()),
                            KeyCode::Char('s') => {
                                app.editing = true;
                                app.process_info = 0;
                            }
                            KeyCode::Char('f') => app.table_state.select_first(),
                            KeyCode::Char('l') => app.table_state.select_last(),
                            KeyCode::Up => {
                                let i = match app.table_state.selected() {
                                    Some(i) => if i == 0 { 0 } else { i - 1 },
                                    None => 0,
                                };
                                app.table_state.select(Some(i));
                            }
                            KeyCode::Down => {
                                let count = app.s.processes().len();
                                let i = match app.table_state.selected() {
                                    Some(i) => if i >= count - 1 { count - 1 } else { i + 1 },
                                    None => 0,
                                };
                                app.table_state.select(Some(i));
                            }
                            KeyCode::Char('-') => {
                                if app.update_freq > 200 {
                                    app.update_freq -= 200;
                                }
                            }
                            KeyCode::Char('+') => {
                                if app.update_freq < 3000 {
                                    app.update_freq += 200;
                                }
                            }
                            KeyCode::Char('p') => {
                                if app.sort_col == app.current_col {
                                    app.reverse = !app.reverse;
                                }
                                app.sort_col = 0;
                            }
                            KeyCode::Char('n') => {
                                if app.sort_col == app.current_col {
                                    app.reverse = !app.reverse;
                                }
                                app.sort_col = 1;
                            }
                            KeyCode::Char('m') => {
                                if app.sort_col == app.current_col {
                                    app.reverse = !app.reverse;
                                }
                                app.sort_col = 2;
                            }
                            KeyCode::Char('c') => {
                                if app.sort_col == app.current_col {
                                    app.reverse = !app.reverse;
                                }
                                app.sort_col = 3;
                            }
                            KeyCode::Char('?') => {
                                app.show_popup = !app.show_popup;
                            }
                            KeyCode::Enter => {
                                if app.table_state.selected().is_some() {
                                    app.process_info = if app.process_info == 0 { 1 } else { 0 };
                                }
                            }
                            _ => {}
                        },

                        true => match key.code {
                            KeyCode::Esc => {
                                app.editing = false;
                                app.filter_text.clear();
                            }
                            KeyCode::Enter => {
                                if app.table_state.selected().is_some() {
                                    app.process_info = if app.process_info == 0 { 1 } else { 0 };
                                }
                            }
                            KeyCode::Char(c) => {
                                app.filter_text.push(c);
                                if app.filter_text.is_empty() {
                                    app.process_info = 0;
                                }
                            }
                            KeyCode::Backspace => {
                                if app.filter_text.is_empty() {
                                    app.editing = false;
                                    app.process_info = 0;
                                } else {
                                    app.filter_text.pop();
                                }
                            }
                            KeyCode::Up => {
                                let i = match app.table_state.selected() {
                                    Some(i) => if i == 0 { 0 } else { i - 1 },
                                    None => 0,
                                };
                                app.table_state.select(Some(i));
                            }
                            KeyCode::Down => {
                                let count = app.s.processes().len();
                                let i = match app.table_state.selected() {
                                    Some(i) => if i >= count - 1 { count - 1 } else { i + 1 },
                                    None => 0,
                                };
                                app.table_state.select(Some(i));
                            }
                            _ => {}
                        },
                    }
                }
            }
        }
    }
}


fn ui(f: &mut Frame, app: &mut App) {

    // colors used in app
    let c_border = Color::Rgb(100, 150, 100);
    let c_border_search = Color::Rgb(200, 100, 100);
    let c_title = Color::Rgb(200, 200, 100);
    let c_menu = Color::Rgb(200, 200, 100);
    let c_menu_mut = Color::Rgb(200, 100, 100);
    let c_pipe = Color::Rgb(60, 60, 60);
    let c_hot_key = Color::LightRed;
    let c_table_header = Color::Rgb(200, 200, 100);
    let c_row_highlight = Color::Rgb(100, 100, 50);
    let c_mem_total = Color::Rgb(200, 200, 100);
    let c_mem_used = Color::Rgb(200, 100, 100);
    let c_mem_avail = Color::Rgb(100, 200, 100);
    let c_mem_free = Color::Rgb(50, 255, 255);
    let c_popup_border = Color::Rgb(200,150,100);
    let c_bg = Color::Rgb(0,0,0);
    let c_fg = Color::Rgb(230,230,230);

    // Get raw list and apply filter
    let mut process_list: Vec<_> = app.s.processes().values().collect();
    if !app.filter_text.is_empty() {
        process_list.retain(|p| {
            p.pid().to_string().to_lowercase().contains(&app.filter_text.to_lowercase())
                || p.name().to_string_lossy().to_lowercase().contains(&app.filter_text.to_lowercase())
        });
        if process_list.is_empty() {
            app.process_info = 0;
        }
    }

    // Setup terminal panels
    let size = f.area();
    let terminal_width = size.width;
    let terminal_height = size.height;

    if terminal_width < 60 || terminal_height < 16 {
        let horizontal = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(100)])
            .split(size);
        let p = Paragraph::new("Terminal size must be at least\n 60 x 16\n to display 'xtop'").centered();
        f.render_widget(p, horizontal[0]);
        return;
    }

    // Split the screen horizontally
    let horizontal = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(40), Constraint::Percentage(60)])
        .split(size);

    // Split the left panel vertically
    let left_panel = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Fill(1), Constraint::Length(6), Constraint::Length(0)])
        .split(horizontal[0]);

    // Adapt right panel to process info
    let right_panel = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3 * if app.editing { 1 } else { 0 }),
            Constraint::Fill(1),
            Constraint::Length((app.process_info as u16) * 7),
        ])
        .split(horizontal[1]);

    // Render Search Box
    let search_style = match app.editing {
        false => Style::default(),
        true => Style::default().fg(Color::White),
    };

    let search_bar = Paragraph::new(app.filter_text.as_str())
        .style(search_style)
        .block(
            Block::default()
                .title_style(c_title)
                .borders(Borders::ALL)
                .border_style(c_border_search)
                .title(Line::from(" Type to search, escape to exit ").
                    style(Style::default().bold())),
        ).bg(c_bg).fg(c_fg);
    f.render_widget(search_bar, right_panel[0]);


    // CPU
    let mut rows = Vec::new();
    for cpu in app.s.cpus().iter() {
        rows.push(Row::new(vec![
            Cell::from(Line::from(cpu.name().to_string()).right_aligned()),
            Cell::from(Line::from(format!("{:.1}%", cpu.cpu_usage())).right_aligned()),
        ]));
    }

    let loadavg = System::load_average();

    let table = Table::new(
        rows,
        [
            Constraint::Length(6),
            Constraint::Length(7),
            // Constraint::Length(6),
            // Constraint::Length(10),
        ])
        .block(Block::default().borders(Borders::ALL))
        .header(
            Row::new(vec![
                Cell::from(Line::from("CPU").right_aligned()),
                Cell::from(Line::from("Usage").right_aligned()),
            ])
                .style(Style::default().bold().fg(c_table_header)),
        )
        .column_spacing(0)
        .block(
            Block::default()
                .title(Line::from(" Core Information ").style(Style::default().bold()))
                .title_style(c_title)
                .borders(Borders::ALL)
                .border_style(c_border)
                .title_bottom(
                    Line::from(vec![
                        Span::styled(" Load Ave: ", Style::default().fg(c_menu)),
                        Span::styled(
                            format!("{:.2} {:.2} {:.2} ", loadavg.one, loadavg.five, loadavg.fifteen),
                            Style::default().fg(c_menu_mut),
                        ),
                    ]).right_aligned(),
                )
                .bg(c_bg)
                .fg(c_fg),
        );

    f.render_widget(table, left_panel[0]);

    // cpu gauge
    let mut area_vec = vec![];
    for i in 1..=app.s.cpus().len() {
        area_vec.push(Rect::new(15, (i + 1) as u16, left_panel[0].width - 17, 1));

        if (i as u16) < (left_panel[0].height-2) {
            let cpuusage = app.s.cpus().get(i - 1).unwrap().cpu_usage();
            let gauge = LineGauge::default()
                .label("")
                .filled_style(Style::new().fg(Color::Rgb(
                    (cpuusage * 255.0 / 100.0) as u8,
                    ((100.0 - cpuusage) * 255.0 / 100.0) as u8,
                    0,
                )))
                .unfilled_style(Style::new().fg(Color::Rgb(30, 30, 30)))
                .filled_symbol(symbols::line::THICK_HORIZONTAL)
                .ratio((cpuusage / 100.0) as f64);
            f.render_widget(&gauge, area_vec[i - 1]);
        }
    }


    // Memory
    let mem_rows = vec![
        Row::new(vec![
            Cell::from("Total: "),
            Cell::from(
                Line::from(format!(
                    "{:.1}",
                    (app.s.total_memory() as f32) / (1024.0f32.powi(3))
                ))
                    .right_aligned(),
            ),
        ]),
        Row::new(vec![
            Cell::from("Used: "),
            Cell::from(
                Line::from(format!(
                    "{:.1}",
                    (app.s.used_memory() as f32) / (1024.0f32.powi(3))
                ))
                    .right_aligned(),
            ),
        ]),
        Row::new(vec![
            Cell::from("Avail: "),
            Cell::from(
                Line::from(format!(
                    "{:.1}",
                    (app.s.available_memory() as f32) / (1024.0f32.powi(3))
                ))
                    .right_aligned(),
            ),
        ]),
        Row::new(vec![
            Cell::from("Free: "),
            Cell::from(
                Line::from(format!(
                    "{:.1}",
                    (app.s.free_memory() as f32) / (1024.0f32.powi(3))
                ))
                    .right_aligned(),
            ),
        ]),
    ];

    let mut memory_vec = vec![];
    memory_vec.push(app.s.total_memory() as f64);
    memory_vec.push(app.s.used_memory() as f64);
    memory_vec.push(app.s.available_memory() as f64);
    memory_vec.push(app.s.free_memory() as f64);

    let mem_table = Table::new(mem_rows, [Constraint::Length(6), Constraint::Length(5)])
        .block(Block::default().borders(Borders::ALL))
        .column_spacing(1)
        .block(
            Block::default()
                .title(Line::from(" Memory (GB) ").style(Style::default().bold()))
                .title_style(c_title)
                .borders(Borders::ALL)
                .border_style(c_border)
                .title_style(c_title)
                .title_bottom(
                    Line::from(vec![
                        Span::styled(" Update (ms):", Style::default().fg(c_menu)),
                        Span::styled(" - ", Style::default().fg(c_hot_key)),
                        Span::styled(
                            format!("{:.0}", app.update_freq),
                            Style::default().fg(c_menu_mut),
                        ),
                        Span::styled(" + ", Style::default().fg(c_hot_key)),
                    ])
                        .right_aligned(),
                )
                .bg(c_bg)
                .fg(c_fg),
        );

    f.render_widget(mem_table, left_panel[1]);

    // memory gauge
    let color_memory = vec![c_mem_total, c_mem_used, c_mem_avail, c_mem_free];
    let mut area_vec = vec![];
    for i in 0..4 {
        area_vec.push(Rect::new(
            14,
            left_panel[1].y + (i + 1) as u16,
            left_panel[1].width - 16,
            1,
        ));

        let gauge = LineGauge::default()
            .label("")
            .filled_style(Style::new().fg(color_memory[i]))
            .unfilled_style(Style::new().fg(Color::Rgb(30, 30, 30)))
            .filled_symbol(symbols::line::THICK_HORIZONTAL)
            .ratio(memory_vec[i] / memory_vec[0]);
        f.render_widget(&gauge, area_vec[i]);
    }


    // Process List
    if app.sort_col != app.current_col {
        app.reverse = false;
    }

    match app.sort_col {
        0 => {
            process_list.sort_by(|a, b| a.pid().cmp(&b.pid()).reverse());
            app.current_col = 0;
        }
        1 => {
            process_list.sort_by(|a, b| a.name().cmp(&b.name()));
            app.current_col = 1;
        }
        2 => {
            process_list.sort_by(|a, b| a.memory().cmp(&b.memory()).reverse());
            app.current_col = 2;
        }
        3 => {
            process_list.sort_by(|a, b| a.cpu_usage().total_cmp(&b.cpu_usage()).reverse());
            app.current_col = 3;
        }
        _ => {}
    }

    if app.reverse {
        process_list.reverse();
    }

    let uptime_secs: u64 = System::uptime();
    let d = uptime_secs / 86400;
    let h = (uptime_secs / 3600) % 24;
    let m = (uptime_secs / 60) % 60;
    let s = uptime_secs % 60;

    let proc_rows: Vec<Row> = process_list
        .iter()
        .map(|p| {
            Row::new(vec![
                Cell::from(Line::from(p.pid().to_string()).right_aligned()),
                Cell::from(p.name().to_string_lossy().to_string()),
                Cell::from(Line::from(format!("{:.1} MB", p.memory() as f64 / 1_048_576.0)).right_aligned()),
                Cell::from(Line::from(format!("{:.1}%", p.cpu_usage())).right_aligned()),
            ])
        })
        .collect();

    let nrows = proc_rows.len();
    let mut srow = app.table_state.selected().unwrap_or(0);
    if nrows == 0 {
        srow = 0;
    }
    if srow < nrows {
        srow = srow + 1;
    }

    let proc_table = Table::new(
        proc_rows,
        [
            Constraint::Length(6),
            Constraint::Min(18),
            Constraint::Length(10),
            Constraint::Length(6),
        ],
    )
        .header(Row::new(vec![
            Line::from(vec![
                Span::styled("p", Style::default().fg(c_hot_key)),
                Span::styled("id", Style::default().fg(c_table_header)),
            ]).right_aligned().style(Style::default().bold()),
            Line::from(vec![
                Span::styled("n", Style::default().fg(c_hot_key)),
                Span::styled("ame", Style::default().fg(c_table_header)),
            ]).left_aligned().style(Style::default().bold()),
            Line::from(vec![
                Span::styled("m", Style::default().fg(c_hot_key)),
                Span::styled("emory", Style::default().fg(c_table_header)),
            ]).right_aligned().style(Style::default().bold()),
            Line::from(vec![
                Span::styled("c", Style::default().fg(c_hot_key)),
                Span::styled("pu", Style::default().fg(c_table_header)),
            ]).right_aligned().style(Style::default().bold()),
        ]))
        .row_highlight_style(Style::default().bg(c_row_highlight))
        .block(
            Block::default()
                .title(
                    Line::from(format!(" Processes [{}/{}] ", srow, nrows))
                        .style(Style::default().bold())
                        .left_aligned(),
                )
                .title(
                    Line::from(
                        vec![Span::styled(if f.area().width >= 70 {" Uptime:"} else {""},
                            Style::default().fg(c_menu)),
                        Span::styled(format!(" {:01}d {:02}:{:02}:{:02} ", d, h, m, s),
                             Style::default().fg(c_menu_mut)),])
                        .right_aligned(),
                )
                .borders(Borders::ALL)
                .border_style(c_border)
                .title_style(c_title)
                .title_bottom(Line::from(vec![
                    Span::styled(" f", Style::default().fg(c_hot_key)),
                    Span::styled("irst", Style::default().fg(c_menu)),
                    Span::styled(" | ", Style::default().fg(c_pipe)),
                    Span::styled("l", Style::default().fg(c_hot_key)),
                    Span::styled("ast", Style::default().fg(c_menu)),
                    Span::styled(" | ", Style::default().fg(c_pipe)),
                    Span::styled("", Style::default().fg(c_hot_key)),
                    Span::styled("Info", Style::default().fg(c_menu)),
                    Span::styled(" | ", Style::default().fg(c_pipe)),
                    Span::styled("s", Style::default().fg(c_hot_key)),
                    Span::styled("earch", Style::default().fg(c_menu)),
                    Span::styled(" | ", Style::default().fg(c_pipe)),
                    Span::styled("q", Style::default().fg(c_hot_key)),
                    Span::styled("uit", Style::default().fg(c_menu)),
                    Span::styled(" | ", Style::default().fg(c_pipe)),
                    Span::styled("? ", Style::default().fg(c_hot_key)),
                ]))
                .bg(c_bg)
                .fg(c_fg),
        );

    f.render_stateful_widget(proc_table, right_panel[1], &mut app.table_state);

    // Process Details
    if app.table_state.selected().is_none() && app.process_info == 1 {
        app.process_info = 0;
    }

    if app.table_state.selected().is_some() && app.process_info == 1 {
        let users = Users::new_with_refreshed_list();

        let selected_process = app.table_state.selected().unwrap();
        let (hours, minutes, seconds) = s_to_hms(process_list[selected_process].run_time());

        let pid = process_list[selected_process].pid();
        let user_name = process_list[selected_process]
            .user_id()
            .and_then(|uid| users.get_user_by_id(uid))
            .map(|user| user.name())
            .unwrap_or("Unknown");

        let path = match process_list[selected_process].exe() {
            Some(p) => p.to_str().unwrap_or("Unknown"),
            None => "Unknown",
        };

        let selected_processes_rows = vec![
            Row::new(vec![Cell::from("PID: "), Cell::from(pid.to_string())]),
            Row::new(vec![Cell::from("User Name: "), Cell::from(user_name)]),
            Row::new(vec![Cell::from("Path: "), Cell::from(path)]),
            Row::new(vec![
                Cell::from("Command: "),
                Cell::from(format!("{:?}", process_list[selected_process].cmd())),
            ]),
            Row::new(vec![
                Cell::from("Run Time: "),
                Cell::from(format!("{:?}:{:02}:{:02}", hours, minutes, seconds)),
            ]),
        ];

        let selected_process_table = Table::new(
            selected_processes_rows,
            [Constraint::Fill(1), Constraint::Fill(3)],
        )
            .row_highlight_style(Style::default().bg(Color::Rgb(100, 100, 50))) // Visual cue for selection
            .block(
                Block::default()
                    .title(Line::from(" Process Details ").style(Style::default().bold()))
                    .borders(Borders::ALL)
                    .border_style(c_border)
                    .title_style(c_title)
                    .title_bottom(Line::from(vec![
                        Span::styled("", Style::default().fg(c_hot_key)),
                        Span::styled("Close ", Style::default().fg(c_menu)),
                    ]))
                    .bg(c_bg)
                    .fg(c_fg),
            );

        f.render_widget(selected_process_table, right_panel[2]);
    }


    // about popup
    if app.show_popup {
        let area = centered_rect(f.area());
        let help_text = vec![
            Line::from(Span::styled(" https://github.com/mabognar ", Color::White)),
            Line::from(vec![Span::styled(
                " https://crates.io/crates/xtop ",
                Color::White,
            )]),
        ];

        const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
        let block = Block::default()
            .title(Line::from(vec![
                Span::raw(" xtop "),
                Span::raw(format!("({}) ", PKG_VERSION)),
            ]))
            .title_bottom(Line::from(vec![
                Span::raw(" To close, type "),
                Span::styled("? ", c_hot_key),
            ]))
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(
                Style::default()
                    .fg(c_popup_border)
                    .bg(Color::Black),
            )
            .bg(c_bg);

        let help_para = Paragraph::new(help_text)
            .block(block)
            .wrap(ratatui::widgets::Wrap { trim: true });

        f.render_widget(Clear, area); // This clears the area under the popup
        f.render_widget(help_para, area);
    }
}

// Helpers
fn centered_rect(r: Rect) -> Rect {
    let popup_layout = Layout::vertical([
        Constraint::Fill(1),
        Constraint::Length(4),
        Constraint::Fill(1),
    ])
        .split(r);

    Layout::horizontal([
        Constraint::Fill(1),
        Constraint::Length(33),
        Constraint::Fill(1),
    ])
        .split(popup_layout[1])[1]
}

fn s_to_hms(secs: u64) -> (u64, u64, u64) {
    let h = secs / 3600;
    let m = (secs % 3600) / 60;
    let s = secs % 60;
    (h, m, s)
}