serge-native 0.1.1

Native runtime of serge: retained view tree, layout, scene collection, input and UI tasks
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
//! The retained node tree native targets mount `Element`s into. Reactive
//! properties are effects that write into nodes and ask for a frame;
//! regions and keyed lists are layout-transparent groups whose children are
//! rebuilt or reordered.

use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use hyve::state::{Signal, effect, on_cleanup, signal, untrack};
use serge_core::paint::track_frame_sources;
use serge_core::{
    Attr, AttrValue, Cursor, FrameSource, Handler, Kind, Node, PaintCmd, PaintCtx, Prop, Rect,
    View, Widget,
};
use serge_style::{Style, Theme};

/// What a node is.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum NKind {
    /// The window's root.
    Root,
    /// A layout-transparent group (fragment, region, keyed list, item).
    Group,
    /// A built-in widget.
    Widget(Kind),
}

pub(crate) struct CanvasState {
    pub bounds: Signal<Rect>,
    pub tick: Signal<u64>,
    pub commands: Vec<PaintCmd>,
    pub sources: Vec<(FrameSource, u64)>,
}

pub(crate) struct NNode {
    pub access_id: accesskit::NodeId,
    pub kind: NKind,
    pub style: Style,
    pub attrs: Vec<(Attr, AttrValue)>,
    pub handlers: Vec<Handler>,
    pub cursor: Option<Cursor>,
    pub children: Vec<usize>,
    pub parent: Option<usize>,
    /// Border box in content coordinates (before scrolling).
    pub rect: Rect,
    pub view: View,
    /// An input's text.
    pub input: String,
    pub viewport: Option<serge_core::viewport::Slot>,
    pub canvas: Option<CanvasState>,
}

impl NNode {
    pub fn focusable(&self) -> bool {
        if self.viewport.is_some() {
            return true;
        }
        matches!(
            self.kind,
            NKind::Widget(Kind::Button | Kind::Slider | Kind::Input | Kind::Checkbox | Kind::Link)
        ) && !self.flag(Attr::Disabled)
    }

    pub fn attr(&self, a: Attr) -> Option<&AttrValue> {
        self.attrs.iter().find(|(k, _)| *k == a).map(|(_, v)| v)
    }

    pub fn text(&self) -> &str {
        self.attr(Attr::Text).map_or("", AttrValue::as_str)
    }

    pub fn num(&self, a: Attr, default: f32) -> f32 {
        self.attr(a).map_or(default, AttrValue::as_num)
    }

    pub fn flag(&self, a: Attr) -> bool {
        self.attr(a).is_some_and(AttrValue::as_bool)
    }

    fn set_attr(&mut self, a: Attr, v: AttrValue) {
        if a == Attr::InputText {
            self.input = v.as_str().to_owned();
        }
        match self.attrs.iter_mut().find(|(k, _)| *k == a) {
            Some(slot) => slot.1 = v,
            None => self.attrs.push((a, v)),
        }
    }
}

/// Mutable UI state behind the tree.
pub(crate) struct Tree {
    pub nodes: Vec<Option<NNode>>,
    free: Vec<usize>,
    next_access_id: u64,
    pub root: usize,
    pub dirty: bool,
    pub layout_dirty: bool,
    pub focus: Option<usize>,
    pub hover: Option<usize>,
    pub pressed: Option<usize>,
    pub drag: Option<usize>,
    pub scroll_y: f32,
    pub content_height: f32,
    pub size: (f32, f32),
    pub scale: f32,
    pub origin: (f32, f32),
}

impl Tree {
    pub fn new(root_view: View) -> Tree {
        let mut t = Tree {
            nodes: Vec::new(),
            free: Vec::new(),
            next_access_id: 1,
            root: 0,
            dirty: true,
            layout_dirty: true,
            focus: None,
            hover: None,
            pressed: None,
            drag: None,
            scroll_y: 0.0,
            content_height: 0.0,
            size: (0.0, 0.0),
            scale: 1.0,
            origin: (0.0, 0.0),
        };
        t.root = t.alloc(NKind::Root, None, root_view);
        t
    }

    pub fn node(&self, id: usize) -> Option<&NNode> {
        self.nodes.get(id).and_then(Option::as_ref)
    }

    pub fn node_mut(&mut self, id: usize) -> Option<&mut NNode> {
        self.nodes.get_mut(id).and_then(Option::as_mut)
    }

