Skip to content

Commit

Permalink
Yeet try_blocks 😢
Browse files Browse the repository at this point in the history
  • Loading branch information
elkowar committed Feb 17, 2024
1 parent 6a76e2a commit 52ac617
Show file tree
Hide file tree
Showing 14 changed files with 202 additions and 196 deletions.
273 changes: 136 additions & 137 deletions crates/eww/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,150 +146,148 @@ impl<B> std::fmt::Debug for App<B> {
}

impl<B: DisplayBackend> App<B> {
/// Handle a [`DaemonCommand`] event.
/// Handle a [`DaemonCommand`] event, logging any errors that occur.
pub fn handle_command(&mut self, event: DaemonCommand) {
if let Err(err) = self.try_handle_command(event) {
error_handling_ctx::print_error(err);
}
}

/// Try to handle a [`DaemonCommand`] event.
fn try_handle_command(&mut self, event: DaemonCommand) -> Result<()> {
log::debug!("Handling event: {:?}", &event);
let result: Result<_> = try {
match event {
DaemonCommand::NoOp => {}
DaemonCommand::OpenInspector => {
gtk::Window::set_interactive_debugging(true);
}
DaemonCommand::UpdateVars(mappings) => {
for (var_name, new_value) in mappings {
self.update_global_variable(var_name, new_value);
}
match event {
DaemonCommand::NoOp => {}
DaemonCommand::OpenInspector => {
gtk::Window::set_interactive_debugging(true);
}
DaemonCommand::UpdateVars(mappings) => {
for (var_name, new_value) in mappings {
self.update_global_variable(var_name, new_value);
}
DaemonCommand::ReloadConfigAndCss(sender) => {
let mut errors = Vec::new();

let config_result = config::read_from_eww_paths(&self.paths);
if let Err(e) = config_result.and_then(|new_config| self.load_config(new_config)) {
errors.push(e)
}
match crate::config::scss::parse_scss_from_config(self.paths.get_config_dir()) {
Ok((file_id, css)) => {
if let Err(e) = self.load_css(file_id, &css) {
errors.push(anyhow!(e));
}
}
Err(e) => {
errors.push(e);
}
}
}
DaemonCommand::ReloadConfigAndCss(sender) => {
let mut errors = Vec::new();

sender.respond_with_error_list(errors)?;
}
DaemonCommand::KillServer => {
log::info!("Received kill command, stopping server!");
self.stop_application();
let config_result = config::read_from_eww_paths(&self.paths);
if let Err(e) = config_result.and_then(|new_config| self.load_config(new_config)) {
errors.push(e)
}
DaemonCommand::CloseAll => {
log::info!("Received close command, closing all windows");
for window_name in self.open_windows.keys().cloned().collect::<Vec<String>>() {
self.close_window(&window_name)?;
match crate::config::scss::parse_scss_from_config(self.paths.get_config_dir()) {
Ok((file_id, css)) => {
if let Err(e) = self.load_css(file_id, &css) {
errors.push(anyhow!(e));
}
}
}
DaemonCommand::OpenMany { windows, args, should_toggle, sender } => {
let errors = windows
.iter()
.map(|w| {
let (config_name, id) = w;
if should_toggle && self.open_windows.contains_key(id) {
self.close_window(id)
} else {
log::debug!("Config: {}, id: {}", config_name, id);
let window_args = args
.iter()
.filter(|(win_id, ..)| win_id.is_empty() || win_id == id)
.map(|(_, n, v)| (n.clone(), v.clone()))
.collect();
self.open_window(&WindowArguments::new_from_args(
id.to_string(),
config_name.clone(),
window_args,
)?)
}
})
.filter_map(Result::err);
sender.respond_with_error_list(errors)?;
}
DaemonCommand::OpenWindow {
window_name,
instance_id,
pos,
size,
anchor,
screen: monitor,
should_toggle,
duration,
sender,
args,
} => {
let instance_id = instance_id.unwrap_or_else(|| window_name.clone());

let is_open = self.open_windows.contains_key(&instance_id);

let result = if should_toggle && is_open {
self.close_window(&instance_id)
} else {
self.open_window(&WindowArguments {
instance_id,
window_name,
pos,
size,
monitor,
anchor,
duration,
args: args.unwrap_or_default().into_iter().collect(),
})
};

sender.respond_with_result(result)?;
}
DaemonCommand::CloseWindows { windows, sender } => {
let errors = windows.iter().map(|window| self.close_window(window)).filter_map(Result::err);
sender.respond_with_error_list(errors)?;
}
DaemonCommand::PrintState { all, sender } => {
let scope_graph = self.scope_graph.borrow();
let used_globals_names = scope_graph.currently_used_globals();
let output = scope_graph
.global_scope()
.data
.iter()
.filter(|(key, _)| all || used_globals_names.contains(*key))
.map(|(key, value)| format!("{}: {}", key, value))
.join("\n");
sender.send_success(output)?
}
DaemonCommand::GetVar { name, sender } => {
let scope_graph = &*self.scope_graph.borrow();
let vars = &scope_graph.global_scope().data;
match vars.get(name.as_str()) {
Some(x) => sender.send_success(x.to_string())?,
None => sender.send_failure(format!("Variable not found \"{}\"", name))?,
Err(e) => {
errors.push(e);
}
}
DaemonCommand::ListWindows(sender) => {
let output = self.eww_config.get_windows().keys().join("\n");
sender.send_success(output)?
}
DaemonCommand::ListActiveWindows(sender) => {
let output = self.open_windows.iter().map(|(id, window)| format!("{id}: {}", window.name)).join("\n");
sender.send_success(output)?
}
DaemonCommand::PrintDebug(sender) => {
let output = format!("{:#?}", &self);
sender.send_success(output)?

sender.respond_with_error_list(errors)?;
}
DaemonCommand::KillServer => {
log::info!("Received kill command, stopping server!");
self.stop_application();
}
DaemonCommand::CloseAll => {
log::info!("Received close command, closing all windows");
for window_name in self.open_windows.keys().cloned().collect::<Vec<String>>() {
self.close_window(&window_name)?;
}
DaemonCommand::PrintGraph(sender) => sender.send_success(self.scope_graph.borrow().visualize())?,
}
};
DaemonCommand::OpenMany { windows, args, should_toggle, sender } => {
let errors = windows
.iter()
.map(|w| {
let (config_name, id) = w;
if should_toggle && self.open_windows.contains_key(id) {
self.close_window(id)
} else {
log::debug!("Config: {}, id: {}", config_name, id);
let window_args = args
.iter()
.filter(|(win_id, ..)| win_id.is_empty() || win_id == id)
.map(|(_, n, v)| (n.clone(), v.clone()))
.collect();
self.open_window(&WindowArguments::new_from_args(id.to_string(), config_name.clone(), window_args)?)
}
})
.filter_map(Result::err);
sender.respond_with_error_list(errors)?;
}
DaemonCommand::OpenWindow {
window_name,
instance_id,
pos,
size,
anchor,
screen: monitor,
should_toggle,
duration,
sender,
args,
} => {
let instance_id = instance_id.unwrap_or_else(|| window_name.clone());

let is_open = self.open_windows.contains_key(&instance_id);

let result = if should_toggle && is_open {
self.close_window(&instance_id)
} else {
self.open_window(&WindowArguments {
instance_id,
window_name,
pos,
size,
monitor,
anchor,
duration,
args: args.unwrap_or_default().into_iter().collect(),
})
};

if let Err(err) = result {
error_handling_ctx::print_error(err);
sender.respond_with_result(result)?;
}
DaemonCommand::CloseWindows { windows, sender } => {
let errors = windows.iter().map(|window| self.close_window(window)).filter_map(Result::err);
sender.respond_with_error_list(errors)?;
}
DaemonCommand::PrintState { all, sender } => {
let scope_graph = self.scope_graph.borrow();
let used_globals_names = scope_graph.currently_used_globals();
let output = scope_graph
.global_scope()
.data
.iter()
.filter(|(key, _)| all || used_globals_names.contains(*key))
.map(|(key, value)| format!("{}: {}", key, value))
.join("\n");
sender.send_success(output)?
}
DaemonCommand::GetVar { name, sender } => {
let scope_graph = &*self.scope_graph.borrow();
let vars = &scope_graph.global_scope().data;
match vars.get(name.as_str()) {
Some(x) => sender.send_success(x.to_string())?,
None => sender.send_failure(format!("Variable not found \"{}\"", name))?,
}
}
DaemonCommand::ListWindows(sender) => {
let output = self.eww_config.get_windows().keys().join("\n");
sender.send_success(output)?
}
DaemonCommand::ListActiveWindows(sender) => {
let output = self.open_windows.iter().map(|(id, window)| format!("{id}: {}", window.name)).join("\n");
sender.send_success(output)?
}
DaemonCommand::PrintDebug(sender) => {
let output = format!("{:#?}", &self);
sender.send_success(output)?
}
DaemonCommand::PrintGraph(sender) => sender.send_success(self.scope_graph.borrow().visualize())?,
}
Ok(())
}

/// Fully stop eww:
Expand Down Expand Up @@ -375,7 +373,7 @@ impl<B: DisplayBackend> App<B> {

self.instance_id_to_args.insert(instance_id.to_string(), window_args.clone());

let open_result: Result<_> = try {
let open_result: Result<_> = (|| {
let window_name: &str = &window_args.window_name;

let window_def = self.eww_config.get_window(window_name)?.clone();
Expand Down Expand Up @@ -461,7 +459,8 @@ impl<B: DisplayBackend> App<B> {
}

self.open_windows.insert(instance_id.to_string(), eww_window);
};
Ok(())
})();

if let Err(err) = open_result {
self.failed_windows.insert(instance_id.to_string());
Expand Down Expand Up @@ -499,15 +498,15 @@ impl<B: DisplayBackend> App<B> {
pub fn load_css(&mut self, file_id: usize, css: &str) -> Result<()> {
if let Err(err) = self.css_provider.load_from_data(css.as_bytes()) {
static PATTERN: Lazy<regex::Regex> = Lazy::new(|| regex::Regex::new(r"[^:]*:(\d+):(\d+)(.*)$").unwrap());
let nice_error_option: Option<_> = try {
let nice_error_option: Option<_> = (|| {
let captures = PATTERN.captures(err.message())?;
let line = captures.get(1).unwrap().as_str().parse::<usize>().ok()?;
let msg = captures.get(3).unwrap().as_str();
let db = error_handling_ctx::FILE_DATABASE.read().ok()?;
let line_range = db.line_range(file_id, line - 1).ok()?;
let span = Span(line_range.start, line_range.end - 1, file_id);
DiagError(gen_diagnostic!(msg, span))
};
Some(DiagError(gen_diagnostic!(msg, span)))
})();
match nice_error_option {
Some(error) => Err(anyhow!(error)),
None => Err(anyhow!("CSS error: {}", err.message())),
Expand Down
1 change: 0 additions & 1 deletion crates/eww/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#![feature(try_blocks)]
#![allow(rustdoc::private_intra_doc_links)]

extern crate gtk;
Expand Down
Loading

0 comments on commit 52ac617

Please sign in to comment.