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
|
use crate::error::{ Error, Result };
use crate::facility::{ FacilityMap, FacilityType };
use crate::facility::i3::{
parse_change_string, parse_name_string, EventType, I3
};
use crate::module::{ CreatableModule, Module };
use std::sync::Arc;
use std::time::Duration;
use async_channel::{ unbounded, Sender, Receiver };
use async_executor::StaticExecutor;
use async_lock::Mutex;
use async_task::Task;
use futures_lite::future::block_on;
pub struct I3ModeModule {
_update_task: Task<()>,
current_mode: Arc<Mutex<String>>,
}
impl CreatableModule for I3ModeModule {
const REQUIRED_FACILITIES: FacilityType = FacilityType::I3;
async fn new(facilities: &mut FacilityMap,
executor: &'static StaticExecutor,
redraw_sender: Sender<()>)
-> Result<I3ModeModule>
{
let i3: &mut I3 = facilities.get().ok_or(Error::custom(
"I3 mode module can't access i3 facility."))?;
let (sender, receiver) = unbounded();
if !i3.subscribe(EventType::MODE, sender).await? {
return Err(Error::custom("Unable to subscribe to i3 mode changes."));
}
let current_mode = Arc::new(Mutex::new(parse_name_string(
i3.command(12, "").await?.as_bytes())?));
let update_task = executor.spawn(update_loop(receiver,
Arc::clone(¤t_mode),
redraw_sender));
Ok(I3ModeModule {
_update_task: update_task,
current_mode,
})
}
}
impl Module for I3ModeModule {
fn format(&mut self, _facilities: &mut FacilityMap) -> Result<String> {
/* A shame we can't be async. */
Ok(format!("--{}--", block_on(self.current_mode.lock())))
}
fn sleep_duration(&self) -> Option<Duration> {
None
}
fn is_visible(&self) -> bool {
*block_on(self.current_mode.lock()) != "default"
}
}
async fn update_loop(receiver: Receiver<(EventType, String)>,
current_mode: Arc<Mutex<String>>,
redraw_sender: Sender<()>)
{
loop {
match receiver.recv().await {
Ok((_, body)) => {
match parse_change_string(body.as_bytes()) {
Ok(new_mode) => {
*current_mode.lock().await = new_mode;
if let Err(error) = redraw_sender.send(()).await {
Into::<Error>::into(error).log()
}
}
Err(error) => { error.log(); }
}
}
Err(error) => {
Into::<Error>::into(error).log();
}
}
}
}
|