Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

20.6 KB
Raw Blame
//! Vencord / BetterDiscord theme translator.
//!
//! Discord themes are CSS, and most of what they change is a set of CSS custom
//! properties (`--background-primary`, `--text-normal`, …). RustCord has no
//! CSS engine, but it can read those variables, resolve `var()`, `calc()`,
//! `hsl()` and friends, and map the results onto its native palette. Layout
//! rules (sizes, fonts, backgrounds images) can't be translated.

use std::collections::{BTreeMap, HashMap};

pub type Rgba = [u8; 4];

/// (slot, human label, CSS variables in priority order)
pub const SLOTS: &[(&str, &str, &[&str])] = &[
    ("bg_primary", "Chat background", &["--background-primary", "--background-base-lower", "--bg-base-primary"]),
    ("bg_secondary", "Channel list", &["--background-secondary", "--background-base-lowest", "--bg-base-secondary"]),
    ("bg_secondary_alt", "User panel", &["--background-secondary-alt", "--bg-base-tertiary"]),
    ("bg_tertiary", "Server list", &["--background-tertiary", "--background-base-lowest", "--bg-base-tertiary"]),
    ("bg_floating", "Menus & popups", &["--background-floating", "--background-surface-high", "--bg-surface-overlay"]),
    ("bg_hover", "Hovered item", &["--background-modifier-hover", "--bg-mod-faint"]),
    ("bg_selected", "Selected item", &["--background-modifier-selected", "--bg-mod-strong"]),
    ("bg_message_hover", "Hovered message", &["--background-message-hover"]),
    ("bg_mentioned", "Mentioned message", &["--background-mentioned"]),
    ("input_bg", "Message box", &["--channeltextarea-background", "--input-background", "--bg-base-secondary"]),
    ("text_normal", "Text", &["--text-normal", "--text-default"]),
    ("text_muted", "Muted text", &["--text-muted"]),
    ("header_primary", "Headings", &["--header-primary", "--text-strong"]),
    ("header_secondary", "Subheadings", &["--header-secondary", "--text-subtle"]),
    ("interactive_normal", "Channel names", &["--interactive-normal", "--interactive-icon-default"]),
    ("interactive_hover", "Hovered channel", &["--interactive-hover", "--interactive-icon-hover"]),
    ("interactive_active", "Selected channel", &["--interactive-active", "--interactive-icon-active"]),
    ("interactive_muted", "Muted channel", &["--interactive-muted"]),
    ("text_link", "Links", &["--text-link"]),
    ("accent", "Accent", &["--brand-experiment", "--brand-500", "--bg-brand", "--brand-experiment-500"]),
    ("danger", "Danger", &["--status-danger", "--text-danger", "--red-400"]),
];

