jay-compositor 1.15.0

The Jay compositor
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use crate::backend::InputDeviceId;
use crate::ifs::wl_seat::SeatId;
use crate::it::test_error::TestError;
use crate::it::test_error::TestResult;
use crate::tree::OutputNode;
use crate::utils::copyhashmap::CopyHashMap;
use crate::utils::errorfmt::ErrorFmt;
use crate::utils::ptr_ext::PtrExt;
use crate::utils::stack::Stack;
use bincode::Options;
use isnt::std_1::primitive::IsntConstPtrExt;
use jay_config::_private::ConfigEntry;
use jay_config::_private::VERSION;
use jay_config::_private::WindowThemeKind;
use jay_config::_private::bincode_ops;
use jay_config::_private::ipc::ClientMessage;
use jay_config::_private::ipc::Response;
use jay_config::_private::ipc::ServerMessage;
use jay_config::Axis;
use jay_config::Direction;
use jay_config::input::InputDevice;
use jay_config::input::Seat;
use jay_config::keyboard::Keymap;
use jay_config::keyboard::ModifiedKeySym;
use jay_config::theme::Color;
use jay_config::theme::JcBarPosition;
use jay_config::theme::JcContainerBorders;
use jay_config::theme::colors::Colorable;
use jay_config::theme::sized::BAR_SEPARATOR_WIDTH;
use jay_config::theme::sized::Resizable;
use jay_config::video::Connector;
use jay_config::video::Transform;
use jay_config::window::Window;
use std::cell::Cell;
use std::ops::Deref;
use std::ptr;
use std::rc::Rc;
use std::time::Duration;

pub static TEST_CONFIG_ENTRY: ConfigEntry = ConfigEntry {
    version: VERSION,
    init,
    unref,
    handle_msg,
};

thread_local! {
    static CONFIG: Cell<*const TestConfig> = const { Cell::new(ptr::null()) };
}

pub fn with_test_config<T, F>(f: F) -> T
where
    F: FnOnce(Rc<TestConfig>) -> T,
{
    let tc = Rc::new(TestConfig {
        srv: Cell::new(None),
        responses: Default::default(),
        invoked_shortcuts: Default::default(),
        graphics_initialized: Cell::new(false),
    });
    let old = CONFIG.get();
    CONFIG.set(tc.deref());
    let res = f(tc.clone());
    CONFIG.set(old);
    res
}

unsafe extern "C" fn init(
    srv_data: *const u8,
    srv_unref: unsafe extern "C" fn(data: *const u8),
    srv_handler: unsafe extern "C" fn(data: *const u8, msg: *const u8, size: usize),
    _msg: *const u8,
    _size: usize,
) -> *const u8 {
    let tc = CONFIG.get();
    assert!(tc.is_not_null());
    unsafe {
        Rc::increment_strong_count(tc);
        {
            let tc = tc.deref();
            tc.srv.set(Some(ServerData {
                srv_data,
                srv_unref,
                srv_handler,
            }));
        }
        tc.cast()
    }
}

unsafe extern "C" fn unref(data: *const u8) {
    unsafe {
        Rc::decrement_strong_count(data.cast::<TestConfig>());
    }
}

