fuckport 0.1.2

A CLI for killing processes by PID, name, or port.
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
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
use std::collections::BTreeSet;
use std::io;
use std::time::Duration;

use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crossterm::execute;
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style, Stylize};
use ratatui::text::Line;
use ratatui::widgets::{Block, Borders, Cell, Clear, Paragraph, Row, Table, TableState, Widget};
use ratatui::{DefaultTerminal, Frame};
use sysinfo::Pid;

use crate::error::AppResult;
use crate::process::{ProcessCatalog, ProcessRecord};

const TABLE_COLUMN_SPACING: u16 = 1;
const SEL_WIDTH: u16 = 5;
const PID_WIDTH: u16 = 7;
const CPU_WIDTH: u16 = 8;
const MEMORY_WIDTH: u16 = 10;
const APP_MIN_WIDTH: u16 = 12;
const APP_MAX_WIDTH: u16 = 22;
const PROCESS_MIN_WIDTH: u16 = 20;
const PROCESS_MAX_WIDTH: u16 = 42;
const PORTS_MIN_WIDTH: u16 = 8;
const PORTS_MAX_WIDTH: u16 = 18;

pub fn pick_interactive(catalog: &ProcessCatalog, verbose: bool) -> AppResult<BTreeSet<Pid>> {
    let records = catalog.process_records();
    if records.is_empty() {
        return Ok(BTreeSet::new());
    }

    let mut terminal =
        init_terminal().map_err(|error| format!("interactive mode failed: {error}"))?;
    let result = run_app(&mut terminal, records, verbose);
    restore_terminal(terminal).map_err(|error| format!("failed to restore terminal: {error}"))?;

    result.map(|state| state.selected_pids().into_iter().collect::<BTreeSet<_>>())
}

fn run_app(
    terminal: &mut DefaultTerminal,
    records: Vec<ProcessRecord>,
    verbose: bool,
) -> AppResult<AppState> {
    let mut state = AppState::new(records, verbose);
    drain_pending_events()?;

    loop {
        terminal
            .draw(|frame| draw(frame, &mut state))
            .map_err(|error| format!("failed to draw interactive UI: {error}"))?;

        if event::poll(Duration::from_millis(200))
            .map_err(|error| format!("failed to read terminal events: {error}"))?
            && let Event::Key(key) =
                event::read().map_err(|error| format!("failed to read key event: {error}"))?
            && handle_key_event(&mut state, key)
        {
            return Ok(state);
        }
    }
}

fn init_terminal() -> io::Result<DefaultTerminal> {
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    ratatui::Terminal::new(ratatui::backend::CrosstermBackend::new(stdout))
}

fn restore_terminal(mut terminal: DefaultTerminal) -> io::Result<()> {
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;
    Ok(())
}

fn drain_pending_events() -> AppResult<()> {
    while event::poll(Duration::from_millis(0))
        .map_err(|error| format!("failed to drain terminal events: {error}"))?
    {
        let _ = event::read().map_err(|error| format!("failed to read terminal event: {error}"))?;
    }
    Ok(())
}

fn handle_key_event(state: &mut AppState, key: KeyEvent) -> bool {
    if key.kind != KeyEventKind::Press {
        return false;
    }

    match key.code {
        KeyCode::Esc => {
            state.cancelled = true;
            true
        }
        KeyCode::Enter => !state.selected.is_empty(),
        KeyCode::F(1) => {
            state.set_sort_mode(SortMode::Cpu);
            false
        }
        KeyCode::F(2) => {
            state.set_sort_mode(SortMode::Memory);
            false
        }
        KeyCode::F(3) => {
            state.set_sort_mode(SortMode::Name);
            false
        }
        KeyCode::Up => {
            state.move_up();
            false
        }
        KeyCode::Down => {
            state.move_down();
            false
        }
        KeyCode::PageUp => {
            state.page_up();
            false
        }
        KeyCode::PageDown => {
            state.page_down();
            false
        }
        KeyCode::Home => {
            state.jump_to_start();
            false
        }
        KeyCode::End => {
            state.jump_to_end();
            false
        }
        KeyCode::Char(' ') => {
            state.toggle_current();
            false
        }
        KeyCode::Backspace => {
            state.pop_query();
            false
        }
        KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            state.cancelled = true;
            true
        }
        KeyCode::Char(ch)
            if !key.modifiers.contains(KeyModifiers::CONTROL)
                && !key.modifiers.contains(KeyModifiers::ALT) =>
        {
            state.push_query(ch);
            false
        }
        _ => false,
    }
}

