lsnet 0.8.0

See what's on your local network: fast, zero-config device discovery and identification
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//! Interactive browser: a scrolling list of devices, or of the services they
//! run, beside the full details of whichever device is selected.

use crate::services::{self, Service, port_name};
use crate::{Device, NOISY_SERVICES, Scan, animate, kind_label};
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style, Stylize};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, Cell, Clear, Padding, Paragraph, Row, Scrollbar, ScrollbarOrientation, ScrollbarState,
    Table, TableState, Wrap,
};
use ratatui::{DefaultTerminal, Frame};
use std::io::Write;
use std::net::Ipv4Addr;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

/// Below this width the details go under the list instead of beside it.
const SIDE_BY_SIDE: u16 = 100;
const LABEL: usize = 13;
const FLASH: Duration = Duration::from_secs(2);

/// Every key, for the help screen.
const KEYS: &[(&str, &str)] = &[
    ("↑ ↓  j k", "Move through the list"),
    ("g G  Home End", "First or last row"),
    ("Tab", "Switch between devices and services"),
    ("Enter  y", "Copy the IP address (or address:port)"),
    ("c", "Copy all the details"),
    ("PgUp PgDn", "Scroll details half a page"),
    ("Ctrl-u Ctrl-d", "Scroll details half a page"),
    ("J K", "Scroll details one line"),
    ("^n ^p ^v M-v", "Emacs: down / up, details page down / up"),
    ("M-< M->  ^g", "Emacs: first / last row, clear the filter"),
    ("/", "Filter the list"),
    ("Esc", "Clear the filter, or quit"),
    ("r", "Scan again"),
    ("h  ?", "Show this help"),
    ("q  Ctrl-c", "Quit"),
];

/// Browse until the user quits, returning the latest scan and whether the
/// services view was showing.
pub fn run(
    scan: impl Fn() -> Result<Scan, String> + Sync,
    show_services: bool,
) -> Result<(Scan, bool), String> {
    let mut terminal = ratatui::init();
    let result = App::start(&mut terminal, &scan, show_services).and_then(|mut app| {
        app.run(&mut terminal, &scan)
            .map(|()| (app.scan, app.show_services))
    });
    ratatui::restore();
    result
}

struct App {
    scan: Scan,
    services: Vec<Service>,
    show_services: bool,
    /// Indices into `scan.devices` (or `services`) that match the filter.
    visible: Vec<usize>,
    table: TableState,
    filter: String,
    typing_filter: bool,
    detail_scroll: u16,
    /// Rows of details that fit on screen, and how many there are, from the last draw.
    detail_height: u16,
    detail_lines: u16,
    flash: Option<(String, Instant)>,
    show_help: bool,
}

impl App {
    fn start(
        terminal: &mut DefaultTerminal,
        scan: &(impl Fn() -> Result<Scan, String> + Sync),
        show_services: bool,
    ) -> Result<App, String> {
        let scan = animate(scan, |ping| draw_scanning(terminal, ping))?;
        let mut app = App {
            services: services::list(&scan.devices),
            show_services,
            scan,
            visible: Vec::new(),
            table: TableState::default(),
            filter: String::new(),
            typing_filter: false,
            detail_scroll: 0,
            detail_height: 0,
            detail_lines: 0,
            flash: None,
            show_help: false,
        };
        app.refilter(None);
        Ok(app)
    }

