Skip to content

Commit

Permalink
More refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
vars1ty committed Jan 24, 2023
1 parent b1a3eb4 commit f80c112
Show file tree
Hide file tree
Showing 11 changed files with 65 additions and 79 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "hybrid-bar"
authors = [ "varsity <[email protected]>" ]
version = "0.4.0"
version = "0.4.2"
edition = "2021"
description = "A simple status bar made for wlroots compositors."
license = "MIT"
Expand Down
4 changes: 1 addition & 3 deletions VARIABLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,4 @@ Then the text will automatically be replaced with the value from `cool_message`.
- `tooltip`

## Limitations
There's only two limitations with variables:
1. You can only specify up to `64`, although I don't expect you to exceed this limit for one single Hybrid session.
2. Tooltip commands do not currently support variables.
There's only one limitation with variables: Tooltip commands do not currently support variables.
4 changes: 2 additions & 2 deletions examples/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@
"command": "whoami",
"tooltip": "And here's your kernel: ",
"tooltip_command": "uname -r",
"update_rate": 5000
"update_rate": 50000
},
"centered-label_centerdummy": {
"text": "dummy centered label",
"text": "Example Config - Create/Edit yours at ~/.config/HybridBar/config.json",
"tooltip": "An example of a centered label"
},
"right-label_rightdummy": {
Expand Down
10 changes: 10 additions & 0 deletions resources/cava_tmp.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Cava Configuration for Hybrid
[general]
framerate = [framerate]
bars = [bars]
[output]
method = raw
raw_target = /dev/stdout
data_format = ascii
ascii_max_range = 7

30 changes: 14 additions & 16 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use crate::{constants::*, environment, math, structures::ConfigData};
use heapless::Vec;
use json::JsonValue;
use lxinfo::info;
use std::{fs, sync::RwLock};
use std::{collections::HashMap, fs, sync::RwLock};

lazy_static! {
/// Cached config.
Expand All @@ -23,12 +22,13 @@ pub fn get_path() -> String {

/// Returns the set update-rate.
pub fn get_update_rate() -> u64 {
let update_rate =
if let Some(c_update_rate) = conf!(HYBRID_ROOT_JSON, "update_rate", false, false).number {
math::clamp_i32(c_update_rate, 5, 10_000)
} else {
100
};
let update_rate = math::clamp_i32(
conf!(HYBRID_ROOT_JSON, "update_rate", false, false)
.number
.unwrap_or(100),
5,
10_000,
);

update_rate
.try_into()
Expand All @@ -47,7 +47,8 @@ fn read_config_raw() -> JsonValue {
conf_path.push_str(&environment::try_get_var("HYBRID_CONFIG", DEFAULT_CONFIG));
json::parse(
&fs::read_to_string(&conf_path)
.unwrap_or_else(|_| panic!("[ERROR] Failed reading config file from '{conf_path}'!")),
// Don't panic if the file doesn't exist/couldn't be read. Instead use the example config.
.unwrap_or_else(|_| include_str!("../examples/config.json").to_owned()),
)
.unwrap_or_else(|_| panic!("[ERROR] Failed parsing config from '{conf_path}'!"))
}
Expand Down Expand Up @@ -83,17 +84,14 @@ pub fn try_get(root: &str, key: &str, is_string: bool, with_custom_variables: bo
}

/// Gets all the custom variables.
fn get_custom_variables() -> Vec<(String, String), 64> {
fn get_custom_variables() -> HashMap<String, String> {
let cfg = &CONFIG.read().unwrap()[HYBRID_V_ROOT_JSON];
// 0.3.0: Only allow for 64 variables.
let mut vector: Vec<(String, String), 64> = Vec::new();
let mut map: HashMap<String, String> = HashMap::new();
for entry in cfg.entries() {
vector
.push((entry.0.to_owned(), entry.1.to_string()))
.expect("[ERROR] You cannot have more than `64` variables!");
map.insert(entry.0.to_owned(), entry.1.to_string());
}

vector
map
}

/// Replaces any variable-matching patterns in the `String` with the variables value.
Expand Down
19 changes: 9 additions & 10 deletions src/loop.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{
cava::{self, get_current_bars, HAS_CAVA_CRASHED},
cava::{self, BARS, HAS_CAVA_CRASHED},
widget::HWidget,
};
use glib::Continue;
Expand All @@ -8,11 +8,10 @@ use std::time::Duration;
/// Updates dynamic bar content.
pub fn update() {
// Only start the tick-loop if there are actually Cava widgets available.
if cava::CAVA_INSTANCES
let widgets = cava::CAVA_INSTANCES
.lock()
.expect("[ERROR] Cannot access ui::CAVA_INSTANCES!")
.is_empty()
{
.expect("[ERROR] Cannot access ui::CAVA_INSTANCES!");
if widgets.is_empty() {
return;
}

Expand All @@ -22,13 +21,13 @@ pub fn update() {

/// Updates all Cava widgets.
fn update_cava() -> Continue {
let bars = &get_current_bars();
let bars = &*BARS.lock().unwrap();
// Loop through all Cava widget instances and sync the text.
for widget in cava::CAVA_INSTANCES
let widgets = cava::CAVA_INSTANCES
.lock()
.expect("[ERROR] Cannot access ui::CAVA_INSTANCES!")
.iter()
{
.expect("[ERROR] Cannot access ui::CAVA_INSTANCES!");
let widgets = widgets.iter();
for widget in widgets {
widget.update_label_direct(bars);
}

Expand Down
26 changes: 9 additions & 17 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,9 @@ fn get_anchors() -> [(gtk_layer_shell::Edge, bool); 4] {
true
};

let pos = if let Some(c_pos) = conf!(HYBRID_ROOT_JSON, "position", true, false).string {
c_pos
} else {
"Top".to_owned()
};
let pos = conf!(HYBRID_ROOT_JSON, "position", true, false)
.string
.unwrap_or_else(|| "Top".to_owned());

if !pos.eq_ignore_ascii_case("Top") && !pos.eq_ignore_ascii_case("Bottom") && !pos.is_empty() {
panic!("[ERROR] Invalid position! Values: [ TOP, BOTTOM ] - casing doesn't matter.")
Expand Down Expand Up @@ -107,12 +105,9 @@ fn activate(application: &Application) {

// Allows for specifing the namespace of the layer.
// The default is "gtk-layer-shell" to not break existing configs.
let namespace =
if let Some(c_namespace) = conf!(HYBRID_ROOT_JSON, "namespace", true, false).string {
c_namespace
} else {
"gtk-layer-shell".to_owned()
};
let namespace = conf!(HYBRID_ROOT_JSON, "namespace", true, false)
.string
.unwrap_or_else(|| "gtk-layer-shell".to_owned());

gtk_layer_shell::set_namespace(&window, &namespace);

Expand Down Expand Up @@ -145,12 +140,9 @@ fn activate(application: &Application) {
pub fn load_css() {
let provider = CssProvider::new();
// 0.2.8: Allow for defining the name of the stylesheet to look up
let css_file =
if let Some(c_css_file) = conf!(HYBRID_ROOT_JSON, "stylesheet", true, false).string {
c_css_file
} else {
DEFAULT_CSS.to_owned()
};
let css_file = conf!(HYBRID_ROOT_JSON, "stylesheet", true, false)
.string
.unwrap_or_else(|| DEFAULT_CSS.to_owned());

let mut css_path = config::get_path();
css_path.push_str(&css_file);
Expand Down
9 changes: 5 additions & 4 deletions src/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,12 @@ fn create_components(left: &Box, centered: &Box, right: &Box) {
const ALIGNMENT: char = '-';
const SEPARATOR: &str = "_";
let mut has_started_cava = false;
for (key, _) in config::CONFIG.read().unwrap().entries() {
if !key.contains(ALIGNMENT) || !key.contains(SEPARATOR) {
continue;
}
let conf = config::CONFIG.read().unwrap();
let relevant = conf
.entries()
.filter(|(key, _)| key.contains(ALIGNMENT) && key.contains(SEPARATOR));

for (key, _) in relevant {
// Gets the widget identifiers.
let identifiers = key.split(SEPARATOR).collect::<Vec<&str, 8>>();

Expand Down
36 changes: 12 additions & 24 deletions src/utils/cava.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use tokio::{

lazy_static! {
/// Current Cava bars.
static ref BARS: Mutex<String> = Mutex::new(String::default());
pub static ref BARS: Mutex<String> = Mutex::new(String::default());
/// Has Cava crashed? If true, don't keep `update_cava` running.
pub static ref HAS_CAVA_CRASHED: Mutex<bool> = Mutex::new(false);
/// All active Cava widget instances.
Expand All @@ -32,11 +32,6 @@ fn get_bars() -> i32 {
math::clamp_i32(bars, 2, 16)
}

/// Returns the current Cava bars.
pub fn get_current_bars() -> String {
BARS.lock().unwrap().to_string()
}

/// Returns the desired framerate to use for Cava updates.
fn get_framerate() -> i32 {
let framerate = conf!(HYBRID_ROOT_JSON, "cava_framerate", false, false)
Expand All @@ -52,23 +47,14 @@ pub fn get_temp_config() -> String {
// 0.2.7: Support for dynamically configuring the temporary config to an extent.
let bars = get_bars();
let framerate = get_framerate();
file.write_all(
format!(
r#"
# Cava Configuration for Hybrid
[general]
framerate = {framerate}
bars = {bars}
[output]
method = raw
raw_target = /dev/stdout
data_format = ascii
ascii_max_range = 7
"#,
)
.as_bytes(),
)
.expect("[ERROR] Failed writing to the temporary Cava config!");
let mut conf = include_str!("../../resources/cava_tmp.conf");
let formatted = conf
.replace("[framerate]", &framerate.to_string())
.replace("[bars]", &bars.to_string());

conf = &formatted;
file.write_all(conf.as_bytes())
.expect("[ERROR] Failed writing to the temporary Cava config!");
path
}

Expand Down Expand Up @@ -119,7 +105,9 @@ pub fn update_bars() {
}
};

*BARS.lock().unwrap() = bars;
if *BARS.lock().unwrap() != bars {
*BARS.lock().unwrap() = bars;
}
}
});
}
2 changes: 1 addition & 1 deletion src/widgets/cmd_widget.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ impl HWidget for CmdWidget {

// .clone() because otherwise it starts crying about move.
widget.clone().connect_key_press_event(move |_, key| {
let real_key = key.keycode().expect("[ERROR] No keycode retrieved (???)");
let real_key = key.keycode().unwrap_or_default();
// 36 = Enter
if real_key == 36 {
// Could use execute!() but it waits for the process to finish, which we don't
Expand Down

0 comments on commit f80c112

Please sign in to comment.