#[derive(Clone, Debug, Default)]
pub struct Palette(pub BTreeMap<&'static str, Rgba>);

impl Palette {
    pub fn get(&self, slot: &str) -> Option<Rgba> {
        self.0.get(slot).copied()
    }
}

#[derive(Clone, Debug)]
pub struct Mapped {
    pub slot: &'static str,
    pub label: &'static str,
    pub variable: String,
    pub color: Rgba,
}

#[derive(Clone, Debug, Default)]
pub struct Translation {
    pub palette: Palette,
    pub mapped: Vec<Mapped>,
    pub variables_found: usize,
    pub warnings: Vec<String>,
}

/// URLs from `@import` rules, for the client to fetch and prepend.
pub fn extract_imports(css: &str) -> Vec<String> {
    let css = strip_comments(css);
    let mut out = Vec::new();
    for part in css.split("@import").skip(1) {
        let part = part.trim_start();
        let rest = part.strip_prefix("url(").unwrap_or(part).trim_start();
        let quote = rest.chars().next();
        let url: String = match quote {
            Some(q @ ('"' | '\'')) => rest[1..].chars().take_while(|c| *c != q).collect(),
            _ => rest.chars().take_while(|c| !matches!(c, ')' | ';' | ' ')).collect(),
        };
        // https only: a plain-http theme could be swapped by anyone on the network.
        if url.starts_with("https://") {
            out.push(url);
        }
    }
    out
}

pub fn translate(css: &str) -> Translation {
    let css = strip_comments(css);
    let vars = collect_vars(&css);
    let mut t = Translation { variables_found: vars.len(), ..Default::default() };

    for (slot, label, candidates) in SLOTS {
        for var in *candidates {
            let Some(raw) = vars.get(*var) else { continue };
            let resolved = resolve(raw, &vars, 0);
            match parse_color(&resolved) {
                Some(color) => {
                    t.palette.0.insert(slot, color);
                    t.mapped.push(Mapped { slot, label, variable: var.to_string(), color });
                    break;
                }
                None => t.warnings.push(format!("{var}: couldn't read \"{}\" as a color", raw.trim())),
            }
        }
    }
    t
}

fn strip_comments(css: &str) -> String {
    let mut out = String::with_capacity(css.len());
    let mut rest = css;
    while let Some(start) = rest.find("/*") {
        out.push_str(&rest[..start]);
        match rest[start + 2..].find("*/") {
            Some(end) => rest = &rest[start + 2 + end + 2..],
            None => return out,
        }
    }
    out.push_str(rest);
    out
}

fn is_root_like(selector: &str) -> bool {
    let s = selector.to_ascii_lowercase();
    let dark_or_global = [":root", "html", "body", ".theme-dark", ".theme-darker", ".theme-midnight", ".visual-refresh"]
        .iter()
        .any(|k| s.contains(k));
    let light_only = s.contains(".theme-light") && !s.contains(".theme-dark");
    dark_or_global && !light_only
}

/// Custom properties declared in root-like rule blocks. Later wins.
fn collect_vars(css: &str) -> HashMap<String, String> {
    let mut vars = HashMap::new();
    let bytes = css.as_bytes();
    let mut i = 0;
    let mut selector_start = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'{' => {
                // Find matching '}' for an innermost block (no nested '{').
                let body_start = i + 1;
                let mut j = body_start;
                while j < bytes.len() && bytes[j] != b'}' && bytes[j] != b'{' {
                    j += 1;
                }
                if j < bytes.len() && bytes[j] == b'}' {
                    let selector = &css[selector_start..i];
                    if is_root_like(selector) {
                        for decl in css[body_start..j].split(';') {
                            if let Some((name, value)) = decl.split_once(':') {
                                let name = name.trim();
                                if name.starts_with("--") {
                                    let value = value.trim().trim_end_matches("!important").trim();
                                    vars.insert(name.to_string(), value.to_string());
                                }
                            }
                        }
                    }
                    i = j + 1;
                    selector_start = i;
                    continue;
                }
                // A block containing nested blocks (@media etc): descend.
                selector_start = i + 1;
            }
            b'}' => selector_start = i + 1,
            _ => {}
        }
        i += 1;
    }
    vars
}

/// Index of the ')' matching the '(' just before `start`.
fn matching_paren(s: &str, start: usize) -> Option<usize> {
    let mut depth = 1;
    for (i, c) in s[start..].char_indices() {
        match c {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(start + i);
                }
            }
            _ => {}
        }
    }
    None
}

/// A resolved value longer than this is cut off: a theme whose variables
/// expand into each other many times over can't eat the memory.
const MAX_RESOLVED: usize = 4096;

/// Most `var()`s one value may substitute, counting those inside the
/// variables it uses: variables that fan out into each other (ten uses of the
/// next, twelve deep) would otherwise take hours while staying short.
const MAX_SUBSTITUTIONS: u32 = 2000;

/// Substitute `var(--x, fallback)` recursively. A variable that (through
/// others) refers to itself, nesting deeper than 12, or a value that needs
/// more than [`MAX_SUBSTITUTIONS`] resolves to nothing, as in a browser: a
/// theme can't make this loop or grow without end.
fn resolve(value: &str, vars: &HashMap<String, String>, depth: u8) -> String {
    let mut budget = MAX_SUBSTITUTIONS;
    resolve_in(value, vars, depth, &mut Vec::new(), &mut budget)
}

