nandi/jolt-nativepublic Fork 0
main
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.

layout.rs · 813 lines · 30.6 KBRust Blame HistoryRaw
  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
//! Two sizes per node, and how a box shares out what it has.
//!
//! Every node answers a *natural* size — what it would like — and a *minimum*
//! — what it can survive on. A container hands out its natural sizes when there
//! is room, shrinks them proportionally toward the minimums when there is not,
//! and gives the surplus to whoever asked to expand. `:width-request` and
//! `:height-request` are a floor on both numbers, so asking for four rows gets
//! four rows even when space is short.
//!
//! `:max-height` is the ceiling on the other end, and only a natural one: a
//! node that says it is four rows tall is asking for at most four, however
//! much is in it. It is there for a `:scroll`, whose content is as long as the
//! list and whose whole job is to be shorter than that — without it a viewport
//! is a viewport only on a screen too short to draw it in full, and on any
//! other it takes the rows its neighbours were sharing.
//!
//! Nothing here touches a terminal or the screen grid: sizes are arithmetic on
//! the tree, which is why the layout tests below need no TTY.

use crate::graphics;
use crate::screen::{glyph_cols, glyphs, text_cols, Rect};
use crate::tree::{Props, Tag, Tree};

use std::cell::RefCell;
use std::collections::HashMap;

// --- measuring the same node twice -------------------------------------------
// A size here is a pure function of the tree, and the tree does not move while
// it is being measured: the reconciler's changes arrive between frames, and
// painting takes the tree by shared reference. So an answer can be kept.
//
// It has to be. Nothing below asks a node its size once. A box shares its room
// out by measuring every child, then `children_rects` measures them again to
// place them, and then the painter recurses and the child repeats the whole
// thing for its own children — so a node is measured once for every ancestor
// that asks, and the work under a message doubles with every box it is wrapped
// in. On frq's backlog, six deep, that is what made a frame cost the best part
// of a second: not the wrapping, but the same wrapping done sixty times.
//
// Keyed on what the answer depends on and nothing else — the node, the room it
// was given, and which of the four questions was asked.

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum Question {
    Width { minimum: bool },
    Height,
    MinHeight,
}

/// A question about a node, and the room it was asked about.
type Asked = (Question, u32, u16);
/// A box, the room it had, the axis and the extent across it.
type Divided = (u32, u16, bool, u16);
/// An answer, and the subtree revision it was true of.
type Answered<T> = (u64, T);

thread_local! {
    /// Sizes answered so far, and the shares boxes divided out. Each remembers
    /// the subtree revision it was taken at, which is what makes it safe to
    /// keep past the frame that asked.
    static SIZES: RefCell<HashMap<Asked, Answered<u16>>> = RefCell::new(HashMap::new());
    static SHARES: RefCell<HashMap<Divided, Answered<Vec<u16>>>> =
        RefCell::new(HashMap::new());
}

/// An answer for a node that has been freed since is never right again, and its
/// handle will be handed out to some other node — which gets a fresh revision,
/// so the stale entry is refused rather than believed. It is only the room it
/// takes that is worth anything, so it is swept on size rather than on every
/// free: a tree of a few thousand nodes asks a handful of questions about each.
const KEEP: usize = 1 << 16;

/// `f`, unless this exact question has already been answered about this node
/// and nothing under it has moved since.
///
/// The borrow is dropped before `f` runs: `f` measures children, which asks
/// again through here, and holding it across the call would panic on the first
/// nested box.
fn remember(tree: &Tree, question: Question, id: u32, avail: u16, f: impl FnOnce() -> u16) -> u16 {
    let rev = tree.revision_of(id);
    let key = (question, id, avail);
    if let Some((then, known)) = SIZES.with(|m| m.borrow().get(&key).copied()) {
        if then == rev {
            return known;
        }
    }
    let answer = f();
    SIZES.with(|m| {
        let mut map = m.borrow_mut();
        if map.len() >= KEEP {
            map.clear();
        }
        map.insert(key, (rev, answer));
    });
    answer
}

/// How a child that is not filling its cross axis sits in the space it was
/// given. `:halign` and `:valign` in the props.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Align {
    Fill,
    Start,
    Center,
    End,
}

