jflib-plat 0.1.0

JFLib's platform layer: one module per operating system with the same functions
Documentation
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
// linux_wl_input -- Wayland seat: pointer, keyboard, touch, key repeat, the event helper
//                                                                  [src/plat/linux/wl_input.s]
//
//   Wl::push(type, btn, x, y, data)   evq_push with the current MOD_* bits and the event's
//                                     window (inp.evwin)
//   Wl::input_service(now) -> next key-repeat deadline (u64::MAX none)   (wait)
//   Wl::release_buttons()             E_UP for every held button (move / resize grabs)
//   wlh_seat_caps, wlh_ptr_*, wlh_kb_*, wlh_touch_* event handlers
//
// Pointer events belong to the window the pointer entered (ptr_win), keyboard events to the
// window with the keyboard focus (kb_win).  Pointer positions are converted from surface
// coordinates (24.8 fixed, logical) to physical pixels: px = fixed * scale120 / 30720 (the
// window's scale).  Wheel events are accumulated until wl_pointer.frame: axis_value120
// (seat >= 8) or discrete steps x 120 (WSLg) or the continuous value x 12 / 256
// (touchpads); vertical is negated so that up = positive, like Win32.
// Keys: the keymap is parsed by linux_xkb.rs; key repeat uses repeat_info (default 25/s
// after 600 ms) with its own deadline in wait (modifiers never repeat).
// wl_touch: every finger goes to plat::finger, for the window of its surface (a popup's: its owner,
// moved by its offset), at that window's scale; its slot is the finger's id.  A finger's serial
// serves xdg_toplevel.move / resize (the compositor sees that it is a touch and follows the finger);
// a child window follows through the library's drag (linux_wl_child.rs).

use rt::os::{syscall6, SYS_MMAP, SYS_MUNMAP};

use super::proto::*;
use super::wire::{sys_close, Args, A};
use super::xkb::{wl_mods, wl_mods_set, xkb_dead_reset, xkb_dump, xkb_is_dead, xkb_is_modifier, xkb_key, xkb_key_typed,
                 xkb_mod_bit, xkb_parse, xkb_set_mods, xkb_use_fallback};
use super::Wl;
use crate::{
    Event, BTN_LEFT, BTN_MIDDLE, BTN_RIGHT, BTN_X1, BTN_X2, E_DOWN, E_FOCUS_IN, E_FOCUS_OUT, E_KEY_DOWN, E_KEY_UP,
    E_LEAVE, E_MOVE, E_TEXT, E_UP, E_WHEEL, PW_MAX,
};

const BTN_CODE_LEFT: u32 = 0x110; // linux/input-event-codes.h

// evdev BTN_LEFT.. BTN_BACK -> BTN_*
static BTN_MAP: [u8; 7] = [BTN_LEFT, BTN_RIGHT, BTN_MIDDLE, BTN_X1, BTN_X2, BTN_X2, BTN_X1];

/// fingers at once
pub(crate) const FINGERS: usize = 10;
/// Drag::tool of a child window that follows finger k: this + k
pub(crate) const FINGER_TOOL: i32 = 1000;

/// a finger that is down
#[derive(Clone, Copy, Default)]
pub(crate) struct Finger {
    pub used: bool,
    id: i32,    // wl_touch's id of the point
    pub win: i32,
    off: [i32; 2], // the offset of the popup it came down on
    pub at: [i32; 2], // the last position (px of the window)
}

