-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathconfig.rs
More file actions
696 lines (611 loc) · 22.4 KB
/
config.rs
File metadata and controls
696 lines (611 loc) · 22.4 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
#![allow(dead_code)]
use std::{
env,
fmt::{self, Display, Formatter},
io,
path::PathBuf,
sync::mpsc::{self, Receiver},
time::Duration,
};
use notify::{DebouncedEvent, RecommendedWatcher, RecursiveMode, Watcher};
use serde::{
de::{self, Deserializer, Unexpected},
Deserialize,
};
use crate::{
maths_utility::{self, Rect, Vec2},
rendering::layout::{LayoutBlock, LayoutElement},
};
// Workaround for rust not allowing contcatenations of str constants yet:
// https://github.com/rust-lang/rust/issues/31383
macro_rules! CONFIG_DIR {
() => {
".config/wired/"
};
}
macro_rules! CONFIG_FILENAME {
() => {
"wired.ron"
};
}
static mut CONFIG: Option<Config> = None;
#[derive(Debug)]
pub enum Error {
// Config file not found.
NotFound,
// Validation error.
Validate(&'static str),
// Bad hex string error.
Hexadecimal(&'static str),
// IO error reading file.
Io(io::Error),
// Deserialization error.
Ron(ron::de::Error),
// Watch error.
Watch(notify::Error),
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::NotFound => None,
Error::Validate(_) => None,
Error::Hexadecimal(_) => None,
Error::Io(err) => err.source(),
Error::Ron(err) => err.source(),
Error::Watch(err) => err.source(),
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Error::NotFound => write!(f, "No config found"),
Error::Validate(problem) => write!(f, "Error validating config file: {}", problem),
Error::Hexadecimal(problem) => {
write!(f, "Error parsing hexadecimal string: {}", problem)
}
Error::Io(err) => write!(f, "Error reading config file: {}", err),
Error::Ron(err) => write!(f, "Problem with config file: {}", err),
Error::Watch(err) => write!(f, "Error watching config directory: {}", err),
}
}
}
pub struct ConfigWatcher {
watcher: RecommendedWatcher,
receiver: Receiver<DebouncedEvent>,
}
impl ConfigWatcher {
// Returns true if config was updated, false if not.
pub fn check_and_update_config(&self) -> bool {
if let Ok(ev) = self.receiver.try_recv() {
match ev {
DebouncedEvent::Write(p) | DebouncedEvent::Create(p) | DebouncedEvent::Chmod(p) => {
if let Some(file_name) = p.file_name() {
// Make sure the file that was changed is our file, since we watch the
// entire directory.
if file_name == CONFIG_FILENAME!() && Config::try_reload(p) {
return true;
}
}
}
_ => (),
}
}
false
}
}
#[derive(Debug, Deserialize)]
pub struct Config {
// Maximum number of notifications to show on screen at once.
pub max_notifications: usize,
pub timeout: i32, // Default timeout, in milliseconds.
pub poll_interval: u64, // Time between checking for updates, events, drawing, etc.
#[serde(default = "maths_utility::val_500")]
pub idle_poll_interval: u64, // Same as above, but when no notifications are present.
pub layout_blocks: Vec<LayoutBlock>,
// How to handle various DBus expire_timeout values
#[serde(default)]
pub zero_timeout_behavior: ZeroTimeoutBehavior,
// Optional Properties
// The threshold before pausing notifications due to being idle. Unspecified = ignore.
pub idle_threshold: Option<u64>,
#[serde(default)]
pub icon_theme: Option<String>,
// Whether a notification should be sent when the config is reloaded.
#[serde(default = "maths_utility::val_true")]
pub notify_on_reload: bool,
#[serde(default)]
pub notifications_spawn_paused: bool,
// When notifications have been paused due to idle threshold, should we unpause when we get
// input or require the user to manually dismiss them?
#[serde(default)]
pub unpause_on_input: bool,
// Enable/disable notification replace functionality. I don't like how some apps do it.
#[serde(default = "maths_utility::val_true")]
pub replacing_enabled: bool,
// Whether or not to refresh the timeout of a notification on an update
#[serde(default)]
pub replacing_resets_timeout: bool,
// Enable/disable notification closing functionality. I don't like how some apps do it.
#[serde(default = "maths_utility::val_true")]
pub closing_enabled: bool,
// How many notifications are kept in history. Older notifications will be removed first.
// Each notification is roughly 256 bytes (excluding buffers), so do the math there.
#[serde(default = "maths_utility::val_100")]
pub history_length: usize,
// Which input should we follow when follow active monitor is set?
#[serde(default)]
pub focus_follows: FollowMode,
// A file to print notification info to, for scripting purposes.
pub print_to_file: Option<String>,
// Minimum window width and height. This is used to create the base rect that the notification
// grows within.
// The notification window will never be smaller than this.
// A value of 1 means that the window will generally always resize with notification, unless
// you have a 1x1 pixel notification...
#[serde(default)]
pub min_window_width: u32,
#[serde(default)]
pub min_window_height: u32,
#[serde(default = "maths_utility::val_true")]
pub trim_whitespace: bool,
// Draws rectangles around elements.
#[serde(default)]
pub debug: bool,
#[serde(default = "Config::default_debug_color")]
pub debug_color: Color,
#[serde(default = "Config::default_debug_color_alt")]
pub debug_color_alt: Color,
#[serde(default)]
pub shortcuts: ShortcutsConfig,
#[serde(skip)] // derived from user settings
pub(crate) layouts: Vec<LayoutBlock>,
#[serde(skip)] // derived from user settings
pub(crate) is_auto_active_monitor: bool,
}
impl Config {
pub fn default_debug_color() -> Color {
Color::from_rgba(0.0, 1.0, 0.0, 1.0)
}
pub fn default_debug_color_alt() -> Color {
Color::from_rgba(1.0, 0.0, 0.0, 1.0)
}
// Initialize the config. This does a two things:
// - Attempts to locate and load a config file on the machine, and if it can't, then loads the
// default config.
// - If config was loaded successfully, then sets up a watcher on the config file to watch for changes,
// and returns the watcher or None.
pub fn init() -> Option<ConfigWatcher> {
fn assign_config(cfg: Config) {
unsafe {
CONFIG = Some(cfg);
}
}
unsafe {
assert!(CONFIG.is_none());
}
let cfg_file = Config::installed_config();
match cfg_file {
Some(f) => {
let cfg = Config::load_file(f.clone());
match cfg {
Ok(c) => assign_config(c),
Err(e) => {
println!(
"Found a config file: {}, but couldn't load it, so will \
use default one for now.\n\
If you fix the error the config will be reloaded automatically.\n\
\tError: {}\n",
f.to_str().unwrap(),
e
);
assign_config(Config::default());
}
}
// Watch the config file directory for changes, even if it didn't load correctly; we
// assume that the config we found is the one we're using.
// It would be nice to be able to watch the config directories for when a user
// creates a config, but it doesn't seem worthwhile to watch that many directories.
//
// NOTE: watching the directory can actually cause us to try and read all file
// changes in this directory, so we need to remember to check the filename
// before reloading.
let watch = Config::watch(f);
match watch {
Ok(w) => Some(w),
Err(e) => {
println!(
"There was a problem watching the config for changes; so won't watch:\n\t{}",
e
);
None
}
}
}
None => {
println!("Couldn't load a config because we couldn't find one, so will use default.");
assign_config(Config::default());
None
}
}
}
// Get immutable reference to global config variable.
pub fn get() -> &'static Config {
unsafe {
assert!(CONFIG.is_some());
// TODO: can as_ref be removed?
// This unwrap is safe according to the above assert.
CONFIG.as_ref().unwrap()
}
}
// Get mutable reference to global config variable.
pub fn get_mut() -> &'static mut Config {
unsafe {
assert!(CONFIG.is_some());
// TODO: can as_ref be removed?
// This unwrap is safe according to the above assert.
CONFIG.as_mut().unwrap()
}
}
// Attempt to load the config again.
// If we can, then replace the existing config.
// If we can't, then do nothing.
pub fn try_reload(path: PathBuf) -> bool {
match Config::load_file(path) {
Ok(cfg) => {
unsafe {
CONFIG = Some(cfg);
}
println!("Config reloaded.");
true
}
Err(e) => {
println!("Tried to reload the config but couldn't: {}", e);
false
}
}
}
// https://github.com/alacritty/alacritty/blob/f14d24542c3ceda3b508c707eb79cf2fe2a04bd1/alacritty/src/config/mod.rs#L98
fn installed_config() -> Option<PathBuf> {
xdg::BaseDirectories::with_prefix("wired")
.ok()
.and_then(|xdg| xdg.find_config_file(CONFIG_FILENAME!()))
.or_else(|| {
xdg::BaseDirectories::new()
.ok()
.and_then(|fallback| fallback.find_config_file(CONFIG_FILENAME!()))
})
.or_else(|| {
if let Ok(home) = env::var("HOME") {
// Fallback path: `$HOME/.config/wired/wired.ron`
let fallback = PathBuf::from(&home).join(concat!(CONFIG_DIR!(), CONFIG_FILENAME!()));
if fallback.exists() {
return Some(fallback);
}
// Fallback path: `$HOME/.wired.ron`
let fallback = PathBuf::from(&home).join(CONFIG_FILENAME!());
if fallback.exists() {
return Some(fallback);
}
}
None
})
}
// Load config or return error.
pub fn load_file(path: PathBuf) -> Result<Self, Error> {
let cfg_string = std::fs::read_to_string(path);
let cfg_string = match cfg_string {
Ok(mut string) => {
string.insert_str(0, "#![enable(implicit_some)]\n");
string
}
Err(e) => return Err(Error::Io(e)),
};
Config::load_str(cfg_string.as_str())
}
pub fn load_str(cfg_str: &str) -> Result<Self, Error> {
// Really ugly and annoying hack because ron doesn't allow implicit some by
// default.
let string = format!("#![enable(implicit_some)]\n{}", cfg_str);
let config: Result<Self, _> = ron::de::from_str(string.as_str());
match config {
Ok(cfg) => Config::transform_and_validate(cfg),
Err(e) => Err(Error::Ron(e)),
}
}
pub fn transform_and_validate(mut config: Config) -> Result<Self, Error> {
// NOTE: we might actually want to search for the "root" text.
if config.layout_blocks.is_empty() {
return Err(Error::Validate("Config did not contain any layout blocks!"));
}
// Look for children of current root.
// If child found, insert it and then look for children of that node.
let mut blocks = config.layout_blocks;
// Check that all blocks are unique.
for i in 0..blocks.len() - 1 {
for j in 0..blocks.len() {
if blocks[i].name == blocks[j].name && i != j {
return Err(Error::Validate("All LayoutBlocks must have unique names!"));
}
}
}
let mut roots: Vec<LayoutBlock> = vec![];
let mut i = 0;
while i < blocks.len() {
if blocks[i].parent.is_empty() {
roots.push(blocks.swap_remove(i));
} else {
i += 1;
}
}
config.layout_blocks = vec![]; // "Take" vec from config.
fn find_and_add_children(
cur_root: &mut LayoutBlock,
mut remaining: Vec<LayoutBlock>,
) -> Vec<LayoutBlock> {
let mut i = 0;
while i < remaining.len() {
if remaining[i].parent == cur_root.name {
let mut block = remaining.swap_remove(i);
remaining = find_and_add_children(&mut block, remaining);
cur_root.children.push(block);
// Back to beginning, as remaining has certainly changed and our information is
// outdated.
// There's surely a better way of doing this, but it works fine for now.
i = 0;
} else {
i += 1;
}
}
remaining
}
for mut root in roots {
blocks = find_and_add_children(&mut root, blocks);
match root.params {
LayoutElement::NotificationBlock(_) => {
config.layouts.push(root);
}
_ => {
return Err(Error::Validate(
"Root LayoutBlock params must be of type NotificationBlock!",
))
}
}
}
if !blocks.is_empty() && config.debug {
eprintln!("There were {} blocks remaining after creating the layout tree. Something must be wrong here.", blocks.len());
}
config.is_auto_active_monitor = config
.layouts
.iter()
.any(|layout| layout.as_notification_block().monitor < 0);
Ok(config)
}
// Watch config file for changes, and send message to `Configwatcher` when something
// happens.
pub fn watch(mut path: PathBuf) -> Result<ConfigWatcher, Error> {
let (sender, receiver) = mpsc::channel();
// Duration is a debouncing period.
let mut watcher =
notify::watcher(sender, Duration::from_millis(10)).expect("Unable to spawn file watcher.");
// Watch dir.
path.pop();
let path = std::fs::canonicalize(path).expect("Couldn't canonicalize path, wtf.");
let result = watcher.watch(path, RecursiveMode::NonRecursive);
match result {
Ok(_) => Ok(ConfigWatcher { watcher, receiver }),
Err(e) => Err(Error::Watch(e)),
}
}
}
impl Default for Config {
fn default() -> Self {
Config::load_str(include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
CONFIG_FILENAME!()
)))
.expect("Failed to load default config. Maintainer fucked something up.\n")
}
}
#[derive(Debug, Deserialize)]
pub struct ShortcutsConfig {
pub notification_interact: Option<u16>,
pub notification_close: Option<u16>,
pub notification_closeall: Option<u16>,
pub notification_pause: Option<u16>,
pub notification_action1: Option<u16>,
pub notification_action2: Option<u16>,
pub notification_action3: Option<u16>,
pub notification_action4: Option<u16>,
pub notification_action1_and_close: Option<u16>,
pub notification_action2_and_close: Option<u16>,
pub notification_action3_and_close: Option<u16>,
pub notification_action4_and_close: Option<u16>,
pub notification_interact_and_close: Option<u16>,
}
impl Default for ShortcutsConfig {
fn default() -> Self {
Self {
notification_interact: Some(1),
notification_close: Some(2),
notification_closeall: Some(7),
notification_pause: None,
notification_action1: Some(3),
notification_action2: None,
notification_action3: None,
notification_action4: None,
notification_action1_and_close: None,
notification_action2_and_close: None,
notification_action3_and_close: None,
notification_action4_and_close: None,
notification_interact_and_close: None,
}
}
}
#[derive(Debug, Deserialize, Clone)]
pub enum ZeroTimeoutBehavior {
// Uses `expire_time`.
UseDefault,
// Treats zero as 'never expire'.
NeverExpire,
}
impl Default for ZeroTimeoutBehavior {
fn default() -> Self {
Self::NeverExpire
}
}
#[derive(Debug, Deserialize, Clone)]
pub enum FollowMode {
Mouse,
Window,
}
impl Default for FollowMode {
fn default() -> Self {
Self::Mouse
}
}
#[derive(Debug, Deserialize, Clone)]
pub struct Padding {
pub left: f64,
pub right: f64,
pub top: f64,
pub bottom: f64,
}
#[derive(Debug, Deserialize, Clone)]
pub struct Offset {
pub x: f64,
pub y: f64,
}
#[derive(Debug, Deserialize, Clone)]
pub enum AnchorPosition {
TL,
LT,
TM,
MT,
TR,
RT,
MR,
RM,
BR,
RB,
BM,
MB,
BL,
LB,
ML,
LM,
MM,
}
#[derive(Debug, Clone)]
pub struct Color {
pub r: f64,
pub g: f64,
pub b: f64,
pub a: f64,
}
impl Color {
pub fn from_rgba(r: f64, g: f64, b: f64, a: f64) -> Self {
Color { r, g, b, a }
}
pub fn from_hex(hex: &str) -> Result<Self, Error> {
// Sanitize string a little.
// Works for strings in format: "#ff000000", "#0xff000000", "0xff000000".
// We also support hex strings that don't specify alpha: "#000000"
let sanitized = hex.trim_start_matches('#').trim_start_matches("0x");
// Convert string to base-16 u32.
let dec = u32::from_str_radix(sanitized, 16);
let dec = match dec {
Ok(d) => d,
Err(_) => return Err(Error::Hexadecimal("Invalid hexadecimal string.")),
};
// If we have 8 chars, then this is hex string includes alpha, if we have 6, then it
// doesn't. Anything else at this point is invalid.
let len = sanitized.chars().count();
if len == 8 {
let a = ((dec >> 24) & 0xff) as f64 / 255.0;
let r = ((dec >> 16) & 0xff) as f64 / 255.0;
let g = ((dec >> 8) & 0xff) as f64 / 255.0;
let b = (dec & 0xff) as f64 / 255.0;
Ok(Color::from_rgba(r, g, b, a))
} else if len == 6 {
let a = 1.0;
let r = ((dec >> 16) & 0xff) as f64 / 255.0;
let g = ((dec >> 8) & 0xff) as f64 / 255.0;
let b = (dec & 0xff) as f64 / 255.0;
Ok(Color::from_rgba(r, g, b, a))
} else {
Err(Error::Hexadecimal("Incorrect hexadecimal string length."))
}
}
}
// We manually implement deserialize so we can nicely support letting users use hex or rgba codes.
// Ron says the position is col: 0, line: 0 when we error during this, because we're directly
// deserializing the struct? Not sure how we would fix this.
impl<'de> Deserialize<'de> for Color {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Intermediate struct with optional fields for ergonomics.
#[derive(Deserialize)]
#[serde(rename = "Color")]
struct Col {
r: Option<f64>,
g: Option<f64>,
b: Option<f64>,
a: Option<f64>,
hex: Option<String>,
}
// Deserialize into the intermediate struct.
let col = Col::deserialize(deserializer)?;
// Check that user hasn't defined both rgba and hex.
if col.hex.is_some() && (col.r.is_some() || col.g.is_some() || col.b.is_some() || col.a.is_some()) {
return Err(de::Error::custom(
"`hex` and `rgba` fields cannot both be present in the same `Color`",
));
}
if let Some(hex) = col.hex {
#[allow(clippy::or_fun_call)]
return Color::from_hex(&hex).or(Err(de::Error::invalid_value(
Unexpected::Str(&hex),
&"a valid hexadecimal string",
)));
} else if let (Some(r), Some(g), Some(b), Some(a)) = (col.r, col.g, col.b, col.a) {
Ok(Color::from_rgba(r, g, b, a))
} else {
Err(de::Error::missing_field("`r`, `g`, `b`, `a` or `hex`"))
}
}
}
impl Padding {
pub fn new(left: f64, right: f64, top: f64, bottom: f64) -> Self {
Padding {
left,
right,
top,
bottom,
}
}
pub fn width(&self) -> f64 {
self.left + self.right
}
pub fn height(&self) -> f64 {
self.top + self.bottom
}
}
impl AnchorPosition {
pub fn get_pos(&self, rect: &Rect) -> Vec2 {
match self {
AnchorPosition::TL | AnchorPosition::LT => rect.top_left(),
AnchorPosition::TM | AnchorPosition::MT => rect.mid_top(),
AnchorPosition::TR | AnchorPosition::RT => rect.top_right(),
AnchorPosition::MR | AnchorPosition::RM => rect.mid_right(),
AnchorPosition::BR | AnchorPosition::RB => rect.bottom_right(),
AnchorPosition::BM | AnchorPosition::MB => rect.mid_bottom(),
AnchorPosition::BL | AnchorPosition::LB => rect.bottom_left(),
AnchorPosition::ML | AnchorPosition::LM => rect.mid_left(),
AnchorPosition::MM => rect.mid_mid(),
}
}
}