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