summaryrefslogtreecommitdiff
path: root/src/i3bar_protocol.rs
blob: d0a371acce58694dde820c64b0a16b84c9060dc9 (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
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
use crate::color::Color;
use crate::pointer_btn::PointerBtn;
use crate::text::Align;
use crate::utils::{de_first_json, de_last_json, last_line};
use serde::{Deserialize, Serialize, de};
use std::io::{self, Error, ErrorKind};

#[derive(Clone, Deserialize, Default, Debug)]
pub struct Block {
    pub full_text: String,
    #[serde(default)]
    pub short_text: Option<String>,
    #[serde(default)]
    pub color: Option<Color>,
    #[serde(default)]
    pub background: Option<Color>,
    #[serde(default)]
    pub min_width: Option<MinWidth>,
    #[serde(default)]
    pub align: Align,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub instance: Option<String>,
    #[serde(default = "def_sep")]
    pub separator: bool,
    #[serde(default = "def_sep_width")]
    pub separator_block_width: u8,
    #[serde(default)]
    pub markup: Option<String>,
}

fn def_sep() -> bool {
    true
}

fn def_sep_width() -> u8 {
    9
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MinWidth {
    Text(String),
    Pixels(u64),
}

#[derive(Serialize, Default)]
pub struct Event<'a> {
    pub name: Option<&'a str>,
    pub instance: Option<&'a str>,
    pub button: PointerBtn,
    // Not available on wayland
    pub modifiers: Vec<()>,
    // I see no reason to have these in the protocol, as a lot depends on font & pango markup
    pub x: u8,
    pub y: u8,
    pub relative_x: u8,
    pub relative_y: u8,
    pub output_x: u8,
    pub output_y: u8,
    pub width: u8,
    pub height: u8,
}

#[derive(Deserialize, Clone, Copy, Debug)]
#[serde(deny_unknown_fields)]
pub struct JsonHeader {
    version: u8,
    #[serde(default)]
    #[allow(dead_code)]
    stop_signal: i32,
    #[serde(default)]
    #[allow(dead_code)]
    cont_signal: i32,
    #[serde(default)]
    click_events: bool,
}

#[derive(Debug)]
pub enum Protocol {
    Unknown,
    PlainText {
        pending_line: Option<String>,
    },
    JsonNotStarted {
        header: JsonHeader,
    },
    Json {
        header: JsonHeader,
        pending_blocks: Option<Vec<Block>>,
    },
}

impl Protocol {
    /// Extract new data from `bytes`, return unused bytes.
    pub fn process_new_bytes<'a>(&mut self, bytes: &'a [u8]) -> io::Result<&'a [u8]> {
        match self {
            Self::Unknown => match de_first_json::<JsonHeader>(bytes) {
                Ok((Some(header), rem)) if header.version == 1 => {
                    *self = Self::JsonNotStarted { header };
                    self.process_new_bytes(rem)
                }
                Ok((Some(header), _)) => Err(Error::other(format!(
                    "Protocol version {} is not supported",
                    header.version
                ))),
                _ => {
                    *self = Self::PlainText { pending_line: None };
                    self.process_new_bytes(bytes)
                }
            },
            Self::PlainText { pending_line } => match last_line(bytes) {
                Some((new_line, rem)) => {
                    *pending_line = Some(String::from_utf8_lossy(new_line).into());
                    Ok(rem)
                }
                None => Ok(bytes),
            },
            Self::JsonNotStarted { header } => match bytes.trim_ascii_start() {
                [] => Ok(&[]),
                [b'[', rem @ ..] => {
                    *self = Self::Json {
                        header: *header,
                        pending_blocks: None,
                    };
                    self.process_new_bytes(rem)
                }
                [other, ..] => Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("invalid json: expected '[', got '{}'", *other as char),
                )),
            },
            Self::Json {
                pending_blocks: blocks,
                ..
            } => match de_last_json(bytes) {
                Err(e) => Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("invalid json: {e}"),
                )),
                Ok((new_blocks, rem)) => {
                    if let Some(new_blocks) = new_blocks {
                        *blocks = Some(new_blocks);
                    }
                    Ok(rem)
                }
            },
        }
    }

    pub fn get_blocks(&mut self) -> Option<Vec<Block>> {
        match self {
            Self::Unknown | Self::JsonNotStarted { .. } => None,
            Self::PlainText { pending_line, .. } => Some(vec![Block {
                full_text: pending_line.take()?,
                ..Default::default()
            }]),
            Self::Json { pending_blocks, .. } => pending_blocks.take(),
        }
    }

    pub fn supports_clicks(&self) -> bool {
        match self {
            Self::JsonNotStarted { header } | Self::Json { header, .. } => header.click_events,
            _ => false,
        }
    }
}

impl<'de> Deserialize<'de> for MinWidth {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct MinWidthVisitor;

        impl de::Visitor<'_> for MinWidthVisitor {
            type Value = MinWidth;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("positive integer or string")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(MinWidth::Text(v.to_owned()))
            }

            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(MinWidth::Text(v))
            }

            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(MinWidth::Pixels(v))
            }

            fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(MinWidth::Pixels(
                    v.try_into().map_err(|_| E::custom("invalid min_width"))?,
                ))
            }
        }

        deserializer.deserialize_any(MinWidthVisitor)
    }
}