nandi/jolt-nativepublic Fork 0
c03a75281355a14d95e6e810f66f52d4ac6d4977
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 · 789 lines · 29.4 KBRust Blame HistoryRaw
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago1//! Two sizes per node, and how a box shares out what it has.
2//!
3//! Every node answers a *natural* size — what it would like — and a *minimum*
4//! — what it can survive on. A container hands out its natural sizes when there
5//! is room, shrinks them proportionally toward the minimums when there is not,
6//! and gives the surplus to whoever asked to expand. `:width-request` and
7//! `:height-request` are a floor on both numbers, so asking for four rows gets
8//! four rows even when space is short.
9//!
10//! Nothing here touches a terminal or the screen grid: sizes are arithmetic on
11//! the tree, which is why the layout tests below need no TTY.
12
Draw a picture in a terminal, over the Kitty graphics protocol c2d912f nandi 16d ago13use crate::graphics;
Keep a glyph whole, selector and all, and copy it across whole 3dd441e nandi 16d ago14use crate::screen::{glyph_cols, glyphs, text_cols, Rect};
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago15use crate::tree::{Props, Tag, Tree};
16
Measure a node once, and paint only what is on screen c41903b nandi 16d ago17use std::cell::RefCell;
18use std::collections::HashMap;
19
20// --- measuring the same node twice -------------------------------------------
21// A size here is a pure function of the tree, and the tree does not move while
22// it is being measured: the reconciler's changes arrive between frames, and
23// painting takes the tree by shared reference. So an answer can be kept.
24//
25// It has to be. Nothing below asks a node its size once. A box shares its room
26// out by measuring every child, then `children_rects` measures them again to
27// place them, and then the painter recurses and the child repeats the whole
28// thing for its own children — so a node is measured once for every ancestor
29// that asks, and the work under a message doubles with every box it is wrapped
30// in. On frq's backlog, six deep, that is what made a frame cost the best part
31// of a second: not the wrapping, but the same wrapping done sixty times.
32//
33// Keyed on what the answer depends on and nothing else — the node, the room it
34// was given, and which of the four questions was asked.
35
36#[derive(Clone, Copy, PartialEq, Eq, Hash)]
37enum Question {
38 Width { minimum: bool },
39 Height,
40 MinHeight,
41}
42
43/// A question about a node, and the room it was asked about.
44type Asked = (Question, u32, u16);
45/// A box, the room it had, the axis and the extent across it.
46type Divided = (u32, u16, bool, u16);
47/// An answer, and the subtree revision it was true of.
48type Answered<T> = (u64, T);
49
50thread_local! {
51 /// Sizes answered so far, and the shares boxes divided out. Each remembers
52 /// the subtree revision it was taken at, which is what makes it safe to
53 /// keep past the frame that asked.
54 static SIZES: RefCell<HashMap<Asked, Answered<u16>>> = RefCell::new(HashMap::new());
55 static SHARES: RefCell<HashMap<Divided, Answered<Vec<u16>>>> =
56 RefCell::new(HashMap::new());
57}
58
59/// An answer for a node that has been freed since is never right again, and its
60/// handle will be handed out to some other node — which gets a fresh revision,
61/// so the stale entry is refused rather than believed. It is only the room it
62/// takes that is worth anything, so it is swept on size rather than on every
63/// free: a tree of a few thousand nodes asks a handful of questions about each.
64const KEEP: usize = 1 << 16;
65
66/// `f`, unless this exact question has already been answered about this node
67/// and nothing under it has moved since.
68///
69/// The borrow is dropped before `f` runs: `f` measures children, which asks
70/// again through here, and holding it across the call would panic on the first
71/// nested box.
72fn remember(tree: &Tree, question: Question, id: u32, avail: u16, f: impl FnOnce() -> u16) -> u16 {
73 let rev = tree.revision_of(id);
74 let key = (question, id, avail);
75 if let Some((then, known)) = SIZES.with(|m| m.borrow().get(&key).copied()) {
76 if then == rev {
77 return known;
78 }
79 }
80 let answer = f();
81 SIZES.with(|m| {
82 let mut map = m.borrow_mut();
83 if map.len() >= KEEP {
84 map.clear();
85 }
86 map.insert(key, (rev, answer));
87 });
88 answer
89}
90
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago91/// How a child that is not filling its cross axis sits in the space it was
92/// given. `:halign` and `:valign` in the props.
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94pub enum Align {
95 Fill,
96 Start,
97 Center,
98 End,
99}
100
101impl Align {
102 pub fn parse(text: &str) -> Self {
103 match text {
104 "start" => Self::Start,
105 "center" | "centre" => Self::Center,
106 "end" => Self::End,
107 _ => Self::Fill,
108 }
109 }
110
111 /// Where a span of `size` sits inside `avail`.
112 fn offset(self, size: u16, avail: u16) -> u16 {
113 let slack = avail.saturating_sub(size);
114 match self {
115 Self::Fill | Self::Start => 0,
116 Self::Center => slack / 2,
117 Self::End => slack,
118 }
119 }
120}
121
122/// Whether a box stacks its children across or down.
123pub fn horizontal(props: &Props) -> bool {
124 props.str("orientation") == "horizontal"
125}
126
127/// The cells a node gives up on each side before its content starts. `:margin`
128/// and `:padding` are one inset here — a terminal cell has no border between
129/// them to tell them apart, and a caller that sets both means both.
130pub fn inset(tag: &Tag, props: &Props) -> u16 {
131 let own = props.cells("margin", 0) + props.cells("padding", 0);
132 // A frame — and an overlay, which is a frame that floats — spends a cell a
133 // side on its border.
134 own + if matches!(tag, Tag::Frame | Tag::Overlay) {
135 1
136 } else {
137 0
138 }
139}
140
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago141/// What a `:reaction` reads as: the glyph, and the tally when there is one.
142/// A pill with no count is the chip you press to put one there — the same
143/// picture the picker offers, which is the point of it being the same node.
144pub fn pill_text(props: &Props) -> String {
145 let glyph = props.str("emoji");
146 match props.cells("count", 0) {
147 0 => glyph.to_owned(),
148 n => format!("{glyph} {n}"),
149 }
150}
151
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago152/// Break `text` to `width` columns, on spaces where it can and mid-word where
153/// it must. Explicit newlines are always breaks.
154pub fn wrap(text: &str, width: u16) -> Vec<String> {
155 if width == 0 {
156 return Vec::new();
157 }
158 let width = width as usize;
159 let mut lines = Vec::new();
160 for paragraph in text.split('\n') {
161 let mut line = String::new();
162 let mut len = 0usize;
163 for word in paragraph.split(' ') {
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago164 // In columns, not characters: an emoji is drawn two cells wide, so
165 // a line of them measured by character is twice the width it was
166 // wrapped to and runs off the edge.
167 let word_len = text_cols(word) as usize;
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago168 if len > 0 && len + 1 + word_len > width {
169 lines.push(std::mem::take(&mut line));
170 len = 0;
171 }
172 if word_len > width {
173 // Longer than the whole line: break it where the line ends
174 // rather than let it run off the edge.
Keep a glyph whole, selector and all, and copy it across whole 3dd441e nandi 16d ago175 for glyph in glyphs(word) {
176 let cols = glyph_cols(&glyph) as usize;
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago177 if len + cols > width && len > 0 {
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago178 lines.push(std::mem::take(&mut line));
179 len = 0;
180 }
Keep a glyph whole, selector and all, and copy it across whole 3dd441e nandi 16d ago181 line.push_str(&glyph);
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago182 len += cols;
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago183 }
184 continue;
185 }
186 if len > 0 {
187 line.push(' ');
188 len += 1;
189 }
190 line.push_str(word);
191 len += word_len;
192 }
193 lines.push(line);
194 }
195 lines
196}
197
198fn columns(text: &str) -> u16 {
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago199 text.split('\n').map(text_cols).max().unwrap_or(0)
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago200}
201
202/// The longest single word — a label cannot usefully be narrower than this.
203fn longest_word(text: &str) -> u16 {
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago204 text.split([' ', '\n']).map(text_cols).max().unwrap_or(0)
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago205}
206
Draw a picture in a terminal, over the Kitty graphics protocol c2d912f nandi 16d ago207/// The cells a picture is given: its own shape, inside the caller's bounds and
208/// inside the room the column has.
209///
210/// Without the protocol to draw one there is no picture, only the note that
211/// says there was — so the box is a line, and the link in the message above it
212/// is what the reader is left with either way.
213pub fn image_cells(props: &Props, avail: u16) -> (u16, u16) {
214 let path = props.str("src");
215 if path.is_empty() {
216 return (0, 0);
217 }
218 if !graphics::supported() {
219 return (text_cols(PICTURE), 1);
220 }
221 let max_cols = match props.cells("max-width", 0) {
222 0 => avail,
223 want => want.min(avail),
224 };
225 let max_rows = match props.cells("max-height", 0) {
226 0 => 16,
227 want => want,
228 };
229 graphics::cells_for(path, max_cols, max_rows)
230}
231
232/// What stands in for a picture where one cannot be drawn.
233pub const PICTURE: &str = "[ picture ]";
234
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago235/// The text an entry shows: its own, or its placeholder when it has none.
236pub fn entry_text(props: &Props) -> String {
237 let text = props.str("text");
238 if text.is_empty() {
239 props.str("placeholder").to_owned()
240 } else {
241 text.to_owned()
242 }
243}
244
245/// A node's content size before its own request or inset is applied.
246fn intrinsic_width(tree: &Tree, id: u32, minimum: bool) -> u16 {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago247 let tag = tree.tag_of(id);
248 let props = tree.props_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago249 let text = props.label();
250 match tag {
251 Tag::Button => columns(text).saturating_add(4),
252 Tag::CheckButton => columns(text).saturating_add(4),
253 Tag::Entry => {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago254 let want = columns(&entry_text(props)).saturating_add(1).max(12);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago255 if minimum {
256 want.min(6)
257 } else {
258 want
259 }
260 }
261 Tag::Label | Tag::Title | Tag::DimLabel => {
262 if minimum {
263 longest_word(text)
264 } else {
265 columns(text)
266 }
267 }
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago268 // An unknown tag with nothing under it paints its own text, so it has
269 // to be measured as the label it turns out to be — a widget given no
270 // room is as invisible as one that was never painted.
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago271 //
272 // Unless it names a picture. An `:avatar`'s label is the nick behind
273 // the face and an `:image`'s is its alt text: words for something that
274 // cannot be drawn here, and in frq's case words already on the row
275 // beside it, which is how every sender came out named twice.
Measure a node once, and paint only what is on screen c41903b nandi 16d ago276 Tag::Unknown(_) if tree.child_count(id) == 0 && !has_picture(props) => {
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago277 if minimum {
278 longest_word(props.label())
279 } else {
280 columns(props.label())
281 }
282 }
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago283 Tag::Separator => 1,
284 Tag::Spacer => props.cells("size", 1),
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago285 Tag::Emoji => text_cols(props.str("emoji")),
Measure a node once, and paint only what is on screen c41903b nandi 16d ago286 Tag::Image => image_cells(props, u16::MAX).0,
287 Tag::Reaction => text_cols(&pill_text(props)),
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago288 Tag::Progress => {
289 if minimum {
290 4
291 } else {
292 20
293 }
294 }
295 Tag::Spinner => 1,
296 Tag::Listbox => tree
Measure a node once, and paint only what is on screen c41903b nandi 16d ago297 .children_of(id)
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago298 .iter()
299 .map(|c| intrinsic_width(tree, *c, minimum).saturating_add(2))
300 .max()
301 .unwrap_or(0),
302 // Every container measures its children the same way; only the axis
303 // the sum runs along differs.
304 Tag::Box | Tag::Window | Tag::Frame | Tag::Scroll | Tag::Overlay | Tag::Unknown(_) => {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago305 let children = tree.children_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago306 let spacing = props.cells("spacing", 0);
307 let sizes = children
308 .iter()
309 .map(|c| width(tree, *c, minimum))
310 .collect::<Vec<_>>();
Measure a node once, and paint only what is on screen c41903b nandi 16d ago311 let content = if horizontal(props) && matches!(tag, Tag::Box) {
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago312 let gaps = spacing.saturating_mul(sizes.len().saturating_sub(1) as u16);
313 sizes.iter().fold(gaps, |a, b| a.saturating_add(*b))
314 } else {
315 sizes.into_iter().max().unwrap_or(0)
316 };
317 // A frame's heading sits in its top edge, so it is part of how wide
318 // the frame has to be — a box narrower than its own label reads as
319 // a truncated one.
320 if matches!(tag, Tag::Frame | Tag::Overlay) {
321 content.max(columns(props.label()).saturating_add(2))
322 } else {
323 content
324 }
325 }
326 }
327}
328
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago329/// True for a node whose label describes a picture rather than being text to
330/// paint — an `:avatar`, an `:image`, a live `:feed`.
331fn has_picture(props: &Props) -> bool {
332 props.has("src") || props.has("feed")
333}
334
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago335/// A node's natural or minimum width, requests and insets included.
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago336///
337/// A `width-request` is the width, not a floor under it. In a window it can be
338/// a floor, because a label wraps to whatever it is given and a column's
339/// natural width is therefore whatever the layout decides. Here a label's
340/// natural width is its whole line, so a column that holds one is as wide as
341/// the longest thing anybody ever said in it — and `max` then hands the
342/// sidebar the screen and leaves the conversation beside it ten cells to wrap
343/// in. Asking for a width is the caller saying how wide the column is; nothing
344/// else in a terminal can say it for them.
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago345pub fn width(tree: &Tree, id: u32, minimum: bool) -> u16 {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago346 remember(tree, Question::Width { minimum }, id, 0, || {
347 width_uncached(tree, id, minimum)
348 })
349}
350
351fn width_uncached(tree: &Tree, id: u32, minimum: bool) -> u16 {
352 let props = tree.props_of(id);
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago353 let requested = props.cells("width-request", 0);
354 if requested > 0 {
355 return requested;
356 }
Measure a node once, and paint only what is on screen c41903b nandi 16d ago357 let pad = inset(tree.tag_of(id), props).saturating_mul(2);
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago358 intrinsic_width(tree, id, minimum).saturating_add(pad)
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago359}
360
361/// How tall `id` is when laid out `avail` columns wide.
362///
363/// Height depends on width — that is what wrapping means — so there is no
364/// natural height to ask for on its own.
365pub fn height_for_width(tree: &Tree, id: u32, avail: u16) -> u16 {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago366 remember(tree, Question::Height, id, avail, || {
367 height_for_width_uncached(tree, id, avail)
368 })
369}
370
371fn height_for_width_uncached(tree: &Tree, id: u32, avail: u16) -> u16 {
372 let tag = tree.tag_of(id);
373 let props = tree.props_of(id);
374 let pad = inset(tag, props);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago375 let inner = avail.saturating_sub(pad.saturating_mul(2));
376 let content = match tag {
377 Tag::Label | Tag::Title | Tag::DimLabel => wrap(props.label(), inner).len() as u16,
Measure a node once, and paint only what is on screen c41903b nandi 16d ago378 Tag::Unknown(_) if tree.child_count(id) == 0 && !has_picture(props) => {
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago379 wrap(props.label(), inner).len() as u16
380 }
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago381 Tag::Button
382 | Tag::CheckButton
383 | Tag::Separator
384 | Tag::Progress
385 | Tag::Spinner
386 | Tag::Reaction
387 | Tag::Emoji => 1,
Measure a node once, and paint only what is on screen c41903b nandi 16d ago388 Tag::Image => image_cells(props, inner).1,
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago389 Tag::Entry => props.cells("rows", 1).max(1),
390 Tag::Spacer => props.cells("size", 1),
391 Tag::Listbox => tree.child_count(id) as u16,
392 Tag::Box | Tag::Window | Tag::Frame | Tag::Scroll | Tag::Overlay | Tag::Unknown(_) => {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago393 let children = tree.children_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago394 let spacing = props.cells("spacing", 0);
Measure a node once, and paint only what is on screen c41903b nandi 16d ago395 if horizontal(props) && matches!(tag, Tag::Box) {
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago396 // Across: each child is measured at the width it will get.
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago397 let shares = share(tree, id, inner, true, 0);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago398 children
399 .iter()
400 .zip(shares)
401 .map(|(c, w)| height_for_width(tree, *c, w))
402 .max()
403 .unwrap_or(0)
404 } else {
405 let gaps = spacing.saturating_mul(children.len().saturating_sub(1) as u16);
406 children
407 .iter()
408 .map(|c| height_for_width(tree, *c, inner))
409 .fold(gaps, |a, b| a.saturating_add(b))
410 }
411 }
412 };
413 content
414 .saturating_add(pad.saturating_mul(2))
415 .max(props.cells("height-request", 0))
416}
417
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago418/// The least `id` can be squeezed to at `avail` columns wide.
419///
420/// Down the page almost nothing can be shorter than it is: a label wrapped to
421/// four lines needs four. A `:scroll` is the exception, and the reason there is
422/// one — it is a viewport, so its height is whatever it is given and its
423/// content moves inside it.
424///
425/// It has to recurse, because the viewport is rarely the child being measured.
426/// In frq's chat screen the backlog is a scroll inside a column inside a row
427/// inside the screen, and a column that reported its natural height all the
428/// way up gave the layout nothing to take: the backlog kept every row it asked
429/// for and the separator and compose bar under it were painted past the bottom
430/// edge — a conversation you cannot type into.
431pub fn min_height_for_width(tree: &Tree, id: u32, avail: u16) -> u16 {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago432 remember(tree, Question::MinHeight, id, avail, || {
433 min_height_for_width_uncached(tree, id, avail)
434 })
435}
436
437fn min_height_for_width_uncached(tree: &Tree, id: u32, avail: u16) -> u16 {
438 let tag = tree.tag_of(id);
439 let props = tree.props_of(id);
440 let pad = inset(tag, props);
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago441 let inner = avail.saturating_sub(pad.saturating_mul(2));
442 let content = match tag {
443 Tag::Scroll => 1,
444 Tag::Box | Tag::Window | Tag::Frame | Tag::Overlay | Tag::Unknown(_)
445 if tree.child_count(id) > 0 =>
446 {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago447 let children = tree.children_of(id);
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago448 let spacing = props.cells("spacing", 0);
Measure a node once, and paint only what is on screen c41903b nandi 16d ago449 if horizontal(props) && matches!(tag, Tag::Box) {
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago450 let shares = share(tree, id, inner, true, 0);
451 children
452 .iter()
453 .zip(shares)
454 .map(|(c, w)| min_height_for_width(tree, *c, w))
455 .max()
456 .unwrap_or(0)
457 } else {
458 let gaps = spacing.saturating_mul(children.len().saturating_sub(1) as u16);
459 children
460 .iter()
461 .map(|c| min_height_for_width(tree, *c, inner))
462 .fold(gaps, |a, b| a.saturating_add(b))
463 }
464 }
465 // Everything else is as short as it is tall.
466 _ => return height_for_width(tree, id, avail),
467 };
468 content
469 .saturating_add(pad.saturating_mul(2))
470 .max(props.cells("height-request", 0))
471}
472
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago473/// Share `avail` out among the children of `id` along one axis.
474///
475/// `across` picks the axis: true for a horizontal box sharing columns, false
476/// for a vertical one sharing rows. The rule is the same either way — natural
477/// sizes first, shrink proportionally toward the minimums when short, and the
478/// surplus to whoever set `:hexpand` / `:vexpand`.
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago479///
480/// `cross` is the extent on the *other* axis, and sharing rows out cannot be
481/// done without it: how tall a child is depends on how wide it is, because
482/// that is what wrapping means. Passing the rows in its place measures every
483/// label at a column count of two or three, wraps it to a paragraph, and the
484/// overrun is then taken off the end — which paints a box's first child and
485/// drops every sibling after it. Unused when `across`, where a width does not
486/// depend on a height.
487pub fn share(tree: &Tree, id: u32, avail: u16, across: bool, cross: u16) -> Vec<u16> {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago488 let rev = tree.revision_of(id);
489 let key = (id, avail, across, cross);
490 if let Some((then, known)) = SHARES.with(|m| m.borrow().get(&key).cloned()) {
491 if then == rev {
492 return known;
493 }
494 }
495 let shares = share_uncached(tree, id, avail, across, cross);
496 SHARES.with(|m| {
497 let mut map = m.borrow_mut();
498 if map.len() >= KEEP {
499 map.clear();
500 }
501 map.insert(key, (rev, shares.clone()));
502 });
503 shares
504}
505
506fn share_uncached(tree: &Tree, id: u32, avail: u16, across: bool, cross: u16) -> Vec<u16> {
507 let children = tree.children_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago508 if children.is_empty() {
509 return Vec::new();
510 }
Measure a node once, and paint only what is on screen c41903b nandi 16d ago511 let props = tree.props_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago512 let spacing = props.cells("spacing", 0);
513 let gaps = spacing.saturating_mul((children.len() - 1) as u16);
514 let room = avail.saturating_sub(gaps) as i64;
515
516 let measure = |child: u32, minimum: bool| -> i64 {
517 if across {
518 width(tree, child, minimum) as i64
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago519 } else if minimum {
520 min_height_for_width(tree, child, cross) as i64
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago521 } else {
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago522 // A child's height depends on the width it gets, which the caller
523 // has already fixed by the time it asks.
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago524 height_for_width(tree, child, cross) as i64
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago525 }
526 };
527
528 let nat: Vec<i64> = children.iter().map(|c| measure(*c, false)).collect();
529 let min: Vec<i64> = children
530 .iter()
531 .zip(&nat)
532 .map(|(c, n)| measure(*c, true).min(*n))
533 .collect();
534 let total: i64 = nat.iter().sum();
535 let mut out = nat.clone();
536
537 if total > room {
538 // Short: take the overrun out of whatever each child is willing to give
539 // up, in proportion to how much that is.
540 let mut over = total - room;
541 let slack: i64 = nat.iter().zip(&min).map(|(n, m)| n - m).sum();
542 if slack > 0 {
543 for i in 0..out.len() {
544 let give = ((nat[i] - min[i]) * over.min(slack)) / slack;
545 out[i] -= give;
546 }
547 over -= nat.iter().zip(&out).map(|(n, o)| n - o).sum::<i64>();
548 }
549 // Rounding, and children with no slack at all: take the rest off the
550 // end, which is where a terminal clips anyway.
551 let mut i = out.len();
552 while over > 0 && i > 0 {
553 i -= 1;
554 let give = (out[i] - min[i]).min(over);
555 out[i] -= give;
556 over -= give;
557 }
558 } else if total < room {
559 let key = if across { "hexpand" } else { "vexpand" };
560 let greedy: Vec<usize> = children
561 .iter()
562 .enumerate()
Measure a node once, and paint only what is on screen c41903b nandi 16d ago563 .filter(|(_, c)| tree.props_of(**c).bool(key, false))
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago564 .map(|(i, _)| i)
565 .collect();
566 if !greedy.is_empty() {
567 let extra = room - total;
568 let each = extra / greedy.len() as i64;
569 let mut rest = extra % greedy.len() as i64;
570 for i in greedy {
571 out[i] += each + if rest > 0 { 1 } else { 0 };
572 rest -= 1;
573 }
574 }
575 }
576 out.into_iter()
577 .map(|n| n.clamp(0, u16::MAX as i64) as u16)
578 .collect()
579}
580
581/// The rect a child of `size` gets inside `avail` on its cross axis.
582pub fn place(align: Align, size: u16, avail: u16) -> (u16, u16) {
583 match align {
584 Align::Fill => (0, avail),
585 other => {
586 let size = size.min(avail);
587 (other.offset(size, avail), size)
588 }
589 }
590}
591
592/// Lay the children of a box out inside `area`.
593pub fn children_rects(tree: &Tree, id: u32, area: Rect) -> Vec<Rect> {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago594 let props = tree.props_of(id);
595 let across = horizontal(props) && matches!(tree.tag_of(id), Tag::Box);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago596 let spacing = props.cells("spacing", 0);
Measure a node once, and paint only what is on screen c41903b nandi 16d ago597 let children = tree.children_of(id);
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago598 let shares = share(
599 tree,
600 id,
601 if across { area.w } else { area.h },
602 across,
603 if across { area.h } else { area.w },
604 );
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago605
606 let mut out = Vec::with_capacity(children.len());
607 let mut at = 0u16;
608 for (child, main) in children.iter().zip(shares) {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago609 let cprops = tree.props_of(*child);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago610 let rect = if across {
611 let want = height_for_width(tree, *child, main).max(cprops.cells("height-request", 0));
612 let (dy, h) = place(Align::parse(cprops.str("valign")), want, area.h);
613 Rect::new(
614 area.x.saturating_add(at),
615 area.y.saturating_add(dy),
616 main,
617 h,
618 )
619 } else {
620 let want = width(tree, *child, false);
621 let (dx, w) = place(Align::parse(cprops.str("halign")), want, area.w);
622 Rect::new(
623 area.x.saturating_add(dx),
624 area.y.saturating_add(at),
625 w,
626 main,
627 )
628 };
629 out.push(rect);
630 at = at.saturating_add(main).saturating_add(spacing);
631 }
632 out
633}
634
635#[cfg(test)]
636mod tests {
637 use super::*;
638 use crate::tree::Value;
639
640 fn label(tree: &mut Tree, parent: u32, text: &str) -> u32 {
641 let id = tree.new_node("label");
642 tree.set(id, "label", Value::Str(text.into()));
643 tree.append(parent, id);
644 id
645 }
646
647 #[test]
648 fn wrapping_breaks_on_spaces_and_mid_word_when_it_must() {
649 assert_eq!(wrap("one two three", 7), vec!["one two", "three"]);
650 assert_eq!(
651 wrap("antidisestablishment", 6),
652 vec!["antidi", "sestab", "lishme", "nt"]
653 );
654 assert_eq!(wrap("a\nb", 10), vec!["a", "b"]);
655 }
656
Measure a node once, and paint only what is on screen c41903b nandi 16d ago657 #[test]
658 fn a_size_measured_before_a_change_is_not_the_answer_after_one() {
659 // Sizes are kept between frames, so what has to be right is when they
660 // stop being. A word typed into a label three boxes down changes how
661 // tall the box at the top is, and the answer taken before it has to go
662 // for every one of them — which is what the walk up the parents in
663 // `Tree::touch` is for.
664 let mut tree = Tree::new();
665 let root = tree.root();
666 let outer = tree.new_node("vbox");
667 tree.append(root, outer);
668 let inner = tree.new_node("vbox");
669 tree.append(outer, inner);
670 let text = label(&mut tree, inner, "one");
671 assert_eq!(height_for_width(&tree, outer, 10), 1);
672 tree.set(text, "label", Value::Str("one two three four".into()));
673 assert_eq!(
674 height_for_width(&tree, outer, 10),
675 2,
676 "the label now wraps, and the boxes above it are a row taller"
677 );
678 }
679
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago680 #[test]
681 fn a_label_is_as_wide_as_its_text_and_as_narrow_as_its_longest_word() {
682 let mut tree = Tree::new();
683 let root = tree.root();
684 let id = label(&mut tree, root, "one two three");
685 assert_eq!(width(&tree, id, false), 13);
686 assert_eq!(width(&tree, id, true), 5);
687 assert_eq!(height_for_width(&tree, id, 7), 2);
688 }
689
690 #[test]
691 fn a_width_request_is_a_floor_on_both_sizes() {
692 let mut tree = Tree::new();
693 let root = tree.root();
694 let id = label(&mut tree, root, "hi");
695 tree.set(id, "width-request", Value::Num(20.0));
696 assert_eq!(width(&tree, id, false), 20);
697 assert_eq!(width(&tree, id, true), 20);
698 }
699
700 #[test]
701 fn a_height_request_of_four_rows_gets_four_rows() {
702 let mut tree = Tree::new();
703 let root = tree.root();
704 let id = label(&mut tree, root, "hi");
705 tree.set(id, "height-request", Value::Num(4.0));
706 assert_eq!(height_for_width(&tree, id, 10), 4);
707 }
708
709 #[test]
710 fn a_horizontal_box_gives_the_surplus_to_whoever_expands() {
711 let mut tree = Tree::new();
712 let row = tree.new_node("hbox");
713 tree.set(row, "orientation", Value::Str("horizontal".into()));
714 let root = tree.root();
715 tree.append(root, row);
716 let a = label(&mut tree, row, "aa");
717 let b = label(&mut tree, row, "bb");
718 tree.set(b, "hexpand", Value::Bool(true));
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago719 assert_eq!(share(&tree, row, 20, true, 1), vec![2, 18]);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago720 let _ = a;
721 }
722
723 #[test]
724 fn a_short_box_shrinks_toward_the_minimums_rather_than_clipping_the_first_child() {
725 let mut tree = Tree::new();
726 let row = tree.new_node("hbox");
727 tree.set(row, "orientation", Value::Str("horizontal".into()));
728 let root = tree.root();
729 tree.append(root, row);
730 label(&mut tree, row, "one two");
731 label(&mut tree, row, "three four");
732 // 17 natural, 10 offered: both give up some, neither goes under its
733 // longest word.
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago734 let shares = share(&tree, row, 10, true, 1);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago735 assert_eq!(shares.iter().sum::<u16>(), 10);
736 assert!(shares[0] >= 3 && shares[1] >= 5, "{shares:?}");
737 }
738
739 #[test]
740 fn spacing_comes_off_the_room_before_it_is_shared() {
741 let mut tree = Tree::new();
742 let row = tree.new_node("hbox");
743 tree.set(row, "orientation", Value::Str("horizontal".into()));
744 tree.set(row, "spacing", Value::Num(2.0));
745 let root = tree.root();
746 tree.append(root, row);
747 let a = label(&mut tree, row, "aa");
748 let b = label(&mut tree, row, "bb");
749 tree.set(a, "hexpand", Value::Bool(true));
750 tree.set(b, "hexpand", Value::Bool(true));
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago751 assert_eq!(share(&tree, row, 12, true, 1), vec![5, 5]);
752 }
753
754 #[test]
755 fn a_column_shares_its_rows_out_at_the_width_it_has() {
756 // A column two rows tall and thirty columns wide holds two labels, and
757 // each is one row at that width. Measured against the rows instead —
758 // as this did — "the second line" wraps to five, the overrun comes off
759 // the end, and the second child is handed nothing: a box that paints
760 // its first child and drops the rest, which is what the chats list did
761 // to every Open button in it.
762 let mut tree = Tree::new();
763 let col = tree.new_node("vbox");
764 tree.set(col, "orientation", Value::Str("vertical".into()));
765 let root = tree.root();
766 tree.append(root, col);
767 label(&mut tree, col, "the first line");
768 label(&mut tree, col, "the second line");
769 assert_eq!(share(&tree, col, 2, false, 30), vec![1, 1]);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago770 }
771
772 #[test]
773 fn a_centred_child_sits_in_the_middle_of_its_row() {
774 assert_eq!(place(Align::Center, 4, 10), (3, 4));
775 assert_eq!(place(Align::End, 4, 10), (6, 4));
776 assert_eq!(place(Align::Fill, 4, 10), (0, 10));
777 }
778
779 #[test]
780 fn a_frame_spends_a_cell_a_side_on_its_border() {
781 let mut tree = Tree::new();
782 let frame = tree.new_node("frame");
783 let root = tree.root();
784 tree.append(root, frame);
785 label(&mut tree, frame, "hi");
786 assert_eq!(width(&tree, frame, false), 4);
787 assert_eq!(height_for_width(&tree, frame, 4), 3);
788 }
789}