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