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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
//! The slot table runtime's node table and the translation of a widget attribute into
//! wire records.
//!
//! The translation is the one the Dioxus adapter's renderer applies to an `rsx!`
//! attribute: the same Modifier slots, the same owners of a shared slot, the same rule
//! that a design property at its neutral value is not sent. A widget composed here and the
//! same widget written in `rsx!` therefore send the same records, which the parity tests
//! check by comparing the trees the two build. The node table is simpler than the
//! adapter's, because a composition has no placeholders and no templates: every child is
//! a node, placed after the one composed before it.
use crate::protocol::{Mutation, PropertyValue, ProtocolError};
use crate::runtime::Batch;
use crate::schema::{PropertyKind, WidgetKind};
use std::collections::{HashMap, HashSet};
/// The inclusive range of design-property tags. Extension properties follow this range.
const FIRST_OPTIONAL_PROPERTY: u16 = PropertyKind::TypeRole as u16;
const LAST_OPTIONAL_PROPERTY: u16 = PropertyKind::Variant as u16;
/// The bit that tracks whether a node has ever carried a list of text runs.
///
/// Outside the range above and kept separately, because widening that range swallowed
/// values where zero means zero: a picker whose minimum really is 0 stopped sending it
/// and got the Renderer's default instead. A list of runs has no such value. Empty and
/// absent are the same state, so the first empty one is worth no record.
const SPANS_BIT: u32 = 63;
/// How many Modifier slots a node has. The slot numbers are assigned in `modifier_for`,
/// and this is one past the last of them.
const MODIFIER_SLOTS: usize = 25;
/// The first of the slots a node's shadow layers take, and how many there are.
const SHADOW_BASE: u16 = 8;
const SHADOW_LAYERS: usize = 4;
/// Bytes one shadow layer takes in the `shadows` attribute: four floats and a paint.
const SHADOW_BYTES: usize = 24;
/// Node id 0 is the "no node" sentinel: a placeholder, which draws nothing and takes no
/// slot in the Compose tree. It is also the root every top-level node is inserted under.
pub(crate) const PLACEHOLDER_NODE: u32 = 0;
/// One attribute value, as either front end hands it over.
///
/// The `rsx!` path converts `dioxus_core::AttributeValue` into this, and the slot table
/// runtime builds it directly, so the translation below never sees which one it came from.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AttrValue<'a> {
/// Unset, or set and then taken away.
None,
Text(&'a str),
Float(f64),
Int(i64),
Bool(bool),
/// An opaque run of bytes: a drawing command list or a list of text runs.
Bytes(&'a [u8]),
}
/// The Host's half of the node table, and the batch the current call is writing.
pub struct NodeWriter {
/// The batch the records go into: the one the Host writes its own records into too.
batch: Batch,
next_node_id: u32,
next_handler_id: u64,
/// Which parent each drawn node hangs under.
parents: HashMap<u32, u32>,
/// What stands under each parent, in order.
///
/// An index is read off this list rather than remembered from the Insert that put a
/// node there. Removing a sibling moves everything after it, so a remembered index is
/// only right until the next removal: a menu whose entries came and went handed the
/// next set of entries the position the old last entry had held, and they piled up
/// past the end of the list instead of taking its place.
children: HashMap<u32, Vec<u32>>,
/// Which design properties a node has actually been given, one bit per tag.
optional_props: HashMap<u32, u64>,
/// A border arrives as a width and a colour in separate attributes; this holds
/// whichever came first until the pair can be written as one modifier.
pending_borders: HashMap<u32, (Option<f32>, Option<crate::Paint>)>,
/// Which attribute last wrote each of a node's Modifier slots, or `""` for a slot
/// nothing has written.
///
/// Two things need the owner rather than a "written" bit. Clearing a slot that was
/// never written would cost a mutation on the first frame of every widget, for a
/// Modifier nobody asked for. And some slots have two attributes that can fill them,
/// `shape_role` and `corner_radius` for the shape, `padding_role` and `padding` for
/// the padding: the one left unset arrives as an empty attribute, and without the
/// owner it would clear the modifier its partner had just written, which is how a
/// rounded container came out square.
modifier_slots: HashMap<u32, [&'static str; MODIFIER_SLOTS]>,
/// Which application token each observed node was given, for reading a report back.
size_tokens: HashMap<u32, u32>,
/// Which animated values each node has been given, one bit for each of
/// `animated_alpha`, `animated_background` and `animated_offset`. The first value is
/// where the node starts; every later one is a change to animate.
animated: HashMap<u32, u8>,
/// The name the next animation this writer starts is given. Never 0.
next_animation_id: u32,
/// The `Window` nodes. Empty in a single-window application.
windows: HashSet<u32>,
/// Windows that left the tree since the composition last looked, so what it keeps for
/// them can go too.
forgotten_windows: Vec<u32>,
}
impl Default for NodeWriter {
fn default() -> Self {
Self::new()
}
}
impl NodeWriter {
pub fn new() -> Self {
Self {
batch: Batch::new(),
next_node_id: 1,
next_handler_id: 1,
parents: HashMap::with_capacity(256),
children: HashMap::with_capacity(256),
optional_props: HashMap::with_capacity(64),
pending_borders: HashMap::with_capacity(16),
modifier_slots: HashMap::with_capacity(64),
// Empty until a screen asks, which is the point: a tree that observes nothing
// allocates nothing here.
size_tokens: HashMap::new(),
// Empty until a screen animates something, for the same reason.
animated: HashMap::new(),
next_animation_id: 1,
windows: HashSet::new(),
forgotten_windows: Vec::new(),
}
}
/// The batch arena, so a runtime that reads Host memory through a mapped view can be
/// handed one.
pub fn arena(&self) -> (*const u8, usize) {
self.batch.arena()
}
/// The application's name for an observed node, if that node is observed.
pub(crate) fn size_token(&self, node_id: u32) -> Option<u32> {
self.size_tokens.get(&node_id).copied()
}
/// Whether `node_id` is a `Window` node.
pub(crate) fn is_window(&self, node_id: u32) -> bool {
self.windows.contains(&node_id)
}
/// The windows that left the tree since the last call.
pub(crate) fn take_forgotten_windows(&mut self) -> Vec<u32> {
std::mem::take(&mut self.forgotten_windows)
}
/// Whether any `Window` node exists, which is whether this is a multi-window tree.
pub(crate) fn has_windows(&self) -> bool {
!self.windows.is_empty()
}
/// The `Window` node that `node_id` is, or stands under, or 0 for one that is in no
/// window.
pub(crate) fn window_of(&self, node_id: u32) -> u32 {
if self.windows.is_empty() {
return 0;
}
let mut current = node_id;
// The tree is finite and acyclic, so this ends; the bound only guards a table that
// is wrong.
for _ in 0..=self.parents.len() {
if self.windows.contains(¤t) {
return current;
}
match self.parents.get(¤t) {
Some(parent) => current = *parent,
None => return 0,
}
}
0
}
/// The batch, for a Host that writes its own records into it.
pub(crate) fn batch(&self) -> &Batch {
&self.batch
}
pub(crate) fn batch_mut(&mut self) -> &mut Batch {
&mut self.batch
}
pub(crate) fn write(&mut self, mutation: Mutation<'_>) {
self.batch.write(mutation);
}
/// The next handler id. Ids are never reused, so an event that arrives for a handler
/// that has since gone away names nothing rather than somebody else's handler.
pub(crate) fn allocate_handler_id(&mut self) -> u64 {
let id = self.next_handler_id;
self.next_handler_id += 1;
id
}
/// Creates a node and says which id it was given.
pub(crate) fn allocate_node(&mut self, widget: WidgetKind) -> u32 {
let id = self.next_node_id;
self.next_node_id = self.next_node_id.checked_add(1).unwrap_or(1);
if widget == WidgetKind::Window {
self.windows.insert(id);
}
self.write(Mutation::Create {
node_id: id,
widget,
});
id
}
/// Writes one widget attribute: a Modifier slot, a property, or nothing.
///
/// This is the whole of what an attribute means on the wire, and both front ends call
/// it with the same names and the same values for the same widget.
pub fn set_attribute(&mut self, node_id: u32, name: &'static str, value: &AttrValue<'_>) {
if name == "shadows" {
self.set_shadows(node_id, value);
return;
}
if let Some(slot) = self.modifier_for(node_id, name, value) {
if let Some((index, modifier)) = slot {
self.write(Mutation::SetModifier {
node_id,
index,
modifier,
});
}
return;
}
self.set_property(node_id, name, value);
}
/// Writes a node's shadow layers, one modifier slot each, and clears the slots a
/// shorter list leaves behind. A slot is cleared only if a shadow wrote it, so a node
/// that never had one costs nothing.
fn set_shadows(&mut self, node_id: u32, value: &AttrValue<'_>) {
let mut layers: Vec<crate::Modifier> = Vec::new();
if let AttrValue::Bytes(bytes) = value {
for chunk in bytes.chunks_exact(SHADOW_BYTES).take(SHADOW_LAYERS) {
let float = |at: usize| f32::from_le_bytes(chunk[at..at + 4].try_into().unwrap());
let bits = u64::from_le_bytes(chunk[16..24].try_into().unwrap());
if let Some(paint) = crate::Paint::from_bits(bits) {
layers.push(crate::Modifier::Shadow {
x: float(0),
y: float(4),
blur: float(8),
spread: float(12),
paint,
});
}
}
}
let mut writes = Vec::new();
let owners = self
.modifier_slots
.entry(node_id)
.or_insert([""; MODIFIER_SLOTS]);
for layer in 0..SHADOW_LAYERS {
let slot = SHADOW_BASE as usize + layer;
if let Some(modifier) = layers.get(layer) {
owners[slot] = "shadows";
writes.push((slot as u16, modifier.clone()));
} else if owners[slot] == "shadows" {
owners[slot] = "";
writes.push((slot as u16, crate::Modifier::Empty));
}
}
for (index, modifier) in writes {
self.write(Mutation::SetModifier {
node_id,
index,
modifier,
});
}
}
/// Writes the handler id of an event listener under the property the Renderer fires
/// it through. Events with no property of their own, such as a clickable modifier,
/// write nothing here.
pub(crate) fn set_listener(&mut self, node_id: u32, name: &str, handler_id: u64) {
if let Some(property) = event_property(name) {
self.write(Mutation::SetProp {
node_id,
property,
value: PropertyValue::Integer(handler_id as i64),
});
}
}
/// Turns a Modifier attribute into one slot of the node's chain.
///
/// The Renderer applies the chain in list order, exactly as hand-written Compose does,
/// so the slot an attribute occupies decides what the result looks like. Padding
/// before a background is a margin; after it, it insets the content. Fixing the slots
/// here means `Card { background: .., padding: 16.0 }` behaves the way the person who
/// wrote it expects, whichever order they happened to type the attributes in.
///
/// The order below reads outside in: how big the widget is, what shape it is, what
/// fills it, what outlines it, what lifts it, what responds to a press, and finally
/// how far its content sits inside all of that.
///
/// A `false` or absent value writes `Empty` into the slot rather than dropping the
/// mutation, because a slot that keeps its old value would leave the removed modifier
/// applied.
fn modifier_for(
&mut self,
node_id: u32,
name: &'static str,
value: &AttrValue<'_>,
) -> Option<Option<(u16, crate::Modifier)>> {
use crate::Modifier;
// Slot assignments. A slot keeps its meaning for as long as a Host runs, because a
// node keeps whatever a slot held until something overwrites it; the Renderer starts
// with every slot empty, so the numbers only have to agree within one run.
//
// The transform and the opacity sit outside the shape, the fill and the outline, so
// all of them turn and fade with the node, and inside the size, so the node turns
// about itself where it was laid out.
const WEIGHT: u16 = 0;
const FILL_MAX_WIDTH: u16 = 1;
const FILL_MAX_HEIGHT: u16 = 2;
const WIDTH: u16 = 3;
const HEIGHT: u16 = 4;
const TRANSFORM: u16 = 5;
const ALPHA: u16 = 6;
// The displacement and the shadow layers (8 to 11) sit outside the shape and the
// fill, so a shadow is cast behind the background and under the padding.
const OFFSET: u16 = 7;
const SHAPE: u16 = 12;
const CLIP: u16 = 13;
const BACKGROUND: u16 = 14;
const BORDER: u16 = 15;
const ELEVATION: u16 = 16;
const CLICKABLE: u16 = 17;
const PADDING: u16 = 18;
const OBSERVE_SIZE: u16 = 19;
const MOTION: u16 = 20;
const MATERIAL: u16 = 21;
const MATCH_PARENT_SIZE: u16 = 22;
const WINDOW_DRAG: u16 = 23;
const PRESS_FEEDBACK: u16 = 24;
let float = |value: &AttrValue<'_>| match value {
AttrValue::Float(number) => Some(*number as f32),
AttrValue::Int(number) => Some(*number as f32),
_ => None,
};
let integer = |value: &AttrValue<'_>| match value {
AttrValue::Int(number) => Some(*number),
AttrValue::Float(number) => Some(*number as i64),
_ => None,
};
let slot_of = |name: &str| match name {
"weight" => Some(WEIGHT),
"fill_max_width" => Some(FILL_MAX_WIDTH),
"match_parent_size" => Some(MATCH_PARENT_SIZE),
"fill_max_height" => Some(FILL_MAX_HEIGHT),
"width" => Some(WIDTH),
"height" => Some(HEIGHT),
"shape_role" | "corner_radius" | "corner_radii" => Some(SHAPE),
"clip" => Some(CLIP),
"window_drag" => Some(WINDOW_DRAG),
"background" | "animated_background" => Some(BACKGROUND),
"transform" | "animated_offset" => Some(TRANSFORM),
"alpha" | "animated_alpha" => Some(ALPHA),
"offset" => Some(OFFSET),
"border_width" | "border_color" => Some(BORDER),
"elevation" => Some(ELEVATION),
"onclickable" => Some(CLICKABLE),
"padding" | "padding_role" => Some(PADDING),
"observe_size" => Some(OBSERVE_SIZE),
"motion" => Some(MOTION),
"material" => Some(MATERIAL),
"press_feedback" => Some(PRESS_FEEDBACK),
_ => None,
};
let slot = slot_of(name)?;
// An unset Modifier attribute is not a property, so it must not fall through to
// set_property and be rejected as an unknown one. It only produces a mutation if
// this slot already holds something, because clearing a slot that was never
// written would cost a mutation on the first frame of every widget.
if matches!(value, AttrValue::None) {
let owners = self
.modifier_slots
.entry(node_id)
.or_insert([""; MODIFIER_SLOTS]);
// Only the attribute that wrote the slot may clear it. `corner_radius` being
// unset says nothing about the `shape_role` sitting in the same slot.
if owners[slot as usize] != name {
return Some(None);
}
owners[slot as usize] = "";
// An animated value taken away starts again from wherever it is next set.
let bit = match name {
"animated_alpha" => 1,
"animated_background" => 2,
"animated_offset" => 4,
_ => 0,
};
if let Some(seen) = self.animated.get_mut(&node_id) {
*seen &= !bit;
}
return Some(Some((slot, crate::Modifier::Empty)));
}
self.modifier_slots
.entry(node_id)
.or_insert([""; MODIFIER_SLOTS])[slot as usize] = name;
match name {
// The token is the application's name for this node, and it stays here: what
// the Renderer reports back is its own node id, so the pairing has to be
// remembered at the moment the two are both in hand.
"observe_size" => {
let token = u32::try_from(integer(value)?).ok()?;
self.size_tokens.insert(node_id, token);
Some(Some((slot, Modifier::ObserveSize { token })))
}
"fill_max_width" | "fill_max_height" | "match_parent_size" => {
let AttrValue::Bool(enabled) = value else {
return Some(None);
};
Some(Some((
slot,
if !enabled {
Modifier::Empty
} else if slot == MATCH_PARENT_SIZE {
Modifier::MatchParentSize
} else if slot == FILL_MAX_WIDTH {
Modifier::FillMaxWidth
} else {
Modifier::FillMaxHeight
},
)))
}
"weight" => Some(Some((WEIGHT, Modifier::Weight(float(value)?)))),
"width" => Some(Some((WIDTH, Modifier::Width(float(value)?)))),
"height" => Some(Some((HEIGHT, Modifier::Height(float(value)?)))),
"padding" => Some(Some((PADDING, Modifier::Padding(float(value)?)))),
"padding_role" => Some(Some((
PADDING,
Modifier::PaddingRole(
crate::SpaceRole::try_from(u16::try_from(integer(value)?).ok()?).ok()?,
),
))),
"elevation" => Some(Some((ELEVATION, Modifier::Elevation(float(value)?)))),
"corner_radius" => {
let radius = float(value)?;
Some(Some((
SHAPE,
Modifier::Shape {
top_start: radius,
top_end: radius,
bottom_end: radius,
bottom_start: radius,
},
)))
}
"corner_radii" => {
let AttrValue::Bytes(bytes) = value else {
return Some(None);
};
let mut words = [0.0_f32; 4];
for (index, word) in words.iter_mut().enumerate() {
*word =
f32::from_le_bytes(bytes.get(4 * index..4 * index + 4)?.try_into().ok()?);
}
let [top_start, top_end, bottom_end, bottom_start] = words;
Some(Some((
SHAPE,
Modifier::Shape {
top_start,
top_end,
bottom_end,
bottom_start,
},
)))
}
"window_drag" => {
let AttrValue::Bool(enabled) = value else {
return Some(None);
};
Some(Some((WINDOW_DRAG, Modifier::WindowDrag(*enabled))))
}
"clip" => {
let AttrValue::Bool(enabled) = value else {
return Some(None);
};
Some(Some((
CLIP,
if *enabled {
Modifier::Clip(true)
} else {
Modifier::Empty
},
)))
}
// The node says how important its changes are. Which curve and how many
// milliseconds that means is the design system's answer, and it is never
// asked here.
"motion" => Some(Some((
MOTION,
Modifier::Motion(
crate::MotionRole::try_from(u16::try_from(integer(value)?).ok()?).ok()?,
),
))),
// What the surface is made of. Blur, tone or a flat fill is the running
// design system's answer, and the node does not get to ask for one of them.
"material" => Some(Some((
MATERIAL,
Modifier::Material(
crate::MaterialRole::try_from(u16::try_from(integer(value)?).ok()?).ok()?,
),
))),
"shape_role" => Some(Some((
SHAPE,
Modifier::ShapeRole(
crate::ShapeRole::try_from(u16::try_from(integer(value)?).ok()?).ok()?,
),
))),
// Colour crosses as the bits of a Paint, so a role and a literal colour take
// the same path and there is one wire representation of colour.
"background" => Some(Some((
BACKGROUND,
Modifier::Background(crate::Paint::from_bits(integer(value)? as u64)?),
))),
// A border needs a width and a colour, which arrive as two attributes. The
// half that arrives first is remembered so the pair can be written as one
// modifier, whichever order the front end hands them over in.
"border_width" | "border_color" => {
let pending = self.pending_borders.entry(node_id).or_default();
if name == "border_width" {
pending.0 = Some(float(value)?);
} else {
pending.1 = Some(crate::Paint::from_bits(integer(value)? as u64)?);
}
let (Some(width), Some(paint)) = (pending.0, pending.1) else {
return Some(None);
};
Some(Some((BORDER, Modifier::Border { width, paint })))
}
"alpha" => Some(Some((ALPHA, Modifier::Alpha(float(value)?)))),
"press_feedback" => {
let AttrValue::Bytes(bytes) = value else {
return Some(None);
};
let scale = f32::from_le_bytes(bytes.get(0..4)?.try_into().ok()?);
let tint_alpha = f32::from_le_bytes(bytes.get(4..8)?.try_into().ok()?);
Some(Some((
PRESS_FEEDBACK,
Modifier::PressFeedback { scale, tint_alpha },
)))
}
"offset" => {
let AttrValue::Bytes(bytes) = value else {
return Some(None);
};
let x = f32::from_le_bytes(bytes.get(0..4)?.try_into().ok()?);
let y = f32::from_le_bytes(bytes.get(4..8)?.try_into().ok()?);
Some(Some((OFFSET, Modifier::Offset { x, y })))
}
// CSS `matrix(a, b, c, d, e, f)` and the origin it turns about, eight floats.
"transform" => {
let AttrValue::Bytes(bytes) = value else {
return Some(None);
};
let mut words = [0.0_f32; 8];
for (index, word) in words.iter_mut().enumerate() {
*word =
f32::from_le_bytes(bytes.get(4 * index..4 * index + 4)?.try_into().ok()?);
}
let [a, b, c, d, e, f, origin_x, origin_y] = words;
Some(Some((
TRANSFORM,
Modifier::Transform {
a,
b,
c,
d,
e,
f,
origin_x,
origin_y,
},
)))
}
// A value that is animated to. The node's underlying value becomes the target at
// once, and from the second value on a transition from whatever is on screen to
// it goes out in the same batch, for the Renderer to play on its own clock.
"animated_alpha" | "animated_background" | "animated_offset" => {
use crate::schema::{AnimatedProperty, KeyframeValue, TransformFunction};
let AttrValue::Bytes(bytes) = value else {
return Some(None);
};
let (target, spec) = crate::animation::read_animated(bytes)?;
let (slot, base, property, to, bit) = match (name, target.as_slice()) {
("animated_alpha", [alpha]) => {
let alpha = f32::from_bits(*alpha);
(
ALPHA,
Modifier::Alpha(alpha),
AnimatedProperty::Alpha,
KeyframeValue::Alpha(alpha),
1_u8,
)
}
("animated_background", [low, high]) => {
let paint =
crate::Paint::from_bits(u64::from(*low) | (u64::from(*high) << 32))?;
(
BACKGROUND,
Modifier::Background(paint),
AnimatedProperty::Background,
KeyframeValue::Paint(paint),
2,
)
}
("animated_offset", [x, y]) => {
let (x, y) = (f32::from_bits(*x), f32::from_bits(*y));
(
TRANSFORM,
Modifier::Transform {
a: 1.0,
b: 0.0,
c: 0.0,
d: 1.0,
e: x,
f: y,
origin_x: 0.5,
origin_y: 0.5,
},
AnimatedProperty::Transform,
KeyframeValue::Transform(std::borrow::Cow::Owned(vec![
TransformFunction::translate(x, y),
])),
4,
)
}
_ => return None,
};
let seen = self.animated.entry(node_id).or_insert(0);
let first = *seen & bit == 0;
*seen |= bit;
if !first {
let animation_id = self.next_animation_id;
self.next_animation_id = self.next_animation_id.wrapping_add(1).max(1);
self.write(Mutation::StartAnimation(crate::animation::transition(
node_id,
animation_id,
property,
to,
spec,
)));
}
Some(Some((slot, base)))
}
// No composable writes a clickable modifier; a clickable widget is a Button.
"onclickable" => Some(None),
_ => None,
}
}
/// Role tag 0 means "not sent", so a design property at its neutral value
/// produces no record at all. A property that was set and then cleared still sends
/// its zero once, which is what tells the Renderer to drop the override.
fn should_write_optional_property(
&mut self,
node_id: u32,
property: PropertyKind,
neutral: bool,
) -> bool {
let tag = property as u16;
let index = if (FIRST_OPTIONAL_PROPERTY..=LAST_OPTIONAL_PROPERTY).contains(&tag) {
u32::from(tag - FIRST_OPTIONAL_PROPERTY)
} else if property == PropertyKind::Spans {
SPANS_BIT
} else {
return true;
};
let bit = 1_u64 << index;
let seen = self.optional_props.get(&node_id).copied().unwrap_or(0);
if neutral {
if seen & bit == 0 {
return false;
}
self.optional_props.insert(node_id, seen & !bit);
} else if seen & bit == 0 {
self.optional_props.insert(node_id, seen | bit);
}
true
}
/// Writes a widget property. A name the schema does not know is a protocol error,
/// kept for the end of the frame.
pub(crate) fn set_property(&mut self, node_id: u32, name: &str, value: &AttrValue<'_>) {
let Some(property) = property_kind(name) else {
// Neither front end has a fallible place to report this from. Keep the
// protocol error and surface it when the batch is finalized.
self.batch.fail(ProtocolError::InvalidProperty(0));
return;
};
let value = match value {
AttrValue::Text(value) => PropertyValue::String(value),
AttrValue::Float(value) => PropertyValue::Float(*value as f32),
AttrValue::Int(value) => PropertyValue::Integer(*value),
AttrValue::Bool(value) => PropertyValue::Bool(*value),
AttrValue::None => PropertyValue::None,
// A drawing command list or a list of text runs. The front end compares it
// before calling here, so an unchanged list never reaches this point and costs
// no record.
AttrValue::Bytes(bytes) => PropertyValue::Bytes(bytes),
};
let neutral = matches!(
value,
PropertyValue::None | PropertyValue::Integer(0) | PropertyValue::Float(0.0)
);
if !self.should_write_optional_property(node_id, property, neutral) {
return;
}
self.write(Mutation::SetProp {
node_id,
property,
value,
});
}
/// Where a drawn node stands under `parent`.
fn position_of(&self, parent: u32, node_id: u32) -> Option<usize> {
self.children
.get(&parent)?
.iter()
.position(|child| *child == node_id)
}
/// Forgets a node and everything under it, as the Renderer does when it is removed.
/// The caller has already taken the node out of its parent's list.
fn forget(&mut self, node_id: u32) {
if self.windows.remove(&node_id) {
crate::windows::forget_window(node_id);
self.forgotten_windows.push(node_id);
}
self.parents.remove(&node_id);
self.animated.remove(&node_id);
// Everything the writer keeps per node, so that a node id that is gone leaves
// nothing behind. Ids are never reused, so a stale entry is never read again and
// only costs memory, for as long as the process runs.
self.optional_props.remove(&node_id);
self.pending_borders.remove(&node_id);
self.modifier_slots.remove(&node_id);
self.size_tokens.remove(&node_id);
for child in self.children.remove(&node_id).unwrap_or_default() {
self.forget(child);
}
}
/// Takes a drawn node and everything under it out of the tree, and tells the Renderer.
pub(crate) fn remove_node(&mut self, node_id: u32) {
if let Some(parent) = self.parents.get(&node_id).copied() {
if let Some(position) = self.position_of(parent, node_id) {
if let Some(list) = self.children.get_mut(&parent) {
list.remove(position);
}
}
}
self.write(Mutation::Remove { node_id });
self.forget(node_id);
}
/// Places a node immediately after `after` under `parent`, or first when `after` is
/// `None`, and says nothing when it is already somewhere after it.
///
/// This is how a front end that knows the order its children came out in keeps the
/// Renderer's order without recounting it. A node that stands anywhere past the one
/// placed before it is left alone: whatever stands between the two is either about to
/// be placed after it or about to be removed, and moving it would cost a record that
/// the removal makes unnecessary. A node that stands before it has really moved, and
/// gets one `Move`. A node that is not in the tree yet gets its `Insert`.
pub(crate) fn place_after(&mut self, parent: u32, node_id: u32, after: Option<u32>) {
// A window is a child of the root and of nothing else, and a node never leaves its
// window for another. Both are refused before anything is
// written, the way the Renderer refuses them, so a tree that asks for either fails
// the batch it is in.
if self.windows.contains(&node_id) && parent != PLACEHOLDER_NODE {
self.batch.fail(ProtocolError::MisplacedWindow);
return;
}
if let Some(from) = self.parents.get(&node_id).copied() {
if from != parent {
let (leaving, entering) = (self.window_of(from), self.window_of(parent));
if leaving != entering && leaving != 0 && entering != 0 {
self.batch.fail(ProtocolError::MisplacedWindow);
return;
}
}
}
let mut target = match after.and_then(|previous| self.position_of(parent, previous)) {
Some(position) => position + 1,
None => 0,
};
let current = self.parents.get(&node_id).copied();
if current == Some(parent) {
// The common case is a node standing exactly where it belongs, so look there
// before scanning the whole list.
let standing = self.children.get(&parent).and_then(|list| list.get(target));
if standing == Some(&node_id) {
return;
}
if let Some(position) = self.position_of(parent, node_id) {
if position >= target {
return;
}
// Taken out from before the target, so the target shifts down by one.
if let Some(list) = self.children.get_mut(&parent) {
list.remove(position);
}
target -= 1;
}
} else if let Some(from) = current {
if let Some(position) = self.position_of(from, node_id) {
if let Some(list) = self.children.get_mut(&from) {
list.remove(position);
}
}
}
let list = self.children.entry(parent).or_default();
let target = target.min(list.len());
list.insert(target, node_id);
self.parents.insert(node_id, parent);
let index = target as u32;
self.write(if current.is_some() {
Mutation::Move {
parent_id: parent,
node_id,
index,
}
} else {
Mutation::Insert {
parent_id: parent,
node_id,
index,
}
});
}
}
fn property_kind(name: &str) -> Option<PropertyKind> {
PropertyKind::from_name(name).ok()
}
/// The property an event listener's handler id is written under.
pub(crate) fn event_property(name: &str) -> Option<PropertyKind> {
match name {
"click" | "onclick" => Some(PropertyKind::OnClick),
"valuechange" | "onvaluechange" => Some(PropertyKind::OnValueChange),
"submit" | "onsubmit" => Some(PropertyKind::OnSubmit),
"focuslost" | "onfocuslost" => Some(PropertyKind::OnFocusLost),
"keydown" | "onkeydown" => Some(PropertyKind::OnKeyDown),
"rangerequest" | "onrangerequest" => Some(PropertyKind::OnRangeRequested),
"dismiss" | "ondismiss" => Some(PropertyKind::OnDismiss),
"filesentered" | "onfilesentered" => Some(PropertyKind::OnFilesEntered),
"filesdropped" | "onfilesdropped" => Some(PropertyKind::OnFilesDropped),
"pointer" | "onpointer" => Some(PropertyKind::OnPointer),
"windowclose" | "onwindowclose" => Some(PropertyKind::OnWindowCloseRequested),
"windowfocus" | "onwindowfocus" => Some(PropertyKind::OnWindowFocusChanged),
"windowmoved" | "onwindowmoved" => Some(PropertyKind::OnWindowMoved),
"windowdrag" | "onwindowdrag" => Some(PropertyKind::OnWindowDrag),
"windowunavailable" | "onwindowunavailable" => Some(PropertyKind::OnWindowUnavailable),
"windowclosed" | "onwindowclosed" => Some(PropertyKind::OnWindowClosed),
"windowdragover" | "onwindowdragover" => Some(PropertyKind::OnWindowDragOver),
"change" | "onchange" => Some(PropertyKind::OnValueChange),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Two windows under the root, and a node in the first.
fn two_windows() -> (NodeWriter, u32, u32, u32) {
let mut writer = NodeWriter::new();
let first = writer.allocate_node(WidgetKind::Window);
let second = writer.allocate_node(WidgetKind::Window);
writer.place_after(PLACEHOLDER_NODE, first, None);
writer.place_after(PLACEHOLDER_NODE, second, Some(first));
let tab = writer.allocate_node(WidgetKind::Box);
writer.place_after(first, tab, None);
(writer, first, second, tab)
}
#[test]
fn nfr7_moving_a_node_between_windows_is_a_protocol_error() {
let (mut writer, _first, second, tab) = two_windows();
assert!(writer.batch_mut().finish().is_ok());
writer.place_after(second, tab, None);
assert_eq!(
writer.batch_mut().finish().err(),
Some(ProtocolError::MisplacedWindow)
);
}
#[test]
fn fr53_moving_a_node_inside_its_window_is_a_move() {
let (mut writer, first, _second, tab) = two_windows();
let inner = writer.allocate_node(WidgetKind::Column);
writer.place_after(first, inner, Some(tab));
writer.place_after(inner, tab, None);
assert!(writer.batch_mut().finish().is_ok());
assert_eq!(writer.window_of(tab), first);
}
#[test]
fn nfr7_a_window_under_anything_but_the_root_is_a_protocol_error() {
let mut writer = NodeWriter::new();
let column = writer.allocate_node(WidgetKind::Column);
writer.place_after(PLACEHOLDER_NODE, column, None);
let window = writer.allocate_node(WidgetKind::Window);
writer.place_after(column, window, None);
assert_eq!(
writer.batch_mut().finish().err(),
Some(ProtocolError::MisplacedWindow)
);
}
}