use super::{Color, Style};
use enum_map::{enum_map, Enum, EnumMap};
#[cfg(feature = "toml")]
use log::warn;
use std::ops::{Index, IndexMut};
use std::str::FromStr;
type HashMap<K, V> = std::collections::HashMap<K, V, ahash::RandomState>;
#[derive(Debug)]
pub struct NoSuchColor;
impl std::fmt::Display for NoSuchColor {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Could not parse the given color")
}
}
impl std::error::Error for NoSuchColor {}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Palette {
basic: EnumMap<PaletteColor, Color>,
custom: HashMap<String, PaletteNode>,
styles: EnumMap<PaletteStyle, Style>,
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum PaletteNode {
Color(Color),
Namespace(HashMap<String, PaletteNode>),
}
impl Index<PaletteColor> for Palette {
type Output = Color;
fn index(&self, palette_color: PaletteColor) -> &Color {
&self.basic[palette_color]
}
}
impl Index<PaletteStyle> for Palette {
type Output = Style;
fn index(&self, palette_style: PaletteStyle) -> &Style {
&self.styles[palette_style]
}
}
impl IndexMut<PaletteColor> for Palette {
fn index_mut(&mut self, palette_color: PaletteColor) -> &mut Color {
&mut self.basic[palette_color]
}
}
impl IndexMut<PaletteStyle> for Palette {
fn index_mut(&mut self, palette_style: PaletteStyle) -> &mut Style {
&mut self.styles[palette_style]
}
}
fn default_styles() -> EnumMap<PaletteStyle, Style> {
use self::PaletteStyle::*;
use crate::theme::{ColorStyle, Effect};
enum_map! {
Shadow => ColorStyle::shadow().into(),
Primary => ColorStyle::primary().into(),
Secondary => ColorStyle::secondary().into(),
Tertiary => ColorStyle::tertiary().into(),
View => ColorStyle::view().into(),
Background => ColorStyle::background().into(),
TitlePrimary => ColorStyle::title_primary().into(),
TitleSecondary => ColorStyle::title_secondary().into(),
Highlight => Style {
color: ColorStyle::highlight().invert(),
effects: enumset::enum_set!(Effect::Reverse),
},
HighlightInactive => Style {
color: ColorStyle::highlight_inactive().invert(),
effects: enumset::enum_set!(Effect::Reverse),
},
}
}
impl Palette {
pub fn terminal_default() -> Self {
use self::PaletteColor::*;
use crate::theme::Color::TerminalDefault;
Palette {
basic: enum_map! {
Background => TerminalDefault,
Shadow => TerminalDefault,
View => TerminalDefault,
Primary => TerminalDefault,
Secondary => TerminalDefault,
Tertiary => TerminalDefault,
TitlePrimary => TerminalDefault,
TitleSecondary => TerminalDefault,
Highlight => TerminalDefault,
HighlightInactive => TerminalDefault,
HighlightText => TerminalDefault,
},
custom: HashMap::default(),
styles: default_styles(),
}
}
pub fn retro() -> Self {
use self::PaletteColor::*;
use crate::theme::BaseColor::*;
use crate::theme::Color::*;
Palette {
basic: enum_map! {
Background => Dark(Blue),
Shadow => Dark(Black),
View => Dark(White),
Primary => Dark(Black),
Secondary => Dark(Blue),
Tertiary => Light(White),
TitlePrimary => Dark(Red),
TitleSecondary => Light(Blue),
Highlight => Dark(Red),
HighlightInactive => Dark(Blue),
HighlightText => Dark(White),
},
custom: HashMap::default(),
styles: default_styles(),
}
}
pub fn custom<'a>(&'a self, key: &str) -> Option<&'a Color> {
self.custom.get(key).and_then(|node| {
if let PaletteNode::Color(ref color) = *node {
Some(color)
} else {
None
}
})
}
#[must_use]
pub fn merge(&self, namespace: &str) -> Self {
let mut result = self.clone();
if let Some(PaletteNode::Namespace(palette)) =
self.custom.get(namespace)
{
for (key, value) in palette.iter() {
match *value {
PaletteNode::Color(color) => result.set_color(key, color),
PaletteNode::Namespace(ref map) => {
result.add_namespace(key, map.clone())
}
}
}
}
result
}
pub fn set_color(&mut self, key: &str, color: Color) {
if self.set_basic_color(key, color).is_err() {
self.custom
.insert(key.to_string(), PaletteNode::Color(color));
}
}
pub fn set_basic_color(
&mut self,
key: &str,
color: Color,
) -> Result<(), NoSuchColor> {
PaletteColor::from_str(key).map(|c| self.basic[c] = color)
}
pub fn add_namespace(
&mut self,
key: &str,
namespace: HashMap<String, PaletteNode>,
) {
self.custom
.insert(key.to_string(), PaletteNode::Namespace(namespace));
}
#[cfg(feature = "toml")]
pub(crate) fn load_toml(&mut self, table: &toml::value::Table) {
for (key, value) in iterate_toml_colors(table) {
match value {
PaletteNode::Color(color) => self.set_color(key, color),
PaletteNode::Namespace(map) => self.add_namespace(key, map),
}
}
}
#[cfg(feature = "toml")]
pub(crate) fn load_toml_styles(&mut self, table: &toml::value::Table) {
for (key, value) in table {
let key = match key.parse() {
Ok(key) => key,
_ => {
log::warn!("Found unknown palette style: `{key}`.");
continue;
}
};
let value = match Style::parse(value) {
Some(value) => value,
_ => {
log::warn!("Could not parse style: `{value}`.");
continue;
}
};
self.styles[key] = value;
}
}
}
impl Extend<(PaletteColor, Color)> for Palette {
fn extend<T>(&mut self, iter: T)
where
T: IntoIterator<Item = (PaletteColor, Color)>,
{
for (k, v) in iter {
(*self)[k] = v;
}
}
}
impl Default for Palette {
fn default() -> Palette {
Palette::retro()
}
}
#[cfg(feature = "toml")]
fn iterate_toml_colors(
table: &toml::value::Table,
) -> impl Iterator<Item = (&str, PaletteNode)> {
table.iter().flat_map(|(key, value)| {
let node = match value {
toml::Value::Table(table) => {
let map = iterate_toml_colors(table)
.map(|(key, value)| (key.to_string(), value))
.collect();
Some(PaletteNode::Namespace(map))
}
toml::Value::Array(colors) => {
colors
.iter()
.flat_map(toml::Value::as_str)
.flat_map(Color::parse)
.map(PaletteNode::Color)
.next()
}
toml::Value::String(color) => {
Color::parse(color).map(PaletteNode::Color)
}
other => {
warn!(
"Found unexpected value in theme: {} = {:?}",
key, other
);
None
}
};
node.map(|node| (key.as_str(), node))
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Enum)]
pub enum PaletteColor {
Background,
Shadow,
View,
Primary,
Secondary,
Tertiary,
TitlePrimary,
TitleSecondary,
Highlight,
HighlightInactive,
HighlightText,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Enum)]
pub enum PaletteStyle {
Primary,
Secondary,
Tertiary,
View,
Background,
TitlePrimary,
TitleSecondary,
Highlight,
HighlightInactive,
Shadow,
}
impl PaletteStyle {
pub fn resolve(self, palette: &Palette) -> Style {
palette[self]
}
pub fn all() -> impl Iterator<Item = Self> {
(0..Self::LENGTH).map(Self::from_usize)
}
}
impl PaletteColor {
pub fn resolve(self, palette: &Palette) -> Color {
palette[self]
}
pub fn all() -> impl Iterator<Item = Self> {
(0..Self::LENGTH).map(Self::from_usize)
}
}
impl FromStr for PaletteStyle {
type Err = NoSuchColor;
fn from_str(s: &str) -> Result<Self, NoSuchColor> {
use PaletteStyle::*;
Ok(match s {
"Background" | "background" => Background,
"Shadow" | "shadow" => Shadow,
"View" | "view" => View,
"Primary" | "primary" => Primary,
"Secondary" | "secondary" => Secondary,
"Tertiary" | "tertiary" => Tertiary,
"TitlePrimary" | "title_primary" => TitlePrimary,
"TitleSecondary" | "title_secondary" => TitleSecondary,
"Highlight" | "highlight" => Highlight,
"HighlightInactive" | "highlight_inactive" => HighlightInactive,
_ => return Err(NoSuchColor),
})
}
}
impl FromStr for PaletteColor {
type Err = NoSuchColor;
fn from_str(s: &str) -> Result<Self, NoSuchColor> {
use PaletteColor::*;
Ok(match s {
"Background" | "background" => Background,
"Shadow" | "shadow" => Shadow,
"View" | "view" => View,
"Primary" | "primary" => Primary,
"Secondary" | "secondary" => Secondary,
"Tertiary" | "tertiary" => Tertiary,
"TitlePrimary" | "title_primary" => TitlePrimary,
"TitleSecondary" | "title_secondary" => TitleSecondary,
"Highlight" | "highlight" => Highlight,
"HighlightInactive" | "highlight_inactive" => HighlightInactive,
"HighlightText" | "highlight_text" => HighlightText,
_ => return Err(NoSuchColor),
})
}
}