crabshell-ui 0.2.0

Widgets, styles, layout, text and text editing, focus, hit testing and invalidation for Crabshell
Documentation
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
//! A window's tree of nodes: turning elements into nodes, applying property
//! changes, and recording what needs layout and what needs repainting.
//!
//! The nodes live in taffy's tree, each carrying a [`Node`] as its context,
//! so taffy's parent and child links are the only ones.
//!
//! The tree sits in an `Rc<RefCell<..>>` that the [`Window`](crate::Window)
//! owns. Effects reach it through a `Weak`, so they never keep a dropped
//! window alive. It is never borrowed while user code runs: closures run
//! before the borrow and handlers after it, and user closures and values
//! live in the reactive runtime rather than here, so the runtime drops them.

use std::cell::{RefCell, RefMut};
use std::path::PathBuf;
use std::rc::{Rc, Weak};

use crabshell_reactive::Signal;
use taffy::TaffyTree;

use crate::animation::{self, Transition};
use crate::cx::{Anchor, Cx};
use crate::floating::FloatingState;
use crate::geometry::{Rect, Size};
use crate::input::{Handlers, Pointer};
use crate::keyboard::Keyboard;
use crate::keyed::KeyedSlot;
use crate::prop::{IntoProp, Prop, PropKind};
use crate::region::Region;
use crate::screencopy::CaptureNode;
use crate::style::{Padding, Style};
use crate::text::TextNode;
use crate::text_input::InputNode;
use crate::widgets::{Align, Element, ElementChild, ElementKind, Fit, IconSource, Justify};
use crate::window::{
  Anchors, DEFAULT_NAMESPACE, Hints, KeyboardFocus, Layer, Margins, Output, PanelWindow, Window,
};

pub(crate) type NodeId = taffy::NodeId;

pub(crate) struct Tree {
  /// This tree, for effects to reach without keeping it alive.
  pub(crate) this: Weak<RefCell<Tree>>,
  pub(crate) taffy: TaffyTree<Node>,
  pub(crate) root: NodeId,
  pub(crate) output: Output,
  pub(crate) surface: Surface,
  /// The size the compositor gave the window.
  pub(crate) size: Size,
  pub(crate) needs_layout: bool,
  /// Areas to repaint, gathered since the renderer last took them.
  pub(crate) damage: Vec<Rect>,
  pub(crate) pointer: Pointer,
  pub(crate) keyboard: Keyboard,
  /// Popups its widgets opened, until the platform takes them.
  pub(crate) popups: Vec<Window>,
  /// Set for a popup's own tree.
  pub(crate) popup: Option<PopupState>,
  /// Set for a floating window's own tree.
  pub(crate) floating: Option<FloatingState>,
  /// The screencopy views, in the order they were built.
  pub(crate) captures: Vec<NodeId>,
}

/// What only a popup's tree has.
pub(crate) struct PopupState {
  /// The widget it opened from, in a panel or another popup.
  pub(crate) opener: Rc<Anchor>,
  /// `close_popup` asked for it to close.
  pub(crate) close: bool,
  /// Lives under the popup's owner, so it is gone once the widget that
  /// opened the popup is.
  pub(crate) alive: Signal<()>,
  /// Where it goes, as the config set it.
  pub(crate) placement: crate::popup::Placement,
}

pub(crate) struct Node {
  /// The widget type, such as `"Row"`.
  pub(crate) name: &'static str,
  /// The widget path, such as `PanelWindow[DP-1]/Row/Button[2]`, for log
  /// lines.
  pub(crate) path: Rc<str>,
  /// The context of the widget's own owner.
  pub(crate) cx: Cx,
  pub(crate) style: Style,
  pub(crate) kind: NodeKind,
  /// The children in order, grouped by the call that added them: one node
  /// per `child`, any number per `children_keyed`.
  pub(crate) groups: Vec<Vec<NodeId>>,
  /// The number the next child's path gets: how many children a row,
  /// column or stack has created so far, single or keyed. Never reused, so
  /// no two children share a path.
  pub(crate) next_child: usize,
  /// The rectangle from the last layout, in window coordinates. `None`
  /// until the first.
  pub(crate) rect: Option<Rect>,
  /// `rect` without padding.
  pub(crate) content: Rect,
  /// What the node draws: `rect`, and text or an icon that overflows it.
  pub(crate) painted: Rect,
  /// `painted` together with every descendant's.
  pub(crate) bounds: Rect,
  /// What the node drew itself at the last layout: `painted` if it has a
  /// background, a border, text or an icon, and nothing otherwise. Moving
  /// or resizing it repaints only this, since its children report their
  /// own; a spacer that grows repaints nothing.
  pub(crate) drawn: Rect,
  /// Whether its style clipped its children at the last layout.
  pub(crate) clips: bool,
  /// A style change fading in, and the count of fades started, which
  /// tells a fade's clock step whether it was replaced.
  pub(crate) fade: Option<Fade>,
  pub(crate) fades: u64,
  /// A layout property changed, so the node is repainted after the next
  /// layout even if it doesn't move.
  pub(crate) changed: bool,
}

