fix: css watcher not working

This commit is contained in:
Jake Stanger 2022-10-16 22:21:51 +01:00
parent e23e691bc6
commit cbd0c49e25
No known key found for this signature in database
GPG Key ID: C51FC8F9CB0BEA61
2 changed files with 25 additions and 19 deletions

View File

@ -105,7 +105,6 @@ async fn main() -> Result<()> {
if style_path.exists() {
load_css(style_path);
debug!("Loaded CSS watcher file");
}
});

View File

@ -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<Event>| match res {
Ok(event) => {
let mut watcher = recommended_watcher(move |res: Result<Event>| 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) => {
_ => {}
})
.expect("Failed to create CSS file 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 start CSS file watcher");
debug!("Installed CSS file watcher on '{}'", style_path.display());
// avoid watcher from dropping
loop {
sleep(Duration::from_secs(1)).await;
}
});