softer_gui 3.0.2

CPU-rendered windowing with vblank-exact frame pacing and one ordered input+render event stream. Speaks X11, Wayland, AppKit and Win32 directly; no dependencies.
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
//! The event model: one totally ordered SPSC ring carrying input AND frame
//! boundaries, stamped with DISPLAY time; the pump-side keyboard state machine
//! (absolute button bitmap, layout text, dead keys, WM-driven autorepeat).
//!
//! Display time: 128-bit femtoseconds that advance ONLY at frame boundaries and
//! only in whole refresh periods, so consecutive RENDERs on a 60 Hz monitor are
//! exactly 1/60 apart. It is not the system clock and drifts from it — the two
//! answer different questions ("when will this be shown" vs "what time is it").
//! Every event within one frame shares that frame's time; equal timestamps mean
//! the same frame: re-render, do not step.

use core::cell::UnsafeCell;
use core::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering::*};
use crate::keysym;

#[cfg(all(target_os = "linux", not(cosmo)))]
fn now_ns() -> u64 { crate::sys::clock_monotonic_ns() }
#[cfg(not(all(target_os = "linux", not(cosmo))))]
fn now_ns() -> u64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(1) }

pub const RING: usize = 256;

// ---- evdev codes the library itself refers to ------------------------------
pub const KEY_ESC: u32 = 1;
pub const KEY_BACKSPACE: u32 = 14;
pub const KEY_TAB: u32 = 15;
pub const KEY_ENTER: u32 = 28;
pub const KEY_LEFTCTRL: u32 = 29;
pub const KEY_LEFTSHIFT: u32 = 42;
pub const KEY_RIGHTSHIFT: u32 = 54;
pub const KEY_LEFTALT: u32 = 56;
pub const KEY_RIGHTCTRL: u32 = 97;
pub const KEY_RIGHTALT: u32 = 100;
pub const KEY_HOME: u32 = 102;
pub const KEY_UP: u32 = 103;
pub const KEY_PAGEUP: u32 = 104;
pub const KEY_LEFT: u32 = 105;
pub const KEY_RIGHT: u32 = 106;
pub const KEY_END: u32 = 107;
pub const KEY_DOWN: u32 = 108;
pub const KEY_PAGEDOWN: u32 = 109;
pub const KEY_INSERT: u32 = 110;
pub const KEY_DELETE: u32 = 111;
pub const KEY_LEFTMETA: u32 = 125;
pub const KEY_RIGHTMETA: u32 = 126;
pub const KEY_F9: u32 = 67;
pub const KEY_F11: u32 = 87;
pub const KEY_F12: u32 = 88;
pub const KEY_UNKNOWN: u32 = 240;
pub const BTN_LEFT: u32 = 0x110;
pub const BTN_RIGHT: u32 = 0x111;
pub const BTN_MIDDLE: u32 = 0x112;
pub const BTN_SIDE: u32 = 0x113;
pub const BTN_EXTRA: u32 = 0x114;

// ---- continuous axes ---------------------------------------------------------
/// Absolute pointer position, 24.8 fixed pixels, window-local. (Also on every RENDER.)
pub const AXIS_MOUSE_X: u32 = 0;
pub const AXIS_MOUSE_Y: u32 = 1;
/// Continuous scroll from a touch surface (touchpad, Magic Mouse, touch screen pan):
/// 24.8 fixed physical pixels, already in the direction the OS's "natural scrolling"
/// setting asks for. Positive = content moves up/left.
///
/// A mouse wheel never lands here: it is AXIS_WHEEL_V/H, in clicks, because the two
/// devices mean different things to an application (a wheel is a stepper, a touchpad
/// is a pan) and no OS agrees on how many pixels a click is worth. The split is done
/// by the backend on every platform, so an application never has to guess the device
/// from the shape of the numbers.
pub const AXIS_SCROLL_V: u32 = 2;
pub const AXIS_SCROLL_H: u32 = 3;
/// Touchpad pinch: change of scale factor, 16.16 fixed (+6554 = +10 %).
pub const AXIS_ZOOM: u32 = 4;
/// Touchpad rotate: degrees, 16.16 fixed, clockwise positive.
pub const AXIS_ROTATE: u32 = 5;
/// Mouse wheel, 24.8 fixed *clicks*: one detent is WHEEL_CLICK (256), high-resolution
/// wheels arrive in fractions of it. Positive = wheel rolled toward the user / tilted
/// right, i.e. the same sense as AXIS_SCROLL. An application that wants the wheel to
/// pan like a touchpad multiplies by SCROLL_STEP / WHEEL_CLICK.
pub const AXIS_WHEEL_V: u32 = 6;
pub const AXIS_WHEEL_H: u32 = 7;
/// One wheel detent on AXIS_WHEEL_V/H.
pub const WHEEL_CLICK: i32 = 256;
/// Conventional pan distance for one wheel click, in AXIS_SCROLL units (15 px in 24.8).
pub const SCROLL_STEP: i32 = 15 * 256;