pub(crate) enum NodeKind {
  /// The `PanelWindow` itself.
  Root,
  Flex(Flex),
  Stack,
  Spacer,
  Text(TextNode),
  Icon(IconNode),
  Image(ImageNode),
  Capture(CaptureNode),
  Scroll(ScrollNode),
  Input(Box<InputNode>),
  // Boxed: its three styles make it the largest by far.
  Button(Box<ButtonNode>),
}

pub(crate) struct Flex {
  pub(crate) column: bool,
  pub(crate) grow: bool,
  pub(crate) gap: u32,
  pub(crate) padding_vertical: Option<u32>,
  pub(crate) padding_horizontal: Option<u32>,
  pub(crate) align: Align,
  pub(crate) justify: Justify,
}

pub(crate) struct ScrollNode {
  /// Written by scrolling, read for the offset.
  pub(crate) signal: Signal<f32>,
  /// The offset asked for; layout shows it clamped to the content.
  pub(crate) offset: f32,
  /// The offset shown at the last layout.
  pub(crate) shown: f32,
  /// How far the child can scroll, from the last layout.
  pub(crate) most: f32,
}

pub(crate) struct ImageNode {
  pub(crate) source: Option<PathBuf>,
  pub(crate) width: u32,
  pub(crate) height: u32,
  pub(crate) fit: Fit,
}

pub(crate) struct IconNode {
  /// `None` until the icon's binding first runs.
  pub(crate) source: Option<IconSource>,
  pub(crate) size: u32,
}

pub(crate) struct ButtonNode {
  pub(crate) hover_style: Style,
  pub(crate) pressed_style: Style,
  pub(crate) focus_style: Style,
  /// Kept in the reactive runtime, which drops the user's closures when
  /// the button's owner goes.
  pub(crate) handlers: Signal<Handlers>,
  /// Written while the pointer is over the button or inside it.
  pub(crate) hover_signal: Option<Signal<bool>>,
  pub(crate) hovered: bool,
  pub(crate) pressed: bool,
  /// Focused while its window has the keyboard.
  pub(crate) focused: bool,
}

/// The layer-surface settings of the window.
pub(crate) struct Surface {
  pub(crate) anchors: Anchors,
  pub(crate) width: u32,
  pub(crate) height: u32,
  pub(crate) exclusive_zone: Option<i32>,
  pub(crate) layer: Layer,
  pub(crate) margins: Margins,
  pub(crate) keyboard_focus: KeyboardFocus,
  pub(crate) namespace: String,
  pub(crate) mask: Option<Region>,
  /// A panel's or floating window's blur region.
  pub(crate) blur: Option<Region>,
  /// Whether a panel or floating window keeps the screen from idling.
  pub(crate) inhibit_idle: bool,
  /// Whether it takes the compositor's shortcuts while it has the keys.
  pub(crate) inhibit_shortcuts: bool,
  /// Written by the platform: whether the compositor honors that.
  pub(crate) shortcuts_inhibited: Option<Signal<bool>>,
  /// Shared by the windows in one focus grab.
  pub(crate) focus_grab: Option<Signal<bool>>,
  /// Something changed since the platform last read the settings.
  pub(crate) changed: bool,
}

impl Default for Surface {
  fn default() -> Surface {
    Surface {
      anchors: Anchors::NONE,
      width: 0,
      height: 0,
      exclusive_zone: None,
      layer: Layer::Top,
      margins: Margins::default(),
      keyboard_focus: KeyboardFocus::None,
      namespace: String::from(DEFAULT_NAMESPACE),
      mask: None,
      blur: None,
      inhibit_idle: false,
      inhibit_shortcuts: false,
      shortcuts_inhibited: None,
      focus_grab: None,
      changed: false,
    }
  }
}