impl Align {
    pub fn parse(text: &str) -> Self {
        match text {
            "start" => Self::Start,
            "center" | "centre" => Self::Center,
            "end" => Self::End,
            _ => Self::Fill,
        }
    }

    /// Where a span of `size` sits inside `avail`.
    fn offset(self, size: u16, avail: u16) -> u16 {
        let slack = avail.saturating_sub(size);
        match self {
            Self::Fill | Self::Start => 0,
            Self::Center => slack / 2,
            Self::End => slack,
        }
    }
}

/// Whether a box stacks its children across or down.
pub fn horizontal(props: &Props) -> bool {
    props.str("orientation") == "horizontal"
}

/// The cells a node gives up on each side before its content starts. `:margin`
/// and `:padding` are one inset here — a terminal cell has no border between
/// them to tell them apart, and a caller that sets both means both.
pub fn inset(tag: &Tag, props: &Props) -> u16 {
    let own = props.cells("margin", 0) + props.cells("padding", 0);
    // A frame — and an overlay, which is a frame that floats — spends a cell a
    // side on its border.
    own + if matches!(tag, Tag::Frame | Tag::Overlay) {
        1
    } else {
        0
    }
}

/// What a `:reaction` reads as: the glyph, and the tally when there is one.
/// A pill with no count is the chip you press to put one there — the same
/// picture the picker offers, which is the point of it being the same node.
pub fn pill_text(props: &Props) -> String {
    let glyph = props.str("emoji");
    match props.cells("count", 0) {
        0 => glyph.to_owned(),
        n => format!("{glyph} {n}"),
    }
}

/// Break `text` to `width` columns, on spaces where it can and mid-word where
/// it must. Explicit newlines are always breaks.
pub fn wrap(text: &str, width: u16) -> Vec<String> {
    if width == 0 {
        return Vec::new();
    }
    let width = width as usize;
    let mut lines = Vec::new();
    for paragraph in text.split('\n') {
        let mut line = String::new();
        let mut len = 0usize;
        for word in paragraph.split(' ') {
            // In columns, not characters: an emoji is drawn two cells wide, so
            // a line of them measured by character is twice the width it was
            // wrapped to and runs off the edge.
            let word_len = text_cols(word) as usize;
            if len > 0 && len + 1 + word_len > width {
                lines.push(std::mem::take(&mut line));
                len = 0;
            }
            if word_len > width {
                // Longer than the whole line: break it where the line ends
                // rather than let it run off the edge.
                for glyph in glyphs(word) {
                    let cols = glyph_cols(&glyph) as usize;
                    if len + cols > width && len > 0 {
                        lines.push(std::mem::take(&mut line));
                        len = 0;
                    }
                    line.push_str(&glyph);
                    len += cols;
                }
                continue;
            }
            if len > 0 {
                line.push(' ');
                len += 1;
            }
            line.push_str(word);
            len += word_len;
        }
        lines.push(line);
    }
    lines
}

fn columns(text: &str) -> u16 {
    text.split('\n').map(text_cols).max().unwrap_or(0)
}

/// The longest single word — a label cannot usefully be narrower than this.
fn longest_word(text: &str) -> u16 {
    text.split([' ', '\n']).map(text_cols).max().unwrap_or(0)
}

/// The cells a picture is given: its own shape, inside the caller's bounds and
/// inside the room the column has.
///
/// Without the protocol to draw one there is no picture, only the note that
/// says there was — so the box is a line, and the link in the message above it
/// is what the reader is left with either way.
pub fn image_cells(props: &Props, avail: u16) -> (u16, u16) {
    let path = props.str("src");
    if path.is_empty() {
        return (0, 0);
    }
    if !graphics::supported() {
        return (text_cols(PICTURE), 1);
    }
    let max_cols = match props.cells("max-width", 0) {
        0 => avail,
        want => want.min(avail),
    };
    let max_rows = match props.cells("max-height", 0) {
        0 => 16,
        want => want,
    };
    graphics::cells_for(path, max_cols, max_rows)
}

/// What stands in for a picture where one cannot be drawn.
pub const PICTURE: &str = "[ picture ]";

/// The text an entry shows: its own, or its placeholder when it has none.
pub fn entry_text(props: &Props) -> String {
    let text = props.str("text");
    if text.is_empty() {
        props.str("placeholder").to_owned()
    } else {
        text.to_owned()
    }
}

