90 lines
3.7 KiB
Rust
90 lines
3.7 KiB
Rust
//! Takes focus on niri over its IPC socket. niri only marks a window urgent when an app asks for focus without a
|
|
//! user input, so a download from the browser would not bring Medlar forward. The socket speaks one JSON value per line.
|
|
|
|
use std::io::{BufRead, BufReader, Write};
|
|
use std::os::unix::net::UnixStream;
|
|
use std::path::Path;
|
|
use std::time::Duration;
|
|
|
|
/// The id of the window of process `pid` with app id `medlar`, from niri's `Windows` answer.
|
|
fn find(reply: &str, pid: u32) -> Option<u64> {
|
|
let v: serde_json::Value = serde_json::from_str(reply).ok()?;
|
|
v["Ok"]["Windows"].as_array()?.iter()
|
|
.find(|w| w["pid"].as_u64() == Some(pid as u64) && w["app_id"].as_str() == Some("medlar"))
|
|
.and_then(|w| w["id"].as_u64())
|
|
}
|
|
|
|
fn ask(stream: &mut UnixStream, line: &str) -> std::io::Result<String> {
|
|
stream.write_all(line.as_bytes())?;
|
|
stream.write_all(b"\n")?;
|
|
let mut reply = String::new();
|
|
BufReader::new(&*stream).read_line(&mut reply)?;
|
|
Ok(reply)
|
|
}
|
|
|
|
/// Asks niri at `socket` to focus the window of `pid`. Errors when there is no such window (yet) or niri refuses.
|
|
pub fn focus(socket: &Path, pid: u32) -> std::io::Result<u64> {
|
|
let bad = |m: &str| std::io::Error::new(std::io::ErrorKind::Other, m.to_string());
|
|
let mut s = UnixStream::connect(socket)?;
|
|
s.set_read_timeout(Some(Duration::from_secs(2)))?;
|
|
s.set_write_timeout(Some(Duration::from_secs(2)))?;
|
|
let id = find(&ask(&mut s, "\"Windows\"")?, pid).ok_or_else(|| bad("no window"))?;
|
|
let reply = ask(&mut s, &format!("{{\"Action\":{{\"FocusWindow\":{{\"id\":{id}}}}}}}"))?;
|
|
if reply.contains("\"Ok\"") { Ok(id) } else { Err(bad("refused")) }
|
|
}
|
|
|
|
/// In the background: the window may still be opening, so it looks for a few seconds. Does nothing outside niri.
|
|
pub fn bring_forward() {
|
|
let Some(socket) = std::env::var_os("NIRI_SOCKET") else { return };
|
|
std::thread::spawn(move || {
|
|
for _ in 0..15 {
|
|
if focus(Path::new(&socket), std::process::id()).is_ok() {
|
|
return;
|
|
}
|
|
std::thread::sleep(Duration::from_millis(200));
|
|
}
|
|
});
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::os::unix::net::UnixListener;
|
|
|
|
#[test]
|
|
fn finds_our_window() {
|
|
let r = r#"{"Ok":{"Windows":[{"id":3,"app_id":"medlar","pid":10},{"id":7,"app_id":"medlar","pid":42},{"id":9,"app_id":"other","pid":42}]}}"#;
|
|
assert_eq!(find(r, 42), Some(7));
|
|
assert_eq!(find(r, 5), None);
|
|
assert_eq!(find("garbage", 42), None);
|
|
}
|
|
|
|
#[test]
|
|
fn asks_niri_to_focus_and_fails_softly() {
|
|
let dir = std::env::temp_dir().join(format!("medlar-niri-{}", std::process::id()));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let path = dir.join("sock");
|
|
let l = UnixListener::bind(&path).unwrap();
|
|
let t = std::thread::spawn(move || {
|
|
let (s, _) = l.accept().unwrap();
|
|
let mut w = s.try_clone().unwrap();
|
|
let mut r = BufReader::new(s);
|
|
let mut seen = vec![];
|
|
let mut line = String::new();
|
|
r.read_line(&mut line).unwrap();
|
|
seen.push(line.trim().to_string());
|
|
w.write_all(b"{\"Ok\":{\"Windows\":[{\"id\":7,\"app_id\":\"medlar\",\"pid\":42}]}}\n").unwrap();
|
|
line.clear();
|
|
r.read_line(&mut line).unwrap();
|
|
seen.push(line.trim().to_string());
|
|
w.write_all(b"{\"Ok\":\"Handled\"}\n").unwrap();
|
|
seen
|
|
});
|
|
assert_eq!(focus(&path, 42).unwrap(), 7);
|
|
let seen = t.join().unwrap();
|
|
assert_eq!(seen[0], "\"Windows\"");
|
|
assert_eq!(seen[1], r#"{"Action":{"FocusWindow":{"id":7}}}"#);
|
|
assert!(focus(&dir.join("none"), 42).is_err());
|
|
std::fs::remove_dir_all(&dir).ok();
|
|
}
|
|
}
|