/// A style change fading in from `from`, `t` of the way.
pub(crate) struct Fade {
  pub(crate) from: Style,
  pub(crate) t: f32,
  pub(crate) generation: u64,
}

/// What a property change invalidates.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Change {
  None,
  Paint,
  Layout,
}

/// Borrows the tree for an effect or a pointer event.
pub(crate) fn borrow(tree: &RefCell<Tree>) -> RefMut<'_, Tree> {
  tree
    .try_borrow_mut()
    .expect("invariant: a window's tree is not borrowed while effects or handlers run")
}

impl Node {
  fn new(name: &'static str, path: Rc<str>, cx: Cx, kind: NodeKind) -> Node {
    Node {
      name,
      path,
      cx,
      style: Style::new(),
      kind,
      groups: Vec::new(),
      next_child: 0,
      rect: None,
      content: Rect::default(),
      painted: Rect::default(),
      bounds: Rect::default(),
      drawn: Rect::default(),
      clips: false,
      fade: None,
      fades: 0,
      changed: true,
    }
  }

  /// The style in effect: a button's focus, hover and pressed styles laid
  /// over its own, in that order.
  pub(crate) fn effective_style(&self) -> Style {
    let NodeKind::Button(button) = &self.kind else {
      return self.style;
    };
    let mut style = self.style;
    if button.focused {
      style = style.merge(button.focus_style);
    }
    if button.hovered {
      style = style.merge(button.hover_style);
      if button.pressed {
        style = style.merge(button.pressed_style);
      }
    }
    style
  }

  /// The style as drawn: the style in effect, or partway to it while a
  /// change fades in.
  pub(crate) fn shown_style(&self) -> Style {
    match &self.fade {
      Some(fade) => fade.from.lerp(&self.effective_style(), fade.t),
      None => self.effective_style(),
    }
  }

  /// Whether the node cuts its children to the inside of its border: a
  /// clipping style or a scroll view.
  pub(crate) fn clips(&self) -> bool {
    self.effective_style().clips() || matches!(self.kind, NodeKind::Scroll(_) | NodeKind::Input(_))
  }

  /// Whether the node draws anything itself, in its style in effect. The
  /// window always does: its area is what a repaint clears.
  pub(crate) fn draws(&self) -> bool {
    let style = self.effective_style();
    matches!(
      self.kind,
      NodeKind::Root
        | NodeKind::Text(_)
        | NodeKind::Icon(_)
        | NodeKind::Image(_)
        | NodeKind::Capture(_)
        | NodeKind::Input(_)
    ) || style.background.is_some()
      || style.gradient.is_some()
      || style.shadow.is_some()
      // A fade still shows what the style had.
      || self.fade.is_some()
      || style.border.is_some()
  }

  /// The padding in effect: a row's or column's own wins over its style's.
  pub(crate) fn padding(&self) -> Padding {
    let style = self.effective_style().padding.unwrap_or_default();
    match &self.kind {
      NodeKind::Flex(flex) => Padding {
        vertical: flex.padding_vertical.unwrap_or(style.vertical),
        horizontal: flex.padding_horizontal.unwrap_or(style.horizontal),
      },
      _ => style,
    }
  }
}

impl Tree {
  /// A tree holding only the window's root node, a `name` such as
  /// `"PanelWindow"`, owned by `cx`, which is anchored at the root.
  pub(crate) fn new(
    this: Weak<RefCell<Tree>>,
    name: &'static str,
    output: Output,
    cx: Cx,
    path: Rc<str>,
  ) -> Tree {
    let mut taffy = TaffyTree::new();
    let anchor = cx.anchor.clone();
    let root = taffy
      .new_leaf_with_context(
        taffy::Style::default(),
        Node::new(name, path, cx, NodeKind::Root),
      )
      .expect("invariant: adding a leaf to taffy never fails");
    if let Some(anchor) = anchor {
      anchor.set(this.clone(), root);
    }
    Tree {
      this,
      taffy,
      root,
      output,
      surface: Surface::default(),
      size: Size::default(),
      needs_layout: true,
      damage: Vec::new(),
      pointer: Pointer::default(),
      keyboard: Keyboard::default(),
      popups: Vec::new(),
      popup: None,
      floating: None,
      captures: Vec::new(),
    }
  }

  pub(crate) fn node(&self, id: NodeId) -> Option<&Node> {
    self.taffy.get_node_context(id)
  }

  pub(crate) fn node_mut(&mut self, id: NodeId) -> Option<&mut Node> {
    self.taffy.get_node_context_mut(id)
  }

