scxtui 2.0.1

TUI for sched_ext schedulers, through scxcli and scx.service
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
// SPDX-License-Identifier: GPL-2.0

//! Rendering. Almost a pure function of the [`App`] state; the one
//! exception is the log view writing its viewport height and clamped
//! scroll offset back into the app.

use crate::model::{Current, DEFAULT_ID, Listing, Pick, Tier};
use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, List, ListItem, ListState, Paragraph, Wrap};

use crate::app::{App, Input, View, is_running, is_running_pick, is_selected, is_selected_pick};
use crate::logs;

const SCHED_PREFIX: &str = "scx_";

pub fn draw(frame: &mut Frame, app: &mut App) {
    let [header, body, footer] = Layout::new(
        Direction::Vertical,
        [
            Constraint::Length(1),
            Constraint::Min(0),
            Constraint::Length(3),
        ],
    )
    .areas(frame.area());

    draw_header(frame, app, header);

    match app.view {
        View::Recommended | View::All => {
            let [left, right] = Layout::new(
                Direction::Horizontal,
                [Constraint::Percentage(45), Constraint::Percentage(55)],
            )
            .areas(body);
            if app.view == View::Recommended {
                draw_recommended_list(frame, app, left);
            } else {
                draw_all_list(frame, app, left);
            }
            draw_status_panel(frame, app, right);
        }
        View::Logs => draw_logs(frame, app, body),
    }

    draw_footer(frame, app, footer);
}

fn draw_header(frame: &mut Frame, app: &App, area: Rect) {
    let line = Line::from(vec![
        Span::styled(
            " scxtui ",
            Style::default()
                .fg(Color::Black)
                .bg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(" via "),
        Span::styled(app.backend_label(), Style::default().fg(Color::Cyan)),
        Span::raw(if app.view == View::All {
            "  all schedulers"
        } else {
            ""
        }),
    ]);
    frame.render_widget(Paragraph::new(line), area);
}

/// The marker in front of a list entry: running, selected for the next
/// start but not running, or nothing.
fn marker(running: bool, selected: bool) -> (&'static str, Style) {
    if running {
        (
            "● ",
            Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD),
        )
    } else if selected {
        ("○ ", Style::default().fg(Color::Yellow))
    } else {
        ("  ", Style::default())
    }
}

/// A profile's marker: by its command, so that of two profiles on one
/// scheduler the one whose options run is the one marked.
fn pick_marker(listing: Option<&Listing>, pick: &Pick) -> (&'static str, Style) {
    match listing {
        Some(l) => marker(is_running_pick(l, pick), is_selected_pick(l, pick)),
        None => marker(false, false),
    }
}

/// A scheduler's marker in the full list: by name.
fn sched_marker(listing: Option<&Listing>, name: &str) -> (&'static str, Style) {
    match listing {
        Some(l) => marker(is_running(l, name), is_selected(l, name)),
        None => marker(false, false),
    }
}

fn draw_recommended_list(frame: &mut Frame, app: &App, area: Rect) {
    let items: Vec<ListItem> = app
        .recommended()
        .iter()
        .map(|pick| {
            let (mark, style) = pick_marker(app.listing.as_ref(), pick);
            let style = if !pick.available {
                Style::default().fg(Color::DarkGray)
            } else {
                style
            };
            // A custom profile says what it runs, after the label: the
            // label is the administrator's name for it, the command is
            // what tells it from the plain entry above.
            let command = match &pick.sched {
                Some(sched) => format!("  {} {}", strip_prefix(sched), format_flags(&pick.args)),
                None => String::new(),
            };
            let mut lines = vec![Line::from(vec![
                Span::styled(mark, style),
                Span::styled(pick.label.clone(), style),
                Span::styled(
                    command.trim_end().to_owned(),
                    Style::default().fg(Color::Cyan),
                ),
                Span::styled(
                    if pick.available {
                        String::new()
                    } else {
                        "  (not installed)".to_owned()
                    },
                    Style::default().fg(Color::DarkGray),
                ),
            ])];
            if !pick.description.is_empty() {
                lines.push(Line::from(Span::styled(
                    format!("    {}", pick.description),
                    Style::default().fg(Color::Gray),
                )));
            }
            ListItem::new(lines)
        })
        .collect();

    let title = match &app.listing {
        Some(l) if l.customized => " Recommended (administrator's catalog) ",
        _ => " Recommended ",
    };
    let list = List::new(items)
        .block(Block::default().borders(Borders::ALL).title(title))
        .highlight_style(
            Style::default()
                .bg(Color::DarkGray)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("▶ ");

    let mut state = ListState::default().with_selected(Some(app.selected));
    frame.render_stateful_widget(list, area, &mut state);
}

/// The groups of the full list, in its order: the featured schedulers
/// (the maintainers' picks, stable by definition), the other stable
/// ones, the experimental ones, and what the catalog does not name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Group {
    Featured,
    Stable,
    Experimental,
    Unknown,
}

