-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.rs
411 lines (357 loc) · 14.3 KB
/
main.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
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
#![warn(clippy::all, clippy::nursery, clippy::pedantic)]
#![allow(clippy::missing_errors_doc)]
use clap::Parser;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Read;
use std::io::Write;
use std::net::TcpStream;
use std::path::PathBuf;
use std::process::Command;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;
use color_eyre::eyre::anyhow;
use color_eyre::Report;
use color_eyre::Result;
use json_dotpath::DotPaths;
use komorebi_client::Notification;
use komorebi_client::NotificationEvent;
use komorebi_client::UnixListener;
use komorebi_client::WindowManagerEvent;
use parking_lot::Mutex;
use serde_json::json;
use windows::Win32::UI::Input::KeyboardAndMouse::GetKeyState;
use crate::configuration::Configuration;
use crate::configuration::Strategy;
mod configuration;
static KANATA_DISCONNECTED: AtomicBool = AtomicBool::new(false);
static KANATA_RECONNECT_REQUIRED: AtomicBool = AtomicBool::new(false);
const NAME: &str = "komokana.sock";
#[derive(Debug, Parser)]
#[clap(author, about, version, arg_required_else_help = true)]
struct Cli {
/// The port on which kanata's TCP server is running
#[clap(short = 'p', long)]
kanata_port: i32,
/// Path to your komokana configuration file
#[clap(short, long, default_value = "~/komokana.yaml")]
configuration: String,
/// Layer to default to when an active window doesn't match any rules
#[clap(short, long)]
default_layer: String,
/// Write the current layer to ~/AppData/Local/Temp/kanata_layer
#[clap(short, long, action)]
tmpfile: bool,
}
fn main() -> Result<()> {
let cli: Cli = Cli::parse();
let configuration = resolve_windows_path(&cli.configuration)?;
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
color_eyre::install()?;
env_logger::builder().format_timestamp(None).init();
let mut komokana = Komokana::init(
configuration,
cli.kanata_port,
cli.default_layer,
cli.tmpfile,
)?;
komokana.listen();
loop {
std::thread::sleep(Duration::from_secs(60));
}
}
struct Komokana {
komorebi: Arc<Mutex<UnixListener>>,
kanata: Arc<Mutex<TcpStream>>,
kanata_port: i32,
configuration: Configuration,
default_layer: String,
tmpfile: bool,
}
impl Komokana {
pub fn init(
configuration: PathBuf,
kanata_port: i32,
default_layer: String,
tmpfile: bool,
) -> Result<Self> {
let configuration: Configuration =
serde_yaml::from_str(&std::fs::read_to_string(configuration)?)?;
let listener = komorebi_client::subscribe(NAME)?;
log::debug!("connected to komorebi");
let stream = TcpStream::connect(format!("localhost:{kanata_port}"))?;
log::debug!("connected to kanata");
Ok(Self {
komorebi: Arc::new(Mutex::new(listener)),
kanata: Arc::new(Mutex::new(stream)),
kanata_port,
configuration,
default_layer,
tmpfile,
})
}
#[allow(clippy::too_many_lines)]
pub fn listen(&mut self) {
let socket = self.komorebi.clone();
let mut stream = self.kanata.clone();
let stream_read = self.kanata.clone();
let kanata_port = self.kanata_port;
let tmpfile = self.tmpfile;
log::info!("listening");
std::thread::spawn(move || -> Result<()> {
let mut read_stream = stream_read.lock().try_clone()?;
drop(stream_read);
loop {
let mut buf = vec![0; 1024];
match read_stream.read(&mut buf) {
Ok(bytes_read) => {
let data = String::from_utf8(buf[0..bytes_read].to_vec())?;
if data == "\n" {
continue;
}
let notification: serde_json::Value = serde_json::from_str(&data)?;
if notification.dot_has("LayerChange.new") {
if let Some(new) = notification.dot_get::<String>("LayerChange.new")? {
log::info!("current layer: {new}");
if tmpfile {
let mut tmp = std::env::temp_dir();
tmp.push("kanata_layer");
std::fs::write(tmp, new)?;
}
}
}
}
Err(error) => {
// Connection reset
if error.raw_os_error().expect("could not get raw os error") == 10054 {
KANATA_DISCONNECTED.store(true, Ordering::SeqCst);
log::warn!("kanata tcp server is no longer running");
let mut result = TcpStream::connect(format!("localhost:{kanata_port}"));
while result.is_err() {
log::warn!("kanata tcp server is not running, retrying connection in 5 seconds");
std::thread::sleep(Duration::from_secs(5));
result = TcpStream::connect(format!("localhost:{kanata_port}"));
}
log::info!("reconnected to kanata on read thread");
read_stream = result?;
KANATA_DISCONNECTED.store(false, Ordering::SeqCst);
KANATA_RECONNECT_REQUIRED.store(true, Ordering::SeqCst);
}
}
}
}
});
let config = self.configuration.clone();
let default_layer = self.default_layer.clone();
std::thread::spawn(move || -> Result<()> {
#[allow(clippy::significant_drop_in_scrutinee)]
for client in socket.lock().incoming() {
match client {
Ok(subscription) => {
let reader = BufReader::new(subscription.try_clone()?);
#[allow(clippy::lines_filter_map_ok)]
for line in reader.lines().flatten() {
let notification: Notification = match serde_json::from_str(&line) {
Ok(value) => value,
Err(error) => {
log::debug!(
"discarding malformed komorebi notification: {error}"
);
continue;
}
};
match notification.event {
NotificationEvent::WindowManager(WindowManagerEvent::Show(
_,
window,
)) => handle_event(
&config,
&mut stream,
&default_layer,
Event::Show,
&window.exe()?,
&window.title()?,
kanata_port,
)?,
NotificationEvent::WindowManager(
WindowManagerEvent::FocusChange(_, window),
) => handle_event(
&config,
&mut stream,
&default_layer,
Event::FocusChange,
&window.exe()?,
&window.title()?,
kanata_port,
)?,
_ => {}
};
}
}
Err(error) => {
// Broken pipe
if error.raw_os_error().expect("could not get raw os error") == 109 {
log::warn!("komorebi is no longer running");
let mut output = Command::new("cmd.exe")
.args(["/C", "komorebic.exe", "subscribe-socket", NAME])
.output()?;
while !output.status.success() {
log::warn!(
"komorebic.exe failed with error code {:?}, retrying in 5 seconds...",
output.status.code()
);
std::thread::sleep(Duration::from_secs(5));
output = Command::new("cmd.exe")
.args(["/C", "komorebic.exe", "subscribe-socket", NAME])
.output()?;
}
log::warn!("reconnected to komorebi");
} else {
return Err(Report::from(error));
}
}
}
}
Ok(())
});
}
}
fn handle_event(
configuration: &Configuration,
stream: &mut Arc<Mutex<TcpStream>>,
default_layer: &str,
event: Event,
exe: &str,
title: &str,
kanata_port: i32,
) -> Result<()> {
let target = calculate_target(
configuration,
event,
exe,
title,
if matches!(event, Event::FocusChange) {
Option::from(default_layer)
} else {
None
},
);
if let Some(target) = target {
if KANATA_RECONNECT_REQUIRED.load(Ordering::SeqCst) {
let mut result = TcpStream::connect(format!("localhost:{kanata_port}"));
while result.is_err() {
std::thread::sleep(Duration::from_secs(5));
result = TcpStream::connect(format!("localhost:{kanata_port}"));
}
log::info!("reconnected to kanata on write thread");
*stream = Arc::new(Mutex::new(result?));
KANATA_RECONNECT_REQUIRED.store(false, Ordering::SeqCst);
}
let request = json!({
"ChangeLayer": {
"new": target,
}
});
stream.lock().write_all(request.to_string().as_bytes())?;
log::debug!("request sent: {request}");
};
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub enum Event {
Show,
FocusChange,
}
fn calculate_target(
configuration: &Configuration,
event: Event,
exe: &str,
title: &str,
default: Option<&str>,
) -> Option<String> {
let mut new_layer = default;
for entry in configuration {
if entry.exe == exe {
if matches!(event, Event::FocusChange) {
new_layer = Option::from(entry.target_layer.as_str());
}
if let Some(title_overrides) = &entry.title_overrides {
for title_override in title_overrides {
match title_override.strategy {
Strategy::StartsWith => {
if title.starts_with(&title_override.title) {
new_layer = Option::from(title_override.target_layer.as_str());
}
}
Strategy::EndsWith => {
if title.ends_with(&title_override.title) {
new_layer = Option::from(title_override.target_layer.as_str());
}
}
Strategy::Contains => {
if title.contains(&title_override.title) {
new_layer = Option::from(title_override.target_layer.as_str());
}
}
Strategy::Equals => {
if title.eq(&title_override.title) {
new_layer = Option::from(title_override.target_layer.as_str());
}
}
}
}
// This acts like a default target layer within the application
// which defaults back to the entry's main target layer
if new_layer.is_none() {
new_layer = Option::from(entry.target_layer.as_str());
}
}
if matches!(event, Event::FocusChange) {
if let Some(virtual_key_overrides) = &entry.virtual_key_overrides {
for virtual_key_override in virtual_key_overrides {
if unsafe { GetKeyState(virtual_key_override.virtual_key_code) } < 0 {
new_layer = Option::from(virtual_key_override.targer_layer.as_str());
}
}
}
if let Some(virtual_key_ignores) = &entry.virtual_key_ignores {
for virtual_key in virtual_key_ignores {
if unsafe { GetKeyState(*virtual_key) } < 0 {
new_layer = None;
}
}
}
}
}
}
new_layer.and_then(|new_layer| Option::from(new_layer.to_string()))
}
fn resolve_windows_path(raw_path: &str) -> Result<PathBuf> {
let path = if raw_path.starts_with('~') {
raw_path.replacen(
'~',
&dirs::home_dir()
.ok_or_else(|| anyhow!("there is no home directory"))?
.display()
.to_string(),
1,
)
} else {
raw_path.to_string()
};
let full_path = PathBuf::from(path);
let parent = full_path
.parent()
.ok_or_else(|| anyhow!("cannot parse directory"))?;
let file = full_path
.components()
.last()
.ok_or_else(|| anyhow!("cannot parse filename"))?;
let mut canonicalized = std::fs::canonicalize(parent)?;
canonicalized.push(file);
Ok(canonicalized)
}