From 6ca07d6af8a338e76817d06c6c6c6f13e64fba9c Mon Sep 17 00:00:00 2001 From: Nathan Reiner Date: Fri, 26 Jul 2024 10:32:55 +0200 Subject: add neosheetrc support --- src/config/theme/colorpair.rs | 106 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 src/config/theme/colorpair.rs (limited to 'src/config/theme/colorpair.rs') diff --git a/src/config/theme/colorpair.rs b/src/config/theme/colorpair.rs new file mode 100644 index 0000000..77e6af4 --- /dev/null +++ b/src/config/theme/colorpair.rs @@ -0,0 +1,106 @@ +use std::str::FromStr; + +use mlua::{FromLua, IntoLua}; +use ratatui::style::{Color, Styled, Stylize}; + +#[derive(Clone)] +pub struct ColorPair { + pub fg: Color, + pub bg: Color, +} + +impl ColorPair { + pub const fn new(fg: Color, bg: Color) -> Self { + ColorPair { bg, fg } + } + + pub fn apply(&self, s: S) -> ::Item + where + S: Styled, + I: Styled, + { + s.bg(self.bg).fg(self.fg) + } +} + +impl<'lua> FromLua<'lua> for ColorPair { + fn from_lua( + value: mlua::prelude::LuaValue<'lua>, + _lua: &'lua mlua::prelude::Lua, + ) -> mlua::prelude::LuaResult { + if value.is_table() { + let table = value.as_table().unwrap(); + if let Ok(fg) = table.get::<_, LuaColor>(1) { + if let Ok(bg) = table.get::<_, LuaColor>(2) { + return Ok(ColorPair::new(fg.into(), bg.into())); + } + } else if let Ok(fg) = table.get::<_, LuaColor>("fg") { + if let Ok(bg) = table.get::<_, LuaColor>("bg") { + return Ok(ColorPair::new(fg.into(), bg.into())); + } + } + } + + return Err(mlua::Error::runtime("could not parse colorpair")); + } +} + +impl<'lua> IntoLua<'lua> for ColorPair { + fn into_lua( + self, + lua: &'lua mlua::prelude::Lua, + ) -> mlua::prelude::LuaResult> { + let table = lua.create_table()?; + table.set("fg", LuaColor::from(self.fg))?; + table.set("bg", LuaColor::from(self.bg))?; + Ok(table.into_lua(lua)?) + } +} + +struct LuaColor { + color: Color, +} + +impl LuaColor { + fn new(color: Color) -> Self { + Self { color } + } +} + +impl From for LuaColor { + fn from(value: Color) -> Self { + LuaColor::new(value) + } +} + +impl Into for LuaColor { + fn into(self) -> Color { + self.color + } +} + +impl<'lua> FromLua<'lua> for LuaColor { + fn from_lua( + value: mlua::prelude::LuaValue<'lua>, + _lua: &'lua mlua::prelude::Lua, + ) -> mlua::prelude::LuaResult { + if value.is_string() { + let str = value.as_str().unwrap(); + match Color::from_str(str) { + Ok(color) => Ok(color.into()), + Err(_) => Err(mlua::Error::runtime("color has wrong format")), + } + } else { + Err(mlua::Error::runtime("color has wrong format")) + } + } +} + +impl<'lua> IntoLua<'lua> for LuaColor { + fn into_lua( + self, + lua: &'lua mlua::prelude::Lua, + ) -> mlua::prelude::LuaResult> { + Ok(self.color.to_string().to_lowercase().into_lua(lua)?) + } +} -- cgit v1.2.3-70-g09d2