From 683936c23d21704e156912e5583cbf3aa092d910 Mon Sep 17 00:00:00 2001 From: elkowar <5300871+elkowar@users.noreply.github.com> Date: Mon, 29 Aug 2022 14:53:02 +0200 Subject: [PATCH] Remove some unused code --- crates/eww/src/app.rs | 11 +-- crates/eww/src/client.rs | 2 +- crates/eww/src/config/eww_config.rs | 2 +- crates/eww/src/config/inbuilt.rs | 2 +- crates/eww/src/daemon_response.rs | 10 --- crates/eww/src/geometry.rs | 6 -- crates/eww/src/main.rs | 128 ++++---------------------- crates/eww/src/paths.rs | 95 ++++++++++++++++++++ crates/eww/src/util.rs | 22 ----- mf:w | 134 ++++++++++++++++++++++++++++ 10 files changed, 252 insertions(+), 160 deletions(-) create mode 100644 crates/eww/src/paths.rs create mode 100644 mf:w diff --git a/crates/eww/src/app.rs b/crates/eww/src/app.rs index 367f216..f281cf9 100644 --- a/crates/eww/src/app.rs +++ b/crates/eww/src/app.rs @@ -3,9 +3,10 @@ use crate::{ daemon_response::DaemonResponseSender, display_backend, error_handling_ctx, gtk::prelude::{ContainerExt, CssProviderExt, GtkWindowExt, StyleContextExt, WidgetExt}, + paths::EwwPaths, script_var_handler::ScriptVarHandlerHandle, state::scope_graph::{ScopeGraph, ScopeIndex}, - EwwPaths, *, + *, }; use anyhow::anyhow; use eww_shared_util::VarName; @@ -33,8 +34,6 @@ pub enum DaemonCommand { NoOp, UpdateVars(Vec<(VarName, DynVal)>), ReloadConfigAndCss(DaemonResponseSender), - UpdateConfig(config::EwwConfig), - UpdateCss(String), OpenInspector, OpenMany { windows: Vec, @@ -144,12 +143,6 @@ impl App { sender.respond_with_error_list(errors)?; } - DaemonCommand::UpdateConfig(config) => { - self.load_config(config)?; - } - DaemonCommand::UpdateCss(css) => { - self.load_css(&css)?; - } DaemonCommand::KillServer => { log::info!("Received kill command, stopping server!"); self.stop_application(); diff --git a/crates/eww/src/client.rs b/crates/eww/src/client.rs index 023dfaa..616c387 100644 --- a/crates/eww/src/client.rs +++ b/crates/eww/src/client.rs @@ -3,7 +3,7 @@ use std::process::Stdio; use crate::{ daemon_response::DaemonResponse, opts::{self, ActionClientOnly}, - EwwPaths, + paths::EwwPaths, }; use anyhow::{Context, Result}; use std::{ diff --git a/crates/eww/src/config/eww_config.rs b/crates/eww/src/config/eww_config.rs index 4fe1dde..e10a3d2 100644 --- a/crates/eww/src/config/eww_config.rs +++ b/crates/eww/src/config/eww_config.rs @@ -11,7 +11,7 @@ use yuck::{ use simplexpr::dynval::DynVal; -use crate::{config::inbuilt, error_handling_ctx, widgets::widget_definitions, EwwPaths}; +use crate::{config::inbuilt, error_handling_ctx, widgets::widget_definitions, paths::EwwPaths}; use super::script_var; diff --git a/crates/eww/src/config/inbuilt.rs b/crates/eww/src/config/inbuilt.rs index 67f3e22..66a2c17 100644 --- a/crates/eww/src/config/inbuilt.rs +++ b/crates/eww/src/config/inbuilt.rs @@ -6,7 +6,7 @@ use yuck::config::{ var_definition::VarDefinition, }; -use crate::{config::system_stats::*, EwwPaths}; +use crate::{config::system_stats::*, paths::EwwPaths}; use eww_shared_util::VarName; macro_rules! define_builtin_vars { diff --git a/crates/eww/src/daemon_response.rs b/crates/eww/src/daemon_response.rs index c4fce94..e2189dd 100644 --- a/crates/eww/src/daemon_response.rs +++ b/crates/eww/src/daemon_response.rs @@ -11,16 +11,6 @@ pub enum DaemonResponse { Failure(String), } -impl DaemonResponse { - pub fn is_success(&self) -> bool { - matches!(self, DaemonResponse::Success(_)) - } - - pub fn is_failure(&self) -> bool { - !self.is_success() - } -} - #[derive(Debug)] pub struct DaemonResponseSender(tokio::sync::mpsc::UnboundedSender); diff --git a/crates/eww/src/geometry.rs b/crates/eww/src/geometry.rs index 3b426ee..1b845a5 100644 --- a/crates/eww/src/geometry.rs +++ b/crates/eww/src/geometry.rs @@ -12,12 +12,6 @@ pub struct Rect { pub height: i32, } -impl Rect { - pub fn of(x: i32, y: i32, width: i32, height: i32) -> Self { - Rect { x, y, width, height } - } -} - impl Rectangular for Rect { fn get_rect(&self) -> Rect { *self diff --git a/crates/eww/src/main.rs b/crates/eww/src/main.rs index 8f09502..976365a 100644 --- a/crates/eww/src/main.rs +++ b/crates/eww/src/main.rs @@ -10,35 +10,31 @@ extern crate gtk; #[cfg(feature = "wayland")] extern crate gtk_layer_shell as gtk_layer_shell; -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result}; use daemon_response::{DaemonResponse, DaemonResponseReceiver}; use opts::ActionWithServer; -use std::{ - collections::hash_map::DefaultHasher, - hash::{Hash, Hasher}, - os::unix::net, - path::{Path, PathBuf}, - time::Duration, -}; +use paths::EwwPaths; +use std::{os::unix::net, path::Path, time::Duration}; use crate::server::ForkResult; -pub mod app; -pub mod application_lifecycle; -pub mod client; -pub mod config; +mod app; +mod application_lifecycle; +mod client; +mod config; mod daemon_response; -pub mod display_backend; -pub mod error; +mod display_backend; +mod error; mod error_handling_ctx; -pub mod geometry; -pub mod ipc_server; -pub mod opts; -pub mod script_var_handler; -pub mod server; -pub mod state; -pub mod util; -pub mod widgets; +mod geometry; +mod ipc_server; +mod opts; +mod paths; +mod script_var_handler; +mod server; +mod state; +mod util; +mod widgets; fn main() { let eww_binary_name = std::env::args().next().unwrap(); @@ -193,91 +189,3 @@ fn check_server_running(socket_path: impl AsRef) -> bool { .and_then(|mut stream| client::do_server_call(&mut stream, &opts::ActionWithServer::Ping).ok()); response.is_some() } - -#[derive(Debug, Clone)] -pub struct EwwPaths { - log_file: PathBuf, - ipc_socket_file: PathBuf, - config_dir: PathBuf, -} - -impl EwwPaths { - pub fn from_config_dir>(config_dir: P) -> Result { - let config_dir = config_dir.as_ref(); - if config_dir.is_file() { - bail!("Please provide the path to the config directory, not a file within it") - } - - if !config_dir.exists() { - bail!("Configuration directory {} does not exist", config_dir.display()); - } - - let config_dir = config_dir.canonicalize()?; - - let mut hasher = DefaultHasher::new(); - format!("{}", config_dir.display()).hash(&mut hasher); - // daemon_id is a hash of the config dir path to ensure that, given a normal XDG_RUNTIME_DIR, - // the absolute path to the socket stays under the 108 bytes limit. (see #387, man 7 unix) - let daemon_id = format!("{:x}", hasher.finish()); - - let ipc_socket_file = std::env::var("XDG_RUNTIME_DIR") - .map(std::path::PathBuf::from) - .unwrap_or_else(|_| std::path::PathBuf::from("/tmp")) - .join(format!("eww-server_{}", daemon_id)); - - // 100 as the limit isn't quite 108 everywhere (i.e 104 on BSD or mac) - if format!("{}", ipc_socket_file.display()).len() > 100 { - log::warn!("The IPC socket file's absolute path exceeds 100 bytes, the socket may fail to create."); - } - - Ok(EwwPaths { - config_dir, - log_file: std::env::var("XDG_CACHE_HOME") - .map(PathBuf::from) - .unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap()).join(".cache")) - .join(format!("eww_{}.log", daemon_id)), - ipc_socket_file, - }) - } - - pub fn default() -> Result { - let config_dir = std::env::var("XDG_CONFIG_HOME") - .map(PathBuf::from) - .unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap()).join(".config")) - .join("eww"); - - Self::from_config_dir(config_dir) - } - - pub fn get_log_file(&self) -> &Path { - self.log_file.as_path() - } - - pub fn get_ipc_socket_file(&self) -> &Path { - self.ipc_socket_file.as_path() - } - - pub fn get_config_dir(&self) -> &Path { - self.config_dir.as_path() - } - - pub fn get_yuck_path(&self) -> PathBuf { - self.config_dir.join("eww.yuck") - } - - pub fn get_eww_scss_path(&self) -> PathBuf { - self.config_dir.join("eww.scss") - } -} - -impl std::fmt::Display for EwwPaths { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "config-dir: {}, ipc-socket: {}, log-file: {}", - self.config_dir.display(), - self.ipc_socket_file.display(), - self.log_file.display() - ) - } -} diff --git a/crates/eww/src/paths.rs b/crates/eww/src/paths.rs new file mode 100644 index 0000000..fc35d80 --- /dev/null +++ b/crates/eww/src/paths.rs @@ -0,0 +1,95 @@ +use std::{ + collections::hash_map::DefaultHasher, + hash::{Hash, Hasher}, + path::{Path, PathBuf}, +}; + +use anyhow::{bail, Result}; + +#[derive(Debug, Clone)] +pub struct EwwPaths { + pub log_file: PathBuf, + pub ipc_socket_file: PathBuf, + pub config_dir: PathBuf, +} + +impl EwwPaths { + pub fn from_config_dir>(config_dir: P) -> Result { + let config_dir = config_dir.as_ref(); + if config_dir.is_file() { + bail!("Please provide the path to the config directory, not a file within it") + } + + if !config_dir.exists() { + bail!("Configuration directory {} does not exist", config_dir.display()); + } + + let config_dir = config_dir.canonicalize()?; + + let mut hasher = DefaultHasher::new(); + format!("{}", config_dir.display()).hash(&mut hasher); + // daemon_id is a hash of the config dir path to ensure that, given a normal XDG_RUNTIME_DIR, + // the absolute path to the socket stays under the 108 bytes limit. (see #387, man 7 unix) + let daemon_id = format!("{:x}", hasher.finish()); + + let ipc_socket_file = std::env::var("XDG_RUNTIME_DIR") + .map(std::path::PathBuf::from) + .unwrap_or_else(|_| std::path::PathBuf::from("/tmp")) + .join(format!("eww-server_{}", daemon_id)); + + // 100 as the limit isn't quite 108 everywhere (i.e 104 on BSD or mac) + if format!("{}", ipc_socket_file.display()).len() > 100 { + log::warn!("The IPC socket file's absolute path exceeds 100 bytes, the socket may fail to create."); + } + + Ok(EwwPaths { + config_dir, + log_file: std::env::var("XDG_CACHE_HOME") + .map(PathBuf::from) + .unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap()).join(".cache")) + .join(format!("eww_{}.log", daemon_id)), + ipc_socket_file, + }) + } + + pub fn default() -> Result { + let config_dir = std::env::var("XDG_CONFIG_HOME") + .map(PathBuf::from) + .unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap()).join(".config")) + .join("eww"); + + Self::from_config_dir(config_dir) + } + + pub fn get_log_file(&self) -> &Path { + self.log_file.as_path() + } + + pub fn get_ipc_socket_file(&self) -> &Path { + self.ipc_socket_file.as_path() + } + + pub fn get_config_dir(&self) -> &Path { + self.config_dir.as_path() + } + + pub fn get_yuck_path(&self) -> PathBuf { + self.config_dir.join("eww.yuck") + } + + pub fn get_eww_scss_path(&self) -> PathBuf { + self.config_dir.join("eww.scss") + } +} + +impl std::fmt::Display for EwwPaths { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "config-dir: {}, ipc-socket: {}, log-file: {}", + self.config_dir.display(), + self.ipc_socket_file.display(), + self.log_file.display() + ) + } +} diff --git a/crates/eww/src/util.rs b/crates/eww/src/util.rs index cc5bb92..b544db8 100644 --- a/crates/eww/src/util.rs +++ b/crates/eww/src/util.rs @@ -83,28 +83,6 @@ pub fn list_difference<'a, 'b, T: PartialEq>(a: &'a [T], b: &'b [T]) -> (Vec<&'a (missing, new) } -/// Joins two paths while keeping it somewhat pretty. -/// If the second path is absolute, this will just return the second path. -/// If it is relative, it will return the second path joined onto the first path, removing any `./` if present. -/// TODO this is not yet perfect, as it will still leave ../ and multiple ./ etc,... check for a Path::simplify or something. -pub fn join_path_pretty, P2: AsRef>(a: P, b: P2) -> std::path::PathBuf { - let a = a.as_ref(); - let b = b.as_ref(); - if b.is_absolute() { - b.to_path_buf() - } else { - a.parent().unwrap().join(b.strip_prefix("./").unwrap_or(b)) - } -} - -/// extends a hashmap, returning a list of keys that already where present in the hashmap. -pub fn extend_safe>( - a: &mut std::collections::HashMap, - b: T, -) -> Vec { - b.into_iter().filter_map(|(k, v)| a.insert(k.clone(), v).map(|_| k.clone())).collect() -} - /// read an scss file, replace all environment variable references within it and /// then parse it into css. pub fn parse_scss_from_file(path: &Path) -> Result { diff --git a/mf:w b/mf:w new file mode 100644 index 0000000..e10a3d2 --- /dev/null +++ b/mf:w @@ -0,0 +1,134 @@ +use anyhow::{bail, Context, Result}; +use eww_shared_util::VarName; +use std::collections::HashMap; +use yuck::{ + config::{ + file_provider::YuckFiles, script_var_definition::ScriptVarDefinition, validate::ValidationError, + widget_definition::WidgetDefinition, window_definition::WindowDefinition, Config, + }, + error::AstError, +}; + +use simplexpr::dynval::DynVal; + +use crate::{config::inbuilt, error_handling_ctx, widgets::widget_definitions, paths::EwwPaths}; + +use super::script_var; + +/// Load an [`EwwConfig`] from the config dir of the given [`crate::EwwPaths`], +/// resetting and applying the global YuckFiles object in [`crate::error_handling_ctx`]. +pub fn read_from_eww_paths(eww_paths: &EwwPaths) -> Result { + error_handling_ctx::clear_files(); + EwwConfig::read_from_dir(&mut error_handling_ctx::YUCK_FILES.write().unwrap(), eww_paths) +} + +/// Eww configuration structure. +#[derive(Debug, Clone)] +pub struct EwwConfig { + widgets: HashMap, + windows: HashMap, + initial_variables: HashMap, + script_vars: HashMap, + + // Links variable which affect state (active/inactive) of poll var to those poll variables + poll_var_links: HashMap>, +} + +impl Default for EwwConfig { + fn default() -> Self { + Self { + widgets: HashMap::new(), + windows: HashMap::new(), + initial_variables: HashMap::new(), + script_vars: HashMap::new(), + poll_var_links: HashMap::new(), + } + } +} + +impl EwwConfig { + /// Load an [`EwwConfig`] from the config dir of the given [`crate::EwwPaths`], reading the main config file. + pub fn read_from_dir(files: &mut YuckFiles, eww_paths: &EwwPaths) -> Result { + let yuck_path = eww_paths.get_yuck_path(); + if !yuck_path.exists() { + bail!("The configuration file `{}` does not exist", yuck_path.display()); + } + let config = Config::generate_from_main_file(files, yuck_path)?; + + // run some validations on the configuration + let magic_globals: Vec<_> = inbuilt::INBUILT_VAR_NAMES + .into_iter() + .chain(inbuilt::MAGIC_CONSTANT_NAMES) + .into_iter() + .map(|x| VarName::from(x.clone())) + .collect(); + yuck::config::validate::validate(&config, magic_globals)?; + + for (name, def) in &config.widget_definitions { + if widget_definitions::BUILTIN_WIDGET_NAMES.contains(&name.as_str()) { + return Err( + AstError::ValidationError(ValidationError::AccidentalBuiltinOverride(def.span, name.to_string())).into() + ); + } + } + + let Config { widget_definitions, window_definitions, mut var_definitions, mut script_vars } = config; + script_vars.extend(inbuilt::get_inbuilt_vars()); + var_definitions.extend(inbuilt::get_magic_constants(eww_paths)); + + let mut poll_var_links = HashMap::>::new(); + script_vars + .iter() + .filter_map(|(_, var)| if let ScriptVarDefinition::Poll(poll_var) = var { Some(poll_var) } else { None }) + .for_each(|var| { + var.run_while_var_refs + .iter() + .for_each(|name| poll_var_links.entry(name.clone()).or_default().push(var.name.clone())) + }); + + Ok(EwwConfig { + windows: window_definitions, + widgets: widget_definitions, + initial_variables: var_definitions.into_iter().map(|(k, v)| (k, v.initial_value)).collect(), + script_vars, + poll_var_links, + }) + } + + // TODO this is kinda ugly + pub fn generate_initial_state(&self) -> Result> { + let mut vars = self + .script_vars + .iter() + .map(|(name, var)| Ok((name.clone(), script_var::initial_value(var)?))) + .collect::>>()?; + vars.extend(self.initial_variables.clone()); + Ok(vars) + } + + pub fn get_windows(&self) -> &HashMap { + &self.windows + } + + pub fn get_window(&self, name: &str) -> Result<&WindowDefinition> { + self.windows.get(name).with_context(|| { + format!( + "No window named '{}' exists in config.\nThis may also be caused by your config failing to load properly, \ + please check for any other errors in that case.", + name + ) + }) + } + + pub fn get_script_var(&self, name: &VarName) -> Result<&ScriptVarDefinition> { + self.script_vars.get(name).with_context(|| format!("No script var named '{}' exists", name)) + } + + pub fn get_widget_definitions(&self) -> &HashMap { + &self.widgets + } + + pub fn get_poll_var_link(&self, name: &VarName) -> Result<&Vec> { + self.poll_var_links.get(name).with_context(|| format!("{} does not links to any poll variable", name.0)) + } +}