fn resolve_in<'a>(value: &str, vars: &'a HashMap<String, String>, depth: u8, stack: &mut Vec<&'a str>, budget: &mut u32) -> String {
    if depth > 12 {
        return String::new();
    }
    let mut out = value.to_string();
    while let Some(pos) = out.find("var(") {
        if out.len() > MAX_RESOLVED || *budget == 0 {
            return String::new();
        }
        *budget -= 1;
        let inner_start = pos + 4;
        let Some(end) = matching_paren(&out, inner_start) else { break };
        let inner = &out[inner_start..end];
        // Split at the first top-level comma.
        let mut level = 0;
        let mut split = None;
        for (i, c) in inner.char_indices() {
            match c {
                '(' => level += 1,
                ')' => level -= 1,
                ',' if level == 0 => {
                    split = Some(i);
                    break;
                }
                _ => {}
            }
        }
        let (name, fallback) = match split {
            Some(i) => (inner[..i].trim(), Some(inner[i + 1..].trim())),
            None => (inner.trim(), None),
        };
        let replacement = match vars.get_key_value(name) {
            Some(_) if stack.iter().any(|s| *s == name) => String::new(),
            Some((key, v)) => {
                stack.push(key.as_str());
                let r = resolve_in(v, vars, depth + 1, stack, budget);
                stack.pop();
                r
            }
            None => fallback.map(|f| resolve_in(f, vars, depth + 1, stack, budget)).unwrap_or_default(),
        };
        out.replace_range(pos..=end, &replacement);
    }
    out
}

/// Evaluate every `calc(...)` in `s` to a plain number (keeping `%`/`deg`).
fn eval_calcs(s: &str) -> String {
    let mut out = s.to_string();
    while let Some(pos) = out.find("calc(") {
        let Some(end) = matching_paren(&out, pos + 5) else { break };
        let inner = out[pos + 5..end].to_string();
        let replacement = match Calc::new(&inner).eval() {
            Some((v, unit)) => format!("{v}{unit}"),
            None => inner,
        };
        out.replace_range(pos..=end, &replacement);
    }
    out
}

struct Calc<'a> {
    s: &'a [u8],
    i: usize,
    /// How many parentheses deep the parser is (it recurses per level).
    depth: u8,
}

impl<'a> Calc<'a> {
    fn new(s: &'a str) -> Self {
        Self { s: s.as_bytes(), i: 0, depth: 0 }
    }

    fn eval(mut self) -> Option<(f64, &'static str)> {
        let v = self.expr()?;
        self.ws();
        (self.i == self.s.len()).then_some(v)
    }

    fn ws(&mut self) {
        while self.i < self.s.len() && self.s[self.i].is_ascii_whitespace() {
            self.i += 1;
        }
    }

    fn expr(&mut self) -> Option<(f64, &'static str)> {
        let (mut v, mut unit) = self.term()?;
        loop {
            self.ws();
            let Some(&op) = self.s.get(self.i) else { return Some((v, unit)) };
            if op != b'+' && op != b'-' {
                return Some((v, unit));
            }
            self.i += 1;
            let (r, u) = self.term()?;
            v = if op == b'+' { v + r } else { v - r };
            if unit.is_empty() {
                unit = u;
            }
        }
    }

    fn term(&mut self) -> Option<(f64, &'static str)> {
        let (mut v, mut unit) = self.factor()?;
        loop {
            self.ws();
            let Some(&op) = self.s.get(self.i) else { return Some((v, unit)) };
            if op != b'*' && op != b'/' {
                return Some((v, unit));
            }
            self.i += 1;
            let (r, u) = self.factor()?;
            v = if op == b'*' { v * r } else if r != 0.0 { v / r } else { return None };
            if unit.is_empty() {
                unit = u;
            }
        }
    }

    fn factor(&mut self) -> Option<(f64, &'static str)> {
        self.ws();
        if self.s.get(self.i) == Some(&b'(') {
            // No real theme nests this far; a hostile one mustn't run the
            // stack out.
            if self.depth >= 32 {
                return None;
            }
            self.i += 1;
            self.depth += 1;
            let v = self.expr()?;
            self.depth -= 1;
            self.ws();
            if self.s.get(self.i) != Some(&b')') {
                return None;
            }
            self.i += 1;
            return Some(v);
        }
        let start = self.i;
        if matches!(self.s.get(self.i), Some(b'-' | b'+')) {
            self.i += 1;
        }
        while self.i < self.s.len() && (self.s[self.i].is_ascii_digit() || self.s[self.i] == b'.') {
            self.i += 1;
        }
        let num: f64 = std::str::from_utf8(&self.s[start..self.i]).ok()?.parse().ok()?;
        let unit_start = self.i;
        while self.i < self.s.len() && (self.s[self.i].is_ascii_alphabetic() || self.s[self.i] == b'%') {
            self.i += 1;
        }
        let unit = match &self.s[unit_start..self.i] {
            b"%" => "%",
            b"deg" => "deg",
            _ => "",
        };
        Some((num, unit))
    }
}