unsafe extern "C" fn handle_msg(data: *const u8, msg: *const u8, size: usize) {
    let tc = unsafe { data.cast::<TestConfig>().deref() };
    let msg = unsafe { std::slice::from_raw_parts(msg, size) };
    let res = bincode_ops().deserialize::<ServerMessage>(msg);
    let msg = match res {
        Ok(msg) => msg,
        Err(e) => {
            log::error!("could not deserialize message: {}", ErrorFmt(e));
            return;
        }
    };
    match msg {
        ServerMessage::Configure { .. } => {}
        ServerMessage::Response { response } => {
            tc.responses.push(response);
        }
        ServerMessage::InvokeShortcut { seat, mods, sym } => {
            tc.invoked_shortcuts
                .set((SeatId::from_raw(seat.0 as _), mods | sym), ());
        }
        ServerMessage::InvokeShortcut2 {
            seat,
            unmasked_mods,
            effective_mods,
            sym,
        } => {
            let _ = unmasked_mods;
            tc.invoked_shortcuts
                .set((SeatId::from_raw(seat.0 as _), effective_mods | sym), ());
        }
        ServerMessage::NewInputDevice { .. } => {}
        ServerMessage::DelInputDevice { .. } => {}
        ServerMessage::ConnectorConnect { .. } => {}
        ServerMessage::ConnectorDisconnect { .. } => {}
        ServerMessage::NewConnector { .. } => {}
        ServerMessage::DelConnector { .. } => {}
        ServerMessage::TimerExpired { .. } => {}
        ServerMessage::GraphicsInitialized => tc.graphics_initialized.set(true),
        ServerMessage::Clear => tc.clear(),
        ServerMessage::NewDrmDev { .. } => {}
        ServerMessage::DelDrmDev { .. } => {}
        ServerMessage::Idle => {}
        ServerMessage::DevicesEnumerated => {}
        ServerMessage::InterestReady { .. } => {}
        ServerMessage::Features { .. } => {}
        ServerMessage::SwitchEvent { .. } => {}
        ServerMessage::ClientMatcherMatched { .. } => {}
        ServerMessage::ClientMatcherUnmatched { .. } => {}
        ServerMessage::WindowMatcherMatched { .. } => {}
        ServerMessage::WindowMatcherUnmatched { .. } => {}
        ServerMessage::Locked { .. } => {}
    }
}

#[derive(Copy, Clone)]
struct ServerData {
    srv_data: *const u8,
    srv_unref: unsafe extern "C" fn(data: *const u8),
    srv_handler: unsafe extern "C" fn(data: *const u8, msg: *const u8, size: usize),
}

pub struct TestConfig {
    srv: Cell<Option<ServerData>>,
    responses: Stack<Response>,
    pub invoked_shortcuts: CopyHashMap<(SeatId, ModifiedKeySym), ()>,
    pub graphics_initialized: Cell<bool>,
}

macro_rules! get_response {
    ($res:expr, $ty:ident { $($field:ident),+ }) => {
        let Response::$ty { $($field,)+ } = $res else {
            bail!("Server did not send a response to a {} request", stringify!($ty));
        };
    }
}

impl TestConfig {
    fn send(&self, msg: ClientMessage<'_>) -> Result<(), TestError> {
        self.send_(&msg)
    }

    fn send_(&self, msg: &ClientMessage<'_>) -> Result<(), TestError> {
        let Some(srv) = self.srv.get() else {
            bail!("srv not set");
        };
        let mut buf = vec![];
        bincode_ops().serialize_into(&mut buf, msg).unwrap();
        unsafe {
            (srv.srv_handler)(srv.srv_data, buf.as_ptr(), buf.len());
        }
        Ok(())
    }

    fn send_with_reply(&self, msg: ClientMessage<'_>) -> Result<Response, TestError> {
        self.send_(&msg)?;
        match self.responses.pop() {
            Some(r) => Ok(r),
            _ => bail!("Compositor did not send a response to {:?}", msg),
        }
    }

    pub fn quit(&self) -> Result<(), TestError> {
        self.send(ClientMessage::Quit)
    }

    pub fn get_seat(&self, name: &str) -> Result<SeatId, TestError> {
        let reply = self.send_with_reply(ClientMessage::GetSeat { name })?;
        get_response!(reply, GetSeat { seat });
        Ok(SeatId::from_raw(seat.0 as _))
    }

    pub fn show_workspace(&self, seat: SeatId, name: &str) -> Result<(), TestError> {
        let reply = self.send_with_reply(ClientMessage::GetWorkspace { name })?;
        get_response!(reply, GetWorkspace { workspace });
        self.send(ClientMessage::ShowWorkspace {
            seat: Seat(seat.raw() as _),
            workspace,
        })
    }

    pub fn parse_keymap(&self, keymap: &str) -> Result<Keymap, TestError> {
        let reply = self.send_with_reply(ClientMessage::ParseKeymap { keymap })?;
        get_response!(reply, ParseKeymap { keymap });
        if keymap.is_invalid() {
            bail!("Could not parse the keymap");
        }
        Ok(keymap)
    }