  /// Applies the window's own properties and adds its child, which the
  /// caller already turned into an element.
  pub(crate) fn mount_panel(&mut self, panel: PanelWindow, child: Option<Element>) {
    let root = self.root;
    let PanelWindow {
      output: _,
      anchors,
      width,
      height,
      exclusive_zone,
      layer,
      margins,
      keyboard_focus,
      namespace,
      mask,
      hints,
      on_key,
      style,
      child: _,
    } = panel;
    self.keyboard.handler = on_key;
    self.bind_opt(root, anchors, "anchors", |tree, _, value| {
      tree.surface.set(|s| &mut s.anchors, value);
    });
    self.bind_opt(root, width, "width", |tree, _, value| {
      tree.surface.set(|s| &mut s.width, value);
    });
    self.bind_opt(root, height, "height", |tree, _, value| {
      tree.surface.set(|s| &mut s.height, value);
    });
    self.bind_opt(root, exclusive_zone, "exclusive_zone", |tree, _, value| {
      tree.surface.set(|s| &mut s.exclusive_zone, Some(value));
    });
    self.bind_opt(root, layer, "layer", |tree, _, value| {
      tree.surface.set(|s| &mut s.layer, value);
    });
    self.bind_opt(root, margins, "margins", |tree, _, value| {
      tree.surface.set(|s| &mut s.margins, value);
    });
    self.bind_opt(root, keyboard_focus, "keyboard_focus", |tree, _, value| {
      tree.surface.set(|s| &mut s.keyboard_focus, value);
    });
    self.bind_opt(root, namespace, "namespace", |tree, _, value| {
      tree.surface.set(|s| &mut s.namespace, value);
    });
    self.bind_opt(root, mask, "mask", |tree, _, value| {
      tree.surface.set(|s| &mut s.mask, value);
    });
    self.bind_compositor_hints(hints);
    self.mount_root(style, child);
    self.surface.changed = true;
  }

  /// Binds what a panel or floating window asks of the compositor: its
  /// blur region, whether it inhibits idle and shortcuts, and the signals
  /// the platform writes.
  pub(crate) fn bind_compositor_hints(&mut self, hints: Hints) {
    let Hints {
      blur,
      inhibit_idle,
      inhibit_shortcuts,
      shortcuts_inhibited,
      focus_grab,
    } = hints;
    self.bind_opt(self.root, blur, "blur", |tree, _, value| {
      tree.surface.set(|s| &mut s.blur, value);
    });
    self.bind_opt(self.root, inhibit_idle, "inhibit_idle", |tree, _, value| {
      tree.surface.set(|s| &mut s.inhibit_idle, value);
    });
    self.bind_opt(
      self.root,
      inhibit_shortcuts,
      "inhibit_shortcuts",
      |tree, _, value| tree.surface.set(|s| &mut s.inhibit_shortcuts, value),
    );
    self.surface.shortcuts_inhibited = shortcuts_inhibited;
    self.surface.focus_grab = focus_grab;
  }

  /// Applies the root's style and adds its child, as a panel's or a
  /// popup's.
  pub(crate) fn mount_root(&mut self, style: Option<Prop<Style>>, child: Option<Element>) {
    let root = self.root;
    self.bind_opt(root, style, "style", set_style);
    if let Some(child) = child {
      let cx = self.node(root).map(|node| node.cx.clone());
      let cx = cx.expect("invariant: the root node exists while the tree does");
      let child = self.mount(child, &cx, root);
      self.set_group(root, 0, vec![child]);
    }
  }

