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
// SPDX-License-Identifier: Apache-2.0

//! X11 activation handling.
//!
//! X11 has a "startup notification" specification similar to Wayland's, see this URL:
//! <https://specifications.freedesktop.org/startup-notification-spec/startup-notification-latest.txt>

use super::{atoms::*, VoidCookie, X11Error, XConnection};

use std::ffi::CString;
use std::fmt::Write;

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

impl XConnection {
    /// "Request" a new activation token from the server.
    pub(crate) fn request_activation_token(&self, window_title: &str) -> Result<String, X11Error> {
        // The specification recommends the format "hostname+pid+"_TIME"+current time"
        let uname = rustix::system::uname();
        let pid = rustix::process::getpid();
        let time = self.timestamp();

        let activation_token = format!(
            "{}{}_TIME{}",
            uname.nodename().to_str().unwrap_or("winit"),
            pid.as_raw_nonzero(),
            time
        );

        // Set up the new startup notification.
        let notification = {
            let mut buffer = Vec::new();
            buffer.extend_from_slice(b"new: ID=");
            quote_string(&activation_token, &mut buffer);
            buffer.extend_from_slice(b" NAME=");
            quote_string(window_title, &mut buffer);
            buffer.extend_from_slice(b" SCREEN=");
            push_display(&mut buffer, &self.default_screen_index());

            CString::new(buffer)
                .map_err(|err| X11Error::InvalidActivationToken(err.into_vec()))?
                .into_bytes_with_nul()
        };
        self.send_message(&notification)?;

        Ok(activation_token)
    }

    /// Finish launching a window with the given startup ID.
    pub(crate) fn remove_activation_token(
        &self,
        window: xproto::Window,
        startup_id: &str,
    ) -> Result<(), X11Error> {
        let atoms = self.atoms();

        // Set the _NET_STARTUP_ID property on the window.
        self.xcb_connection()
            .change_property(
                xproto::PropMode::REPLACE,
                window,
                atoms[_NET_STARTUP_ID],
                xproto::AtomEnum::STRING,
                8,
                startup_id.len().try_into().unwrap(),
                startup_id.as_bytes(),
            )?
            .check()?;

        // Send the message indicating that the startup is over.
        let message = {
            const MESSAGE_ROOT: &str = "remove: ID=";

            let mut buffer = Vec::with_capacity(
                MESSAGE_ROOT
                    .len()
                    .checked_add(startup_id.len())
                    .and_then(|x| x.checked_add(1))
                    .unwrap(),
            );
            buffer.extend_from_slice(MESSAGE_ROOT.as_bytes());
            quote_string(startup_id, &mut buffer);
            CString::new(buffer)
                .map_err(|err| X11Error::InvalidActivationToken(err.into_vec()))?
                .into_bytes_with_nul()
        };

        self.send_message(&message)
    }

    /// Send a startup notification message to the window manager.
    fn send_message(&self, message: &[u8]) -> Result<(), X11Error> {
        let atoms = self.atoms();

        // Create a new window to send the message over.
        let screen = self.default_root();
        let window = xproto::WindowWrapper::create_window(
            self.xcb_connection(),
            screen.root_depth,
            screen.root,
            -100,
            -100,
            1,
            1,
            0,
            xproto::WindowClass::INPUT_OUTPUT,
            screen.root_visual,
            &xproto::CreateWindowAux::new()
                .override_redirect(1)
                .event_mask(
                    xproto::EventMask::STRUCTURE_NOTIFY | xproto::EventMask::PROPERTY_CHANGE,
                ),
        )?;

        // Serialize the messages in 20-byte chunks.
        let mut message_type = atoms[_NET_STARTUP_INFO_BEGIN];
        message
            .chunks(20)
            .map(|chunk| {
                let mut buffer = [0u8; 20];
                buffer[..chunk.len()].copy_from_slice(chunk);
                let event =
                    xproto::ClientMessageEvent::new(8, window.window(), message_type, buffer);

                // Set the message type to the continuation atom for the next chunk.
                message_type = atoms[_NET_STARTUP_INFO];

                event
            })
            .try_for_each(|event| {
                // Send each event in order.
                self.xcb_connection()
                    .send_event(
                        false,
                        screen.root,
                        xproto::EventMask::PROPERTY_CHANGE,
                        event,
                    )
                    .map(VoidCookie::ignore_error)
            })?;

        Ok(())
    }
}

/// Quote a literal string as per the startup notification specification.
fn quote_string(s: &str, target: &mut Vec<u8>) {
    let total_len = s.len().checked_add(3).expect("quote string overflow");
    target.reserve(total_len);

    // Add the opening quote.
    target.push(b'"');

    // Iterate over the string split by literal quotes.
    s.as_bytes().split(|&b| b == b'"').for_each(|part| {
        // Add the part.
        target.extend_from_slice(part);

        // Escape the quote.
        target.push(b'\\');
        target.push(b'"');
    });

    // Un-escape the last quote.
    target.remove(target.len() - 2);
}

/// Push a `Display` implementation to the buffer.
fn push_display(buffer: &mut Vec<u8>, display: &impl std::fmt::Display) {
    struct Writer<'a> {
        buffer: &'a mut Vec<u8>,
    }

    impl<'a> std::fmt::Write for Writer<'a> {
        fn write_str(&mut self, s: &str) -> std::fmt::Result {
            self.buffer.extend_from_slice(s.as_bytes());
            Ok(())
        }
    }

    write!(Writer { buffer }, "{}", display).unwrap();
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn properly_escapes_x11_messages() {
        let assert_eq = |input: &str, output: &[u8]| {
            let mut buf = vec![];
            quote_string(input, &mut buf);
            assert_eq!(buf, output);
        };

        assert_eq("", b"\"\"");
        assert_eq("foo", b"\"foo\"");
        assert_eq("foo\"bar", b"\"foo\\\"bar\"");
    }
}