uzor-framework 1.5.22

uzor app engine: one kernel of single-writer engines driven by a typed input bus
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
//! Native winit `ApplicationHandler` (design §2.3).
//!
//! The host translates events and executes commands; it never decides
//! routing, layout, or intent delivery — those stay in the runtime.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;

use uzor::RenderBackend;
use uzor_render_hub::{RenderHub, WindowRenderState};
use winit::application::ApplicationHandler;
use winit::event::{DeviceEvent, DeviceId, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::WindowId as WinitWindowId;

use super::clipboard::NativeClipboard;
use super::executor::{self, ExecutorFollowUp};
use super::paint::paint_frame;
use super::screenshot::{capture_screenshot, encode_png};
use super::single_instance::{self, SingleInstanceGuard};
use super::tray::{TrayBuilder, TrayEvent, TrayHandle, TraySpec};
use super::window::NativeWindow;
use super::window_create::{build_hub, create_window, geometry_echo};
use crate::runtime::{Runtime, RuntimeConfig};
use crate::types::bus::{
    HostCaps, HostEvent, InputEnvelope, InputEvent, PointerInput, RenderInfo, WindowInput,
};
use crate::types::error::FrameworkError;
use crate::types::frame::Wake;
use crate::types::ids::{Seconds, WindowId};
use crate::types::window::{RenderCmd, WindowCommand, WindowSpec};
use crate::{App, Spec, Waker};

/// User-event payload that wakes the loop from another thread.
#[derive(Debug, Clone, Copy)]
pub enum HostWake {
    /// A handle dispatch arrived; run a tick.
    Wake,
}

/// Native host: one runtime, a map of OS windows, a render hub.
pub struct NativeHost<S: Spec, A: App<Spec = S>> {
    runtime: Runtime<S, A>,
    windows: HashMap<WinitWindowId, NativeWindow>,
    by_id: HashMap<WindowId, WinitWindowId>,
    hub: RenderHub,
    clipboard: NativeClipboard,
    tray: Option<TrayHandle>,
    tray_spec: Option<TraySpec>,
    /// Pending spawn specs that could not be created yet (before resumed).
    pending: Vec<(WindowId, WindowSpec)>,
    start: Instant,
    /// When true, the next about_to_wait should exit after draining.
    exit: bool,
    /// Cursor locked: device mouse motion becomes RawDelta.
    raw_delta: bool,
}

impl<S: Spec, A: App<Spec = S>> NativeHost<S, A> {
    fn now(&self) -> Seconds {
        Seconds(self.start.elapsed().as_secs_f64())
    }

    fn caps() -> HostCaps {
        HostCaps {
            multi_window: true,
            #[cfg(target_os = "windows")]
            os_resize_bezel: true,
            #[cfg(not(target_os = "windows"))]
            os_resize_bezel: false,
            clipboard_async: false,
        }
    }

    fn push(&mut self, window: WindowId, event: InputEvent) {
        self.runtime.push_input(InputEnvelope {
            window,
            t: self.now(),
            event,
        });
    }

    fn execute_all(&mut self, el: &ActiveEventLoop, cmds: Vec<(WindowId, WindowCommand)>) {
        for (id, cmd) in cmds {
            self.execute_one(el, id, cmd);
        }
    }

    fn execute_one(&mut self, el: &ActiveEventLoop, id: WindowId, cmd: WindowCommand) {
        // Spawn / Exit / clipboard / screenshot / render do not need the
        // window surface first.
        match &cmd {
            WindowCommand::Spawn(spec) => {
                let spec = spec.clone();
                match create_window(el, &self.hub, id, spec) {
                    Ok(nw) => {
                        let (size, dpr, position) = geometry_echo(&nw.window);
                        let wid = nw.winit_id();
                        self.windows.insert(wid, nw);
                        self.by_id.insert(id, wid);
                        self.push(
                            id,
                            InputEvent::Window(WindowInput::Created {
                                size,
                                dpr,
                                position,
                                caps: Self::caps(),
                            }),
                        );
                        // Install tray on first successful window.
                        if self.tray.is_none() {
                            if let Some(spec) = self.tray_spec.take() {
                                match TrayBuilder::from_spec(spec).build() {
                                    Ok(t) => self.tray = Some(t),
                                    Err(e) => log::warn!("tray build failed: {e}"),
                                }
                            }
                        }
                    }
                    Err(e) => log::warn!("spawn window {id:?} failed: {e}"),
                }
                return;
            }
            WindowCommand::ExitApp => {
                self.exit = true;
                el.exit();
                return;
            }
            _ => {}
        }

        let Some(&wid) = self.by_id.get(&id) else {
            log::warn!("execute: unknown window {id:?}");
            return;
        };
        let follow = {
            let Some(nw) = self.windows.get_mut(&wid) else {
                return;
            };
            let mut os = nw.as_os();
            executor::execute(&mut os, cmd)
        };

        let Some(follow) = follow else {
            return;
        };
        match follow {
            ExecutorFollowUp::ClipboardWrite(text) => self.clipboard.write(&text),
            ExecutorFollowUp::ClipboardWriteImage(img) => self.clipboard.write_image(&img),
            ExecutorFollowUp::ClipboardRead(ticket) => {
                let result = self.clipboard.read(ticket);
                // No text: an image paste is the app's (e.g. an attachment chip).
                let image = if result.text.is_none() { self.clipboard.read_image() } else { None };
                self.push(id, InputEvent::Clipboard(result));
                if let Some(img) = image {
                    self.push(id, InputEvent::ClipboardImage(img));
                }
            }
            ExecutorFollowUp::Screenshot(ticket) => self.take_screenshot(id, ticket),
            ExecutorFollowUp::Spawn(spec) => {
                // Unreachable: Spawn handled above. Keep for exhaustiveness.
                let _ = spec;
            }
            ExecutorFollowUp::Close => {
                if let Some(wid) = self.by_id.remove(&id) {
                    self.windows.remove(&wid);
                    self.push(id, InputEvent::Window(WindowInput::Destroyed));
                }
                if self.windows.is_empty() {
                    self.exit = true;
                    el.exit();
                }
            }
            ExecutorFollowUp::ExitApp => {
                self.exit = true;
                el.exit();
            }
            ExecutorFollowUp::Render(cmd) => self.apply_render(cmd),
            ExecutorFollowUp::OuterRectEcho { position, size } => {
                self.push(
                    id,
                    InputEvent::Window(WindowInput::OuterRect { position, size }),
                );
            }
        }
    }

    fn apply_render(&mut self, cmd: RenderCmd) {
        match cmd {
            RenderCmd::SetBackend(b) => {
                if let Err(e) = self.hub.set_active(b) {
                    log::warn!("set_backend failed: {e}");
                }
            }
            RenderCmd::SetFpsLimit(fps) => self.hub.set_fps_limit(fps),
            RenderCmd::SetMsaa(n) => self.hub.set_msaa(n),
            RenderCmd::SetVsync(on) => self.hub.set_vsync(on),
        }
    }

    fn take_screenshot(&mut self, id: WindowId, ticket: crate::types::ids::Ticket) {
        let Some(&wid) = self.by_id.get(&id) else {
            return;
        };
        let Some(nw) = self.windows.get_mut(&wid) else {
            return;
        };
        let Some((device, queue, surface)) = nw.render_state.gpu_handles() else {
            log::warn!("screenshot: no GPU surface for {id:?}");
            return;
        };
        let Some((pixels, w, h)) = capture_screenshot(device, queue, surface, None) else {
            return;
        };
        let Some(png) = encode_png(&pixels, w, h) else {
            return;
        };
        self.push(
            id,
            InputEvent::Host(HostEvent::Screenshot {
                ticket,
                png: Arc::<[u8]>::from(png),
            }),
        );
    }

    fn drain_tray(&mut self) {
        let mut events = Vec::new();
        if let Some(tray) = self.tray.as_ref() {
            while let Some(ev) = tray.next_event() {
                events.push(ev);
            }
        }
        for ev in events {
            if let TrayEvent::MenuClick(id) = ev {
                // Tray has no window; attach to the first open window.
                if let Some((&win, _)) = self.by_id.iter().next() {
                    self.push(win, InputEvent::Host(HostEvent::Tray { id }));
                }
            }
        }
    }

    fn paint_due(&mut self, frames: Vec<crate::types::frame::FrameRequest>) {
        for req in frames {
            let Some(&wid) = self.by_id.get(&req.window) else {
                continue;
            };
            // Split borrows: take the window entry, paint, put metrics back.
            let Some(mut nw) = self.windows.remove(&wid) else {
                continue;
            };
            // A transparent window clears to alpha 0 so what the app leaves
            // unpainted (rounded corners) shows the desktop.
            let mut req = req;
            if nw.transparent {
                req.background = 0;
            }
            if let Err(e) = paint_frame(&mut self.runtime, &mut self.hub, &mut nw.render_state, &req)
            {
                log::warn!("paint failed: {e}");
            }
            flush_x11(&nw.window);
            if std::env::var_os("UZOR_TRACE_PAINT").is_some() {
                eprintln!("[paint] {:?} t={:.3}", req.window, self.now().get());
            }
            // Report render facts.
            let m = *self.hub.metrics();
            let info = RenderInfo {
                backend: Some(self.hub.active()),
                available: self.hub.available_backends(),
                fps_ema: 0.0,
                frame_ms: m.submit_us as f64 / 1000.0,
                frame_count: 0,
            };
            self.windows.insert(wid, nw);
            self.push(req.window, InputEvent::Host(HostEvent::RenderInfo(info)));
        }
    }
}

impl<S: Spec, A: App<Spec = S>> ApplicationHandler<HostWake> for NativeHost<S, A> {
    fn resumed(&mut self, el: &ActiveEventLoop) {
        let pending = std::mem::take(&mut self.pending);
        for (id, spec) in pending {
            self.execute_one(el, id, WindowCommand::Spawn(spec));
        }
    }

    fn window_event(&mut self, el: &ActiveEventLoop, id: WinitWindowId, ev: WindowEvent) {
        let Some(nw) = self.windows.get_mut(&id) else {
            return;
        };
        let framework_id = nw.id;

        // Scale factor: update mapper and emit a real Resized with current size.
        if let WindowEvent::ScaleFactorChanged { scale_factor, .. } = &ev {
            let _ = nw.mapper.map(&ev);
            let (size, _, _) = geometry_echo(&nw.window);
            self.push(
                framework_id,
                InputEvent::Window(WindowInput::Resized {
                    size,
                    dpr: *scale_factor,
                }),
            );
            return;
        }

        // Resize: the surface (GPU swapchain / software presenter pixmap) follows the
        // window, otherwise frames keep presenting at the creation size (only the
        // top-left part drawn after maximize) and a shrink can stall presents.
        if let WindowEvent::Resized(size) = &ev {
            resize_render_surface(&mut nw.render_state, size.width, size.height);
            nw.window.request_redraw();
            // The OS (WM, double-click, Win+Up) can maximize too: echo the state
            // so a restore toggle reads the truth.
            let maximized = nw.window.is_maximized();
            if nw.maximized != Some(maximized) {
                nw.maximized = Some(maximized);
                self.push(framework_id, InputEvent::Window(WindowInput::Maximized(maximized)));
            }
            // `self.windows` borrow ended by push; re-fetch below.
            let Some(nw) = self.windows.get_mut(&id) else {
                return;
            };
            let events = nw.mapper.map(&ev);
            for e in events {
                self.push(framework_id, e);
            }
            return;
        }

        if matches!(ev, WindowEvent::RedrawRequested) {
            // Force an immediate tick+paint for this window by waking.
            // about_to_wait does the real work; request a poll.
            el.set_control_flow(ControlFlow::Poll);
            return;
        }

        // OS file drag: the pointer is grabbed by the drag source, so no
        // CursorMoved arrives; query it so drops (and the hover) target the
        // widget under the pointer.
        match &ev {
            WindowEvent::HoveredFile(_) | WindowEvent::DroppedFile(_) => {
                if let Some(p) = query_pointer(&nw.window) {
                    nw.dnd_hover = matches!(ev, WindowEvent::HoveredFile(_)).then_some(p);
                    let pos = crate::Point::new(p.0, p.1);
                    self.push(framework_id, InputEvent::Pointer(PointerInput::Moved { pos, mods: Default::default() }));
                } else {
                    nw.dnd_hover = None;
                }
            }
            WindowEvent::HoveredFileCancelled => nw.dnd_hover = None,
            _ => {}
        }
        let Some(nw) = self.windows.get_mut(&id) else {
            return;
        };
        let events = nw.mapper.map(&ev);
        for e in events {
            self.push(framework_id, e);
        }
    }

    fn device_event(&mut self, _el: &ActiveEventLoop, _id: DeviceId, event: DeviceEvent) {
        if !self.raw_delta {
            return;
        }
        if let DeviceEvent::MouseMotion { delta } = event {
            if let Some((&win, _)) = self.by_id.iter().next() {
                self.push(
                    win,
                    InputEvent::Pointer(PointerInput::RawDelta {
                        dx: delta.0,
                        dy: delta.1,
                    }),
                );
            }
        }
    }

    fn user_event(&mut self, _el: &ActiveEventLoop, _event: HostWake) {
        // about_to_wait will tick; nothing else to do.
    }

    fn about_to_wait(&mut self, el: &ActiveEventLoop) {
        self.drain_tray();
        let (moved, dnd) = dnd_moves(self.windows.values_mut());
        for (id, p) in moved {
            self.push(id, InputEvent::Pointer(PointerInput::Moved { pos: crate::Point::new(p.0, p.1), mods: Default::default() }));
        }
        let out = self.runtime.tick(self.now());
        // Windows already open had their Created delivered by this tick, so
        // the icon command is in `out`. A spawn inside execute_all is not
        // in this list: its button waits until the next tick.
        let mut reveal = Vec::new();
        for (wid, nw) in &mut self.windows {
            if nw.defer_show {
                nw.defer_show = false;
                reveal.push(*wid);
            }
        }
        self.execute_all(el, out.window_commands);
        for wid in reveal {
            if let Some(nw) = self.windows.get(&wid) {
                nw.window.set_visible(true);
            }
        }
        if std::env::var_os("UZOR_TRACE_PAINT").is_some() {
            eprintln!("[tick] frames {} wake {:?}", out.frames.len(), out.wake);
        }
        self.paint_due(out.frames);

        if self.exit || self.runtime.should_exit() {
            el.exit();
            return;
        }

        // A paint that asked for another frame (or declared commands) must not
        // park the loop on the pre-paint wake.
        let wake = if self.runtime.take_paint_wants_tick() { Wake::Immediate } else { out.wake };
        el.set_control_flow(match wake {
            Wake::Idle => ControlFlow::Wait,
            Wake::Immediate => ControlFlow::Poll,
            Wake::At(t) => {
                let now = self.now().get();
                let target = t.get();
                if target <= now {
                    ControlFlow::Poll
                } else {
                    let dur = std::time::Duration::from_secs_f64(target - now);
                    ControlFlow::WaitUntil(Instant::now() + dur)
                }
            }
        });
        if dnd && !matches!(wake, Wake::Immediate) {
            el.set_control_flow(ControlFlow::WaitUntil(Instant::now() + std::time::Duration::from_millis(40)));
        }
    }
}

/// While a file drag hovers a window, follow the pointer (X11 DnD sends no
/// motion to the target window): moved windows, and whether any drag is active.
fn dnd_moves<'a>(windows: impl Iterator<Item = &'a mut super::window::NativeWindow>) -> (Vec<(crate::WindowId, (f64, f64))>, bool) {
    let mut moved = Vec::new();
    let mut any = false;
    for nw in windows {
        let Some(last) = nw.dnd_hover else { continue };
        any = true;
        if let Some(p) = query_pointer(&nw.window) {
            if p != last {
                nw.dnd_hover = Some(p);
                moved.push((nw.id, p));
            }
        }
    }
    (moved, any)
}

