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
//! Parser for the xsettings data format.
//!
//! Some of this code is referenced from [here].
//!
//! [here]: https://github.com/derat/xsettingsd

use std::iter;
use std::num::NonZeroUsize;

use x11rb::protocol::xproto::{self, ConnectionExt};

use super::atoms::*;
use super::XConnection;

type Result<T> = core::result::Result<T, ParserError>;

const DPI_NAME: &[u8] = b"Xft/DPI";
const DPI_MULTIPLIER: f64 = 1024.0;
const LITTLE_ENDIAN: u8 = b'l';
const BIG_ENDIAN: u8 = b'B';

impl XConnection {
    /// Get the DPI from XSettings.
    pub(crate) fn xsettings_dpi(
        &self,
        xsettings_screen: xproto::Atom,
    ) -> core::result::Result<Option<f64>, super::X11Error> {
        let atoms = self.atoms();

        // Get the current owner of the screen's settings.
        let owner = self.xcb_connection().get_selection_owner(xsettings_screen)?.reply()?;

        // Read the _XSETTINGS_SETTINGS property.
        let data: Vec<u8> =
            self.get_property(owner.owner, atoms[_XSETTINGS_SETTINGS], atoms[_XSETTINGS_SETTINGS])?;

        // Parse the property.
        let dpi_setting = read_settings(&data)?
            .find(|res| res.as_ref().map_or(true, |s| s.name == DPI_NAME))
            .transpose()?;
        if let Some(dpi_setting) = dpi_setting {
            let base_dpi = match dpi_setting.data {
                SettingData::Integer(dpi) => dpi as f64,
                SettingData::String(_) => {
                    return Err(ParserError::BadType(SettingType::String).into())
                },
                SettingData::Color(_) => {
                    return Err(ParserError::BadType(SettingType::Color).into())
                },
            };

            Ok(Some(base_dpi / DPI_MULTIPLIER))
        } else {
            Ok(None)
        }
    }
}

/// Read over the settings in the block of data.
fn read_settings(data: &[u8]) -> Result<impl Iterator<Item = Result<Setting<'_>>> + '_> {
    // Create a parser. This automatically parses the first 8 bytes for metadata.
    let mut parser = Parser::new(data)?;

    // Read the total number of settings.
    let total_settings = parser.i32()?;

    // Iterate over the settings.
    let iter = iter::repeat_with(move || Setting::parse(&mut parser)).take(total_settings as usize);
    Ok(iter)
}

/// A setting in the settings list.
struct Setting<'a> {
    /// The name of the setting.
    name: &'a [u8],

    /// The data contained in the setting.
    data: SettingData<'a>,
}

/// The data contained in a setting.
enum SettingData<'a> {
    Integer(i32),
    String(#[allow(dead_code)] &'a [u8]),
    Color(#[allow(dead_code)] [i16; 4]),
}

impl<'a> Setting<'a> {
    /// Parse a new `SettingData`.
    fn parse(parser: &mut Parser<'a>) -> Result<Self> {
        // Read the type.
        let ty: SettingType = parser.i8()?.try_into()?;

        // Read another byte of padding.
        parser.advance(1)?;

        // Read the name of the setting.
        let name_len = parser.i16()?;
        let name = parser.advance(name_len as usize)?;
        parser.pad(name.len(), 4)?;

        // Ignore the serial number.
        parser.advance(4)?;

        let data = match ty {
            SettingType::Integer => {
                // Read a 32-bit integer.
                SettingData::Integer(parser.i32()?)
            },

            SettingType::String => {
                // Read the data.
                let data_len = parser.i32()?;
                let data = parser.advance(data_len as usize)?;
                parser.pad(data.len(), 4)?;

                SettingData::String(data)
            },

            SettingType::Color => {
                // Read i16's of color.
                let (red, blue, green, alpha) =
                    (parser.i16()?, parser.i16()?, parser.i16()?, parser.i16()?);

                SettingData::Color([red, blue, green, alpha])
            },
        };

        Ok(Setting { name, data })
    }
}

#[derive(Debug)]
pub enum SettingType {
    Integer = 0,
    String = 1,
    Color = 2,
}

impl TryFrom<i8> for SettingType {
    type Error = ParserError;

    fn try_from(value: i8) -> Result<Self> {
        Ok(match value {
            0 => Self::Integer,
            1 => Self::String,
            2 => Self::Color,
            x => return Err(ParserError::InvalidType(x)),
        })
    }
}

/// Parser for the incoming byte stream.
struct Parser<'a> {
    bytes: &'a [u8],
    endianness: Endianness,
}