  /// Turns `element` and everything in it into nodes under a new child
  /// owner of `parent_cx`. The caller adds the returned node to `parent`.
  pub(crate) fn mount(&mut self, element: Element, parent_cx: &Cx, parent: NodeId) -> NodeId {
    let Element {
      name,
      style,
      mut kind,
      children,
    } = element;
    let index = self.next_index(parent);
    let parent_path = self.node(parent).map_or("", |node| &node.path);
    let path: Rc<str> = match index {
      Some(index) => format!("{parent_path}/{name}[{index}]"),
      None => format!("{parent_path}/{name}"),
    }
    .into();
    let anchor = Rc::new(Anchor::default());
    let cx = parent_cx
      .child()
      .named(path.to_string())
      .at(Rc::clone(&anchor));

    // The node starts with defaults; the properties are applied below.
    let node_kind = match &mut kind {
      ElementKind::Flex(props) => NodeKind::Flex(Flex {
        column: props.column,
        grow: props.grow,
        gap: 0,
        padding_vertical: None,
        padding_horizontal: None,
        align: Align::default(),
        justify: Justify::default(),
      }),
      ElementKind::Stack => NodeKind::Stack,
      ElementKind::Spacer => NodeKind::Spacer,
      ElementKind::Text(_) => NodeKind::Text(TextNode::new()),
      ElementKind::Input(props) => NodeKind::Input(Box::new(InputNode::new(
        props.text,
        cx.signal(props.on_accept.take()),
      ))),
      ElementKind::Scroll(props) => NodeKind::Scroll(ScrollNode {
        signal: props.offset.unwrap_or_else(|| cx.signal(0.0)),
        offset: 0.0,
        shown: 0.0,
        most: 0.0,
      }),
      ElementKind::Image(_) => NodeKind::Image(ImageNode {
        source: None,
        width: crate::Image::DEFAULT_SIZE,
        height: crate::Image::DEFAULT_SIZE,
        fit: Fit::default(),
      }),
      ElementKind::Capture(_) => NodeKind::Capture(CaptureNode::new()),
      ElementKind::Icon(_) => NodeKind::Icon(IconNode {
        source: None,
        size: crate::Icon::DEFAULT_SIZE,
      }),
      ElementKind::Button(props) => NodeKind::Button(Box::new(ButtonNode {
        hover_style: Style::new(),
        pressed_style: Style::new(),
        focus_style: Style::new(),
        handlers: cx.signal(std::mem::take(&mut props.handlers)),
        hover_signal: props.hovered,
        hovered: false,
        pressed: false,
        focused: false,
      })),
    };
    let id = self
      .taffy
      .new_leaf_with_context(
        taffy::Style::default(),
        Node::new(name, Rc::clone(&path), cx.clone(), node_kind),
      )
      .expect("invariant: adding a leaf to taffy never fails");
    anchor.set(self.this.clone(), id);

    self.bind_opt(id, style, "style", set_style);
    self.bind_kind(id, kind);
    self.mount_children(id, children, &cx, &path);
    id
  }

