fader_master/tui/examples/doc_screenshots.rs

331 lines
11 KiB
Rust

//! Regenerates the deterministic TUI screenshots embedded in the README.
use std::{fs, io, path::PathBuf};
use ratatui::{
Terminal,
backend::TestBackend,
buffer::Buffer,
style::{Color, Modifier},
};
use tui::{
ConfigurationSnapshot, ConfiguredApplication, ConfiguredFader, ConfiguredGroup, FaderDensity,
GroupVolumeMode, LiveTui, MidiDevice, MixerClient, MixerItem, MixerLayoutEntry, MixerObjectId,
MixerObjectKind, MixerOrientation, MixerSnapshot, PickupStatus, ThemeName,
};
const CELL_WIDTH: u16 = 9;
const CELL_HEIGHT: u16 = 18;
#[derive(Clone)]
struct ScreenshotClient(MixerSnapshot);
impl MixerClient for ScreenshotClient {
fn snapshot(&mut self) -> io::Result<MixerSnapshot> {
Ok(self.0.clone())
}
fn set_volume(
&mut self,
_id: MixerObjectId,
_gain: f64,
_expected_revision: u64,
) -> io::Result<MixerSnapshot> {
Ok(self.0.clone())
}
fn toggle_mute(
&mut self,
_id: MixerObjectId,
_expected_revision: u64,
) -> io::Result<MixerSnapshot> {
Ok(self.0.clone())
}
}
fn main() -> io::Result<()> {
let output = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../docs/images");
fs::create_dir_all(&output)?;
render(
MixerOrientation::Horizontal,
140,
26,
output.join("mixer-horizontal.svg"),
)?;
render(
MixerOrientation::Vertical,
104,
38,
output.join("mixer-vertical.svg"),
)
}
fn render(
orientation: MixerOrientation,
width: u16,
height: u16,
output: PathBuf,
) -> io::Result<()> {
let app = LiveTui::new(ScreenshotClient(snapshot(orientation)))?;
let mut terminal = Terminal::new(TestBackend::new(width, height))?;
terminal.draw(|frame| frame.render_widget(&app, frame.area()))?;
fs::write(output, buffer_svg(terminal.backend().buffer()))
}
fn snapshot(mixer_orientation: MixerOrientation) -> MixerSnapshot {
let targets = [
(MixerObjectKind::Application, "music", "Music"),
(MixerObjectKind::Application, "browser", "Browser"),
(MixerObjectKind::Group, "media", "Media group"),
(MixerObjectKind::Output, "default", "Master output"),
];
let items = targets
.into_iter()
.enumerate()
.map(|(index, (kind, id, label))| MixerItem {
id: MixerObjectId {
kind,
id: id.to_owned(),
},
label: label.to_owned(),
detail: match kind {
MixerObjectKind::Application => "2 streams",
MixerObjectKind::Group => "Music + Browser",
MixerObjectKind::Output => "Built-in Audio Analog Stereo",
}
.to_owned(),
gain: Some([0.78, 0.46, 0.62, 0.88][index]),
gain_mixed: kind == MixerObjectKind::Group,
muted: Some(index == 1),
mute_mixed: kind == MixerObjectKind::Group,
pending: false,
pickup: Some(match index {
0 | 3 => PickupStatus::Tracking,
1 => PickupStatus::Waiting,
_ => PickupStatus::Mixed,
}),
writable: true,
error: None,
})
.collect();
let faders = targets
.into_iter()
.map(|(kind, id, _)| ConfiguredFader {
id: format!("{id}-fader"),
target: MixerObjectId {
kind,
id: id.to_owned(),
},
pickup: true,
pickup_tolerance: 0.02,
})
.collect();
MixerSnapshot {
revision: 42,
backend: "pulse · PipeWire".to_owned(),
status: "ready".to_owned(),
error: None,
items,
devices: vec![MidiDevice {
id: "apc-mini".to_owned(),
label: "APC MINI".to_owned(),
status: "connected".to_owned(),
backend_id: Some("24:0".to_owned()),
error: None,
}],
discovered_midi_ports: Vec::new(),
configuration: ConfigurationSnapshot {
revision: 7,
dirty: false,
applied_revision: 7,
selection_saved: true,
learning: None,
error: None,
profile_id: "desktop".to_owned(),
available_profiles: vec!["desktop".to_owned()],
mixer_orientation,
status_display: tui::StatusDisplayMode::Detailed,
default_controller: Some("apc-mini".to_owned()),
theme: ThemeName::CatppuccinMocha,
applications: vec![
ConfiguredApplication {
id: "music".to_owned(),
label: "Music".to_owned(),
selectors: Vec::new(),
},
ConfiguredApplication {
id: "browser".to_owned(),
label: "Browser".to_owned(),
selectors: Vec::new(),
},
],
groups: vec![ConfiguredGroup {
id: "media".to_owned(),
label: "Media group".to_owned(),
members: vec!["music".to_owned(), "browser".to_owned()],
volume_mode: GroupVolumeMode::Absolute,
}],
faders,
mixer_layout: vec![
MixerLayoutEntry::Separator {
id: "applications".to_owned(),
label: "Applications".to_owned(),
size: tui::SeparatorSize::Standard,
decoration: tui::SeparatorDecoration::Line,
},
layout_fader(
"music",
horizontal_density(mixer_orientation, FaderDensity::Standard),
),
layout_fader(
"browser",
horizontal_density(mixer_orientation, FaderDensity::Slim),
),
MixerLayoutEntry::Separator {
id: "groups".to_owned(),
label: "Groups".to_owned(),
size: tui::SeparatorSize::Standard,
decoration: tui::SeparatorDecoration::Line,
},
layout_fader("media", FaderDensity::Thick),
MixerLayoutEntry::Separator {
id: "outputs".to_owned(),
label: "Outputs".to_owned(),
size: tui::SeparatorSize::Standard,
decoration: tui::SeparatorDecoration::Line,
},
layout_fader(
"default",
horizontal_density(mixer_orientation, FaderDensity::Standard),
),
],
bindings: Vec::new(),
},
}
}
const fn horizontal_density(
orientation: MixerOrientation,
vertical_density: FaderDensity,
) -> FaderDensity {
match orientation {
MixerOrientation::Horizontal => FaderDensity::Thick,
MixerOrientation::Vertical => vertical_density,
}
}
fn layout_fader(id: &str, density: FaderDensity) -> MixerLayoutEntry {
MixerLayoutEntry::Fader {
fader: format!("{id}-fader"),
hidden: false,
density,
}
}
fn buffer_svg(buffer: &Buffer) -> String {
let width = buffer.area.width * CELL_WIDTH;
let height = buffer.area.height * CELL_HEIGHT;
let mut svg = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}\" height=\"{height}\" viewBox=\"0 0 {width} {height}\" role=\"img\" aria-label=\"fader_master terminal interface\">\n<rect width=\"100%\" height=\"100%\" fill=\"#1e1e2e\"/>\n<g font-family=\"DejaVu Sans Mono, monospace\" font-size=\"14\" dominant-baseline=\"text-before-edge\">\n"
);
for y in 0..buffer.area.height {
let mut start = 0;
while start < buffer.area.width {
let background = buffer[(start, y)].bg;
let mut end = start + 1;
while end < buffer.area.width && buffer[(end, y)].bg == background {
end += 1;
}
if background != Color::Reset {
svg.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"{}\"/>\n",
start * CELL_WIDTH,
y * CELL_HEIGHT,
(end - start) * CELL_WIDTH,
CELL_HEIGHT,
color(background, "#1e1e2e")
));
}
start = end;
}
let mut start = 0;
while start < buffer.area.width {
let cell = &buffer[(start, y)];
let mut end = start + 1;
let mut text = cell.symbol().to_owned();
while end < buffer.area.width {
let next = &buffer[(end, y)];
if next.fg != cell.fg || next.modifier != cell.modifier {
break;
}
text.push_str(next.symbol());
end += 1;
}
if !text.trim().is_empty() {
let weight = if cell.modifier.contains(Modifier::BOLD) {
" font-weight=\"bold\""
} else {
""
};
svg.push_str(&format!(
"<text x=\"{}\" y=\"{}\" fill=\"{}\" xml:space=\"preserve\"{}>{}</text>\n",
start * CELL_WIDTH,
y * CELL_HEIGHT + 1,
color(cell.fg, "#cdd6f4"),
weight,
escape_xml(&text)
));
}
start = end;
}
}
svg.push_str("</g>\n</svg>\n");
svg
}
fn color(color: Color, reset: &str) -> String {
match color {
Color::Reset => reset.to_owned(),
Color::Black => "#11111b".to_owned(),
Color::Red => "#f38ba8".to_owned(),
Color::Green => "#a6e3a1".to_owned(),
Color::Yellow => "#f9e2af".to_owned(),
Color::Blue => "#89b4fa".to_owned(),
Color::Magenta => "#cba6f7".to_owned(),
Color::Cyan => "#89dceb".to_owned(),
Color::Gray => "#bac2de".to_owned(),
Color::DarkGray => "#585b70".to_owned(),
Color::LightRed => "#eba0ac".to_owned(),
Color::LightGreen => "#94e2d5".to_owned(),
Color::LightYellow => "#fab387".to_owned(),
Color::LightBlue => "#74c7ec".to_owned(),
Color::LightMagenta => "#f5c2e7".to_owned(),
Color::LightCyan => "#b4befe".to_owned(),
Color::White => "#cdd6f4".to_owned(),
Color::Rgb(red, green, blue) => format!("#{red:02x}{green:02x}{blue:02x}"),
Color::Indexed(index) => indexed_color(index).to_owned(),
}
}
const fn indexed_color(index: u8) -> &'static str {
match index {
0..=7 => "#6c7086",
8..=15 => "#cdd6f4",
16..=51 => "#89b4fa",
52..=87 => "#f38ba8",
88..=123 => "#a6e3a1",
124..=159 => "#f9e2af",
160..=195 => "#cba6f7",
196..=231 => "#89dceb",
_ => "#bac2de",
}
}
fn escape_xml(value: &str) -> String {
value
.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
}