Skip to main content

lx_cli/
theme.rs

1use serde::Deserialize;
2use std::collections::HashMap;
3use std::fmt::Write as _;
4use std::hash::{BuildHasherDefault, Hasher};
5use std::io::IsTerminal;
6use std::sync::OnceLock;
7use toml::{Table, Value};
8
9const RESET: &str = "\x1b[0m";
10
11/// Terminal font attributes shared by every semantic style.
12#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq)]
13#[serde(rename_all = "snake_case")]
14pub enum FontStyle {
15    Bold,
16    #[serde(alias = "dim")]
17    Dimmed,
18    Italic,
19    Underline,
20    Strikethrough,
21    Reversed,
22}
23
24impl FontStyle {
25    /// Escape sequences list attributes in this order, whatever order they were configured in.
26    const EMISSION_ORDER: [Self; 6] = [
27        Self::Bold,
28        Self::Dimmed,
29        Self::Underline,
30        Self::Reversed,
31        Self::Italic,
32        Self::Strikethrough,
33    ];
34
35    fn sgr_code(self) -> u8 {
36        match self {
37            Self::Bold => 1,
38            Self::Dimmed => 2,
39            Self::Italic => 3,
40            Self::Underline => 4,
41            Self::Reversed => 7,
42            Self::Strikethrough => 9,
43        }
44    }
45
46    fn bit(self) -> u8 {
47        1 << self as u8
48    }
49}
50
51/// A set of font attributes, kept as bits so styles stay `Copy`.
52#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
53pub struct FontStyles(u8);
54
55impl FontStyles {
56    pub fn from_slice(styles: &[FontStyle]) -> Self {
57        Self(styles.iter().fold(0, |bits, style| bits | style.bit()))
58    }
59
60    pub fn contains(self, style: FontStyle) -> bool {
61        self.0 & style.bit() != 0
62    }
63
64    fn iter(self) -> impl Iterator<Item = FontStyle> {
65        FontStyle::EMISSION_ORDER
66            .into_iter()
67            .filter(move |style| self.contains(*style))
68    }
69}
70
71/// A terminal colour as configured.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Color {
74    /// One of the 16 standard colours: 0–7 normal, 8–15 bright.
75    Ansi(u8),
76    TrueColor {
77        r: u8,
78        g: u8,
79        b: u8,
80    },
81}
82
83impl Color {
84    /// Approximate RGB values of the standard colours, used to downgrade RGB colours.
85    const ANSI_RGB: [(u8, u8, u8); 16] = [
86        (0, 0, 0),
87        (205, 0, 0),
88        (0, 205, 0),
89        (205, 205, 0),
90        (0, 0, 238),
91        (205, 0, 205),
92        (0, 205, 205),
93        (229, 229, 229),
94        (127, 127, 127),
95        (255, 0, 0),
96        (0, 255, 0),
97        (255, 255, 0),
98        (92, 92, 255),
99        (255, 0, 255),
100        (0, 255, 255),
101        (255, 255, 255),
102    ];
103
104    /// Writes the SGR parameter, using `base` 30 for foregrounds or 40 for backgrounds.
105    fn write_sgr(self, output: &mut String, base: u8, truecolor: bool) {
106        match self {
107            Self::Ansi(index) if index < 8 => push_number(output, base + index),
108            Self::Ansi(index) => push_number(output, base + 60 + index - 8),
109            Self::TrueColor { r, g, b } if truecolor => {
110                let _ = write!(output, "{};2;{r};{g};{b}", base + 8);
111            }
112            Self::TrueColor { .. } => self.nearest_ansi().write_sgr(output, base, truecolor),
113        }
114    }
115
116    fn nearest_ansi(self) -> Self {
117        let Self::TrueColor { r, g, b } = self else {
118            return self;
119        };
120        let distance = |&(ar, ag, ab): &(u8, u8, u8)| {
121            u32::from(ar.abs_diff(r)).pow(2)
122                + u32::from(ag.abs_diff(g)).pow(2)
123                + u32::from(ab.abs_diff(b)).pow(2)
124        };
125        // `min_by_key` keeps the first of equally close colours.
126        let index = (0..16u8)
127            .min_by_key(|&index| distance(&Self::ANSI_RGB[usize::from(index)]))
128            .unwrap_or(0);
129        Self::Ansi(index)
130    }
131}
132
133fn push_number(output: &mut String, number: u8) {
134    let _ = write!(output, "{number}");
135}
136
137/// Whether and how to colour output, read from the environment once per run.
138struct ColorSupport {
139    enabled: bool,
140    truecolor: bool,
141}
142
143impl ColorSupport {
144    /// `CLICOLOR_FORCE` wins, then `NO_COLOR`, then `CLICOLOR` combined with a terminal check.
145    fn get() -> &'static Self {
146        static SUPPORT: OnceLock<ColorSupport> = OnceLock::new();
147        SUPPORT.get_or_init(|| {
148            let set = |name| std::env::var(name).ok().map(|value| value != "0");
149            let enabled = if set("CLICOLOR_FORCE") == Some(true) {
150                true
151            } else if std::env::var_os("NO_COLOR").is_some() {
152                false
153            } else {
154                set("CLICOLOR").unwrap_or(true) && std::io::stdout().is_terminal()
155            };
156            let truecolor = matches!(
157                std::env::var("COLORTERM").as_deref(),
158                Ok("truecolor" | "24bit")
159            );
160            Self { enabled, truecolor }
161        })
162    }
163}
164
165/// A validated terminal style. Omitted overlay properties inherit their base.
166#[derive(Debug, Clone, Copy, Default)]
167pub struct Style {
168    pub foreground: Option<Color>,
169    pub background: Option<Color>,
170    pub attributes: FontStyles,
171    foreground_present: bool,
172    background_present: bool,
173    attributes_present: bool,
174    inline_attributes: bool,
175}
176
177impl Style {
178    pub fn paint(&self, text: &str) -> String {
179        let mut output = String::new();
180        self.paint_into(&mut output, text);
181        output
182    }
183
184    /// Appends `text` wrapped in this style's escape sequences.
185    pub fn paint_into(&self, output: &mut String, text: &str) {
186        if text.is_empty() {
187            return;
188        }
189        let support = ColorSupport::get();
190        if !support.enabled
191            || (self.foreground.is_none() && self.background.is_none() && self.attributes.0 == 0)
192        {
193            output.push_str(text);
194            return;
195        }
196        let start = output.len();
197        output.push_str("\x1b[");
198        let mut separator = false;
199        for attribute in self.attributes.iter() {
200            if separator {
201                output.push(';');
202            }
203            push_number(output, attribute.sgr_code());
204            separator = true;
205        }
206        for (color, base) in [(self.background, 40), (self.foreground, 30)] {
207            if let Some(color) = color {
208                if separator {
209                    output.push(';');
210                }
211                color.write_sgr(output, base, support.truecolor);
212                separator = true;
213            }
214        }
215        output.push('m');
216        if text.contains(RESET) {
217            // Restore this style after any reset embedded in the text.
218            let prefix = output[start..].to_string();
219            output.push_str(&text.replace(RESET, &format!("{RESET}{prefix}")));
220        } else {
221            output.push_str(text);
222        }
223        output.push_str(RESET);
224    }
225}
226
227/// FNV-1a. Role names are short and come from lx and its config, so SipHash's
228/// resistance to crafted keys only costs time on every styled cell.
229struct RoleHasher(u64);
230
231impl Default for RoleHasher {
232    fn default() -> Self {
233        Self(0xcbf2_9ce4_8422_2325)
234    }
235}
236
237impl Hasher for RoleHasher {
238    fn finish(&self) -> u64 {
239        self.0
240    }
241
242    fn write(&mut self, bytes: &[u8]) {
243        for &byte in bytes {
244            self.0 = (self.0 ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3);
245        }
246    }
247}
248
249type RoleMap<V> = HashMap<String, V, BuildHasherDefault<RoleHasher>>;
250
251/// Resolved semantic styles; raw config keys never reach the formatters.
252#[derive(Debug, Clone)]
253pub struct Theme {
254    styles: RoleMap<Style>,
255    legacy_field_attributes: RoleMap<FontStyles>,
256    plain: Style,
257}
258
259impl Default for Theme {
260    fn default() -> Self {
261        let document: Table = toml::from_str(include_str!("../themes/default.toml"))
262            .expect("built-in theme must be valid TOML");
263        let mut theme = Self {
264            styles: RoleMap::default(),
265            legacy_field_attributes: RoleMap::default(),
266            plain: Style::default(),
267        };
268        let mut diagnostics = Vec::new();
269        theme.apply_table(
270            document["style"].as_table().expect("built-in style table"),
271            "",
272            false,
273            true,
274            &mut diagnostics,
275        );
276        assert!(
277            diagnostics.is_empty(),
278            "invalid built-in theme: {diagnostics:?}"
279        );
280        theme
281    }
282}
283
284impl Theme {
285    pub fn style(&self, role: &str) -> &Style {
286        self.styles.get(role).unwrap_or(&self.plain)
287    }
288
289    pub fn overlay(&self, base: &Style, role: &str) -> Style {
290        let overlay = self.style(role);
291        let mut result = *base;
292        if overlay.foreground_present {
293            result.foreground = overlay.foreground;
294            result.foreground_present = true;
295        }
296        if overlay.background_present {
297            result.background = overlay.background;
298            result.background_present = true;
299        }
300        if overlay.attributes_present {
301            result.attributes = overlay.attributes;
302            result.attributes_present = true;
303            result.inline_attributes = overlay.inline_attributes;
304        }
305        result
306    }
307
308    pub fn field_attributes_override(&self, field: &str) -> Option<FontStyles> {
309        self.legacy_field_attributes.get(field).copied()
310    }
311
312    /// Legacy whole-column attributes apply only in long output; inline styles win.
313    pub fn field_style(&self, base: &Style, field: &str) -> Style {
314        let mut result = *base;
315        if !base.inline_attributes {
316            if let Some(attributes) = self.field_attributes_override(field) {
317                result.attributes = attributes;
318            }
319        }
320        result
321    }
322
323    pub(crate) fn apply_document(
324        &mut self,
325        document: &Table,
326        inline: bool,
327        diagnostics: &mut Vec<String>,
328    ) {
329        if let Some(value) = document.get("style") {
330            if let Some(styles) = value.as_table() {
331                self.apply_table(styles, "", inline, false, diagnostics);
332            } else {
333                diagnostics.push("style must be a table".into());
334            }
335        }
336    }
337
338    fn apply_table(
339        &mut self,
340        table: &Table,
341        prefix: &str,
342        inline: bool,
343        builtin: bool,
344        diagnostics: &mut Vec<String>,
345    ) {
346        for (name, value) in table {
347            let role = if prefix.is_empty() {
348                name.clone()
349            } else {
350                format!("{prefix}.{name}")
351            };
352            let Some(properties) = value.as_table() else {
353                diagnostics.push(format!("style.{role} must be a style table"));
354                continue;
355            };
356            let is_style = self.styles.contains_key(&role)
357                || builtin
358                    && properties.keys().any(|key| {
359                        matches!(key.as_str(), "foreground" | "background" | "attributes")
360                    });
361            if is_style {
362                let style = self.styles.entry(role.clone()).or_default();
363                update_style(style, properties, inline, &role, diagnostics);
364            } else if builtin
365                || self
366                    .styles
367                    .keys()
368                    .any(|known| known.starts_with(&format!("{role}.")))
369            {
370                self.apply_table(properties, &role, inline, builtin, diagnostics);
371            } else {
372                diagnostics.push(format!("unknown style role: style.{role}"));
373            }
374        }
375    }
376
377    pub(crate) fn apply_legacy(&mut self, document: &Table, diagnostics: &mut Vec<String>) {
378        if let Some(colors) = document.get("colors").and_then(Value::as_table) {
379            for (name, value) in colors {
380                if name == "git" {
381                    if let Some(git) = value.as_table() {
382                        for (status, color) in git {
383                            self.legacy_property(
384                                &format!("git.{status}"),
385                                "foreground",
386                                color,
387                                diagnostics,
388                            );
389                        }
390                    }
391                } else {
392                    self.legacy_filename_property(name, "foreground", value, diagnostics);
393                }
394            }
395        }
396        if let Some(styles) = document.get("styles").and_then(Value::as_table) {
397            for (name, attributes) in styles {
398                self.legacy_filename_property(name, "attributes", attributes, diagnostics);
399            }
400        }
401        if let Some(colors) = document
402            .get("icons")
403            .and_then(|icons| icons.get("colors"))
404            .and_then(Value::as_table)
405        {
406            for (name, color) in colors {
407                self.legacy_property(&format!("icons.{name}"), "foreground", color, diagnostics);
408            }
409        }
410        let Some(display) = document.get("display").and_then(Value::as_table) else {
411            return;
412        };
413        if let Some(color) = display.get("long_format_title_color") {
414            self.legacy_property("header", "foreground", color, diagnostics);
415        }
416        if let Some(attributes) = display.get("long_format_title_style") {
417            self.legacy_property("header", "attributes", attributes, diagnostics);
418        }
419        if let Some(fields) = display.get("long_format_styles").and_then(Value::as_table) {
420            for (field, value) in fields {
421                if !matches!(
422                    field.as_str(),
423                    "filename"
424                        | "permissions"
425                        | "nlink"
426                        | "owner"
427                        | "group"
428                        | "size"
429                        | "modified"
430                        | "git"
431                ) {
432                    diagnostics.push(format!("unknown long format style field: {field}"));
433                    continue;
434                }
435                match value.clone().try_into::<Vec<FontStyle>>() {
436                    Ok(attributes) => {
437                        self.legacy_field_attributes
438                            .insert(field.clone(), FontStyles::from_slice(&attributes));
439                    }
440                    Err(error) => {
441                        diagnostics.push(format!("display.long_format_styles.{field}: {error}"))
442                    }
443                }
444            }
445        }
446    }
447
448    fn legacy_filename_property(
449        &mut self,
450        name: &str,
451        property: &str,
452        value: &Value,
453        diagnostics: &mut Vec<String>,
454    ) {
455        let mut roles = vec![filename_role(name)];
456        if name == "regular" {
457            roles.extend(
458                self.styles
459                    .keys()
460                    .filter(|role| role.starts_with("file_type."))
461                    .cloned(),
462            );
463        } else if name == "symlink" {
464            roles.push("symlink_path".to_string());
465        }
466        for role in roles {
467            self.legacy_property(&role, property, value, diagnostics);
468        }
469    }
470
471    fn legacy_property(
472        &mut self,
473        role: &str,
474        property: &str,
475        value: &Value,
476        diagnostics: &mut Vec<String>,
477    ) {
478        let Some(style) = self.styles.get_mut(role) else {
479            diagnostics.push(format!("unknown legacy style role: {role}"));
480            return;
481        };
482        let properties = Table::from_iter([(property.to_string(), value.clone())]);
483        update_style(style, &properties, false, role, diagnostics);
484    }
485}
486
487fn filename_role(name: &str) -> String {
488    if name == "hidden" {
489        "filenames.hidden".to_string()
490    } else {
491        format!("filekinds.{name}")
492    }
493}
494
495fn update_style(
496    style: &mut Style,
497    properties: &Table,
498    inline: bool,
499    role: &str,
500    diagnostics: &mut Vec<String>,
501) {
502    for (property, value) in properties {
503        match property.as_str() {
504            "foreground" | "background" => {
505                let parsed = value
506                    .as_str()
507                    .ok_or("must be a colour string")
508                    .and_then(parse_color);
509                match parsed {
510                    Ok(color) if property == "foreground" => {
511                        style.foreground = color;
512                        style.foreground_present = true;
513                    }
514                    Ok(color) => {
515                        style.background = color;
516                        style.background_present = true;
517                    }
518                    Err(error) => diagnostics.push(format!("style.{role}.{property}: {error}")),
519                }
520            }
521            "attributes" => match value.clone().try_into::<Vec<FontStyle>>() {
522                Ok(attributes) => {
523                    style.attributes = FontStyles::from_slice(&attributes);
524                    style.attributes_present = true;
525                    style.inline_attributes = inline;
526                }
527                Err(error) => diagnostics.push(format!("style.{role}.attributes: {error}")),
528            },
529            _ => diagnostics.push(format!("unknown style property: style.{role}.{property}")),
530        }
531    }
532}
533
534fn parse_color(value: &str) -> Result<Option<Color>, &'static str> {
535    let value = value.to_ascii_lowercase();
536    let named = match value.as_str() {
537        "default" => return Ok(None),
538        "black" => Some(Color::Ansi(0)),
539        "red" => Some(Color::Ansi(1)),
540        "green" => Some(Color::Ansi(2)),
541        "yellow" => Some(Color::Ansi(3)),
542        "blue" => Some(Color::Ansi(4)),
543        "magenta" | "purple" => Some(Color::Ansi(5)),
544        "cyan" => Some(Color::Ansi(6)),
545        "white" => Some(Color::Ansi(7)),
546        "bright_black" => Some(Color::Ansi(8)),
547        "bright_red" => Some(Color::Ansi(9)),
548        "bright_green" => Some(Color::Ansi(10)),
549        "bright_yellow" => Some(Color::Ansi(11)),
550        "bright_blue" => Some(Color::Ansi(12)),
551        "bright_magenta" | "bright_purple" => Some(Color::Ansi(13)),
552        "bright_cyan" => Some(Color::Ansi(14)),
553        "bright_white" => Some(Color::Ansi(15)),
554        _ => None,
555    };
556    if named.is_some() {
557        return Ok(named);
558    }
559    let digits = value.strip_prefix('#').unwrap_or(&value);
560    let digits = if value.starts_with('#') && digits.len() == 3 {
561        digits
562            .chars()
563            .flat_map(|digit| [digit, digit])
564            .collect::<String>()
565    } else {
566        digits.to_string()
567    };
568    if digits.len() != 6 || !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) {
569        return Err("expected a named terminal colour, default, #RGB or #RRGGBB");
570    }
571    let number = u32::from_str_radix(&digits, 16).map_err(|_| "invalid RGB colour")?;
572    Ok(Some(Color::TrueColor {
573        r: ((number >> 16) & 0xff) as u8,
574        g: ((number >> 8) & 0xff) as u8,
575        b: (number & 0xff) as u8,
576    }))
577}