/// Parse a CSS color. Supports hex, rgb[a](), hsl[a]() (both comma and space
/// syntax, with `/ alpha`) and a few keywords.
pub fn parse_color(input: &str) -> Option<Rgba> {
    // Longer than any colour is written: not worth the parsing.
    if input.len() > 1024 {
        return None;
    }
    let s = eval_calcs(input.trim()).to_ascii_lowercase();
    let s = s.trim();

    if let Some(hex) = s.strip_prefix('#') {
        return parse_hex(hex);
    }
    match s {
        "transparent" => return Some([0, 0, 0, 0]),
        "white" => return Some([255, 255, 255, 255]),
        "black" => return Some([0, 0, 0, 255]),
        _ => {}
    }

    let open = s.find('(')?;
    let func = &s[..open];
    let close = s.rfind(')')?;
    let args: Vec<&str> = s[open + 1..close]
        .split(|c: char| c == ',' || c == '/' || c.is_whitespace())
        .filter(|a| !a.is_empty())
        .collect();
    if args.len() < 3 {
        return None;
    }
    let alpha = match args.get(3) {
        Some(a) => parse_alpha(a)?,
        None => 255,
    };

    match func {
        "rgb" | "rgba" => {
            let ch = |a: &str| -> Option<u8> {
                Some(if let Some(p) = a.strip_suffix('%') {
                    (p.parse::<f64>().ok()? * 2.55).round().clamp(0.0, 255.0) as u8
                } else {
                    a.parse::<f64>().ok()?.round().clamp(0.0, 255.0) as u8
                })
            };
            Some([ch(args[0])?, ch(args[1])?, ch(args[2])?, alpha])
        }
        "hsl" | "hsla" => {
            let h = args[0]
                .trim_end_matches("deg")
                .parse::<f64>()
                .ok()?;
            let pct = |a: &str| a.trim_end_matches('%').parse::<f64>().ok().map(|v| (v / 100.0).clamp(0.0, 1.0));
            let (r, g, b) = hsl_to_rgb(h, pct(args[1])?, pct(args[2])?);
            Some([r, g, b, alpha])
        }
        _ => None,
    }
}

fn parse_alpha(a: &str) -> Option<u8> {
    let v = match a.strip_suffix('%') {
        Some(p) => p.parse::<f64>().ok()? / 100.0,
        None => a.parse::<f64>().ok()?,
    };
    Some((v.clamp(0.0, 1.0) * 255.0).round() as u8)
}

fn parse_hex(hex: &str) -> Option<Rgba> {
    let digit = |i: usize| u8::from_str_radix(&hex[i..i + 1], 16).ok().map(|d| d * 17);
    let pair = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok();
    match hex.len() {
        3 => Some([digit(0)?, digit(1)?, digit(2)?, 255]),
        4 => Some([digit(0)?, digit(1)?, digit(2)?, digit(3)?]),
        6 => Some([pair(0)?, pair(2)?, pair(4)?, 255]),
        8 => Some([pair(0)?, pair(2)?, pair(4)?, pair(6)?]),
        _ => None,
    }
}