    fn run(
        &mut self,
        terminal: &mut DefaultTerminal,
        scan: &(impl Fn() -> Result<Scan, String> + Sync),
    ) -> Result<(), String> {
        loop {
            if self
                .flash
                .as_ref()
                .is_some_and(|(_, at)| at.elapsed() > FLASH)
            {
                self.flash = None;
            }
            terminal.draw(|f| self.draw(f)).map_err(|e| e.to_string())?;
            // Wake up now and then so a flashed message can expire.
            if !event::poll(Duration::from_millis(250)).map_err(|e| e.to_string())? {
                continue;
            }
            let Event::Key(key) = event::read().map_err(|e| e.to_string())? else {
                continue;
            };
            if key.kind != KeyEventKind::Press {
                continue;
            }
            let key = emacs(key);
            if self.show_help {
                // Any key closes the help, except that the quit keys still quit.
                self.show_help = false;
                if key.code == KeyCode::Char('q')
                    || (key.code == KeyCode::Char('c')
                        && key.modifiers.contains(KeyModifiers::CONTROL))
                {
                    return Ok(());
                }
                continue;
            }
            if self.typing_filter {
                self.filter_key(key);
                continue;
            }
            let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
            match key.code {
                KeyCode::Char('c') if ctrl => return Ok(()),
                KeyCode::Char('q') => return Ok(()),
                KeyCode::Esc if !self.filter.is_empty() => {
                    self.filter.clear();
                    self.refilter(self.selected_key());
                }
                // Esc quits here, but C-g only ever cancels.
                KeyCode::Esc if key.modifiers == KeyModifiers::CONTROL => {}
                KeyCode::Esc => return Ok(()),
                KeyCode::Down | KeyCode::Char('j') => {
                    self.select(self.table.selected().map_or(0, |i| i + 1))
                }
                KeyCode::Up | KeyCode::Char('k') => {
                    self.select(self.table.selected().map_or(0, |i| i.saturating_sub(1)))
                }
                KeyCode::Home | KeyCode::Char('g') => self.select(0),
                KeyCode::End | KeyCode::Char('G') => self.select(usize::MAX),
                KeyCode::PageDown | KeyCode::Char('d') if key.code == KeyCode::PageDown || ctrl => {
                    self.scroll_detail(self.detail_height as i32 / 2)
                }
                KeyCode::PageUp | KeyCode::Char('u') if key.code == KeyCode::PageUp || ctrl => {
                    self.scroll_detail(-(self.detail_height as i32 / 2))
                }
                KeyCode::Char('J') => self.scroll_detail(1),
                KeyCode::Char('K') => self.scroll_detail(-1),
                KeyCode::Enter | KeyCode::Char('y') => self.copy_ip(),
                KeyCode::Char('c') if !ctrl => self.copy_details(),
                KeyCode::Char('/') => self.typing_filter = true,
                KeyCode::Tab | KeyCode::BackTab => {
                    let keep = self.selected_key();
                    self.show_services = !self.show_services;
                    self.refilter(keep);
                }
                KeyCode::Char('h' | '?') => self.show_help = true,
                KeyCode::Char('r') => {
                    let result = animate(scan, |ping| {
                        self.flash = Some((format!("{ping}  Scanning…"), Instant::now()));
                        let _ = terminal.draw(|f| self.draw(f));
                    });
                    match result {
                        Ok(s) => {
                            let keep = self.selected_key();
                            self.services = services::list(&s.devices);
                            self.scan = s;
                            self.refilter(keep);
                            self.flash = None;
                        }
                        Err(e) => {
                            self.flash = Some((format!("Rescan failed: {e}"), Instant::now()))
                        }
                    }
                }
                _ => {}
            }
        }
    }