pub const MODE_DEAD_KEY: u8 = 1;

pub const CP_COPY: u32 = 1;
pub const CP_CUT: u32 = 2;
pub const CP_PASTE: u32 = 3;

pub const EVENT_NONE: u32 = 0;
/// A frame boundary passed: draw the current state. Fields: width, height, scale_fx, cursor_x/y, dt_fs.
pub const EVENT_RENDER: u32 = 1;
/// Absolute snapshot of every key and mouse button (evdev codes). Fields: bits, modes.
pub const EVENT_BUTTONS: u32 = 2;
/// Layout-aware text. Fields: text, text_len.
pub const EVENT_TEXT: u32 = 3;
/// Copy/cut/paste intent. Field: action (CP_*).
pub const EVENT_COPYPASTE: u32 = 4;
/// Continuous input. Fields: axes, axis_count.
pub const EVENT_AXES: u32 = 5;
/// The window was asked to close.
pub const EVENT_CLOSE: u32 = 6;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AxisDiff { pub axis: u32, pub delta: i32 }

/// One event. `kind` says which fields are meaningful; the rest are zero.
/// A flat struct on purpose: it is what goes into the ring, and it reads like C.
#[derive(Clone, Copy, Debug)]
pub struct Event {
    pub kind: u32,
    pub device: u32,
    /// Display time, femtoseconds (see the module doc).
    pub t_fs: u128,
    // EVENT_RENDER
    pub width: u32,
    pub height: u32,
    /// UI scale, 16.16 fixed (65536 = 1.0).
    pub scale_fx: u32,
    /// Pointer, 32.32 fixed, window-local. Integer pixel = v >> 32.
    pub cursor_x: i64,
    pub cursor_y: i64,
    /// Nominal frame period (1 s / refresh rate), femtoseconds. Not a measurement.
    pub dt_fs: u64,
    // EVENT_BUTTONS
    pub bits: [u64; 8],
    /// MODE_* flags — armed dead key etc.
    pub modes: u8,
    // EVENT_TEXT
    pub text_len: u8,
    pub text: [char; 19],
    // EVENT_COPYPASTE
    pub action: u32,
    // EVENT_AXES
    pub axis_count: u8,
    pub axes: [AxisDiff; 11],
}

impl Default for Event {
    fn default() -> Event {
        Event { kind: EVENT_NONE, device: 0, t_fs: 0, width: 0, height: 0, scale_fx: 0, cursor_x: 0, cursor_y: 0, dt_fs: 0,
                bits: [0; 8], modes: 0, text_len: 0, text: ['\0'; 19], action: 0, axis_count: 0, axes: [AxisDiff::default(); 11] }
    }
}

impl Event {
    /// EVENT_BUTTONS: is this evdev code held?
    #[inline] pub fn button(&self, code: u32) -> bool { (self.bits[(code as usize >> 6) & 7] >> (code & 63)) & 1 != 0 }
    pub fn text(&self) -> &[char] { &self.text[..self.text_len as usize] }
    pub fn axes(&self) -> &[AxisDiff] { &self.axes[..self.axis_count as usize] }
}

// ---- pump-owned keyboard / clock state -------------------------------------
pub struct PumpState {
    pub keybits: [u64; 8],
    pub resync_pending: bool,
    pub render_id_p1: u64,   // (ring index of the last pushed RENDER) + 1, 0 = none
    pub disp_fs: u128,
    pub disp_period_fs: u64,
    pub mode_flags: u8,
    pub dead_sym: u32,       // armed dead keysym, 0 = none
    pub repeat_code: u32,
    pub repeat_text: [char; 4],
    pub repeat_text_len: u8,
    pub repeat_deadline_ns: u64,
    pub repeat_delay_ns: u64,
    pub repeat_interval_ns: u64,
    pub device: u32,
}

