i3status_rs/blocks/keyboard_layout/
xkb_event.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
use super::*;
use x11rb_async::{
    connection::{Connection as _, RequestConnection as _},
    protocol::{
        Event,
        xkb::{
            self, ConnectionExt as _, EventType, ID, MapPart, NameDetail, SelectEventsAux,
            UseExtensionReply,
        },
        xproto::ConnectionExt as _,
    },
    rust_connection::RustConnection,
};

const XCB_XKB_MINOR_VERSION: u16 = 0;
const XCB_XKB_MAJOR_VERSION: u16 = 1;

pub(super) struct XkbEvent {
    connection: RustConnection,
}

fn parse_layout(buf: &[u8], index: usize) -> Result<&str> {
    let colon_i = buf.iter().position(|c| *c == b':').unwrap_or(buf.len());
    let layout = buf[..colon_i]
        .split(|&c| c == b'+')
        .skip(1) // layout names start from index 1
        .nth(index)
        .error("Index out of range")?;
    std::str::from_utf8(layout).error("non utf8 layout")
}

async fn get_layout(connection: &RustConnection) -> Result<String> {
    let xkb_state = connection
        .xkb_get_state(ID::USE_CORE_KBD.into())
        .await
        .error("xkb_get_state failed")?
        .reply()
        .await
        .error("xkb_get_state reply failed")?;
    let group: u8 = xkb_state.group.into();

    let symbols_name = connection
        .xkb_get_names(
            ID::USE_CORE_KBD.into(),
            NameDetail::GROUP_NAMES | NameDetail::SYMBOLS,
        )
        .await
        .error("xkb_get_names failed")?
        .reply()
        .await
        .error("xkb_get_names reply failed")?
        .value_list
        .symbols_name
        .error("symbols_name is empty")?;

    let name = connection
        .get_atom_name(symbols_name)
        .await
        .error("get_atom_name failed")?
        .reply()
        .await
        .error("get_atom_name reply failed")?
        .name;
    let layout = parse_layout(&name, group as _)?;

    Ok(layout.to_owned())
}

async fn prefetch_xkb_extension(connection: &RustConnection) -> Result<UseExtensionReply> {
    connection
        .prefetch_extension_information(xkb::X11_EXTENSION_NAME)
        .await
        .error("prefetch_extension_information failed")?;

    let reply = connection
        .xkb_use_extension(XCB_XKB_MAJOR_VERSION, XCB_XKB_MINOR_VERSION)
        .await
        .error("xkb_use_extension failed")?
        .reply()
        .await
        .error("xkb_use_extension reply failed")?;

    Ok(reply)
}

impl XkbEvent {
    pub(super) async fn new() -> Result<Self> {
        let (connection, _, drive) = RustConnection::connect(None)
            .await
            .error("Failed to open XCB connection")?;

        tokio::spawn(drive);
        let reply = prefetch_xkb_extension(&connection)
            .await
            .error("Failed to prefetch xkb extension")?;

        if !reply.supported {
            return Err(Error::new(
                "This program requires the X11 server to support the XKB extension",
            ));
        }

        connection
            .xkb_select_events(
                ID::USE_CORE_KBD.into(),
                EventType::default(),
                EventType::STATE_NOTIFY,
                MapPart::default(),
                MapPart::default(),
                &SelectEventsAux::new(),
            )
            .await
            .error("Failed to select events")?;

        Ok(XkbEvent { connection })
    }
}

#[async_trait]
impl Backend for XkbEvent {
    async fn get_info(&mut self) -> Result<Info> {
        let cur_layout = get_layout(&self.connection)
            .await
            .error("Failed to get current layout")?;
        Ok(Info::from_layout_variant_str(&cur_layout))
    }

    async fn wait_for_change(&mut self) -> Result<()> {
        loop {
            let event = self
                .connection
                .wait_for_event()
                .await
                .error("Failed to read the event")?;

            if let Event::XkbStateNotify(e) = event {
                if e.changed.contains(xkb::StatePart::GROUP_STATE) {
                    return Ok(());
                }
            }
        }
    }
}