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

Paint the same tree into a terminal, for the machines with no window a7f6202 · on a7f62025fc9a5a5db4edb9a6ba6808dc31f7596b · nandi · 17d ago
layout.rs · 490 lines · 17.0 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
//! 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.
//!
//! 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::screen::Rect;
use crate::tree::{Props, Tag, Tree};

/// 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
    }
}

/// 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(' ') {
            let word_len = word.chars().count();
            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 ch in word.chars() {
                    if len == width {
                        lines.push(std::mem::take(&mut line));
                        len = 0;
                    }
                    line.push(ch);
                    len += 1;
                }
                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(|line| line.chars().count())
        .max()
        .unwrap_or(0)
        .min(u16::MAX as usize) as u16
}

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

/// 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()
    }
}

/// 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(id);
    let props = tree.props(id);
    let text = props.label();
    match tag {
        Tag::Button => columns(text).saturating_add(4),
        Tag::CheckButton => columns(text).saturating_add(4),
        Tag::Entry => {
            let want = columns(&entry_text(&props)).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)
            }
        }
        Tag::Separator => 1,
        Tag::Spacer => props.cells("size", 1),
        Tag::Progress => {
            if minimum {
                4
            } else {
                20
            }
        }
        Tag::Spinner => 1,
        Tag::Listbox => tree
            .children(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(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
            }
        }
    }
}

/// A node's natural or minimum width, requests and insets included.
pub fn width(tree: &Tree, id: u32, minimum: bool) -> u16 {
    let props = tree.props(id);
    let pad = inset(&tree.tag(id), &props).saturating_mul(2);
    let content = intrinsic_width(tree, id, minimum).saturating_add(pad);
    content.max(props.cells("width-request", 0))
}

/// 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 {
    let tag = tree.tag(id);
    let props = tree.props(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::Button | Tag::CheckButton | Tag::Separator | Tag::Progress | Tag::Spinner => 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(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);
                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))
            }
        }
    };
    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`.
pub fn share(tree: &Tree, id: u32, avail: u16, across: bool) -> Vec<u16> {
    let children = tree.children(id);
    if children.is_empty() {
        return Vec::new();
    }
    let props = tree.props(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 {
            // Down the page 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, avail) 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(**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(id);
    let across = horizontal(&props) && matches!(tree.tag(id), Tag::Box);
    let spacing = props.cells("spacing", 0);
    let children = tree.children(id);
    let shares = share(tree, id, if across { area.w } else { area.h }, across);

    let mut out = Vec::with_capacity(children.len());
    let mut at = 0u16;
    for (child, main) in children.iter().zip(shares) {
        let cprops = tree.props(*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_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), 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);
        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), vec![5, 5]);
    }

    #[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);
    }
}