fn draw(frame: &mut Frame<'_>, state: &mut AppState) {
    let vertical = Layout::vertical([
        Constraint::Length(3),
        Constraint::Min(8),
        Constraint::Length(3),
        Constraint::Length(2),
    ]);
    let [search_area, table_area, detail_area, help_area] = vertical.areas(frame.area());

    render_search(frame, search_area, state);
    render_table(frame, table_area, state);
    render_detail(frame, detail_area, state);
    render_help(frame, help_area, state);
}

fn render_search(frame: &mut Frame<'_>, area: Rect, state: &AppState) {
    let title = format!(
        " Search {} ",
        if state.query.is_empty() {
            "(type for fuzzy search)"
        } else {
            ""
        }
    );
    let input = Paragraph::new(state.query.clone()).block(
        Block::bordered()
            .title(title)
            .border_style(Style::default().fg(Color::Cyan)),
    );
    frame.render_widget(input, area);
}

fn render_table(frame: &mut Frame<'_>, area: Rect, state: &mut AppState) {
    state.sync_table_state();

    let header = Row::new([
        Cell::from("Sel"),
        Cell::from("PID"),
        Cell::from("App"),
        Cell::from("Process"),
        Cell::from(format!("{:>6}", "CPU")),
        Cell::from("Memory"),
        Cell::from("Ports"),
    ])
    .style(
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD),
    )
    .height(1);

    let filtered_records = state.filtered_records();
    let widths = compute_table_widths(&filtered_records, state.verbose, area.width);
    let rows = filtered_records.into_iter().map(|record| {
        let selected = if state.is_selected(record.pid) {
            "[x]"
        } else {
            "[ ]"
        };

        let process_name = if state.verbose && !record.cmd.is_empty() {
            format!("{} | {}", record.name, truncate(&record.cmd, 48))
        } else {
            record.name.clone()
        };

        let cpu_style = cpu_style(record.cpu_usage);
        let mem_style = memory_style(record.memory_bytes);
        let wrapped_ports = format_ports_wrapped(&record.ports);
        let port_lines = wrapped_ports.lines().count().max(1) as u16;

        Row::new([
            Cell::from(selected),
            Cell::from(record.pid.as_u32().to_string()),
            Cell::from(truncate(&record.app_name, 22)),
            Cell::from(truncate(&process_name, 42)),
            Cell::from(format!("{:>5.1}%", record.cpu_usage)).style(cpu_style),
            Cell::from(format_memory(record.memory_bytes)).style(mem_style),
            Cell::from(wrapped_ports),
        ])
        .height(port_lines)
    });

    let table = Table::new(
        rows,
        widths,
    )
    .column_spacing(TABLE_COLUMN_SPACING)
    .header(header)
    .row_highlight_style(
        Style::default()
            .bg(Color::Rgb(24, 34, 54))
            .add_modifier(Modifier::BOLD),
    )
    .block(
        Block::default()
            .title(" Processes ")
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Blue)),
    );

    frame.render_stateful_widget(table, area, &mut state.table_state);

    if state.filtered_indexes.is_empty() {
        frame.render_widget(Clear, centered_rect(50, 10, area));
        frame.render_widget(EmptyState, centered_rect(50, 10, area));
    }
}

fn render_help(frame: &mut Frame<'_>, area: Rect, state: &AppState) {
    let total = state.filtered_records().len();
    let selected = state.selected.len();
    let sort = state.sort_mode.label();
    let line = Line::from(vec![
        "F1".cyan().bold(),
        " CPU  ".dark_gray(),
        "F2".cyan().bold(),
        " Memory  ".dark_gray(),
        "F3".cyan().bold(),
        " Name  ".dark_gray(),
        "Space".cyan().bold(),
        " toggle  ".dark_gray(),
        "Enter".green().bold(),
        " confirm  ".dark_gray(),
        "Esc".yellow().bold(),
        " cancel  ".dark_gray(),
        format!("Sort {sort}  Showing {total}  Selected {selected}").white(),
    ]);
    frame.render_widget(Paragraph::new(line), area);
}