/// Whether an entry is a box of text rather than a line of it.
///
/// Asked for the rows it was given, and also of the text itself: a field with
/// a newline in it is a box whatever it was declared as, and drawing that text
/// on one line would show the newline as a hole and hide everything after it.
pub fn entry_multiline(props: &Props) -> bool {
    props.cells("rows", 1) > 1 || props.str("text").contains('\n')
}

/// A node's content size before its own request or inset is applied.
fn intrinsic_width(tree: &Tree, id: u32, minimum: bool) -> u16 {
    let tag = tree.tag_of(id);
    let props = tree.props_of(id);
    let text = props.label();
    match tag {
        Tag::Button => columns(text).saturating_add(4),
        Tag::CheckButton => columns(text).saturating_add(4),
        Tag::Entry => {
            // The longest line of it: a box of text is as wide as its widest
            // row, not as wide as all its rows laid end to end.
            let text = entry_text(props);
            let widest = text.split('\n').map(columns).max().unwrap_or(0);
            let want = widest.saturating_add(1).max(12);
            if minimum {
                want.min(6)
            } else {
                want
            }
        }
        Tag::Label | Tag::Title | Tag::DimLabel => {
            if minimum {
                longest_word(text)
            } else {
                columns(text)
            }
        }
        // An unknown tag with nothing under it paints its own text, so it has
        // to be measured as the label it turns out to be — a widget given no
        // room is as invisible as one that was never painted.
        //
        // Unless it names a picture. An `:avatar`'s label is the nick behind
        // the face and an `:image`'s is its alt text: words for something that
        // cannot be drawn here, and in frq's case words already on the row
        // beside it, which is how every sender came out named twice.
        Tag::Unknown(_) if tree.child_count(id) == 0 && !has_picture(props) => {
            if minimum {
                longest_word(props.label())
            } else {
                columns(props.label())
            }
        }
        Tag::Separator => 1,
        Tag::Spacer => props.cells("size", 1),
        Tag::Emoji => text_cols(props.str("emoji")),
        Tag::Image => image_cells(props, u16::MAX).0,
        Tag::Reaction => text_cols(&pill_text(props)),
        Tag::Progress => {
            if minimum {
                4
            } else {
                20
            }
        }
        Tag::Spinner => 1,
        Tag::Listbox => tree
            .children_of(id)
            .iter()
            .map(|c| intrinsic_width(tree, *c, minimum).saturating_add(2))
            .max()
            .unwrap_or(0),
        // Every container measures its children the same way; only the axis
        // the sum runs along differs.
        Tag::Box | Tag::Window | Tag::Frame | Tag::Scroll | Tag::Overlay | Tag::Unknown(_) => {
            let children = tree.children_of(id);
            let spacing = props.cells("spacing", 0);
            let sizes = children
                .iter()
                .map(|c| width(tree, *c, minimum))
                .collect::<Vec<_>>();
            let content = if horizontal(props) && matches!(tag, Tag::Box) {
                let gaps = spacing.saturating_mul(sizes.len().saturating_sub(1) as u16);
                sizes.iter().fold(gaps, |a, b| a.saturating_add(*b))
            } else {
                sizes.into_iter().max().unwrap_or(0)
            };
            // A frame's heading sits in its top edge, so it is part of how wide
            // the frame has to be — a box narrower than its own label reads as
            // a truncated one.
            if matches!(tag, Tag::Frame | Tag::Overlay) {
                content.max(columns(props.label()).saturating_add(2))
            } else {
                content
            }
        }
    }
}

/// True for a node whose label describes a picture rather than being text to
/// paint — an `:avatar`, an `:image`, a live `:feed`.
fn has_picture(props: &Props) -> bool {
    props.has("src") || props.has("feed")
}

/// A node's natural or minimum width, requests and insets included.
///
/// A `width-request` is the width, not a floor under it. In a window it can be
/// a floor, because a label wraps to whatever it is given and a column's
/// natural width is therefore whatever the layout decides. Here a label's
/// natural width is its whole line, so a column that holds one is as wide as
/// the longest thing anybody ever said in it — and `max` then hands the
/// sidebar the screen and leaves the conversation beside it ten cells to wrap
/// in. Asking for a width is the caller saying how wide the column is; nothing
/// else in a terminal can say it for them.
pub fn width(tree: &Tree, id: u32, minimum: bool) -> u16 {
    remember(tree, Question::Width { minimum }, id, 0, || {
        width_uncached(tree, id, minimum)
    })
}

