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);
}
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())
}
}
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),
}
}
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
};
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);
}
#[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,
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AllRow {
Header { group: Group, first: bool },
Scheduler(usize),
}
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) {
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,
),
}
}
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) = ¤t.next else {
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,
);
}
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);
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 ¤t.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) = ¤t.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) = ¤t.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)),
]));
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)
}
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),
]
}
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)
}
}
#[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());
assert_eq!(
all_list_rows(&[installed("scx_flow", Tier::Experimental)])[0],
AllRow::Header {
group: Group::Experimental,
first: true
}
);
}
#[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;
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);
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);
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);
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);
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);
let c = current(Some(DEFAULT_ID), false, false, None, None);
assert_eq!(line(&c), "nothing (not at boot)");
assert_eq!(colour(&c), Color::White);
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);
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"));
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);
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));
}
}