pub(crate) struct Input {
    pub ptr: u32, // wl_pointer
    pub kb: u32,  // wl_keyboard
    pub touch: u32, // wl_touch
    pub fingers: [Finger; FINGERS],
    touch_clock: Option<i32>,
    pub csd: u32, // wp_cursor_shape_device_v1 of the pointer
    pub enter_serial: u32,
    pub btn_serial: u32,
    pub input_serial: u32,
    pub ptr_in: bool,
    pub mx: i32,
    pub my: i32,
    btn_mask: u32,
    pub kb_focus: bool,
    pub kb_win: i32,  // window with the keyboard focus
    pub kb_child: i32, // child window of kb_win that gets the keys (-1 = none; linux_wl_child.rs)
    pub evwin: i32,   // window of the event being pushed
    pub ptr_win: i32, // window under the pointer (-1 = none)
    pub off_x: i32,   // offset of the popup under the pointer in its owner (px, wl_popup)
    pub off_y: i32,
    pub s120_test: i32, // pointer scale while there is no window (g_wl_s120, tests)
    kb_ready: bool,
    rep_key: u32, // evdev + 1 of the repeating key
    rep_next: u64,
    rep_rate: i32,
    rep_delay: i32,
    ax_val: [i32; 2], // per axis (24.8)
    ax_disc: [i32; 2],
    ax_120: [i32; 2],
    ax_flags: u32, // bit axis: discrete, bit 2+axis: value120
}

impl Input {
    pub fn new() -> Input {
        Input {
            ptr: 0,
            kb: 0,
            touch: 0,
            fingers: [Finger { used: false, id: 0, win: 0, off: [0; 2], at: [0; 2] }; FINGERS],
            touch_clock: None,
            csd: 0,
            enter_serial: 0,
            btn_serial: 0,
            input_serial: 0,
            ptr_in: false,
            mx: 0,
            my: 0,
            btn_mask: 0,
            kb_focus: false,
            kb_win: 0,
            kb_child: -1,
            evwin: 0,
            ptr_win: -1,
            off_x: 0,
            off_y: 0,
            s120_test: 0,
            kb_ready: false,
            rep_key: 0,
            rep_next: 0,
            rep_rate: 25,
            rep_delay: 600,
            ax_val: [0; 2],
            ax_disc: [0; 2],
            ax_120: [0; 2],
            ax_flags: 0,
        }
    }
}

impl Wl {
    /// queue an event with the current modifiers and the window inp.evwin  [wl_push]
    pub(crate) fn push(&mut self, typ: u8, btn: u8, x: i32, y: i32, data: u32) {
        let win = (self.inp.evwin as u32 & (PW_MAX as u32 - 1)) as u8;
        crate::evq_push(Event { typ, btn, mods: wl_mods() as u8, win, x, y, data });
    }

    /// events of the pointer: its window  [ptr_evwin]
    fn ptr_evwin(&mut self) {
        self.inp.evwin = self.inp.ptr_win.max(0);
    }

    /// fixed -> physical pixels at the scale of the pointer's window (without a window
    /// s120_test, set by synthetic tests)  [ptr_px]
    fn ptr_px(&self, fixed: i32) -> i32 {
        let w = self.inp.ptr_win.max(0) as usize & (PW_MAX - 1);
        let r = &self.win[w];
        let s = if r.flags & super::window::WLWF_USED != 0 { r.s120 } else { self.inp.s120_test };
        (fixed as i64 * s as i64 / 30720) as i32
    }

    /// the left button is held (the implicit grab of a drag, dnd.rs)
    pub(crate) fn left_held(&self) -> bool {
        self.inp.btn_mask & 1 << BTN_LEFT != 0
    }

    /// the held pointer buttons (BTN_* bits)
    pub(crate) fn held_buttons(&self) -> u32 {
        self.inp.btn_mask
    }

    /// fixed (24.8 logical) -> physical pixels at the scale of window w
    pub(crate) fn ptr_px_of(&self, w: usize, fixed: i32) -> i32 {
        let s = self.win[w & (PW_MAX - 1)].s120.max(1);
        (fixed as i64 * s as i64 / 30720) as i32
    }

