1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
|
//! A retained node tree, painted into a character grid.
//!
//! The same arena glimmer's reconciler expects everywhere else: nodes are
//! integer handles, `create` / `apply-props!` / `append-child!` mutate them,
//! and nothing is drawn until the frame call walks the whole thing at once.
//! Interactions come back as a queue the caller drains, because a jolt closure
//! cannot be a callback down here — identity crosses the boundary instead.
//!
//! This module knows nothing about terminals. It is the data; [`crate::layout`]
//! measures it and [`crate::paint`] draws it.
use std::collections::{HashMap, VecDeque};
/// A prop value: the three types the ABI can carry, which is all glimmer needs.
/// Keywords and colours arrive as strings, numbers as doubles, flags as ints.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
Str(String),
Num(f64),
Bool(bool),
}
/// What a node renders as.
///
/// An unknown tag is kept rather than refused — it paints as a vertical box, so
/// a component written against a tag this backend has not grown yet still shows
/// its children instead of nothing.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Tag {
Window,
Box,
Frame,
Scroll,
Overlay,
Label,
Title,
DimLabel,
Button,
CheckButton,
Entry,
Separator,
Spacer,
Listbox,
Progress,
Spinner,
Unknown(String),
}
impl Default for Tag {
fn default() -> Self {
Self::Unknown(String::new())
}
}
impl Tag {
fn parse(name: &str) -> Self {
match name {
"window" => Self::Window,
"box" | "hbox" | "vbox" => Self::Box,
"frame" => Self::Frame,
"scroll" => Self::Scroll,
"overlay" => Self::Overlay,
"label" => Self::Label,
"title" | "title-2" => Self::Title,
"dim-label" => Self::DimLabel,
"button" => Self::Button,
"checkbutton" | "checkbox" => Self::CheckButton,
"entry" => Self::Entry,
"separator" => Self::Separator,
"spacer" | "gap" => Self::Spacer,
"listbox" => Self::Listbox,
"progress" => Self::Progress,
"spinner" => Self::Spinner,
other => Self::Unknown(other.to_owned()),
}
}
/// The canonical name: `hbox` and `vbox` are one node, so both answer
/// `box` and carry their orientation in a prop.
pub fn name(&self) -> &str {
match self {
Self::Window => "window",
Self::Box => "box",
Self::Frame => "frame",
Self::Scroll => "scroll",
Self::Overlay => "overlay",
Self::Label => "label",
Self::Title => "title",
Self::DimLabel => "dim-label",
Self::Button => "button",
Self::CheckButton => "checkbutton",
Self::Entry => "entry",
Self::Separator => "separator",
Self::Spacer => "spacer",
Self::Listbox => "listbox",
Self::Progress => "progress",
Self::Spinner => "spinner",
Self::Unknown(name) => name,
}
}
/// Whether the focus ring stops here. A container never takes focus of its
/// own; a control that does nothing with a key does not either.
pub fn focusable(&self) -> bool {
matches!(
self,
Self::Button | Self::CheckButton | Self::Entry | Self::Listbox
)
}
}
/// One interaction, waiting to be drained by the caller. Names are glimmer's
/// handler props with the `on-` dropped.
#[derive(Clone, Debug, PartialEq)]
pub struct Event {
pub node: u32,
pub name: &'static str,
pub text: String,
pub num: f64,
}
#[derive(Clone, Debug, Default)]
struct Node {
tag: Tag,
props: HashMap<String, Value>,
children: Vec<u32>,
/// 0 when unparented. The root's parent is 0 as well, which is what stops
/// the ancestor walk in [`Tree::would_cycle`].
parent: u32,
}
/// A node's props, copied out for the duration of one measure or paint.
///
/// Reading them through this rather than the map means a missing prop and a
/// prop of the wrong type answer the same thing: the default. Nothing a caller
/// can write should be able to make a widget vanish.
#[derive(Clone, Debug, Default)]
pub struct Props(pub HashMap<String, Value>);
impl Props {
pub fn str(&self, key: &str) -> &str {
match self.0.get(key) {
Some(Value::Str(s)) => s,
_ => "",
}
}
pub fn num(&self, key: &str, fallback: f64) -> f64 {
match self.0.get(key) {
Some(Value::Num(n)) => *n,
Some(Value::Bool(b)) => {
if *b {
1.0
} else {
0.0
}
}
_ => fallback,
}
}
/// A count of cells. Negative and absurd values are clamped rather than
/// cast, since `as u16` on a negative double is a silent 0 or 65535.
pub fn cells(&self, key: &str, fallback: u16) -> u16 {
match self.0.get(key) {
Some(Value::Num(n)) if n.is_finite() => n.clamp(0.0, u16::MAX as f64) as u16,
_ => fallback,
}
}
pub fn bool(&self, key: &str, fallback: bool) -> bool {
match self.0.get(key) {
Some(Value::Bool(b)) => *b,
Some(Value::Num(n)) => *n != 0.0,
Some(Value::Str(s)) => s == "true",
_ => fallback,
}
}
pub fn has(&self, key: &str) -> bool {
self.0.contains_key(key)
}
/// The text a widget shows. `:label` and `:text` are the same prop to every
/// glimmer backend; whichever the caller wrote is the one that shows.
pub fn label(&self) -> &str {
if self.has("label") {
self.str("label")
} else {
self.str("text")
}
}
}
/// One prop value as EDN. Whole numbers print without a trailing `.0`: every
/// number crossed the boundary as a double, and `{:spacing 8}` reads better
/// than `{:spacing 8.0}`.
fn write_value(value: &Value, out: &mut String) {
match value {
Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Value::Num(n) => {
if n.is_finite() && n.fract() == 0.0 && n.abs() < 1e15 {
out.push_str(&format!("{}", *n as i64));
} else if n.is_finite() {
out.push_str(&format!("{n}"));
} else {
// EDN has no infinity or NaN literal; say nil rather than emit
// something no reader will take.
out.push_str("nil");
}
}
Value::Str(text) => {
out.push('"');
for c in text.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
_ => out.push(c),
}
}
out.push('"');
}
}
}
pub struct Tree {
/// Index 0 is never handed out: 0 is "no node" throughout the ABI.
nodes: Vec<Option<Node>>,
free: Vec<u32>,
root: u32,
pending: VecDeque<Event>,
current: Option<Event>,
}
impl Default for Tree {
fn default() -> Self {
Self::new()
}
}
impl Tree {
pub fn new() -> Self {
let mut tree = Self {
nodes: vec![None],
free: Vec::new(),
root: 0,
pending: VecDeque::new(),
current: None,
};
tree.root = tree.new_node("window");
tree
}
pub fn root(&self) -> u32 {
self.root
}
fn slot(&self, id: u32) -> Option<&Node> {
self.nodes.get(id as usize).and_then(|n| n.as_ref())
}
fn slot_mut(&mut self, id: u32) -> Option<&mut Node> {
self.nodes.get_mut(id as usize).and_then(|n| n.as_mut())
}
pub fn exists(&self, id: u32) -> bool {
self.slot(id).is_some()
}
pub fn new_node(&mut self, tag: &str) -> u32 {
let node = Node {
tag: Tag::parse(tag),
..Node::default()
};
match self.free.pop() {
Some(id) => {
self.nodes[id as usize] = Some(node);
id
}
None => {
self.nodes.push(Some(node));
(self.nodes.len() - 1) as u32
}
}
}
/// Free `id` and everything under it. The root is refused: the window node
/// is the one thing a caller cannot drop out from under itself.
pub fn free_node(&mut self, id: u32) {
if id == self.root || !self.exists(id) {
return;
}
let parent = self.slot(id).map(|n| n.parent).unwrap_or(0);
if parent != 0 {
if let Some(node) = self.slot_mut(parent) {
node.children.retain(|c| *c != id);
}
}
self.free_subtree(id);
}
fn free_subtree(&mut self, id: u32) {
let children = self
.slot(id)
.map(|n| n.children.clone())
.unwrap_or_default();
for child in children {
self.free_subtree(child);
}
if self.nodes[id as usize].take().is_some() {
self.free.push(id);
}
// An event queued against a node that has since gone would be routed to
// a handler the reconciler has already dropped. Drop it here instead.
self.pending.retain(|e| e.node != id);
}
/// Whether making `child` a child of `parent` would make a loop — `child`
/// being `parent` or one of its ancestors.
fn would_cycle(&self, parent: u32, child: u32) -> bool {
let mut at = parent;
while at != 0 {
if at == child {
return true;
}
at = match self.slot(at) {
Some(node) => node.parent,
None => return false,
};
}
false
}
fn unparent(&mut self, child: u32) {
let parent = self.slot(child).map(|n| n.parent).unwrap_or(0);
if parent != 0 {
if let Some(node) = self.slot_mut(parent) {
node.children.retain(|c| *c != child);
}
}
if let Some(node) = self.slot_mut(child) {
node.parent = 0;
}
}
pub fn append(&mut self, parent: u32, child: u32) -> bool {
if !self.exists(parent) || !self.exists(child) || self.would_cycle(parent, child) {
return false;
}
self.unparent(child);
self.slot_mut(parent).unwrap().children.push(child);
self.slot_mut(child).unwrap().parent = parent;
true
}
/// Unparent *and* free `child`, which is what the reconciler means by
/// remove: a node it has taken out of the tree is a node it has dropped.
pub fn remove(&mut self, parent: u32, child: u32) {
if self.slot(child).map(|n| n.parent) == Some(parent) {
self.free_node(child);
}
}
/// Move `child` after `sibling`; `sibling` 0 means the first position.
pub fn insert_after(&mut self, parent: u32, child: u32, sibling: u32) -> bool {
if !self.exists(parent) || !self.exists(child) || self.would_cycle(parent, child) {
return false;
}
if sibling != 0 && self.slot(sibling).map(|n| n.parent) != Some(parent) {
return false;
}
self.unparent(child);
let at = match sibling {
0 => 0,
_ => {
let children = &self.slot(parent).unwrap().children;
children
.iter()
.position(|c| *c == sibling)
.map_or(0, |i| i + 1)
}
};
self.slot_mut(parent).unwrap().children.insert(at, child);
self.slot_mut(child).unwrap().parent = parent;
true
}
/// Put `new` where `old` was, and free `old`.
pub fn replace(&mut self, parent: u32, old: u32, new: u32) -> bool {
if self.slot(old).map(|n| n.parent) != Some(parent) || !self.exists(new) {
return false;
}
if self.would_cycle(parent, new) {
return false;
}
self.unparent(new);
let at = self
.slot(parent)
.and_then(|n| n.children.iter().position(|c| *c == old));
let Some(at) = at else { return false };
self.slot_mut(parent).unwrap().children[at] = new;
self.slot_mut(new).unwrap().parent = parent;
if let Some(node) = self.slot_mut(old) {
node.parent = 0;
}
self.free_subtree(old);
true
}
// ── reading it back ─────────────────────────────────────────────────────
pub fn tag(&self, id: u32) -> Tag {
self.slot(id).map(|n| n.tag.clone()).unwrap_or_default()
}
pub fn tag_name(&self, id: u32) -> &str {
self.slot(id).map_or("", |n| n.tag.name())
}
pub fn children(&self, id: u32) -> Vec<u32> {
self.slot(id)
.map(|n| n.children.clone())
.unwrap_or_default()
}
pub fn child_count(&self, id: u32) -> usize {
self.slot(id).map_or(0, |n| n.children.len())
}
pub fn child_at(&self, id: u32, index: usize) -> u32 {
self.slot(id)
.and_then(|n| n.children.get(index).copied())
.unwrap_or(0)
}
pub fn parent(&self, id: u32) -> u32 {
self.slot(id).map_or(0, |n| n.parent)
}
pub fn props(&self, id: u32) -> Props {
Props(self.slot(id).map(|n| n.props.clone()).unwrap_or_default())
}
pub fn set(&mut self, id: u32, key: &str, value: Value) {
if let Some(node) = self.slot_mut(id) {
node.props.insert(key.to_owned(), value);
}
}
pub fn clear_props(&mut self, id: u32) {
if let Some(node) = self.slot_mut(id) {
node.props.clear();
}
}
pub fn get(&self, id: u32, key: &str) -> Option<&Value> {
self.slot(id).and_then(|n| n.props.get(key))
}
/// The subtree at `id` as pretty-printed hiccup — what the tree *is*, read
/// back from the arena, rather than what a component meant to build.
///
/// Props are sorted, so two dumps of the same tree compare as text.
pub fn dump(&self, id: u32) -> String {
let mut out = String::new();
self.dump_into(id, 0, &mut out);
out
}
fn dump_into(&self, id: u32, depth: usize, out: &mut String) {
let Some(node) = self.slot(id) else {
out.push_str("nil");
return;
};
let indent = " ".repeat(depth);
out.push_str("[:");
out.push_str(node.tag.name());
let mut keys: Vec<&String> = node.props.keys().collect();
keys.sort();
out.push_str(" {");
for (i, key) in keys.iter().enumerate() {
if i > 0 {
out.push(' ');
}
out.push(':');
out.push_str(key);
out.push(' ');
write_value(&node.props[*key], out);
}
out.push('}');
for child in &node.children {
out.push('\n');
out.push_str(&indent);
out.push_str(" ");
self.dump_into(*child, depth + 1, out);
}
out.push(']');
}
// ── events ──────────────────────────────────────────────────────────────
pub fn emit(&mut self, node: u32, name: &'static str, text: String, num: f64) {
self.pending.push_back(Event {
node,
name,
text,
num,
});
}
/// Dequeue one event into the accessor slot. False when the queue is empty.
pub fn poll(&mut self) -> bool {
self.current = self.pending.pop_front();
self.current.is_some()
}
pub fn current(&self) -> Option<&Event> {
self.current.as_ref()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn tree_with_button() -> (Tree, u32) {
let mut tree = Tree::new();
let button = tree.new_node("button");
tree.set(button, "label", Value::Str("go".into()));
let root = tree.root();
tree.append(root, button);
(tree, button)
}
#[test]
fn a_dump_is_the_tree_as_hiccup_with_sorted_props() {
let (mut tree, button) = tree_with_button();
tree.set(button, "kind", Value::Str("primary".into()));
assert_eq!(
tree.dump(tree.root()),
"[:window {}\n [:button {:kind \"primary\" :label \"go\"}]]"
);
}
#[test]
fn hbox_and_vbox_are_one_node() {
let mut tree = Tree::new();
let h = tree.new_node("hbox");
let v = tree.new_node("vbox");
assert_eq!(tree.tag_name(h), "box");
assert_eq!(tree.tag_name(v), "box");
}
#[test]
fn an_unknown_tag_keeps_its_name() {
let mut tree = Tree::new();
let node = tree.new_node("sparkline");
assert_eq!(tree.tag_name(node), "sparkline");
assert_eq!(tree.tag(node), Tag::Unknown("sparkline".into()));
}
#[test]
fn removing_a_node_frees_its_subtree_and_reuses_the_handles() {
let mut tree = Tree::new();
let outer = tree.new_node("vbox");
let inner = tree.new_node("label");
tree.append(outer, inner);
tree.append(tree.root(), outer);
tree.remove(tree.root(), outer);
assert!(!tree.exists(outer));
assert!(!tree.exists(inner));
assert_eq!(tree.child_count(tree.root()), 0);
// The arena hands the slots back out rather than growing forever.
assert!([outer, inner].contains(&tree.new_node("label")));
}
#[test]
fn a_node_cannot_become_its_own_ancestor() {
let mut tree = Tree::new();
let outer = tree.new_node("vbox");
let inner = tree.new_node("vbox");
tree.append(outer, inner);
assert!(!tree.append(inner, outer));
assert_eq!(tree.parent(outer), 0);
}
#[test]
fn insert_after_zero_is_the_first_position() {
let mut tree = Tree::new();
let (a, b, c) = (
tree.new_node("label"),
tree.new_node("label"),
tree.new_node("label"),
);
let root = tree.root();
tree.append(root, a);
tree.append(root, b);
tree.insert_after(root, c, 0);
assert_eq!(tree.children(root), vec![c, a, b]);
tree.insert_after(root, c, a);
assert_eq!(tree.children(root), vec![a, c, b]);
}
#[test]
fn replace_keeps_the_position_and_frees_the_old_node() {
let mut tree = Tree::new();
let root = tree.root();
let (a, b) = (tree.new_node("label"), tree.new_node("label"));
tree.append(root, a);
tree.append(root, b);
let fresh = tree.new_node("button");
assert!(tree.replace(root, a, fresh));
assert_eq!(tree.children(root), vec![fresh, b]);
assert!(!tree.exists(a));
}
#[test]
fn the_root_cannot_be_freed() {
let mut tree = Tree::new();
let root = tree.root();
tree.free_node(root);
assert!(tree.exists(root));
}
#[test]
fn an_event_for_a_freed_node_never_reaches_the_caller() {
let (mut tree, button) = tree_with_button();
tree.emit(button, "click", String::new(), 0.0);
tree.remove(tree.root(), button);
assert!(!tree.poll());
}
#[test]
fn props_of_the_wrong_type_read_as_the_default() {
let mut tree = Tree::new();
let node = tree.new_node("progress");
tree.set(node, "value", Value::Str("lots".into()));
let props = tree.props(node);
assert_eq!(props.num("value", 0.5), 0.5);
assert_eq!(props.cells("width-request", 7), 7);
}
#[test]
fn label_and_text_are_the_same_prop() {
let mut tree = Tree::new();
let node = tree.new_node("label");
tree.set(node, "text", Value::Str("hello".into()));
assert_eq!(tree.props(node).label(), "hello");
tree.set(node, "label", Value::Str("hi".into()));
assert_eq!(tree.props(node).label(), "hi");
}
}
|