fn width_uncached(tree: &Tree, id: u32, minimum: bool) -> u16 {
    let props = tree.props_of(id);
    let requested = props.cells("width-request", 0);
    if requested > 0 {
        return requested;
    }
    let pad = inset(tree.tag_of(id), props).saturating_mul(2);
    intrinsic_width(tree, id, minimum).saturating_add(pad)
}

/// How tall `id` is when laid out `avail` columns wide.
///
/// Height depends on width — that is what wrapping means — so there is no
/// natural height to ask for on its own.
pub fn height_for_width(tree: &Tree, id: u32, avail: u16) -> u16 {
    remember(tree, Question::Height, id, avail, || {
        height_for_width_uncached(tree, id, avail)
    })
}

fn height_for_width_uncached(tree: &Tree, id: u32, avail: u16) -> u16 {
    let tag = tree.tag_of(id);
    let props = tree.props_of(id);
    let pad = inset(tag, props);
    let inner = avail.saturating_sub(pad.saturating_mul(2));
    let content = match tag {
        Tag::Label | Tag::Title | Tag::DimLabel => wrap(props.label(), inner).len() as u16,
        Tag::Unknown(_) if tree.child_count(id) == 0 && !has_picture(props) => {
            wrap(props.label(), inner).len() as u16
        }
        Tag::Button
        | Tag::CheckButton
        | Tag::Separator
        | Tag::Progress
        | Tag::Spinner
        | Tag::Reaction
        | Tag::Emoji => 1,
        Tag::Image => image_cells(props, inner).1,
        Tag::Entry => props.cells("rows", 1).max(1),
        Tag::Spacer => props.cells("size", 1),
        Tag::Listbox => tree.child_count(id) as u16,
        Tag::Box | Tag::Window | Tag::Frame | Tag::Scroll | Tag::Overlay | Tag::Unknown(_) => {
            let children = tree.children_of(id);
            let spacing = props.cells("spacing", 0);
            if horizontal(props) && matches!(tag, Tag::Box) {
                // Across: each child is measured at the width it will get.
                let shares = share(tree, id, inner, true, 0);
                children
                    .iter()
                    .zip(shares)
                    .map(|(c, w)| height_for_width(tree, *c, w))
                    .max()
                    .unwrap_or(0)
            } else {
                let gaps = spacing.saturating_mul(children.len().saturating_sub(1) as u16);
                children
                    .iter()
                    .map(|c| height_for_width(tree, *c, inner))
                    .fold(gaps, |a, b| a.saturating_add(b))
            }
        }
    };
    let want = content
        .saturating_add(pad.saturating_mul(2))
        .max(props.cells("height-request", 0));
    match props.cells("max-height", 0) {
        0 => want,
        most => want.min(most),
    }
}

/// The least `id` can be squeezed to at `avail` columns wide.
///
/// Down the page almost nothing can be shorter than it is: a label wrapped to
/// four lines needs four. A `:scroll` is the exception, and the reason there is
/// one — it is a viewport, so its height is whatever it is given and its
/// content moves inside it.
///
/// It has to recurse, because the viewport is rarely the child being measured.
/// In frq's chat screen the backlog is a scroll inside a column inside a row
/// inside the screen, and a column that reported its natural height all the
/// way up gave the layout nothing to take: the backlog kept every row it asked
/// for and the separator and compose bar under it were painted past the bottom
/// edge — a conversation you cannot type into.
pub fn min_height_for_width(tree: &Tree, id: u32, avail: u16) -> u16 {
    remember(tree, Question::MinHeight, id, avail, || {
        min_height_for_width_uncached(tree, id, avail)
    })
}