    /// E_UP for every held button (at the last position)  [wl_release_buttons]
    pub(crate) fn release_buttons(&mut self) {
        self.ptr_evwin();
        for b in 1..=5u8 {
            if self.inp.btn_mask & 1 << b != 0 {
                self.inp.btn_mask &= !(1 << b);
                let (x, y) = (self.inp.mx, self.inp.my);
                self.push(E_UP, b, x, y, 0);
            }
        }
    }

    /// key repeat -> the next repeat deadline (u64::MAX = none)  [wl_input_service]
    pub(crate) fn input_service(&mut self, now: u64) -> u64 {
        if self.inp.rep_key == 0 {
            return u64::MAX;
        }
        if !self.inp.kb_focus {
            self.inp.rep_key = 0;
            return u64::MAX;
        }
        if now < self.inp.rep_next {
            return self.inp.rep_next;
        }
        self.inp.evwin = self.kb_target();
        let (vk, text) = xkb_key(self.inp.rep_key - 1);
        if vk != 0 {
            self.push(E_KEY_DOWN, 0, 0, 0, vk | 0x8000_0000);
        }
        if text != 0 {
            self.push(E_TEXT, 0, 0, 0, text);
        }
        if self.inp.rep_rate <= 0 {
            self.inp.rep_key = 0;
            return u64::MAX;
        }
        let iv = (1_000_000 / self.inp.rep_rate as u32) as u64;
        let mut next = self.inp.rep_next + iv;
        if next <= now {
            next = now + iv; // fell behind: no bursts
        }
        self.inp.rep_next = next;
        next
    }
}

// ------------------------------------------------------------------ seat

/// wl_seat.capabilities: create / drop pointer + keyboard  [wlh_seat_caps]
pub(crate) fn wlh_seat_caps(wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    let caps = a.u(0);
    if caps & 1 != 0 {
        if wl.inp.ptr == 0 {
            let p = wl.w.send(wl.g.seat, &SEAT_GET_POINTER, &[A::N(&IFACE_WL_POINTER)]);
            wl.inp.ptr = p;
            if wl.g.csm != 0 {
                wl.inp.csd = wl.w.send(wl.g.csm, &CSM_GET_POINTER, &[A::N(&IFACE_WP_CSD), A::O(p)]);
            }
        }
    } else if wl.inp.ptr != 0 {
        let p = wl.inp.ptr;
        wl.inp.ptr = 0;
        wl.inp.ptr_in = false;
        if wl.g.seat_ver >= 3 {
            wl.w.send(p, &POINTER_RELEASE, &[]);
        }
    }
    if caps & 4 != 0 {
        if wl.inp.touch == 0 {
            wl.inp.touch = wl.w.send(wl.g.seat, &SEAT_GET_TOUCH, &[A::N(&IFACE_WL_TOUCH)]);
        }
    } else if wl.inp.touch != 0 {
        let t = wl.inp.touch;
        wl.inp.touch = 0;
        wl.fingers_cancel();
        if wl.g.seat_ver >= 3 {
            wl.w.send(t, &TOUCH_RELEASE, &[]);
        }
    }
    if caps & 2 != 0 {
        if wl.inp.kb == 0 {
            wl.inp.kb = wl.w.send(wl.g.seat, &SEAT_GET_KEYBOARD, &[A::N(&IFACE_WL_KEYBOARD)]);
        }
    } else if wl.inp.kb != 0 {
        let k = wl.inp.kb;
        wl.inp.kb = 0;
        wl.inp.rep_key = 0;
        if wl.g.seat_ver >= 3 {
            wl.w.send(k, &KEYBOARD_RELEASE, &[]);
        }
    }
}

// ------------------------------------------------------------------ touch

impl Wl {
    // fixed -> px at the scale of window w (without a window s120_test, as the pointer)
    fn finger_px(&self, w: usize, fixed: i32) -> i32 {
        let r = &self.win[w & (PW_MAX - 1)];
        let s = if r.flags & super::window::WLWF_USED != 0 { r.s120 } else { self.inp.s120_test };
        (fixed as i64 * s as i64 / 30720) as i32
    }