impl Group {
    fn of(sched: &crate::model::Installed) -> Self {
        if sched.featured {
            Group::Featured
        } else {
            match sched.tier {
                Tier::Stable => Group::Stable,
                Tier::Experimental => Group::Experimental,
                Tier::Unknown => Group::Unknown,
            }
        }
    }
}

/// One item of the full list: a group header, or the scheduler at
/// that index of the listing's `all`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AllRow {
    Header { group: Group, first: bool },
    Scheduler(usize),
}

/// The full list's items in order: a header before the first scheduler
/// of each group, then the schedulers. Pure, so the mapping between
/// the cursor (a scheduler index) and the item list is tested on its
/// own.
fn all_list_rows(all: &[crate::model::Installed]) -> Vec<AllRow> {
    let mut rows = Vec::with_capacity(all.len() + 4);
    let mut last: Option<Group> = None;
    for (idx, sched) in all.iter().enumerate() {
        let group = Group::of(sched);
        if last != Some(group) {
            rows.push(AllRow::Header {
                group,
                first: rows.is_empty(),
            });
            last = Some(group);
        }
        rows.push(AllRow::Scheduler(idx));
    }
    rows
}

fn draw_all_list(frame: &mut Frame, app: &App, area: Rect) {
    // Featured first, the other stable ones, experimental after, then
    // what the catalog does not name, as the listing orders them. Each
    // group is named once, by a
    // header item of its own (a rule and the name, the rule left off
    // the first group, which starts at the frame). Headers are items
    // so that the list lays them out, but they are never the selected
    // item: the cursor is a scheduler, and its position in the item
    // list is looked up by `all_list_rows`.
    let rows = all_list_rows(app.all());
    let rule = "\u{2500}".repeat(usize::from(area.width.saturating_sub(4)));
    let items: Vec<ListItem> = rows
        .iter()
        .map(|row| match row {
            AllRow::Header { group, first } => {
                let (title, style) = match group {
                    Group::Featured => ("  featured", Style::default().fg(Color::Cyan)),
                    Group::Stable => ("  stable", Style::default().fg(Color::DarkGray)),
                    Group::Experimental => ("  experimental", Style::default().fg(Color::Yellow)),
                    Group::Unknown => {
                        ("  not in the catalog", Style::default().fg(Color::DarkGray))
                    }
                };
                let mut lines = Vec::new();
                if !first {
                    lines.push(Line::from(Span::styled(
                        rule.clone(),
                        Style::default().fg(Color::DarkGray),
                    )));
                }
                lines.push(Line::from(Span::styled(title, style)));
                ListItem::new(lines)
            }
            AllRow::Scheduler(idx) => {
                let sched = &app.all()[*idx];
                let (mark, style) = sched_marker(app.listing.as_ref(), &sched.name);
                ListItem::new(Line::from(vec![
                    Span::styled(mark, style),
                    Span::styled(strip_prefix(&sched.name).to_owned(), style),
                ]))
            }
        })
        .collect();

    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(" All installed schedulers "),
        )
        .highlight_style(
            Style::default()
                .bg(Color::DarkGray)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("▶ ");

    let selected = rows
        .iter()
        .position(|row| *row == AllRow::Scheduler(app.sched_selected));
    let mut state = ListState::default().with_selected(selected);
    frame.render_stateful_widget(list, area, &mut state);
}

