VNOX-Client/src/ui/appearance/css.rs

181 lines
6.3 KiB
Rust

use std::collections::HashSet;
use super::{COLOR_TOKENS, Rgba, ThemeSpec};
pub const MAX_CSS_BYTES: usize = 16 * 1024;
pub(super) fn parse_color(text: &str) -> Result<Rgba, String> {
let hex = text
.strip_prefix('#')
.ok_or(crate::ui::i18n::text("A colour must start with #."))?;
if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(crate::ui::i18n::format(
"Invalid colour: {text}",
&[("text", text.to_string())],
));
}
let byte = |s: &str| {
u8::from_str_radix(s, 16).map_err(|_| {
crate::ui::i18n::format("Invalid colour: {text}", &[("text", text.to_string())])
})
};
match hex.len() {
3 | 4 => {
let values = hex
.bytes()
.map(|b| match b.to_ascii_lowercase() {
b'0'..=b'9' => (b - b'0') * 17,
lower => (lower - b'a' + 10) * 17,
})
.collect::<Vec<_>>();
Ok(Rgba(
values[0],
values[1],
values[2],
values.get(3).copied().unwrap_or(255),
))
}
6 | 8 => Ok(Rgba(
byte(&hex[0..2])?,
byte(&hex[2..4])?,
byte(&hex[4..6])?,
if hex.len() == 8 {
byte(&hex[6..8])?
} else {
255
},
)),
_ => Err(crate::ui::i18n::format(
"Colour {text} requires 3, 4, 6 or 8 hexadecimal digits.",
&[("text", text.to_string())],
)),
}
}
fn strip_comments(css: &str) -> Result<String, String> {
let mut rest = css;
let mut result = String::new();
while let Some(start) = rest.find("/*") {
result.push_str(&rest[..start]);
let tail = &rest[start + 2..];
let end = tail
.find("*/")
.ok_or(crate::ui::i18n::text("Unclosed CSS comment."))?;
result.push(' ');
rest = &tail[end + 2..];
}
result.push_str(rest);
Ok(result)
}
/// Parse the deliberately restricted native-theme CSS format; never fetch or execute CSS.
pub fn parse_css(css: &str) -> Result<ThemeSpec, String> {
if css.len() > MAX_CSS_BYTES {
return Err(crate::ui::i18n::text(
"Theme file is too large: maximum 16 KB.",
));
}
let stripped = strip_comments(css)?;
let root = stripped
.trim()
.strip_prefix(":root")
.ok_or(crate::ui::i18n::text(
"A theme must contain one :root { … } block. ",
))?
.trim();
let body = root
.strip_prefix('{')
.and_then(|s| s.strip_suffix('}'))
.ok_or(crate::ui::i18n::text("Expected one :root { … } block. "))?;
if body.contains(['{', '}']) {
return Err(crate::ui::i18n::text(
"Only one :root block without nested rules is supported.",
));
}
let mut theme = ThemeSpec::builtin("dark");
let mut seen = HashSet::new();
for declaration in body.split(';').map(str::trim).filter(|s| !s.is_empty()) {
let (name, value) = declaration.split_once(':').ok_or(crate::ui::i18n::text(
"A variable name must be followed by :.",
))?;
let (name, value) = (name.trim(), value.trim());
if !seen.insert(name) {
return Err(crate::ui::i18n::format(
"Variable {name} is defined twice.",
&[("name", name.to_string())],
));
}
if name == "--vnox-font-size" {
let number = value.strip_suffix("px").ok_or(crate::ui::i18n::text(
"Text size must use px, for example 16px.",
))?;
let size: f32 = number
.trim()
.parse()
.map_err(|_| crate::ui::i18n::text("Invalid text size."))?;
if !size.is_finite() || !(12.0..=22.0).contains(&size) {
return Err(crate::ui::i18n::text(
"Text size must be between 12px and 22px.",
));
}
theme.font_size = size;
} else if let Some(index) = COLOR_TOKENS.iter().position(|token| *token == name) {
theme.colors[index] = parse_color(value).map_err(|e| format!("{name}: {e}"))?;
} else {
return Err(crate::ui::i18n::format(
"Unsupported variable {name}. CSS selectors, url() and @import are not supported.",
&[("name", name.to_string())],
));
}
}
if seen.is_empty() {
return Err(crate::ui::i18n::text(
"Add at least one --vnox-… variable to :root.",
));
}
Ok(theme)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_native_variables_comments_and_rgba_without_changing_defaults() {
let theme = parse_css("/* custom */ :root { --vnox-bg: #123; --vnox-border: #abcd; --vnox-text: #f0eeeaff; --vnox-font-size: 18px; }").unwrap();
assert_eq!(theme.colors[0], Rgba(17, 34, 51, 255));
assert_eq!(theme.colors[7], Rgba(170, 187, 204, 221));
assert_eq!(theme.colors[9], Rgba(240, 238, 234, 255));
assert_eq!(theme.font_size, 18.0);
assert_eq!(theme.colors[1], ThemeSpec::builtin("dark").colors[1]);
}
#[test]
fn rejects_executable_external_unknown_and_malformed_input() {
for invalid in [
"@import 'https://example.com/x.css';",
"body { color: #fff; }",
":root { --vnox-bg: url(file:///etc/passwd); }",
":root { --typo: #fff; }",
":root { --vnox-bg: #ggg; }",
":root { --vnox-bg: #fff; --vnox-bg: #000; }",
":root { --vnox-font-size: NaNpx; }",
":root { --vnox-font-size: 200px; }",
":root { --vnox-font-size: 1rem; }",
":root {}",
":root { --vnox-bg: #fff; } body {}",
"/* unfinished",
] {
assert!(parse_css(invalid).is_err(), "must reject {invalid}");
}
assert!(parse_css(&"x".repeat(MAX_CSS_BYTES + 1)).is_err());
}
#[test]
fn built_in_themes_roundtrip_without_color_or_alpha_loss() {
for mode in ["light", "dark", "black"] {
let theme = ThemeSpec::builtin(mode);
assert_eq!(parse_css(&theme.to_css()).unwrap(), theme);
}
}
}