/// Everything shared between the pump thread (sole producer) and the app thread
/// (sole consumer). Word-sized atomics only; no locks on the hot path.
pub struct Core {
    ring: [UnsafeCell<Event>; RING],
    head: AtomicU64,
    tail: AtomicU64,
    /// Futex word: low 32 bits of head, bumped on every commit so the consumer can sleep on it.
    head_futex: AtomicU32,
    sleeping: AtomicU32,
    #[cfg(not(all(target_os = "linux", not(cosmo))))]
    park: (std::sync::Mutex<()>, std::sync::Condvar),
    pump: UnsafeCell<PumpState>,

    pub win_w: AtomicU32,
    pub win_h: AtomicU32,
    pub scale_fx: AtomicU32,
    pub cursor_x: AtomicI64,
    pub cursor_y: AtomicI64,
    pub busy: [AtomicBool; 2],
    pub full_redraw: AtomicBool,
    pub cursor_hidden: AtomicBool,
    pub wants_fullscreen: AtomicBool,
    pub wants_frame: AtomicBool,
    pub quit: AtomicBool,
    pub focused: AtomicBool,
    /// Trace the backend's own decisions. Set once at open from Options, and read
    /// by every backend, so a caller can turn it on without an environment.
    pub debug: AtomicBool,
    /// The app asking for the next rendering path. Windows only, where there is
    /// more than one; a request the pump acts on, like the fullscreen flag,
    /// because only the pump may touch the presenter.
    pub wants_cycle: AtomicBool,
    /// Presents submitted but not yet completed by the display server.
    pub in_flight: AtomicU32,
    /// Bumped by the pump to poke the app-side wait (resize, etc.).
    pub title_changed: AtomicBool,
    /// Window icon, largest first. The pump applies it and clears `icon_dirty`.
    /// Behind a Mutex rather than in the ring because it is bulk state the app
    /// replaces wholesale, not an event with a place in the order.
    pub icon: std::sync::Mutex<Vec<crate::icon::OwnedIcon>>,
    pub icon_dirty: AtomicBool,
}

unsafe impl Sync for Core {}
unsafe impl Send for Core {}

macro_rules! ps { ($s:expr) => { (unsafe { &mut *$s.pump.get() }) } }

impl Core {
    pub fn new() -> Core {
        let t = now_ns();
        Core {
            ring: core::array::from_fn(|_| UnsafeCell::new(Event::default())),
            head: AtomicU64::new(0),
            tail: AtomicU64::new(0),
            head_futex: AtomicU32::new(0),
            sleeping: AtomicU32::new(0),
            #[cfg(not(all(target_os = "linux", not(cosmo))))]
            park: (std::sync::Mutex::new(()), std::sync::Condvar::new()),
            pump: UnsafeCell::new(PumpState {
                keybits: [0; 8],
                resync_pending: false,
                render_id_p1: 0,
                disp_fs: 0,
                disp_period_fs: 1_000_000_000_000_000 / 60,
                mode_flags: 0,
                dead_sym: 0,
                repeat_code: 0,
                repeat_text: ['\0'; 4],
                repeat_text_len: 0,
                repeat_deadline_ns: 0,
                repeat_delay_ns: 400_000_000,
                repeat_interval_ns: 33_000_000,
                device: ((t & 0xFFFF) as u32) | 1,
            }),
            win_w: AtomicU32::new(0),
            win_h: AtomicU32::new(0),
            scale_fx: AtomicU32::new(65536),
            cursor_x: AtomicI64::new(0),
            cursor_y: AtomicI64::new(0),
            busy: [AtomicBool::new(false), AtomicBool::new(false)],
            full_redraw: AtomicBool::new(true),
            cursor_hidden: AtomicBool::new(false),
            wants_fullscreen: AtomicBool::new(false),
            wants_frame: AtomicBool::new(false),
            quit: AtomicBool::new(false),
            focused: AtomicBool::new(true),
            debug: AtomicBool::new(false),
            wants_cycle: AtomicBool::new(false),
            in_flight: AtomicU32::new(0),
            title_changed: AtomicBool::new(false),
            icon: std::sync::Mutex::new(Vec::new()),
            icon_dirty: AtomicBool::new(false),
        }
    }

    // ---- producer side (pump thread only) --------------------------------------

