diff --git a/src/main.rs b/src/main.rs index 1e10a3a..5e7e3b4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -105,7 +105,6 @@ async fn main() -> Result<()> { if style_path.exists() { load_css(style_path); - debug!("Loaded CSS watcher file"); } }); diff --git a/src/style.rs b/src/style.rs index 66686d1..a38108d 100644 --- a/src/style.rs +++ b/src/style.rs @@ -2,10 +2,13 @@ use color_eyre::{Help, Report}; use glib::Continue; use gtk::prelude::CssProviderExt; use gtk::{gdk, gio, CssProvider, StyleContext}; -use notify::{Event, RecursiveMode, Result, Watcher}; +use notify::event::{DataChange, ModifyKind}; +use notify::{recommended_watcher, Event, EventKind, RecursiveMode, Result, Watcher}; use std::path::PathBuf; +use std::time::Duration; use tokio::spawn; -use tracing::{error, info}; +use tokio::time::sleep; +use tracing::{debug, error, info}; /// Attempts to load CSS file at the given path /// and attach if to the current GTK application. @@ -15,13 +18,14 @@ use tracing::{error, info}; pub fn load_css(style_path: PathBuf) { let provider = CssProvider::new(); - if let Err(err) = provider.load_from_file(&gio::File::for_path(&style_path)) { - error!("{:?}", Report::new(err) + match provider.load_from_file(&gio::File::for_path(&style_path)) { + Ok(()) => debug!("Loaded css from '{}'", style_path.display()), + Err(err) => error!("{:?}", Report::new(err) .wrap_err("Failed to load CSS") .suggestion("Check the CSS file for errors") .suggestion("GTK CSS uses a subset of the full CSS spec and many properties are not available. Ensure you are not using any unsupported property.") - ); - } + ) + }; let screen = gdk::Screen::default().expect("Failed to get default GTK screen"); StyleContext::add_provider_for_screen(&screen, &provider, 800); @@ -29,24 +33,27 @@ pub fn load_css(style_path: PathBuf) { let (tx, rx) = glib::MainContext::channel(glib::PRIORITY_DEFAULT); spawn(async move { - match notify::recommended_watcher(move |res: Result| match res { - Ok(event) => { + let mut watcher = recommended_watcher(move |res: Result| match res { + Ok(event) if event.kind == EventKind::Modify(ModifyKind::Data(DataChange::Any)) => { + debug!("{event:?}"); if let Some(path) = event.paths.first() { tx.send(path.clone()) .expect("Failed to send style changed message"); } } Err(e) => error!("Error occurred when watching stylesheet: {:?}", e), - }) { - Ok(mut watcher) => { - watcher - .watch(&style_path, RecursiveMode::NonRecursive) - .expect("Unexpected error when attempting to watch CSS"); - } - Err(err) => error!( - "{:?}", - Report::new(err).wrap_err("Failed to start CSS watcher") - ), + _ => {} + }) + .expect("Failed to create CSS file watcher"); + + watcher + .watch(&style_path, RecursiveMode::NonRecursive) + .expect("Failed to start CSS file watcher"); + debug!("Installed CSS file watcher on '{}'", style_path.display()); + + // avoid watcher from dropping + loop { + sleep(Duration::from_secs(1)).await; } });