revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
Documentation
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
//! Process Monitor widget (htop-style)
//!
//! Displays system processes with CPU/memory usage,
//! sorting, filtering, and process management.

#[cfg(feature = "sysinfo")]
use sysinfo::System;

use crate::render::{Cell, Modifier};
use crate::style::Color;
use crate::utils::format_size_compact;
use crate::widget::theme::LIGHT_GRAY;
use crate::widget::traits::{RenderContext, View, WidgetProps};
use crate::{impl_props_builders, impl_styled_view};

/// Sort column for process list
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ProcessSort {
    /// Sort by PID
    Pid,
    /// Sort by process name
    Name,
    /// Sort by CPU usage (default)
    #[default]
    Cpu,
    /// Sort by memory usage
    Memory,
    /// Sort by status
    Status,
}

/// Process display mode
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ProcessView {
    /// Show all processes
    #[default]
    All,
    /// Show only user processes
    User,
    /// Show tree view
    Tree,
}

/// Process information
#[derive(Clone, Debug)]
pub struct ProcessInfo {
    /// Process ID
    pub pid: u32,
    /// Parent PID
    pub parent_pid: Option<u32>,
    /// Process name
    pub name: String,
    /// CPU usage percentage
    pub cpu: f32,
    /// Memory usage in bytes
    pub memory: u64,
    /// Memory usage percentage
    pub memory_percent: f32,
    /// Process status
    pub status: String,
    /// Command line
    pub cmd: String,
    /// User
    pub user: String,
}

/// Color scheme for process monitor
#[derive(Clone, Debug)]
pub struct ProcColors {
    /// Header background
    pub header_bg: Color,
    /// Header foreground
    pub header_fg: Color,
    /// Selected row background
    pub selected_bg: Color,
    /// High CPU color
    pub high_cpu: Color,
    /// Medium CPU color
    pub medium_cpu: Color,
    /// Low CPU color
    pub low_cpu: Color,
    /// High memory color
    pub high_mem: Color,
    /// Process name color
    pub name: Color,
    /// PID color
    pub pid: Color,
}

impl Default for ProcColors {
    fn default() -> Self {
        Self {
            header_bg: Color::rgb(40, 40, 60),
            header_fg: Color::WHITE,
            selected_bg: Color::rgb(60, 80, 120),
            high_cpu: Color::RED,
            medium_cpu: Color::YELLOW,
            low_cpu: Color::GREEN,
            high_mem: Color::MAGENTA,
            name: Color::WHITE,
            pid: Color::CYAN,
        }
    }
}

/// Process Monitor widget
///
/// # Example
///
/// ```rust,ignore
/// use revue::prelude::*;
///
/// let mut monitor = ProcessMonitor::new();
/// monitor.refresh();  // Update process list
///
/// // Sort by memory
/// monitor.sort_by(ProcessSort::Memory);
///
/// // Filter by name
/// monitor.filter("rust");
/// ```
pub struct ProcessMonitor {
    /// System info handle
    system: System,
    /// Cached process list
    processes: Vec<ProcessInfo>,
    /// Sort column
    sort: ProcessSort,
    /// Sort ascending
    sort_asc: bool,
    /// Filter string
    filter: String,
    /// Selected row
    selected: usize,
    /// Scroll offset
    scroll: usize,
    /// View mode
    view: ProcessView,
    /// Colors
    colors: ProcColors,
    /// Show command line
    show_cmd: bool,
    /// Update interval (ms)
    update_interval: u64,
    /// Last update time
    last_update: std::time::Instant,
    /// CSS styling properties (id, classes)
    props: WidgetProps,
}

impl ProcessMonitor {
    /// Create a new process monitor
    pub fn new() -> Self {
        let mut sys = System::new_all();
        sys.refresh_all();

        Self {
            system: sys,
            processes: Vec::new(),
            sort: ProcessSort::default(),
            sort_asc: false,
            filter: String::new(),
            selected: 0,
            scroll: 0,
            view: ProcessView::default(),
            colors: ProcColors::default(),
            show_cmd: false,
            update_interval: 1000,
            last_update: std::time::Instant::now(),
            props: WidgetProps::new(),
        }
    }

    /// Set sort column
    pub fn sort_by(mut self, sort: ProcessSort) -> Self {
        self.sort = sort;
        self
    }