    fn filter_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Enter => self.typing_filter = false,
            KeyCode::Esc => {
                self.typing_filter = false;
                self.filter.clear();
            }
            KeyCode::Backspace => {
                self.filter.pop();
            }
            KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.typing_filter = false;
                self.filter.clear();
            }
            KeyCode::Char(c) => self.filter.push(c),
            _ => return,
        }
        self.refilter(self.selected_key());
    }

    /// The device (and, in the services view, the port) on list row `row`.
    fn row_key(&self, row: usize) -> (Ipv4Addr, Option<u16>) {
        let i = self.visible[row];
        if self.show_services {
            (self.services[i].ip, Some(self.services[i].port))
        } else {
            (self.scan.devices[i].ip, None)
        }
    }

    fn selected_key(&self) -> Option<(Ipv4Addr, Option<u16>)> {
        self.table
            .selected()
            .filter(|&r| r < self.visible.len())
            .map(|r| self.row_key(r))
    }

    fn selected_service(&self) -> Option<&Service> {
        let i = *self.visible.get(self.table.selected()?)?;
        self.show_services.then(|| &self.services[i])
    }

    fn selected(&self) -> Option<&Device> {
        let i = *self.visible.get(self.table.selected()?)?;
        Some(if self.show_services {
            &self.scan.devices[self.services[i].device]
        } else {
            &self.scan.devices[i]
        })
    }

    fn selected_ip(&self) -> Option<Ipv4Addr> {
        self.selected().map(|d| d.ip)
    }

    /// Recompute which rows match the filter. `keep` stays selected if it
    /// still shows; otherwise the first row for the same device does.
    fn refilter(&mut self, keep: Option<(Ipv4Addr, Option<u16>)>) {
        let needle = self.filter.to_lowercase();
        let matches = |d: &Device, extra: String| {
            needle.is_empty() || (haystack(d) + &extra).contains(&needle)
        };
        self.visible = if self.show_services {
            (0..self.services.len())
                .filter(|&i| {
                    let s = &self.services[i];
                    matches(
                        &self.scan.devices[s.device],
                        format!("\n{}\n{}", s.address(), s.name.unwrap_or("")).to_lowercase(),
                    )
                })
                .collect()
        } else {
            (0..self.scan.devices.len())
                .filter(|&i| matches(&self.scan.devices[i], String::new()))
                .collect()
        };
        let rows = 0..self.visible.len();
        let pos = keep.and_then(|key| {
            rows.clone()
                .find(|&r| self.row_key(r) == key)
                .or_else(|| rows.clone().find(|&r| self.row_key(r).0 == key.0))
        });
        let before = self.selected_ip();
        self.table.select(if self.visible.is_empty() {
            None
        } else {
            Some(pos.unwrap_or(0))
        });
        if self.selected_ip() != before {
            self.detail_scroll = 0;
        }
    }

    fn select(&mut self, i: usize) {
        if self.visible.is_empty() {
            return;
        }
        let i = i.min(self.visible.len() - 1);
        if self.table.selected() != Some(i) {
            self.table.select(Some(i));
            self.detail_scroll = 0;
        }
    }

    fn scroll_detail(&mut self, by: i32) {
        let max = self.detail_lines.saturating_sub(self.detail_height) as i32;
        self.detail_scroll = (self.detail_scroll as i32 + by).clamp(0, max) as u16;
    }

    fn copy_ip(&mut self) {
        let text = match (self.selected_service(), self.selected_ip()) {
            (Some(s), _) => s.address(),
            (None, Some(ip)) => ip.to_string(),
            (None, None) => return,
        };
        copy_to_clipboard(&text);
        self.flash = Some((format!("Copied {text} to the clipboard"), Instant::now()));
    }

    fn copy_details(&mut self) {
        let Some(d) = self.selected() else { return };
        let title = d.name.clone().unwrap_or_else(|| d.ip.to_string());
        copy_to_clipboard(&details_text(d));
        self.flash = Some((
            format!("Copied the details for {title} to the clipboard"),
            Instant::now(),
        ));
    }

    fn draw(&mut self, f: &mut Frame) {
        let notes = self.scan.notes.len() as u16;
        let [header, body, footer] = Layout::vertical([
            Constraint::Length(1 + notes),
            Constraint::Fill(1),
            Constraint::Length(1),
        ])
        .areas(f.area());

        let mut head = vec![Line::from(vec![
            " lsnet ".bold(),
            Span::raw(" "),
            Span::raw(self.scan.summary.clone()).dim(),
        ])];
        head.extend(
            self.scan
                .notes
                .iter()
                .map(|n| Line::from(format!(" {n}")).dim()),
        );
        f.render_widget(Paragraph::new(head), header);

        let [list, detail] = if body.width >= SIDE_BY_SIDE {
            // As wide as the list needs, up to 60%; details get the rest.
            let (first, name, last) = self.column_widths();
            let list = 2 + 2 + first + 1 + name + 1 + last;
            Layout::horizontal([
                Constraint::Length(list.min(body.width * 6 / 10)),
                Constraint::Fill(1),
            ])
            .areas(body)
        } else {
            Layout::vertical([Constraint::Percentage(50), Constraint::Percentage(50)]).areas(body)
        };
        if self.show_services {
            self.draw_services(f, list);
        } else {
            self.draw_list(f, list);
        }
        self.draw_detail(f, detail);
        self.draw_footer(f, footer);
        if self.show_help {
            draw_help(f, body);
        }
    }

    /// Widths of the list's three columns (IP, NAME, TYPE or ADDRESS, HOST,
    /// SERVICE), measured over every row so that filtering doesn't shift the
    /// layout. The services view shows SERVICE before HOST.
    fn column_widths(&self) -> (u16, u16, u16) {
        let widest = |header: &str, widths: &mut dyn Iterator<Item = usize>| {
            widths.max().unwrap_or(0).max(header.len()) as u16
        };
        let devices = &self.scan.devices;
        if self.show_services {
            let s = &self.services;
            (
                widest("ADDRESS", &mut s.iter().map(|s| s.address().len())),
                widest(
                    "HOST",
                    &mut s.iter().map(|s| list_name(&devices[s.device]).width()),
                ),
                widest("SERVICE", &mut s.iter().map(|s| s.name.map_or(0, str::len))),
            )
        } else {
            (
                15,
                widest("NAME", &mut devices.iter().map(|d| list_name(d).width())),
                widest(
                    "TYPE",
                    &mut devices
                        .iter()
                        .map(|d| kind_label(d).map_or(0, |k| k.chars().count())),
                ),
            )
        }
    }

    fn list_title(&self, what: &str, total: usize) -> String {
        if self.filter.is_empty() {
            format!(" {what} ({}) ", self.visible.len())
        } else {
            format!(" {what} ({} of {total}) ", self.visible.len())
        }
    }

    fn draw_services(&mut self, f: &mut Frame, area: Rect) {
        let (address_width, _, service_width) = self.column_widths();
        let rows = self.visible.iter().map(|&i| {
            let s = &self.services[i];
            Row::new([
                Cell::from(s.address()).green(),
                Cell::from(s.name.map_or_else(|| Span::raw("·").dark_gray(), Span::raw)),
                Cell::from(list_name(&self.scan.devices[s.device])),
            ])
        });
        let widths = [
            Constraint::Length(address_width),
            Constraint::Length(service_width),
            Constraint::Fill(1),
        ];
        let table = Table::new(rows, widths)
            .header(Row::new(["ADDRESS", "SERVICE", "HOST"]).bold())
            .block(Block::bordered().title(self.list_title("Services", self.services.len())))
            .row_highlight_style(Style::new().add_modifier(Modifier::REVERSED))
            .highlight_symbol("› ");
        f.render_stateful_widget(table, area, &mut self.table);
    }

    fn draw_list(&mut self, f: &mut Frame, area: Rect) {
        // TYPE gets the room it needs; NAME takes whatever is left.
        let (_, _, type_width) = self.column_widths();
        let rows = self.visible.iter().map(|&i| {
            let d = &self.scan.devices[i];
            let kind_style = match (d.this_device, d.gateway) {
                (true, _) => Style::new().cyan(),
                (_, true) => Style::new().yellow(),
                _ => Style::new(),
            };
            Row::new([
                Cell::from(d.ip.to_string()).green(),
                Cell::from(list_name(d)),
                Cell::from(kind_label(d).unwrap_or_default()).style(kind_style),
            ])
        });
        let table = Table::new(
            rows,
            [
                Constraint::Length(15),
                Constraint::Fill(1),
                Constraint::Length(type_width),
            ],
        )
        .header(Row::new(["IP", "NAME", "TYPE"]).bold())
        .block(Block::bordered().title(self.list_title("Devices", self.scan.devices.len())))
        .row_highlight_style(Style::new().add_modifier(Modifier::REVERSED))
        .highlight_symbol("› ");
        f.render_stateful_widget(table, area, &mut self.table);
    }

    fn draw_detail(&mut self, f: &mut Frame, area: Rect) {
        let Some(d) = self.selected() else {
            let what = match (self.show_services, self.filter.is_empty()) {
                (true, true) => "No services found.",
                (true, false) => "No services match the filter.",
                (false, _) => "No devices match the filter.",
            };
            let empty = Paragraph::new(what.dim()).block(Block::bordered());
            f.render_widget(empty, area);
            return;
        };
        let title = d.name.clone().unwrap_or_else(|| d.ip.to_string());
        let block = Block::bordered()
            .title(format!(" {title} ").bold())
            .padding(Padding::horizontal(1));
        let inner = block.inner(area);
        let para = Paragraph::new(details(d, inner.width)).wrap(Wrap { trim: false });
        self.detail_lines = para.line_count(inner.width) as u16;
        self.detail_height = inner.height;
        self.scroll_detail(0);
        f.render_widget(para.scroll((self.detail_scroll, 0)).block(block), area);
        if self.detail_lines > self.detail_height {
            let mut state =
                ScrollbarState::new(self.detail_lines.saturating_sub(self.detail_height) as usize)
                    .position(self.detail_scroll as usize);
            f.render_stateful_widget(
                Scrollbar::new(ScrollbarOrientation::VerticalRight),
                area,
                &mut state,
            );
        }
    }

    fn draw_footer(&self, f: &mut Frame, area: Rect) {
        let line = if self.typing_filter {
            Line::from(vec![
                " /".bold(),
                Span::raw(self.filter.clone()),
                "▏".slow_blink(),
            ])
        } else if let Some((msg, _)) = &self.flash {
            Line::from(format!(" {msg}")).green()
        } else {
            let mut keys = vec![
                ("↑↓", "move"),
                (
                    "tab",
                    if self.show_services {
                        "devices"
                    } else {
                        "services"
                    },
                ),
                (
                    "⏎",
                    if self.show_services {
                        "copy address"
                    } else {
                        "copy IP"
                    },
                ),
                ("c", "copy details"),
                ("/", "filter"),
                ("r", "rescan"),
                ("?", "help"),
                ("q", "quit"),
            ];
            if !self.filter.is_empty() {
                keys.insert(5, ("esc", "clear filter"));
            }
            let mut spans = vec![Span::raw(" ")];
            for (k, what) in keys {
                spans.push(k.bold());
                spans.push(Span::raw(format!(" {what}  ")).dim());
            }
            Line::from(spans)
        };
        f.render_widget(Paragraph::new(line), area);
    }
}