    fn alloc(&mut self, kind: NKind, parent: Option<usize>, view: View) -> usize {
        let access_id = accesskit::NodeId(self.next_access_id);
        self.next_access_id = self
            .next_access_id
            .checked_add(1)
            .expect("native accessibility IDs exhausted");
        let node = NNode {
            access_id,
            kind,
            style: Style::default(),
            attrs: Vec::new(),
            handlers: Vec::new(),
            cursor: None,
            children: Vec::new(),
            parent,
            rect: Rect::default(),
            view,
            input: String::new(),
            canvas: None,
            viewport: None,
        };
        let id = match self.free.pop() {
            Some(id) => {
                self.nodes[id] = Some(node);
                id
            }
            None => {
                self.nodes.push(Some(node));
                self.nodes.len() - 1
            }
        };
        if let Some(p) = parent.and_then(|p| self.node_mut(p)) {
            p.children.push(id);
        }
        self.layout_dirty = true;
        self.dirty = true;
        id
    }

    /// Removes `id` and its subtree.
    pub fn remove(&mut self, id: usize) {
        let Some(node) = self.nodes.get_mut(id).and_then(Option::take) else {
            return;
        };
        if let Some(p) = node.parent.and_then(|p| self.node_mut(p)) {
            p.children.retain(|c| *c != id);
        }
        for c in node.children {
            if let Some(n) = self.node_mut(c) {
                n.parent = None;
            }
            self.remove(c);
        }
        for slot in [
            &mut self.focus,
            &mut self.hover,
            &mut self.pressed,
            &mut self.drag,
        ] {
            if *slot == Some(id) {
                *slot = None;
            }
        }
        self.free.push(id);
        self.layout_dirty = true;
        self.dirty = true;
    }

    /// Visits `id`'s subtree in paint order.
    pub fn walk(&self, id: usize, f: &mut impl FnMut(usize, &NNode)) {
        if let Some(n) = self.node(id) {
            f(id, n);
            for &c in &n.children {
                self.walk(c, f);
            }
        }
    }
}

/// The shared handle effects and handlers use.
pub(crate) struct Shared {
    pub tree: RefCell<Tree>,
    pub theme: Theme,
    pub request_frame: RefCell<Rc<dyn Fn()>>,
}

impl Shared {
    pub fn changed(&self) {
        if let Ok(mut t) = self.tree.try_borrow_mut() {
            t.layout_dirty = true;
            t.dirty = true;
        }
        let r = self.request_frame.borrow().clone();
        r();
    }

    fn with<R>(&self, f: impl FnOnce(&mut Tree) -> R) -> R {
        let r = f(&mut self.tree.borrow_mut());
        self.changed();
        r
    }
}

/// Mounts `node` as children of `parent`, inside `view` (the caller runs
/// this with `view` current).
pub(crate) fn mount(ui: &Rc<Shared>, node: Node, parent: usize, view: &View) {
    match node {
        Node::Empty => {}
        Node::Fragment(children) => {
            for c in children {
                mount(ui, c, parent, view);
            }
        }
        Node::Widget(w) => mount_widget(ui, *w, parent, view),
        Node::Region(f) => {
            let group = group(ui, parent, view);
            let (ui, v) = (ui.clone(), view.clone());
            effect(move || {
                v.enter(|| {
                    let child = v.child();
                    let el = child.run(|| f());
                    child.run(|| untrack(|| mount(&ui, el.0, group, &child)));
                    ui.changed();
                })
            });
        }
        Node::Keyed(k) => {
            let group = group(ui, parent, view);
            type Entry = (View, usize, Rc<dyn std::any::Any>);
            let items: Rc<RefCell<HashMap<u64, Entry>>> = Rc::default();
            let (ui, v) = (ui.clone(), view.clone());
            effect(move || {
                v.enter(|| {
                    let list = (k.items)();
                    let mut order = Vec::with_capacity(list.len());
                    let mut alive = HashMap::with_capacity(list.len());
                    let mut items = items.borrow_mut();
                    for item in list {
                        let key = item.key;
                        let kept = match items.remove(&key) {
                            Some(e) if (item.same)(&*e.2, &*item.value) => Some(e),
                            Some((iv, _, _)) => {
                                iv.dispose();
                                None
                            }
                            None => None,
                        };
                        let entry = match kept {
                            Some(e) => e,
                            None => {
                                let build = item.build;
                                // Items outlive the effect's reruns: their
                                // views belong to the list's view.
                                let iv = v.owner().with(|| v.child());
                                let slot =
                                    ui.with(|t| t.alloc(NKind::Group, Some(group), iv.clone()));
                                let ui2 = ui.clone();
                                iv.owner()
                                    .with(|| on_cleanup(move || ui2.with(|t| t.remove(slot))));
                                let el = untrack(|| iv.run(build));
                                iv.run(|| untrack(|| mount(&ui, el.0, slot, &iv)));
                                (iv, slot, item.value)
                            }
                        };
                        order.push(entry.1);
                        alive.insert(key, entry);
                    }
                    for (_, (iv, _, _)) in items.drain() {
                        iv.dispose();
                    }
                    *items = alive;
                    ui.with(|t| {
                        if let Some(g) = t.node_mut(group) {
                            g.children = order;
                        }
                    });
                })
            });
        }
        Node::Scoped(scope, inner) => {
            let v = view.child_in(&scope);
            v.run(|| mount(ui, *inner, parent, &v));
        }
    }
}

