zng_view/config/
dconf.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use std::{io::BufRead as _, time::Duration};

use zng_unit::{Rgba, TimeUnits as _};
use zng_view_api::{
    config::{
        AnimationsConfig, ChromeConfig, ColorScheme, ColorsConfig, FontAntiAliasing, KeyRepeatConfig, LocaleConfig, MultiClickConfig,
        TouchConfig,
    },
    Event,
};

use crate::AppEvent;

pub fn font_aa() -> FontAntiAliasing {
    super::other::font_aa()
}

pub fn multi_click_config() -> MultiClickConfig {
    let mut cfg = MultiClickConfig::default();
    if let Some(d) = dconf_uint("/org/gnome/desktop/peripherals/mouse/double-click") {
        cfg.time = d.ms();
    }
    cfg
}

pub fn animations_config() -> AnimationsConfig {
    let mut cfg = AnimationsConfig::default();
    if let Some(e) = dconf_bool("/org/gnome/desktop/interface/enable-animations") {
        cfg.enabled = e;
    }
    if let Some(d) = dconf_uint("/org/gnome/desktop/interface/cursor-blink-time") {
        cfg.caret_blink_interval = (d / 2).ms();
    }
    if let Some(e) = dconf_bool("/org/gnome/desktop/interface/cursor-blink") {
        if !e {
            cfg.caret_blink_interval = Duration::MAX;
        }
    }
    cfg
}

pub fn key_repeat_config() -> KeyRepeatConfig {
    let mut cfg = KeyRepeatConfig::default();
    if let Some(d) = dconf_uint("/org/gnome/desktop/peripherals/keyboard/delay") {
        cfg.start_delay = d.ms();
    }
    if let Some(d) = dconf_uint("/org/gnome/desktop/peripherals/keyboard/repeat-interval") {
        cfg.interval = d.ms();
    }
    cfg
}

pub fn touch_config() -> TouchConfig {
    super::other::touch_config()
}

pub fn colors_config() -> ColorsConfig {
    let scheme = match dconf("/org/gnome/desktop/interface/color-scheme") {
        Some(cs) => {
            if cs.contains("dark") {
                ColorScheme::Dark
            } else {
                ColorScheme::Light
            }
        }
        None => ColorScheme::Light,
    };

    // the color value is not in any config, need to parse theme name
    let theme = dconf("/org/gnome/desktop/interface/gtk-theme");
    let theme = match theme.as_ref() {
        Some(n) => n.strip_prefix("Yaru-").unwrap_or("").split('-').next().unwrap_or(""),
        None => "?",
    };
    // see https://github.com/ubuntu/yaru/blob/6e28865e0ce55c0f95d17a25871618b1660e97b5/common/accent-colors.scss.in
    let accent = match theme {
        "" => Rgba::new(233, 84, 32, 255),               // #E95420
        "bark" => Rgba::new(120, 120, 89, 255),          // #787859
        "sage" => Rgba::new(101, 123, 105, 255),         // #657b69
        "olive" => Rgba::new(75, 133, 1, 255),           // #4B8501
        "viridian" => Rgba::new(3, 135, 91, 255),        // #03875b
        "prussiangreen" => Rgba::new(48, 130, 128, 255), // #308280
        "blue" => Rgba::new(0, 115, 229, 255),           // #0073E5
        "purple" => Rgba::new(119, 100, 216, 255),       // #7764d8
        "magenta" => Rgba::new(179, 76, 179, 255),       // #b34cb3
        "red" => Rgba::new(218, 52, 80, 255),            // #DA3450
        _ => ColorsConfig::default().accent,
    };

    ColorsConfig { scheme, accent }
}

pub fn locale_config() -> LocaleConfig {
    // sys_locale
    super::other::locale_config()
}

