1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
//! Bar configuration state.
//!
//! This module contains everything required to express the any state of the bar. The root
//! element ([`Config`]) can be accessed through the [`Bar`] using the [`load`] and [`lock`] methods.
//!
//! # Examples
//!
//! ```
//! use bar_config::Bar;
//! use std::io::Cursor;
//!
//! let config_file = Cursor::new(String::from(
//!     "height: 30\n\
//!      monitors:\n\
//!       - { name: \"DVI-1\" }"
//! ));
//!
//! let bar = Bar::load(config_file).unwrap();
//! let config = bar.lock();
//!
//! assert_eq!(config.height, 30);
//! assert_eq!(config.monitors.len(), 1);
//! assert_eq!(config.monitors[0].name, "DVI-1");
//! ```
//!
//! [`Config`]: struct.Config.html
//! [`Bar`]: ../struct.Bar.html
//! [`load`]: ../struct.Bar.html#method.load
//! [`lock`]: ../struct.Bar.html#method.lock

use serde::de::{Deserializer, Error};
use serde::Deserialize;

use std::path::{Path, PathBuf};

use crate::components::Component;

/// Root element of the bar configuration.
///
/// This element contains the complete state of the bar necessary to render it.
#[derive(Debug, Deserialize)]
pub struct Config {
    pub height: u8,
    pub position: Option<Position>,
    pub background: Option<Background>,
    #[serde(
        deserialize_with = "deserialize_monitors",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub monitors: Vec<Monitor>,
    pub defaults: Option<ComponentSettings>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub left: Vec<Box<Component>>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub center: Vec<Box<Component>>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub right: Vec<Box<Component>>,
}

// Require at least one monitor
fn deserialize_monitors<'a, D>(deserializer: D) -> Result<Vec<Monitor>, D::Error>
where
    D: Deserializer<'a>,
{
    match Vec::<Monitor>::deserialize(deserializer) {
        Ok(monitors) => {
            if monitors.is_empty() {
                Err(D::Error::custom(String::from(
                    "at least one monitor is required",
                )))
            } else {
                Ok(monitors)
            }
        }
        err => err,
    }
}

/// Default options available for every component.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Deserialize)]
pub struct ComponentSettings {
    pub foreground: Option<Color>,
    pub background: Option<Background>,
    pub width: Option<u8>,
    pub padding: Option<u8>,
    pub offset_x: Option<i8>,
    pub offset_y: Option<i8>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fonts: Vec<Font>,
    pub border: Option<Border>,
}

/// Background of a component or the bar.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum Background {
    Image(PathBuf),
    Color(Color),
}

impl<'de> Deserialize<'de> for Background {
    fn deserialize<D>(deserializer: D) -> Result<Background, D::Error>
    where
        D: Deserializer<'de>,
    {
        match String::deserialize(deserializer) {
            Ok(text) => {
                if text.starts_with('#') {
                    Color::from_str(&text)
                        .map_err(D::Error::custom)
                        .map(Background::Color)
                } else {
                    Path::new(&text)
                        .canonicalize()
                        .map_err(D::Error::custom)
                        .map(Background::Image)
                }
            }
            Err(err) => Err(err),
        }
    }
}

/// Distinct identification for a font.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Deserialize)]
pub struct Font {
    pub description: String,
    pub size: u8,
}

/// Distinct identification for a monitor.
///
/// The [`fallback_names`] can be used to specify alternative screens which should be used when the
/// primary monitor is not available.
///
/// [`fallback_names`]: #structfield.fallback_names
#[derive(Clone, Debug, Eq, PartialEq, Hash, Deserialize)]
pub struct Monitor {
    pub name: String,
    #[serde(default)]
    pub fallback_names: Vec<String>,
}

/// Border separating the bar from the rest of the WM.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Deserialize)]
pub struct Border {
    pub height: u8,
    pub color: Color,
}

/// Available positions for the bar.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Deserialize)]
pub enum Position {
    Top,
    Bottom,
}

/// RGBA color specified as four values from 0 to 255.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct Color {
    r: u8,
    g: u8,
    b: u8,
    a: u8,
}

impl Color {
    fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
        Color { r, g, b, a }
    }

    // Deserialize the `#ff00ff` and `#ff00ff00` color formats
    fn from_str(string: &str) -> Result<Self, String> {
        if !string.starts_with('#') || (string.len() != 7 && string.len() != 9) {
            return Err(String::from(
                "colors need to follow the format `#RRGGBB` or `#RRGGBBAA`",
            ));
        }

        let radix_error =
            |_| String::from("hexadecimal color digits need to be within the range 0..=F");
        let r = u8::from_str_radix(&string[1..3], 16).map_err(radix_error)?;
        let g = u8::from_str_radix(&string[3..5], 16).map_err(radix_error)?;
        let b = u8::from_str_radix(&string[5..7], 16).map_err(radix_error)?;
        let a = if string.len() == 9 {
            u8::from_str_radix(&string[7..9], 16).map_err(radix_error)?
        } else {
            255
        };

        Ok(Color::new(r, g, b, a))
    }
}

// Format the color in the format `#RRGGBBAA`
impl ToString for Color {
    fn to_string(&self) -> String {
        format!("#{:02x}{:02x}{:02x}{:02x}", self.r, self.g, self.b, self.a)
    }
}

impl<'de> Deserialize<'de> for Color {
    fn deserialize<D>(deserializer: D) -> Result<Color, D::Error>
    where
        D: Deserializer<'de>,
    {
        match String::deserialize(deserializer) {
            Ok(color_string) => Color::from_str(&color_string).map_err(D::Error::custom),
            Err(err) => Err(err),
        }
    }
}