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