    fn finger_slot(&self, id: i32) -> Option<usize> {
        self.inp.fingers.iter().position(|f| f.used && f.id == id)
    }

    fn finger_push(&mut self, k: usize, phase: crate::FingerPhase, age: u32) {
        let f = self.inp.fingers[k];
        let win = (f.win as u32 & (PW_MAX as u32 - 1)) as u8;
        let mut e = crate::finger_event(win, phase, k as u8, f.at[0], f.at[1], age);
        e.mods = wl_mods() as u8;
        crate::evq_push(e);
    }

    /// the finger that is down on window w: its slot and position (a drag of a child window)
    pub(crate) fn finger_on(&self, w: usize) -> Option<(usize, i32, i32)> {
        self.inp.fingers.iter().position(|f| f.used && f.win == w as i32).map(|k| (k, self.inp.fingers[k].at[0], self.inp.fingers[k].at[1]))
    }

    /// wl_touch.cancel: every finger is gone, no click, no fling
    pub(crate) fn fingers_cancel(&mut self) {
        if self.drag.on && self.drag.tool >= FINGER_TOOL {
            self.child_drag_end();
        }
        for k in 0..FINGERS {
            if self.inp.fingers[k].used {
                self.finger_push(k, crate::FingerPhase::Cancel, 0);
                self.inp.fingers[k].used = false;
            }
        }
    }
}

/// down(serial, time, surface, id, x, y)
pub(crate) fn wlh_touch_down(wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    let surf = a.u(2);
    let mut w = wl.find(surf);
    let mut off = [0; 2];
    if w < 0 {
        // a popup: its owner and offset (the pointer's offset is kept)
        let (px, py) = (wl.inp.off_x, wl.inp.off_y);
        w = wl.popup_ptr(surf);
        off = [wl.inp.off_x, wl.inp.off_y];
        wl.inp.off_x = px;
        wl.inp.off_y = py;
        if w < 0 {
            return;
        }
    }
    wl.inp.btn_serial = a.u(0);
    wl.inp.input_serial = a.u(0);
    let id = a.i(3);
    if let Some(k) = wl.finger_slot(id) {
        wl.finger_push(k, crate::FingerPhase::Cancel, 0); // (it never lifted)
        wl.inp.fingers[k].used = false;
    }
    let Some(k) = wl.inp.fingers.iter().position(|f| !f.used) else { return };
    let at = [wl.finger_px(w as usize, a.i(4)) + off[0], wl.finger_px(w as usize, a.i(5)) + off[1]];
    wl.inp.fingers[k] = Finger { used: true, id, win: w, off, at };
    wl.child_press(w, at[0], at[1]); // the keyboard between a toplevel and its child windows
    let age = crate::evq::finger_age(&mut wl.inp.touch_clock, a.u(1));
    wl.finger_push(k, crate::FingerPhase::Down, age);
}

/// up(serial, time, id)
pub(crate) fn wlh_touch_up(wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    let Some(k) = wl.finger_slot(a.i(2)) else { return };
    if wl.drag.on && wl.drag.tool == FINGER_TOOL + k as i32 {
        wl.child_drag_end();
    }
    let age = crate::evq::finger_age(&mut wl.inp.touch_clock, a.u(1));
    wl.finger_push(k, crate::FingerPhase::Up, age);
    wl.inp.fingers[k].used = false;
}

/// motion(time, id, x, y)
pub(crate) fn wlh_touch_motion(wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    let Some(k) = wl.finger_slot(a.i(1)) else { return };
    let f = wl.inp.fingers[k];
    let w = f.win as usize;
    let at = [wl.finger_px(w, a.i(2)) + f.off[0], wl.finger_px(w, a.i(3)) + f.off[1]];
    wl.inp.fingers[k].at = at;
    if wl.drag.on && wl.drag.tool == FINGER_TOOL + k as i32 {
        wl.child_drag_motion(f.win, at[0], at[1]); // a child window moved / resized by the library: no move
        return;
    }
    let age = crate::evq::finger_age(&mut wl.inp.touch_clock, a.u(0));
    wl.finger_push(k, crate::FingerPhase::Move, age);
}