fn draw_help(f: &mut Frame, area: Rect) {
    let key_width = KEYS
        .iter()
        .map(|(k, _)| k.chars().count())
        .max()
        .unwrap_or(0);
    let mut lines: Vec<Line> = KEYS
        .iter()
        .map(|(k, what)| Line::from(vec![format!("{k:<key_width$}   ").bold(), Span::raw(*what)]))
        .collect();
    lines.push(Line::default());
    lines.push(Line::from("Press any key to close").dim());
    let width = lines.iter().map(Line::width).max().unwrap_or(0) as u16 + 4;
    let height = lines.len() as u16 + 2;
    let popup = Rect {
        x: area.x + area.width.saturating_sub(width) / 2,
        y: area.y + area.height.saturating_sub(height) / 2,
        width: width.min(area.width),
        height: height.min(area.height),
    };
    f.render_widget(Clear, popup);
    let block = Block::bordered()
        .title(" Keys ".bold())
        .padding(Padding::horizontal(1));
    f.render_widget(Paragraph::new(lines).block(block), popup);
}

/// Emacs's movement keys, as the keys they stand for, so they work
/// wherever those do: C-n C-p for ↓ ↑, C-v M-v for a page, M-< M-> for the
/// ends, and C-g for Esc. C-g keeps Control, so it can cancel without quitting.
fn emacs(key: KeyEvent) -> KeyEvent {
    let ctrl = key.modifiers == KeyModifiers::CONTROL;
    let alt = key.modifiers.difference(KeyModifiers::SHIFT) == KeyModifiers::ALT;
    let code = match key.code {
        KeyCode::Char('n') if ctrl => KeyCode::Down,
        KeyCode::Char('p') if ctrl => KeyCode::Up,
        KeyCode::Char('v') if ctrl => KeyCode::PageDown,
        KeyCode::Char('v') if alt => KeyCode::PageUp,
        KeyCode::Char('<') if alt => KeyCode::Home,
        KeyCode::Char('>') if alt => KeyCode::End,
        KeyCode::Char('g') if ctrl => return KeyEvent::new(KeyCode::Esc, KeyModifiers::CONTROL),
        _ => return key,
    };
    KeyEvent::new(code, KeyModifiers::NONE)
}

