Skip to content

Commit

Permalink
Implement all of theming, in a better way.
Browse files Browse the repository at this point in the history
  • Loading branch information
jerzywilczek committed Oct 5, 2023
1 parent 19e36b1 commit 908580b
Show file tree
Hide file tree
Showing 10 changed files with 234 additions and 252 deletions.
7 changes: 4 additions & 3 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use regex::Regex;
use sysinfo::{CpuExt, Pid, Process, ProcessExt, System, SystemExt};
use systemstat::{BlockDeviceStats, Platform};

use crate::ui::processes::Column;
use crate::{config::Config, ui::processes::Column};

/// Application result type.
pub type AppResult<T> = std::result::Result<T, Box<dyn error::Error>>;
Expand Down Expand Up @@ -168,6 +168,7 @@ pub struct App {
/// Is the application running?
pub running: bool,
pub input_state: InputState,
pub config: Config,

pub cpu_history: Vec<VecDeque<f64>>,
pub mem_history: VecDeque<f64>,
Expand All @@ -185,9 +186,8 @@ pub struct App {
}

impl App {
#[allow(clippy::new_without_default)]
/// Constructs a new instance of [`App`].
pub fn new() -> Self {
pub fn new(config: Config) -> Self {
let mut system = sysinfo::System::new();
let systemstat = systemstat::System::new();
system.refresh_cpu();
Expand Down Expand Up @@ -224,6 +224,7 @@ impl App {
Self {
running: true,
input_state: Default::default(),
config,
cpu_history,
mem_history,
mem_total,
Expand Down
39 changes: 26 additions & 13 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
mod color;
mod theme;

use std::{ffi::OsString, path::PathBuf};
use std::path::PathBuf;

use anyhow::{Context, Result};
use anyhow::{anyhow, Context, Result};
use serde::{Deserialize, Serialize};

pub use color::RgbColor;
pub use color::SerdeColor;
pub use theme::*;

#[derive(clap::Parser)]
Expand All @@ -32,7 +32,7 @@ pub struct Config {

impl Config {
pub fn load(cli: &Cli) -> Result<Self> {
let Some(config_dir_path) = config_path(cli) else {
let Some(config_dir_path) = config_path(cli)? else {
return Ok(Default::default());
};

Expand Down Expand Up @@ -61,34 +61,47 @@ impl Config {
});
};

let theme = Theme::load_from_file(&config_dir_path.join("themes").join(theme))?;
let theme = if theme == "default" {
Theme::default()
} else {
Theme::load_from_file(&config_dir_path.join("themes").join(format!("{theme}.toml")))?
};

Ok(Self { theme })
}
}

#[derive(Debug, Serialize, Deserialize, Clone, Default)]
struct RawConfig {
theme: Option<OsString>,
theme: Option<String>,
}

pub fn sample_config() -> String {
toml::to_string_pretty(&RawConfig {
theme: Some("theme name (has to correspond with a valid theme file located in <config path>/themes/<theme name>.toml)".into())
}).unwrap()
theme: Some("default".into()),
})
.unwrap()
}

pub fn config_path(cli: &Cli) -> Option<PathBuf> {
pub fn config_path(cli: &Cli) -> Result<Option<PathBuf>> {
if let Some(ref path) = cli.config_path {
if path.exists() {
return Some(path.clone());
return Ok(Some(path.clone()));
} else {
return Err(anyhow!(
"The config path passed in the cli option does not exist"
));
}
}

if let Ok(path) = std::env::var("JWTOP_CONFIG_DIR") {
let path: PathBuf = path.into();
if path.exists() {
return path.into();
return Ok(path.into());
} else {
return Err(anyhow!(
"The config path passed in the environment variable does not exist"
));
}
}

Expand All @@ -98,8 +111,8 @@ pub fn config_path(cli: &Cli) -> Option<PathBuf> {
.to_path_buf();

if path.exists() {
return Some(path);
return Ok(Some(path));
}

None
Ok(None)
}
42 changes: 26 additions & 16 deletions src/config/color.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,35 @@
use tui::style::Color;

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RgbColor(pub u8, pub u8, pub u8);
pub struct SerdeColor(pub Color);

impl std::ops::Deref for SerdeColor {
type Target = Color;

fn deref(&self) -> &Self::Target {
&self.0
}
}

impl serde::Serialize for RgbColor {
impl serde::Serialize for SerdeColor {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&format!("#{:02x}{:02x}{:02x}", self.0, self.1, self.2))
let Color::Rgb(r, g, b) = self.0 else {
return Err(serde::ser::Error::custom(
"only rgb colors are serializable",
));
};

serializer.serialize_str(&format!("#{:02x}{:02x}{:02x}", r, g, b))
}
}

struct RgbColorVisitor;

impl<'de> serde::de::Visitor<'de> for RgbColorVisitor {
type Value = RgbColor;
type Value = SerdeColor;

fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a string containing a hex color value looking like this: #rrggbb or like this: #RRGGBB")
Expand Down Expand Up @@ -60,11 +76,11 @@ impl<'de> serde::de::Visitor<'de> for RgbColorVisitor {
let g = color([v[2], v[3]])?;
let b = color([v[4], v[5]])?;

Ok(RgbColor(r, g, b))
Ok(SerdeColor(Color::Rgb(r, g, b)))
}
}

impl<'de> serde::Deserialize<'de> for RgbColor {
impl<'de> serde::Deserialize<'de> for SerdeColor {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
Expand All @@ -73,32 +89,26 @@ impl<'de> serde::Deserialize<'de> for RgbColor {
}
}

impl From<RgbColor> for tui::style::Color {
fn from(value: RgbColor) -> Self {
tui::style::Color::Rgb(value.0, value.1, value.2)
}
}

#[cfg(test)]
mod tests {
use super::*;

#[derive(Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
struct Wrapper {
color: RgbColor,
color: SerdeColor,
}

#[test]
fn color_de() {
assert_eq!(
Wrapper {
color: RgbColor(0xaa, 0xbb, 0xcc)
color: SerdeColor(tui::style::Color::Rgb(0xaa, 0xbb, 0xcc))
},
toml::from_str("color = \"#AABBCC\"").unwrap()
);
assert_eq!(
Wrapper {
color: RgbColor(0xdd, 0xee, 0xff)
color: SerdeColor(tui::style::Color::Rgb(0xdd, 0xee, 0xff))
},
toml::from_str("color = \"#ddeeff\"").unwrap()
);
Expand All @@ -107,7 +117,7 @@ mod tests {
#[test]
fn both_ways() {
let val = Wrapper {
color: RgbColor(12, 240, 144),
color: SerdeColor(tui::style::Color::Rgb(12, 240, 144)),
};
assert_eq!(
val,
Expand Down
Loading

0 comments on commit 908580b

Please sign in to comment.