/// Pointer position in the window's logical px (X11 XQueryPointer), if available.
#[cfg(all(unix, not(target_os = "macos")))]
fn query_pointer(window: &winit::window::Window) -> Option<(f64, f64)> {
    use std::sync::OnceLock;
    use winit::raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle};
    static XLIB: OnceLock<Option<x11_dl::xlib::Xlib>> = OnceLock::new();
    let xlib = XLIB.get_or_init(|| x11_dl::xlib::Xlib::open().ok()).as_ref()?;
    let RawDisplayHandle::Xlib(dh) = window.display_handle().ok()?.as_raw() else { return None };
    let d = dh.display?.as_ptr().cast();
    let win = match window.window_handle().ok()?.as_raw() {
        RawWindowHandle::Xlib(w) => w.window,
        RawWindowHandle::Xcb(w) => w.window.get() as _,
        _ => return None,
    };
    let (mut root, mut child) = (0, 0);
    let (mut rx, mut ry, mut wx, mut wy, mut mask) = (0, 0, 0, 0, 0);
    // SAFETY: winit's live display + window; XQueryPointer only reads.
    let ok = unsafe { (xlib.XQueryPointer)(d, win, &mut root, &mut child, &mut rx, &mut ry, &mut wx, &mut wy, &mut mask) };
    if ok == 0 {
        return None;
    }
    let k = window.scale_factor();
    Some((wx as f64 / k, wy as f64 / k))
}