    pub fn set_keymap(&self, seat: SeatId, keymap: Keymap) -> TestResult {
        self.send(ClientMessage::SeatSetKeymap {
            seat: Seat(seat.raw() as _),
            keymap,
        })
    }

    pub fn create_split(&self, seat: SeatId, axis: Axis) -> TestResult {
        self.send(ClientMessage::CreateSeatSplit {
            seat: Seat(seat.raw() as _),
            axis,
        })
    }

    pub fn set_mono(&self, seat: SeatId, mono: bool) -> TestResult {
        self.send(ClientMessage::SetSeatMono {
            seat: Seat(seat.raw() as _),
            mono,
        })
    }

    pub fn add_shortcut<T: Into<ModifiedKeySym>>(
        &self,
        seat: SeatId,
        key: T,
    ) -> Result<(), TestError> {
        let key = key.into();
        self.send(ClientMessage::AddShortcut {
            seat: Seat(seat.raw() as _),
            mods: key.mods,
            sym: key.sym,
        })
    }

    pub fn set_input_device_seat(&self, id: InputDeviceId, seat: SeatId) -> Result<(), TestError> {
        self.send(ClientMessage::SetSeat {
            device: InputDevice(id.raw() as _),
            seat: Seat(seat.raw() as _),
        })
    }

    pub fn focus(&self, seat: SeatId, direction: Direction) -> TestResult {
        self.send(ClientMessage::SeatFocus {
            seat: Seat(seat.raw() as _),
            direction,
        })
    }

    pub fn set_fullscreen(&self, seat: SeatId, fs: bool) -> TestResult {
        self.send(ClientMessage::SetSeatFullscreen {
            seat: Seat(seat.raw() as _),
            fullscreen: fs,
        })
    }

    pub fn set_idle(&self, timeout: Duration) -> TestResult {
        self.send(ClientMessage::SetIdle { timeout })
    }

    pub fn set_idle_grace_period(&self, period: Duration) -> TestResult {
        self.send(ClientMessage::SetIdleGracePeriod { period })
    }

    pub fn set_floating(&self, seat: SeatId, floating: bool) -> TestResult {
        self.send(ClientMessage::SetSeatFloating {
            seat: Seat(seat.raw() as _),
            floating,
        })
    }

    fn clear(&self) {
        unsafe {
            if let Some(srv) = self.srv.take() {
                (srv.srv_unref)(srv.srv_data);
            }
        }
    }

    pub fn set_scale(&self, output: &OutputNode, scale: f64) -> TestResult {
        self.send(ClientMessage::ConnectorSetScale {
            connector: Connector(output.global.connector.connector.id().raw() as _),
            scale,
        })
    }

    pub fn set_output_transform(&self, output: &OutputNode, transform: Transform) -> TestResult {
        self.send(ClientMessage::ConnectorSetTransform {
            connector: Connector(output.global.connector.connector.id().raw() as _),
            transform,
        })
    }

    pub fn set_size(&self, sized: Resizable, size: i32) -> TestResult {
        self.send(ClientMessage::SetSize { sized, size })
    }

    pub fn set_bar_separator_width(&self, width: i32) -> TestResult {
        self.set_size(BAR_SEPARATOR_WIDTH, width)
    }

    pub fn set_bar_position(&self, position: JcBarPosition) -> TestResult {
        self.send(ClientMessage::SetBarPosition { position })
    }

    pub fn set_show_bar(&self, show: bool) -> TestResult {
        self.send(ClientMessage::SetShowBar { show })
    }

    pub fn get_show_bar(&self) -> Result<bool, TestError> {
        let reply = self.send_with_reply(ClientMessage::GetShowBar)?;
        get_response!(reply, GetShowBar { show });
        Ok(show)
    }

    pub fn set_show_titles(&self, show: bool) -> TestResult {
        self.send(ClientMessage::SetShowTitles { show })
    }