/// A device's name for the list, falling back to its hostname, then its vendor.
fn list_name(d: &Device) -> Span<'static> {
    match (&d.name, &d.hostname, d.vendor) {
        (Some(n), _, _) => Span::raw(n.clone()).bold(),
        (None, Some(h), _) => Span::raw(h.clone()),
        (None, None, Some(v)) => Span::raw(v).dim(),
        (None, None, None) => Span::raw("·").dark_gray(),
    }
}

fn draw_scanning(terminal: &mut DefaultTerminal, ping: &str) {
    let _ = terminal.draw(|f| {
        let text = format!("{ping}  Scanning the network…");
        let width = text.chars().count() as u16;
        let area = f.area();
        let at = Rect {
            x: area.x + area.width.saturating_sub(width) / 2,
            y: area.y + area.height / 2,
            width: width.min(area.width),
            height: 1.min(area.height),
        };
        f.render_widget(Paragraph::new(text).dim(), at);
    });
}

/// Everything the filter matches against, lowercased.
fn haystack(d: &Device) -> String {
    let fields = [
        Some(d.ip.to_string()),
        d.name.clone(),
        kind_label(d),
        d.model.clone(),
        d.vendor.map(String::from),
        d.mac.clone(),
        d.hostname.clone(),
    ];
    fields
        .into_iter()
        .flatten()
        .collect::<Vec<_>>()
        .join("\n")
        .to_lowercase()
}