fn min_height_for_width_uncached(tree: &Tree, id: u32, avail: u16) -> u16 {
    let tag = tree.tag_of(id);
    let props = tree.props_of(id);
    let pad = inset(tag, props);
    let inner = avail.saturating_sub(pad.saturating_mul(2));
    let content = match tag {
        Tag::Scroll => 1,
        Tag::Box | Tag::Window | Tag::Frame | Tag::Overlay | Tag::Unknown(_)
            if tree.child_count(id) > 0 =>
        {
            let children = tree.children_of(id);
            let spacing = props.cells("spacing", 0);
            if horizontal(props) && matches!(tag, Tag::Box) {
                let shares = share(tree, id, inner, true, 0);
                children
                    .iter()
                    .zip(shares)
                    .map(|(c, w)| min_height_for_width(tree, *c, w))
                    .max()
                    .unwrap_or(0)
            } else {
                let gaps = spacing.saturating_mul(children.len().saturating_sub(1) as u16);
                children
                    .iter()
                    .map(|c| min_height_for_width(tree, *c, inner))
                    .fold(gaps, |a, b| a.saturating_add(b))
            }
        }
        // Everything else is as short as it is tall.
        _ => return height_for_width(tree, id, avail),
    };
    content
        .saturating_add(pad.saturating_mul(2))
        .max(props.cells("height-request", 0))
}

/// Share `avail` out among the children of `id` along one axis.
///
/// `across` picks the axis: true for a horizontal box sharing columns, false
/// for a vertical one sharing rows. The rule is the same either way — natural
/// sizes first, shrink proportionally toward the minimums when short, and the
/// surplus to whoever set `:hexpand` / `:vexpand`.
///
/// `cross` is the extent on the *other* axis, and sharing rows out cannot be
/// done without it: how tall a child is depends on how wide it is, because
/// that is what wrapping means. Passing the rows in its place measures every
/// label at a column count of two or three, wraps it to a paragraph, and the
/// overrun is then taken off the end — which paints a box's first child and
/// drops every sibling after it. Unused when `across`, where a width does not
/// depend on a height.
pub fn share(tree: &Tree, id: u32, avail: u16, across: bool, cross: u16) -> Vec<u16> {
    let rev = tree.revision_of(id);
    let key = (id, avail, across, cross);
    if let Some((then, known)) = SHARES.with(|m| m.borrow().get(&key).cloned()) {
        if then == rev {
            return known;
        }
    }
    let shares = share_uncached(tree, id, avail, across, cross);
    SHARES.with(|m| {
        let mut map = m.borrow_mut();
        if map.len() >= KEEP {
            map.clear();
        }
        map.insert(key, (rev, shares.clone()));
    });
    shares
}

fn share_uncached(tree: &Tree, id: u32, avail: u16, across: bool, cross: u16) -> Vec<u16> {
    let children = tree.children_of(id);
    if children.is_empty() {
        return Vec::new();
    }
    let props = tree.props_of(id);
    let spacing = props.cells("spacing", 0);
    let gaps = spacing.saturating_mul((children.len() - 1) as u16);
    let room = avail.saturating_sub(gaps) as i64;

    let measure = |child: u32, minimum: bool| -> i64 {
        if across {
            width(tree, child, minimum) as i64
        } else if minimum {
            min_height_for_width(tree, child, cross) as i64
        } else {
            // A child's height depends on the width it gets, which the caller
            // has already fixed by the time it asks.
            height_for_width(tree, child, cross) as i64
        }
    };

    let nat: Vec<i64> = children.iter().map(|c| measure(*c, false)).collect();
    let min: Vec<i64> = children
        .iter()
        .zip(&nat)
        .map(|(c, n)| measure(*c, true).min(*n))
        .collect();
    let total: i64 = nat.iter().sum();
    let mut out = nat.clone();

    if total > room {
        // Short: take the overrun out of whatever each child is willing to give
        // up, in proportion to how much that is.
        let mut over = total - room;
        let slack: i64 = nat.iter().zip(&min).map(|(n, m)| n - m).sum();
        if slack > 0 {
            for i in 0..out.len() {
                let give = ((nat[i] - min[i]) * over.min(slack)) / slack;
                out[i] -= give;
            }
            over -= nat.iter().zip(&out).map(|(n, o)| n - o).sum::<i64>();
        }
        // Rounding, and children with no slack at all: take the rest off the
        // end, which is where a terminal clips anyway.
        let mut i = out.len();
        while over > 0 && i > 0 {
            i -= 1;
            let give = (out[i] - min[i]).min(over);
            out[i] -= give;
            over -= give;
        }
    } else if total < room {
        let key = if across { "hexpand" } else { "vexpand" };
        let greedy: Vec<usize> = children
            .iter()
            .enumerate()
            .filter(|(_, c)| tree.props_of(**c).bool(key, false))
            .map(|(i, _)| i)
            .collect();
        if !greedy.is_empty() {
            let extra = room - total;
            let each = extra / greedy.len() as i64;
            let mut rest = extra % greedy.len() as i64;
            for i in greedy {
                out[i] += each + if rest > 0 { 1 } else { 0 };
                rest -= 1;
            }
        }
    }
    out.into_iter()
        .map(|n| n.clamp(0, u16::MAX as i64) as u16)
        .collect()
}

