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
use crate::layouts::Layout;
use crate::models::TagId;
use crate::{Command, ReleaseScratchPadOption};
use std::env;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use tokio::fs;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::mpsc;
#[derive(Debug)]
pub struct CommandPipe {
pipe_file: PathBuf,
rx: mpsc::UnboundedReceiver<Command>,
}
impl Drop for CommandPipe {
fn drop(&mut self) {
use std::os::unix::fs::OpenOptionsExt;
self.rx.close();
std::fs::OpenOptions::new()
.write(true)
.custom_flags(nix::fcntl::OFlag::O_NONBLOCK.bits())
.open(self.pipe_file.clone())
.ok();
}
}
impl CommandPipe {
pub async fn new(pipe_file: PathBuf) -> Result<Self, std::io::Error> {
fs::remove_file(pipe_file.as_path()).await.ok();
if let Err(e) = nix::unistd::mkfifo(&pipe_file, nix::sys::stat::Mode::S_IRWXU) {
tracing::error!("Failed to create new fifo {:?}", e);
}
let path = pipe_file.clone();
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(async move {
while !tx.is_closed() {
read_from_pipe(&path, &tx).await;
}
fs::remove_file(path).await.ok();
});
Ok(Self { pipe_file, rx })
}
pub fn pipe_name() -> PathBuf {
let display = env::var("DISPLAY")
.ok()
.and_then(|d| d.rsplit_once(':').map(|(_, r)| r.to_owned()))
.unwrap_or_else(|| "0".to_string());
PathBuf::from(format!("command-{}.pipe", display))
}
pub async fn read_command(&mut self) -> Option<Command> {
self.rx.recv().await
}
}
async fn read_from_pipe(pipe_file: &Path, tx: &mpsc::UnboundedSender<Command>) -> Option<()> {
let file = fs::File::open(pipe_file).await.ok()?;
let mut lines = BufReader::new(file).lines();
while let Some(line) = lines.next_line().await.ok()? {
let cmd = match parse_command(&line) {
Ok(cmd) => cmd,
Err(err) => {
tracing::error!("An error occurred while parsing the command: {}", err);
return None;
}
};
tx.send(cmd).ok()?;
}
Some(())
}
fn parse_command(s: &str) -> Result<Command, Box<dyn std::error::Error>> {
let (head, rest) = s.split_once(' ').unwrap_or((s, ""));
match head {
"MoveWindowDown" => Ok(Command::MoveWindowDown),
"MoveWindowTop" => build_move_window_top(rest),
"MoveWindowUp" => Ok(Command::MoveWindowUp),
"MoveWindowToNextTag" => build_move_window_to_next_tag(rest),
"MoveWindowToPreviousTag" => build_move_window_to_previous_tag(rest),
"MoveWindowToLastWorkspace" => Ok(Command::MoveWindowToLastWorkspace),
"MoveWindowToNextWorkspace" => Ok(Command::MoveWindowToNextWorkspace),
"MoveWindowToPreviousWorkspace" => Ok(Command::MoveWindowToPreviousWorkspace),
"SendWindowToTag" => build_send_window_to_tag(rest),
"FocusWindowDown" => Ok(Command::FocusWindowDown),
"FocusWindowTop" => build_focus_window_top(rest),
"FocusWindowUp" => Ok(Command::FocusWindowUp),
"FocusNextTag" => Ok(Command::FocusNextTag),
"FocusPreviousTag" => Ok(Command::FocusPreviousTag),
"FocusWorkspaceNext" => Ok(Command::FocusWorkspaceNext),
"FocusWorkspacePrevious" => Ok(Command::FocusWorkspacePrevious),
"DecreaseMainWidth" => build_decrease_main_width(rest),
"IncreaseMainWidth" => build_increase_main_width(rest),
"NextLayout" => Ok(Command::NextLayout),
"PreviousLayout" => Ok(Command::PreviousLayout),
"RotateTag" => Ok(Command::RotateTag),
"SetLayout" => build_set_layout(rest),
"SetMarginMultiplier" => build_set_margin_multiplier(rest),
"ToggleScratchPad" => build_toggle_scratchpad(rest),
"AttachScratchPad" => build_attach_scratchpad(rest),
"ReleaseScratchPad" => Ok(build_release_scratchpad(rest)),
"NextScratchPadWindow" => Ok(Command::NextScratchPadWindow {
scratchpad: rest.to_owned().into(),
}),
"PrevScratchPadWindow" => Ok(Command::PrevScratchPadWindow {
scratchpad: rest.to_owned().into(),
}),
"FloatingToTile" => Ok(Command::FloatingToTile),
"TileToFloating" => Ok(Command::TileToFloating),
"ToggleFloating" => Ok(Command::ToggleFloating),
"GoToTag" => build_go_to_tag(rest),
"ReturnToLastTag" => Ok(Command::ReturnToLastTag),
"SendWorkspaceToTag" => build_send_workspace_to_tag(rest),
"SwapScreens" => Ok(Command::SwapScreens),
"ToggleFullScreen" => Ok(Command::ToggleFullScreen),
"ToggleSticky" => Ok(Command::ToggleSticky),
"CloseWindow" => Ok(Command::CloseWindow),
"CloseAllOtherWindows" => Ok(Command::CloseAllOtherWindows),
"SoftReload" => Ok(Command::SoftReload),
_ => Ok(Command::Other(s.into())),
}
}
fn build_attach_scratchpad(raw: &str) -> Result<Command, Box<dyn std::error::Error>> {
let name = if raw.is_empty() {
return Err("missing argument scratchpad's name".into());
} else {
raw
};
Ok(Command::AttachScratchPad {
scratchpad: name.into(),
window: None,
})
}
fn build_release_scratchpad(raw: &str) -> Command {
if raw.is_empty() {
Command::ReleaseScratchPad {
window: ReleaseScratchPadOption::None,
tag: None,
}
} else if let Ok(tag_id) = usize::from_str(raw) {
Command::ReleaseScratchPad {
window: ReleaseScratchPadOption::None,
tag: Some(tag_id),
}
} else {
Command::ReleaseScratchPad {
window: ReleaseScratchPadOption::ScratchpadName(raw.into()),
tag: None,
}
}
}
fn build_toggle_scratchpad(raw: &str) -> Result<Command, Box<dyn std::error::Error>> {
let name = if raw.is_empty() {
return Err("missing argument scratchpad's name".into());
} else {
raw
};
Ok(Command::ToggleScratchPad(name.into()))
}
fn build_go_to_tag(raw: &str) -> Result<Command, Box<dyn std::error::Error>> {
let headless = without_head(raw, "GoToTag ");
let parts: Vec<&str> = headless.split(' ').collect();
let tag: TagId = parts.first().ok_or("missing argument tag_id")?.parse()?;
let swap: bool = parts.get(1).ok_or("missing argument swap")?.parse()?;
Ok(Command::GoToTag { tag, swap })
}
fn build_send_window_to_tag(raw: &str) -> Result<Command, Box<dyn std::error::Error>> {
let tag_id = if raw.is_empty() {
return Err("missing argument tag_id".into());
} else {
TagId::from_str(raw)?
};
Ok(Command::SendWindowToTag {
window: None,
tag: tag_id,
})
}
fn build_send_workspace_to_tag(raw: &str) -> Result<Command, Box<dyn std::error::Error>> {
if raw.is_empty() {
return Err("missing argument workspace index".into());
}
let mut parts = raw.split(' ');
let ws_index: usize = parts
.next()
.expect("split() always returns an array of at least 1 element")
.parse()?;
let tag_index: usize = parts.next().ok_or("missing argument tag index")?.parse()?;
Ok(Command::SendWorkspaceToTag(ws_index, tag_index))
}
fn build_set_layout(raw: &str) -> Result<Command, Box<dyn std::error::Error>> {
let layout_name = if raw.is_empty() {
return Err("missing layout name".into());
} else {
raw
};
Ok(Command::SetLayout(Layout::from_str(layout_name)?))
}
fn build_set_margin_multiplier(raw: &str) -> Result<Command, Box<dyn std::error::Error>> {
let margin_multiplier = if raw.is_empty() {
return Err("missing argument multiplier".into());
} else {
f32::from_str(raw)?
};
Ok(Command::SetMarginMultiplier(margin_multiplier))
}
fn build_focus_window_top(raw: &str) -> Result<Command, Box<dyn std::error::Error>> {
let swap = if raw.is_empty() {
false
} else {
bool::from_str(raw)?
};
Ok(Command::FocusWindowTop { swap })
}
fn build_move_window_top(raw: &str) -> Result<Command, Box<dyn std::error::Error>> {
let swap = if raw.is_empty() {
true
} else {
bool::from_str(raw)?
};
Ok(Command::MoveWindowTop { swap })
}
fn build_move_window_to_next_tag(raw: &str) -> Result<Command, Box<dyn std::error::Error>> {
let follow = if raw.is_empty() {
true
} else {
bool::from_str(raw)?
};
Ok(Command::MoveWindowToNextTag { follow })
}
fn build_move_window_to_previous_tag(raw: &str) -> Result<Command, Box<dyn std::error::Error>> {
let follow = if raw.is_empty() {
true
} else {
bool::from_str(raw)?
};
Ok(Command::MoveWindowToPreviousTag { follow })
}
fn build_increase_main_width(raw: &str) -> Result<Command, Box<dyn std::error::Error>> {
let headless = without_head(raw, "IncreaseMainWidth ");
let parts: Vec<&str> = headless.split(' ').collect();
let change: i8 = parts.first().ok_or("missing argument change")?.parse()?;
Ok(Command::IncreaseMainWidth(change))
}
fn build_decrease_main_width(raw: &str) -> Result<Command, Box<dyn std::error::Error>> {
let headless = without_head(raw, "DecreaseMainWidth ");
let parts: Vec<&str> = headless.split(' ').collect();
let change: i8 = parts.first().ok_or("missing argument change")?.parse()?;
Ok(Command::DecreaseMainWidth(change))
}
fn without_head<'a, 'b>(s: &'a str, head: &'b str) -> &'a str {
if !s.starts_with(head) {
return s;
}
&s[head.len()..]
}
#[cfg(test)]
mod test {
use super::*;
use crate::utils::helpers::test::temp_path;
use tokio::io::AsyncWriteExt;
use tokio::time;
#[tokio::test]
async fn read_good_command() {
let pipe_file = temp_path().await.unwrap();
let mut command_pipe = CommandPipe::new(pipe_file.clone()).await.unwrap();
{
let mut pipe = fs::OpenOptions::new()
.write(true)
.open(&pipe_file)
.await
.unwrap();
pipe.write_all(b"SoftReload\n").await.unwrap();
pipe.flush().await.unwrap();
assert_eq!(
Command::SoftReload,
command_pipe.read_command().await.unwrap()
);
}
}
#[tokio::test]
async fn read_bad_command() {
let pipe_file = temp_path().await.unwrap();
let mut command_pipe = CommandPipe::new(pipe_file.clone()).await.unwrap();
{
let mut pipe = fs::OpenOptions::new()
.write(true)
.open(&pipe_file)
.await
.unwrap();
pipe.write_all(b"Hello World\n").await.unwrap();
pipe.flush().await.unwrap();
assert_eq!(
Command::Other("Hello World".to_string()),
command_pipe.read_command().await.unwrap()
);
}
}
#[tokio::test]
async fn pipe_cleanup() {
let pipe_file = temp_path().await.unwrap();
fs::remove_file(pipe_file.as_path()).await.unwrap();
{
let _command_pipe = CommandPipe::new(pipe_file.clone()).await.unwrap();
let mut pipe = fs::OpenOptions::new()
.write(true)
.open(&pipe_file)
.await
.unwrap();
pipe.write_all(b"ToggleFullScreen\n").await.unwrap();
pipe.flush().await.unwrap();
}
time::sleep(time::Duration::from_millis(100)).await;
{
assert!(!pipe_file.exists());
}
}
#[test]
fn build_toggle_scratchpad_without_parameter() {
assert!(build_toggle_scratchpad("").is_err());
}
#[test]
fn build_send_window_to_tag_without_parameter() {
assert!(build_send_window_to_tag("").is_err());
}
#[test]
fn build_send_workspace_to_tag_without_parameter() {
assert!(build_send_workspace_to_tag("").is_err());
}
#[test]
fn build_set_layout_without_parameter() {
assert!(build_set_layout("").is_err());
}
#[test]
fn build_set_margin_multiplier_without_parameter() {
assert!(build_set_margin_multiplier("").is_err());
}
#[test]
fn build_move_window_top_without_parameter() {
assert_eq!(
build_move_window_top("").unwrap(),
Command::MoveWindowTop { swap: true }
);
}
#[test]
fn build_focus_window_top_without_parameter() {
assert_eq!(
build_focus_window_top("").unwrap(),
Command::FocusWindowTop { swap: false }
);
}
#[test]
fn build_move_window_to_next_tag_without_parameter() {
assert_eq!(
build_move_window_to_next_tag("").unwrap(),
Command::MoveWindowToNextTag { follow: true }
);
}
#[test]
fn build_move_window_to_previous_tag_without_parameter() {
assert_eq!(
build_move_window_to_previous_tag("").unwrap(),
Command::MoveWindowToPreviousTag { follow: true }
);
}
}