/// The details pane's lines for `d`, wrapped to `cols` with long values
/// continuing under the value column rather than the label.
fn details(d: &Device, cols: u16) -> Vec<Line<'static>> {
    let mut out = Vec::new();
    // One value column for the whole pane, wide enough for the longest Bonjour service type.
    let services = d.mdns.iter().flat_map(|m| m.services.keys());
    let width = services.map(String::len).max().unwrap_or(0).max(LABEL);
    let room = (cols as usize).saturating_sub(width + 1);
    let row = |out: &mut Vec<Line<'static>>, label: Span<'static>, value: &str, style: Style| {
        for (i, part) in wrap(value, room).into_iter().enumerate() {
            let label = if i == 0 { label.clone() } else { Span::raw("") };
            let pad = " ".repeat(width + 1 - label.width().min(width));
            out.push(Line::from(vec![
                label,
                Span::raw(pad),
                Span::styled(part, style),
            ]));
        }
    };
    let field = |out: &mut Vec<Line<'static>>, label: &'static str, value: Option<String>| {
        if let Some(v) = value.filter(|v| !v.is_empty()) {
            row(out, label.dim(), &v, Style::new());
        }
    };
    let heading = [kind_label(d), d.model.clone()]
        .into_iter()
        .flatten()
        .collect::<Vec<_>>()
        .join(" · ");
    if !heading.is_empty() {
        out.push(Line::from(heading).italic());
        out.push(Line::default());
    }

    field(&mut out, "IP", Some(d.ip.to_string()));
    field(&mut out, "MAC", d.mac.clone());
    let vendor = match (d.vendor, d.randomized_mac) {
        (Some(v), _) => Some(v.to_string()),
        (None, true) => Some("unknown (private MAC)".into()),
        (None, false) => None,
    };
    field(&mut out, "Vendor", vendor);
    field(&mut out, "Hostname", d.hostname.clone());
    if !d.open_ports.is_empty() {
        let ports = d
            .open_ports
            .iter()
            .map(|&p| match port_name(p) {
                Some(n) => format!("{p} {n}"),
                None => p.to_string(),
            })
            .collect::<Vec<_>>()
            .join(" · ");
        field(&mut out, "Open ports", Some(ports));
    }

    if let Some(m) = &d.mdns {
        section(&mut out, "Bonjour (mDNS)");
        field(&mut out, "Name", m.hostname.clone());
        // Services that identify the device first; generic infrastructure dimmed at the end.
        let (noisy, useful): (Vec<_>, Vec<_>) = m
            .services
            .iter()
            .partition(|(s, _)| NOISY_SERVICES.contains(&s.as_str()));
        for (dim, (svc, instance)) in useful
            .into_iter()
            .map(|s| (false, s))
            .chain(noisy.into_iter().map(|s| (true, s)))
        {
            let style = if dim {
                Style::new().dark_gray()
            } else {
                Style::new()
            };
            let label = Span::styled(
                svc.clone(),
                style.fg(if dim { Color::DarkGray } else { Color::Blue }),
            );
            row(&mut out, label, instance, style);
            for (k, v) in m.txt.get(svc).into_iter().flatten() {
                row(
                    &mut out,
                    Span::raw(""),
                    &format!("{k} = {v}"),
                    Style::new().dark_gray(),
                );
            }
        }
    }

    if let Some(s) = &d.ssdp {
        section(&mut out, "UPnP");
        field(&mut out, "Name", s.friendly_name.clone());
        field(&mut out, "Manufacturer", s.manufacturer.clone());
        let model = match (&s.model_name, &s.model_number) {
            (Some(name), Some(number)) if !name.contains(number.as_str()) => {
                Some(format!("{name} {number}"))
            }
            (Some(name), _) => Some(name.clone()),
            (None, number) => number.clone(),
        };
        field(&mut out, "Model", model);
        field(&mut out, "Device type", s.device_type.clone());
        field(&mut out, "Server", s.server.clone());
    }

    if let Some(k) = &d.kasa {
        section(&mut out, "TP-Link Kasa");
        field(&mut out, "Name", k.alias.clone());
        field(&mut out, "Model", k.model.clone());
        field(&mut out, "Description", k.description.clone());
        field(&mut out, "Device type", k.device_type.clone());
    }

    if let Some(n) = &d.netbios {
        section(&mut out, "NetBIOS");
        field(&mut out, "Name", Some(n.name.clone()));
        field(&mut out, "MAC", n.mac.clone());
    }

    if let Some(h) = &d.http {
        section(&mut out, "Web (port 80)");
        field(&mut out, "Title", h.title.clone());
        field(&mut out, "Server", h.server.clone());
    }
    out
}