  /// Applies the properties only one kind of widget has.
  fn bind_kind(&mut self, id: NodeId, kind: ElementKind) {
    match kind {
      ElementKind::Flex(props) => {
        self.bind_opt(id, props.gap, "gap", |tree, id, value| {
          tree.update_flex(id, |flex| replace(&mut flex.gap, value))
        });
        self.bind_opt(id, props.padding_vertical, "padding", |tree, id, value| {
          tree.update_flex(id, |flex| replace(&mut flex.padding_vertical, Some(value)))
        });
        self.bind_opt(
          id,
          props.padding_horizontal,
          "padding",
          |tree, id, value| {
            tree.update_flex(id, |flex| {
              replace(&mut flex.padding_horizontal, Some(value))
            })
          },
        );
        self.bind_opt(id, props.align, "align", |tree, id, value| {
          tree.update_flex(id, |flex| replace(&mut flex.align, value))
        });
        self.bind_opt(id, props.justify, "justify", |tree, id, value| {
          tree.update_flex(id, |flex| replace(&mut flex.justify, value))
        });
      }
      ElementKind::Text(props) => {
        self.bind(id, props.text, "text", |tree, id, value| {
          tree.update_text(id, |text| text.set_content(value))
        });
        self.bind_opt(id, props.ellipsis, "ellipsis", |tree, id, value| {
          tree.update_text(id, |text| text.set_ellipsis(value))
        });
        self.bind_opt(id, props.max_lines, "max_lines", |tree, id, value| {
          tree.update_text(id, |text| text.set_max_lines(value))
        });
      }
      ElementKind::Input(props) => {
        let signal = props.text;
        self.bind(
          id,
          (move || signal.get()).into_prop(),
          "text",
          |tree, id, value| {
            tree.update_input(id, |input| {
              input.edit.set_text(value);
              input.refresh();
            });
          },
        );
        self.bind_opt(id, props.placeholder, "placeholder", |tree, id, value| {
          tree.update_input(id, |input| {
            input.placeholder = value;
            input.refresh();
          });
        });
        self.bind_opt(id, props.password, "password", |tree, id, value| {
          tree.update_input(id, |input| {
            input.password = value;
            input.refresh();
          });
        });
        self.bind_opt(id, props.focus, "focus", |tree, id, value| {
          if value {
            tree.focus(Some(id));
          }
        });
      }
      ElementKind::Scroll(_) => {
        if let Some(NodeKind::Scroll(scroll)) = self.node(id).map(|node| &node.kind) {
          let signal = scroll.signal;
          self.bind(
            id,
            (move || signal.get()).into_prop(),
            "offset",
            |tree, id, value| {
              tree.update(id, |node| match &mut node.kind {
                NodeKind::Scroll(scroll) => replace(&mut scroll.offset, value),
                _ => Change::None,
              });
            },
          );
        }
      }
      ElementKind::Image(props) => {
        self.bind(id, props.source, "image", |tree, id, value| {
          tree.update_image(id, |image| match replace(&mut image.source, Some(value)) {
            // A new picture of the same size only needs a repaint.
            Change::None => Change::None,
            _ => Change::Paint,
          })
        });
        self.bind_opt(id, props.width, "width", |tree, id, value| {
          tree.update_image(id, |image| replace(&mut image.width, value))
        });
        self.bind_opt(id, props.height, "height", |tree, id, value| {
          tree.update_image(id, |image| replace(&mut image.height, value))
        });
        self.bind_opt(id, props.fit, "fit", |tree, id, value| {
          tree.update_image(id, |image| match replace(&mut image.fit, value) {
            Change::None => Change::None,
            _ => Change::Paint,
          })
        });
      }
      ElementKind::Capture(props) => self.bind_capture(id, props),
      ElementKind::Icon(props) => {
        self.bind(id, props.source, "icon", |tree, id, value| {
          tree.update_icon(id, |icon| match replace(&mut icon.source, Some(value)) {
            // A new picture of the same size only needs a repaint.
            Change::None => Change::None,
            _ => Change::Paint,
          })
        });
        self.bind_opt(id, props.size, "size", |tree, id, value| {
          tree.update_icon(id, |icon| replace(&mut icon.size, value))
        });
      }
      ElementKind::Button(props) => {
        self.bind_opt(id, props.hover_style, "hover_style", |tree, id, value| {
          tree.update_button_style(id, |button| button.hover_style = value);
        });
        self.bind_opt(
          id,
          props.pressed_style,
          "pressed_style",
          |tree, id, value| {
            tree.update_button_style(id, |button| button.pressed_style = value);
          },
        );
        self.bind_opt(id, props.focus_style, "focus_style", |tree, id, value| {
          tree.update_button_style(id, |button| button.focus_style = value);
        });
      }
      ElementKind::Stack | ElementKind::Spacer => {}
    }
  }

  /// Mounts a container's children, each `child` call as one group and
  /// each `children_keyed` call as a group its effect fills.
  fn mount_children(&mut self, id: NodeId, children: Vec<ElementChild>, cx: &Cx, path: &Rc<str>) {
    for child in children {
      let Some(node) = self.node(id) else {
        return;
      };
      let group = node.groups.len();
      match child {
        ElementChild::One(element) => {
          let child = self.mount(*element, cx, id);
          self.set_group(id, group, vec![child]);
        }
        ElementChild::Keyed(mount) => {
          self.set_group(id, group, Vec::new());
          mount(KeyedSlot {
            tree: self.this.clone(),
            container: id,
            group,
            cx: cx.clone(),
            path: Rc::clone(path),
          });
        }
      }
    }
  }

  /// The number in the path of `parent`'s next child, such as the 2 in
  /// `Row/Button[2]`. `None` for the only child of a window or button.
  fn next_index(&mut self, parent: NodeId) -> Option<usize> {
    let node = self.node_mut(parent)?;
    if !matches!(node.kind, NodeKind::Flex(_) | NodeKind::Stack) {
      return None;
    }
    let index = node.next_child;
    node.next_child += 1;
    Some(index)
  }

  /// Replaces the nodes of one child group of `parent`, adding the group if
  /// it is the next one.
  pub(crate) fn set_group(&mut self, parent: NodeId, group: usize, nodes: Vec<NodeId>) {
    let Some(node) = self.node_mut(parent) else {
      return;
    };
    if group == node.groups.len() {
      node.groups.push(nodes);
    } else if let Some(slot) = node.groups.get_mut(group) {
      *slot = nodes;
    }
    let children: Vec<NodeId> = node.groups.iter().flatten().copied().collect();
    self
      .taffy
      .set_children(parent, &children)
      .expect("invariant: every node in a child group is in the tree");
    self.needs_layout = true;
  }

