nandi/jolt-nativepublic Fork 0
42dabb0835e3d1aded9830f8dda2fb4ecf550ca0
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 · 1614 lines · 66.5 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 });
Catch up with vidya c90f8af nandi 20d ago818 } else if props.bool("wrap", true) {
Bring vidya in cfd3e36 nandi 20d ago819 ui.horizontal_wrapped(|ui| {
820 ui.spacing_mut().item_spacing = axis;
821 tree.paint_children(id, ui, theme);
Catch up with vidya c90f8af nandi 20d ago822 });
823 } else {
824 // `:wrap false` for a row whose children are
825 // columns rather than controls. A wrapped row moves
826 // a child that does not fit onto a line below,
827 // which is right for buttons beside a message and
828 // ruinous for the second half of a split: a pane
829 // asking for a few points more than are left is
830 // painted under the first one, off the bottom of
831 // the window, and reads as a pane that renders
832 // nothing at all.
833 ui.horizontal(|ui| {
834 ui.spacing_mut().item_spacing = axis;
835 tree.paint_children(id, ui, theme);
Bring vidya in cfd3e36 nandi 20d ago836 });
837 }
838 } else {
839 // `:align :center` puts a column's children on the
840 // middle of the width rather than against its left
841 // edge — what a picture on a screen of its own wants,
842 // and nothing a column of text ever does.
843 let cross = if props.str("align") == "center" {
844 Align::Center
845 } else {
846 Align::Min
847 };
848 ui.with_layout(Layout::top_down(cross), |ui| {
849 ui.spacing_mut().item_spacing = axis;
850 tree.paint_children(id, ui, theme);
851 });
852 }
853 });
854 }
855
856 // A scrolling column with page padding, optionally centred at a
857 // maximum width — the shell most Vidya apps put everything inside.
858 Tag::Page => {
859 let max_width = props.num("max-width", 0.0) as f32;
860 let pad = theme.spacing.page;
861 egui::ScrollArea::vertical()
862 .auto_shrink([false, false])
863 .show(ui, |ui| {
864 egui::Frame::new()
865 .inner_margin(Margin::same(pad.clamp(0.0, 127.0) as i8))
866 .show(ui, |ui| {
867 let avail = ui.available_width();
868 let width = if max_width > 0.0 {
869 max_width.min(avail)
870 } else {
871 avail
872 };
873 let indent = ((avail - width) * 0.5).max(0.0);
874 ui.horizontal(|ui| {
875 ui.add_space(indent);
876 ui.allocate_ui_with_layout(
877 Vec2::new(width, 0.0),
878 Layout::top_down(Align::Min),
879 |ui| {
880 ui.set_min_width(width);
881 ui.set_max_width(width);
882 vidya_core::vstack(ui, theme, |ui| {
883 self.paint_children(id, ui, theme);
884 });
885 },
886 );
887 });
888 });
889 });
890 }
891
892 Tag::Scroll => {
893 let area = match props.str("orientation") {
894 "horizontal" => egui::ScrollArea::horizontal(),
895 "both" => egui::ScrollArea::both(),
896 _ => egui::ScrollArea::vertical(),
897 };
898 // Without a bound a scroll area takes every point left in its
899 // parent, so anything after it — a compose bar under a message
900 // list — is pushed off the bottom. `:max-height` bounds it
901 // outright; `:reserve` bounds it by what it must leave behind,
902 // which is what a caller actually knows: the compose bar's
903 // height, not the window's.
904 let area = {
905 let reserve = props.num("reserve", 0.0) as f32;
906 let max_height = if reserve > 0.0 {
907 // Clamped against the clip rect as well as the layout's
908 // own idea of what is left: on Android the two differ
909 // once the soft keyboard takes the bottom of the
910 // screen, and it is the visible one that has to win or
911 // the row below the list is pushed off under the
912 // keyboard.
913 let visible = (ui.clip_rect().bottom() - ui.cursor().top()).max(0.0);
914 (ui.available_height().min(visible) - reserve).max(0.0)
915 } else {
916 props.num("max-height", 0.0) as f32
917 };
918 if max_height > 0.0 {
919 area.max_height(max_height)
920 } else {
921 area
922 }
923 };
924 // Keyed by the node rather than by where it sits: egui derives
925 // a scroll area's id from its parent ui, so two areas that
926 // occupy the same place in the tree at different times — the
927 // message list and the picture that replaces the screen it is
928 // on — would otherwise share one offset, and the list would
929 // come back showing whatever the picture left behind.
930 //
931 // `:scroll-key` names an area that outlives its node instead.
932 // A node id is only as durable as the node: a list unmounted
933 // while another screen is up comes back as a new node, and a
934 // position keyed by that is a position thrown away. A caller
935 // that means "this same list again" says so with a name, and
936 // the reader returns to the line they left.
937 let key = {
938 let name = props.str("scroll-key");
939 if name.is_empty() {
940 Id::new(("vidya_scroll", id))
941 } else {
942 Id::new(("vidya_scroll_key", name))
943 }
944 };
945 let area = area.id_salt(key);
946 // A chat wants the newest line, not the oldest — except on a
947 // frame where something inside asked to be scrolled to. The
948 // two are the same control pulling opposite ways, and sticking
949 // wins every time it is asked, so a jump to an old message
950 // would land nowhere.
951 let sticks = props.bool("stick-to-bottom", false) && !self.wants_scroll_to(id);
952 let area = area.stick_to_bottom(sticks);
953 // `:scroll-to-bottom` is a number the caller bumps rather than
954 // a flag it sets: a flag would have to be cleared afterwards,
955 // and there is no frame in which the caller could do it. A
956 // value it has not seen before means "now".
957 let jump_key = key.with("jump");
958 let jump = props.num("scroll-to-bottom", 0.0);
959 let jumped = ui.ctx().data(|d| d.get_temp::<f64>(jump_key));
960 let jump_now = jump > 0.0 && jumped != Some(jump);
961 // The end is last frame's own maximum offset, kept for exactly
962 // this. Not f32::MAX — egui subtracts the viewport from what it
963 // is given, and MAX minus anything is still MAX, an offset the
964 // content can never reach: the area painted nothing and stayed
965 // that way. Not `scroll_to_rect` either, which a scroll area
966 // that has been scrolled away from ignores here.
967 let end_offset_key = key.with("end_offset");
968 let area = if jump_now {
969 ui.ctx().data_mut(|d| d.insert_temp(jump_key, jump));
970 let end = ui
971 .ctx()
972 .data(|d| d.get_temp::<f32>(end_offset_key))
973 .unwrap_or(0.0);
974 area.vertical_scroll_offset(end)
975 } else {
976 area
977 };
978 // Hold the content to the viewport's width, as `:page` does,
979 // so a wrapping child wraps at the visible edge.
980 let viewport_width = ui.available_width();
981 let output = area.auto_shrink([false, false]).show(ui, |ui| {
982 ui.set_max_width(viewport_width);
983 self.paint_children(id, ui, theme);
984 // The end asked for by scrolling to it, not by setting an
985 // offset of f32::MAX: egui subtracts the viewport from
986 // whatever it is given, and MAX minus anything is still
987 // MAX — an offset the content can never reach, which left
988 // the area painting nothing at all.
989
990 });
991
992 // Say when the view leaves the end and when it comes back, so
993 // a caller can offer the way back. Reported on change only: the
994 // position itself changes every frame of a scroll, and an event
995 // a frame is not news.
996 // Within a line of the end counts as the end, and content
997 // shorter than the viewport is always at it.
998 let max_offset = (output.content_size.y - output.inner_rect.height()).max(0.0);
999 // What `:scroll-to-bottom` will aim at next time it is asked.
1000 ui.ctx()
1001 .data_mut(|d| d.insert_temp(end_offset_key, max_offset));
1002 let at_end = output.state.offset.y >= max_offset - 24.0;
1003 // Reaching the end is reported at once; leaving it has to hold
1004 // for a few frames first. A burst of arriving messages grows
1005 // the content faster than the offset follows it, and reporting
1006 // that honestly would blink "scrolled away" whenever a channel
1007 // is busy.
1008 let end_key = key.with("at_end");
1009 let away_key = key.with("away_frames");
1010 let away_frames = ui.ctx().data(|d| d.get_temp::<u32>(away_key)).unwrap_or(0);
1011 let away_frames = if at_end { 0 } else { away_frames.saturating_add(1) };
1012 ui.ctx().data_mut(|d| d.insert_temp(away_key, away_frames));
1013
1014 let settled = if at_end {
1015 Some(true)
1016 } else if away_frames >= 3 {
1017 Some(false)
1018 } else {
1019 None
1020 };
1021 if let Some(at_end) = settled {
1022 let was_at_end = ui.ctx().data(|d| d.get_temp::<bool>(end_key));
1023 if was_at_end != Some(at_end) {
1024 ui.ctx().data_mut(|d| d.insert_temp(end_key, at_end));
1025 // Only after the first report: the opening one would
1026 // arrive before the content has a height.
1027 if was_at_end.is_some() {
1028 self.emit(
1029 id,
1030 "change",
1031 if at_end { "end" } else { "away" }.to_owned(),
1032 if at_end { 1.0 } else { 0.0 },
1033 );
1034 }
1035 }
1036 }
1037 }
1038
1039 Tag::Card => {
1040 vidya_core::card(ui, theme, |ui| self.paint_children(id, ui, theme));
1041 }
1042
1043 // A card with a heading — glimmer-tui's `:frame` label, in the
1044 // idiom this theme actually has for one.
1045 Tag::Frame => {
1046 let label = props.label();
1047 vidya_core::card(ui, theme, |ui| {
1048 if !label.is_empty() {
1049 vidya_core::title_2(ui, theme, label);
1050 }
1051 self.paint_children(id, ui, theme);
1052 });
1053 }
1054
1055 Tag::Label => vidya_core::body(ui, theme, props.label()),
1056
1057 // Body text that answers the pointer: the accent colour and the
1058 // hand cursor are the whole affordance, and the click is reported
1059 // like a button's so the caller decides what opening it means.
1060 Tag::Link => {
1061 let response = ui
1062 .add(
1063 egui::Label::new(
1064 egui::RichText::new(props.label())
1065 .size(theme.type_scale.body)
1066 .color(theme.palette.accent),
1067 )
1068 .wrap()
1069 .sense(egui::Sense::click()),
1070 )
1071 .on_hover_cursor(egui::CursorIcon::PointingHand);
1072 if response.clicked() {
1073 self.emit(id, "click", props.label().to_owned(), 0.0);
1074 }
1075 }
1076 Tag::Title => vidya_core::title(ui, theme, props.label()),
1077 Tag::Title2 => vidya_core::title_2(ui, theme, props.label()),
1078 Tag::DimLabel => vidya_core::dim_label(ui, theme, props.label()),
1079
1080 Tag::Button => {
1081 let kind = match props.str("kind") {
1082 "primary" => 1,
1083 "destructive" => 2,
1084 _ => 0,
1085 };
1086 if crate::ui::button(ui, theme, props.label(), kind) {
1087 self.emit(id, "click", String::new(), 0.0);
1088 }
1089 }
1090
1091 Tag::CheckButton => {
1092 let was = props.bool("active", false);
1093 let (now, changed) = crate::ui::checkbox(ui, theme, was, props.label());
1094 if changed {
1095 // The widget does not own the value: the new state is
1096 // written back so a component that ignores `:on-toggled`
1097 // still tracks the click, and the handler decides whether
1098 // it survives the next render of `:active`.
1099 self.set(id, "active", Value::Bool(now));
1100 self.emit(id, "toggled", String::new(), if now { 1.0 } else { 0.0 });
1101 }
1102 }
1103
1104 Tag::Entry => {
1105 let mut text = props.str("text").to_owned();
1106 let placeholder = props.str("placeholder").to_owned();
1107 let rows = props.num("rows", 4.0) as usize;
1108 let response = if props.bool("multiline", false) {
1109 vidya_core::text_field_multiline(ui, theme, &mut text, rows.max(1))
1110 } else {
1111 crate::ui::text_field(ui, theme, &mut text, &placeholder)
1112 };
1113 if text != props.str("text") {
1114 self.set(id, "text", Value::Str(text.clone()));
1115 self.emit(id, "change", text, 0.0);
1116 }
1117 if response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
1118 self.emit(id, "activate", String::new(), 0.0);
1119 }
1120 // A paste of something that is not text. egui turns Ctrl+V
1121 // into a `Paste` event carrying the clipboard's text, and a
1122 // clipboard holding a picture has none — so the keystroke
1123 // arrives as a key press with no paste behind it, and the
1124 // field would otherwise swallow it. Reported instead, for a
1125 // caller that has somewhere to put a picture; one that has not
1126 // ignores it and the keystroke stays as inert as it was.
1127 //
1128 // The clipboard is not read here: whether there is a picture
1129 // on it is answered by `vidya_clipboard_image_png`, and asking
1130 // twice would copy every pasted image for nothing.
1131 if response.has_focus() {
1132 let paste_without_text = ui.input(|i| {
1133 i.events.iter().any(|e| {
1134 matches!(
1135 e,
1136 egui::Event::Key {
1137 key: egui::Key::V,
1138 pressed: true,
1139 modifiers,
1140 ..
1141 } if modifiers.command
1142 )
1143 }) && !i
1144 .events
1145 .iter()
1146 .any(|e| matches!(e, egui::Event::Paste(_)))
1147 });
1148 if paste_without_text {
1149 self.emit(id, "paste-empty", String::new(), 0.0);
1150 }
1151 }
1152 }
1153
1154 Tag::Separator => crate::ui::separator(ui),
1155 Tag::Spacer => crate::ui::gap(ui, props.num("size", theme.spacing.md as f64) as f32),
1156 Tag::Status => crate::ui::status(ui, theme, props.label(), props.bool("live", false)),
1157
1158 Tag::Progress => {
1159 let value = props.num("value", 0.0) as f32;
1160 let mut bar = egui::ProgressBar::new(value.clamp(0.0, 1.0));
1161 if !props.label().is_empty() {
1162 bar = bar.text(props.label());
1163 }
1164 ui.add(bar);
1165 }
1166
1167 // A picture from a file the caller has already fetched. Decoded
1168 // once and kept as a texture: the tree is walked every frame, and
1169 // decoding a PNG sixty times a second is not a thing to do.
1170 // Someone's face, or the next best thing. A chat wants one column
1171 // of them down the left, so this is a fixed square whatever the
1172 // picture's own proportions are, and there is always something to
1173 // draw: a name with no picture behind it becomes its initial on a
1174 // colour of its own, which keeps the column straight and still
1175 // tells one person from another at a glance.
1176 Tag::Avatar => {
1177 let size = props.num("size", 24.0) as f32;
1178 let label = props.label().to_owned();
1179 let path = props.str("src").to_owned();
1180 let (rect, response) =
1181 ui.allocate_exact_size(Vec2::splat(size), egui::Sense::click());
1182
1183 let texture = if path.is_empty() {
1184 None
1185 } else {
1186 self.texture(ui, &path)
1187 };
1188 match texture {
1189 // A corner radius of half the side is a circle.
1190 Some(texture) => egui::Image::new(egui::load::SizedTexture::new(
1191 texture.id(),
1192 Vec2::splat(size),
1193 ))
1194 .corner_radius(size * 0.5)
1195 .paint_at(ui, rect),
1196 None => {
1197 let initial = label
1198 .trim_start_matches(['#', '&', '@', '+', '%', '~'])
1199 .chars()
1200 .next()
1201 .map(|c| c.to_uppercase().to_string())
1202 .unwrap_or_else(|| "?".to_owned());
1203 ui.painter()
1204 .circle_filled(rect.center(), size * 0.5, name_colour(&label, theme));
1205 ui.painter().text(
1206 rect.center(),
1207 Align2::CENTER_CENTER,
1208 initial,
1209 FontId::proportional((size * 0.45).max(9.0)),
1210 theme.palette.accent_fg,
1211 );
1212 }
1213 }
1214 if response.clicked() {
1215 self.emit(id, "click", label, 0.0);
1216 }
1217 }
1218
1219 // A reaction chip: the emoji drawn from the Twemoji pack rather
1220 // than set as text, so it is the colour picture people expect and
1221 // not a monochrome glyph — or, where the font has no glyph at all,
1222 // tofu. `:count` rides beside it once more than one person is on
1223 // it, and `:mine` is what marks the ones you put there yourself.
1224 Tag::Reaction => {
1225 let emoji = props.str("emoji").to_owned();
1226 let emoji = if emoji.is_empty() {
1227 props.label().to_owned()
1228 } else {
1229 emoji
1230 };
1231 let count = props.num("count", 0.0).max(0.0) as usize;
1232 let mine = props.bool("mine", false);
1233 // `:size` is the glyph's, and the pill is sized from it.
1234 let size = props.num("size", 0.0) as f32;
1235 let response = if size > 0.0 {
1236 vidya_core::reaction_chip_sized(ui, theme, &emoji, count, mine, size)
1237 } else {
1238 vidya_core::reaction_chip(ui, theme, &emoji, count, mine)
1239 };
1240 if response.clicked() {
1241 self.emit(id, "click", emoji, count as f64);
1242 }
1243 }
1244
1245 Tag::Image => {
1246 // Two sources, one tag: a `src` is a file decoded once and
1247 // cached by its path, a `feed` is live pixels pushed in under
1248 // a name (`vidya_frame_rgba`) and re-uploaded as they arrive.
1249 // Everything downstream — fit, bounds, the click — is the same
1250 // for both, which is why this is a prop and not a second tag.
1251 let feed = props.str("feed").to_owned();
1252 let path = props.str("src").to_owned();
1253 let max_width = props.num("max-width", 0.0) as f32;
1254 let texture = if !feed.is_empty() {
1255 self.feed_texture(ui, &feed)
1256 } else if !path.is_empty() {
1257 self.texture(ui, &path)
1258 } else {
1259 return;
1260 };
1261 let Some(texture) = texture else {
1262 // A file that will not decode is not worth a broken-image
1263 // glyph; the message text beside it already says what it
1264 // was meant to be. A feed that has had no frame yet is the
1265 // same: the tile appears when the first one lands.
1266 return;
1267 };
1268 let size = texture.size_vec2();
1269
1270 // `:fit` gives the picture every point of the space it has
1271 // been handed and centres it in it — a picture on a screen of
1272 // its own, rather than one in a line of chat. It is the one
1273 // case that scales *up*: a picture opened to be looked at is
1274 // meant to fill the window, and how big the window is this
1275 // frame is something only this side knows. Everywhere else the
1276 // caller's `:max-height` bounds it and nothing is enlarged
1277 // past its own pixels.
1278 if props.bool("fit", false) {
1279 let space = ui.available_size();
1280 if space.x <= 0.0 || space.y <= 0.0 || size.x <= 0.0 || size.y <= 0.0 {
1281 return;
1282 }
1283 let scale = (space.x / size.x).min(space.y / size.y);
1284 let (rect, response) =
1285 ui.allocate_exact_size(space, egui::Sense::click());
1286 let painted =
1287 egui::Rect::from_center_size(rect.center(), size * scale);
1288 egui::Image::new(egui::load::SizedTexture::new(texture.id(), size * scale))
1289 .paint_at(ui, painted);
1290 if response.clicked() {
1291 self.emit(id, "click", String::new(), 0.0);
1292 }
1293 return;
1294 }
1295
1296 let max_height = props.num("max-height", 240.0) as f32;
1297 let avail = if max_width > 0.0 {
1298 max_width.min(ui.available_width())
1299 } else {
1300 ui.available_width()
1301 };
1302 let scale = (avail / size.x).min(max_height / size.y).min(1.0);
1303 // Clickable whether or not the caller listens: the tree does
1304 // not know which nodes have handlers, and an unheard event
1305 // costs a queue slot.
1306 let response = ui
1307 .add(
1308 egui::Image::new(egui::load::SizedTexture::new(texture.id(), size * scale))
1309 .corner_radius(theme.spacing.radius_sm)
1310 .sense(egui::Sense::click()),
1311 )
1312 .on_hover_cursor(egui::CursorIcon::PointingHand);
1313 if response.clicked() {
1314 self.emit(id, "click", String::new(), 0.0);
1315 }
1316 }
1317
1318 Tag::Spinner => {
1319 ui.horizontal(|ui| {
1320 ui.add(egui::Spinner::new());
1321 if !props.label().is_empty() {
1322 vidya_core::body(ui, theme, props.label());
1323 }
1324 });
1325 }
1326 }
1327 }
1328
1329 /// Wrap `add` in the node's `:margin`, when it has one.
1330 fn with_margin(&mut self, props: &Props, ui: &mut Ui, add: impl FnOnce(&mut Self, &mut Ui)) {
1331 // `:margin` sets all four sides; `:margin-top` and its siblings say
1332 // otherwise for one of them. A row that sits at the bottom of a screen
1333 // wants its space above it, not under it, and that is not a thing a
1334 // single number can express.
1335 let side = |key: &str| {
1336 props.num(key, props.num("margin", 0.0)).clamp(0.0, 127.0) as i8
1337 };
1338 let margin = Margin {
1339 left: side("margin-left"),
1340 right: side("margin-right"),
1341 top: side("margin-top"),
1342 bottom: side("margin-bottom"),
1343 };
1344 if margin == Margin::ZERO {
1345 add(self, ui);
1346 return;
1347 }
1348 egui::Frame::new()
1349 .inner_margin(margin)
1350 .show(ui, |ui| add(self, ui));
1351 }
1352}
1353
1354/// Typed reads over a node's prop map, with the defaults each widget wants.
1355struct Props(HashMap<String, Value>);
1356
1357impl Props {
1358 fn str(&self, key: &str) -> &str {
1359 match self.0.get(key) {
1360 Some(Value::Str(s)) => s,
1361 _ => "",
1362 }
1363 }
1364
1365 fn num(&self, key: &str, default: f64) -> f64 {
1366 match self.0.get(key) {
1367 Some(Value::Num(n)) => *n,
1368 Some(Value::Bool(b)) => {
1369 if *b {
1370 1.0
1371 } else {
1372 0.0
1373 }
1374 }
1375 _ => default,
1376 }
1377 }
1378
1379 fn bool(&self, key: &str, default: bool) -> bool {
1380 match self.0.get(key) {
1381 Some(Value::Bool(b)) => *b,
1382 Some(Value::Num(n)) => *n != 0.0,
1383 _ => default,
1384 }
1385 }
1386
1387 /// `:label` is the family's name for a widget's text; `:text` is what a
1388 /// label is also allowed to use (and what an entry always uses).
1389 fn label(&self) -> &str {
1390 let label = self.str("label");
1391 if label.is_empty() {
1392 self.str("text")
1393 } else {
1394 label
1395 }
1396 }
1397}
1398
1399#[cfg(test)]
1400mod tests {
1401 use super::*;
1402
1403 fn kids(tree: &Tree, id: u32) -> Vec<u32> {
1404 tree.slot(id)
1405 .map(|n| n.children.clone())
1406 .unwrap_or_default()
1407 }
1408
1409 #[test]
1410 fn root_exists_and_is_a_window() {
1411 let tree = Tree::default();
1412 assert!(tree.exists(tree.root()));
1413 assert_eq!(tree.slot(tree.root()).unwrap().tag, Tag::Window);
1414 }
1415
1416 #[test]
1417 fn append_parents_once_even_when_reparenting() {
1418 let mut tree = Tree::default();
1419 let a = tree.new_node("vbox");
1420 let b = tree.new_node("hbox");
1421 let leaf = tree.new_node("label");
1422 tree.append(tree.root(), a);
1423 tree.append(tree.root(), b);
1424
1425 tree.append(a, leaf);
1426 tree.append(b, leaf);
1427 assert_eq!(kids(&tree, a), vec![]);
1428 assert_eq!(kids(&tree, b), vec![leaf]);
1429 }
1430
1431 #[test]
1432 fn a_cycle_is_refused() {
1433 let mut tree = Tree::default();
1434 let outer = tree.new_node("vbox");
1435 let inner = tree.new_node("vbox");
1436 tree.append(tree.root(), outer);
1437 tree.append(outer, inner);
1438 assert!(!tree.append(inner, outer));
1439 assert_eq!(kids(&tree, inner), vec![]);
1440 }
1441
1442 #[test]
1443 fn remove_frees_the_whole_subtree_and_reuses_slots() {
1444 let mut tree = Tree::default();
1445 let parent = tree.new_node("vbox");
1446 let child = tree.new_node("label");
1447 tree.append(tree.root(), parent);
1448 tree.append(parent, child);
1449
1450 tree.remove(tree.root(), parent);
1451 assert!(!tree.exists(parent));
1452 assert!(!tree.exists(child));
1453 assert_eq!(tree.new_node("label"), child);
1454 }
1455
1456 #[test]
1457 fn remove_ignores_a_child_of_someone_else() {
1458 let mut tree = Tree::default();
1459 let a = tree.new_node("vbox");
1460 let b = tree.new_node("vbox");
1461 let leaf = tree.new_node("label");
1462 tree.append(tree.root(), a);
1463 tree.append(tree.root(), b);
1464 tree.append(a, leaf);
1465
1466 tree.remove(b, leaf);
1467 assert!(tree.exists(leaf));
1468 assert_eq!(kids(&tree, a), vec![leaf]);
1469 }
1470
1471 #[test]
1472 fn insert_after_reorders_in_both_directions() {
1473 let mut tree = Tree::default();
1474 let parent = tree.new_node("vbox");
1475 tree.append(tree.root(), parent);
1476 let a = tree.new_node("label");
1477 let b = tree.new_node("label");
1478 let c = tree.new_node("label");
1479 for id in [a, b, c] {
1480 tree.append(parent, id);
1481 }
1482
1483 // Move a forward, past two siblings.
1484 assert!(tree.insert_after(parent, a, c));
1485 assert_eq!(kids(&tree, parent), vec![b, c, a]);
1486 // And back to the front.
1487 assert!(tree.insert_after(parent, a, 0));
1488 assert_eq!(kids(&tree, parent), vec![a, b, c]);
1489 // A no-op move keeps the order it already had.
1490 assert!(tree.insert_after(parent, b, a));
1491 assert_eq!(kids(&tree, parent), vec![a, b, c]);
1492 }
1493
1494 #[test]
1495 fn replace_swaps_in_place_and_drops_the_old_node() {
1496 let mut tree = Tree::default();
1497 let parent = tree.new_node("vbox");
1498 tree.append(tree.root(), parent);
1499 let a = tree.new_node("label");
1500 let b = tree.new_node("label");
1501 let c = tree.new_node("button");
1502 tree.append(parent, a);
1503 tree.append(parent, b);
1504
1505 assert!(tree.replace(parent, a, c));
1506 assert_eq!(kids(&tree, parent), vec![c, b]);
1507 assert!(!tree.exists(a));
1508 }
1509
1510 #[test]
1511 fn props_round_trip_and_clear() {
1512 let mut tree = Tree::default();
1513 let id = tree.new_node("button");
1514 tree.set(id, "label", Value::Str("Save".into()));
1515 tree.set(id, "value", Value::Num(0.5));
1516 tree.set(id, "active", Value::Bool(true));
1517 assert_eq!(tree.get(id, "label"), Some(&Value::Str("Save".into())));
1518 assert_eq!(tree.get(id, "value"), Some(&Value::Num(0.5)));
1519 assert_eq!(tree.get(id, "active"), Some(&Value::Bool(true)));
1520
1521 tree.clear_props(id);
1522 assert_eq!(tree.get(id, "label"), None);
1523 }
1524
1525 #[test]
1526 fn events_drain_in_order_and_skip_removed_nodes() {
1527 let mut tree = Tree::default();
1528 let a = tree.new_node("button");
1529 let b = tree.new_node("button");
1530 tree.append(tree.root(), a);
1531 tree.append(tree.root(), b);
1532 tree.emit(a, "click", String::new(), 0.0);
1533 tree.emit(b, "click", String::new(), 0.0);
1534
1535 // Dropping `a` must drop the event still queued against it, or it would
1536 // be routed to a handler the caller has already forgotten.
1537 tree.remove(tree.root(), a);
1538 assert!(tree.poll());
1539 assert_eq!(tree.current().unwrap().node, b);
1540 assert!(!tree.poll());
1541 assert!(tree.current().is_none());
1542 }
1543
1544 #[test]
1545 fn unknown_tags_are_kept_as_boxes() {
1546 let mut tree = Tree::default();
1547 let id = tree.new_node("carousel");
1548 assert!(tree.exists(id));
1549 assert_eq!(tree.slot(id).unwrap().tag, Tag::Unknown("carousel".to_owned()));
1550 }
1551 #[test]
1552 fn dump_is_hiccup_of_what_the_tree_holds() {
1553 let mut tree = Tree::default();
1554 let root = tree.new_node("vbox");
1555 tree.set(root, "spacing", Value::Num(8.0));
1556 tree.set(root, "orientation", Value::Str("vertical".to_owned()));
1557 let button = tree.new_node("button");
1558 tree.set(button, "label", Value::Str("go".to_owned()));
1559 tree.set(button, "sensitive", Value::Bool(false));
1560 tree.append(root, button);
1561
1562 assert_eq!(
1563 tree.dump(root),
1564 "[:box {:orientation \"vertical\" :spacing 8}\n \
1565 [:button {:label \"go\" :sensitive false}]]"
1566 );
1567 }
1568
1569 #[test]
1570 fn dump_keeps_an_unknown_tag_and_escapes_a_string() {
1571 let mut tree = Tree::default();
1572 let id = tree.new_node("carousel");
1573 tree.set(id, "label", Value::Str("a \"quote\"\nand a line".to_owned()));
1574 assert_eq!(
1575 tree.dump(id),
1576 "[:carousel {:label \"a \\\"quote\\\"\\nand a line\"}]"
1577 );
1578 assert_eq!(tree.dump(9999), "nil");
1579 }
1580
1581 #[test]
1582 fn a_frame_is_kept_for_the_paint_that_will_upload_it() {
1583 let mut tree = Tree::default();
1584 assert!(tree.set_frame("nandi", 2, 2, &[0u8; 16]));
1585 assert!(tree.feeds["nandi"].pending.is_some());
1586
1587 // The newest frame is the only one worth painting: a second one
1588 // arriving before the first was drawn replaces it rather than queuing.
1589 assert!(tree.set_frame("nandi", 2, 2, &[7u8; 16]));
1590 let pending = tree.feeds["nandi"].pending.as_ref().unwrap();
1591 assert_eq!(pending.size, [2, 2]);
1592 assert_eq!(tree.feeds.len(), 1);
1593 }
1594
1595 #[test]
1596 fn a_frame_that_does_not_match_its_dimensions_is_refused() {
1597 let mut tree = Tree::default();
1598 // Short of 2x2x4 — a capture path that changed resolution mid-stream
1599 // would otherwise paint the tail of the old buffer as the new one.
1600 assert!(!tree.set_frame("nandi", 2, 2, &[0u8; 15]));
1601 assert!(!tree.set_frame("nandi", 0, 2, &[]));
1602 assert!(!tree.set_frame("", 2, 2, &[0u8; 16]));
1603 assert!(tree.feeds.is_empty());
1604 }
1605
1606 #[test]
1607 fn dropping_a_feed_forgets_it() {
1608 let mut tree = Tree::default();
1609 tree.set_frame("nandi", 1, 1, &[0u8; 4]);
1610 assert!(tree.drop_frame("nandi"));
1611 assert!(!tree.drop_frame("nandi"));
1612 assert!(tree.feeds.is_empty());
1613 }
1614}