    /// Reserve a slot; None when the ring is full (the event is dropped and a resync is owed).
    fn reserve(&self, mut ev: Event) -> Option<u64> {
        let head = self.head.load(Relaxed);
        let tail = self.tail.load(Acquire);
        if head - tail >= RING as u64 {
            ps!(self).resync_pending = true;
            return None;
        }
        ev.t_fs = ps!(self).disp_fs;
        ev.device = ps!(self).device;
        unsafe { *self.ring[(head as usize) & (RING - 1)].get() = ev; }
        Some(head)
    }
    fn commit(&self, id: u64) {
        self.head.store(id + 1, Release);
        self.head_futex.fetch_add(1, Release);
        if self.sleeping.load(Acquire) != 0 {
            #[cfg(all(target_os = "linux", not(cosmo)))]
            crate::sys::futex_wake(&self.head_futex, 1);
            #[cfg(not(all(target_os = "linux", not(cosmo))))]
            { let _g = self.park.0.lock().unwrap(); self.park.1.notify_one(); }
        }
    }
    fn push(&self, ev: Event) -> bool {
        match self.reserve(ev) { Some(id) => { self.commit(id); true } None => false }
    }

    pub fn push_close(&self) { self.push(Event { kind: EVENT_CLOSE, ..Event::default() }); }
    pub fn push_copypaste(&self, action: u32) { self.push(Event { kind: EVENT_COPYPASTE, action, ..Event::default() }); }

    pub fn push_button_snapshot(&self) {
        let ev = Event { kind: EVENT_BUTTONS, bits: ps!(self).keybits, modes: ps!(self).mode_flags, ..Event::default() };
        self.push(ev);
    }

    /// Pay off an owed snapshot once there is room again. Call at the top of every pump pass.
    pub fn service_resync(&self) {
        if ps!(self).resync_pending && self.head.load(Relaxed) - self.tail.load(Acquire) < RING as u64 {
            ps!(self).resync_pending = false;
            self.push_button_snapshot();
        }
    }

