kui-core 0.1.0-alpha.34

kui contract: flat per-frame tree, clay-style flex layout, text stack, events as data, quad display list
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
//! Windows as data. A node can declare a chrome role (drag handle,
//! close/minimize/maximize button); interacting with it produces
//! [`WindowCommand`]s that the frame driver drains and applies to the real
//! window. A frame can declare that a *window exists* (`Core::declare_window`,
//! `docs/adr/0004-multi-window.md`): the core diffs the declared set and the
//! same queue carries the [`WindowCommand::Open`] / [`WindowCommand::Close`]
//! the diff produces. A declared window is a [`WindowKind::Normal`] one or
//! a [`WindowKind::Popup`] — borderless, owned, anchored, non-activating —
//! and a driver reports a popup dismissed the way it reports one closed
//! ([`DismissReason`]). Host window facts flow back in through [`WindowEnv`]
//! on `Env`. The core never touches a window — headless drivers just never
//! drain.

use crate::geom::{Rect, Size};
use crate::tree::OriginId;

/// Which OS window something belongs to: an opaque integer the core's
/// declaration diff assigns when it opens a window, not a handle an app
/// builds. [`WindowId::MAIN`] is 0 — the window the launcher opens, which is
/// always live. Apps name windows with a stable string
/// (`Core::declare_window`); the id is how the driver and the events refer
/// to the surface that string opened.
///
/// It crosses every transport as a plain integer — `UiEvent::window` in
/// Rust, `window` on a JSX `UiEvent`, `KuiEvent.window` in C — so nothing
/// has to model window identity twice.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct WindowId(pub u32);

impl WindowId {
    /// The window the app starts in, and the answer everywhere until a
    /// driver opens a second one.
    pub const MAIN: WindowId = WindowId(0);
}

/// Role a node plays in window chrome (set via `NodeSpec::window_drag` /
/// `NodeSpec::window_button`). Chrome nodes never emit `UiEvent`s — their
/// interactions become [`WindowCommand`]s for the driver instead.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WindowRole {
    /// Mouse-down here asks the driver to start an OS window drag (drivers
    /// conventionally promote a quick second press to a maximize toggle).
    Drag,
    /// Clicking here emits the button's window command.
    Button(WindowButton),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WindowButton {
    Close,
    Minimize,
    Maximize,
}

impl WindowButton {
    /// The command a click on this button issues, for the window the
    /// button was drawn in.
    pub fn command(self, window: WindowId) -> WindowCommand {
        match self {
            WindowButton::Close => WindowCommand::Close(window),
            WindowButton::Minimize => WindowCommand::Minimize(window),
            WindowButton::Maximize => WindowCommand::ToggleMaximize(window),
        }
    }
}

/// What kind of OS surface a declared window is
/// (`docs/adr/0004-multi-window.md`, decision 9).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WindowKind {
    /// A regular top-level window with the launcher's chrome.
    #[default]
    Normal,
    /// A menu surface: borderless, absent from the taskbar, owned by the
    /// window that declared it and closed when that window closes, placed
    /// in screen coordinates against [`WindowConfig::anchor`] rather than
    /// clamped into a viewport, and **non-activating** by default — it
    /// must not take OS focus, or opening a combobox would blur the field
    /// that opened it. While a non-activating popup is up the driver
    /// routes its owner's keyboard input to it and the owner's
    /// `env.focused` stays true, so the field still draws focused while
    /// the arrow keys walk the list.
    ///
    /// Reach for it only for the three placements a float cannot make: a
    /// list taller than the window, a menu near an edge with nowhere
    /// in-window to go, and a panel the user wants beside the app.
    /// Everything else is cheaper as a float — see
    /// [`crate::spec::FloatConfig::fit`] — because a float costs one tree
    /// and one draw call where this costs an OS surface, a swapchain, a
    /// `Core` and an accessibility adapter.
    Popup,
}

impl WindowKind {
    /// Every kind, in wire order: the index a binding that spells kinds
    /// as numbers sends. Append-only.
    pub const ALL: [WindowKind; 2] = [WindowKind::Normal, WindowKind::Popup];

    /// The wire name, for the bindings and the report.
    pub fn name(self) -> &'static str {
        match self {
            WindowKind::Normal => "normal",
            WindowKind::Popup => "popup",
        }
    }

    /// The kind a wire name spells: the inverse of [`Self::name`].
    pub fn from_name(name: &str) -> Option<WindowKind> {
        Self::ALL.into_iter().find(|k| k.name() == name)
    }
}