/// cancel: the compositor took them
pub(crate) fn wlh_touch_cancel(wl: &mut Wl, _id: u32, _a: &Args, _u: u64) {
    wl.fingers_cancel();
}

// ------------------------------------------------------------------ pointer

/// enter(serial, surface, x, y): the pointer is over one of our windows  [wlh_ptr_enter]
pub(crate) fn wlh_ptr_enter(wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    wl.inp.enter_serial = a.u(0);
    wl.inp.off_x = 0;
    wl.inp.off_y = 0;
    wl.popup_ptr_reset();
    let surf = a.u(1);
    let mut w = wl.find(surf);
    if w < 0 {
        w = wl.popup_ptr(surf); // (U3) a popup window: the events are its owner's, moved by its offset
        if w < 0 {
            return;
        }
    }
    wl.inp.ptr_win = w;
    wl.inp.evwin = w;
    wl.inp.ptr_in = true;
    wl.inp.mx = wl.ptr_px(a.i(2)) + wl.inp.off_x;
    wl.inp.my = wl.ptr_px(a.i(3)) + wl.inp.off_y;
    wl.cursor_apply();
    let (x, y) = (wl.inp.mx, wl.inp.my);
    wl.push(E_MOVE, 0, x, y, 0);
}

/// [wlh_ptr_leave]
pub(crate) fn wlh_ptr_leave(wl: &mut Wl, _id: u32, _a: &Args, _u: u64) {
    if wl.drag.on && wl.drag.tool < 0 {
        wl.child_drag_end(); // (the grab ended)
    }
    if !wl.inp.ptr_in {
        return;
    }
    wl.inp.ptr_in = false;
    wl.release_buttons();
    wl.ptr_evwin();
    wl.push(E_LEAVE, 0, 0, 0, 0);
    wl.inp.ptr_win = -1;
}

/// motion(time, x, y)  [wlh_ptr_motion]
pub(crate) fn wlh_ptr_motion(wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    wl.inp.mx = wl.ptr_px(a.i(1)) + wl.inp.off_x; // (U3) over a popup window
    wl.inp.my = wl.ptr_px(a.i(2)) + wl.inp.off_y;
    if wl.drag.on && wl.drag.tool < 0 {
        let (x, y) = (wl.inp.mx, wl.inp.my);
        wl.child_drag_ptr_motion(x, y); // a child window moved / resized by the library: no E_MOVE
        return;
    }
    wl.ptr_evwin();
    let (x, y) = (wl.inp.mx, wl.inp.my);
    wl.push(E_MOVE, 0, x, y, 0);
}

/// button(serial, time, button, state)  [wlh_ptr_button]
pub(crate) fn wlh_ptr_button(wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    wl.inp.btn_serial = a.u(0);
    wl.inp.input_serial = a.u(0);
    let b = a.u(2).wrapping_sub(BTN_CODE_LEFT);
    if wl.drag.on && wl.drag.tool < 0 {
        // the release of a button that started the drag of a child window ends it
        if a.u(3) == 0 && b <= 6 && wl.drag.btns & 1 << BTN_MAP[b as usize] != 0 {
            wl.child_drag_end();
        } else {
            wl.drag.other = true; // (its frame is no motion)
        }
        return;
    }
    if b > 6 {
        return;
    }
    let btn = BTN_MAP[b as usize];
    let typ = if a.u(3) != 0 {
        wl.inp.btn_mask |= 1 << btn;
        let (w, x, y) = (wl.inp.ptr_win, wl.inp.mx, wl.inp.my);
        wl.child_press(w, x, y); // the keyboard between a toplevel and its child windows
        E_DOWN
    } else {
        if wl.inp.btn_mask & 1 << btn == 0 {
            return; // not pressed inside our window
        }
        wl.inp.btn_mask &= !(1 << btn);
        E_UP
    };
    wl.ptr_evwin();
    let (x, y) = (wl.inp.mx, wl.inp.my);
    wl.push(typ, btn, x, y, 0);
}