    pub fn get_keyboard_window(&self, seat: SeatId) -> TestResult<Window> {
        let reply = self.send_with_reply(ClientMessage::GetSeatKeyboardWindow {
            seat: Seat(seat.raw() as _),
        })?;
        get_response!(reply, GetSeatKeyboardWindow { window });
        Ok(window)
    }

    pub fn get_window_parent(&self, window: Window) -> TestResult<Window> {
        let reply = self.send_with_reply(ClientMessage::GetWindowParent { window })?;
        get_response!(reply, GetWindowParent { window });
        Ok(window)
    }

    pub fn reset_window_theme(&self, window: Window, kind: WindowThemeKind) -> TestResult {
        self.send(ClientMessage::ResetWindowTheme { window, kind })
    }

    pub fn set_window_theme_color(
        &self,
        window: Window,
        kind: WindowThemeKind,
        colorable: Colorable,
        color: Option<Color>,
    ) -> TestResult {
        self.send(ClientMessage::SetWindowThemeColor {
            window,
            kind,
            colorable,
            color,
        })
    }

    pub fn get_window_theme_color(
        &self,
        window: Window,
        kind: WindowThemeKind,
        colorable: Colorable,
    ) -> TestResult<Option<Color>> {
        let reply = self.send_with_reply(ClientMessage::GetWindowThemeColor {
            window,
            kind,
            colorable,
        })?;
        get_response!(reply, GetWindowThemeColor { color });
        Ok(color)
    }

    pub fn set_window_theme_size(
        &self,
        window: Window,
        kind: WindowThemeKind,
        sized: Resizable,
        size: Option<i32>,
    ) -> TestResult {
        self.send(ClientMessage::SetWindowThemeSize {
            window,
            kind,
            sized,
            size,
        })
    }

    pub fn get_window_theme_size(
        &self,
        window: Window,
        kind: WindowThemeKind,
        sized: Resizable,
    ) -> TestResult<Option<i32>> {
        let reply = self.send_with_reply(ClientMessage::GetWindowThemeSize {
            window,
            kind,
            sized,
        })?;
        get_response!(reply, GetWindowThemeSize { size });
        Ok(size)
    }

    pub fn set_window_theme_show_titles(
        &self,
        window: Window,
        kind: WindowThemeKind,
        show: Option<bool>,
    ) -> TestResult {
        self.send(ClientMessage::SetWindowThemeShowTitles { window, kind, show })
    }

    pub fn get_window_theme_show_titles(
        &self,
        window: Window,
        kind: WindowThemeKind,
    ) -> TestResult<Option<bool>> {
        let reply =
            self.send_with_reply(ClientMessage::GetWindowThemeShowTitles { window, kind })?;
        get_response!(reply, GetWindowThemeShowTitles { show });
        Ok(show)
    }

    pub fn set_window_theme_window_icons_grayscale(
        &self,
        window: Window,
        kind: WindowThemeKind,
        grayscale: Option<bool>,
    ) -> TestResult {
        self.send(ClientMessage::SetWindowThemeWindowIconsGrayscale {
            window,
            kind,
            grayscale,
        })
    }

    pub fn set_window_theme_title_font(
        &self,
        window: Window,
        kind: WindowThemeKind,
        font: Option<&str>,
    ) -> TestResult {
        self.send(ClientMessage::SetWindowThemeTitleFont { window, kind, font })
    }

    pub fn set_window_theme_container_borders(
        &self,
        window: Window,
        kind: WindowThemeKind,
        borders: Option<JcContainerBorders>,
    ) -> TestResult {
        self.send(ClientMessage::SetWindowThemeContainerBorders {
            window,
            kind,
            borders,
        })
    }

    pub fn get_window_theme_container_borders(
        &self,
        window: Window,
        kind: WindowThemeKind,
    ) -> TestResult<Option<JcContainerBorders>> {
        let reply =
            self.send_with_reply(ClientMessage::GetWindowThemeContainerBorders { window, kind })?;
        get_response!(reply, GetWindowThemeContainerBorders { borders });
        Ok(borders)
    }
}

impl Drop for TestConfig {
    fn drop(&mut self) {
        self.clear();
    }
}