#[cfg(not(all(unix, not(target_os = "macos"))))]
fn query_pointer(_window: &winit::window::Window) -> Option<(f64, f64)> {
    None
}

/// Prefer a fixed backend when set; otherwise autodetection.
#[derive(Clone, Copy, Debug, Default)]
pub struct RenderPreference {
    /// Explicit backend, or `None` for autodetection.
    pub backend: Option<RenderBackend>,
}

/// Extra native-only startup options (design §6.1).
#[derive(Clone, Debug, Default)]
pub struct NativeOptions {
    /// Optional single-instance mutex name.
    pub single_instance: Option<String>,
    /// Optional system tray.
    pub tray: Option<TraySpec>,
    /// Render backend preference.
    pub render: RenderPreference,
}

/// Run the app on the native host (feature `native`).
pub fn run_native<S, A>(
    app: A,
    cfg: RuntimeConfig,
    native: NativeOptions,
) -> Result<(), FrameworkError>
where
    S: Spec,
    A: App<Spec = S>,
{
    let _guard: Option<SingleInstanceGuard> = native
        .single_instance
        .as_deref()
        .map(single_instance::single_instance);

    let event_loop = EventLoop::<HostWake>::with_user_event()
        .build()
        .map_err(|e| FrameworkError::Host(format!("event loop: {e}")))?;
    let proxy = event_loop.create_proxy();
    let waker = Waker::new(move || {
        let _ = proxy.send_event(HostWake::Wake);
    });

    let (runtime, _handle) = Runtime::new(app, cfg, waker);
    let hub = build_hub(native.render.backend);

    let mut host = NativeHost {
        runtime,
        windows: HashMap::new(),
        by_id: HashMap::new(),
        hub,
        clipboard: NativeClipboard::new(),
        tray: None,
        tray_spec: native.tray,
        pending: Vec::new(),
        start: Instant::now(),
        exit: false,
        raw_delta: false,
    };

    // The first tick drains Open commands into Spawn follow-ups. Run it
    // before the loop so resumed() can create the windows.
    let out = host.runtime.tick(host.now());
    for (id, cmd) in out.window_commands {
        if let WindowCommand::Spawn(spec) = cmd {
            host.pending.push((id, spec));
        }
    }

    event_loop
        .run_app(&mut host)
        .map_err(|e| FrameworkError::Host(format!("event loop run: {e}")))?;
    Ok(())
}

