summaryrefslogtreecommitdiff
path: root/src/status_cmd.rs
blob: 539ee3aeb0ec25b266d794cc774c683436de51f0 (plain) (blame)
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
use std::io::{BufWriter, Write};
use std::os::unix::io::{AsRawFd, RawFd};
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};

use anyhow::Result;

use nix::errno::Errno;
use nix::libc;

use crate::i3bar_protocol::{Block, Event, Protocol};

#[derive(Debug)]
pub struct StatusCmd {
    pub child: Child,
    pub output: ChildStdout,
    input: BufWriter<ChildStdin>,
    protocol: Protocol,
    buf: Vec<u8>,
}

impl StatusCmd {
    pub fn new(cmd: &str) -> Result<Self> {
        let mut child = Command::new("sh")
            .args(["-c", &format!("exec {cmd}")])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()?;
        let output = child.stdout.take().unwrap();
        let input = BufWriter::new(child.stdin.take().unwrap());
        nix::fcntl::fcntl(
            output.as_raw_fd(),
            nix::fcntl::F_SETFL(nix::fcntl::OFlag::O_NONBLOCK),
        )?;
        Ok(Self {
            child,
            output,
            input,
            protocol: Protocol::Unknown,
            buf: Vec::new(),
        })
    }

    pub fn receive_blocks(&mut self) -> Result<Option<Vec<Block>>> {
        match read_to_vec(self.output.as_raw_fd(), &mut self.buf) {
            Ok(0) => bail!("status command exited"),
            Ok(_n) => (),
            Err(Errno::EAGAIN) => return Ok(None),
            Err(e) => bail!(e),
        }

        let rem = self.protocol.process_new_bytes(&self.buf)?;
        let used = self.buf.len() - rem.len();
        self.buf.drain(..used);

        Ok(self.protocol.get_blocks())
    }

    pub fn send_click_event(&mut self, event: &Event) -> Result<()> {
        if self.protocol.supports_clicks() {
            serde_json::to_writer(&mut self.input, event)?;
            self.input.write_all(b"\n")?;
            self.input.flush()?;
        }
        Ok(())
    }
}

/// Read from a raw file descriptor to the vector.
///
/// Appends data at the end of the buffer. Resizes vector as needed.
pub fn read_to_vec(fd: RawFd, buf: &mut Vec<u8>) -> nix::Result<usize> {
    if buf.capacity() - buf.len() < 1024 {
        buf.reserve(buf.capacity().max(1024));
    }

    let res = unsafe {
        libc::read(
            fd,
            buf.as_mut_ptr().add(buf.len()) as *mut libc::c_void,
            (buf.capacity() - buf.len()) as libc::size_t,
        )
    };

    let read = Errno::result(res)? as usize;
    unsafe { buf.set_len(buf.len() + read) };

    Ok(read)
}