Merge pull request #38 from AdaShoelace/change-to-serde

Change to serde
This commit is contained in:
Mustafa Salih 2021-01-22 00:53:11 +03:00 committed by GitHub
commit 9525a10751
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 512 additions and 386 deletions

87
Cargo.lock generated
View File

@ -204,6 +204,12 @@ dependencies = [
"libdbus-sys", "libdbus-sys",
] ]
[[package]]
name = "dtoa"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88d7ed2934d741c6b37e33e3832298e8850b53fd2d2bea03873375596c7cea4e"
[[package]] [[package]]
name = "event-listener" name = "event-listener"
version = "2.5.1" version = "2.5.1"
@ -264,6 +270,12 @@ dependencies = [
"cfg-if 1.0.0", "cfg-if 1.0.0",
] ]
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.81" version = "0.2.81"
@ -408,6 +420,24 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "proc-macro2"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "991431c3519a3f36861882da93630ce66b52918dcf1b8e2fd66b397fc96f28df"
dependencies = [
"proc-macro2",
]
[[package]] [[package]]
name = "ref_slice" name = "ref_slice"
version = "1.2.0" version = "1.2.0"
@ -422,10 +452,12 @@ dependencies = [
"breadx", "breadx",
"chrono", "chrono",
"dbus", "dbus",
"lazy_static",
"minreq", "minreq",
"mpd", "mpd",
"nix 0.19.1", "nix 0.19.1",
"yaml-rust", "serde",
"serde_yaml",
] ]
[[package]] [[package]]
@ -434,6 +466,49 @@ version = "0.3.24"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda" checksum = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda"
[[package]]
name = "serde"
version = "1.0.120"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "166b2349061381baf54a58e4b13c89369feb0ef2eaa57198899e2312aac30aab"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.120"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ca2a8cb5805ce9e3b95435e3765b7b553cecc762d938d409434338386cb5775"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_yaml"
version = "0.8.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "971be8f6e4d4a47163b405a3df70d14359186f9ab0f3a3ec37df144ca1ce089f"
dependencies = [
"dtoa",
"linked-hash-map",
"serde",
"yaml-rust",
]
[[package]]
name = "syn"
version = "1.0.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc60a3d73ea6594cd712d830cc1f0390fd71542d8c8cd24e70cc54cdfd5e05d5"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]] [[package]]
name = "time" name = "time"
version = "0.1.44" version = "0.1.44"
@ -460,6 +535,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
[[package]]
name = "unicode-xid"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
[[package]] [[package]]
name = "vec-arena" name = "vec-arena"
version = "1.0.0" version = "1.0.0"
@ -517,9 +598,9 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]] [[package]]
name = "yaml-rust" name = "yaml-rust"
version = "0.4.4" version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39f0c922f1a334134dc2f7a8b67dc5d25f0735263feec974345ff706bcf20b0d" checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
dependencies = [ dependencies = [
"linked-hash-map", "linked-hash-map",
] ]

View File

@ -12,12 +12,15 @@ description = "a multi threaded status bar for dwm window manager for linux"
[dependencies] [dependencies]
chrono = "0.4" chrono = "0.4"
yaml-rust = "0.4"
minreq = "2.2.1" minreq = "2.2.1"
alsa = "0.4.3" alsa = "0.4.3"
nix = "0.19.1" nix = "0.19.1"
mpd = "0.0.12" mpd = "0.0.12"
dbus = "0.9.1" dbus = "0.9.1"
serde = {version = "1.0.120", features = ["derive"]}
serde_yaml = "0.8.15"
lazy_static = "1.4.0"
[dependencies.breadx] [dependencies.breadx]
version = "0.1.11" version = "0.1.11"

View File

@ -6,7 +6,7 @@ general:
seperator: '┃' seperator: '┃'
# Time always running, no enable option for this # Time always running, no enabled option for this
time: time:
icon: '' icon: ''
format: '%d %b, %I:%M:%S %p' format: '%d %b, %I:%M:%S %p'
@ -15,33 +15,33 @@ time:
memory: memory:
icon: '▦' icon: '▦'
enable: true enabled: true
delay: 2.0 delay: 2.0
disk: disk:
icon: '' icon: ''
enable: true enabled: true
delay: 120.0 delay: 120.0
battery: battery:
icon: '' icon: ''
enable: false enabled: false
source: 'BAT0' source: 'BAT0'
delay: 120.0 delay: 120.0
cpu_temperature: cpu_temperature:
icon: '' icon: ''
enable: true enabled: true
delay: 120.0 delay: 120.0
# cpu load average # cpu load average
loadavg: loadavg:
icon: '' icon: ''
enable: false enabled: false
delay: 2.0 delay: 2.0
@ -49,20 +49,20 @@ mpd:
icon: '' icon: ''
host: '127.0.0.1' host: '127.0.0.1'
port: '6600' port: '6600'
enable: false enabled: false
delay: 5.0 delay: 5.0
volume: volume:
icon: '' icon: ''
enable: true enabled: true
delay: 0.18 delay: 0.18
card: 'PULSE' card: 'PULSE'
spotify: spotify:
icon: '' icon: ''
enable: false enabled: false
delay: 0.5 delay: 0.5
@ -73,7 +73,7 @@ spotify:
# - if you have multiple formats and want to insert space between them use '+' instead. # - if you have multiple formats and want to insert space between them use '+' instead.
# - giving (city) a value is recommended. # - giving (city) a value is recommended.
weather: weather:
enable: true enabled: true
icon: '' icon: ''
city: '' city: ''
format: '%l:+%t' format: '%l:+%t'

