nandi/jolt-nativepublic Fork 0
cfd3e3677bed92e80cfe447469a249cfdc0b1401
Commits
Clone
git clone https://git.rickub.com/nandi/jolt-native.git
git clone ssh://git@rickub.com/nandi/jolt-native.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

tree.rs · 1600 lines · 65.6 KBRust Blame HistoryRaw
Bring vidya in cfd3e36 nandi 20d ago1//! A retained node tree, painted immediately.
2//!
3//! The push/pop half of this ABI (`vidya_card_begin` … `vidya_card_end`) suits
4//! a caller that writes its UI out top to bottom every frame. A *reactive*
5//! caller does not: glimmer keeps a component tree, reconciles it against new
6//! hiccup, and emits create/patch/append/remove against whatever the toolkit
7//! calls a widget. GTK has widgets to hand it; egui has none.
8//!
9//! So this module is the widget layer glimmer expects, on the Rust side of the
10//! FFI. The caller gets integer node handles and mutates them — set a prop,
11//! append a child, drop a subtree. Nothing is drawn by those calls. Once a
12//! frame, [`Tree::paint`] walks the whole tree and emits the egui calls it
13//! describes, and interactions come back out as a queue of events the caller
14//! drains and routes to its own handlers.
15//!
16//! Two things fall out of that split that the push/pop ABI could not have:
17//!
18//! * **Closure-shaped egui APIs work.** `ScrollArea`, `Frame` and friends take
19//! an `FnOnce(&mut Ui)` and keep their `begin`/`end` private, which is why
20//! `vidya_page_begin` had to reimplement scrolling by hand and why the page
21//! was documented as non-scrolling. Painting from a tree we already hold
22//! means the recursion *is* the closure; nothing has to stay open across a
23//! call boundary.
24//! * **FFI traffic tracks edits, not frames.** A static UI at 60fps costs zero
25//! crossings per frame; only what the reconciler actually changed is sent.
26//!
27//! The tree deliberately knows nothing about egui until [`Tree::paint`], so the
28//! arena and its edit operations are unit-testable with no window.
29
30use std::collections::HashMap;
31use std::collections::VecDeque;
32
33use egui::{Align, Align2, Color32, FontId, Id, Layout, Margin, TextureOptions, Ui, Vec2};
34use vidya_core::Theme;
35
36/// A prop value. The three types the ABI can carry, and all glimmer needs:
37/// keywords and colours arrive as strings, numbers as doubles, flags as ints.
38#[derive(Clone, Debug, PartialEq)]
39pub enum Value {
40 Str(String),
41 Num(f64),
42 Bool(bool),
43}
44
45/// What a node renders as. Unknown tags are kept rather than rejected: they
46/// paint as a plain vertical box, so a caller using a tag this backend has not
47/// grown yet still sees its children instead of nothing.
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub enum Tag {
50 Window,
51 Box,
52 Page,
53 Card,
54 Frame,
55 Scroll,
56 Label,
57 Link,
58 Title,
59 Title2,
60 DimLabel,
61 Button,
62 CheckButton,
63 Entry,
64 Separator,
65 Spacer,
66 Progress,
67 Spinner,
68 Image,
69 Avatar,
70 Reaction,
71 Status,
72 /// A tag this backend has not grown yet, keeping the name it was created
73 /// with so a dump answers what the caller actually asked for.
74 Unknown(String),
75}
76
77impl Tag {
78 /// Parse a hiccup tag name. `:hbox`/`:vbox` are the same box — the tag only
79 /// implies an orientation, which the caller sets as a prop.
80 fn parse(name: &str) -> Self {
81 match name {
82 "window" => Self::Window,
83 "box" | "hbox" | "vbox" => Self::Box,
84 "page" => Self::Page,
85 "card" => Self::Card,
86 "frame" => Self::Frame,
87 "scroll" => Self::Scroll,
88 "label" => Self::Label,
89 "link" => Self::Link,
90 "title" => Self::Title,
91 "title-2" => Self::Title2,
92 "dim-label" => Self::DimLabel,
93 "button" => Self::Button,
94 "checkbutton" | "checkbox" => Self::CheckButton,
95 "entry" => Self::Entry,
96 "separator" => Self::Separator,
97 "spacer" | "gap" => Self::Spacer,
98 "progress" => Self::Progress,
99 "spinner" => Self::Spinner,
100 "image" => Self::Image,
101 "avatar" => Self::Avatar,
102 "reaction" => Self::Reaction,
103 "status" => Self::Status,
104 other => Self::Unknown(other.to_owned()),
105 }
106 }
107
108 /// The canonical name of a parsed tag: `:hbox` and `:vbox` both answer
109 /// `box`, since the orientation lives in a prop rather than in the tag.
110 fn name(&self) -> &str {
111 match self {
112 Self::Window => "window",
113 Self::Box => "box",
114 Self::Page => "page",
115 Self::Card => "card",
116 Self::Frame => "frame",
117 Self::Scroll => "scroll",
118 Self::Label => "label",
119 Self::Link => "link",
120 Self::Title => "title",
121 Self::Title2 => "title-2",
122 Self::DimLabel => "dim-label",
123 Self::Button => "button",
124 Self::CheckButton => "checkbutton",
125 Self::Entry => "entry",
126 Self::Separator => "separator",
127 Self::Spacer => "spacer",
128 Self::Progress => "progress",
129 Self::Spinner => "spinner",
130 Self::Image => "image",
131 Self::Avatar => "avatar",
132 Self::Reaction => "reaction",
133 Self::Status => "status",
134 Self::Unknown(name) => name,
135 }
136 }
137}
138
139/// One interaction, waiting to be drained by the caller.
140///
141/// Names match glimmer's handler props with the `on-` dropped: `click` pairs
142/// with `:on-click`, `change` with `:on-change`, and so on. `text` and `num`
143/// carry the payload the handler is called with, empty when it takes none.
144#[derive(Clone, Debug, PartialEq)]
145pub struct Event {
146 pub node: u32,
147 pub name: &'static str,
148 pub text: String,
149 pub num: f64,
150}
151
152/// One prop value as EDN. Numbers that happen to be whole print without a
153/// trailing `.0`, since every number crossed the boundary as a double and
154/// `{:spacing 8.0}` reads worse than `{:spacing 8}`.
155fn write_value(value: &Value, out: &mut String) {
156 match value {
157 Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
158 Value::Num(n) => {
159 if n.is_finite() && n.fract() == 0.0 && n.abs() < 1e15 {
160 out.push_str(&format!("{}", *n as i64));
161 } else if n.is_finite() {
162 out.push_str(&format!("{n}"));
163 } else {
164 // EDN has no infinity or NaN literal; say so rather than emit
165 // something no reader will take.
166 out.push_str("nil");
167 }
168 }
169 Value::Str(text) => {
170 out.push('"');
171 for c in text.chars() {
172 match c {
173 '"' => out.push_str("\\\""),
174 '\\' => out.push_str("\\\\"),
175 '\n' => out.push_str("\\n"),
176 '\r' => out.push_str("\\r"),
177 '\t' => out.push_str("\\t"),
178 _ => out.push(c),
179 }
180 }
181 out.push('"');
182 }
183 }
184}
185
186#[derive(Clone, Debug, Default)]
187struct Node {
188 tag: Tag,
189 props: HashMap<String, Value>,
190 children: Vec<u32>,
191 /// 0 when unparented. The root's parent is 0 too, which is what stops the
192 /// ancestor walk in [`Tree::would_cycle`].
193 parent: u32,
194}
195
196impl Default for Tag {
197 fn default() -> Self {
198 Self::Unknown(String::new())
199 }
200}
201
202/// One named source of live pixels: what has arrived, and what is on the GPU.
203#[derive(Default)]
204struct Feed {
205 /// Pixels written since the last paint, waiting to be uploaded. Taken (not
206 /// copied) by the paint that consumes them.
207 pending: Option<egui::ColorImage>,
208 /// The texture the last upload produced. Kept when nothing new arrives, so
209 /// a still source keeps painting instead of blinking out between frames.
210 texture: Option<egui::TextureHandle>,
211}
212
213/// The node arena.
214///
215/// Handles are `index + 1`, so 0 is always "no node" — the value C gets back
216/// from a failed allocation and the sibling argument that means "first".
217/// Freed slots are reused, so a list that churns rows does not grow the arena.
218pub struct Tree {
219 nodes: Vec<Option<Node>>,
220 free: Vec<u32>,
221 root: u32,
222 /// Decoded images, by the path they came from. An `:image` node is walked
223 /// every frame and must not decode a file every time.
224 textures: HashMap<String, Option<egui::TextureHandle>>,
225 /// Live pixels pushed in by name, for an `:image` with a `feed` rather
226 /// than a `src`. A caller that has frames of its own — a camera, a video
227 /// decoder, a renderer — writes them here and the tag paints the latest.
228 ///
229 /// Two halves, because the writer is not in a frame and the uploader is:
230 /// `pending` is what arrived since the last paint, `texture` is what was
231 /// uploaded from it. A frame that arrives twice between paints overwrites
232 /// the first, so a 30fps source cannot outrun a 60fps window into a queue.
233 feeds: HashMap<String, Feed>,
234 pending: VecDeque<Event>,
235 /// The event most recently dequeued by `poll`, whose fields the accessors
236 /// read. Held here so the ABI can return a payload without out-parameters.
237 current: Option<Event>,
238}
239
240/// A stable colour for a name: the same person is the same colour every time,
241/// and two people are unlikely to share one. Kept dark enough for the light
242/// text drawn on top and dull enough not to compete with the accent.
243fn name_colour(name: &str, theme: &Theme) -> Color32 {
244 let mut hash: u32 = 2166136261;
245 for b in name.as_bytes() {
246 hash ^= *b as u32;
247 hash = hash.wrapping_mul(16777619);
248 }
249 // Six hues around the wheel, at a fixed saturation and value, rather than
250 // free RGB: random channels give muddy colours as often as good ones.
251 let sector = (hash % 6) as f32;
252 let (r, g, b) = match sector as u32 {
253 0 => (0.80, 0.35, 0.35),
254 1 => (0.80, 0.55, 0.25),
255 2 => (0.45, 0.65, 0.35),
256 3 => (0.30, 0.60, 0.65),
257 4 => (0.40, 0.50, 0.80),
258 _ => (0.65, 0.40, 0.70),
259 };
260 let _ = theme;
261 Color32::from_rgb((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8)
262}
263
264impl Tree {
265 /// Whether anything under `id` has `:scroll-here` set this frame.
266 ///
267 /// Walked rather than remembered: the prop is set for the moment of a jump
268 /// and taken off again, so there is nothing to keep, and this runs once
269 /// per scroll area rather than once per node.
270 fn wants_scroll_to(&self, id: u32) -> bool {
271 let Some(node) = self.slot(id) else {
272 return false;
273 };
274 matches!(node.props.get("scroll-here"), Some(Value::Bool(true)))
275 || node
276 .children
277 .iter()
278 .any(|child| self.wants_scroll_to(*child))
279 }
280
281 /// The texture for a file, decoding it the first time it is asked for.
282 /// A file that will not decode is remembered as such, so a bad path costs
283 /// one failed read rather than one per frame.
284 /// Hand the tree a frame of live pixels under `key`, to be painted by any
285 /// `:image` whose `feed` names it. `rgba` is `width * height * 4` bytes,
286 /// row-major, and is copied — the caller keeps ownership and may reuse the
287 /// buffer the moment this returns.
288 ///
289 /// Rejects a frame whose length disagrees with its dimensions rather than
290 /// painting torn pixels: a capture path that changes resolution mid-stream
291 /// otherwise reads the tail of the old buffer as the head of the new one.
292 pub fn set_frame(&mut self, key: &str, width: u32, height: u32, rgba: &[u8]) -> bool {
293 if key.is_empty() || width == 0 || height == 0 {
294 return false;
295 }
296 let expected = (width as usize)
297 .saturating_mul(height as usize)
298 .saturating_mul(4);
299 if rgba.len() != expected {
300 return false;
301 }
302 let image = egui::ColorImage::from_rgba_unmultiplied(
303 [width as usize, height as usize],
304 rgba,
305 );
306 // Overwrites whatever had not been painted yet: the newest frame is
307 // the only one worth showing, and a backlog of stale ones is latency.
308 self.feeds.entry(key.to_owned()).or_default().pending = Some(image);
309 true
310 }
311
312 /// Forget a feed and release its texture. A call that ends leaves a tile
313 /// behind otherwise — the last frame of a participant who has gone.
314 pub fn drop_frame(&mut self, key: &str) -> bool {
315 self.feeds.remove(key).is_some()
316 }
317
318 /// The texture for a feed, uploading this paint's pending frame first.
319 fn feed_texture(&mut self, ui: &Ui, key: &str) -> Option<egui::TextureHandle> {
320 let feed = self.feeds.get_mut(key)?;
321 if let Some(image) = feed.pending.take() {
322 match feed.texture.as_mut() {
323 // `set` reuses the allocation when the size is unchanged,
324 // which is the whole point at video rates.
325 Some(texture) => texture.set(image, TextureOptions::LINEAR),
326 None => {
327 feed.texture = Some(ui.ctx().load_texture(
328 format!("vidya/tree/feed/{key}"),
329 image,
330 TextureOptions::LINEAR,
331 ))
332 }
333 }
334 }
335 feed.texture.clone()
336 }
337
338 fn texture(&mut self, ui: &Ui, path: &str) -> Option<egui::TextureHandle> {
339 if let Some(cached) = self.textures.get(path) {
340 return cached.clone();
341 }
342 let handle = std::fs::read(path)
343 .ok()
344 .and_then(|bytes| decode_png_rgba(&bytes))
345 .map(|image| {
346 ui.ctx()
347 .load_texture(format!("vidya/tree/{path}"), image, TextureOptions::LINEAR)
348 });
349 self.textures.insert(path.to_owned(), handle.clone());
350 handle
351 }
352}
353
354/// PNG bytes as an egui image. PNG alone: it is what the vendored decoder
355/// reads, and what the media this paints is served as.
356fn decode_png_rgba(bytes: &[u8]) -> Option<egui::ColorImage> {
357 let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
358 decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::ALPHA);
359 let mut reader = decoder.read_info().ok()?;
360 let mut buf = vec![0; reader.output_buffer_size()];
361 let info = reader.next_frame(&mut buf).ok()?;
362 let (w, h) = (info.width as usize, info.height as usize);
363 let raw = &buf[..info.buffer_size()];
364 let rgba: Vec<u8> = match info.color_type {
365 png::ColorType::Rgba => raw.to_vec(),
366 png::ColorType::Rgb => raw
367 .chunks_exact(3)
368 .flat_map(|c| [c[0], c[1], c[2], 255])
369 .collect(),
370 _ => return None,
371 };
372 (rgba.len() == w * h * 4).then(|| egui::ColorImage::from_rgba_unmultiplied([w, h], &rgba))
373}
374
375impl Default for Tree {
376 fn default() -> Self {
377 let mut tree = Self {
378 nodes: Vec::new(),
379 free: Vec::new(),
380 root: 0,
381 textures: HashMap::new(),
382 feeds: HashMap::new(),
383 pending: VecDeque::new(),
384 current: None,
385 };
386 tree.root = tree.new_node("window");
387 tree
388 }
389}
390
391impl Tree {
392 pub fn root(&self) -> u32 {
393 self.root
394 }
395
396 fn slot(&self, id: u32) -> Option<&Node> {
397 if id == 0 {
398 return None;
399 }
400 self.nodes.get(id as usize - 1).and_then(Option::as_ref)
401 }
402
403 fn slot_mut(&mut self, id: u32) -> Option<&mut Node> {
404 if id == 0 {
405 return None;
406 }
407 self.nodes.get_mut(id as usize - 1).and_then(Option::as_mut)
408 }
409
410 pub fn exists(&self, id: u32) -> bool {
411 self.slot(id).is_some()
412 }
413
414 // ── editing ─────────────────────────────────────────────────────────────
415
416 pub fn new_node(&mut self, tag: &str) -> u32 {
417 let node = Node {
418 tag: Tag::parse(tag),
419 ..Node::default()
420 };
421 match self.free.pop() {
422 Some(id) => {
423 self.nodes[id as usize - 1] = Some(node);
424 id
425 }
426 None => {
427 self.nodes.push(Some(node));
428 self.nodes.len() as u32
429 }
430 }
431 }
432
433 /// Drop `id` and everything under it, unparenting it first.
434 ///
435 /// glimmer has no separate destroy operation — `remove-child!` is the last
436 /// the reconciler ever says about a widget — so removal frees, and a node
437 /// handle the caller still holds after that is simply dead.
438 pub fn free_node(&mut self, id: u32) {
439 let parent = match self.slot(id) {
440 Some(n) => n.parent,
441 None => return,
442 };
443 self.detach(parent, id);
444 self.free_subtree(id);
445 }
446
447 fn free_subtree(&mut self, id: u32) {
448 let Some(node) = self.slot_mut(id).map(std::mem::take) else {
449 return;
450 };
451 self.nodes[id as usize - 1] = None;
452 self.free.push(id);
453 for child in node.children {
454 self.free_subtree(child);
455 }
456 // An event queued against a node that has since been removed would be
457 // routed to a handler the caller has already forgotten.
458 self.pending.retain(|e| e.node != id);
459 }
460
461 /// Unparent `child` without freeing it. `parent` may be 0 (already loose).
462 fn detach(&mut self, parent: u32, child: u32) {
463 if let Some(p) = self.slot_mut(parent) {
464 p.children.retain(|&c| c != child);
465 }
466 if let Some(c) = self.slot_mut(child) {
467 c.parent = 0;
468 }
469 }
470
471 /// True when parenting `child` under `parent` would make a loop — `child`
472 /// is `parent`, or an ancestor of it. A cycle here is an infinite paint,
473 /// so it is checked rather than trusted.
474 fn would_cycle(&self, parent: u32, child: u32) -> bool {
475 let mut at = parent;
476 while at != 0 {
477 if at == child {
478 return true;
479 }
480 at = match self.slot(at) {
481 Some(n) => n.parent,
482 None => 0,
483 };
484 }
485 false
486 }
487
488 pub fn append(&mut self, parent: u32, child: u32) -> bool {
489 self.insert_at(parent, child, usize::MAX)
490 }
491
492 fn insert_at(&mut self, parent: u32, child: u32, index: usize) -> bool {
493 if parent == 0 || child == 0 || !self.exists(parent) || !self.exists(child) {
494 return false;
495 }
496 if self.would_cycle(parent, child) {
497 return false;
498 }
499 // Moving a child that already has a parent (including this one) is a
500 // reparent, not a duplicate: take it out first so it appears once.
501 let old_parent = self.slot(child).map_or(0, |n| n.parent);
502 self.detach(old_parent, child);
503
504 let p = self.slot_mut(parent).expect("checked above");
505 let at = index.min(p.children.len());
506 p.children.insert(at, child);
507 self.slot_mut(child).expect("checked above").parent = parent;
508 true
509 }
510
511 pub fn remove(&mut self, parent: u32, child: u32) {
512 if self.slot(child).map_or(true, |n| n.parent != parent) {
513 return;
514 }
515 self.free_node(child);
516 }
517
518 /// Move `child` to sit immediately after `sibling`; `sibling` 0 means first.
519 /// glimmer's keyed reconciliation calls this to reorder a list without
520 /// rebuilding the widgets in it.
521 pub fn insert_after(&mut self, parent: u32, child: u32, sibling: u32) -> bool {
522 if !self.exists(parent) || !self.exists(child) {
523 return false;
524 }
525 let index = if sibling == 0 {
526 0
527 } else {
528 match self
529 .slot(parent)
530 .and_then(|p| p.children.iter().position(|&c| c == sibling))
531 {
532 // The sibling's own slot, once `child` is out of the way, is
533 // the position after it.
534 Some(i) => i + 1,
535 None => return false,
536 }
537 };
538 // Re-derive the index after detaching: removing `child` from earlier in
539 // the list shifts everything after it down one.
540 let before = self
541 .slot(parent)
542 .and_then(|p| p.children.iter().position(|&c| c == child))
543 .map_or(false, |i| i < index);
544 self.insert_at(parent, child, if before { index - 1 } else { index })
545 }
546
547 pub fn replace(&mut self, parent: u32, old: u32, new: u32) -> bool {
548 let Some(index) = self
549 .slot(parent)
550 .and_then(|p| p.children.iter().position(|&c| c == old))
551 else {
552 return false;
553 };
554 if !self.insert_at(parent, new, index) {
555 return false;
556 }
557 self.remove(parent, old);
558 true
559 }
560
561 /// The canonical tag name, or the empty string for a node that is not
562 /// there. With [`Tree::child_count`] and [`Tree::child_at`] this is enough
563 /// for a caller to read back the tree it built — which is how the jolt
564 /// backend's tests assert against a real reconcile with no window open.
565 pub fn tag_name(&self, id: u32) -> &str {
566 self.slot(id).map_or("", |n| n.tag.name())
567 }
568
569 pub fn child_count(&self, id: u32) -> usize {
570 self.slot(id).map_or(0, |n| n.children.len())
571 }
572
573 pub fn child_at(&self, id: u32, index: usize) -> u32 {
574 self.slot(id)
575 .and_then(|n| n.children.get(index))
576 .copied()
577 .unwrap_or(0)
578 }
579
580 // ── props ───────────────────────────────────────────────────────────────
581
582 pub fn set(&mut self, id: u32, key: &str, value: Value) {
583 if let Some(node) = self.slot_mut(id) {
584 node.props.insert(key.to_owned(), value);
585 }
586 }
587
588 pub fn clear_props(&mut self, id: u32) {
589 if let Some(node) = self.slot_mut(id) {
590 node.props.clear();
591 }
592 }
593
594 pub fn get(&self, id: u32, key: &str) -> Option<&Value> {
595 self.slot(id).and_then(|n| n.props.get(key))
596 }
597
598 // ── reading it back as hiccup ───────────────────────────────────────────
599
600 /// The subtree at `id` as pretty-printed hiccup, in the same shape the
601 /// caller wrote: `[:tag {props} children…]`, one node to a line.
602 ///
603 /// This is what the tree *is*, not what a component said — it is read from
604 /// the arena after the reconciler has had its way with it, so a patch that
605 /// went to the wrong node shows up here as a difference from the source.
606 ///
607 /// A node that does not exist dumps as `nil`. `:hbox` and `:vbox` both
608 /// dump as `:box`, as they are both stored as one; their orientation is in
609 /// the props. Handlers are not here — they never crossed the boundary.
610 pub fn dump(&self, id: u32) -> String {
611 let mut out = String::new();
612 self.dump_into(id, 0, &mut out);
613 out
614 }
615
616 fn dump_into(&self, id: u32, depth: usize, out: &mut String) {
617 let Some(node) = self.slot(id) else {
618 out.push_str("nil");
619 return;
620 };
621 let indent = " ".repeat(depth);
622 out.push_str("[:");
623 out.push_str(node.tag.name());
624
625 // Sorted, so two dumps of the same tree compare as text.
626 let mut keys: Vec<&String> = node.props.keys().collect();
627 keys.sort();
628 out.push_str(" {");
629 for (i, key) in keys.iter().enumerate() {
630 if i > 0 {
631 out.push(' ');
632 }
633 out.push(':');
634 out.push_str(key);
635 out.push(' ');
636 write_value(&node.props[*key], out);
637 }
638 out.push('}');
639
640 for child in &node.children {
641 out.push('\n');
642 out.push_str(&indent);
643 out.push_str(" ");
644 self.dump_into(*child, depth + 1, out);
645 }
646 out.push(']');
647 }
648
649 // ── events ──────────────────────────────────────────────────────────────
650
651 fn emit(&mut self, node: u32, name: &'static str, text: String, num: f64) {
652 self.pending.push_back(Event {
653 node,
654 name,
655 text,
656 num,
657 });
658 }
659
660 /// Dequeue one event into the accessor slot. False when the queue is empty.
661 pub fn poll(&mut self) -> bool {
662 self.current = self.pending.pop_front();
663 self.current.is_some()
664 }
665
666 pub fn current(&self) -> Option<&Event> {
667 self.current.as_ref()
668 }
669
670 // ── painting ────────────────────────────────────────────────────────────
671
672 /// Emit the whole tree into `ui`. Called once per frame.
673 pub fn paint(&mut self, ui: &mut Ui, theme: &Theme) {
674 let root = self.root;
675 self.paint_node(root, ui, theme);
676 }
677
678 fn paint_children(&mut self, id: u32, ui: &mut Ui, theme: &Theme) {
679 // The child list is copied rather than borrowed: painting a child can
680 // write a prop back (an entry's text) or queue an event, both of which
681 // need `&mut self` while the walk is in flight. A UI's worth of `u32`s
682 // is a cheap price for not threading a cell through every widget.
683 let children = self
684 .slot(id)
685 .map(|n| n.children.clone())
686 .unwrap_or_default();
687 for child in children {
688 self.paint_node(child, ui, theme);
689 }
690 }
691
692 fn paint_node(&mut self, id: u32, ui: &mut Ui, theme: &Theme) {
693 let Some((tag, props)) = self
694 .slot(id)
695 .map(|n| (n.tag.clone(), Props(n.props.clone())))
696 else {
697 return;
698 };
699 let enabled = props.bool("sensitive", true);
700 // `:scroll-here` brings this node into view in whatever scroll area it
701 // sits in. It fires on every frame the prop is set, so a caller sets it
702 // for the moment of a jump and takes it off again — leaving it on would
703 // pin the area there and take scrolling away from the reader.
704 let scroll_here = props.bool("scroll-here", false);
705 let before = ui.cursor().top();
706 self.with_width(&props, ui, |tree, ui| {
707 if enabled {
708 tree.paint_tag(id, &tag, &props, ui, theme);
709 } else {
710 // Scoped rather than per-widget: a dimmed container dims its
711 // whole subtree, which is what `:sensitive false` means
712 // everywhere else in glimmer.
713 ui.add_enabled_ui(false, |ui| tree.paint_tag(id, &tag, &props, ui, theme));
714 }
715 });
716 if scroll_here {
717 // Horizontally the rect is the visible width, not the node's own:
718 // a rect wider than the viewport is off-screen sideways as far as
719 // egui is concerned, so it scrolls across to centre it and the
720 // reader lands on a message with its left edge cut off. Already
721 // visible on that axis means only the vertical scroll happens.
722 let clip = ui.clip_rect();
723 let rect = egui::Rect::from_min_max(
724 egui::pos2(clip.left(), before),
725 egui::pos2(clip.right(), ui.cursor().top()),
726 );
727 ui.scroll_to_rect(rect, Some(Align::Center));
728 }
729 }
730
731 /// Constrain `add` to the node's `:width-request`, when it has one.
732 ///
733 /// Immediate mode has no natural width for a field: an entry asks for
734 /// whatever is left, so an entry beside a button in an `:hbox` takes the
735 /// row and wraps the button onto the next line. This is how a caller says
736 /// otherwise.
737 fn with_width(&mut self, props: &Props, ui: &mut Ui, add: impl FnOnce(&mut Self, &mut Ui)) {
738 let requested = props.num("width-request", 0.0) as f32;
739 let fill_height = props.bool("fill-height", false);
740 if requested <= 0.0 && !fill_height {
741 add(self, ui);
742 return;
743 }
744 let avail = ui.available_width().max(1.0);
745 let width = if requested > 0.0 {
746 requested.min(avail)
747 } else {
748 avail
749 };
750 // The height is the row's, not zero: a region allocated with no height
751 // leaves the row measuring nothing at the moment the next widget is
752 // placed, so a button beside a text field lands at the row's top edge
753 // instead of beside it.
754 //
755 // A column of a split is the other case. Inside a row, "what is left"
756 // is the row's own height — one button tall at the moment the column
757 // is placed — so a pane asking for it is allocated a strip, and the
758 // scrolling list inside it gets no room. `:fill-height` measures
759 // against what is visible below the cursor instead, the way `:scroll`
760 // does: everything from here to the bottom of the window.
761 let height = if fill_height {
762 (ui.clip_rect().bottom() - ui.cursor().top()).max(0.0)
763 } else {
764 ui.available_height().max(0.0)
765 };
766 ui.allocate_ui_with_layout(
767 Vec2::new(width, height),
768 Layout::top_down(Align::Min),
769 |ui| {
770 ui.set_min_width(width);
771 ui.set_max_width(width);
772 add(self, ui);
773 },
774 );
775 }
776
777 fn paint_tag(&mut self, id: u32, tag: &Tag, props: &Props, ui: &mut Ui, theme: &Theme) {
778 match tag {
779 // The root is the window itself: its children stack down the page.
780 //
781 // Its width is written back onto it, the way an entry writes back
782 // its text: a caller laying out against the window — one pane on a
783 // phone, two side by side on a desktop — has no other way to ask
784 // how much room it has, since nothing else here measures.
785 Tag::Window => {
786 let width = ui.available_width().max(0.0) as f64;
787 self.set(id, "window-width", Value::Num(width));
788 self.paint_children(id, ui, theme)
789 }
790
791 Tag::Box | Tag::Unknown(_) => {
792 let horizontal = props.str("orientation") == "horizontal";
793 let spacing = props.num("spacing", theme.spacing.sm as f64) as f32;
794 self.with_margin(props, ui, |tree, ui| {
795 let axis = if horizontal {
796 Vec2::new(spacing, ui.spacing().item_spacing.y)
797 } else {
798 Vec2::new(ui.spacing().item_spacing.x, spacing)
799 };
800 if horizontal {
801 // `:align :end` lays the row out from the right edge of
802 // the space it is given, which is how a trailing group
803 // — an action beside a message, a count beside a name —
804 // sits against the right of a row rather than trailing
805 // whatever came before it.
806 if props.str("align") == "end" {
807 // Nested in a row of its own: a right-to-left
808 // layout takes the height available to it, which
809 // in a column is everything below — every such row
810 // would be as tall as the rest of the screen, and
811 // the gaps would land between the rows above it.
812 ui.horizontal(|ui| {
813 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
814 ui.spacing_mut().item_spacing = axis;
815 tree.paint_children(id, ui, theme);
816 });
817 });
818 } else {
819 ui.horizontal_wrapped(|ui| {
820 ui.spacing_mut().item_spacing = axis;
821 tree.paint_children(id, ui, theme);
822 });
823 }
824 } else {
825 // `:align :center` puts a column's children on the
826 // middle of the width rather than against its left
827 // edge — what a picture on a screen of its own wants,
828 // and nothing a column of text ever does.
829 let cross = if props.str("align") == "center" {
830 Align::Center
831 } else {
832 Align::Min
833 };
834 ui.with_layout(Layout::top_down(cross), |ui| {
835 ui.spacing_mut().item_spacing = axis;
836 tree.paint_children(id, ui, theme);
837 });
838 }
839 });
840 }
841
842 // A scrolling column with page padding, optionally centred at a
843 // maximum width — the shell most Vidya apps put everything inside.
844 Tag::Page => {
845 let max_width = props.num("max-width", 0.0) as f32;
846 let pad = theme.spacing.page;
847 egui::ScrollArea::vertical()
848 .auto_shrink([false, false])
849 .show(ui, |ui| {
850 egui::Frame::new()
851 .inner_margin(Margin::same(pad.clamp(0.0, 127.0) as i8))
852 .show(ui, |ui| {
853 let avail = ui.available_width();
854 let width = if max_width > 0.0 {
855 max_width.min(avail)
856 } else {
857 avail
858 };
859 let indent = ((avail - width) * 0.5).max(0.0);
860 ui.horizontal(|ui| {
861 ui.add_space(indent);
862 ui.allocate_ui_with_layout(
863 Vec2::new(width, 0.0),
864 Layout::top_down(Align::Min),
865 |ui| {
866 ui.set_min_width(width);
867 ui.set_max_width(width);
868 vidya_core::vstack(ui, theme, |ui| {
869 self.paint_children(id, ui, theme);
870 });
871 },
872 );
873 });
874 });
875 });
876 }
877
878 Tag::Scroll => {
879 let area = match props.str("orientation") {
880 "horizontal" => egui::ScrollArea::horizontal(),
881 "both" => egui::ScrollArea::both(),
882 _ => egui::ScrollArea::vertical(),
883 };
884 // Without a bound a scroll area takes every point left in its
885 // parent, so anything after it — a compose bar under a message
886 // list — is pushed off the bottom. `:max-height` bounds it
887 // outright; `:reserve` bounds it by what it must leave behind,
888 // which is what a caller actually knows: the compose bar's
889 // height, not the window's.
890 let area = {
891 let reserve = props.num("reserve", 0.0) as f32;
892 let max_height = if reserve > 0.0 {
893 // Clamped against the clip rect as well as the layout's
894 // own idea of what is left: on Android the two differ
895 // once the soft keyboard takes the bottom of the
896 // screen, and it is the visible one that has to win or
897 // the row below the list is pushed off under the
898 // keyboard.
899 let visible = (ui.clip_rect().bottom() - ui.cursor().top()).max(0.0);
900 (ui.available_height().min(visible) - reserve).max(0.0)
901 } else {
902 props.num("max-height", 0.0) as f32
903 };
904 if max_height > 0.0 {
905 area.max_height(max_height)
906 } else {
907 area
908 }
909 };
910 // Keyed by the node rather than by where it sits: egui derives
911 // a scroll area's id from its parent ui, so two areas that
912 // occupy the same place in the tree at different times — the
913 // message list and the picture that replaces the screen it is
914 // on — would otherwise share one offset, and the list would
915 // come back showing whatever the picture left behind.
916 //
917 // `:scroll-key` names an area that outlives its node instead.
918 // A node id is only as durable as the node: a list unmounted
919 // while another screen is up comes back as a new node, and a
920 // position keyed by that is a position thrown away. A caller
921 // that means "this same list again" says so with a name, and
922 // the reader returns to the line they left.
923 let key = {
924 let name = props.str("scroll-key");
925 if name.is_empty() {
926 Id::new(("vidya_scroll", id))
927 } else {
928 Id::new(("vidya_scroll_key", name))
929 }
930 };
931 let area = area.id_salt(key);
932 // A chat wants the newest line, not the oldest — except on a
933 // frame where something inside asked to be scrolled to. The
934 // two are the same control pulling opposite ways, and sticking
935 // wins every time it is asked, so a jump to an old message
936 // would land nowhere.
937 let sticks = props.bool("stick-to-bottom", false) && !self.wants_scroll_to(id);
938 let area = area.stick_to_bottom(sticks);
939 // `:scroll-to-bottom` is a number the caller bumps rather than
940 // a flag it sets: a flag would have to be cleared afterwards,
941 // and there is no frame in which the caller could do it. A
942 // value it has not seen before means "now".
943 let jump_key = key.with("jump");
944 let jump = props.num("scroll-to-bottom", 0.0);
945 let jumped = ui.ctx().data(|d| d.get_temp::<f64>(jump_key));
946 let jump_now = jump > 0.0 && jumped != Some(jump);
947 // The end is last frame's own maximum offset, kept for exactly
948 // this. Not f32::MAX — egui subtracts the viewport from what it
949 // is given, and MAX minus anything is still MAX, an offset the
950 // content can never reach: the area painted nothing and stayed
951 // that way. Not `scroll_to_rect` either, which a scroll area
952 // that has been scrolled away from ignores here.
953 let end_offset_key = key.with("end_offset");
954 let area = if jump_now {
955 ui.ctx().data_mut(|d| d.insert_temp(jump_key, jump));
956 let end = ui
957 .ctx()
958 .data(|d| d.get_temp::<f32>(end_offset_key))
959 .unwrap_or(0.0);
960 area.vertical_scroll_offset(end)
961 } else {
962 area
963 };
964 // Hold the content to the viewport's width, as `:page` does,
965 // so a wrapping child wraps at the visible edge.
966 let viewport_width = ui.available_width();
967 let output = area.auto_shrink([false, false]).show(ui, |ui| {
968 ui.set_max_width(viewport_width);
969 self.paint_children(id, ui, theme);
970 // The end asked for by scrolling to it, not by setting an
971 // offset of f32::MAX: egui subtracts the viewport from
972 // whatever it is given, and MAX minus anything is still
973 // MAX — an offset the content can never reach, which left
974 // the area painting nothing at all.
975
976 });
977
978 // Say when the view leaves the end and when it comes back, so
979 // a caller can offer the way back. Reported on change only: the
980 // position itself changes every frame of a scroll, and an event
981 // a frame is not news.
982 // Within a line of the end counts as the end, and content
983 // shorter than the viewport is always at it.
984 let max_offset = (output.content_size.y - output.inner_rect.height()).max(0.0);
985 // What `:scroll-to-bottom` will aim at next time it is asked.
986 ui.ctx()
987 .data_mut(|d| d.insert_temp(end_offset_key, max_offset));
988 let at_end = output.state.offset.y >= max_offset - 24.0;
989 // Reaching the end is reported at once; leaving it has to hold
990 // for a few frames first. A burst of arriving messages grows
991 // the content faster than the offset follows it, and reporting
992 // that honestly would blink "scrolled away" whenever a channel
993 // is busy.
994 let end_key = key.with("at_end");
995 let away_key = key.with("away_frames");
996 let away_frames = ui.ctx().data(|d| d.get_temp::<u32>(away_key)).unwrap_or(0);
997 let away_frames = if at_end { 0 } else { away_frames.saturating_add(1) };
998 ui.ctx().data_mut(|d| d.insert_temp(away_key, away_frames));
999
1000 let settled = if at_end {
1001 Some(true)
1002 } else if away_frames >= 3 {
1003 Some(false)
1004 } else {
1005 None
1006 };
1007 if let Some(at_end) = settled {
1008 let was_at_end = ui.ctx().data(|d| d.get_temp::<bool>(end_key));
1009 if was_at_end != Some(at_end) {
1010 ui.ctx().data_mut(|d| d.insert_temp(end_key, at_end));
1011 // Only after the first report: the opening one would
1012 // arrive before the content has a height.
1013 if was_at_end.is_some() {
1014 self.emit(
1015 id,
1016 "change",
1017 if at_end { "end" } else { "away" }.to_owned(),
1018 if at_end { 1.0 } else { 0.0 },
1019 );
1020 }
1021 }
1022 }
1023 }
1024
1025 Tag::Card => {
1026 vidya_core::card(ui, theme, |ui| self.paint_children(id, ui, theme));
1027 }
1028
1029 // A card with a heading — glimmer-tui's `:frame` label, in the
1030 // idiom this theme actually has for one.
1031 Tag::Frame => {
1032 let label = props.label();
1033 vidya_core::card(ui, theme, |ui| {
1034 if !label.is_empty() {
1035 vidya_core::title_2(ui, theme, label);
1036 }
1037 self.paint_children(id, ui, theme);
1038 });
1039 }
1040
1041 Tag::Label => vidya_core::body(ui, theme, props.label()),
1042
1043 // Body text that answers the pointer: the accent colour and the
1044 // hand cursor are the whole affordance, and the click is reported
1045 // like a button's so the caller decides what opening it means.
1046 Tag::Link => {
1047 let response = ui
1048 .add(
1049 egui::Label::new(
1050 egui::RichText::new(props.label())
1051 .size(theme.type_scale.body)
1052 .color(theme.palette.accent),
1053 )
1054 .wrap()
1055 .sense(egui::Sense::click()),
1056 )
1057 .on_hover_cursor(egui::CursorIcon::PointingHand);
1058 if response.clicked() {
1059 self.emit(id, "click", props.label().to_owned(), 0.0);
1060 }
1061 }
1062 Tag::Title => vidya_core::title(ui, theme, props.label()),
1063 Tag::Title2 => vidya_core::title_2(ui, theme, props.label()),
1064 Tag::DimLabel => vidya_core::dim_label(ui, theme, props.label()),
1065
1066 Tag::Button => {
1067 let kind = match props.str("kind") {
1068 "primary" => 1,
1069 "destructive" => 2,
1070 _ => 0,
1071 };
1072 if crate::ui::button(ui, theme, props.label(), kind) {
1073 self.emit(id, "click", String::new(), 0.0);
1074 }
1075 }
1076
1077 Tag::CheckButton => {
1078 let was = props.bool("active", false);
1079 let (now, changed) = crate::ui::checkbox(ui, theme, was, props.label());
1080 if changed {
1081 // The widget does not own the value: the new state is
1082 // written back so a component that ignores `:on-toggled`
1083 // still tracks the click, and the handler decides whether
1084 // it survives the next render of `:active`.
1085 self.set(id, "active", Value::Bool(now));
1086 self.emit(id, "toggled", String::new(), if now { 1.0 } else { 0.0 });
1087 }
1088 }
1089
1090 Tag::Entry => {
1091 let mut text = props.str("text").to_owned();
1092 let placeholder = props.str("placeholder").to_owned();
1093 let rows = props.num("rows", 4.0) as usize;
1094 let response = if props.bool("multiline", false) {
1095 vidya_core::text_field_multiline(ui, theme, &mut text, rows.max(1))
1096 } else {
1097 crate::ui::text_field(ui, theme, &mut text, &placeholder)
1098 };
1099 if text != props.str("text") {
1100 self.set(id, "text", Value::Str(text.clone()));
1101 self.emit(id, "change", text, 0.0);
1102 }
1103 if response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
1104 self.emit(id, "activate", String::new(), 0.0);
1105 }
1106 // A paste of something that is not text. egui turns Ctrl+V
1107 // into a `Paste` event carrying the clipboard's text, and a
1108 // clipboard holding a picture has none — so the keystroke
1109 // arrives as a key press with no paste behind it, and the
1110 // field would otherwise swallow it. Reported instead, for a
1111 // caller that has somewhere to put a picture; one that has not
1112 // ignores it and the keystroke stays as inert as it was.
1113 //
1114 // The clipboard is not read here: whether there is a picture
1115 // on it is answered by `vidya_clipboard_image_png`, and asking
1116 // twice would copy every pasted image for nothing.
1117 if response.has_focus() {
1118 let paste_without_text = ui.input(|i| {
1119 i.events.iter().any(|e| {
1120 matches!(
1121 e,
1122 egui::Event::Key {
1123 key: egui::Key::V,
1124 pressed: true,
1125 modifiers,
1126 ..
1127 } if modifiers.command
1128 )
1129 }) && !i
1130 .events
1131 .iter()
1132 .any(|e| matches!(e, egui::Event::Paste(_)))
1133 });
1134 if paste_without_text {
1135 self.emit(id, "paste-empty", String::new(), 0.0);
1136 }
1137 }
1138 }
1139
1140 Tag::Separator => crate::ui::separator(ui),
1141 Tag::Spacer => crate::ui::gap(ui, props.num("size", theme.spacing.md as f64) as f32),
1142 Tag::Status => crate::ui::status(ui, theme, props.label(), props.bool("live", false)),
1143
1144 Tag::Progress => {
1145 let value = props.num("value", 0.0) as f32;
1146 let mut bar = egui::ProgressBar::new(value.clamp(0.0, 1.0));
1147 if !props.label().is_empty() {
1148 bar = bar.text(props.label());
1149 }
1150 ui.add(bar);
1151 }
1152
1153 // A picture from a file the caller has already fetched. Decoded
1154 // once and kept as a texture: the tree is walked every frame, and
1155 // decoding a PNG sixty times a second is not a thing to do.
1156 // Someone's face, or the next best thing. A chat wants one column
1157 // of them down the left, so this is a fixed square whatever the
1158 // picture's own proportions are, and there is always something to
1159 // draw: a name with no picture behind it becomes its initial on a
1160 // colour of its own, which keeps the column straight and still
1161 // tells one person from another at a glance.
1162 Tag::Avatar => {
1163 let size = props.num("size", 24.0) as f32;
1164 let label = props.label().to_owned();
1165 let path = props.str("src").to_owned();
1166 let (rect, response) =
1167 ui.allocate_exact_size(Vec2::splat(size), egui::Sense::click());
1168
1169 let texture = if path.is_empty() {
1170 None
1171 } else {
1172 self.texture(ui, &path)
1173 };
1174 match texture {
1175 // A corner radius of half the side is a circle.
1176 Some(texture) => egui::Image::new(egui::load::SizedTexture::new(
1177 texture.id(),
1178 Vec2::splat(size),
1179 ))
1180 .corner_radius(size * 0.5)
1181 .paint_at(ui, rect),
1182 None => {
1183 let initial = label
1184 .trim_start_matches(['#', '&', '@', '+', '%', '~'])
1185 .chars()
1186 .next()
1187 .map(|c| c.to_uppercase().to_string())
1188 .unwrap_or_else(|| "?".to_owned());
1189 ui.painter()
1190 .circle_filled(rect.center(), size * 0.5, name_colour(&label, theme));
1191 ui.painter().text(
1192 rect.center(),
1193 Align2::CENTER_CENTER,
1194 initial,
1195 FontId::proportional((size * 0.45).max(9.0)),
1196 theme.palette.accent_fg,
1197 );
1198 }
1199 }
1200 if response.clicked() {
1201 self.emit(id, "click", label, 0.0);
1202 }
1203 }
1204
1205 // A reaction chip: the emoji drawn from the Twemoji pack rather
1206 // than set as text, so it is the colour picture people expect and
1207 // not a monochrome glyph — or, where the font has no glyph at all,
1208 // tofu. `:count` rides beside it once more than one person is on
1209 // it, and `:mine` is what marks the ones you put there yourself.
1210 Tag::Reaction => {
1211 let emoji = props.str("emoji").to_owned();
1212 let emoji = if emoji.is_empty() {
1213 props.label().to_owned()
1214 } else {
1215 emoji
1216 };
1217 let count = props.num("count", 0.0).max(0.0) as usize;
1218 let mine = props.bool("mine", false);
1219 // `:size` is the glyph's, and the pill is sized from it.
1220 let size = props.num("size", 0.0) as f32;
1221 let response = if size > 0.0 {
1222 vidya_core::reaction_chip_sized(ui, theme, &emoji, count, mine, size)
1223 } else {
1224 vidya_core::reaction_chip(ui, theme, &emoji, count, mine)
1225 };
1226 if response.clicked() {
1227 self.emit(id, "click", emoji, count as f64);
1228 }
1229 }
1230
1231 Tag::Image => {
1232 // Two sources, one tag: a `src` is a file decoded once and
1233 // cached by its path, a `feed` is live pixels pushed in under
1234 // a name (`vidya_frame_rgba`) and re-uploaded as they arrive.
1235 // Everything downstream — fit, bounds, the click — is the same
1236 // for both, which is why this is a prop and not a second tag.
1237 let feed = props.str("feed").to_owned();
1238 let path = props.str("src").to_owned();
1239 let max_width = props.num("max-width", 0.0) as f32;
1240 let texture = if !feed.is_empty() {
1241 self.feed_texture(ui, &feed)
1242 } else if !path.is_empty() {
1243 self.texture(ui, &path)
1244 } else {
1245 return;
1246 };
1247 let Some(texture) = texture else {
1248 // A file that will not decode is not worth a broken-image
1249 // glyph; the message text beside it already says what it
1250 // was meant to be. A feed that has had no frame yet is the
1251 // same: the tile appears when the first one lands.
1252 return;
1253 };
1254 let size = texture.size_vec2();
1255
1256 // `:fit` gives the picture every point of the space it has
1257 // been handed and centres it in it — a picture on a screen of
1258 // its own, rather than one in a line of chat. It is the one
1259 // case that scales *up*: a picture opened to be looked at is
1260 // meant to fill the window, and how big the window is this
1261 // frame is something only this side knows. Everywhere else the
1262 // caller's `:max-height` bounds it and nothing is enlarged
1263 // past its own pixels.
1264 if props.bool("fit", false) {
1265 let space = ui.available_size();
1266 if space.x <= 0.0 || space.y <= 0.0 || size.x <= 0.0 || size.y <= 0.0 {
1267 return;
1268 }
1269 let scale = (space.x / size.x).min(space.y / size.y);
1270 let (rect, response) =
1271 ui.allocate_exact_size(space, egui::Sense::click());
1272 let painted =
1273 egui::Rect::from_center_size(rect.center(), size * scale);
1274 egui::Image::new(egui::load::SizedTexture::new(texture.id(), size * scale))
1275 .paint_at(ui, painted);
1276 if response.clicked() {
1277 self.emit(id, "click", String::new(), 0.0);
1278 }
1279 return;
1280 }
1281
1282 let max_height = props.num("max-height", 240.0) as f32;
1283 let avail = if max_width > 0.0 {
1284 max_width.min(ui.available_width())
1285 } else {
1286 ui.available_width()
1287 };
1288 let scale = (avail / size.x).min(max_height / size.y).min(1.0);
1289 // Clickable whether or not the caller listens: the tree does
1290 // not know which nodes have handlers, and an unheard event
1291 // costs a queue slot.
1292 let response = ui
1293 .add(
1294 egui::Image::new(egui::load::SizedTexture::new(texture.id(), size * scale))
1295 .corner_radius(theme.spacing.radius_sm)
1296 .sense(egui::Sense::click()),
1297 )
1298 .on_hover_cursor(egui::CursorIcon::PointingHand);
1299 if response.clicked() {
1300 self.emit(id, "click", String::new(), 0.0);
1301 }
1302 }
1303
1304 Tag::Spinner => {
1305 ui.horizontal(|ui| {
1306 ui.add(egui::Spinner::new());
1307 if !props.label().is_empty() {
1308 vidya_core::body(ui, theme, props.label());
1309 }
1310 });
1311 }
1312 }
1313 }
1314
1315 /// Wrap `add` in the node's `:margin`, when it has one.
1316 fn with_margin(&mut self, props: &Props, ui: &mut Ui, add: impl FnOnce(&mut Self, &mut Ui)) {
1317 // `:margin` sets all four sides; `:margin-top` and its siblings say
1318 // otherwise for one of them. A row that sits at the bottom of a screen
1319 // wants its space above it, not under it, and that is not a thing a
1320 // single number can express.
1321 let side = |key: &str| {
1322 props.num(key, props.num("margin", 0.0)).clamp(0.0, 127.0) as i8
1323 };
1324 let margin = Margin {
1325 left: side("margin-left"),
1326 right: side("margin-right"),
1327 top: side("margin-top"),
1328 bottom: side("margin-bottom"),
1329 };
1330 if margin == Margin::ZERO {
1331 add(self, ui);
1332 return;
1333 }
1334 egui::Frame::new()
1335 .inner_margin(margin)
1336 .show(ui, |ui| add(self, ui));
1337 }
1338}
1339
1340/// Typed reads over a node's prop map, with the defaults each widget wants.
1341struct Props(HashMap<String, Value>);
1342
1343impl Props {
1344 fn str(&self, key: &str) -> &str {
1345 match self.0.get(key) {
1346 Some(Value::Str(s)) => s,
1347 _ => "",
1348 }
1349 }
1350
1351 fn num(&self, key: &str, default: f64) -> f64 {
1352 match self.0.get(key) {
1353 Some(Value::Num(n)) => *n,
1354 Some(Value::Bool(b)) => {
1355 if *b {
1356 1.0
1357 } else {
1358 0.0
1359 }
1360 }
1361 _ => default,
1362 }
1363 }
1364
1365 fn bool(&self, key: &str, default: bool) -> bool {
1366 match self.0.get(key) {
1367 Some(Value::Bool(b)) => *b,
1368 Some(Value::Num(n)) => *n != 0.0,
1369 _ => default,
1370 }
1371 }
1372
1373 /// `:label` is the family's name for a widget's text; `:text` is what a
1374 /// label is also allowed to use (and what an entry always uses).
1375 fn label(&self) -> &str {
1376 let label = self.str("label");
1377 if label.is_empty() {
1378 self.str("text")
1379 } else {
1380 label
1381 }
1382 }
1383}
1384
1385#[cfg(test)]
1386mod tests {
1387 use super::*;
1388
1389 fn kids(tree: &Tree, id: u32) -> Vec<u32> {
1390 tree.slot(id)
1391 .map(|n| n.children.clone())
1392 .unwrap_or_default()
1393 }
1394
1395 #[test]
1396 fn root_exists_and_is_a_window() {
1397 let tree = Tree::default();
1398 assert!(tree.exists(tree.root()));
1399 assert_eq!(tree.slot(tree.root()).unwrap().tag, Tag::Window);
1400 }
1401
1402 #[test]
1403 fn append_parents_once_even_when_reparenting() {
1404 let mut tree = Tree::default();
1405 let a = tree.new_node("vbox");
1406 let b = tree.new_node("hbox");
1407 let leaf = tree.new_node("label");
1408 tree.append(tree.root(), a);
1409 tree.append(tree.root(), b);
1410
1411 tree.append(a, leaf);
1412 tree.append(b, leaf);
1413 assert_eq!(kids(&tree, a), vec![]);
1414 assert_eq!(kids(&tree, b), vec![leaf]);
1415 }
1416
1417 #[test]
1418 fn a_cycle_is_refused() {
1419 let mut tree = Tree::default();
1420 let outer = tree.new_node("vbox");
1421 let inner = tree.new_node("vbox");
1422 tree.append(tree.root(), outer);
1423 tree.append(outer, inner);
1424 assert!(!tree.append(inner, outer));
1425 assert_eq!(kids(&tree, inner), vec![]);
1426 }
1427
1428 #[test]
1429 fn remove_frees_the_whole_subtree_and_reuses_slots() {
1430 let mut tree = Tree::default();
1431 let parent = tree.new_node("vbox");
1432 let child = tree.new_node("label");
1433 tree.append(tree.root(), parent);
1434 tree.append(parent, child);
1435
1436 tree.remove(tree.root(), parent);
1437 assert!(!tree.exists(parent));
1438 assert!(!tree.exists(child));
1439 assert_eq!(tree.new_node("label"), child);
1440 }
1441
1442 #[test]
1443 fn remove_ignores_a_child_of_someone_else() {
1444 let mut tree = Tree::default();
1445 let a = tree.new_node("vbox");
1446 let b = tree.new_node("vbox");
1447 let leaf = tree.new_node("label");
1448 tree.append(tree.root(), a);
1449 tree.append(tree.root(), b);
1450 tree.append(a, leaf);
1451
1452 tree.remove(b, leaf);
1453 assert!(tree.exists(leaf));
1454 assert_eq!(kids(&tree, a), vec![leaf]);
1455 }
1456
1457 #[test]
1458 fn insert_after_reorders_in_both_directions() {
1459 let mut tree = Tree::default();
1460 let parent = tree.new_node("vbox");
1461 tree.append(tree.root(), parent);
1462 let a = tree.new_node("label");
1463 let b = tree.new_node("label");
1464 let c = tree.new_node("label");
1465 for id in [a, b, c] {
1466 tree.append(parent, id);
1467 }
1468
1469 // Move a forward, past two siblings.
1470 assert!(tree.insert_after(parent, a, c));
1471 assert_eq!(kids(&tree, parent), vec![b, c, a]);
1472 // And back to the front.
1473 assert!(tree.insert_after(parent, a, 0));
1474 assert_eq!(kids(&tree, parent), vec![a, b, c]);
1475 // A no-op move keeps the order it already had.
1476 assert!(tree.insert_after(parent, b, a));
1477 assert_eq!(kids(&tree, parent), vec![a, b, c]);
1478 }
1479
1480 #[test]
1481 fn replace_swaps_in_place_and_drops_the_old_node() {
1482 let mut tree = Tree::default();
1483 let parent = tree.new_node("vbox");
1484 tree.append(tree.root(), parent);
1485 let a = tree.new_node("label");
1486 let b = tree.new_node("label");
1487 let c = tree.new_node("button");
1488 tree.append(parent, a);
1489 tree.append(parent, b);
1490
1491 assert!(tree.replace(parent, a, c));
1492 assert_eq!(kids(&tree, parent), vec![c, b]);
1493 assert!(!tree.exists(a));
1494 }
1495
1496 #[test]
1497 fn props_round_trip_and_clear() {
1498 let mut tree = Tree::default();
1499 let id = tree.new_node("button");
1500 tree.set(id, "label", Value::Str("Save".into()));
1501 tree.set(id, "value", Value::Num(0.5));
1502 tree.set(id, "active", Value::Bool(true));
1503 assert_eq!(tree.get(id, "label"), Some(&Value::Str("Save".into())));
1504 assert_eq!(tree.get(id, "value"), Some(&Value::Num(0.5)));
1505 assert_eq!(tree.get(id, "active"), Some(&Value::Bool(true)));
1506
1507 tree.clear_props(id);
1508 assert_eq!(tree.get(id, "label"), None);
1509 }
1510
1511 #[test]
1512 fn events_drain_in_order_and_skip_removed_nodes() {
1513 let mut tree = Tree::default();
1514 let a = tree.new_node("button");
1515 let b = tree.new_node("button");
1516 tree.append(tree.root(), a);
1517 tree.append(tree.root(), b);
1518 tree.emit(a, "click", String::new(), 0.0);
1519 tree.emit(b, "click", String::new(), 0.0);
1520
1521 // Dropping `a` must drop the event still queued against it, or it would
1522 // be routed to a handler the caller has already forgotten.
1523 tree.remove(tree.root(), a);
1524 assert!(tree.poll());
1525 assert_eq!(tree.current().unwrap().node, b);
1526 assert!(!tree.poll());
1527 assert!(tree.current().is_none());
1528 }
1529
1530 #[test]
1531 fn unknown_tags_are_kept_as_boxes() {
1532 let mut tree = Tree::default();
1533 let id = tree.new_node("carousel");
1534 assert!(tree.exists(id));
1535 assert_eq!(tree.slot(id).unwrap().tag, Tag::Unknown("carousel".to_owned()));
1536 }
1537 #[test]
1538 fn dump_is_hiccup_of_what_the_tree_holds() {
1539 let mut tree = Tree::default();
1540 let root = tree.new_node("vbox");
1541 tree.set(root, "spacing", Value::Num(8.0));
1542 tree.set(root, "orientation", Value::Str("vertical".to_owned()));
1543 let button = tree.new_node("button");
1544 tree.set(button, "label", Value::Str("go".to_owned()));
1545 tree.set(button, "sensitive", Value::Bool(false));
1546 tree.append(root, button);
1547
1548 assert_eq!(
1549 tree.dump(root),
1550 "[:box {:orientation \"vertical\" :spacing 8}\n \
1551 [:button {:label \"go\" :sensitive false}]]"
1552 );
1553 }
1554
1555 #[test]
1556 fn dump_keeps_an_unknown_tag_and_escapes_a_string() {
1557 let mut tree = Tree::default();
1558 let id = tree.new_node("carousel");
1559 tree.set(id, "label", Value::Str("a \"quote\"\nand a line".to_owned()));
1560 assert_eq!(
1561 tree.dump(id),
1562 "[:carousel {:label \"a \\\"quote\\\"\\nand a line\"}]"
1563 );
1564 assert_eq!(tree.dump(9999), "nil");
1565 }
1566
1567 #[test]
1568 fn a_frame_is_kept_for_the_paint_that_will_upload_it() {
1569 let mut tree = Tree::default();
1570 assert!(tree.set_frame("nandi", 2, 2, &[0u8; 16]));
1571 assert!(tree.feeds["nandi"].pending.is_some());
1572
1573 // The newest frame is the only one worth painting: a second one
1574 // arriving before the first was drawn replaces it rather than queuing.
1575 assert!(tree.set_frame("nandi", 2, 2, &[7u8; 16]));
1576 let pending = tree.feeds["nandi"].pending.as_ref().unwrap();
1577 assert_eq!(pending.size, [2, 2]);
1578 assert_eq!(tree.feeds.len(), 1);
1579 }
1580
1581 #[test]
1582 fn a_frame_that_does_not_match_its_dimensions_is_refused() {
1583 let mut tree = Tree::default();
1584 // Short of 2x2x4 — a capture path that changed resolution mid-stream
1585 // would otherwise paint the tail of the old buffer as the new one.
1586 assert!(!tree.set_frame("nandi", 2, 2, &[0u8; 15]));
1587 assert!(!tree.set_frame("nandi", 0, 2, &[]));
1588 assert!(!tree.set_frame("", 2, 2, &[0u8; 16]));
1589 assert!(tree.feeds.is_empty());
1590 }
1591
1592 #[test]
1593 fn dropping_a_feed_forgets_it() {
1594 let mut tree = Tree::default();
1595 tree.set_frame("nandi", 1, 1, &[0u8; 4]);
1596 assert!(tree.drop_frame("nandi"));
1597 assert!(!tree.drop_frame("nandi"));
1598 assert!(tree.feeds.is_empty());
1599 }
1600}