/// What a frame says about a window it declares (`Core::declare_window`).
/// Plain data by ADR 0004 decision 5 — no title, no callbacks — so a
/// `WindowCommand` stays `Copy` and equality is derived, which is how the
/// diff tells two declarations of one name apart.
///
/// **Read on the opening edge only.** The config that reaches
/// [`WindowCommand::Open`] is the one the declaration carried on the frame
/// it started; a live window's config is never looked at again, so
/// re-declaring `"palette"` at a new size does not resize it. The user owns
/// a window's geometry once it exists.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WindowConfig {
    pub kind: WindowKind,
    /// Initial inner size, logical px.
    pub size: Size,
    /// Whether opening it takes OS focus. True for a normal window;
    /// [`WindowConfig::popup`] turns it off, so the field that opened a
    /// dropdown keeps the ring while the list is up.
    pub activates: bool,
    /// [`WindowKind::Popup`] only: what the popup is placed against, as a
    /// rect in the **declaring window's** logical viewport coordinates —
    /// which is exactly the rect an `onLayout` node reports, so an app
    /// needs no new geometry query to fill it. The driver resolves it to
    /// screen coordinates against the owner's own position and puts the
    /// popup below it, flipping above when the display's bottom edge is
    /// nearer than the popup is tall.
    ///
    /// Read on the opening edge with the rest of the config and never
    /// again: a popup that has to follow a moving anchor stops being
    /// declared and is declared again, which is what a dropdown does when
    /// its field scrolls away anyway. Ignored by a `Normal` window.
    pub anchor: Rect,
}

impl WindowConfig {
    /// `{kind, width, height, activates, anchor: {x, y, w, h}}`.
    pub fn to_value(&self) -> crate::value::Value {
        use crate::value::Value;
        Value::map([
            ("kind", Value::str(self.kind.name())),
            ("width", Value::float(self.size.w)),
            ("height", Value::float(self.size.h)),
            ("activates", Value::Bool(self.activates)),
            ("anchor", self.anchor.to_value()),
        ])
    }

    /// The size a declaration that names none gets.
    pub const DEFAULT_SIZE: Size = Size { w: 640.0, h: 480.0 };

    /// A normal, activating window of `w` x `h` logical px.
    pub fn sized(w: f32, h: f32) -> Self {
        Self {
            size: Size::new(w, h),
            ..Self::default()
        }
    }

    /// A [`WindowKind::Popup`] of `w` x `h` logical px placed against
    /// `anchor` — the rect, in the declaring window's viewport
    /// coordinates, that an `onLayout` handler reported for the field or
    /// button the menu belongs to.
    ///
    /// Non-activating, which is the default a popup wants and the reason
    /// this is a constructor rather than a `kind` you set: a popup that
    /// takes OS focus blurs whatever opened it. Set `activates` back to
    /// true afterwards for the rare surface that should steal focus.
    pub fn popup(anchor: Rect, w: f32, h: f32) -> Self {
        Self {
            size: Size::new(w, h),
            anchor,
            ..Self::of_kind(WindowKind::Popup)
        }
    }

    /// The defaults for a window of `kind`: the one decision the kind
    /// makes on its own is whether opening it takes OS focus — a popup
    /// that did would blur the field that opened it, so it does not unless
    /// asked. Every binding's window entry starts from this.
    pub fn of_kind(kind: WindowKind) -> Self {
        Self {
            kind,
            activates: kind == WindowKind::Normal,
            ..Self::default()
        }
    }