  /// Removes `id` and everything under it, and repaints where it was.
  /// Their owners are disposed by whoever owns them, after the tree is
  /// released.
  pub(crate) fn unmount(&mut self, id: NodeId) {
    if let Some(node) = self.taffy.get_node_context(id)
      && node.rect.is_some()
    {
      add_damage(&mut self.damage, node.bounds);
    }
    let mut removed = Vec::new();
    let mut pending = vec![id];
    while let Some(next) = pending.pop() {
      removed.push(next);
      if let Ok(children) = self.taffy.children(next) {
        pending.extend(children);
      }
    }
    self.pointer.forget(&removed);
    self.captures.retain(|node| !removed.contains(node));
    self.keyboard.forget(&removed);
    for node in removed.into_iter().rev() {
      // `remove` only fails for a node that isn't in the tree.
      let _ = self.taffy.remove(node);
    }
    self.needs_layout = true;
  }

  /// Applies `prop` to node `id` with `apply`: once now for a value, or
  /// from an effect under the node's owner for a binding. The effect is
  /// named after the widget path and `name`, for log lines.
  pub(crate) fn bind<T: 'static>(
    &mut self,
    id: NodeId,
    prop: Prop<T>,
    name: &str,
    apply: fn(&mut Tree, NodeId, T),
  ) {
    match prop.0 {
      PropKind::Value(value) => apply(self, id, value),
      PropKind::Binding(mut compute) => {
        let Some(node) = self.node(id) else {
          return;
        };
        let label = format!("{}.{name}", node.path);
        let tree = self.this.clone();
        node
          .cx
          .effect(move || {
            // The user's closure runs before the tree is borrowed.
            let value = compute();
            if let Some(tree) = tree.upgrade() {
              apply(&mut borrow(&tree), id, value);
            }
          })
          .named(label);
      }
    }
  }

  pub(crate) fn bind_opt<T: 'static>(
    &mut self,
    id: NodeId,
    prop: Option<Prop<T>>,
    name: &str,
    apply: fn(&mut Tree, NodeId, T),
  ) {
    if let Some(prop) = prop {
      self.bind(id, prop, name, apply);
    }
  }

  /// Runs `f` on node `id`, if it still exists, and records and returns
  /// what it invalidated.
  pub(crate) fn update(&mut self, id: NodeId, f: impl FnOnce(&mut Node) -> Change) -> Change {
    let Some(node) = self.node_mut(id) else {
      return Change::None;
    };
    let change = f(node);
    self.invalidate(id, change);
    change
  }

  /// Runs `f` on node `id` and works out from the style in effect before
  /// and after whether the change needs a layout or only a repaint.
  pub(crate) fn update_style(&mut self, id: NodeId, f: impl FnOnce(&mut Node)) -> Change {
    let mut fade = None;
    let change = self.update(id, |node| {
      let shown = node.shown_style();
      let before = node.effective_style();
      f(node);
      let after = node.effective_style();
      if before == after {
        return Change::None;
      }
      node.fade = None;
      if !before.same_layout(&after) {
        return Change::Layout;
      }
      // A node not yet drawn shows its style at once.
      if let Some(transition) = after.transition.filter(|transition| transition.ms > 0)
        && node.rect.is_some()
      {
        node.fades += 1;
        node.fade = Some(Fade {
          from: shown,
          t: 0.0,
          generation: node.fades,
        });
        fade = Some((node.fades, transition));
      }
      // A shadow reaches past the box, so the area painted is worked
      // out again, to cover a fade's start as well as its end.
      if before.shadow == after.shadow {
        Change::Paint
      } else {
        Change::Layout
      }
    });
    if let Some((generation, transition)) = fade {
      self.start_fade(id, generation, transition);
    }
    change
  }

  /// Advances node `id`'s fade number `generation` with the animation
  /// clock, repainting it each tick, until it ends or another replaces it.
  fn start_fade(&self, id: NodeId, generation: u64, transition: Transition) {
    let tree = self.this.clone();
    let mut started = animation::start_time();
    let label = self.node(id).map_or_else(
      || Rc::from("a fade"),
      |node| format!("{}.transition", node.path).into(),
    );
    animation::start(
      label,
      Box::new(move |now| {
        let Some(tree) = tree.upgrade() else {
          return false;
        };
        let Ok(mut tree) = tree.try_borrow_mut() else {
          return true;
        };
        let begun = *started.get_or_insert(now);
        let (t, ended) = transition.progress(begun, now);
        let change = tree.update(id, |node| {
          if node
            .fade
            .as_ref()
            .is_none_or(|fade| fade.generation != generation)
          {
            return Change::None;
          }
          if ended {
            node.fade = None;
          } else if let Some(fade) = &mut node.fade {
            fade.t = t;
          }
          Change::Paint
        });
        change == Change::Paint && !ended
      }),
    );
  }

  fn update_flex(&mut self, id: NodeId, f: impl FnOnce(&mut Flex) -> Change) {
    self.update(id, |node| match &mut node.kind {
      NodeKind::Flex(flex) => f(flex),
      _ => Change::None,
    });
  }

  fn update_text(&mut self, id: NodeId, f: impl FnOnce(&mut TextNode) -> bool) {
    self.update(id, |node| match &mut node.kind {
      NodeKind::Text(text) => {
        if f(text) {
          Change::Layout
        } else {
          Change::None
        }
      }
      _ => Change::None,
    });
  }

  /// Changes a field; anything about it may move the caret, so it is laid
  /// out again.
  pub(crate) fn update_input(&mut self, id: NodeId, f: impl FnOnce(&mut InputNode)) {
    self.update(id, |node| match &mut node.kind {
      NodeKind::Input(input) => {
        f(input);
        Change::Layout
      }
      _ => Change::None,
    });
  }

  fn update_image(&mut self, id: NodeId, f: impl FnOnce(&mut ImageNode) -> Change) {
    self.update(id, |node| match &mut node.kind {
      NodeKind::Image(image) => f(image),
      _ => Change::None,
    });
  }

  fn update_icon(&mut self, id: NodeId, f: impl FnOnce(&mut IconNode) -> Change) {
    self.update(id, |node| match &mut node.kind {
      NodeKind::Icon(icon) => f(icon),
      _ => Change::None,
    });
  }

  pub(crate) fn update_button_style(
    &mut self,
    id: NodeId,
    f: impl FnOnce(&mut ButtonNode),
  ) -> Change {
    self.update_style(id, |node| {
      if let NodeKind::Button(button) = &mut node.kind {
        f(button);
      }
    })
  }

  /// Records that node `id` needs a repaint, or the window a layout.
  pub(crate) fn invalidate(&mut self, id: NodeId, change: Change) {
    match change {
      Change::None => {}
      Change::Paint => {
        // A node that was never laid out is painted after its first
        // layout anyway. Its bounds cover the descendants, which
        // inherit its color and opacity.
        if let Some(node) = self.taffy.get_node_context_mut(id)
          && node.rect.is_some()
        {
          add_damage(&mut self.damage, node.bounds);
          // It may draw now, as when a background was added, so a
          // later move repaints where it was.
          node.drawn = node.painted;
        }
      }
      Change::Layout => {
        if let Some(node) = self.node_mut(id) {
          node.changed = true;
        }
        self.needs_layout = true;
      }
    }
  }
}