fn hsl_to_rgb(h: f64, s: f64, l: f64) -> (u8, u8, u8) {
    let h = h.rem_euclid(360.0) / 360.0;
    if s == 0.0 {
        let v = (l * 255.0).round() as u8;
        return (v, v, v);
    }
    let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s };
    let p = 2.0 * l - q;
    let hue = |mut t: f64| {
        if t < 0.0 {
            t += 1.0;
        }
        if t > 1.0 {
            t -= 1.0;
        }
        if t < 1.0 / 6.0 {
            p + (q - p) * 6.0 * t
        } else if t < 0.5 {
            q
        } else if t < 2.0 / 3.0 {
            p + (q - p) * (2.0 / 3.0 - t) * 6.0
        } else {
            p
        }
    };
    let c = |v: f64| (v * 255.0).round().clamp(0.0, 255.0) as u8;
    (c(hue(h + 1.0 / 3.0)), c(hue(h)), c(hue(h - 1.0 / 3.0)))
}

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

    #[test]
    fn colors() {
        assert_eq!(parse_color("#fff"), Some([255, 255, 255, 255]));
        assert_eq!(parse_color("#11223380"), Some([0x11, 0x22, 0x33, 0x80]));
        assert_eq!(parse_color("rgba(10, 20, 30, 0.5)"), Some([10, 20, 30, 128]));
        assert_eq!(parse_color("rgb(10 20 30 / 50%)"), Some([10, 20, 30, 128]));
        assert_eq!(parse_color("hsl(0, 100%, 50%)"), Some([255, 0, 0, 255]));
        assert_eq!(parse_color("hsl(220 calc(1*7.7%) 22.9% / 1)"), Some([54, 57, 63, 255]));
    }

    #[test]
    fn hostile_values_are_given_up_on() {
        // Variables that fan out while staying empty: 10^12 substitutions
        // without the budget.
        let mut vars: HashMap<String, String> =
            (0..12).map(|i| (format!("--e{i}"), format!("var(--e{}) ", i + 1).repeat(10).trim().to_string())).collect();
        vars.insert("--e12".into(), String::new());
        let started = std::time::Instant::now();
        assert_eq!(resolve("var(--e0)", &vars, 0).trim(), "");
        assert!(started.elapsed() < std::time::Duration::from_secs(2));
        // Parentheses nested past what the stack would hold.
        let deep = format!("calc({}1{})", "(".repeat(200), ")".repeat(200));
        assert_eq!(parse_color(&deep), None);
        assert_eq!(Calc::new(&format!("{}1{}", "(".repeat(100), ")".repeat(100))).eval(), None);
        assert_eq!(parse_color(&format!("calc({}1{})", "(".repeat(100_000), ")".repeat(100_000))), None);
    }

    #[test]
    fn self_referring_and_exploding_variables_resolve_quickly() {
        let vars: HashMap<String, String> = [
            ("--loop", "var(--loop)"),
            ("--a", "var(--b)"),
            ("--b", "var(--a) red"),
            ("--x0", "var(--x1) var(--x1) var(--x1) var(--x1)"),
            ("--x1", "var(--x2) var(--x2) var(--x2) var(--x2)"),
            ("--x2", "var(--x3) var(--x3) var(--x3) var(--x3)"),
            ("--x3", "var(--x4) var(--x4) var(--x4) var(--x4)"),
            ("--x4", "var(--x5) var(--x5) var(--x5) var(--x5)"),
            ("--x5", "var(--x6) var(--x6) var(--x6) var(--x6)"),
            ("--x6", "#123456"),
        ]
        .into_iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
        let started = std::time::Instant::now();
        assert_eq!(resolve("var(--loop)", &vars, 0), "");
        assert_eq!(resolve("var(--a)", &vars, 0).trim(), "red");
        assert!(resolve("var(--x0)", &vars, 0).len() <= MAX_RESOLVED + 64);
        assert_eq!(resolve("var(--missing, blue)", &vars, 0), "blue");
        assert!(started.elapsed() < std::time::Duration::from_secs(1));
        // The one-liner from the audit no longer hangs.
        let t = translate(":root{--background-primary: var(--background-primary)}");
        assert!(t.variables_found >= 1);
        assert!(extract_imports("@import url('http://evil.example/x.css');").is_empty());
    }

    #[test]
    fn translates_vencord_style_theme() {
        let css = r#"
            @import url("https://example.com/base.css");
            /* comment { --background-primary: red; } */
            :root { --saturation-factor: 1; --primary-630-hsl: 220 calc(var(--saturation-factor, 1)*7.7%) 22.9%; }
            .theme-dark {
                --background-primary: hsl(var(--primary-630-hsl) / 1) !important;
                --text-normal: #e0e0e0;
                --brand-experiment: var(--my-accent, #ff00ff);
            }
            .theme-light { --background-secondary: #ffffff; }
            @media (min-width: 10px) { :root { --background-tertiary: rgb(1,2,3); } }
        "#;
        assert_eq!(extract_imports(css), vec!["https://example.com/base.css"]);
        let t = translate(css);
        assert_eq!(t.palette.get("bg_primary"), Some([54, 57, 63, 255]));
        assert_eq!(t.palette.get("text_normal"), Some([0xe0, 0xe0, 0xe0, 255]));
        assert_eq!(t.palette.get("accent"), Some([255, 0, 255, 255]));
        assert_eq!(t.palette.get("bg_tertiary"), Some([1, 2, 3, 255]));
        assert_eq!(t.palette.get("bg_secondary"), None, "light-only rules are ignored");
    }
}