View File

@ -1,281 +0,0 @@
use crate::types::*;
use std::fs::File;
use std::io::Error;
use std::io::Read;
use yaml_rust::{yaml, YamlLoader};
/*
this function is responsible to check if the rsblocks.yml file
exists to call parse_config to read it OTHERWISE
it will call load_defaults to load a hardcoded default configuration
it will always return a valid configuration inside a Result.
*/
pub fn load_config() -> Result<Config, Error> {
let yml_source = std::env::var("HOME").unwrap() + "/.config/rsblocks/rsblocks.yml";
let mut data = String::new();
let mut file = match File::open(&yml_source) {
Ok(file) => file,
Err(_) => {
eprintln!("{} file not found, loading defaults!", &yml_source);
return Ok(load_defaults());
}
};
file.read_to_string(&mut data)?;
// checking if rsblocks.yml is empty
let yml_content = match YamlLoader::load_from_str(&data) {
Ok(content) => {
if content.len() > 0 {
content[0].clone()
} else {
eprintln!("configuration file looks empty, loading defaults!");
return Ok(load_defaults());
}
}
_ => return Ok(load_defaults()),
};
let config = parse_config(&yml_content);
Ok(config)
}
/*
this is simply returns a hardcoded configuration as default
*/
fn load_defaults() -> Config {
Config {
seperator: String::from("|"),
time: Time {
format: String::from("%T"),
icon: String::from(""),
delay: 1.0,
},
memory: Memory {
icon: String::from(""),
enabled: true,
delay: 2.0,
},
disk: Disk {
icon: String::from(""),
enabled: false,
delay: 60.0,
},
volume: Volume {
icon: String::from(""),
enabled: false,
delay: 0.17,
card: String::from("ALSA"),
},
weather: Weather {
city: String::from(""),
format: String::from("+%t"),
icon: String::from(""),
enabled: false,
delay: 7200.0, //7200 seconds = 2 hours
},
battery: Battery {
source: String::from("BAT0"),
icon: String::from(""),
enabled: false,
delay: 120.0,
},
cpu_temperature: CpuTemp {
icon: String::from(""),
enabled: false,
delay: 120.0,
},
uptime: Uptime {
icon: String::from(""),
enabled: false,
delay: 60.0,
},
mpd: Mpd {
icon: String::from(""),
host: String::from("127.0.0.1"),
port: String::from("6600"),
enabled: false,
delay: 15.0,
},
spotify: Spotify {
icon: String::from(""),
enabled: false,
delay: 15.0,
},
loadavg: LoadAvg {
icon: String::from(""),
enabled: false,
delay: 60.0,
},
}
}
/*
it will read and parse the rsblocks.yml file content and return a valid configuration
IF some content is missing in the rsblocks.yml file, it will set
a default values to that.
NOTE: (get_or_set) functions job below getting the values from the configuration doc IF
a value is not exist in the config it will SET a value givin in the last argument.
*/
fn parse_config(doc: &yaml::Yaml) -> Config {
let seperator = get_or_set_string(doc, "general", "seperator", "|");
// time values
let time_icon = get_or_set_string(doc, "time", "icon", "");
let time_format = get_or_set_string(doc, "time", "format", "%T");
let time_delay = get_or_set_f64(doc, "time", "delay", 1.0);
// memory values
let mem_icon = get_or_set_string(doc, "memory", "icon", "");
let memory_enabled = get_or_set_bool(doc, "memory", "enable");
let memory_delay = get_or_set_f64(doc, "memory", "delay", 2.0);
//disk values
let disk_icon = get_or_set_string(doc, "disk", "icon", "");
let disk_enabled = get_or_set_bool(doc, "disk", "enable");
let disk_delay = get_or_set_f64(doc, "disk", "delay", 120.0);
// volume values
let volume_icon = get_or_set_string(doc, "volume", "icon", "");
let volume_enabled = get_or_set_bool(doc, "volume", "enable");
let volume_delay = get_or_set_f64(doc, "volume", "delay", 0.17);
let volume_card = get_or_set_string(doc, "volume", "card", "ALSA");
// weather values
let weather_icon = get_or_set_string(doc, "weather", "icon", "");
let weather_format = get_or_set_string(doc, "weather", "format", "%l:+%t");
let weather_city = get_or_set_string(doc, "weather", "city", "");
let weather_enabled = get_or_set_bool(doc, "weather", "enable");
let weather_delay = get_or_set_f64(doc, "weather", "delay", 7200.0);
// battery values
let battery_icon = get_or_set_string(doc, "battery", "icon", "");
let battery_enabled = get_or_set_bool(doc, "battery", "enable");
let battery_source = get_or_set_string(doc, "battery", "source", "BAT0");
let battery_delay = get_or_set_f64(doc, "battery", "delay", 120.0);
// cpu values
let cpu_temperature_icon = get_or_set_string(doc, "cpu_temperature", "icon", "");
let cpu_temperature_enabled = get_or_set_bool(doc, "cpu_temperature", "enable");
let cpu_temperature_delay = get_or_set_f64(doc, "cpu_temperature", "delay", 120.0);
// uptime values
let uptime_icon = get_or_set_string(doc, "uptime", "icon", "");
let uptime_enabled = get_or_set_bool(doc, "uptime", "enable");
let uptime_delay = get_or_set_f64(doc, "uptime", "delay", 60.0);
// mpd values
let mpd_icon = get_or_set_string(doc, "mpd", "icon", "");
let mpd_host = get_or_set_string(doc, "mpd", "host", "127.0.0.1");
let mpd_port = get_or_set_string(doc, "mpd", "port", "6600");
let mpd_enabled = get_or_set_bool(doc, "mpd", "enable");
let mpd_delay = get_or_set_f64(doc, "mpd", "delay", 15.0);
//spotify values
let spotify_icon = get_or_set_string(doc, "spotify", "icon", "");
let spotify_enabled = get_or_set_bool(doc, "spotify", "enable");
let spotify_delay = get_or_set_f64(doc, "spotify", "delay", 10.0);
//Load Avrage values
let loadavg_icon = get_or_set_string(doc, "loadavg", "icon", "");
let loadavg_enabled = get_or_set_bool(doc, "loadavg", "enable");
let loadavg_delay = get_or_set_f64(doc, "loadavg", "delay", 60.0);
Config {
seperator,
time: Time {
format: time_format,
icon: time_icon,
delay: time_delay,
},
memory: Memory {
icon: mem_icon,
enabled: memory_enabled,
delay: memory_delay,
},
disk: Disk {
icon: disk_icon,
enabled: disk_enabled,
delay: disk_delay,
},
volume: Volume {
icon: volume_icon,
enabled: volume_enabled,
delay: volume_delay,
card: volume_card,
},
weather: Weather {
city: weather_city,
format: weather_format,
icon: weather_icon,
enabled: weather_enabled,
delay: weather_delay,
},
battery: Battery {
source: battery_source,
icon: battery_icon,
enabled: battery_enabled,
delay: battery_delay,
},
cpu_temperature: CpuTemp {
icon: cpu_temperature_icon,
enabled: cpu_temperature_enabled,
delay: cpu_temperature_delay,
},
uptime: Uptime {
icon: uptime_icon,
enabled: uptime_enabled,
delay: uptime_delay,
},
mpd: Mpd {
icon: mpd_icon,
host: mpd_host,
port: mpd_port,
enabled: mpd_enabled,
delay: mpd_delay,
},
spotify: Spotify {
icon: spotify_icon,
enabled: spotify_enabled,
delay: spotify_delay,
},
loadavg: LoadAvg {
icon: loadavg_icon,
enabled: loadavg_enabled,
delay: loadavg_delay,
},
}
}
// getting a f64 value from rsblocks.yml file or set default (last argument)
fn get_or_set_f64(doc: &yaml::Yaml, parent: &str, child: &str, default: f64) -> f64 {
let val: f64 = if doc[parent][child].is_badvalue() {
default
} else {
doc[parent][child].as_f64().unwrap()
};
val
}
// getting a boolean value from rsblocks.yml file or set it false if it does not exist
fn get_or_set_bool(doc: &yaml::Yaml, parent: &str, child: &str) -> bool {
let val: bool;
if doc[parent][child].is_badvalue() {
val = false;
} else {
val = doc[parent][child].as_bool().unwrap()
}
val
}
// getting a String value from the rsblocks.yml file or set the default(last argument)
fn get_or_set_string(doc: &yaml::Yaml, parent: &str, child: &str, default_val: &str) -> String {
let val: String;
if doc[parent][child].is_badvalue() {
val = String::from(default_val)
} else {
val = String::from(doc[parent][child].as_str().unwrap());
}
val
}