fn section(out: &mut Vec<Line<'static>>, title: &'static str) {
    out.push(Line::default());
    out.push(Line::from(title).bold().cyan());
}

/// The details pane as plain text for the clipboard: a title, then every
/// line unwrapped, with styling and trailing spaces dropped.
fn details_text(d: &Device) -> String {
    let title = d.name.clone().unwrap_or_else(|| d.ip.to_string());
    let lines = details(d, u16::MAX).into_iter().map(|line| {
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        text.trim_end().to_string()
    });
    let mut out = std::iter::once(title)
        .chain(lines)
        .collect::<Vec<_>>()
        .join("\n");
    out.push('\n');
    out
}

/// Break `text` into lines of at most `max` characters, at spaces where it can.
fn wrap(text: &str, max: usize) -> Vec<String> {
    let max = max.max(1);
    let mut lines = Vec::new();
    let mut line = String::new();
    for mut word in text.split(' ') {
        loop {
            let used = line.chars().count();
            if used + usize::from(used > 0) + word.chars().count() <= max {
                if used > 0 {
                    line.push(' ');
                }
                line.push_str(word);
                break;
            }
            if used > 0 {
                lines.push(std::mem::take(&mut line));
                continue;
            }
            // A word longer than a whole line gets split, after punctuation
            // if there's some (hostnames, URNs, paths), or else anywhere.
            let fits = word.char_indices().nth(max).map_or(word.len(), |(i, _)| i);
            let at = word[..fits]
                .rfind(['.', ':', '/', '-', '_', '@'])
                .map_or(fits, |i| i + 1);
            lines.push(word[..at].to_string());
            word = &word[at..];
        }
    }
    if !line.is_empty() || lines.is_empty() {
        lines.push(line);
    }
    lines
}