fn state_line(current: &Current) -> (String, Color) {
    match current.scheduler.as_deref() {
        Some(DEFAULT_ID) => ("default (kernel scheduler)".to_owned(), Color::White),
        Some(name) => (format!("{} running", strip_prefix(name)), Color::Green),
        None if current.attached() => (
            "a scheduler is attached outside scx.service".to_owned(),
            Color::Yellow,
        ),
        None => (
            "scx.service is active, nothing attached yet".to_owned(),
            Color::Yellow,
        ),
    }
}

/// The Configured line: what the next start would run (the file, or an
/// override, which the line then says), whether that is what runs now,
/// and whether there will be a next start at boot. The last is the
/// first thing a user who just switched wants to know; the answer is
/// the unit's `enabled`, which `start ID` sets and `start default` or a
/// hand `systemctl disable` clear, and it belongs next to the
/// configuration it applies to. `enable --runtime` is said as what it
/// is, since it looks enabled to `systemctl status` and is gone after
/// the reboot.
fn configured_line(current: &Current) -> (String, Color) {
    let boot = if current.unit.enabled {
        "starts at boot"
    } else if current.unit.enabled_runtime {
        "enabled until reboot only"
    } else {
        "not at boot"
    };
    let Some(next) = &current.next else {
        // Nothing to run: after `start default`, or a cleared file.
        // `start default` also disables the unit; an enabled one with
        // nothing to run is a hand edit, and when it starts it runs
        // nothing (`exec` of an empty expansion is a no-op to bash)
        // and exits, which is pointless enough for a colour. The
        // enablement is said in the same words as everywhere else on
        // this line, so a runtime one does not read as "at boot".
        return if current.unit.enabled || current.unit.enabled_runtime {
            (
                format!("nothing (scx.service {boot}, nothing to run)"),
                Color::Yellow,
            )
        } else {
            (format!("nothing ({boot})"), Color::White)
        };
    };
    let what = format!("{} {}", strip_prefix(next.name()), format_flags(&next.args));
    let what = what.trim_end();
    if next.overridden {
        return (
            format!("{what} (SCX_*_OVERRIDE in effect, {boot})"),
            Color::Yellow,
        );
    }
    // "running" takes the kernel's word as well as the unit's: the
    // unit's process exists before its scheduler is attached, and
    // `scheduler` is set only once the kernel reports it.
    let running = current.scheduler.as_deref() == Some(next.name())
        && current
            .running
            .as_ref()
            .is_some_and(|r| r.sched == next.name() && r.args == next.args);
    // "not running" and no more: `failure` is the unit's last run,
    // which may have been another configuration, and the Last start
    // line below reports it on its own. A running scheduler that will
    // not come back at boot is the one surprise worth a colour, and a
    // runtime enablement is that surprise with a delay.
    match (running, current.unit.enabled) {
        (true, true) => (format!("{what} (running, {boot})"), Color::White),
        (true, false) => (format!("{what} (running, {boot})"), Color::Yellow),
        (false, _) => (format!("{what} (not running, {boot})"), Color::Yellow),
    }
}

