| 1 |
use std::{ |
| 2 |
collections::{HashMap, HashSet}, |
| 3 |
path::{Path, PathBuf}, |
| 4 |
str, |
| 5 |
}; |
| 6 |
|
| 7 |
use anyhow::{anyhow, Result}; |
| 8 |
use helix_core::{hashmap, syntax::Highlight}; |
| 9 |
use helix_loader::merge_toml_values; |
| 10 |
use log::warn; |
| 11 |
use once_cell::sync::Lazy; |
| 12 |
use serde::{Deserialize, Deserializer}; |
| 13 |
use toml::{map::Map, Value}; |
| 14 |
|
| 15 |
use crate::graphics::UnderlineStyle; |
| 16 |
pub use crate::graphics::{Color, Modifier, Style}; |
| 17 |
|
| 18 |
pub static DEFAULT_THEME_DATA: Lazy<Value> = Lazy::new(|| { |
| 19 |
let bytes = include_bytes!("../../theme.toml"); |
| 20 |
toml::from_str(str::from_utf8(bytes).unwrap()).expect("Failed to parse base default theme") |
| 21 |
}); |
| 22 |
|
| 23 |
pub static BASE16_DEFAULT_THEME_DATA: Lazy<Value> = Lazy::new(|| { |
| 24 |
let bytes = include_bytes!("../../base16_theme.toml"); |
| 25 |
toml::from_str(str::from_utf8(bytes).unwrap()).expect("Failed to parse base 16 default theme") |
| 26 |
}); |
| 27 |
|
| 28 |
pub static DEFAULT_THEME: Lazy<Theme> = Lazy::new(|| Theme { |
| 29 |
name: "default".into(), |
| 30 |
..Theme::from(DEFAULT_THEME_DATA.clone()) |
| 31 |
}); |
| 32 |
|
| 33 |
pub static BASE16_DEFAULT_THEME: Lazy<Theme> = Lazy::new(|| Theme { |
| 34 |
name: "base16_default".into(), |
| 35 |
..Theme::from(BASE16_DEFAULT_THEME_DATA.clone()) |
| 36 |
}); |
| 37 |
|
| 38 |
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 39 |
pub enum Mode { |
| 40 |
Dark, |
| 41 |
Light, |
| 42 |
} |
| 43 |
|
| 44 |
#[cfg(feature = "term")] |
| 45 |
impl From<termina::escape::csi::ThemeMode> for Mode { |
| 46 |
fn from(mode: termina::escape::csi::ThemeMode) -> Self { |
| 47 |
match mode { |
| 48 |
termina::escape::csi::ThemeMode::Dark => Self::Dark, |
| 49 |
termina::escape::csi::ThemeMode::Light => Self::Light, |
| 50 |
} |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] |
| 55 |
#[serde(untagged, deny_unknown_fields, rename_all = "kebab-case")] |
| 56 |
pub enum Config { |
| 57 |
Constant(String), |
| 58 |
Adaptive { |
| 59 |
light: String, |
| 60 |
dark: String, |
| 61 |
|
| 62 |
|
| 63 |
fallback: Option<String>, |
| 64 |
}, |
| 65 |
} |
| 66 |
|
| 67 |
impl Config { |
| 68 |
pub fn choose(&self, preference: Option<Mode>) -> &str { |
| 69 |
match self { |
| 70 |
Config::Constant(theme) => theme, |
| 71 |
Config::Adaptive { |
| 72 |
light, |
| 73 |
dark, |
| 74 |
fallback, |
| 75 |
} => match preference { |
| 76 |
Some(Mode::Light) => light, |
| 77 |
Some(Mode::Dark) => dark, |
| 78 |
None => fallback.as_ref().unwrap_or(dark), |
| 79 |
}, |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
pub fn is_adaptive(&self) -> bool { |
| 84 |
matches!(self, Self::Adaptive { .. }) |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
#[derive(Clone, Debug)] |
| 89 |
pub struct Loader { |
| 90 |
|
| 91 |
theme_dirs: Vec<PathBuf>, |
| 92 |
} |
| 93 |
impl Loader { |
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
pub fn new(dirs: &[PathBuf]) -> Self { |
| 99 |
Self { |
| 100 |
theme_dirs: dirs.iter().map(|p| p.join("themes")).collect(), |
| 101 |
} |
| 102 |
} |
| 103 |
|
| 104 |
|
| 105 |
pub fn load(&self, name: &str) -> Result<Theme> { |
| 106 |
let (theme, warnings) = self.load_with_warnings(name)?; |
| 107 |
|
| 108 |
for warning in warnings { |
| 109 |
warn!("Theme '{}': {}", name, warning); |
| 110 |
} |
| 111 |
|
| 112 |
Ok(theme) |
| 113 |
} |
| 114 |
|
| 115 |
|
| 116 |
pub fn load_with_warnings(&self, name: &str) -> Result<(Theme, Vec<String>)> { |
| 117 |
if name == "default" { |
| 118 |
return Ok((self.default(), Vec::new())); |
| 119 |
} |
| 120 |
if name == "base16_default" { |
| 121 |
return Ok((self.base16_default(), Vec::new())); |
| 122 |
} |
| 123 |
|
| 124 |
let mut visited_paths = HashSet::new(); |
| 125 |
let (theme, warnings) = self |
| 126 |
.load_theme(name, &mut visited_paths) |
| 127 |
.map(Theme::from_toml)?; |
| 128 |
|
| 129 |
let theme = Theme { |
| 130 |
name: name.into(), |
| 131 |
..theme |
| 132 |
}; |
| 133 |
Ok((theme, warnings)) |
| 134 |
} |
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
fn load_theme(&self, name: &str, visited_paths: &mut HashSet<PathBuf>) -> Result<Value> { |
| 146 |
let path = self.path(name, visited_paths)?; |
| 147 |
|
| 148 |
let theme_toml = self.load_toml(path)?; |
| 149 |
|
| 150 |
let inherits = theme_toml.get("inherits"); |
| 151 |
|
| 152 |
let theme_toml = if let Some(parent_theme_name) = inherits { |
| 153 |
let parent_theme_name = parent_theme_name.as_str().ok_or_else(|| { |
| 154 |
anyhow!("Expected 'inherits' to be a string: {}", parent_theme_name) |
| 155 |
})?; |
| 156 |
|
| 157 |
let parent_theme_toml = match parent_theme_name { |
| 158 |
|
| 159 |
"default" => DEFAULT_THEME_DATA.clone(), |
| 160 |
"base16_default" => BASE16_DEFAULT_THEME_DATA.clone(), |
| 161 |
_ => self.load_theme(parent_theme_name, visited_paths)?, |
| 162 |
}; |
| 163 |
|
| 164 |
self.merge_themes(parent_theme_toml, theme_toml) |
| 165 |
} else { |
| 166 |
theme_toml |
| 167 |
}; |
| 168 |
|
| 169 |
Ok(theme_toml) |
| 170 |
} |
| 171 |
|
| 172 |
pub fn read_names(path: &Path) -> Vec<String> { |
| 173 |
std::fs::read_dir(path) |
| 174 |
.map(|entries| { |
| 175 |
entries |
| 176 |
.filter_map(|entry| { |
| 177 |
let entry = entry.ok()?; |
| 178 |
let path = entry.path(); |
| 179 |
(path.extension()? == "toml") |
| 180 |
.then(|| path.file_stem().unwrap().to_string_lossy().into_owned()) |
| 181 |
}) |
| 182 |
.collect() |
| 183 |
}) |
| 184 |
.unwrap_or_default() |
| 185 |
} |
| 186 |
|
| 187 |
|
| 188 |
fn merge_themes(&self, parent_theme_toml: Value, theme_toml: Value) -> Value { |
| 189 |
let parent_palette = parent_theme_toml.get("palette"); |
| 190 |
let palette = theme_toml.get("palette"); |
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
let palette_values = match (parent_palette, palette) { |
| 195 |
(Some(parent_palette), Some(palette)) => { |
| 196 |
merge_toml_values(parent_palette.clone(), palette.clone(), 2) |
| 197 |
} |
| 198 |
(Some(parent_palette), None) => parent_palette.clone(), |
| 199 |
(None, Some(palette)) => palette.clone(), |
| 200 |
(None, None) => Map::new().into(), |
| 201 |
}; |
| 202 |
|
| 203 |
|
| 204 |
let mut palette = Map::new(); |
| 205 |
palette.insert(String::from("palette"), palette_values); |
| 206 |
|
| 207 |
|
| 208 |
let theme = merge_toml_values(parent_theme_toml, theme_toml, 1); |
| 209 |
|
| 210 |
merge_toml_values(theme, palette.into(), 1) |
| 211 |
} |
| 212 |
|
| 213 |
|
| 214 |
fn load_toml(&self, path: PathBuf) -> Result<Value> { |
| 215 |
let data = std::fs::read_to_string(path)?; |
| 216 |
let value = toml::from_str(&data)?; |
| 217 |
|
| 218 |
Ok(value) |
| 219 |
} |
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
fn path(&self, name: &str, visited_paths: &mut HashSet<PathBuf>) -> Result<PathBuf> { |
| 225 |
let filename = format!("{}.toml", name); |
| 226 |
|
| 227 |
let mut cycle_found = false; |
| 228 |
self.theme_dirs |
| 229 |
.iter() |
| 230 |
.find_map(|dir| { |
| 231 |
let path = dir.join(&filename); |
| 232 |
if !path.exists() { |
| 233 |
None |
| 234 |
} else if visited_paths.contains(&path) { |
| 235 |
|
| 236 |
cycle_found = true; |
| 237 |
None |
| 238 |
} else { |
| 239 |
visited_paths.insert(path.clone()); |
| 240 |
Some(path) |
| 241 |
} |
| 242 |
}) |
| 243 |
.ok_or_else(|| { |
| 244 |
if cycle_found { |
| 245 |
anyhow!("Cycle found in inheriting: {}", name) |
| 246 |
} else { |
| 247 |
anyhow!("File not found for: {}", name) |
| 248 |
} |
| 249 |
}) |
| 250 |
} |
| 251 |
|
| 252 |
pub fn default_theme(&self, true_color: bool) -> Theme { |
| 253 |
if true_color { |
| 254 |
self.default() |
| 255 |
} else { |
| 256 |
self.base16_default() |
| 257 |
} |
| 258 |
} |
| 259 |
|
| 260 |
|
| 261 |
pub fn default(&self) -> Theme { |
| 262 |
DEFAULT_THEME.clone() |
| 263 |
} |
| 264 |
|
| 265 |
|
| 266 |
pub fn base16_default(&self) -> Theme { |
| 267 |
BASE16_DEFAULT_THEME.clone() |
| 268 |
} |
| 269 |
} |
| 270 |
|
| 271 |
#[derive(Clone, Debug, Default)] |
| 272 |
pub struct Theme { |
| 273 |
name: String, |
| 274 |
|
| 275 |
|
| 276 |
styles: HashMap<String, Style>, |
| 277 |
|
| 278 |
scopes: Vec<String>, |
| 279 |
highlights: Vec<Style>, |
| 280 |
|
| 281 |
|
| 282 |
scope_index: HashMap<String, Highlight>, |
| 283 |
rainbow_length: usize, |
| 284 |
} |
| 285 |
|
| 286 |
impl From<Value> for Theme { |
| 287 |
fn from(value: Value) -> Self { |
| 288 |
let (theme, warnings) = Theme::from_toml(value); |
| 289 |
for warning in warnings { |
| 290 |
warn!("{}", warning); |
| 291 |
} |
| 292 |
theme |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
impl<'de> Deserialize<'de> for Theme { |
| 297 |
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 298 |
where |
| 299 |
D: Deserializer<'de>, |
| 300 |
{ |
| 301 |
let values = Map::<String, Value>::deserialize(deserializer)?; |
| 302 |
let (theme, warnings) = Theme::from_keys(values); |
| 303 |
for warning in warnings { |
| 304 |
warn!("{}", warning); |
| 305 |
} |
| 306 |
Ok(theme) |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
#[allow(clippy::type_complexity)] |
| 311 |
fn build_theme_values( |
| 312 |
mut values: Map<String, Value>, |
| 313 |
) -> ( |
| 314 |
HashMap<String, Style>, |
| 315 |
Vec<String>, |
| 316 |
Vec<Style>, |
| 317 |
usize, |
| 318 |
Vec<String>, |
| 319 |
) { |
| 320 |
let mut styles = HashMap::new(); |
| 321 |
let mut scopes = Vec::new(); |
| 322 |
let mut highlights = Vec::new(); |
| 323 |
let mut rainbow_length = 0; |
| 324 |
|
| 325 |
let mut warnings = Vec::new(); |
| 326 |
|
| 327 |
|
| 328 |
let palette = values |
| 329 |
.remove("palette") |
| 330 |
.map(|value| { |
| 331 |
ThemePalette::try_from(value).unwrap_or_else(|err| { |
| 332 |
warnings.push(err); |
| 333 |
ThemePalette::default() |
| 334 |
}) |
| 335 |
}) |
| 336 |
.unwrap_or_default(); |
| 337 |
|
| 338 |
let _ = values.remove("inherits"); |
| 339 |
styles.reserve(values.len()); |
| 340 |
scopes.reserve(values.len()); |
| 341 |
highlights.reserve(values.len()); |
| 342 |
|
| 343 |
for (i, style) in values |
| 344 |
.remove("rainbow") |
| 345 |
.and_then(|value| match palette.parse_style_array(value) { |
| 346 |
Ok(styles) => Some(styles), |
| 347 |
Err(err) => { |
| 348 |
warnings.push(err); |
| 349 |
None |
| 350 |
} |
| 351 |
}) |
| 352 |
.unwrap_or_else(default_rainbow) |
| 353 |
.into_iter() |
| 354 |
.enumerate() |
| 355 |
{ |
| 356 |
let name = format!("rainbow.{i}"); |
| 357 |
styles.insert(name.clone(), style); |
| 358 |
scopes.push(name); |
| 359 |
highlights.push(style); |
| 360 |
rainbow_length += 1; |
| 361 |
} |
| 362 |
|
| 363 |
for (name, style_value) in values { |
| 364 |
let mut style = Style::default(); |
| 365 |
if let Err(err) = palette.parse_style(&mut style, style_value) { |
| 366 |
warnings.push(format!("Failed to parse style for key {name:?}. {err}")); |
| 367 |
} |
| 368 |
|
| 369 |
|
| 370 |
styles.insert(name.clone(), style); |
| 371 |
scopes.push(name); |
| 372 |
highlights.push(style); |
| 373 |
} |
| 374 |
|
| 375 |
(styles, scopes, highlights, rainbow_length, warnings) |
| 376 |
} |
| 377 |
|
| 378 |
fn default_rainbow() -> Vec<Style> { |
| 379 |
vec![ |
| 380 |
Style::default().fg(Color::Red), |
| 381 |
Style::default().fg(Color::Yellow), |
| 382 |
Style::default().fg(Color::Green), |
| 383 |
Style::default().fg(Color::Blue), |
| 384 |
Style::default().fg(Color::Cyan), |
| 385 |
Style::default().fg(Color::Magenta), |
| 386 |
] |
| 387 |
} |
| 388 |
impl Theme { |
| 389 |
|
| 390 |
|
| 391 |
const RGB_START: u32 = (u32::MAX << (8 + 8 + 8)) - 1 - (u32::MAX - Highlight::MAX); |
| 392 |
|
| 393 |
|
| 394 |
fn decode_rgb_highlight(highlight: Highlight) -> Option<(u8, u8, u8)> { |
| 395 |
(highlight.get() > Self::RGB_START).then(|| { |
| 396 |
let [b, g, r, ..] = (highlight.get() + 1).to_le_bytes(); |
| 397 |
(r, g, b) |
| 398 |
}) |
| 399 |
} |
| 400 |
|
| 401 |
|
| 402 |
pub fn rgb_highlight(r: u8, g: u8, b: u8) -> Highlight { |
| 403 |
|
| 404 |
|
| 405 |
Highlight::new(u32::from_le_bytes([b, g, r, u8::MAX]) - 1) |
| 406 |
} |
| 407 |
|
| 408 |
#[inline] |
| 409 |
pub fn highlight(&self, highlight: Highlight) -> Style { |
| 410 |
if let Some((red, green, blue)) = Self::decode_rgb_highlight(highlight) { |
| 411 |
Style::new().fg(Color::Rgb(red, green, blue)) |
| 412 |
} else { |
| 413 |
self.highlights[highlight.idx()] |
| 414 |
} |
| 415 |
} |
| 416 |
|
| 417 |
#[inline] |
| 418 |
pub fn scope(&self, highlight: Highlight) -> &str { |
| 419 |
&self.scopes[highlight.idx()] |
| 420 |
} |
| 421 |
|
| 422 |
pub fn name(&self) -> &str { |
| 423 |
&self.name |
| 424 |
} |
| 425 |
|
| 426 |
pub fn get(&self, scope: &str) -> Style { |
| 427 |
self.try_get(scope).unwrap_or_default() |
| 428 |
} |
| 429 |
|
| 430 |
|
| 431 |
|
| 432 |
|
| 433 |
pub fn try_get(&self, scope: &str) -> Option<Style> { |
| 434 |
std::iter::successors(Some(scope), |s| Some(s.rsplit_once('.')?.0)) |
| 435 |
.find_map(|s| self.styles.get(s).copied()) |
| 436 |
} |
| 437 |
|
| 438 |
|
| 439 |
|
| 440 |
|
| 441 |
pub fn try_get_exact(&self, scope: &str) -> Option<Style> { |
| 442 |
self.styles.get(scope).copied() |
| 443 |
} |
| 444 |
|
| 445 |
#[inline] |
| 446 |
pub fn scopes(&self) -> &[String] { |
| 447 |
&self.scopes |
| 448 |
} |
| 449 |
|
| 450 |
pub fn find_highlight_exact(&self, scope: &str) -> Option<Highlight> { |
| 451 |
self.scope_index.get(scope).copied() |
| 452 |
} |
| 453 |
|
| 454 |
pub fn find_highlight(&self, mut scope: &str) -> Option<Highlight> { |
| 455 |
loop { |
| 456 |
if let Some(highlight) = self.find_highlight_exact(scope) { |
| 457 |
return Some(highlight); |
| 458 |
} |
| 459 |
if let Some(new_end) = scope.rfind('.') { |
| 460 |
scope = &scope[..new_end]; |
| 461 |
} else { |
| 462 |
return None; |
| 463 |
} |
| 464 |
} |
| 465 |
} |
| 466 |
|
| 467 |
pub fn is_16_color(&self) -> bool { |
| 468 |
self.styles.iter().all(|(_, style)| { |
| 469 |
[style.fg, style.bg] |
| 470 |
.into_iter() |
| 471 |
.all(|color| !matches!(color, Some(Color::Rgb(..)))) |
| 472 |
}) |
| 473 |
} |
| 474 |
|
| 475 |
pub fn rainbow_length(&self) -> usize { |
| 476 |
self.rainbow_length |
| 477 |
} |
| 478 |
|
| 479 |
fn from_toml(value: Value) -> (Self, Vec<String>) { |
| 480 |
if let Value::Table(table) = value { |
| 481 |
Theme::from_keys(table) |
| 482 |
} else { |
| 483 |
warn!("Expected theme TOML value to be a table, found {:?}", value); |
| 484 |
Default::default() |
| 485 |
} |
| 486 |
} |
| 487 |
|
| 488 |
fn from_keys(toml_keys: Map<String, Value>) -> (Self, Vec<String>) { |
| 489 |
let (styles, scopes, highlights, rainbow_length, load_errors) = |
| 490 |
build_theme_values(toml_keys); |
| 491 |
|
| 492 |
let scope_index = scopes |
| 493 |
.iter() |
| 494 |
.enumerate() |
| 495 |
.map(|(i, s)| (s.clone(), Highlight::new(i as u32))) |
| 496 |
.collect(); |
| 497 |
|
| 498 |
let theme = Self { |
| 499 |
styles, |
| 500 |
scopes, |
| 501 |
highlights, |
| 502 |
scope_index, |
| 503 |
rainbow_length, |
| 504 |
..Default::default() |
| 505 |
}; |
| 506 |
(theme, load_errors) |
| 507 |
} |
| 508 |
} |
| 509 |
|
| 510 |
struct ThemePalette { |
| 511 |
palette: HashMap<String, Color>, |
| 512 |
} |
| 513 |
|
| 514 |
impl Default for ThemePalette { |
| 515 |
fn default() -> Self { |
| 516 |
Self { |
| 517 |
palette: hashmap! { |
| 518 |
"default".to_string() => Color::Reset, |
| 519 |
"black".to_string() => Color::Black, |
| 520 |
"red".to_string() => Color::Red, |
| 521 |
"green".to_string() => Color::Green, |
| 522 |
"yellow".to_string() => Color::Yellow, |
| 523 |
"blue".to_string() => Color::Blue, |
| 524 |
"magenta".to_string() => Color::Magenta, |
| 525 |
"cyan".to_string() => Color::Cyan, |
| 526 |
"gray".to_string() => Color::Gray, |
| 527 |
"light-red".to_string() => Color::LightRed, |
| 528 |
"light-green".to_string() => Color::LightGreen, |
| 529 |
"light-yellow".to_string() => Color::LightYellow, |
| 530 |
"light-blue".to_string() => Color::LightBlue, |
| 531 |
"light-magenta".to_string() => Color::LightMagenta, |
| 532 |
"light-cyan".to_string() => Color::LightCyan, |
| 533 |
"light-gray".to_string() => Color::LightGray, |
| 534 |
"white".to_string() => Color::White, |
| 535 |
}, |
| 536 |
} |
| 537 |
} |
| 538 |
} |
| 539 |
|
| 540 |
impl ThemePalette { |
| 541 |
pub fn new(palette: HashMap<String, Color>) -> Self { |
| 542 |
let ThemePalette { |
| 543 |
palette: mut default, |
| 544 |
} = ThemePalette::default(); |
| 545 |
|
| 546 |
default.extend(palette); |
| 547 |
Self { palette: default } |
| 548 |
} |
| 549 |
|
| 550 |
pub fn string_to_rgb(s: &str) -> Result<Color, String> { |
| 551 |
if s.starts_with('#') { |
| 552 |
Color::from_hex(s).map_err(|e| format!("{e}: {s}")) |
| 553 |
} else { |
| 554 |
Self::ansi_string_to_rgb(s) |
| 555 |
} |
| 556 |
} |
| 557 |
|
| 558 |
fn ansi_string_to_rgb(s: &str) -> Result<Color, String> { |
| 559 |
if let Ok(index) = s.parse::<u8>() { |
| 560 |
return Ok(Color::Indexed(index)); |
| 561 |
} |
| 562 |
Err(format!("Malformed ANSI: {}", s)) |
| 563 |
} |
| 564 |
|
| 565 |
fn parse_value_as_str(value: &Value) -> Result<&str, String> { |
| 566 |
value |
| 567 |
.as_str() |
| 568 |
.ok_or(format!("Unrecognized value: {}", value)) |
| 569 |
} |
| 570 |
|
| 571 |
pub fn parse_color(&self, value: Value) -> Result<Color, String> { |
| 572 |
let value = Self::parse_value_as_str(&value)?; |
| 573 |
|
| 574 |
self.palette |
| 575 |
.get(value) |
| 576 |
.copied() |
| 577 |
.ok_or("") |
| 578 |
.or_else(|_| Self::string_to_rgb(value)) |
| 579 |
} |
| 580 |
|
| 581 |
pub fn parse_modifier(value: &Value) -> Result<Modifier, String> { |
| 582 |
value |
| 583 |
.as_str() |
| 584 |
.and_then(|s| s.parse().ok()) |
| 585 |
.ok_or(format!("Invalid modifier: {}", value)) |
| 586 |
} |
| 587 |
|
| 588 |
pub fn parse_underline_style(value: &Value) -> Result<UnderlineStyle, String> { |
| 589 |
value |
| 590 |
.as_str() |
| 591 |
.and_then(|s| s.parse().ok()) |
| 592 |
.ok_or(format!("Invalid underline style: {}", value)) |
| 593 |
} |
| 594 |
|
| 595 |
pub fn parse_style(&self, style: &mut Style, value: Value) -> Result<(), String> { |
| 596 |
if let Value::Table(entries) = value { |
| 597 |
for (name, mut value) in entries { |
| 598 |
match name.as_str() { |
| 599 |
"fg" => *style = style.fg(self.parse_color(value)?), |
| 600 |
"bg" => *style = style.bg(self.parse_color(value)?), |
| 601 |
"underline" => { |
| 602 |
let table = value.as_table_mut().ok_or("Underline must be table")?; |
| 603 |
if let Some(value) = table.remove("color") { |
| 604 |
*style = style.underline_color(self.parse_color(value)?); |
| 605 |
} |
| 606 |
if let Some(value) = table.remove("style") { |
| 607 |
*style = style.underline_style(Self::parse_underline_style(&value)?); |
| 608 |
} |
| 609 |
|
| 610 |
if let Some(attr) = table.keys().next() { |
| 611 |
return Err(format!("Invalid underline attribute: {attr}")); |
| 612 |
} |
| 613 |
} |
| 614 |
"modifiers" => { |
| 615 |
let modifiers = value.as_array().ok_or("Modifiers should be an array")?; |
| 616 |
|
| 617 |
for modifier in modifiers { |
| 618 |
if modifier.as_str() == Some("underlined") { |
| 619 |
*style = style.underline_style(UnderlineStyle::Line); |
| 620 |
} else { |
| 621 |
*style = style.add_modifier(Self::parse_modifier(modifier)?); |
| 622 |
} |
| 623 |
} |
| 624 |
} |
| 625 |
_ => return Err(format!("Invalid style attribute: {}", name)), |
| 626 |
} |
| 627 |
} |
| 628 |
} else { |
| 629 |
*style = style.fg(self.parse_color(value)?); |
| 630 |
} |
| 631 |
Ok(()) |
| 632 |
} |
| 633 |
|
| 634 |
fn parse_style_array(&self, value: Value) -> Result<Vec<Style>, String> { |
| 635 |
let mut styles = Vec::new(); |
| 636 |
|
| 637 |
for v in value |
| 638 |
.as_array() |
| 639 |
.ok_or_else(|| format!("Could not parse value as an array: '{value}'"))? |
| 640 |
{ |
| 641 |
let mut style = Style::default(); |
| 642 |
self.parse_style(&mut style, v.clone())?; |
| 643 |
styles.push(style); |
| 644 |
} |
| 645 |
|
| 646 |
Ok(styles) |
| 647 |
} |
| 648 |
} |
| 649 |
|
| 650 |
impl TryFrom<Value> for ThemePalette { |
| 651 |
type Error = String; |
| 652 |
|
| 653 |
fn try_from(value: Value) -> Result<Self, Self::Error> { |
| 654 |
let map = match value { |
| 655 |
Value::Table(entries) => entries, |
| 656 |
_ => return Ok(Self::default()), |
| 657 |
}; |
| 658 |
|
| 659 |
let mut palette = HashMap::with_capacity(map.len()); |
| 660 |
for (name, value) in map { |
| 661 |
let value = Self::parse_value_as_str(&value)?; |
| 662 |
let color = Self::string_to_rgb(value)?; |
| 663 |
palette.insert(name, color); |
| 664 |
} |
| 665 |
|
| 666 |
Ok(Self::new(palette)) |
| 667 |
} |
| 668 |
} |
| 669 |
|
| 670 |
#[cfg(test)] |
| 671 |
mod tests { |
| 672 |
use super::*; |
| 673 |
|
| 674 |
#[test] |
| 675 |
fn test_parse_style_string() { |
| 676 |
let fg = Value::String("#ffffff".to_string()); |
| 677 |
|
| 678 |
let mut style = Style::default(); |
| 679 |
let palette = ThemePalette::default(); |
| 680 |
palette.parse_style(&mut style, fg).unwrap(); |
| 681 |
|
| 682 |
assert_eq!(style, Style::default().fg(Color::Rgb(255, 255, 255))); |
| 683 |
} |
| 684 |
|
| 685 |
#[test] |
| 686 |
fn test_palette() { |
| 687 |
use helix_core::hashmap; |
| 688 |
let fg = Value::String("my_color".to_string()); |
| 689 |
|
| 690 |
let mut style = Style::default(); |
| 691 |
let palette = |
| 692 |
ThemePalette::new(hashmap! { "my_color".to_string() => Color::Rgb(255, 255, 255) }); |
| 693 |
palette.parse_style(&mut style, fg).unwrap(); |
| 694 |
|
| 695 |
assert_eq!(style, Style::default().fg(Color::Rgb(255, 255, 255))); |
| 696 |
} |
| 697 |
|
| 698 |
#[test] |
| 699 |
fn test_parse_style_table() { |
| 700 |
let table = toml::toml! { |
| 701 |
"keyword" = { |
| 702 |
fg = "#ffffff", |
| 703 |
bg = "#000000", |
| 704 |
modifiers = ["bold"], |
| 705 |
} |
| 706 |
}; |
| 707 |
|
| 708 |
let mut style = Style::default(); |
| 709 |
let palette = ThemePalette::default(); |
| 710 |
for (_name, value) in table { |
| 711 |
palette.parse_style(&mut style, value).unwrap(); |
| 712 |
} |
| 713 |
|
| 714 |
assert_eq!( |
| 715 |
style, |
| 716 |
Style::default() |
| 717 |
.fg(Color::Rgb(255, 255, 255)) |
| 718 |
.bg(Color::Rgb(0, 0, 0)) |
| 719 |
.add_modifier(Modifier::BOLD) |
| 720 |
); |
| 721 |
} |
| 722 |
|
| 723 |
|
| 724 |
|
| 725 |
#[test] |
| 726 |
fn convert_to_and_from() { |
| 727 |
let (r, g, b) = (0xFF, 0xFE, 0xFA); |
| 728 |
let highlight = Theme::rgb_highlight(r, g, b); |
| 729 |
assert_eq!(Theme::decode_rgb_highlight(highlight), Some((r, g, b))); |
| 730 |
} |
| 731 |
|
| 732 |
|
| 733 |
#[test] |
| 734 |
fn full_numeric_range() { |
| 735 |
assert_eq!(Highlight::MAX - Theme::RGB_START, 256_u32.pow(3)); |
| 736 |
} |
| 737 |
|
| 738 |
#[test] |
| 739 |
fn retrieve_color() { |
| 740 |
|
| 741 |
let (r, g, b) = (0x14, 0xAA, 0xF7); |
| 742 |
assert_eq!( |
| 743 |
Theme::default().highlight(Theme::rgb_highlight(r, g, b)), |
| 744 |
Style::new().fg(Color::Rgb(r, g, b)) |
| 745 |
); |
| 746 |
|
| 747 |
let (r, g, b) = (0x00, 0x00, 0x00); |
| 748 |
assert_eq!( |
| 749 |
Theme::default().highlight(Theme::rgb_highlight(r, g, b)), |
| 750 |
Style::new().fg(Color::Rgb(r, g, b)) |
| 751 |
); |
| 752 |
|
| 753 |
let (r, g, b) = (0xff, 0xff, 0xff); |
| 754 |
assert_eq!( |
| 755 |
Theme::default().highlight(Theme::rgb_highlight(r, g, b)), |
| 756 |
Style::new().fg(Color::Rgb(r, g, b)) |
| 757 |
); |
| 758 |
} |
| 759 |
|
| 760 |
#[test] |
| 761 |
#[should_panic(expected = "index out of bounds: the len is 0 but the index is 4278190078")] |
| 762 |
fn out_of_bounds() { |
| 763 |
let highlight = Highlight::new(Theme::rgb_highlight(0, 0, 0).get() - 1); |
| 764 |
Theme::default().highlight(highlight); |
| 765 |
} |
| 766 |
} |