pub fn chrome_config() -> ChromeConfig {
    let is_wayland = std::env::var("WAYLAND_DISPLAY").is_ok();
    // VSCode/Electron, it changes XDG_CURRENT_DESKTOP to "Unity" and sets ORIGINAL_XDG_CURRENT_DESKTOP,
    // so running from VSCode gets the wrong value.
    let is_gnome = std::env::var("ORIGINAL_XDG_CURRENT_DESKTOP")
        .or_else(|_| std::env::var("XDG_CURRENT_DESKTOP"))
        .map_or(false, |val| val.contains("GNOME"));
    ChromeConfig {
        prefer_custom: is_gnome,
        provided: !(is_wayland && is_gnome),
    }
}

fn on_change(key: &str, s: &crate::AppEventSender) {
    // println!("{key}"); // to discover keys, uncomment and change the config in system config app.

    match key {
        "/org/gnome/desktop/interface/color-scheme" | "/org/gnome/desktop/interface/gtk-theme" => {
            let _ = s.send(AppEvent::Notify(Event::ColorsConfigChanged(colors_config())));
        }
        "/org/gnome/desktop/peripherals/keyboard/delay" | "/org/gnome/desktop/peripherals/keyboard/repeat-interval" => {
            let _ = s.send(AppEvent::Notify(Event::KeyRepeatConfigChanged(key_repeat_config())));
        }
        "/org/gnome/desktop/peripherals/mouse/double-click" => {
            let _ = s.send(AppEvent::Notify(Event::MultiClickConfigChanged(multi_click_config())));
        }
        "/org/gnome/desktop/interface/enable-animations"
        | "/org/gnome/desktop/interface/cursor-blink-time"
        | "/org/gnome/desktop/interface/cursor-blink" => {
            let _ = s.send(AppEvent::Notify(Event::AnimationsConfigChanged(animations_config())));
        }
        _ => {}
    }
}

fn dconf_bool(key: &str) -> Option<bool> {
    let s = dconf(key)?;
    match s.parse::<bool>() {
        Ok(b) => Some(b),
        Err(e) => {
            tracing::error!("unexpected value for {key} '{s}', parse error: {e}");
            None
        }
    }
}

fn dconf_uint(key: &str) -> Option<u64> {
    let s = dconf(key)?;
    let s = if let Some((t, i)) = s.rsplit_once(' ') {
        if !t.starts_with("uint") {
            tracing::error!("unexpected value for {key} '{s}'");
            return None;
        }
        i
    } else {
        s.as_str()
    };
    match s.parse::<u64>() {
        Ok(i) => Some(i),
        Err(e) => {
            tracing::error!("unexpected value for {key} '{s}', parse error: {e}");
            None
        }
    }
}

fn dconf(key: &str) -> Option<String> {
    let out = std::process::Command::new("dconf").arg("read").arg(key).output();
    match out {
        Ok(s) => {
            if s.status.success() {
                Some(String::from_utf8_lossy(&s.stdout).trim().to_owned())
            } else {
                let e = String::from_utf8_lossy(&s.stderr);
                tracing::error!("dconf read {key} error, {}", e.lines().next().unwrap_or_default());
                None
            }
        }
        Err(e) => {
            tracing::error!("cannot run dconf, {e}");
            None
        }
    }
}

pub fn spawn_listener(event_loop: crate::AppEventSender) -> Option<Box<dyn FnOnce()>> {
    let mut w = std::process::Command::new("dconf");
    w.arg("watch")
        .arg("/")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null());

    let mut w = match w.spawn() {
        Ok(w) => w,
        Err(e) => {
            tracing::error!("cannot monitor config, dconf did not spawn, {e}");
            return None;
        }
    };
    let stdout = w.stdout.take().unwrap();
    std::thread::spawn(move || {
        for line in std::io::BufReader::new(stdout).lines() {
            match line {
                Ok(l) => {
                    if l.starts_with('/') {
                        on_change(&l, &event_loop);
                    }
                }
                Err(_) => {
                    break;
                }
            }
        }
    });

    Some(Box::new(move || {
        let _ = w.kill();
        let _ = w.wait();
    }))
}