/// axis(time, axis, value)  [wlh_ptr_axis]
pub(crate) fn wlh_ptr_axis(wl: &mut Wl, id: u32, a: &Args, u: u64) {
    let ax = a.u(1);
    if ax > 1 {
        return;
    }
    wl.inp.ax_val[ax as usize] = wl.inp.ax_val[ax as usize].wrapping_add(a.i(2));
    if wl.g.seat_ver < 5 {
        wlh_ptr_frame(wl, id, a, u); // no frame events before v5
    }
}

/// axis_discrete(axis, steps)  [wlh_ptr_discrete]
pub(crate) fn wlh_ptr_discrete(wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    let ax = a.u(0);
    if ax > 1 {
        return;
    }
    wl.inp.ax_disc[ax as usize] = wl.inp.ax_disc[ax as usize].wrapping_add(a.i(1));
    wl.inp.ax_flags |= 1 << ax;
}

/// axis_value120(axis, value120)  [wlh_ptr_value120]
pub(crate) fn wlh_ptr_value120(wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    let ax = a.u(0);
    if ax > 1 {
        return;
    }
    wl.inp.ax_120[ax as usize] = wl.inp.ax_120[ax as usize].wrapping_add(a.i(1));
    wl.inp.ax_flags |= 1 << (ax + 2);
}

/// end of a pointer event group: the motion of a child window's drag, flush the wheel
/// [wlh_ptr_frame]
pub(crate) fn wlh_ptr_frame(wl: &mut Wl, _id: u32, _a: &Args, _u: u64) {
    if wl.drag.on && wl.drag.tool < 0 {
        let wheel = wl.inp.ax_flags != 0 || wl.inp.ax_val != [0; 2];
        wl.child_drag_frame(wheel);
    }
    let mut d = [0i32; 2]; // dy, dx
    for ax in 0..2 {
        let f = wl.inp.ax_flags;
        let v = if f & 1 << (ax + 2) != 0 {
            wl.inp.ax_120[ax]
        } else if f & 1 << ax != 0 {
            wl.inp.ax_disc[ax].wrapping_mul(120)
        } else {
            ((wl.inp.ax_val[ax] as i64 * 12) >> 8) as i32
        };
        let v = v.clamp(-32767, 32767);
        d[ax] = if ax == 0 { -v } else { v }; // Wayland: positive = down
    }
    wl.inp.ax_flags = 0;
    wl.inp.ax_val = [0; 2];
    wl.inp.ax_disc = [0; 2];
    wl.inp.ax_120 = [0; 2];
    if d[0] | d[1] == 0 {
        return;
    }
    let data = (d[0] as u32 & 0xFFFF) | (d[1] as u32) << 16;
    wl.ptr_evwin();
    let (x, y) = (wl.inp.mx, wl.inp.my);
    wl.push(E_WHEEL, 0, x, y, data);
}

// ------------------------------------------------------------------ keyboard