fn render_detail(frame: &mut Frame<'_>, area: Rect, state: &AppState) {
    let block = Block::default()
        .title(" Details ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Blue));

    let content = match state.current_record() {
        Some(record) => {
            let ports = format_ports_inline(&record.ports);
            let line1 = Line::from(vec![
                "App ".dark_gray(),
                record.app_name.as_str().white().bold(),
                "  Process ".dark_gray(),
                record.name.as_str().white(),
                "  PID ".dark_gray(),
                record.pid.as_u32().to_string().cyan(),
                "  CPU ".dark_gray(),
                format!("{:.1}%", record.cpu_usage).fg(cpu_color(record.cpu_usage)),
                "  Memory ".dark_gray(),
                format_memory(record.memory_bytes).fg(memory_color(record.memory_bytes)),
                "  Ports ".dark_gray(),
                ports.white(),
            ]);
            let cmd = if record.cmd.is_empty() {
                "Command: -".to_string()
            } else {
                format!("Command: {}", truncate(&record.cmd, 160))
            };
            vec![line1, Line::from(cmd.dark_gray())]
        }
        None => vec![Line::from("No process selected".dark_gray())],
    };

    frame.render_widget(Paragraph::new(content).block(block), area);
}

fn centered_rect(horizontal: u16, vertical: u16, area: Rect) -> Rect {
    let vertical_layout = Layout::vertical([
        Constraint::Percentage((100 - vertical) / 2),
        Constraint::Percentage(vertical),
        Constraint::Percentage((100 - vertical) / 2),
    ]);
    let [_, middle, _] = vertical_layout.areas(area);
    let horizontal_layout = Layout::horizontal([
        Constraint::Percentage((100 - horizontal) / 2),
        Constraint::Percentage(horizontal),
        Constraint::Percentage((100 - horizontal) / 2),
    ]);
    let [_, center, _] = horizontal_layout.areas(middle);
    center
}

fn cpu_style(cpu: f32) -> Style {
    Style::default().fg(cpu_color(cpu))
}

fn cpu_color(cpu: f32) -> Color {
    if cpu >= 60.0 {
        Color::Red
    } else if cpu >= 25.0 {
        Color::Yellow
    } else {
        Color::Green
    }
}

fn memory_style(memory: u64) -> Style {
    Style::default().fg(memory_color(memory))
}

fn memory_color(memory: u64) -> Color {
    if memory >= 1_500_000_000 {
        Color::Red
    } else if memory >= 512_000_000 {
        Color::Yellow
    } else {
        Color::Green
    }
}

fn format_ports_inline(ports: &BTreeSet<u16>) -> String {
    if ports.is_empty() {
        return "-".to_string();
    }

    ports
        .iter()
        .take(4)
        .map(|port| format!(":{port}"))
        .collect::<Vec<_>>()
        .join(",")
}

fn format_ports_wrapped(ports: &BTreeSet<u16>) -> String {
    if ports.is_empty() {
        return "-".to_string();
    }

    ports
        .iter()
        .take(4)
        .map(|port| format!(":{port}"))
        .collect::<Vec<_>>()
        .chunks(2)
        .map(|chunk| chunk.join(","))
        .collect::<Vec<_>>()
        .join("\n")
}

fn compute_table_widths(
    records: &[&ProcessRecord],
    verbose: bool,
    total_width: u16,
) -> [Constraint; 7] {
    let reserved = SEL_WIDTH + PID_WIDTH + CPU_WIDTH + MEMORY_WIDTH + 2;
    let spacing = TABLE_COLUMN_SPACING * 6;
    let flexible = total_width.saturating_sub(reserved + spacing);

    let app_target = content_width(
        records.iter().map(|record| record.app_name.chars().count()),
        APP_MIN_WIDTH,
        APP_MAX_WIDTH,
    );
    let process_target = content_width(
        records.iter().map(|record| {
            if verbose && !record.cmd.is_empty() {
                format!("{} | {}", record.name, truncate(&record.cmd, 48))
                    .chars()
                    .count()
            } else {
                record.name.chars().count()
            }
        }),
        PROCESS_MIN_WIDTH,
        PROCESS_MAX_WIDTH,
    );
    let ports_target = content_width(
        records
            .iter()
            .map(|record| longest_line_width(&format_ports_wrapped(&record.ports))),
        PORTS_MIN_WIDTH,
        PORTS_MAX_WIDTH,
    );

    let (app_width, process_width, ports_width) = allocate_flexible_widths(
        flexible,
        [
            (APP_MIN_WIDTH, app_target),
            (PROCESS_MIN_WIDTH, process_target),
            (PORTS_MIN_WIDTH, ports_target),
        ],
    );

    [
        Constraint::Length(SEL_WIDTH),
        Constraint::Length(PID_WIDTH),
        Constraint::Length(app_width),
        Constraint::Length(process_width),
        Constraint::Length(CPU_WIDTH),
        Constraint::Length(MEMORY_WIDTH),
        Constraint::Length(ports_width),
    ]
}

fn content_width<I>(lengths: I, min_width: u16, max_width: u16) -> u16
where
    I: Iterator<Item = usize>,
{
    let width = lengths.max().unwrap_or(min_width as usize) as u16;
    width.clamp(min_width, max_width)
}

fn longest_line_width(value: &str) -> usize {
    value.lines().map(|line| line.chars().count()).max().unwrap_or(0)
}

fn allocate_flexible_widths(total: u16, specs: [(u16, u16); 3]) -> (u16, u16, u16) {
    let min_total = specs.iter().map(|(min, _)| *min).sum::<u16>();
    if total <= min_total {
        return (specs[0].0, specs[1].0, specs[2].0);
    }

    let mut widths = [specs[0].0, specs[1].0, specs[2].0];
    let targets = [specs[0].1, specs[1].1, specs[2].1];
    let mut remaining = total - min_total;

    loop {
        let mut changed = false;

        for index in 0..widths.len() {
            if remaining == 0 {
                break;
            }

            if widths[index] < targets[index] {
                widths[index] += 1;
                remaining -= 1;
                changed = true;
            }
        }

        if !changed {
            break;
        }
    }

    while remaining > 0 {
        widths[1] += 1;
        remaining -= 1;
    }

    (widths[0], widths[1], widths[2])
}

fn format_memory(bytes: u64) -> String {
    const KB: f64 = 1024.0;
    const MB: f64 = KB * 1024.0;
    const GB: f64 = MB * 1024.0;

    let bytes = bytes as f64;
    if bytes >= GB {
        format!("{:.1}G", bytes / GB)
    } else if bytes >= MB {
        format!("{:.1}M", bytes / MB)
    } else if bytes >= KB {
        format!("{:.1}K", bytes / KB)
    } else {
        format!("{:.0}B", bytes)
    }
}

fn truncate(value: &str, width: usize) -> String {
    let mut result = value.chars().take(width).collect::<String>();
    if value.chars().count() > width && width > 1 {
        result.pop();
        result.push('~');
    }
    result
}

#[derive(Default)]
struct EmptyState;

impl Widget for EmptyState {
    fn render(self, area: Rect, buf: &mut Buffer) {
        Paragraph::new("No matching processes")
            .block(Block::bordered().title(" Filter "))
            .render(area, buf);
    }
}

struct AppState {
    records: Vec<ProcessRecord>,
    filtered_indexes: Vec<usize>,
    selected: BTreeSet<Pid>,
    cursor: usize,
    query: String,
    sort_mode: SortMode,
    verbose: bool,
    cancelled: bool,
    table_state: TableState,
}

impl AppState {
    fn new(records: Vec<ProcessRecord>, verbose: bool) -> Self {
        let filtered_indexes = (0..records.len()).collect::<Vec<_>>();
        let mut table_state = TableState::default();
        table_state.select(Some(0));

        Self {
            records,
            filtered_indexes,
            selected: BTreeSet::new(),
            cursor: 0,
            query: String::new(),
            sort_mode: SortMode::Cpu,
            verbose,
            cancelled: false,
            table_state,
        }
    }

    fn filtered_records(&self) -> Vec<&ProcessRecord> {
        self.filtered_indexes
            .iter()
            .map(|index| &self.records[*index])
            .collect()
    }

    fn selected_pids(&self) -> Vec<Pid> {
        if self.cancelled {
            Vec::new()
        } else {
            self.selected.iter().copied().collect()
        }
    }

    fn is_selected(&self, pid: Pid) -> bool {
        self.selected.contains(&pid)
    }

    fn current_record(&self) -> Option<&ProcessRecord> {
        self.filtered_indexes
            .get(self.cursor)
            .map(|index| &self.records[*index])
    }

    fn sync_table_state(&mut self) {
        if self.filtered_indexes.is_empty() {
            self.cursor = 0;
            self.table_state.select(None);
        } else {
            self.cursor = self.cursor.min(self.filtered_indexes.len() - 1);
            self.table_state.select(Some(self.cursor));
        }
    }

    fn move_up(&mut self) {
        if self.cursor > 0 {
            self.cursor -= 1;
        }
    }

    fn move_down(&mut self) {
        if !self.filtered_indexes.is_empty() && self.cursor + 1 < self.filtered_indexes.len() {
            self.cursor += 1;
        }
    }

    fn page_up(&mut self) {
        self.cursor = self.cursor.saturating_sub(10);
    }

    fn page_down(&mut self) {
        if !self.filtered_indexes.is_empty() {
            self.cursor = (self.cursor + 10).min(self.filtered_indexes.len() - 1);
        }
    }

    fn jump_to_start(&mut self) {
        self.cursor = 0;
    }

    fn jump_to_end(&mut self) {
        if !self.filtered_indexes.is_empty() {
            self.cursor = self.filtered_indexes.len() - 1;
        }
    }

    fn toggle_current(&mut self) {
        if let Some(pid) = self.current_pid() {
            if !self.selected.insert(pid) {
                self.selected.remove(&pid);
            }
        }
    }

    fn current_pid(&self) -> Option<Pid> {
        self.filtered_indexes
            .get(self.cursor)
            .map(|index| self.records[*index].pid)
    }

    fn push_query(&mut self, ch: char) {
        self.query.push(ch);
        self.refresh_filter();
    }

    fn pop_query(&mut self) {
        self.query.pop();
        self.refresh_filter();
    }

    fn set_sort_mode(&mut self, sort_mode: SortMode) {
        self.sort_mode = sort_mode;
        self.refresh_filter();
    }

    fn refresh_filter(&mut self) {
        let mut matches = self
            .records
            .iter()
            .enumerate()
            .filter_map(|(index, record)| {
                fuzzy_match_score(record, &self.query).map(|score| (index, score))
            })
            .collect::<Vec<_>>();

        matches.sort_by(|(left_index, left_score), (right_index, right_score)| {
            let left = &self.records[*left_index];
            let right = &self.records[*right_index];

            let fuzzy_cmp = right_score.cmp(left_score);
            let sort_cmp = self.sort_mode.compare(left, right);

            if self.query.trim().is_empty() {
                sort_cmp.then(left.pid.as_u32().cmp(&right.pid.as_u32()))
            } else {
                fuzzy_cmp
                    .then(sort_cmp)
                    .then(left.pid.as_u32().cmp(&right.pid.as_u32()))
            }
        });

        self.filtered_indexes = matches.into_iter().map(|(index, _)| index).collect();
        self.cursor = 0;
        self.sync_table_state();
    }
}

#[derive(Clone, Copy)]
enum SortMode {
    Cpu,
    Memory,
    Name,
}

impl SortMode {
    fn label(self) -> &'static str {
        match self {
            SortMode::Cpu => "CPU",
            SortMode::Memory => "Memory",
            SortMode::Name => "Name",
        }
    }

    fn compare(self, left: &ProcessRecord, right: &ProcessRecord) -> std::cmp::Ordering {
        match self {
            SortMode::Cpu => right
                .cpu_usage
                .partial_cmp(&left.cpu_usage)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then(right.memory_bytes.cmp(&left.memory_bytes))
                .then(left.app_name.cmp(&right.app_name))
                .then(left.name.cmp(&right.name)),
            SortMode::Memory => right
                .memory_bytes
                .cmp(&left.memory_bytes)
                .then(
                    right
                        .cpu_usage
                        .partial_cmp(&left.cpu_usage)
                        .unwrap_or(std::cmp::Ordering::Equal),
                )
                .then(left.app_name.cmp(&right.app_name))
                .then(left.name.cmp(&right.name)),
            SortMode::Name => left
                .app_name
                .cmp(&right.app_name)
                .then(left.name.cmp(&right.name))
                .then(
                    right
                        .cpu_usage
                        .partial_cmp(&left.cpu_usage)
                        .unwrap_or(std::cmp::Ordering::Equal),
                ),
        }
    }
}