fn group(ui: &Rc<Shared>, parent: usize, view: &View) -> usize {
    let id = ui.with(|t| t.alloc(NKind::Group, Some(parent), view.clone()));
    let ui2 = ui.clone();
    on_cleanup(move || ui2.with(|t| t.remove(id)));
    id
}

fn mount_widget(ui: &Rc<Shared>, w: Widget, parent: usize, view: &View) {
    let Widget {
        kind,
        style,
        attrs,
        handlers,
        web: _,
        cursor,
        children,
        site: _,
    } = w;
    let paint = handlers.iter().find_map(|h| match h {
        Handler::Paint(p) => Some(p.clone()),
        _ => None,
    });
    let id = ui.with(|t| {
        let id = t.alloc(NKind::Widget(kind), Some(parent), view.clone());
        let n = t.node_mut(id).expect("just allocated");
        n.viewport = handlers.iter().find_map(|h| {
            if let Handler::Viewport(v) = h {
                Some(v.mount())
            } else {
                None
            }
        });
        n.handlers = handlers;
        n.cursor = cursor;
        id
    });
    let ui2 = ui.clone();
    on_cleanup(move || ui2.with(|t| t.remove(id)));

    // Style: computed once when fixed, else an effect.
    let theme = ui.theme;
    if style.iter().any(Prop::is_dynamic) {
        let (ui, v) = (ui.clone(), view.clone());
        effect(move || {
            v.enter(|| {
                let s = Widget::resolve_style(kind, &theme, &style);
                ui.with(|t| {
                    if let Some(n) = t.node_mut(id) {
                        n.style = s;
                    }
                });
            })
        });
    } else {
        let s = Widget::resolve_style(kind, &theme, &style);
        ui.with(|t| t.node_mut(id).expect("alive").style = s);
    }

    for (a, p) in attrs {
        match p {
            Prop::Static(v) | Prop::Const(v) => {
                ui.with(|t| t.node_mut(id).expect("alive").set_attr(a, v))
            }
            Prop::Dynamic(f) => {
                let (ui, v) = (ui.clone(), view.clone());
                effect(move || {
                    v.enter(|| {
                        let value = f();
                        ui.with(|t| {
                            if let Some(n) = t.node_mut(id) {
                                n.set_attr(a, value);
                                if a == Attr::Disabled && n.flag(a) {
                                    if t.focus == Some(id) {
                                        t.focus = None;
                                    }
                                    if t.drag == Some(id) {
                                        t.drag = None;
                                    }
                                }
                            }
                        });
                    })
                });
            }
        }
    }

    if let Some(paint) = paint {
        let bounds = signal(Rect::default());
        let tick = signal(0u64);
        ui.with(|t| {
            t.node_mut(id).expect("alive").canvas = Some(CanvasState {
                bounds,
                tick,
                commands: Vec::new(),
                sources: Vec::new(),
            })
        });
        let (ui, v) = (ui.clone(), view.clone());
        effect(move || {
            v.enter(|| {
                let b = bounds.get();
                let _ = tick.get();
                if b.width <= 0.0 || b.height <= 0.0 {
                    return;
                }
                let mut ctx = PaintCtx::new(b.width, b.height);
                let ((), sources) = track_frame_sources(|| paint(ctx.bounds(), &mut ctx));
                let commands = ctx.into_commands();
                ui.with(|t| {
                    if let Some(c) = t.node_mut(id).and_then(|n| n.canvas.as_mut()) {
                        c.commands = commands;
                        c.sources = sources;
                    }
                });
            })
        });
    }

    for c in children {
        mount(ui, c, id, view);
    }
}