Skip to main content

nmrs_gui/
style.rs

1use gtk::gdk::Display;
2use gtk::gio::File;
3use gtk::{CssProvider, STYLE_PROVIDER_PRIORITY_APPLICATION, STYLE_PROVIDER_PRIORITY_USER};
4use std::fs;
5use std::io::Write;
6
7/// Load and apply the user's custom ~/.config/nmrs/style.css.
8/// If the file does not exist it is created with the bundled defaults.
9/// This must be called after any theme provider is registered so that
10/// same-priority (STYLE_PROVIDER_PRIORITY_USER) rules resolve in favour of
11/// the user's stylesheet.
12pub fn load_user_css() {
13    let path = dirs::config_dir()
14        .unwrap_or_default()
15        .join("nmrs/style.css");
16
17    let display = Display::default().expect("No display found");
18
19    if path.exists() {
20        let provider = CssProvider::new();
21        let file = File::for_path(&path);
22
23        provider.load_from_file(&file);
24
25        gtk::style_context_add_provider_for_display(
26            &display,
27            &provider,
28            STYLE_PROVIDER_PRIORITY_USER,
29        );
30    } else {
31        if let Some(parent) = path.parent() {
32            fs::create_dir_all(parent).ok();
33        }
34
35        let default = include_str!("style.css");
36        let mut f = fs::File::create(&path).expect("Failed to create CSS file");
37        f.write_all(default.as_bytes())
38            .expect("Failed to write default CSS");
39    }
40}
41
42pub fn load_css() {
43    let provider = CssProvider::new();
44
45    let css = include_str!("style.css");
46    provider.load_from_data(css);
47
48    let display = Display::default().expect("No display found");
49
50    gtk::style_context_add_provider_for_display(
51        &display,
52        &provider,
53        STYLE_PROVIDER_PRIORITY_APPLICATION,
54    );
55}