/// The rect a child of `size` gets inside `avail` on its cross axis.
pub fn place(align: Align, size: u16, avail: u16) -> (u16, u16) {
    match align {
        Align::Fill => (0, avail),
        other => {
            let size = size.min(avail);
            (other.offset(size, avail), size)
        }
    }
}

/// Lay the children of a box out inside `area`.
pub fn children_rects(tree: &Tree, id: u32, area: Rect) -> Vec<Rect> {
    let props = tree.props_of(id);
    let across = horizontal(props) && matches!(tree.tag_of(id), Tag::Box);
    let spacing = props.cells("spacing", 0);
    let children = tree.children_of(id);
    let shares = share(
        tree,
        id,
        if across { area.w } else { area.h },
        across,
        if across { area.h } else { area.w },
    );

    let mut out = Vec::with_capacity(children.len());
    let mut at = 0u16;
    for (child, main) in children.iter().zip(shares) {
        let cprops = tree.props_of(*child);
        let rect = if across {
            let want = height_for_width(tree, *child, main).max(cprops.cells("height-request", 0));
            let (dy, h) = place(Align::parse(cprops.str("valign")), want, area.h);
            Rect::new(
                area.x.saturating_add(at),
                area.y.saturating_add(dy),
                main,
                h,
            )
        } else {
            let want = width(tree, *child, false);
            let (dx, w) = place(Align::parse(cprops.str("halign")), want, area.w);
            Rect::new(
                area.x.saturating_add(dx),
                area.y.saturating_add(at),
                w,
                main,
            )
        };
        out.push(rect);
        at = at.saturating_add(main).saturating_add(spacing);
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tree::Value;

    fn label(tree: &mut Tree, parent: u32, text: &str) -> u32 {
        let id = tree.new_node("label");
        tree.set(id, "label", Value::Str(text.into()));
        tree.append(parent, id);
        id
    }

    #[test]
    fn wrapping_breaks_on_spaces_and_mid_word_when_it_must() {
        assert_eq!(wrap("one two three", 7), vec!["one two", "three"]);
        assert_eq!(
            wrap("antidisestablishment", 6),
            vec!["antidi", "sestab", "lishme", "nt"]
        );
        assert_eq!(wrap("a\nb", 10), vec!["a", "b"]);
    }

    #[test]
    fn a_size_measured_before_a_change_is_not_the_answer_after_one() {
        // Sizes are kept between frames, so what has to be right is when they
        // stop being. A word typed into a label three boxes down changes how
        // tall the box at the top is, and the answer taken before it has to go
        // for every one of them — which is what the walk up the parents in
        // `Tree::touch` is for.
        let mut tree = Tree::new();
        let root = tree.root();
        let outer = tree.new_node("vbox");
        tree.append(root, outer);
        let inner = tree.new_node("vbox");
        tree.append(outer, inner);
        let text = label(&mut tree, inner, "one");
        assert_eq!(height_for_width(&tree, outer, 10), 1);
        tree.set(text, "label", Value::Str("one two three four".into()));
        assert_eq!(
            height_for_width(&tree, outer, 10),
            2,
            "the label now wraps, and the boxes above it are a row taller"
        );
    }

    #[test]
    fn a_label_is_as_wide_as_its_text_and_as_narrow_as_its_longest_word() {
        let mut tree = Tree::new();
        let root = tree.root();
        let id = label(&mut tree, root, "one two three");
        assert_eq!(width(&tree, id, false), 13);
        assert_eq!(width(&tree, id, true), 5);
        assert_eq!(height_for_width(&tree, id, 7), 2);
    }

    #[test]
    fn a_width_request_is_a_floor_on_both_sizes() {
        let mut tree = Tree::new();
        let root = tree.root();
        let id = label(&mut tree, root, "hi");
        tree.set(id, "width-request", Value::Num(20.0));
        assert_eq!(width(&tree, id, false), 20);
        assert_eq!(width(&tree, id, true), 20);
    }

    #[test]
    fn a_height_request_of_four_rows_gets_four_rows() {
        let mut tree = Tree::new();
        let root = tree.root();
        let id = label(&mut tree, root, "hi");
        tree.set(id, "height-request", Value::Num(4.0));
        assert_eq!(height_for_width(&tree, id, 10), 4);
    }

    #[test]
    fn a_horizontal_box_gives_the_surplus_to_whoever_expands() {
        let mut tree = Tree::new();
        let row = tree.new_node("hbox");
        tree.set(row, "orientation", Value::Str("horizontal".into()));
        let root = tree.root();
        tree.append(root, row);
        let a = label(&mut tree, row, "aa");
        let b = label(&mut tree, row, "bb");
        tree.set(b, "hexpand", Value::Bool(true));
        assert_eq!(share(&tree, row, 20, true, 1), vec![2, 18]);
        let _ = a;
    }

    #[test]
    fn a_short_box_shrinks_toward_the_minimums_rather_than_clipping_the_first_child() {
        let mut tree = Tree::new();
        let row = tree.new_node("hbox");
        tree.set(row, "orientation", Value::Str("horizontal".into()));
        let root = tree.root();
        tree.append(root, row);
        label(&mut tree, row, "one two");
        label(&mut tree, row, "three four");
        // 17 natural, 10 offered: both give up some, neither goes under its
        // longest word.
        let shares = share(&tree, row, 10, true, 1);
        assert_eq!(shares.iter().sum::<u16>(), 10);
        assert!(shares[0] >= 3 && shares[1] >= 5, "{shares:?}");
    }

    #[test]
    fn spacing_comes_off_the_room_before_it_is_shared() {
        let mut tree = Tree::new();
        let row = tree.new_node("hbox");
        tree.set(row, "orientation", Value::Str("horizontal".into()));
        tree.set(row, "spacing", Value::Num(2.0));
        let root = tree.root();
        tree.append(root, row);
        let a = label(&mut tree, row, "aa");
        let b = label(&mut tree, row, "bb");
        tree.set(a, "hexpand", Value::Bool(true));
        tree.set(b, "hexpand", Value::Bool(true));
        assert_eq!(share(&tree, row, 12, true, 1), vec![5, 5]);
    }

    #[test]
    fn a_column_shares_its_rows_out_at_the_width_it_has() {
        // A column two rows tall and thirty columns wide holds two labels, and
        // each is one row at that width. Measured against the rows instead —
        // as this did — "the second line" wraps to five, the overrun comes off
        // the end, and the second child is handed nothing: a box that paints
        // its first child and drops the rest, which is what the chats list did
        // to every Open button in it.
        let mut tree = Tree::new();
        let col = tree.new_node("vbox");
        tree.set(col, "orientation", Value::Str("vertical".into()));
        let root = tree.root();
        tree.append(root, col);
        label(&mut tree, col, "the first line");
        label(&mut tree, col, "the second line");
        assert_eq!(share(&tree, col, 2, false, 30), vec![1, 1]);
    }

    #[test]
    fn a_centred_child_sits_in_the_middle_of_its_row() {
        assert_eq!(place(Align::Center, 4, 10), (3, 4));
        assert_eq!(place(Align::End, 4, 10), (6, 4));
        assert_eq!(place(Align::Fill, 4, 10), (0, 10));
    }

    #[test]
    fn a_frame_spends_a_cell_a_side_on_its_border() {
        let mut tree = Tree::new();
        let frame = tree.new_node("frame");
        let root = tree.root();
        tree.append(root, frame);
        label(&mut tree, frame, "hi");
        assert_eq!(width(&tree, frame, false), 4);
        assert_eq!(height_for_width(&tree, frame, 4), 3);
    }
}