/// Convenience: run with default native options.
pub fn run_native_default<S, A>(app: A, cfg: RuntimeConfig) -> Result<(), FrameworkError>
where
    S: Spec,
    A: App<Spec = S>,
{
    run_native(app, cfg, NativeOptions::default())
}

/// Resize a window's render surface to the new physical size (no-op for 0×0,
/// which winit reports for a minimized window).
pub(crate) fn resize_render_surface(rs: &mut WindowRenderState, width: u32, height: u32) {
    if width == 0 || height == 0 {
        return;
    }
    rs.resize_surface(width, height);
}

/// Flushes the window's Xlib connection after a present. softbuffer's X11
/// path writes `shm::PutImage` plus a `GetInputFocus` completion probe into
/// the shared Xlib/XCB output buffer without flushing it, so the frame (and
/// the probe the next present waits on) sat in the buffer until some other
/// traffic flushed it: the last frame after a state change stayed unseen
/// until the mouse moved.
#[cfg(all(unix, not(target_os = "macos")))]
fn flush_x11(window: &winit::window::Window) {
    use std::sync::OnceLock;
    use winit::raw_window_handle::{HasDisplayHandle, RawDisplayHandle};
    static XLIB: OnceLock<Option<x11_dl::xlib::Xlib>> = OnceLock::new();
    let Ok(h) = window.display_handle() else { return };
    if let RawDisplayHandle::Xlib(x) = h.as_raw() {
        if let (Some(d), Some(xlib)) = (x.display, XLIB.get_or_init(|| x11_dl::xlib::Xlib::open().ok())) {
            // SAFETY: winit's live display pointer; XFlush only writes the buffer out.
            unsafe { (xlib.XFlush)(d.as_ptr().cast()) };
        }
    }
}

#[cfg(not(all(unix, not(target_os = "macos"))))]
fn flush_x11(_window: &winit::window::Window) {}