/// Use the platform's clipboard tool, or failing that ask the terminal to do
/// it (OSC 52), which also works over SSH in most modern terminals.
fn copy_to_clipboard(text: &str) {
    #[cfg(windows)]
    if crate::platform::set_clipboard(text) {
        return;
    }
    let tools: &[&[&str]] = if cfg!(target_os = "macos") {
        &[&["pbcopy"]]
    } else if cfg!(windows) {
        &[]
    } else {
        &[
            &["wl-copy"],
            &["xclip", "-selection", "clipboard"],
            &["xsel", "--clipboard", "--input"],
        ]
    };
    for tool in tools {
        let child = Command::new(tool[0])
            .args(&tool[1..])
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn();
        let Ok(mut child) = child else { continue };
        let wrote = child
            .stdin
            .take()
            .is_some_and(|mut stdin| stdin.write_all(text.as_bytes()).is_ok());
        if wrote && child.wait().is_ok_and(|s| s.success()) {
            return;
        }
    }
    let mut out = std::io::stdout();
    let _ = write!(out, "\x1b]52;c;{}\x07", base64(text.as_bytes()));
    let _ = out.flush();
}

fn base64(data: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::new();
    for chunk in data.chunks(3) {
        let n = chunk
            .iter()
            .enumerate()
            .fold(0u32, |n, (i, &b)| n | (b as u32) << (16 - 8 * i));
        for i in 0..4 {
            if i <= chunk.len() {
                out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char);
            } else {
                out.push('=');
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn emacs_keys_stand_for_the_usual_ones() {
        let k = |c, m| emacs(KeyEvent::new(KeyCode::Char(c), m)).code;
        assert_eq!(k('n', KeyModifiers::CONTROL), KeyCode::Down);
        assert_eq!(k('p', KeyModifiers::CONTROL), KeyCode::Up);
        assert_eq!(k('v', KeyModifiers::CONTROL), KeyCode::PageDown);
        assert_eq!(k('v', KeyModifiers::ALT), KeyCode::PageUp);
        assert_eq!(
            k('<', KeyModifiers::ALT | KeyModifiers::SHIFT),
            KeyCode::Home
        );
        assert_eq!(k('>', KeyModifiers::ALT), KeyCode::End);
        assert_eq!(k('g', KeyModifiers::CONTROL), KeyCode::Esc);
        // Plain letters, and Ctrl-c and Ctrl-d, are left alone.
        assert_eq!(k('n', KeyModifiers::NONE), KeyCode::Char('n'));
        assert_eq!(k('d', KeyModifiers::CONTROL), KeyCode::Char('d'));
    }

    #[test]
    fn wrap_breaks_at_spaces_then_mid_word() {
        assert_eq!(
            wrap("7000 AirPlay · 62078 iOS sync", 20),
            ["7000 AirPlay · 62078", "iOS sync"]
        );
        assert_eq!(
            wrap("fhrouter.mynetworksettings.com", 29),
            ["fhrouter.mynetworksettings.", "com"]
        );
        assert_eq!(
            wrap("urn:schemas-upnp-org:device:InternetGatewayDevice:2", 30),
            ["urn:schemas-upnp-org:device:", "InternetGatewayDevice:2"]
        );
        assert_eq!(wrap("abcdefghij", 4), ["abcd", "efgh", "ij"]);
        assert_eq!(wrap("short", 20), ["short"]);
        assert_eq!(wrap("", 20), [""]);
    }

    #[test]
    fn details_text_is_plain_and_unwrapped() {
        let mut d = Device::new(Ipv4Addr::new(192, 168, 1, 1));
        d.name = Some("Home Router".into());
        d.hostname = Some("a-very-long-hostname.mynetworksettings.example.com".into());
        let mut m = crate::mdns::MdnsInfo::default();
        m.services.insert("airplay".into(), "Home Router".into());
        m.txt
            .entry("airplay".into())
            .or_default()
            .insert("model".into(), "AppleTV14,1".into());
        d.mdns = Some(m);
        let text = details_text(&d);
        assert!(text.starts_with("Home Router\n"));
        assert!(
            text.contains("Hostname      a-very-long-hostname.mynetworksettings.example.com\n")
        );
        assert!(text.contains("airplay       Home Router\n              model = AppleTV14,1\n"));
        assert!(text.lines().all(|l| l == l.trim_end()));
    }

    #[test]
    fn base64_pads() {
        assert_eq!(base64(b"192.168.1.1"), "MTkyLjE2OC4xLjE=");
        assert_eq!(base64(b"ab"), "YWI=");
        assert_eq!(base64(b"abc"), "YWJj");
        assert_eq!(base64(b"a"), "YQ==");
    }
}