//! Rosé Pine palettes and ANSI painting with truecolor / 256-colour fallback.
use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Rgb(pub u8, pub u8, pub u8);
impl Rgb {
pub const fn hex(v: u32) -> Rgb {
Rgb(
((v >> 16) & 0xff) as u8,
((v >> 8) & 0xff) as u8,
(v & 0xff) as u8,
)
}
pub fn css(self) -> String {
format!("#{:02x}{:02x}{:02x}", self.0, self.1, self.2)
}
/// Nearest xterm-256 index (colour cube or grey ramp).
pub fn to_256(self) -> u8 {
let Rgb(r, g, b) = self;
let cube = |c: u8| -> u8 {
if c < 48 {
0
} else if c < 115 {
1
} else {
((c as u16 - 35) / 40) as u8
}
};
let (ri, gi, bi) = (cube(r), cube(g), cube(b));
let levels = [0u8, 95, 135, 175, 215, 255];
let (cr, cg, cb) = (
levels[ri as usize],
levels[gi as usize],
levels[bi as usize],
);
let cube_idx = 16 + 36 * ri + 6 * gi + bi;
let avg = (r as u16 + g as u16 + b as u16) / 3;
let grey_idx = if avg > 238 {
23
} else {
((avg.saturating_sub(3)) / 10) as u8
};
let grey_val = 8 + 10 * grey_idx as u16;
let d_cube = (r as i32 - cr as i32).pow(2)
+ (g as i32 - cg as i32).pow(2)
+ (b as i32 - cb as i32).pow(2);
let d_grey = (r as i32 - grey_val as i32).pow(2)
+ (g as i32 - grey_val as i32).pow(2)
+ (b as i32 - grey_val as i32).pow(2);
if d_grey < d_cube {
232 + grey_idx
} else {
cube_idx
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Variant {
Main,
Moon,
Dawn,
}
impl Variant {
pub fn parse(s: &str) -> Option<Variant> {
match s.trim().to_ascii_lowercase().replace('_', "-").as_str() {
"rose-pine" | "rosepine" | "main" | "rose-pine-main" | "rosé-pine" => {
Some(Variant::Main)
}
"rose-pine-moon" | "moon" => Some(Variant::Moon),
"rose-pine-dawn" | "dawn" | "light" => Some(Variant::Dawn),
_ => None,
}
}
pub fn name(self) -> &'static str {
match self {
Variant::Main => "rose-pine",
Variant::Moon => "rose-pine-moon",
Variant::Dawn => "rose-pine-dawn",
}
}
pub fn is_light(self) -> bool {
matches!(self, Variant::Dawn)
}
/// Try to match the Omarchy desktop theme currently in use.
pub fn from_system() -> Option<Variant> {
if let Ok(v) = std::env::var("PERCIVAL_THEME") {
if let Some(var) = Variant::parse(&v) {
return Some(var);
}
}
let home = std::env::var_os("HOME")?;
let link = std::path::Path::new(&home).join(".config/omarchy/current/theme");
let target = std::fs::read_link(&link).ok()?;
let name = target.file_name()?.to_string_lossy().to_ascii_lowercase();
if name.contains("rose") || name.contains("rosé") {
if name.contains("dawn") {
Some(Variant::Dawn)
} else if name.contains("moon") {
Some(Variant::Moon)
} else {
Some(Variant::Main)
}
} else {
None
}
}
}
/// The Rosé Pine palette (https://rosepinetheme.com/palette).
#[derive(Clone, Copy, Debug)]
pub struct Palette {
pub base: Rgb,
pub surface: Rgb,
pub overlay: Rgb,
pub muted: Rgb,
pub subtle: Rgb,
pub text: Rgb,
pub love: Rgb,
pub gold: Rgb,
pub rose: Rgb,
pub pine: Rgb,
pub foam: Rgb,
pub iris: Rgb,
pub hl_low: Rgb,
pub hl_med: Rgb,
pub hl_high: Rgb,
}
impl Palette {
pub const fn main() -> Palette {
Palette {
base: Rgb::hex(0x191724),
surface: Rgb::hex(0x1f1d2e),
overlay: Rgb::hex(0x26233a),
muted: Rgb::hex(0x6e6a86),
subtle: Rgb::hex(0x908caa),
text: Rgb::hex(0xe0def4),
love: Rgb::hex(0xeb6f92),
gold: Rgb::hex(0xf6c177),
rose: Rgb::hex(0xebbcba),
pine: Rgb::hex(0x31748f),
foam: Rgb::hex(0x9ccfd8),
iris: Rgb::hex(0xc4a7e7),
hl_low: Rgb::hex(0x21202e),
hl_med: Rgb::hex(0x403d52),
hl_high: Rgb::hex(0x524f67),
}
}
pub const fn moon() -> Palette {
Palette {
base: Rgb::hex(0x232136),
surface: Rgb::hex(0x2a273f),
overlay: Rgb::hex(0x393552),
muted: Rgb::hex(0x6e6a86),
subtle: Rgb::hex(0x908caa),
text: Rgb::hex(0xe0def4),
love: Rgb::hex(0xeb6f92),
gold: Rgb::hex(0xf6c177),
rose: Rgb::hex(0xea9a97),
pine: Rgb::hex(0x3e8fb0),
foam: Rgb::hex(0x9ccfd8),
iris: Rgb::hex(0xc4a7e7),
hl_low: Rgb::hex(0x2a283e),
hl_med: Rgb::hex(0x44415a),
hl_high: Rgb::hex(0x56526e),
}
}
pub const fn dawn() -> Palette {
Palette {
base: Rgb::hex(0xfaf4ed),
surface: Rgb::hex(0xfffaf3),
overlay: Rgb::hex(0xf2e9e1),
muted: Rgb::hex(0x9893a5),
subtle: Rgb::hex(0x797593),
text: Rgb::hex(0x575279),
love: Rgb::hex(0xb4637a),
gold: Rgb::hex(0xea9d34),
rose: Rgb::hex(0xd7827e),
pine: Rgb::hex(0x286983),
foam: Rgb::hex(0x56949f),
iris: Rgb::hex(0x907aa9),
hl_low: Rgb::hex(0xf4ede8),
hl_med: Rgb::hex(0xdfdad9),
hl_high: Rgb::hex(0xcecacd),
}
}
pub fn for_variant(v: Variant) -> Palette {
match v {
Variant::Main => Palette::main(),
Variant::Moon => Palette::moon(),
Variant::Dawn => Palette::dawn(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColorMode {
None,
Ansi256,
Truecolor,
}
impl ColorMode {
pub fn detect(stdout_is_tty: bool, force_off: bool) -> ColorMode {
if force_off || std::env::var_os("NO_COLOR").is_some() {
return ColorMode::None;
}
let forced = std::env::var("CLICOLOR_FORCE")
.map(|v| v != "0")
.unwrap_or(false);
if !stdout_is_tty && !forced {
return ColorMode::None;
}
let colorterm = std::env::var("COLORTERM")
.unwrap_or_default()
.to_ascii_lowercase();
let term = std::env::var("TERM")
.unwrap_or_default()
.to_ascii_lowercase();
if colorterm.contains("truecolor")
|| colorterm.contains("24bit")
|| term.contains("kitty")
|| term.contains("alacritty")
|| term.contains("ghostty")
|| term.contains("foot")
|| term.contains("wezterm")
{
ColorMode::Truecolor
} else if term == "dumb" {
ColorMode::None
} else {
ColorMode::Ansi256
}
}
}
/// A painter bound to a palette and colour mode.
#[derive(Clone, Copy, Debug)]
pub struct Theme {
pub variant: Variant,
pub p: Palette,
pub mode: ColorMode,
}
impl Theme {
pub fn new(variant: Variant, mode: ColorMode) -> Theme {
Theme {
variant,
p: Palette::for_variant(variant),
mode,
}
}
pub fn plain() -> Theme {
Theme::new(Variant::Main, ColorMode::None)
}
pub fn enabled(&self) -> bool {
self.mode != ColorMode::None
}
/// Raw foreground escape for a colour (empty when colour is off).
pub fn seq(&self, c: Rgb) -> String {
self.fg(c)
}
fn fg(&self, c: Rgb) -> String {
match self.mode {
ColorMode::None => String::new(),
ColorMode::Ansi256 => format!("\x1b[38;5;{}m", c.to_256()),
ColorMode::Truecolor => format!("\x1b[38;2;{};{};{}m", c.0, c.1, c.2),
}
}
pub fn paint(&self, c: Rgb, s: impl fmt::Display) -> String {
if !self.enabled() {
return s.to_string();
}
format!("{}{s}\x1b[0m", self.fg(c))
}
pub fn paint_bold(&self, c: Rgb, s: impl fmt::Display) -> String {
if !self.enabled() {
return s.to_string();
}
format!("\x1b[1m{}{s}\x1b[0m", self.fg(c))
}
pub fn bold(&self, s: impl fmt::Display) -> String {
if !self.enabled() {
return s.to_string();
}
format!("\x1b[1m{s}\x1b[0m")
}
pub fn dim(&self, s: impl fmt::Display) -> String {
self.paint(self.p.muted, s)
}
// Semantic helpers.
pub fn text(&self, s: impl fmt::Display) -> String {
self.paint(self.p.text, s)
}
pub fn subtle(&self, s: impl fmt::Display) -> String {
self.paint(self.p.subtle, s)
}
pub fn found(&self, s: impl fmt::Display) -> String {
self.paint_bold(self.p.foam, s)
}
pub fn warn(&self, s: impl fmt::Display) -> String {
self.paint_bold(self.p.gold, s)
}
pub fn error(&self, s: impl fmt::Display) -> String {
self.paint_bold(self.p.love, s)
}
pub fn link(&self, s: impl fmt::Display) -> String {
self.paint(self.p.iris, s)
}
pub fn accent(&self, s: impl fmt::Display) -> String {
self.paint(self.p.rose, s)
}
pub fn info(&self, s: impl fmt::Display) -> String {
self.paint(self.p.pine, s)
}
pub fn category(&self, s: impl fmt::Display) -> String {
self.paint(self.p.gold, s)
}
pub fn heading(&self, s: impl fmt::Display) -> String {
self.paint_bold(self.p.iris, s)
}
pub fn rule(&self, width: usize) -> String {
self.paint(self.p.hl_high, "─".repeat(width))
}
/// indicatif template colour spec (256-colour indices).
pub fn bar_style(&self) -> String {
format!("{}/{}", self.p.iris.to_256(), self.p.hl_high.to_256())
}
pub fn spinner_color(&self) -> String {
self.p.iris.to_256().to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn palette_and_modes() {
assert_eq!(Rgb::hex(0xc4a7e7), Rgb(0xc4, 0xa7, 0xe7));
assert_eq!(Rgb::hex(0xc4a7e7).css(), "#c4a7e7");
assert_eq!(Rgb(0, 0, 0).to_256(), 16);
assert_eq!(Rgb(255, 255, 255).to_256(), 231);
assert!(Rgb(128, 128, 128).to_256() >= 232);
let t = Theme::new(Variant::Main, ColorMode::Truecolor);
assert!(t.found("x").contains("38;2;156;207;216"));
let t = Theme::new(Variant::Dawn, ColorMode::Ansi256);
assert!(t.found("x").starts_with("\x1b[1m\x1b[38;5;"));
assert_eq!(Theme::plain().found("x"), "x");
assert_eq!(Variant::parse("Rose-Pine-Moon"), Some(Variant::Moon));
assert_eq!(Variant::parse("dawn"), Some(Variant::Dawn));
assert_eq!(Variant::parse("nope"), None);
assert_eq!(ColorMode::detect(false, false), ColorMode::None);
assert_eq!(ColorMode::detect(true, true), ColorMode::None);
}
}