    /// A declaration from plain data: a bare name (the defaults), or a map
    /// with `name`, `kind` (`"normal"` | `"popup"`), `width` and `height`
    /// (both and positive, or the default size), `activates`, and the `anchor` rect
    /// (`{x, y, w, h}`) a popup is placed against. Returns the name with
    /// the config. An entry is plain data with a fixed shape, not a node's
    /// loose prop bag, so a value that does nothing is refused rather than
    /// dropped: a kind kui does not have would otherwise open a normal
    /// window and read as the popup having worked.
    pub fn from_value(v: &crate::value::Value) -> Result<(String, Self), String> {
        use crate::value::Value;
        match v {
            Value::Str(name) => Ok((name.clone(), Self::default())),
            Value::Map(_) => {
                let name = v
                    .get_str("name")
                    .ok_or("a windows entry needs a name")?
                    .to_string();
                let kind = match v.get_str("kind") {
                    None => WindowKind::Normal,
                    Some(k) => WindowKind::from_name(k).ok_or_else(|| {
                        format!(
                            "windows entry `{name}` has kind {k:?}; the kinds are {}",
                            WindowKind::ALL
                                .iter()
                                .map(|k| format!("{:?}", k.name()))
                                .collect::<Vec<_>>()
                                .join(" and ")
                        )
                    })?,
                };
                let mut cfg = Self::of_kind(kind);
                let num = |key: &str| v.get(key).and_then(Value::as_float).map(|n| n as f32);
                // Both, and positive: a zero is the default size, as C's
                // `kui_window_declare` reads it and the runner opens it —
                // Node's own decoder said so and this did not (AR43).
                if let (Some(w), Some(h)) = (num("width"), num("height"))
                    && w > 0.0
                    && h > 0.0
                {
                    cfg.size = Size::new(w, h);
                }
                if let Some(a) = v.get_bool("activates") {
                    cfg.activates = a;
                }
                if let Some(a) = v.get("anchor") {
                    let f = |key: &str| a.get(key).and_then(Value::as_float).unwrap_or(0.0) as f32;
                    cfg.anchor = Rect::new(f("x"), f("y"), f("w"), f("h"));
                }
                Ok((name, cfg))
            }
            other => Err(format!(
                "a windows entry is a name or a table, not {}",
                other.type_name()
            )),
        }
    }
}

impl Default for WindowConfig {
    fn default() -> Self {
        Self {
            kind: WindowKind::Normal,
            size: Self::DEFAULT_SIZE,
            activates: true,
            anchor: Rect::new(0.0, 0.0, 0.0, 0.0),
        }
    }
}

/// A window-level intent for the frame driver, drained via
/// `Core::take_window_commands` after each input dispatch and each frame.
/// Three things produce one: input on a chrome node, the declared set's
/// diff, and an app asking directly (`Core::set_window_size`,
/// `Core::focus_window`, `Core::push_window_command`). A headless driver
/// never drains, which is the whole of "the core never touches a window".
///
/// Every variant says which window it is about, and every variant is
/// `Copy` and pointer-free — an `Open` carries no title (the new window's
/// own first frame declares one through `window_title`) and a `SetSize`
/// carries two floats — so nothing borrowed ever enters a driver's drain
/// loop.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WindowCommand {
    /// Begin an interactive OS move (the press landed on a `Drag` node).
    StartDrag(WindowId),
    /// Close this window: from its chrome close button, or because no
    /// frame declares it any more. For the main window a driver exits.
    Close(WindowId),
    Minimize(WindowId),
    ToggleMaximize(WindowId),
    /// Open a window the declared set gained. `id` is the one the core
    /// assigned and will stamp on the window's events; `origin` is the
    /// frontend whose declaration won (a host may refuse an extension's);
    /// `owner` is the window whose frame that declaration came from — what
    /// a [`WindowKind::Popup`] is anchored against and owned by, and what
    /// closing takes the popup with it (the owner's declarations leave the
    /// declared set when the owner does, so the diff closes the child in
    /// the same pass).
    Open {
        id: WindowId,
        owner: WindowId,
        origin: OriginId,
        config: WindowConfig,
    },
    /// Resize `window` to `size` (logical px), asked for by the app
    /// (`Core::set_window_size`). A command and not part of a declaration,
    /// because the user owns a window's size once it exists — a declared
    /// size would fight every drag of the window's edge, which is why
    /// `WindowConfig::size` is read on the opening edge only. The OS may
    /// answer with a different size (a minimum, a tiling manager); the
    /// frame that follows posts a `resize` event with whatever it actually
    /// became, the way every resize already does.
    SetSize {
        window: WindowId,
        size: Size,
    },
    /// Give `window` keyboard focus (`Core::focus_window`). Advisory, like
    /// every focus request an app makes of a window manager.
    Focus(WindowId),
    /// Draw `window` again: something another window's frame or input
    /// changed is shown there (`docs/adr/0024`, decision 7 — the devtools
    /// window's row hover outlines a node in the main window, and an event
    /// the main window logs moves the stream in the devtools window). A
    /// driver that redraws every window on every event may ignore it.
    Redraw(WindowId),
}