    /// Set sort direction
    pub fn ascending(mut self, asc: bool) -> Self {
        self.sort_asc = asc;
        self
    }

    /// Set view mode
    pub fn view(mut self, view: ProcessView) -> Self {
        self.view = view;
        self
    }

    /// Set colors
    pub fn colors(mut self, colors: ProcColors) -> Self {
        self.colors = colors;
        self
    }

    /// Show/hide command line
    pub fn show_cmd(mut self, show: bool) -> Self {
        self.show_cmd = show;
        self
    }

    /// Set update interval (ms)
    pub fn update_interval(mut self, ms: u64) -> Self {
        self.update_interval = ms;
        self
    }

    /// Set filter string
    pub fn filter(&mut self, filter: impl Into<String>) {
        self.filter = filter.into().to_lowercase();
        self.selected = 0;
        self.scroll = 0;
    }

    /// Clear filter
    pub fn clear_filter(&mut self) {
        self.filter.clear();
    }

    /// Toggle sort column
    pub fn toggle_sort(&mut self, column: ProcessSort) {
        if self.sort == column {
            self.sort_asc = !self.sort_asc;
        } else {
            self.sort = column;
            self.sort_asc = false;
        }
    }

    /// Refresh process list
    pub fn refresh(&mut self) {
        self.system.refresh_all();
        self.update_process_list();
        self.last_update = std::time::Instant::now();
    }

    /// Check if update is needed
    pub fn needs_update(&self) -> bool {
        self.last_update.elapsed().as_millis() >= self.update_interval as u128
    }

    /// Tick (auto-refresh if needed)
    pub fn tick(&mut self) {
        if self.needs_update() {
            self.refresh();
        }
    }

    /// Update process list from system
    fn update_process_list(&mut self) {
        let total_memory = self.system.total_memory() as f32;

        self.processes = self
            .system
            .processes()
            .iter()
            .map(|(pid, proc): (&sysinfo::Pid, &sysinfo::Process)| {
                let memory = proc.memory();
                ProcessInfo {
                    pid: pid.as_u32(),
                    parent_pid: proc.parent().map(|p| p.as_u32()),
                    name: proc.name().to_string_lossy().into_owned(),
                    cpu: proc.cpu_usage(),
                    memory,
                    memory_percent: (memory as f32 / total_memory) * 100.0,
                    status: format!("{:?}", proc.status()),
                    cmd: proc
                        .cmd()
                        .iter()
                        .map(|s| s.to_string_lossy().into_owned())
                        .collect::<Vec<_>>()
                        .join(" "),
                    user: proc.user_id().map(|u| u.to_string()).unwrap_or_default(),
                }
            })
            .filter(|p| {
                if self.filter.is_empty() {
                    true
                } else {
                    p.name.to_lowercase().contains(&self.filter)
                        || p.cmd.to_lowercase().contains(&self.filter)
                }
            })
            .collect();

        // Sort
        self.processes.sort_by(|a, b| {
            let ord = match self.sort {
                ProcessSort::Pid => a.pid.cmp(&b.pid),
                ProcessSort::Name => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
                ProcessSort::Cpu => a
                    .cpu
                    .partial_cmp(&b.cpu)
                    .unwrap_or(std::cmp::Ordering::Equal),
                ProcessSort::Memory => a.memory.cmp(&b.memory),
                ProcessSort::Status => a.status.cmp(&b.status),
            };
            if self.sort_asc {
                ord
            } else {
                ord.reverse()
            }
        });

        // Adjust selection
        if self.selected >= self.processes.len() {
            self.selected = self.processes.len().saturating_sub(1);
        }
    }

    /// Select next process
    pub fn select_next(&mut self) {
        if self.selected < self.processes.len().saturating_sub(1) {
            self.selected += 1;
        }
    }

    /// Select previous process
    pub fn select_prev(&mut self) {
        if self.selected > 0 {
            self.selected -= 1;
        }
    }

    /// Page down
    pub fn page_down(&mut self, page_size: usize) {
        self.selected = (self.selected + page_size).min(self.processes.len().saturating_sub(1));
    }

    /// Page up
    pub fn page_up(&mut self, page_size: usize) {
        self.selected = self.selected.saturating_sub(page_size);
    }

    /// Get selected process
    pub fn selected_process(&self) -> Option<&ProcessInfo> {
        self.processes.get(self.selected)
    }