fn draw_status_panel(frame: &mut Frame, app: &App, area: Rect) {
    let mut lines: Vec<Line> = Vec::new();

    match &app.listing {
        Some(listing) => {
            let current = &listing.current;
            let (state, color) = state_line(current);
            lines.push(kv("State", &state, color));
            match &current.running {
                Some(r) if r.args.is_empty() => {
                    lines.push(kv("Running", strip_prefix(&r.sched), Color::White));
                }
                Some(r) => lines.push(kv(
                    "Running",
                    &format!("{} {}", strip_prefix(&r.sched), format_flags(&r.args)),
                    Color::White,
                )),
                None if current.unit.active => lines.push(kv(
                    "Running",
                    "scx.service active, process not readable",
                    Color::Yellow,
                )),
                None => lines.push(kv(
                    "Running",
                    "nothing (scx.service inactive)",
                    Color::White,
                )),
            }
            if let Some(err) = &current.config_error {
                lines.push(kv("Configured", "unknown", Color::Red));
                lines.push(Line::from(Span::styled(
                    format!("  ⚠ {err}"),
                    Style::default().fg(Color::Red),
                )));
            } else {
                let (text, color) = configured_line(current);
                lines.push(kv("Configured", &text, color));
            }
            if let Some(f) = &current.failure {
                lines.push(kv(
                    "Last start",
                    &format!("failed ({}): {}", f.status, f.message),
                    Color::Red,
                ));
            }
        }
        None => {
            let reason = app
                .listing_error
                .as_deref()
                .map_or_else(|| "unknown".to_owned(), |err| format!("unknown; {err}"));
            lines.push(kv("State", &reason, Color::Red));
        }
    }

    lines.push(Line::default());
    draw_kernel_section(app, &mut lines);

    lines.push(Line::default());
    match app.view {
        View::Recommended => {
            if let Some(pick) = app.selected_pick() {
                lines.push(Line::from(vec![
                    Span::styled("Focused: ", Style::default().add_modifier(Modifier::BOLD)),
                    Span::styled(pick.label.clone(), Style::default().fg(Color::Cyan)),
                ]));
                // The id, and for a custom profile the command it
                // stands for: the scheduler with the options.
                lines.push(Line::from(Span::styled(
                    format!(
                        "  {}",
                        match (&pick.sched, pick.id.as_str()) {
                            (_, DEFAULT_ID) => "kernel default".to_owned(),
                            (Some(sched), id) =>
                                format!("{id}: {sched} {}", format_flags(&pick.args))
                                    .trim_end()
                                    .to_owned(),
                            (None, id) => id.to_owned(),
                        }
                    ),
                    Style::default().fg(Color::Gray),
                )));
                if let Some(path) = &pick.path {
                    lines.push(Line::from(Span::styled(
                        format!("  {path}"),
                        Style::default().fg(Color::DarkGray),
                    )));
                }
            }
            if let Some(listing) = &app.listing {
                lines.push(Line::from(Span::styled(
                    format!(
                        "  catalog from {}{}",
                        listing.source.display(),
                        if app.preview_catalog {
                            " (preview: custom profiles do not start from here)"
                        } else {
                            ""
                        }
                    ),
                    Style::default().fg(Color::DarkGray),
                )));
            }
        }
        View::All => {
            if let Some(sched) = app.selected_scheduler() {
                lines.push(Line::from(vec![
                    Span::styled("Focused: ", Style::default().add_modifier(Modifier::BOLD)),
                    Span::styled(
                        strip_prefix(&sched.name).to_owned(),
                        Style::default().fg(Color::Cyan),
                    ),
                    Span::raw(
                        "  (Enter starts it with its own defaults, a with arguments you type)",
                    ),
                ]));
                match sched.tier {
                    Tier::Stable => {}
                    Tier::Experimental => lines.push(Line::from(Span::styled(
                        "  experimental: the catalog does not classify this scheduler as stable",
                        Style::default().fg(Color::Yellow),
                    ))),
                    Tier::Unknown => lines.push(Line::from(Span::styled(
                        "  the catalog says nothing about this scheduler; it is installed, and \
that is all that is known",
                        Style::default().fg(Color::DarkGray),
                    ))),
                }
                lines.push(Line::from(Span::styled(
                    format!("  {}", sched.path),
                    Style::default().fg(Color::DarkGray),
                )));
            }
            lines.push(Line::from(Span::styled(
                "  a scheduler unsuited to the workload can perform worse than the kernel's \
default",
                Style::default().fg(Color::Yellow),
            )));
        }
        View::Logs => {}
    }

    if let Some(input) = &app.args {
        lines.push(Line::default());
        let mut spans = vec![Span::styled(
            "Args: ",
            Style::default().add_modifier(Modifier::BOLD),
        )];
        spans.extend(input_spans(input));
        lines.push(Line::from(spans));
        lines.push(Line::from(Span::styled(
            "  the selected scheduler's own command-line arguments, as to `scxcli run`; Enter \
runs it with them, Esc cancels",
            Style::default().fg(Color::DarkGray),
        )));
    }

    let panel = Paragraph::new(lines)
        .wrap(Wrap { trim: false })
        .block(Block::default().borders(Borders::ALL).title(" Status "));
    frame.render_widget(panel, area);
}

