This repository was archived by the owner on Jun 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathblocks.rs
324 lines (283 loc) · 8.85 KB
/
blocks.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
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
//! The collection of blocks
pub mod prelude;
use serde::de::Deserialize;
use serde_derive::Deserialize;
use smallvec::SmallVec;
use smartstring::alias::String;
use std::collections::HashMap;
use std::future::Future;
use std::time::Duration;
use tokio::sync::mpsc;
use toml::value::Table;
use crate::click::{ClickHandler, MouseButton};
use crate::config::SharedConfig;
use crate::errors::*;
use crate::formatting::{value::Value, Format};
use crate::protocol::i3bar_event::I3BarEvent;
use crate::signals::Signal;
use crate::widget::State;
use crate::{Request, RequestCmd};
macro_rules! define_blocks {
($($block:ident,)*) => {
$(pub mod $block;)*
#[derive(Deserialize, Debug, Clone, Copy)]
pub enum BlockType {
$(
#[allow(non_camel_case_types)]
$block,
)*
}
impl BlockType {
pub async fn run(self, config: toml::Value, api: CommonApi) -> Result<()> {
let id = api.id;
match self {
$(
Self::$block => {
$block::run(config, api).await.in_block(self, id)
}
)*
}
}
}
};
}
define_blocks!(
apt,
backlight,
battery,
bluetooth,
cpu,
custom,
custom_dbus,
disk_space,
dnf,
docker,
external_ip,
focused_window,
github,
hueshift,
kdeconnect,
load,
maildir,
menu,
memory,
music,
net,
// networkmanager,
notify,
notmuch,
pacman,
pomodoro,
rofication,
sound,
speedtest,
keyboard_layout,
taskwarrior,
temperature,
time,
toggle,
uptime,
watson,
weather,
xrandr,
);
pub type EventsRx = mpsc::Receiver<BlockEvent>;
#[derive(Debug, Clone, Copy)]
pub enum BlockEvent {
Click(I3BarEvent),
Signal(Signal),
}
pub struct CommonApi {
pub id: usize,
pub shared_config: SharedConfig,
pub request_sender: mpsc::Sender<Request>,
pub cmd_buf: SmallVec<[RequestCmd; 4]>,
pub error_interval: Duration,
pub error_format: Option<String>,
}
impl CommonApi {
pub fn hide(&mut self) {
self.cmd_buf.push(RequestCmd::Hide);
}
pub fn hide_buttons(&mut self) {
self.cmd_buf.push(RequestCmd::HideButtons);
}
pub fn show_buttons(&mut self) {
self.cmd_buf.push(RequestCmd::ShowButtons);
}
pub fn show(&mut self) {
self.cmd_buf.push(RequestCmd::Show);
}
pub async fn get_events(&mut self) -> Result<EventsRx> {
let (sender, receiver) = tokio::sync::oneshot::channel();
self.cmd_buf.push(RequestCmd::GetEvents(sender));
self.flush().await?;
receiver.await.ok().error("Failed to get events receiver")
}
pub fn set_icon(&mut self, icon: &str) -> Result<()> {
let icon = if icon.is_empty() {
String::new()
} else {
self.get_icon(icon)?
};
self.cmd_buf.push(RequestCmd::SetIcon(icon));
Ok(())
}
pub fn set_state(&mut self, state: State) {
self.cmd_buf.push(RequestCmd::SetState(state));
}
pub fn set_text(&mut self, text: String) {
self.cmd_buf.push(RequestCmd::SetText(text))
}
pub fn set_texts(&mut self, full: String, short: String) {
self.cmd_buf.push(RequestCmd::SetTexts(full, short))
}
pub fn set_values(&mut self, values: HashMap<String, Value>) {
self.cmd_buf.push(RequestCmd::SetValues(values));
}
pub fn set_format(&mut self, format: Format) {
self.cmd_buf.push(RequestCmd::SetFormat(
format.run(&self.request_sender, self.id),
));
}
pub fn add_button(&mut self, instance: usize, icon: &str) -> Result<()> {
self.cmd_buf
.push(RequestCmd::AddButton(instance, self.get_icon(icon)?));
Ok(())
}
pub fn set_button(&mut self, instance: usize, icon: &str) -> Result<()> {
self.cmd_buf
.push(RequestCmd::SetButton(instance, self.get_icon(icon)?));
Ok(())
}
pub fn set_full_screen(&mut self, value: bool) {
self.cmd_buf.push(RequestCmd::SetFullScreen(value));
}
pub fn preserve(&mut self) {
self.cmd_buf.push(RequestCmd::Preserve);
}
pub fn restore(&mut self) {
self.cmd_buf.push(RequestCmd::Restore);
}
pub async fn get_dbus_connection(&mut self) -> Result<zbus::Connection> {
let (sender, receiver) = tokio::sync::oneshot::channel();
self.cmd_buf.push(RequestCmd::GetDbusConnection(sender));
self.flush().await?;
receiver.await.ok().error("Failed to get dbus connection")?
}
pub async fn get_system_dbus_connection(&mut self) -> Result<zbus::Connection> {
let (sender, receiver) = tokio::sync::oneshot::channel();
self.cmd_buf
.push(RequestCmd::GetSystemDbusConnection(sender));
self.flush().await?;
receiver.await.ok().error("Failed to get dbus connection")?
}
pub async fn flush(&mut self) -> Result<()> {
let cmds = std::mem::replace(&mut self.cmd_buf, SmallVec::new());
self.request_sender
.send(Request {
block_id: self.id,
cmds,
})
.await
.error("Failed to send Request")?;
Ok(())
}
pub fn get_icon(&self, icon: &str) -> Result<String> {
self.shared_config.get_icon(icon)
}
pub async fn recoverable<Fn, Fut, T, E, Msg>(&mut self, mut f: Fn, msg: Msg) -> Result<T>
where
Fn: FnMut() -> Fut,
Fut: Future<Output = StdResult<T, E>>,
E: StdError,
Msg: Clone + Into<String>,
{
let mut focused = false;
let mut been_err = false;
loop {
match f().await {
Ok(res) => {
if been_err {
// TODO restore hidden
// TODO restore the full screen properly
self.set_full_screen(false);
self.restore();
}
return Ok(res);
}
Err(err) => {
if !been_err {
self.preserve();
been_err = true;
}
let retry_at = tokio::time::Instant::now() + self.error_interval;
self.show();
self.set_state(State::Critical);
// TODO: do not toggle fullscreen if the block was already fullscreen before
// the error
loop {
if focused {
self.set_text(format!("{}", err).into());
self.set_full_screen(true);
} else {
self.set_text(
self.error_format
.clone()
.unwrap_or_else(|| msg.clone().into()),
);
self.set_full_screen(false);
}
// Note: self.get_events() calls flush() internally
let mut events = self.get_events().await?;
tokio::select! {
_ = tokio::time::sleep_until(retry_at) => break,
Some(BlockEvent::Click(click)) = events.recv() => {
if click.button == MouseButton::Left {
focused = !focused;
}
}
}
}
}
}
}
}
}
#[derive(Deserialize, Debug)]
pub struct CommonConfig {
#[serde(default)]
pub click: ClickHandler,
#[serde(default)]
pub icons_format: Option<String>,
#[serde(default)]
pub theme_overrides: Option<HashMap<String, String>>,
#[serde(default = "CommonConfig::default_error_interval")]
pub error_interval: u64,
#[serde(default)]
pub error_format: Option<String>,
}
impl CommonConfig {
fn default_error_interval() -> u64 {
5
}
pub fn new(from: &mut toml::Value) -> Result<Self> {
const FIELDS: &[&str] = &[
"click",
"theme_overrides",
"icons_format",
"error_interval",
"error_format",
];
let mut common_table = Table::new();
if let Some(table) = from.as_table_mut() {
for &field in FIELDS {
if let Some(it) = table.remove(field) {
common_table.insert(field.to_string(), it);
}
}
}
let common_value: toml::Value = common_table.into();
CommonConfig::deserialize(common_value).config_error()
}
}