21
src/config/battery.rs Normal file
View File

@ -0,0 +1,21 @@
use serde::{Deserialize, Serialize};
use std::default::Default;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Battery {
pub source: String,
pub icon: String,
pub enabled: bool,
pub delay: f64,
}
impl Default for Battery {
fn default() -> Self {
Battery {
source: String::from("BAT0"),
icon: String::from(""),
enabled: false,
delay: 120.0,
}
}
}

19
src/config/cputemp.rs Normal file
View File

@ -0,0 +1,19 @@
use serde::{Deserialize, Serialize};
use std::default::Default;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CpuTemp {
pub icon: String,
pub enabled: bool,
pub delay: f64,
}
impl Default for CpuTemp {
fn default() -> Self {
CpuTemp {
icon: String::from(""),
enabled: false,
delay: 120.0,
}
}
}

19
src/config/disk.rs Normal file
View File

@ -0,0 +1,19 @@
use serde::{Deserialize, Serialize};
use std::default::Default;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Disk {
pub icon: String,
pub enabled: bool,
pub delay: f64,
}
impl Default for Disk {
fn default() -> Self {
Disk {
icon: String::from(""),
enabled: false,
delay: 60.0,
}
}
}

19
src/config/loadavg.rs Normal file
View File

@ -0,0 +1,19 @@
use serde::{Deserialize, Serialize};
use std::default::Default;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LoadAvg {
pub icon: String,
pub enabled: bool,
pub delay: f64,
}
impl Default for LoadAvg {
fn default() -> Self {
LoadAvg {
icon: String::from(""),
enabled: false,
delay: 60.0,
}
}
}