fn fuzzy_match_score(record: &ProcessRecord, query: &str) -> Option<i64> {
    if query.trim().is_empty() {
        return Some(0);
    }

    let ports = format_ports_inline(&record.ports);
    let fields = [
        record.app_name.as_str(),
        record.name.as_str(),
        record.cmd.as_str(),
        ports.as_str(),
    ];

    let mut best = None;
    for field in fields {
        if let Some(score) = fuzzy_score(field, query) {
            best = Some(best.map_or(score, |current: i64| current.max(score)));
        }
    }

    if let Some(score) = fuzzy_score(&record.pid.as_u32().to_string(), query) {
        best = Some(best.map_or(score, |current: i64| current.max(score)));
    }

    best
}

fn fuzzy_score(haystack: &str, needle: &str) -> Option<i64> {
    let haystack = haystack.to_lowercase();
    let needle = needle.to_lowercase();
    let needle_chars = needle.chars().collect::<Vec<_>>();
    if needle_chars.is_empty() {
        return Some(0);
    }

    let haystack_chars = haystack.chars().collect::<Vec<_>>();
    let mut score = 0_i64;
    let mut needle_index = 0_usize;
    let mut consecutive = 0_i64;
    let mut last_match = None;

    for (index, ch) in haystack_chars.iter().enumerate() {
        if needle_index >= needle_chars.len() {
            break;
        }

        if *ch == needle_chars[needle_index] {
            score += 10;

            if index == 0
                || matches!(
                    haystack_chars.get(index.saturating_sub(1)),
                    Some(' ' | '-' | '_' | '/' | '\\' | '.')
                )
            {
                score += 15;
            }

            if let Some(previous) = last_match {
                if index == previous + 1 {
                    consecutive += 1;
                    score += 20 + consecutive * 5;
                } else {
                    consecutive = 0;
                    score -= (index - previous - 1) as i64;
                }
            } else {
                score += 25_i64.saturating_sub(index as i64);
            }

            last_match = Some(index);
            needle_index += 1;
        }
    }

    if needle_index == needle_chars.len() {
        score += (needle_chars.len() as i64) * 8;
        Some(score)
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;

    use sysinfo::Pid;

    use super::{
        AppState, SortMode, allocate_flexible_widths, format_memory, format_ports_wrapped,
        fuzzy_match_score,
    };
    use crate::process::ProcessRecord;

    fn sample_record() -> ProcessRecord {
        ProcessRecord {
            pid: Pid::from_u32(42),
            app_name: "chrome".to_string(),
            name: "chrome.exe".to_string(),
            cmd: "chrome.exe --profile".to_string(),
            cpu_usage: 12.5,
            memory_bytes: 512 * 1024 * 1024,
            ports: BTreeSet::from([9222]),
        }
    }

    #[test]
    fn fuzzy_filter_matches_app_name_and_ports() {
        let record = sample_record();
        assert!(fuzzy_match_score(&record, "chrm").is_some());
        assert!(fuzzy_match_score(&record, "922").is_some());
        assert!(fuzzy_match_score(&record, "cexp").is_some());
        assert!(fuzzy_match_score(&record, "firefox").is_none());
    }

    #[test]
    fn state_resets_cursor_on_filter_change() {
        let records = vec![sample_record()];
        let mut state = AppState::new(records, false);
        state.push_query('c');
        assert_eq!(state.cursor, 0);
    }

    #[test]
    fn memory_format_uses_human_units() {
        assert_eq!(format_memory(1024), "1.0K");
        assert_eq!(format_memory(1024 * 1024), "1.0M");
    }

    #[test]
    fn wrapped_ports_break_after_every_two_entries() {
        let ports = BTreeSet::from([3000, 3001, 3002]);
        assert_eq!(format_ports_wrapped(&ports), ":3000,:3001\n:3002");
    }

    #[test]
    fn flexible_widths_expand_toward_targets() {
        let widths = allocate_flexible_widths(45, [(12, 18), (20, 30), (8, 14)]);
        assert_eq!(widths, (14, 22, 9));
    }

    #[test]
    fn sort_mode_switches() {
        let mut second = sample_record();
        second.pid = Pid::from_u32(99);
        second.memory_bytes = 2048;
        second.cpu_usage = 99.0;
        second.app_name = "aaa".to_string();
        let records = vec![sample_record(), second];
        let mut state = AppState::new(records, false);
        state.set_sort_mode(SortMode::Name);
        assert_eq!(
            state
                .current_record()
                .map(|record| record.app_name.as_str()),
            Some("aaa")
        );
    }
}