impl Surface {
  /// Sets one field and remembers that the settings changed.
  fn set<T: PartialEq>(&mut self, field: impl FnOnce(&mut Surface) -> &mut T, value: T) {
    let slot = field(self);
    if *slot != value {
      *slot = value;
      self.changed = true;
    }
  }
}

fn set_style(tree: &mut Tree, id: NodeId, style: Style) {
  tree.update_style(id, |node| node.style = style);
}

/// Where an icon of `size` logical pixels is drawn in its node's `content`
/// box: a square, centered, on whole pixels. It overflows a smaller box.
pub(crate) fn icon_rect(content: Rect, size: u32) -> Rect {
  centered(content, size, size)
}

/// A `width` by `height` box centered in `content`, on whole logical
/// pixels.
pub(crate) fn centered(content: Rect, width: u32, height: u32) -> Rect {
  let (width, height) = (width as f32, height as f32);
  Rect::new(
    content.x + ((content.width - width) / 2.0).round(),
    content.y + ((content.height - height) / 2.0).round(),
    width,
    height,
  )
}

/// Adds `rect` to the areas to repaint, unless it is empty or already there.
pub(crate) fn add_damage(damage: &mut Vec<Rect>, rect: Rect) {
  if !rect.is_empty() && !damage.contains(&rect) {
    damage.push(rect);
  }
}

/// Stores `value` in `slot` and reports a layout change if it differs.
pub(crate) fn replace<T: PartialEq>(slot: &mut T, value: T) -> Change {
  if *slot == value {
    Change::None
  } else {
    *slot = value;
    Change::Layout
  }
}