19
src/config/memory.rs Normal file
View File

@ -0,0 +1,19 @@
use serde::{Deserialize, Serialize};
use std::default::Default;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Memory {
pub icon: String,
pub enabled: bool,
pub delay: f64,
}
impl Default for Memory {
fn default() -> Self {
Memory {
icon: String::from(""),
enabled: true,
delay: 2.0,
}
}
}

107
src/config/mod.rs Normal file
View File

@ -0,0 +1,107 @@
mod battery;
mod cputemp;
mod disk;
mod memory;
mod mpd;
mod time;
mod uptime;
mod volume;
mod weather;
mod spotify;
mod loadavg;
use self::mpd::Mpd;
use battery::Battery;
use cputemp::CpuTemp;
use disk::Disk;
use memory::Memory;
use time::Time;
use uptime::Uptime;
use volume::Volume;
use weather::Weather;
use spotify::Spotify;
use loadavg::LoadAvg;
use std::default::Default;
use std::fs::File;
use std::io::Read;
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
lazy_static! {
pub static ref CONFIG: Config = {
let yml_source = std::env::var("HOME").unwrap() + "/.config/rsblocks/rsblocks.yml";
let mut data = String::new();
match File::open(&yml_source) {
Ok(mut file) => {
file.read_to_string(&mut data).expect("Failed to read config to string");
serde_yaml::from_str(&data).expect("Failed to parse config")
}
Err(_) => Config::default(),
}
};
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Config {
#[serde(default = "default_seperator")]
pub seperator: String,
#[serde(default)]
pub time: Time,
#[serde(default)]
pub memory: Memory,
#[serde(default)]
pub disk: Disk,
#[serde(default)]
pub volume: Volume,
#[serde(default)]
pub weather: Weather,
#[serde(default)]
pub battery: Battery,
#[serde(default)]
pub cpu_temperature: CpuTemp,
#[serde(default)]
pub uptime: Uptime,
#[serde(default)]
pub mpd: Mpd,
#[serde(default)]
pub spotify: Spotify,
#[serde(default)]
pub loadavg: LoadAvg
}
impl Default for Config {
fn default() -> Self {
Self {
seperator: "|".to_string(),
time: Default::default(),
memory: Default::default(),
disk: Default::default(),
volume: Default::default(),
weather: Default::default(),
battery: Default::default(),
cpu_temperature: Default::default(),
uptime: Default::default(),
mpd: Default::default(),
spotify: Default::default(),
loadavg: Default::default()
}
}
}
fn default_seperator() -> String {
"|".to_string()
}

23
src/config/mpd.rs Normal file
View File

@ -0,0 +1,23 @@
use serde::{Deserialize, Serialize};
use std::default::Default;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Mpd {
pub icon: String,
pub host: String,
pub port: String,
pub enabled: bool,
pub delay: f64,
}
impl Default for Mpd {
fn default() -> Self {
Mpd {
icon: String::from(""),
host: String::from("127.0.0.1"),
port: String::from("6600"),
enabled: false,
delay: 15.0,
}
}
}

19
src/config/spotify.rs Normal file
View File

@ -0,0 +1,19 @@
use serde::{Deserialize, Serialize};
use std::default::Default;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Spotify {
pub icon: String,
pub enabled: bool,
pub delay: f64,
}
impl Default for Spotify {
fn default() -> Self {
Spotify {
icon: String::from(""),
enabled: false,
delay: 15.0,
}
}
}

19
src/config/time.rs Normal file
View File

@ -0,0 +1,19 @@
use serde::{Deserialize, Serialize};
use std::default::Default;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Time {
pub format: String,
pub icon: String,
pub delay: f64,
}
impl Default for Time {
fn default() -> Self {
Time {
format: String::from("%T"),
icon: String::from(""),
delay: 1.0,
}
}
}

19
src/config/uptime.rs Normal file
View File

@ -0,0 +1,19 @@
use serde::{Deserialize, Serialize};
use std::default::Default;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Uptime {
pub icon: String,
pub enabled: bool,
pub delay: f64,
}
impl Default for Uptime {
fn default() -> Self {
Uptime {
icon: String::from(""),
enabled: false,
delay: 60.0,
}
}
}

21
src/config/volume.rs Normal file
View File

@ -0,0 +1,21 @@
use serde::{Deserialize, Serialize};
use std::default::Default;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Volume {
pub icon: String,
pub enabled: bool,
pub delay: f64,
pub card: String,
}
impl Default for Volume {
fn default() -> Self {
Volume {
icon: String::from(""),
enabled: false,
delay: 0.17,
card: String::from("ALSA"),
}
}
}

23
src/config/weather.rs Normal file
View File

@ -0,0 +1,23 @@
use serde::{Deserialize, Serialize};
use std::default::Default;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Weather {
pub city: String,
pub format: String,
pub icon: String,
pub enabled: bool,
pub delay: f64,
}
impl Default for Weather {
fn default() -> Self {
Weather {
city: String::from(""),
format: String::from("+%t"),
icon: String::from(""),
enabled: false,
delay: 7200.0, //7200 seconds = 2 hours
}
}
}

View File

@ -5,13 +5,18 @@ mod utils;
use std::env; use std::env;
use std::process; use std::process;
use lazy_static::initialize;
fn main() { fn main() {
initialize(&config::CONFIG);
// if X display is not found then exit the program // if X display is not found then exit the program
if env::var("DISPLAY").is_err() { if env::var("DISPLAY").is_err() {
eprintln!("Error: No Display Running!"); eprintln!("Error: No Display Running!");
process::exit(1); process::exit(1);
}; };
let config = config::load_config().unwrap();
let blocks = types::Blocks::new(); let blocks = types::Blocks::new();
run::run(config, blocks); run::run(blocks);
} }

View File

@ -1,131 +1,121 @@
use crate::types::*; use crate::types::*;
use crate::utils::*; use crate::utils::*;
use crate::config::CONFIG;
use std::sync::mpsc; use std::sync::mpsc;
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
/* This is ugly, maybe i will try to impliment a threadpool */ /* This is ugly, maybe i will try to impliment a threadpool */
pub fn run(config: Config, mut blocks: Blocks) { pub fn run(mut blocks: Blocks) {
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
// loadavrage thread // loadavrage thread
if config.loadavg.enabled { if CONFIG.loadavg.enabled {
let loadavg_tx = tx.clone(); let loadavg_tx = tx.clone();
let configcp = config.clone();
thread::spawn(move || loop { thread::spawn(move || loop {
let loadavg_data = ThreadsData::LoadAvg(load_average::get_load_avg(&configcp)); let loadavg_data = ThreadsData::LoadAvg(load_average::get_load_avg());
loadavg_tx.send(loadavg_data).unwrap(); loadavg_tx.send(loadavg_data).unwrap();
thread::sleep(Duration::from_secs_f64(configcp.loadavg.delay)) thread::sleep(Duration::from_secs_f64(CONFIG.loadavg.delay))
}); });
} }
// spotify thread // spotify thread
if config.spotify.enabled { if CONFIG.spotify.enabled {
let spotify_tx = tx.clone(); let spotify_tx = tx.clone();
let configcp = config.clone();
thread::spawn(move || loop { thread::spawn(move || loop {
let spotify_data = ThreadsData::Spotify(spotify::get_spotify(&configcp)); let spotify_data = ThreadsData::Spotify(spotify::get_spotify());
spotify_tx.send(spotify_data).unwrap(); spotify_tx.send(spotify_data).unwrap();
thread::sleep(Duration::from_secs_f64(configcp.spotify.delay)) thread::sleep(Duration::from_secs_f64(CONFIG.spotify.delay))
}); });
} }
// mpd thread // mpd thread
if config.mpd.enabled { if CONFIG.mpd.enabled {
let mpd_tx = tx.clone(); let mpd_tx = tx.clone();
let configcp = config.clone();
thread::spawn(move || loop { thread::spawn(move || loop {
let mpd_data = ThreadsData::Mpd(mpd::get_mpd_current(&configcp)); let mpd_data = ThreadsData::Mpd(mpd::get_mpd_current());
mpd_tx.send(mpd_data).unwrap(); mpd_tx.send(mpd_data).unwrap();
thread::sleep(Duration::from_secs_f64(configcp.mpd.delay)) thread::sleep(Duration::from_secs_f64(CONFIG.mpd.delay))
}); });
} }
// volume thread // volume thread
if config.volume.enabled { if CONFIG.volume.enabled {
let volume_tx = tx.clone(); let volume_tx = tx.clone();
let configcp = config.clone();
thread::spawn(move || loop { thread::spawn(move || loop {
let vol_data = ThreadsData::Sound(volume::get_volume(&configcp)); let vol_data = ThreadsData::Sound(volume::get_volume());
volume_tx.send(vol_data).unwrap(); volume_tx.send(vol_data).unwrap();
thread::sleep(Duration::from_secs_f64(configcp.volume.delay)) thread::sleep(Duration::from_secs_f64(CONFIG.volume.delay))
}); });
} }
// Disk thread // Disk thread
if config.disk.enabled { if CONFIG.disk.enabled {
let disk_tx = tx.clone(); let disk_tx = tx.clone();
let configcp = config.clone();
thread::spawn(move || loop { thread::spawn(move || loop {
let disk_data = ThreadsData::Disk(disk::get_disk(&configcp)); let disk_data = ThreadsData::Disk(disk::get_disk());
disk_tx.send(disk_data).unwrap(); disk_tx.send(disk_data).unwrap();
thread::sleep(Duration::from_secs_f64(configcp.disk.delay)) thread::sleep(Duration::from_secs_f64(CONFIG.disk.delay))
}); });
} }
// Memory thread // Memory thread
if config.memory.enabled { if CONFIG.memory.enabled {
let memory_tx = tx.clone(); let memory_tx = tx.clone();
let configcp = config.clone();
thread::spawn(move || loop { thread::spawn(move || loop {
let memory_data = ThreadsData::Memory(memory::get_memory(&configcp).unwrap()); let memory_data = ThreadsData::Memory(memory::get_memory().unwrap());
memory_tx.send(memory_data).unwrap(); memory_tx.send(memory_data).unwrap();
thread::sleep(Duration::from_secs_f64(configcp.memory.delay)) thread::sleep(Duration::from_secs_f64(CONFIG.memory.delay))
}); });
} }
// Weather thread // Weather thread
if config.weather.enabled { if CONFIG.weather.enabled {
let weather_tx = tx.clone(); let weather_tx = tx.clone();
let configcp = config.clone();
thread::spawn(move || loop { thread::spawn(move || loop {
let weather_data = ThreadsData::Weather(weather::get_weather(&configcp)); let weather_data = ThreadsData::Weather(weather::get_weather());
weather_tx.send(weather_data).unwrap(); weather_tx.send(weather_data).unwrap();
thread::sleep(Duration::from_secs_f64(configcp.weather.delay)) thread::sleep(Duration::from_secs_f64(CONFIG.weather.delay))
}); });
} }
// Battery thread // Battery thread
if config.battery.enabled { if CONFIG.battery.enabled {
let battery_tx = tx.clone(); let battery_tx = tx.clone();
let configcp = config.clone();
thread::spawn(move || loop { thread::spawn(move || loop {
let battery_data = ThreadsData::Battery(battery::get_battery(&configcp).unwrap()); let battery_data = ThreadsData::Battery(battery::get_battery().unwrap());
battery_tx.send(battery_data).unwrap(); battery_tx.send(battery_data).unwrap();
thread::sleep(Duration::from_secs_f64(configcp.battery.delay)) thread::sleep(Duration::from_secs_f64(CONFIG.battery.delay))
}); });
} }
// Cpu temperature thread // Cpu temperature thread
if config.cpu_temperature.enabled { if CONFIG.cpu_temperature.enabled {
let cpu_temp_tx = tx.clone(); let cpu_temp_tx = tx.clone();
let configcp = config.clone();
thread::spawn(move || loop { thread::spawn(move || loop {
let cpu_temp_data = ThreadsData::CpuTemp(cpu::get_cpu_temp(&configcp).unwrap()); let cpu_temp_data = ThreadsData::CpuTemp(cpu::get_cpu_temp().unwrap());
cpu_temp_tx.send(cpu_temp_data).unwrap(); cpu_temp_tx.send(cpu_temp_data).unwrap();
thread::sleep(Duration::from_secs_f64(configcp.cpu_temperature.delay)) thread::sleep(Duration::from_secs_f64(CONFIG.cpu_temperature.delay))
}); });
} }
// Uptime thread // Uptime thread
if config.uptime.enabled { if CONFIG.uptime.enabled {
let uptime_tx = tx.clone(); let uptime_tx = tx.clone();
let configcp = config.clone();
thread::spawn(move || loop { thread::spawn(move || loop {
let uptime_data = ThreadsData::Uptime(uptime::get_uptime(&configcp).unwrap()); let uptime_data = ThreadsData::Uptime(uptime::get_uptime().unwrap());
uptime_tx.send(uptime_data).unwrap(); uptime_tx.send(uptime_data).unwrap();
thread::sleep(Duration::from_secs_f64(configcp.uptime.delay)) thread::sleep(Duration::from_secs_f64(CONFIG.uptime.delay))
}); });
} }
// Time thread // Time thread
{ {
let time_tx = tx; let time_tx = tx;
let configcp = config;
thread::spawn(move || loop { thread::spawn(move || loop {
let time_data = ThreadsData::Time(time::get_time(&configcp)); let time_data = ThreadsData::Time(time::get_time());
time_tx.send(time_data).unwrap(); time_tx.send(time_data).unwrap();
thread::sleep(Duration::from_secs_f64(configcp.time.delay)) thread::sleep(Duration::from_secs_f64(CONFIG.time.delay))
}); });
} }

View File

@ -1,17 +1,17 @@
use crate::types::Config; use crate::config::CONFIG;
use std::fs::File; use std::fs::File;
use std::io::Error; use std::io::Error;
use std::io::Read; use std::io::Read;
// getting battery percentage // getting battery percentage
pub fn get_battery(config: &Config) -> Result<String, Error> { pub fn get_battery() -> Result<String, Error> {
let battery_full_cap_file = format!( let battery_full_cap_file = format!(
"/sys/class/power_supply/{}/charge_full_design", "/sys/class/power_supply/{}/charge_full_design",
config.battery.source CONFIG.battery.source
); );
let battery_charge_now_file = format!( let battery_charge_now_file = format!(
"/sys/class/power_supply/{}/charge_now", "/sys/class/power_supply/{}/charge_now",
config.battery.source CONFIG.battery.source
); );
let mut buf = String::new(); let mut buf = String::new();
@ -31,7 +31,7 @@ pub fn get_battery(config: &Config) -> Result<String, Error> {
let battery_percentage = (charge_now as f32 / full_design as f32) * 100.0; let battery_percentage = (charge_now as f32 / full_design as f32) * 100.0;
let result = format!( let result = format!(
" {} {:.0}% {}", " {} {:.0}% {}",
config.battery.icon, battery_percentage, config.seperator CONFIG.battery.icon, battery_percentage, CONFIG.seperator
); );
Ok(result) Ok(result)
} }

View File

@ -1,18 +1,18 @@
use crate::types::Config; use crate::config::CONFIG;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
// getting cpu temperature // getting cpu temperature
pub fn get_cpu_temp(config: &Config) -> Result<String, std::io::Error> { pub fn get_cpu_temp() -> Result<String, std::io::Error> {
let mut buf = String::new(); let mut buf = String::new();
File::open("/sys/class/thermal/thermal_zone0/temp")?.read_to_string(&mut buf)?; File::open("/sys/class/thermal/thermal_zone0/temp")?.read_to_string(&mut buf)?;
let value = buf.trim().parse::<f32>().unwrap(); let value = buf.trim().parse::<f32>().unwrap();
let result = format!( let result = format!(
" {} {}° {}", " {} {}° {}",
config.cpu_temperature.icon, CONFIG.cpu_temperature.icon,
value / 1000.0, value / 1000.0,
config.seperator CONFIG.seperator
); );
Ok(result) Ok(result)
} }

View File

@ -1,6 +1,6 @@
use crate::types::Config; use crate::config::CONFIG;
pub fn get_disk(config: &Config) -> String { pub fn get_disk() -> String {
const GB: u64 = (1024 * 1024) * 1024; const GB: u64 = (1024 * 1024) * 1024;
let statvfs = nix::sys::statvfs::statvfs("/").unwrap(); let statvfs = nix::sys::statvfs::statvfs("/").unwrap();
let mut disk_used = String::new(); let mut disk_used = String::new();
@ -12,6 +12,6 @@ pub fn get_disk(config: &Config) -> String {
disk_used.push_str(&format!("{}G", used)); disk_used.push_str(&format!("{}G", used));
format!( format!(
" {} {} {}", " {} {} {}",
config.disk.icon, disk_used, config.seperator CONFIG.disk.icon, disk_used, CONFIG.seperator
) )
} }

View File

@ -1,8 +1,8 @@
use crate::types::Config; use crate::config::CONFIG;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
pub fn get_load_avg(config: &Config) -> String { pub fn get_load_avg() -> String {
let mut buf = String::new(); let mut buf = String::new();
match File::open("/proc/loadavg") { match File::open("/proc/loadavg") {
Ok(mut file) => match file.read_to_string(&mut buf) { Ok(mut file) => match file.read_to_string(&mut buf) {
@ -12,5 +12,5 @@ pub fn get_load_avg(config: &Config) -> String {
_ => return String::from("Error"), _ => return String::from("Error"),
}; };
let buf = buf.split_whitespace().collect::<Vec<_>>()[0]; let buf = buf.split_whitespace().collect::<Vec<_>>()[0];
format!(" {} {} {}", config.loadavg.icon, buf, config.seperator) format!(" {} {} {}", CONFIG.loadavg.icon, buf, CONFIG.seperator)
} }

View File

@ -1,4 +1,4 @@
use crate::types::Config; use crate::config::CONFIG;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
@ -7,7 +7,7 @@ mem_used = (mem_total + shmem - mem_free - mem_buffers - mem_cached - mem_srecl
thanks for htop's developer on stackoverflow for providing this algorithm to thanks for htop's developer on stackoverflow for providing this algorithm to
calculate used memory. calculate used memory.
*/ */
pub fn get_memory(config: &Config) -> Result<String, std::io::Error> { pub fn get_memory() -> Result<String, std::io::Error> {
let mut buf = String::new(); let mut buf = String::new();
File::open("/proc/meminfo")?.read_to_string(&mut buf)?; File::open("/proc/meminfo")?.read_to_string(&mut buf)?;
@ -56,14 +56,14 @@ pub fn get_memory(config: &Config) -> Result<String, std::io::Error> {
if mem_used > 1000 { if mem_used > 1000 {
result = format!( result = format!(
" {} {:.1}G {}", " {} {:.1}G {}",
config.memory.icon, CONFIG.memory.icon,
mem_used as f32 / 1000.0, mem_used as f32 / 1000.0,
config.seperator CONFIG.seperator
); );
} else { } else {
result = format!( result = format!(
" {} {}M {}", " {} {}M {}",
config.memory.icon, mem_used, config.seperator CONFIG.memory.icon, mem_used, CONFIG.seperator
); );
} }
Ok(result) Ok(result)

View File

@ -1,10 +1,10 @@
use crate::types::Config; use crate::config::CONFIG;
use mpd::{Client, Song}; use mpd::{Client, Song};
// yes, error handling looks fucking sucks! // yes, error handling looks fucking sucks!
// getting mpd song file // getting mpd song file
pub fn get_mpd_current(config: &Config) -> String { pub fn get_mpd_current() -> String {
let stream_path = format!("{}:{}", config.mpd.host, config.mpd.port); let stream_path = format!("{}:{}", CONFIG.mpd.host, CONFIG.mpd.port);
let empty_string = String::from(""); let empty_string = String::from("");
let mut conn = match Client::connect(&stream_path) { let mut conn = match Client::connect(&stream_path) {
Ok(connection) => connection, Ok(connection) => connection,
@ -20,7 +20,7 @@ pub fn get_mpd_current(config: &Config) -> String {
let result = format!( let result = format!(
" {} {} {}", " {} {} {}",
config.mpd.icon, current.file, config.seperator CONFIG.mpd.icon, current.file, CONFIG.seperator
); );
result result

View File

@ -1,11 +1,11 @@
use crate::types::Config; use crate::config::CONFIG;
use dbus::blocking::stdintf::org_freedesktop_dbus::Properties; use dbus::blocking::stdintf::org_freedesktop_dbus::Properties;
use dbus::{arg, blocking::Connection}; use dbus::{arg, blocking::Connection};
use std::time::Duration; use std::time::Duration;
// getting spotify current artist and title. // getting spotify current artist and title.
// FIXME: I know im lazy asshole, this error handling looks ugly, i dont like it too, need to fix soon. // FIXME: I know im lazy asshole, this error handling looks ugly, i dont like it too, need to fix soon.
pub fn get_spotify(config: &Config) -> String { pub fn get_spotify() -> String {
let conn = match Connection::new_session() { let conn = match Connection::new_session() {
Ok(conn) => conn, Ok(conn) => conn,
_ => return String::from(""), _ => return String::from(""),
@ -40,6 +40,6 @@ pub fn get_spotify(config: &Config) -> String {
format!( format!(
" {} {} - {} {}", " {} {} - {} {}",
config.spotify.icon, artist, title, config.seperator CONFIG.spotify.icon, artist, title, CONFIG.seperator
) )
} }

View File

@ -1,13 +1,13 @@
use crate::types::Config; use crate::config::CONFIG;
use chrono::prelude::*; use chrono::prelude::*;
pub fn get_time(config: &Config) -> String { pub fn get_time() -> String {
let now = Local::now(); let now = Local::now();
format!( format!(
" {} {} {}", " {} {} {}",
config.time.icon, CONFIG.time.icon,
now.format(&config.time.format), now.format(&CONFIG.time.format),
config.seperator CONFIG.seperator
) )
} }

View File

@ -1,8 +1,8 @@
use crate::types::Config; use crate::config::CONFIG;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
pub fn get_uptime(config: &Config) -> Result<String, std::io::Error> { pub fn get_uptime() -> Result<String, std::io::Error> {
let mut buf = String::new(); let mut buf = String::new();
match File::open("/proc/uptime") { match File::open("/proc/uptime") {
Ok(mut file) => file.read_to_string(&mut buf)?, Ok(mut file) => file.read_to_string(&mut buf)?,
@ -20,6 +20,6 @@ pub fn get_uptime(config: &Config) -> Result<String, std::io::Error> {
} else { } else {
format!("{} min", minutes) format!("{} min", minutes)
}; };
let result = format!(" {} {} {}", config.uptime.icon, uptime, config.seperator); let result = format!(" {} {} {}", CONFIG.uptime.icon, uptime, CONFIG.seperator);
Ok(result) Ok(result)
} }

View File

@ -1,9 +1,9 @@
use crate::types::Config; use crate::config::CONFIG;
use alsa::mixer::{Mixer, SelemChannelId, SelemId}; use alsa::mixer::{Mixer, SelemChannelId, SelemId};
// getting volume percentage // getting volume percentage
pub fn get_volume(config: &Config) -> String { pub fn get_volume() -> String {
let card = if config.volume.card == "PULSE" { let card = if CONFIG.volume.card == "PULSE" {
"pulse" "pulse"
} else { } else {
"default" "default"
@ -27,5 +27,5 @@ pub fn get_volume(config: &Config) -> String {
((raw_volume as f64 / range as f64) * 100.) as u64 ((raw_volume as f64 / range as f64) * 100.) as u64
}; };
format!(" {} {}% {}", config.volume.icon, vol, config.seperator) format!(" {} {}% {}", CONFIG.volume.icon, vol, CONFIG.seperator)
} }

View File

@ -1,14 +1,14 @@
use crate::types::Config; use crate::config::CONFIG;
// will make a GET request from wttr.in // will make a GET request from wttr.in
pub fn get_weather(config: &Config) -> String { pub fn get_weather() -> String {
let format = if config.weather.format.is_empty() { let format = if CONFIG.weather.format.is_empty() {
String::from("%l:+%t") String::from("%l:+%t")
} else { } else {
config.weather.format.clone() CONFIG.weather.format.clone()
}; };
let url = format!("http://wttr.in/{}?format=\"{}", config.weather.city, format); let url = format!("http://wttr.in/{}?format=\"{}", CONFIG.weather.city, format);
let err_string = String::from("Error"); let err_string = String::from("Error");
let res = match minreq::get(url).send() { let res = match minreq::get(url).send() {
Ok(resp) => match resp.as_str() { Ok(resp) => match resp.as_str() {
@ -18,5 +18,5 @@ pub fn get_weather(config: &Config) -> String {
Err(_) => err_string, Err(_) => err_string,
}; };
format!(" {} {} {}", config.weather.icon, res, config.seperator) format!(" {} {} {}", CONFIG.weather.icon, res, CONFIG.seperator)
} }