/// keymap(format, fd, size): parse it (MAP_PRIVATE)  [wlh_kb_keymap]
pub(crate) fn wlh_kb_keymap(wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    let fmt = a.u(0);
    let fd = a.u(1) as i32;
    let size = a.u(2) as usize;
    wl.inp.kb_ready = true;
    let mut ok = false;
    if fmt == 1 && size != 0 {
        // XKB_V1
        // SAFETY: a private read-only mapping of the keymap fd, unmapped below.
        let p = unsafe { syscall6(SYS_MMAP, 0, size, 1, 2, fd as u32 as usize, 0) };
        if !(-4095..0).contains(&p) {
            // SAFETY: the mapping holds size bytes.
            let text = unsafe { core::slice::from_raw_parts(p as *const u8, size) };
            ok = xkb_parse(text) == 0;
            // SAFETY: the mapping made above.
            unsafe { syscall6(SYS_MUNMAP, p as usize, size, 0, 0, 0, 0) };
        }
    }
    if !ok {
        crate::write_stderr(b"wayland: keymap not usable, using the built-in US layout\n");
        xkb_use_fallback();
    }
    sys_close(fd);
    if crate::env("jfgui_XKBDUMP").is_some() {
        xkb_dump();
    }
}

/// enter(serial, surface, keys): one of our windows has the keyboard focus  [wlh_kb_enter]
pub(crate) fn wlh_kb_enter(wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    wl.inp.input_serial = a.u(0);
    let w = wl.find(a.u(1));
    if w < 0 {
        return;
    }
    wl.inp.kb_win = w;
    wl.inp.evwin = wl.kb_target();
    wl.inp.kb_focus = true;
    wl.push(E_FOCUS_IN, 0, 0, 0, 0);
}

/// [wlh_kb_leave]
pub(crate) fn wlh_kb_leave(wl: &mut Wl, _id: u32, _a: &Args, _u: u64) {
    xkb_dead_reset();
    wl.inp.kb_focus = false;
    wl.inp.rep_key = 0;
    wl.inp.evwin = wl.kb_target();
    wl.push(E_FOCUS_OUT, 0, 0, 0, 0);
}

/// key(serial, time, key, state)  [wlh_kb_key]
pub(crate) fn wlh_kb_key(wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    wl.inp.input_serial = a.u(0);
    let key = a.u(2); // evdev code
    let down = a.u(3) != 0;
    if key >= 256 {
        return;
    }
    if !wl.inp.kb_ready {
        wl.inp.kb_ready = true;
        xkb_use_fallback();
    }
    // like Win32, a modifier's own key event already carries its new state
    let mb = xkb_mod_bit(key);
    if mb != 0 {
        wl_mods_set(if down { wl_mods() | mb } else { wl_mods() & !mb });
    }
    wl.inp.evwin = wl.kb_target();
    if down {
        let dead = xkb_is_dead(key);
        let (vk, text) = xkb_key_typed(key); // dead keys composed (´ e -> é)
        if vk != 0 {
            wl.push(E_KEY_DOWN, 0, 0, 0, vk);
        }
        for t in text.into_iter().filter(|&t| t != 0) {
            wl.push(E_TEXT, 0, 0, 0, t);
        }
        if dead {
            wl.inp.rep_key = 0; // a new key ends the repeat; a dead key does not repeat
        } else if !xkb_is_modifier(key) && wl.inp.rep_rate > 0 {
            wl.inp.rep_key = key + 1;
            wl.inp.rep_next = crate::time_us() + (wl.inp.rep_delay as u32).wrapping_mul(1000) as u64;
        }
    } else {
        let (vk, _) = xkb_key(key);
        if key + 1 == wl.inp.rep_key {
            wl.inp.rep_key = 0;
        }
        if vk != 0 {
            wl.push(E_KEY_UP, 0, 0, 0, vk);
        }
    }
}

/// modifiers(serial, depressed, latched, locked, group)  [wlh_kb_modifiers]
pub(crate) fn wlh_kb_modifiers(_wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    xkb_set_mods(a.u(1), a.u(2), a.u(3), a.u(4));
}

/// repeat_info(rate per s, delay ms)  [wlh_kb_repeat]
pub(crate) fn wlh_kb_repeat(wl: &mut Wl, _id: u32, a: &Args, _u: u64) {
    wl.inp.rep_rate = a.i(0).clamp(0, 1000); // a huge rate would make the repeat deadline "now" forever
    wl.inp.rep_delay = a.i(1).clamp(0, 60_000);
}