use crate::config::Config;
use crate::segment::Segment;
use ansi_term::Style;
use ansi_term::{ANSIString, ANSIStrings};
use std::fmt;
pub struct Module<'a> {
config: Option<&'a toml::value::Table>,
name: String,
style: Style,
prefix: ModuleAffix,
segments: Vec<Segment>,
suffix: ModuleAffix,
}
impl<'a> Module<'a> {
pub fn new(name: &str, config: Option<&'a toml::value::Table>) -> Module<'a> {
Module {
config,
name: name.to_string(),
style: Style::default(),
prefix: ModuleAffix::default_prefix(name.to_string()),
segments: Vec::new(),
suffix: ModuleAffix::default_suffix(name.to_string()),
}
}
pub fn new_segment(&mut self, name: &str, value: &str) -> &mut Segment {
let mut segment = Segment::new(name);
segment.set_style(self.style);
segment.set_value(self.config_value(name).unwrap_or(value));
self.segments.push(segment);
self.segments.last_mut().unwrap()
}
pub fn is_empty(&self) -> bool {
self.segments.is_empty()
}
pub fn get_prefix(&mut self) -> &mut ModuleAffix {
&mut self.prefix
}
pub fn get_suffix(&mut self) -> &mut ModuleAffix {
&mut self.suffix
}
pub fn set_style<T>(&mut self, style: T) -> &mut Module<'a>
where
T: Into<Style>,
{
self.style = style.into();
self
}
pub fn ansi_strings(&self) -> Vec<ANSIString> {
let mut ansi_strings = self
.segments
.iter()
.map(|s| s.ansi_string())
.collect::<Vec<ANSIString>>();
ansi_strings.insert(0, self.prefix.ansi_string());
ansi_strings.push(self.suffix.ansi_string());
ansi_strings
}
pub fn to_string_without_prefix(&self) -> String {
ANSIStrings(&self.ansi_strings()[1..]).to_string()
}
fn config_value(&self, key: &str) -> Option<&str> {
self.config.and_then(|config| config.get_as_str(key))
}
pub fn config_value_i64(&self, key: &str) -> Option<i64> {
self.config.and_then(|config| config.get_as_i64(key))
}
pub fn config_value_bool(&self, key: &str) -> Option<bool> {
self.config.and_then(|config| config.get_as_bool(key))
}
}
impl<'a> fmt::Display for Module<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ansi_strings = self.ansi_strings();
write!(f, "{}", ANSIStrings(&ansi_strings))
}
}
pub struct ModuleAffix {
name: String,
style: Style,
value: String,
}
impl ModuleAffix {
pub fn default_prefix(name: String) -> ModuleAffix {
ModuleAffix {
name: format!("{}_prefix", name),
style: Style::default(),
value: "via ".to_string(),
}
}
pub fn default_suffix(name: String) -> ModuleAffix {
ModuleAffix {
name: format!("{}_suffix", name),
style: Style::default(),
value: " ".to_string(),
}
}
pub fn set_style<T>(&mut self, style: T) -> &mut ModuleAffix
where
T: Into<Style>,
{
self.style = style.into();
self
}
pub fn set_value<T>(&mut self, value: T) -> &mut ModuleAffix
where
T: Into<String>,
{
self.value = value.into();
self
}
pub fn ansi_string(&self) -> ANSIString {
self.style.paint(&self.value)
}
}
impl fmt::Display for ModuleAffix {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.ansi_string())
}
}