impl<'a> Parser<'a> {
    /// Create a new parser.
    fn new(bytes: &'a [u8]) -> Result<Self> {
        let (endianness, bytes) = bytes.split_first().ok_or_else(|| ParserError::ran_out(1, 0))?;
        let endianness = match *endianness {
            BIG_ENDIAN => Endianness::Big,
            LITTLE_ENDIAN => Endianness::Little,
            _ => Endianness::native(),
        };

        Ok(Self {
            // Ignore three bytes of padding and the four-byte serial.
            bytes: bytes.get(7..).ok_or_else(|| ParserError::ran_out(7, bytes.len()))?,
            endianness,
        })
    }

    /// Get a slice of bytes.
    fn advance(&mut self, n: usize) -> Result<&'a [u8]> {
        if n == 0 {
            return Ok(&[]);
        }

        if n > self.bytes.len() {
            Err(ParserError::ran_out(n, self.bytes.len()))
        } else {
            let (part, rem) = self.bytes.split_at(n);
            self.bytes = rem;
            Ok(part)
        }
    }

    /// Skip some padding.
    fn pad(&mut self, size: usize, pad: usize) -> Result<()> {
        let advance = (pad - (size % pad)) % pad;
        self.advance(advance)?;
        Ok(())
    }

    /// Get a single byte.
    fn i8(&mut self) -> Result<i8> {
        self.advance(1).map(|s| s[0] as i8)
    }

    /// Get two bytes.
    fn i16(&mut self) -> Result<i16> {
        self.advance(2).map(|s| {
            let bytes: &[u8; 2] = s.try_into().unwrap();
            match self.endianness {
                Endianness::Big => i16::from_be_bytes(*bytes),
                Endianness::Little => i16::from_le_bytes(*bytes),
            }
        })
    }

    /// Get four bytes.
    fn i32(&mut self) -> Result<i32> {
        self.advance(4).map(|s| {
            let bytes: &[u8; 4] = s.try_into().unwrap();
            match self.endianness {
                Endianness::Big => i32::from_be_bytes(*bytes),
                Endianness::Little => i32::from_le_bytes(*bytes),
            }
        })
    }
}

/// Endianness of the incoming data.
enum Endianness {
    Little,
    Big,
}

impl Endianness {
    #[cfg(target_endian = "little")]
    fn native() -> Self {
        Endianness::Little
    }

    #[cfg(target_endian = "big")]
    fn native() -> Self {
        Endianness::Big
    }
}

/// Parser errors.
#[allow(dead_code)]
#[derive(Debug)]
pub enum ParserError {
    /// Ran out of bytes.
    NoMoreBytes { expected: NonZeroUsize, found: usize },

    /// Invalid type.
    InvalidType(i8),

    /// Bad setting type.
    BadType(SettingType),
}

impl ParserError {
    fn ran_out(expected: usize, found: usize) -> ParserError {
        let expected = NonZeroUsize::new(expected).unwrap();
        Self::NoMoreBytes { expected, found }
    }
}

#[cfg(test)]
/// Tests for the XSETTINGS parser.
mod tests {
    use super::*;

    const XSETTINGS: &str = include_str!("tests/xsettings.dat");

    #[test]
    fn empty() {
        let err = match read_settings(&[]) {
            Ok(_) => panic!(),
            Err(err) => err,
        };
        match err {
            ParserError::NoMoreBytes { expected, found } => {
                assert_eq!(expected.get(), 1);
                assert_eq!(found, 0);
            },

            _ => panic!(),
        }
    }

    #[test]
    fn parse_xsettings() {
        let data = XSETTINGS
            .trim()
            .split(',')
            .map(|tok| {
                let val = tok.strip_prefix("0x").unwrap();
                u8::from_str_radix(val, 16).unwrap()
            })
            .collect::<Vec<_>>();

        let settings = read_settings(&data).unwrap().collect::<Result<Vec<_>>>().unwrap();

        let dpi = settings.iter().find(|s| s.name == b"Xft/DPI").unwrap();
        assert_int(&dpi.data, 96 * 1024);
        let hinting = settings.iter().find(|s| s.name == b"Xft/Hinting").unwrap();
        assert_int(&hinting.data, 1);

        let rgba = settings.iter().find(|s| s.name == b"Xft/RGBA").unwrap();
        assert_string(&rgba.data, "rgb");
        let lcd = settings.iter().find(|s| s.name == b"Xft/Lcdfilter").unwrap();
        assert_string(&lcd.data, "lcddefault");
    }

    fn assert_string(dat: &SettingData<'_>, s: &str) {
        match dat {
            SettingData::String(left) => assert_eq!(*left, s.as_bytes()),
            _ => panic!("invalid data type"),
        }
    }

    fn assert_int(dat: &SettingData<'_>, i: i32) {
        match dat {
            SettingData::Integer(left) => assert_eq!(*left, i),
            _ => panic!("invalid data type"),
        }
    }
}