    /// Get process count
    pub fn process_count(&self) -> usize {
        self.processes.len()
    }

    /// Get system CPU usage
    pub fn cpu_usage(&self) -> f32 {
        self.system.global_cpu_usage()
    }

    /// Get system memory usage
    pub fn memory_usage(&self) -> (u64, u64) {
        (self.system.used_memory(), self.system.total_memory())
    }

    /// Format bytes to human readable
    fn format_bytes(bytes: u64) -> String {
        format_size_compact(bytes)
    }

    /// Render header
    fn render_header(&self, ctx: &mut RenderContext) {
        let area = ctx.area;

        // Header background
        for x in 0..area.width {
            let mut cell = Cell::new(' ');
            cell.bg = Some(self.colors.header_bg);
            ctx.set(x, 0, cell);
        }

        // Column headers
        let headers = [
            ("PID", 7, ProcessSort::Pid),
            ("NAME", 20, ProcessSort::Name),
            ("CPU%", 7, ProcessSort::Cpu),
            ("MEM%", 7, ProcessSort::Memory),
            ("MEM", 8, ProcessSort::Memory),
            ("STATUS", 10, ProcessSort::Status),
        ];

        let mut x_offset = 0u16;
        for (name, width, sort) in headers {
            let indicator = if self.sort == sort {
                if self.sort_asc {
                    "â–²"
                } else {
                    "â–¼"
                }
            } else {
                ""
            };

            let text = format!("{}{}", name, indicator);
            let mut hx = x_offset;
            for ch in text.chars() {
                let cw = crate::utils::char_width(ch) as u16;
                if hx + cw > area.width {
                    break;
                }
                let mut cell = Cell::new(ch);
                cell.fg = Some(self.colors.header_fg);
                cell.bg = Some(self.colors.header_bg);
                cell.modifier = Modifier::BOLD;
                ctx.set(hx, 0, cell);
                hx += cw;
            }
            x_offset += width as u16;
        }
    }

    /// Render system stats bar
    fn render_stats(&self, ctx: &mut RenderContext, y: u16) {
        let area = ctx.area;
        let (used_mem, total_mem) = self.memory_usage();
        let cpu = self.cpu_usage();

        let stats = format!(
            "CPU: {:5.1}%  MEM: {} / {} ({:.1}%)  Processes: {}",
            cpu,
            Self::format_bytes(used_mem),
            Self::format_bytes(total_mem),
            (used_mem as f64 / total_mem as f64) * 100.0,
            self.process_count()
        );

        let mut sx: u16 = 0;
        for ch in stats.chars() {
            let cw = crate::utils::char_width(ch) as u16;
            if sx + cw > area.width {
                break;
            }
            let mut cell = Cell::new(ch);
            cell.fg = Some(LIGHT_GRAY);
            ctx.set(sx, y, cell);
            sx += cw;
        }
    }
}

impl Default for ProcessMonitor {
    fn default() -> Self {
        Self::new()
    }
}