fn draw_logs(frame: &mut Frame, app: &mut App, area: Rect) {
    let height = area.height.saturating_sub(2) as usize;
    app.log_page = height.max(1);

    let total = app.log_lines.len();
    let max_scroll = total.saturating_sub(height);
    if app.log_scroll > max_scroll {
        app.log_scroll = max_scroll;
    }
    let end = total - app.log_scroll;
    let start = end.saturating_sub(height);

    let lines: Vec<Line> = app.log_lines[start..end]
        .iter()
        .map(|line| {
            if line.continuation {
                Line::from(Span::styled(
                    format!("           ↳ {}", line.text),
                    Style::default().fg(Color::DarkGray),
                ))
            } else {
                Line::from(vec![
                    Span::styled(
                        format!("{:8} ", line.time),
                        Style::default().fg(Color::DarkGray),
                    ),
                    Span::styled(line.text.clone(), priority_style(line.priority)),
                ])
            }
        })
        .collect();

    let boot = if app.log_previous_boot {
        "-1 (previous)"
    } else {
        "0 (current)"
    };
    let title = format!(" Logs: {} · boot {} · {} lines ", logs::UNIT, boot, total);

    let panel = Paragraph::new(lines).block(
        Block::default()
            .borders(Borders::ALL)
            .title(title)
            .title_style(Style::default().add_modifier(Modifier::BOLD)),
    );
    frame.render_widget(panel, area);
}

fn draw_kernel_section(app: &App, lines: &mut Vec<Line>) {
    let Some(kernel) = &app.kernel else {
        lines.push(kv(
            "Kernel",
            "sched_ext not available in this kernel",
            Color::DarkGray,
        ));
        return;
    };
    let ops_suffix = kernel
        .ops
        .as_deref()
        .map(|ops| format!(" · ops: {ops}"))
        .unwrap_or_default();
    let color = if kernel.enabled() {
        Color::Green
    } else {
        Color::White
    };
    lines.push(kv(
        "Kernel",
        &format!("sched_ext {}{}", kernel.state, ops_suffix),
        color,
    ));
    if let Some(text) = app.kernel_warning() {
        lines.push(Line::from(Span::styled(
            format!("  ⚠ {text}"),
            Style::default().fg(Color::Yellow),
        )));
    }
}

fn priority_style(priority: u8) -> Style {
    match priority {
        0..=3 => Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
        4 => Style::default().fg(Color::Yellow),
        7 => Style::default().fg(Color::DarkGray),
        _ => Style::default(),
    }
}

fn draw_footer(frame: &mut Frame, app: &App, area: Rect) {
    let [keys_area, message_area] = Layout::new(
        Direction::Vertical,
        [Constraint::Length(1), Constraint::Length(2)],
    )
    .areas(area);

    let key_help = match (app.view, &app.args) {
        (_, Some(_)) => " type scheduler arguments · Enter run with them · Esc cancel",
        (View::Recommended, None) => {
            " ↑/↓ select · Enter start · s stop · A all schedulers · l logs · t monitor · R refresh · q quit"
        }
        (View::All, None) => {
            " ↑/↓ select · Enter start with defaults · a run with args · s stop · l logs · t monitor · R refresh · A/Esc back"
        }
        (View::Logs, None) => {
            " ↑/↓ scroll · PgUp/PgDn page · g/G top/bottom · b boot · R reload · q/Esc back"
        }
    };

    let keys = Line::from(Span::styled(key_help, Style::default().fg(Color::DarkGray)));
    frame.render_widget(Paragraph::new(keys), keys_area);

    if let Some(message) = &app.message {
        let color = if message.is_error {
            Color::Red
        } else {
            Color::Green
        };
        let line = Line::from(Span::styled(
            format!(" {}", message.text),
            Style::default().fg(color),
        ));
        frame.render_widget(
            Paragraph::new(line).wrap(Wrap { trim: false }),
            message_area,
        );
    }
}

fn kv<'a>(key: &'a str, value: &str, value_color: Color) -> Line<'a> {
    Line::from(vec![
        Span::styled(
            format!("{key}: "),
            Style::default().add_modifier(Modifier::BOLD),
        ),
        Span::styled(value.to_owned(), Style::default().fg(value_color)),
    ])
}

fn strip_prefix(sched: &str) -> &str {
    sched.strip_prefix(SCHED_PREFIX).unwrap_or(sched)
}