    /// Set/clear one discrete input and publish the absolute snapshot.
    pub fn key(&self, code: u32, pressed: bool) {
        if code >= 512 { return; }
        let w = &mut ps!(self).keybits[(code >> 6) as usize];
        let bit = 1u64 << (code & 63);
        if pressed { *w |= bit } else { *w &= !bit }
        self.push_button_snapshot();
    }
    #[inline] pub fn key_down(&self, code: u32) -> bool {
        code < 512 && (ps!(self).keybits[(code >> 6) as usize] >> (code & 63)) & 1 != 0
    }
    /// Release+press so the bit ends SET and the app sees a fresh edge (autorepeat of a nav key).
    pub fn key_refire(&self, code: u32) { self.key(code, false); self.key(code, true); }

    /// Focus lost: every key is logically up. Left set, our autorepeat would run forever.
    pub fn release_all_keys(&self, keyboard_only: bool) {
        let mut held = 0u64;
        let n = if keyboard_only { 4 } else { 8 };
        for i in 0..n { held |= ps!(self).keybits[i]; ps!(self).keybits[i] = 0; }
        ps!(self).repeat_code = 0;
        if held != 0 { self.push_button_snapshot(); }
    }

    pub fn push_text(&self, chars: &[char]) {
        let mut ev = Event { kind: EVENT_TEXT, ..Event::default() };
        for c in chars.iter().take(19) { ev.text[ev.text_len as usize] = *c; ev.text_len += 1; }
        if ev.text_len > 0 { self.push(ev); }
    }
    /// One Text event per codepoint (streams must not reduce last-wins). Control chars dropped.
    pub fn push_text_str(&self, s: &str) -> Option<char> {
        let mut last = None;
        for c in s.chars() {
            if (c as u32) < 0x20 || c as u32 == 0x7f { continue; }
            self.push_text(&[c]);
            last = Some(c);
        }
        last
    }

    pub fn push_axes(&self, diffs: &[AxisDiff]) {
        let mut ev = Event { kind: EVENT_AXES, ..Event::default() };
        for d in diffs.iter().take(11) { ev.axes[ev.axis_count as usize] = *d; ev.axis_count += 1; }
        if ev.axis_count > 0 { self.push(ev); }
    }

    /// A RENDER means "a frame boundary passed, draw the current state" — it is not
    /// a unit of queued work, so a new one is dropped while the previous is still
    /// unconsumed. The pump owns render_id_p1 and only reads the app's tail; a
    /// stale-low tail can only make us drop one extra RENDER, never stall the clock.
    pub fn push_render(&self) -> bool {
        if ps!(self).render_id_p1 != 0 && ps!(self).render_id_p1 - 1 >= self.tail.load(Acquire) { return false; }
        let r = Event {
            kind: EVENT_RENDER,
            width: self.win_w.load(Relaxed),
            height: self.win_h.load(Relaxed),
            scale_fx: self.scale_fx.load(Relaxed),
            cursor_x: self.cursor_x.load(Relaxed),
            cursor_y: self.cursor_y.load(Relaxed),
            dt_fs: ps!(self).disp_period_fs,
            ..Event::default()
        };
        if let Some(id) = self.reserve(r) {
            ps!(self).render_id_p1 = id + 1;
            self.commit(id);
            self.wants_frame.store(false, Relaxed);
            true
        } else { false }
    }
    pub fn render_pending(&self) -> bool {
        ps!(self).render_id_p1 != 0 && ps!(self).render_id_p1 - 1 >= self.tail.load(Acquire)
    }

    /// The ONLY way display time moves: never from a wall clock reading.
    pub fn display_tick(&self, frames: u64) {
        ps!(self).disp_fs += ps!(self).disp_period_fs as u128 * frames as u128;
    }
    pub fn set_period_fs(&self, fs: u64) { if fs != 0 { ps!(self).disp_period_fs = fs; } }
    pub fn period_fs(&self) -> u64 { ps!(self).disp_period_fs }

    /// Publish the pointer position (32.32 window-local) and emit it as an axes event.
    pub fn pointer_abs(&self, x_fx: i64, y_fx: i64) {
        self.cursor_x.store(x_fx, Relaxed);
        self.cursor_y.store(y_fx, Relaxed);
        self.push_axes(&[AxisDiff { axis: AXIS_MOUSE_X, delta: (x_fx >> 24) as i32 },
                         AxisDiff { axis: AXIS_MOUSE_Y, delta: (y_fx >> 24) as i32 }]);
    }

    // ---- layout-aware key handling (shared by every backend) ------------------
    /// A key press with its resolved keysym and layout text. Order is load-bearing:
    /// text/dead-key first (it may arm or disarm the dead mode the snapshot must
    /// carry), then the button snapshot, then arm autorepeat.
    pub fn key_press_sym(&self, code: u32, sym: u32, text: &str, now_ns: u64) {
        let mut produced: Option<char> = None;
        let mut emitted_dead = false;
        if sym != 0 {
            if keysym::is_modifier(sym) {
                // Modifiers pass through an armed dead key untouched.
            } else if let Some(base) = keysym::dead_key_base(sym) {
                // Arm (or re-arm) the dead key; pressing the same dead key twice yields the bare accent.
                if ps!(self).dead_sym == sym {
                    ps!(self).dead_sym = 0; ps!(self).mode_flags &= !MODE_DEAD_KEY;
                    produced = self.push_text_str(&base.to_string());
                    emitted_dead = true;
                } else {
                    ps!(self).dead_sym = sym; ps!(self).mode_flags |= MODE_DEAD_KEY;
                }
            } else if ps!(self).dead_sym != 0 {
                let dead = ps!(self).dead_sym;
                ps!(self).dead_sym = 0; ps!(self).mode_flags &= !MODE_DEAD_KEY;
                let ctrl = self.key_down(KEY_LEFTCTRL) || self.key_down(KEY_RIGHTCTRL);
                if !ctrl {
                    if let Some(c) = text.chars().next() {
                        let out = keysym::dead_compose(dead, c).unwrap_or(c);
                        produced = self.push_text_str(&out.to_string());
                        emitted_dead = true;
                    }
                }
            }
        }
        if !emitted_dead && ps!(self).dead_sym == 0 {
            let ctrl = self.key_down(KEY_LEFTCTRL) || self.key_down(KEY_RIGHTCTRL)
                || self.key_down(KEY_LEFTMETA) && cfg!(target_os = "macos");
            if ctrl {
                // Layout-aware: the key that PRODUCES c/x/v triggers copy/cut/paste wherever it sits.
                match keysym::to_char(sym).map(|c| c.to_ascii_lowercase()) {
                    Some('c') => self.push_copypaste(CP_COPY),
                    Some('x') => self.push_copypaste(CP_CUT),
                    Some('v') => self.push_copypaste(CP_PASTE),
                    _ => {}
                }
            } else {
                produced = self.push_text_str(text);
            }
        }
        self.key(code, true);
        self.repeat_arm(code, produced, now_ns);
    }

    /// Platforms whose layout engine composes dead keys itself (macOS) report the armed state here.
    pub fn set_dead_flag(&self, armed: bool) {
        if armed { ps!(self).mode_flags |= MODE_DEAD_KEY; } else { ps!(self).mode_flags &= !MODE_DEAD_KEY; }
        ps!(self).dead_sym = 0;
    }

    fn repeat_arm(&self, code: u32, produced: Option<char>, now_ns: u64) {
        let nav = matches!(code, KEY_BACKSPACE | KEY_DELETE | KEY_LEFT | KEY_RIGHT | KEY_UP | KEY_DOWN
                                | KEY_HOME | KEY_END | KEY_PAGEUP | KEY_PAGEDOWN | KEY_TAB | KEY_ENTER);
        if produced.is_none() && !nav { return; }
        if ps!(self).repeat_interval_ns == 0 { return; }
        ps!(self).repeat_code = code;
        ps!(self).repeat_text_len = 0;
        if let Some(c) = produced { ps!(self).repeat_text[0] = c; ps!(self).repeat_text_len = 1; }
        ps!(self).repeat_deadline_ns = now_ns + ps!(self).repeat_delay_ns;
    }

    /// Run after every dispatch pass. Returns the poll timeout in ms (≤100) to wake in time.
    pub fn repeat_tick(&self, now_ns: u64) -> i32 {
        if ps!(self).repeat_code != 0 {
            if !self.key_down(ps!(self).repeat_code) { ps!(self).repeat_code = 0; }
            else if now_ns >= ps!(self).repeat_deadline_ns {
                ps!(self).repeat_deadline_ns = now_ns + ps!(self).repeat_interval_ns;
                if ps!(self).repeat_text_len > 0 {
                    let t: Vec<char> = ps!(self).repeat_text[..ps!(self).repeat_text_len as usize].to_vec();
                    self.push_text(&t);
                } else {
                    let c = ps!(self).repeat_code;
                    self.key_refire(c);
                }
            }
        }
        if ps!(self).repeat_code == 0 { return 100; }
        let left = ps!(self).repeat_deadline_ns.saturating_sub(now_ns);
        ((left / 1_000_000) as i32).clamp(1, 100)
    }
    /// Replace the window icon set. The pump picks it up on its next pass.
    pub fn set_icon(&self, images: Vec<crate::icon::OwnedIcon>) {
        *self.icon.lock().unwrap() = images;
        self.icon_dirty.store(true, Release);
    }
    /// Pump side: take the icon set if it changed since the last call.
    pub fn take_icon(&self) -> Option<Vec<crate::icon::OwnedIcon>> {
        if !self.icon_dirty.swap(false, AcqRel) { return None; }
        Some(self.icon.lock().unwrap().clone())
    }

    pub fn set_repeat(&self, delay_ms: u64, interval_ms: u64) {
        ps!(self).repeat_delay_ns = delay_ms * 1_000_000;
        ps!(self).repeat_interval_ns = interval_ms * 1_000_000;
    }

    // ---- consumer side (app thread only) ----------------------------------------
    /// Copy the next event into `out`; false when the ring is empty.
    pub fn next_event(&self, out: &mut Event) -> bool {
        let tail = self.tail.load(Relaxed);
        if tail == self.head.load(Acquire) { return false; }
        *out = unsafe { *self.ring[(tail as usize) & (RING - 1)].get() };
        self.tail.store(tail + 1, Release);
        true
    }
    pub fn has_events(&self) -> bool { self.tail.load(Relaxed) != self.head.load(Acquire) }

    /// Sleep until an event arrives (futex on the head counter), at most `timeout_ns` (0 = forever).
    pub fn wait(&self, timeout_ns: u64) {
        let seen = self.head_futex.load(Acquire);
        if self.has_events() { return; }
        self.sleeping.store(1, Release);
        #[cfg(all(target_os = "linux", not(cosmo)))]
        if !self.has_events() { crate::sys::futex_wait(&self.head_futex, seen, timeout_ns); }
        #[cfg(not(all(target_os = "linux", not(cosmo))))]
        {
            let g = self.park.0.lock().unwrap();
            if !self.has_events() && self.head_futex.load(Acquire) == seen {
                let d = if timeout_ns == 0 { std::time::Duration::from_secs(3600) } else { std::time::Duration::from_nanos(timeout_ns) };
                let _ = self.park.1.wait_timeout(g, d).unwrap();
            }
        }
        self.sleeping.store(0, Release);
    }
}