impl View for ProcessMonitor {
    fn render(&self, ctx: &mut RenderContext) {
        let area = ctx.area;
        if area.width < 40 || area.height < 5 {
            return;
        }

        // Stats bar
        self.render_stats(ctx, 0);

        // Header (row 1)
        let _header_ctx = RenderContext::new(ctx.buffer, ctx.sub_area(0, 1, area.width, 1));
        // We need to create a new RenderContext properly
        self.render_header(ctx);

        // Process list
        let list_start = 2u16;
        let visible_rows = (area.height - list_start) as usize;

        // Adjust scroll to keep selection visible
        let scroll = if self.selected < self.scroll {
            self.selected
        } else if self.selected >= self.scroll + visible_rows {
            self.selected - visible_rows + 1
        } else {
            self.scroll
        };

        for (i, proc) in self
            .processes
            .iter()
            .skip(scroll)
            .take(visible_rows)
            .enumerate()
        {
            let y = list_start + i as u16;
            let is_selected = scroll + i == self.selected;

            // Background
            if is_selected {
                for x in 0..area.width {
                    let mut cell = Cell::new(' ');
                    cell.bg = Some(self.colors.selected_bg);
                    ctx.set(x, y, cell);
                }
            }

            let bg = if is_selected {
                Some(self.colors.selected_bg)
            } else {
                None
            };

            // PID
            let pid_str = format!("{:>6}", proc.pid);
            for (j, ch) in pid_str.chars().enumerate() {
                let mut cell = Cell::new(ch);
                cell.fg = Some(self.colors.pid);
                cell.bg = bg;
                ctx.set(j as u16, y, cell);
            }

            // Name (truncated)
            let name = crate::utils::truncate_to_width(&proc.name, 19);
            let mut nx: u16 = 7;
            for ch in name.chars() {
                let cw = crate::utils::char_width(ch) as u16;
                if nx + cw > 26 {
                    break;
                }
                let mut cell = Cell::new(ch);
                cell.fg = Some(self.colors.name);
                cell.bg = bg;
                ctx.set(nx, y, cell);
                nx += cw;
            }

            // CPU%
            let cpu_str = format!("{:>6.1}", proc.cpu);
            let cpu_color = if proc.cpu > 80.0 {
                self.colors.high_cpu
            } else if proc.cpu > 30.0 {
                self.colors.medium_cpu
            } else {
                self.colors.low_cpu
            };
            for (j, ch) in cpu_str.chars().enumerate() {
                let mut cell = Cell::new(ch);
                cell.fg = Some(cpu_color);
                cell.bg = bg;
                ctx.set(27 + j as u16, y, cell);
            }

            // MEM%
            let mem_pct_str = format!("{:>6.1}", proc.memory_percent);
            let mem_color = if proc.memory_percent > 10.0 {
                self.colors.high_mem
            } else {
                Color::WHITE
            };
            for (j, ch) in mem_pct_str.chars().enumerate() {
                let mut cell = Cell::new(ch);
                cell.fg = Some(mem_color);
                cell.bg = bg;
                ctx.set(34 + j as u16, y, cell);
            }

            // MEM (bytes)
            let mem_str = format!("{:>7}", Self::format_bytes(proc.memory));
            for (j, ch) in mem_str.chars().enumerate() {
                let mut cell = Cell::new(ch);
                cell.fg = Some(Color::WHITE);
                cell.bg = bg;
                ctx.set(41 + j as u16, y, cell);
            }

            // Status
            if area.width > 55 {
                let status = crate::utils::truncate_to_width(&proc.status, 8);
                let mut stx: u16 = 49;
                for ch in status.chars() {
                    let cw = crate::utils::char_width(ch) as u16;
                    if stx + cw > 57 {
                        break;
                    }
                    let mut cell = Cell::new(ch);
                    cell.fg = Some(LIGHT_GRAY);
                    cell.bg = bg;
                    ctx.set(stx, y, cell);
                    stx += cw;
                }
            }
        }
    }

    crate::impl_view_meta!("ProcessMonitor");
}

impl_styled_view!(ProcessMonitor);
impl_props_builders!(ProcessMonitor);

/// Create a new process monitor
pub fn process_monitor() -> ProcessMonitor {
    ProcessMonitor::new()
}

/// Alias for htop-style monitor
pub fn htop() -> ProcessMonitor {
    ProcessMonitor::new()
}

// KEEP HERE: Private tests for ProcessMonitor
// ProcessInfo struct tests are private because they test implementation details
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_process_info_clone() {
        let info = ProcessInfo {
            pid: 1234,
            parent_pid: Some(1),
            name: "test".to_string(),
            cpu: 5.0,
            memory: 1024,
            memory_percent: 0.1,
            status: "Running".to_string(),
            cmd: "test".to_string(),
            user: "user".to_string(),
        };
        let cloned = info.clone();
        assert_eq!(info.pid, cloned.pid);
        assert_eq!(info.name, cloned.name);
    }

    #[test]
    fn test_process_info_debug() {
        let info = ProcessInfo {
            pid: 1,
            parent_pid: None,
            name: "init".to_string(),
            cpu: 0.0,
            memory: 0,
            memory_percent: 0.0,
            status: "Sleeping".to_string(),
            cmd: "".to_string(),
            user: "root".to_string(),
        };
        let debug_str = format!("{:?}", info);
        assert!(debug_str.contains("ProcessInfo"));
    }

    #[test]
    fn test_update_process_list() {
        // Test private method implementation
        let mut monitor = ProcessMonitor::new();
        // Just ensure the method exists and can be called
        // Actual functionality depends on sysinfo being available
        if cfg!(feature = "sysinfo") {
            monitor.refresh();
            let _count = monitor.process_count(); // Just verify the method works
        }
    }
}