/// Renders the field content with a reversed-video block as the cursor.
fn input_spans(input: &Input) -> Vec<Span<'static>> {
    let mut before = String::new();
    let mut at = None;
    let mut after = String::new();
    for (i, c) in input.buffer.chars().enumerate() {
        match i.cmp(&input.cursor) {
            std::cmp::Ordering::Less => before.push(c),
            std::cmp::Ordering::Equal => at = Some(c),
            std::cmp::Ordering::Greater => after.push(c),
        }
    }
    let cursor = at.map_or_else(|| " ".to_owned(), |c| c.to_string());
    vec![
        Span::raw(before),
        Span::styled(cursor, Style::default().add_modifier(Modifier::REVERSED)),
        Span::raw(after),
    ]
}

/// Renders a flag vector so token boundaries survive: `shell_words::join`.
fn format_flags(flags: &[String]) -> String {
    shell_words::join(flags)
}

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

    fn installed(name: &str, tier: Tier) -> Installed {
        Installed {
            name: name.into(),
            path: format!("/usr/bin/{name}"),
            recommended: false,
            featured: false,
            tier,
        }
    }

    fn featured(name: &str) -> Installed {
        Installed {
            featured: true,
            ..installed(name, Tier::Stable)
        }
    }

    /// A header goes before the first scheduler of each group and
    /// nowhere else; the rule is left off the first header; the
    /// scheduler items keep the listing's indices.
    #[test]
    fn the_full_list_puts_one_header_before_each_group() {
        let all = [
            featured("scx_cosmos"),
            featured("scx_lavd"),
            installed("scx_rusty", Tier::Stable),
            installed("scx_flow", Tier::Experimental),
            installed("scx_rake", Tier::Unknown),
        ];
        assert_eq!(
            all_list_rows(&all),
            vec![
                AllRow::Header {
                    group: Group::Featured,
                    first: true
                },
                AllRow::Scheduler(0),
                AllRow::Scheduler(1),
                AllRow::Header {
                    group: Group::Stable,
                    first: false
                },
                AllRow::Scheduler(2),
                AllRow::Header {
                    group: Group::Experimental,
                    first: false
                },
                AllRow::Scheduler(3),
                AllRow::Header {
                    group: Group::Unknown,
                    first: false
                },
                AllRow::Scheduler(4),
            ]
        );
        assert!(all_list_rows(&[]).is_empty());
        // A list that starts with an experimental scheduler still has
        // its first header without a rule.
        assert_eq!(
            all_list_rows(&[installed("scx_flow", Tier::Experimental)])[0],
            AllRow::Header {
                group: Group::Experimental,
                first: true
            }
        );
    }

    /// The Configured line answers "will it come back after a reboot"
    /// next to the configuration it applies to, from the unit's
    /// `enabled`, and tells a scheduler that runs now but will not come
    /// back from one that will.
    #[test]
    fn the_configured_line_says_whether_the_unit_starts_at_boot() {
        let current = |scheduler: Option<&str>,
                       active: bool,
                       enabled: bool,
                       running: Option<&str>,
                       next: Option<(&str, bool)>| {
            let json = serde_json::json!({
                "version": 2,
                "scheduler": scheduler,
                "unit": {"active": active, "enabled": enabled, "enabled_runtime": false},
                "running": running.map(|s| serde_json::json!({"sched": s, "args": []})),
                "next": next.map(|(s, o)| serde_json::json!({"sched": s, "args": [], "override": o})),
                "kernel": {"state": "enabled", "ops": scheduler.filter(|s| *s != DEFAULT_ID).map(|s| s.trim_start_matches("scx_"))},
                "failure": null,
            });
            serde_json::from_value::<Current>(json).unwrap()
        };
        let line = |c: &Current| configured_line(c).0;
        let colour = |c: &Current| configured_line(c).1;

        // Running and enabled: the ordinary case after `start ID`.
        let c = current(
            Some("scx_cosmos"),
            true,
            true,
            Some("scx_cosmos"),
            Some(("/usr/bin/scx_cosmos", false)),
        );
        assert_eq!(line(&c), "cosmos (running, starts at boot)");
        assert_eq!(colour(&c), Color::White);
        // Running, but `systemctl disable` was run by hand: it will not
        // come back, which is the surprise worth a colour.
        let c = current(
            Some("scx_cosmos"),
            true,
            false,
            Some("scx_cosmos"),
            Some(("/usr/bin/scx_cosmos", false)),
        );
        assert_eq!(line(&c), "cosmos (running, not at boot)");
        assert_eq!(colour(&c), Color::Yellow);
        // Stopped with `s`: the selection stays and so does the boot.
        let c = current(
            Some(DEFAULT_ID),
            false,
            true,
            None,
            Some(("/usr/bin/scx_cosmos", false)),
        );
        assert_eq!(line(&c), "cosmos (not running, starts at boot)");
        assert_eq!(colour(&c), Color::Yellow);
        // Stopped and disabled by hand.
        let c = current(
            Some(DEFAULT_ID),
            false,
            false,
            None,
            Some(("/usr/bin/scx_cosmos", false)),
        );
        assert_eq!(line(&c), "cosmos (not running, not at boot)");
        assert_eq!(colour(&c), Color::Yellow);
        // An override in effect is said first; the boot still applies,
        // and an override on a disabled unit is exactly "runs now, not
        // after a reboot".
        let c = current(
            Some("scx_lavd"),
            true,
            true,
            Some("scx_lavd"),
            Some(("scx_lavd", true)),
        );
        assert_eq!(line(&c), "lavd (SCX_*_OVERRIDE in effect, starts at boot)");
        assert_eq!(colour(&c), Color::Yellow);
        let c = current(
            Some("scx_lavd"),
            true,
            false,
            Some("scx_lavd"),
            Some(("scx_lavd", true)),
        );
        assert_eq!(line(&c), "lavd (SCX_*_OVERRIDE in effect, not at boot)");
        assert_eq!(colour(&c), Color::Yellow);
        // After `start default`: nothing configured, unit disabled.
        let c = current(Some(DEFAULT_ID), false, false, None, None);
        assert_eq!(line(&c), "nothing (not at boot)");
        assert_eq!(colour(&c), Color::White);
        // `systemctl enable --runtime`: enabled to every tool that looks,
        // and gone after the reboot. Said as what it is, and coloured
        // like "not at boot", which after the reboot it is.
        let mut c = current(
            Some("scx_cosmos"),
            true,
            false,
            Some("scx_cosmos"),
            Some(("/usr/bin/scx_cosmos", false)),
        );
        c.unit.enabled_runtime = true;
        assert_eq!(line(&c), "cosmos (running, enabled until reboot only)");
        assert_eq!(colour(&c), Color::Yellow);
        // The same enablement under an override, and with nothing to
        // run: the line never says "at boot" for a runtime enablement.
        let mut c = current(
            Some("scx_lavd"),
            true,
            false,
            Some("scx_lavd"),
            Some(("scx_lavd", true)),
        );
        c.unit.enabled_runtime = true;
        assert_eq!(
            line(&c),
            "lavd (SCX_*_OVERRIDE in effect, enabled until reboot only)"
        );
        assert_eq!(colour(&c), Color::Yellow);
        let mut c = current(Some(DEFAULT_ID), false, false, None, None);
        c.unit.enabled_runtime = true;
        assert_eq!(
            line(&c),
            "nothing (scx.service enabled until reboot only, nothing to run)"
        );
        assert_eq!(colour(&c), Color::Yellow);
        assert!(!line(&c).contains("at boot"));
        // Older output without the field reads as not runtime-enabled.
        let older: Current = serde_json::from_str(
            r#"{"version":2,"scheduler":"default","unit":{"active":false,"enabled":true},
            "running":null,"next":null,"kernel":{"state":"disabled","ops":null},"failure":null}"#,
        )
        .unwrap();
        assert!(!older.unit.enabled_runtime);
        // A cleared file under an enabled unit: it starts at boot, runs
        // nothing and exits.
        let c = current(Some(DEFAULT_ID), false, true, None, None);
        assert_eq!(
            line(&c),
            "nothing (scx.service starts at boot, nothing to run)"
        );
        assert_eq!(colour(&c), Color::Yellow);
    }

    #[test]
    fn flags_format_round_trips() {
        let flags = ["--name", "foo bar", "", "a'b"]
            .map(str::to_string)
            .to_vec();
        assert_eq!(shell_words::split(&format_flags(&flags)), Ok(flags));
    }
}