impl WindowCommand {
    /// The command's wire name: `startDrag`, `close`, `minimize`,
    /// `toggleMaximize`, `open`, `setSize`, `focus`, `redraw`.
    pub fn kind_name(&self) -> &'static str {
        match self {
            WindowCommand::StartDrag(_) => "startDrag",
            WindowCommand::Close(_) => "close",
            WindowCommand::Minimize(_) => "minimize",
            WindowCommand::ToggleMaximize(_) => "toggleMaximize",
            WindowCommand::Open { .. } => "open",
            WindowCommand::SetSize { .. } => "setSize",
            WindowCommand::Focus(_) => "focus",
            WindowCommand::Redraw(_) => "redraw",
        }
    }

    /// `{kind, window}` plus what the variant carries: `width`/`height`
    /// for `setSize`; `owner`, `origin` and `config` for `open`.
    pub fn to_value(&self) -> crate::value::Value {
        use crate::value::Value;
        let mut out = vec![
            ("kind".to_string(), Value::str(self.kind_name())),
            ("window".to_string(), Value::Int(self.window().0 as i64)),
        ];
        match self {
            WindowCommand::SetSize { size, .. } => {
                out.push(("width".into(), Value::float(size.w)));
                out.push(("height".into(), Value::float(size.h)));
            }
            WindowCommand::Open {
                owner,
                origin,
                config,
                ..
            } => {
                out.push(("owner".into(), Value::Int(owner.0 as i64)));
                out.push(("origin".into(), Value::Int(origin.0 as i64)));
                out.push(("config".into(), config.to_value()));
            }
            _ => {}
        }
        Value::Map(out)
    }

    /// The window the command is about.
    pub fn window(&self) -> WindowId {
        match *self {
            WindowCommand::StartDrag(w)
            | WindowCommand::Close(w)
            | WindowCommand::Minimize(w)
            | WindowCommand::ToggleMaximize(w)
            | WindowCommand::Focus(w)
            | WindowCommand::Redraw(w) => w,
            WindowCommand::Open { id, .. } => id,
            WindowCommand::SetSize { window, .. } => window,
        }
    }
}

/// Why a window was asked to go away (`Core::dismiss_window`): the same
/// two reasons ADR 0003 gave a modal node, one level up.
///
/// A [`WindowKind::Popup`] is dismissed by the driver, because both facts
/// are the OS's and not the frame's: a press outside a window lands in
/// another surface, and Escape reaches a non-activating popup only through
/// whichever window the OS gave the keyboard to. What the core does with
/// either is what ADR 0003 decided — raise `{kind:"dismiss", reason}` and
/// close nothing. The app stops declaring the window on the frame it
/// decides to, so a dropdown that graduates from a `modal` float to a
/// popup window changes its declaration and not its handler.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DismissReason {
    /// A press landed outside the window.
    Outside,
    /// Escape, wherever the OS delivered it.
    Escape,
}

impl DismissReason {
    /// The string the `dismiss` payload carries, the same spelling a
    /// modal's `reason` uses.
    pub fn as_str(self) -> &'static str {
        match self {
            DismissReason::Outside => "outside",
            DismissReason::Escape => "escape",
        }
    }
}

/// What the host knows about its window, pushed into `Env` by the frame
/// driver. Views (e.g. `widgets::titlebar`) read this to adapt: reserve
/// space for native controls, pick the maximize/restore glyph, or render
/// nothing at all under native decorations.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct WindowEnv {
    /// Which window this core is drawing: the id the `Open` that created
    /// it carried, written here by the driver (`MAIN` for the launcher's).
    /// A view reads it here rather than through a query, and it is what the
    /// core stamps onto every `UiEvent` it hands out — so a driver that
    /// pushes the rest of these facts has already said where its events
    /// came from. The window's *name* is `Core::window_name`.
    pub id: WindowId,
    /// The host asked the app to draw its own chrome (no native titlebar).
    pub custom_chrome: bool,
    pub maximized: bool,
    pub fullscreen: bool,
    /// The window is above every other app's: the level the driver set
    /// after the frame asked (`Core::set_always_on_top`, backlog C30), on
    /// a platform that has one — where winit has no call for it (Wayland)
    /// a driver reports false however often the app asks, which is what
    /// a pin button draws its state from. It is the driver's record of
    /// what it set and not a query: winit has no level getter, so a level
    /// the OS dropped afterwards (a fullscreen space, a tiling manager)
    /// is not seen here (backlog AR49 names the gap).
    pub always_on_top: bool,
    /// Area (logical px, window coords) covered by controls the OS still
    /// draws over our content — macOS traffic lights under custom chrome.
    /// Views keep out of it; `None` means the OS draws nothing over us.
    pub native_controls: Option<Rect>,
}