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
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//!
Let a node say how tall it is willing to be 5ba95e0 nandi 7d ago10//! `:max-height` is the ceiling on the other end, and only a natural one: a
11//! node that says it is four rows tall is asking for at most four, however
12//! much is in it. It is there for a `:scroll`, whose content is as long as the
13//! list and whose whole job is to be shorter than that — without it a viewport
14//! is a viewport only on a screen too short to draw it in full, and on any
15//! other it takes the rows its neighbours were sharing.
16//!
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago17//! Nothing here touches a terminal or the screen grid: sizes are arithmetic on
18//! the tree, which is why the layout tests below need no TTY.
19
Draw a picture in a terminal, over the Kitty graphics protocol c2d912f nandi 16d ago20use crate::graphics;
Keep a glyph whole, selector and all, and copy it across whole 3dd441e nandi 16d ago21use crate::screen::{glyph_cols, glyphs, text_cols, Rect};
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago22use crate::tree::{Props, Tag, Tree};
23
Measure a node once, and paint only what is on screen c41903b nandi 15d ago24use std::cell::RefCell;
25use std::collections::HashMap;
26
27// --- measuring the same node twice -------------------------------------------
28// A size here is a pure function of the tree, and the tree does not move while
29// it is being measured: the reconciler's changes arrive between frames, and
30// painting takes the tree by shared reference. So an answer can be kept.
31//
32// It has to be. Nothing below asks a node its size once. A box shares its room
33// out by measuring every child, then `children_rects` measures them again to
34// place them, and then the painter recurses and the child repeats the whole
35// thing for its own children — so a node is measured once for every ancestor
36// that asks, and the work under a message doubles with every box it is wrapped
37// in. On frq's backlog, six deep, that is what made a frame cost the best part
38// of a second: not the wrapping, but the same wrapping done sixty times.
39//
40// Keyed on what the answer depends on and nothing else — the node, the room it
41// was given, and which of the four questions was asked.
42
43#[derive(Clone, Copy, PartialEq, Eq, Hash)]
44enum Question {
45 Width { minimum: bool },
46 Height,
47 MinHeight,
48}
49
50/// A question about a node, and the room it was asked about.
51type Asked = (Question, u32, u16);
52/// A box, the room it had, the axis and the extent across it.
53type Divided = (u32, u16, bool, u16);
54/// An answer, and the subtree revision it was true of.
55type Answered<T> = (u64, T);
56
57thread_local! {
58 /// Sizes answered so far, and the shares boxes divided out. Each remembers
59 /// the subtree revision it was taken at, which is what makes it safe to
60 /// keep past the frame that asked.
61 static SIZES: RefCell<HashMap<Asked, Answered<u16>>> = RefCell::new(HashMap::new());
62 static SHARES: RefCell<HashMap<Divided, Answered<Vec<u16>>>> =
63 RefCell::new(HashMap::new());
64}
65
66/// An answer for a node that has been freed since is never right again, and its
67/// handle will be handed out to some other node — which gets a fresh revision,
68/// so the stale entry is refused rather than believed. It is only the room it
69/// takes that is worth anything, so it is swept on size rather than on every
70/// free: a tree of a few thousand nodes asks a handful of questions about each.
71const KEEP: usize = 1 << 16;
72
73/// `f`, unless this exact question has already been answered about this node
74/// and nothing under it has moved since.
75///
76/// The borrow is dropped before `f` runs: `f` measures children, which asks
77/// again through here, and holding it across the call would panic on the first
78/// nested box.
79fn remember(tree: &Tree, question: Question, id: u32, avail: u16, f: impl FnOnce() -> u16) -> u16 {
80 let rev = tree.revision_of(id);
81 let key = (question, id, avail);
82 if let Some((then, known)) = SIZES.with(|m| m.borrow().get(&key).copied()) {
83 if then == rev {
84 return known;
85 }
86 }
87 let answer = f();
88 SIZES.with(|m| {
89 let mut map = m.borrow_mut();
90 if map.len() >= KEEP {
91 map.clear();
92 }
93 map.insert(key, (rev, answer));
94 });
95 answer
96}
97
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago98/// How a child that is not filling its cross axis sits in the space it was
99/// given. `:halign` and `:valign` in the props.
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub enum Align {
102 Fill,
103 Start,
104 Center,
105 End,
106}
107
108impl Align {
109 pub fn parse(text: &str) -> Self {
110 match text {
111 "start" => Self::Start,
112 "center" | "centre" => Self::Center,
113 "end" => Self::End,
114 _ => Self::Fill,
115 }
116 }
117
118 /// Where a span of `size` sits inside `avail`.
119 fn offset(self, size: u16, avail: u16) -> u16 {
120 let slack = avail.saturating_sub(size);
121 match self {
122 Self::Fill | Self::Start => 0,
123 Self::Center => slack / 2,
124 Self::End => slack,
125 }
126 }
127}
128
129/// Whether a box stacks its children across or down.
130pub fn horizontal(props: &Props) -> bool {
131 props.str("orientation") == "horizontal"
132}
133
134/// The cells a node gives up on each side before its content starts. `:margin`
135/// and `:padding` are one inset here — a terminal cell has no border between
136/// them to tell them apart, and a caller that sets both means both.
137pub fn inset(tag: &Tag, props: &Props) -> u16 {
138 let own = props.cells("margin", 0) + props.cells("padding", 0);
139 // A frame — and an overlay, which is a frame that floats — spends a cell a
140 // side on its border.
141 own + if matches!(tag, Tag::Frame | Tag::Overlay) {
142 1
143 } else {
144 0
145 }
146}
147
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago148/// What a `:reaction` reads as: the glyph, and the tally when there is one.
149/// A pill with no count is the chip you press to put one there — the same
150/// picture the picker offers, which is the point of it being the same node.
151pub fn pill_text(props: &Props) -> String {
152 let glyph = props.str("emoji");
153 match props.cells("count", 0) {
154 0 => glyph.to_owned(),
155 n => format!("{glyph} {n}"),
156 }
157}
158
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago159/// Break `text` to `width` columns, on spaces where it can and mid-word where
160/// it must. Explicit newlines are always breaks.
161pub fn wrap(text: &str, width: u16) -> Vec<String> {
162 if width == 0 {
163 return Vec::new();
164 }
165 let width = width as usize;
166 let mut lines = Vec::new();
167 for paragraph in text.split('\n') {
168 let mut line = String::new();
169 let mut len = 0usize;
170 for word in paragraph.split(' ') {
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago171 // In columns, not characters: an emoji is drawn two cells wide, so
172 // a line of them measured by character is twice the width it was
173 // wrapped to and runs off the edge.
174 let word_len = text_cols(word) as usize;
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago175 if len > 0 && len + 1 + word_len > width {
176 lines.push(std::mem::take(&mut line));
177 len = 0;
178 }
179 if word_len > width {
180 // Longer than the whole line: break it where the line ends
181 // rather than let it run off the edge.
Keep a glyph whole, selector and all, and copy it across whole 3dd441e nandi 16d ago182 for glyph in glyphs(word) {
183 let cols = glyph_cols(&glyph) as usize;
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago184 if len + cols > width && len > 0 {
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago185 lines.push(std::mem::take(&mut line));
186 len = 0;
187 }
Keep a glyph whole, selector and all, and copy it across whole 3dd441e nandi 16d ago188 line.push_str(&glyph);
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago189 len += cols;
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago190 }
191 continue;
192 }
193 if len > 0 {
194 line.push(' ');
195 len += 1;
196 }
197 line.push_str(word);
198 len += word_len;
199 }
200 lines.push(line);
201 }
202 lines
203}
204
205fn columns(text: &str) -> u16 {
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago206 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 ago207}
208
209/// The longest single word — a label cannot usefully be narrower than this.
210fn longest_word(text: &str) -> u16 {
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago211 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 ago212}
213
Draw a picture in a terminal, over the Kitty graphics protocol c2d912f nandi 16d ago214/// The cells a picture is given: its own shape, inside the caller's bounds and
215/// inside the room the column has.
216///
217/// Without the protocol to draw one there is no picture, only the note that
218/// says there was — so the box is a line, and the link in the message above it
219/// is what the reader is left with either way.
220pub fn image_cells(props: &Props, avail: u16) -> (u16, u16) {
221 let path = props.str("src");
222 if path.is_empty() {
223 return (0, 0);
224 }
225 if !graphics::supported() {
226 return (text_cols(PICTURE), 1);
227 }
228 let max_cols = match props.cells("max-width", 0) {
229 0 => avail,
230 want => want.min(avail),
231 };
232 let max_rows = match props.cells("max-height", 0) {
233 0 => 16,
234 want => want,
235 };
236 graphics::cells_for(path, max_cols, max_rows)
237}
238
239/// What stands in for a picture where one cannot be drawn.
240pub const PICTURE: &str = "[ picture ]";
241
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago242/// The text an entry shows: its own, or its placeholder when it has none.
243pub fn entry_text(props: &Props) -> String {
244 let text = props.str("text");
245 if text.is_empty() {
246 props.str("placeholder").to_owned()
247 } else {
248 text.to_owned()
249 }
250}
251
Give the terminal's entry a caret that means what it says 361b4dc nandi 8d ago252/// Whether an entry is a box of text rather than a line of it.
253///
254/// Asked for the rows it was given, and also of the text itself: a field with
255/// a newline in it is a box whatever it was declared as, and drawing that text
256/// on one line would show the newline as a hole and hide everything after it.
257pub fn entry_multiline(props: &Props) -> bool {
258 props.cells("rows", 1) > 1 || props.str("text").contains('\n')
259}
260
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago261/// A node's content size before its own request or inset is applied.
262fn intrinsic_width(tree: &Tree, id: u32, minimum: bool) -> u16 {
Measure a node once, and paint only what is on screen c41903b nandi 15d ago263 let tag = tree.tag_of(id);
264 let props = tree.props_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago265 let text = props.label();
266 match tag {
267 Tag::Button => columns(text).saturating_add(4),
268 Tag::CheckButton => columns(text).saturating_add(4),
269 Tag::Entry => {
Give the terminal's entry a caret that means what it says 361b4dc nandi 8d ago270 // The longest line of it: a box of text is as wide as its widest
271 // row, not as wide as all its rows laid end to end.
272 let text = entry_text(props);
273 let widest = text.split('\n').map(columns).max().unwrap_or(0);
274 let want = widest.saturating_add(1).max(12);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago275 if minimum {
276 want.min(6)
277 } else {
278 want
279 }
280 }
281 Tag::Label | Tag::Title | Tag::DimLabel => {
282 if minimum {
283 longest_word(text)
284 } else {
285 columns(text)
286 }
287 }
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago288 // An unknown tag with nothing under it paints its own text, so it has
289 // to be measured as the label it turns out to be — a widget given no
290 // 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 ago291 //
292 // Unless it names a picture. An `:avatar`'s label is the nick behind
293 // the face and an `:image`'s is its alt text: words for something that
294 // cannot be drawn here, and in frq's case words already on the row
295 // beside it, which is how every sender came out named twice.
Measure a node once, and paint only what is on screen c41903b nandi 15d ago296 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 ago297 if minimum {
298 longest_word(props.label())
299 } else {
300 columns(props.label())
301 }
302 }
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago303 Tag::Separator => 1,
304 Tag::Spacer => props.cells("size", 1),
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago305 Tag::Emoji => text_cols(props.str("emoji")),
Measure a node once, and paint only what is on screen c41903b nandi 15d ago306 Tag::Image => image_cells(props, u16::MAX).0,
307 Tag::Reaction => text_cols(&pill_text(props)),
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago308 Tag::Progress => {
309 if minimum {
310 4
311 } else {
312 20
313 }
314 }
315 Tag::Spinner => 1,
316 Tag::Listbox => tree
Measure a node once, and paint only what is on screen c41903b nandi 15d ago317 .children_of(id)
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago318 .iter()
319 .map(|c| intrinsic_width(tree, *c, minimum).saturating_add(2))
320 .max()
321 .unwrap_or(0),
322 // Every container measures its children the same way; only the axis
323 // the sum runs along differs.
324 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 15d ago325 let children = tree.children_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago326 let spacing = props.cells("spacing", 0);
327 let sizes = children
328 .iter()
329 .map(|c| width(tree, *c, minimum))
330 .collect::<Vec<_>>();
Measure a node once, and paint only what is on screen c41903b nandi 15d ago331 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 ago332 let gaps = spacing.saturating_mul(sizes.len().saturating_sub(1) as u16);
333 sizes.iter().fold(gaps, |a, b| a.saturating_add(*b))
334 } else {
335 sizes.into_iter().max().unwrap_or(0)
336 };
337 // A frame's heading sits in its top edge, so it is part of how wide
338 // the frame has to be — a box narrower than its own label reads as
339 // a truncated one.
340 if matches!(tag, Tag::Frame | Tag::Overlay) {
341 content.max(columns(props.label()).saturating_add(2))
342 } else {
343 content
344 }
345 }
346 }
347}
348
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago349/// True for a node whose label describes a picture rather than being text to
350/// paint — an `:avatar`, an `:image`, a live `:feed`.
351fn has_picture(props: &Props) -> bool {
352 props.has("src") || props.has("feed")
353}
354
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago355/// 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 ago356///
357/// A `width-request` is the width, not a floor under it. In a window it can be
358/// a floor, because a label wraps to whatever it is given and a column's
359/// natural width is therefore whatever the layout decides. Here a label's
360/// natural width is its whole line, so a column that holds one is as wide as
361/// the longest thing anybody ever said in it — and `max` then hands the
362/// sidebar the screen and leaves the conversation beside it ten cells to wrap
363/// in. Asking for a width is the caller saying how wide the column is; nothing
364/// 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 ago365pub fn width(tree: &Tree, id: u32, minimum: bool) -> u16 {
Measure a node once, and paint only what is on screen c41903b nandi 15d ago366 remember(tree, Question::Width { minimum }, id, 0, || {
367 width_uncached(tree, id, minimum)
368 })
369}
370
371fn width_uncached(tree: &Tree, id: u32, minimum: bool) -> u16 {
372 let props = tree.props_of(id);
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago373 let requested = props.cells("width-request", 0);
374 if requested > 0 {
375 return requested;
376 }
Measure a node once, and paint only what is on screen c41903b nandi 15d ago377 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 ago378 intrinsic_width(tree, id, minimum).saturating_add(pad)
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago379}
380
381/// How tall `id` is when laid out `avail` columns wide.
382///
383/// Height depends on width — that is what wrapping means — so there is no
384/// natural height to ask for on its own.
385pub fn height_for_width(tree: &Tree, id: u32, avail: u16) -> u16 {
Measure a node once, and paint only what is on screen c41903b nandi 15d ago386 remember(tree, Question::Height, id, avail, || {
387 height_for_width_uncached(tree, id, avail)
388 })
389}
390
391fn height_for_width_uncached(tree: &Tree, id: u32, avail: u16) -> u16 {
392 let tag = tree.tag_of(id);
393 let props = tree.props_of(id);
394 let pad = inset(tag, props);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago395 let inner = avail.saturating_sub(pad.saturating_mul(2));
396 let content = match tag {
397 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 15d ago398 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 ago399 wrap(props.label(), inner).len() as u16
400 }
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago401 Tag::Button
402 | Tag::CheckButton
403 | Tag::Separator
404 | Tag::Progress
405 | Tag::Spinner
406 | Tag::Reaction
407 | Tag::Emoji => 1,
Measure a node once, and paint only what is on screen c41903b nandi 15d ago408 Tag::Image => image_cells(props, inner).1,
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago409 Tag::Entry => props.cells("rows", 1).max(1),
410 Tag::Spacer => props.cells("size", 1),
411 Tag::Listbox => tree.child_count(id) as u16,
412 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 15d ago413 let children = tree.children_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago414 let spacing = props.cells("spacing", 0);
Measure a node once, and paint only what is on screen c41903b nandi 15d ago415 if horizontal(props) && matches!(tag, Tag::Box) {
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago416 // 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 ago417 let shares = share(tree, id, inner, true, 0);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago418 children
419 .iter()
420 .zip(shares)
421 .map(|(c, w)| height_for_width(tree, *c, w))
422 .max()
423 .unwrap_or(0)
424 } else {
425 let gaps = spacing.saturating_mul(children.len().saturating_sub(1) as u16);
426 children
427 .iter()
428 .map(|c| height_for_width(tree, *c, inner))
429 .fold(gaps, |a, b| a.saturating_add(b))
430 }
431 }
432 };
Let a node say how tall it is willing to be 5ba95e0 nandi 7d ago433 let want = content
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago434 .saturating_add(pad.saturating_mul(2))
Let a node say how tall it is willing to be 5ba95e0 nandi 7d ago435 .max(props.cells("height-request", 0));
436 match props.cells("max-height", 0) {
437 0 => want,
438 most => want.min(most),
439 }
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago440}
441
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago442/// The least `id` can be squeezed to at `avail` columns wide.
443///
444/// Down the page almost nothing can be shorter than it is: a label wrapped to
445/// four lines needs four. A `:scroll` is the exception, and the reason there is
446/// one — it is a viewport, so its height is whatever it is given and its
447/// content moves inside it.
448///
449/// It has to recurse, because the viewport is rarely the child being measured.
450/// In frq's chat screen the backlog is a scroll inside a column inside a row
451/// inside the screen, and a column that reported its natural height all the
452/// way up gave the layout nothing to take: the backlog kept every row it asked
453/// for and the separator and compose bar under it were painted past the bottom
454/// edge — a conversation you cannot type into.
455pub 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 15d ago456 remember(tree, Question::MinHeight, id, avail, || {
457 min_height_for_width_uncached(tree, id, avail)
458 })
459}
460
461fn min_height_for_width_uncached(tree: &Tree, id: u32, avail: u16) -> u16 {
462 let tag = tree.tag_of(id);
463 let props = tree.props_of(id);
464 let pad = inset(tag, props);
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago465 let inner = avail.saturating_sub(pad.saturating_mul(2));
466 let content = match tag {
467 Tag::Scroll => 1,
468 Tag::Box | Tag::Window | Tag::Frame | Tag::Overlay | Tag::Unknown(_)
469 if tree.child_count(id) > 0 =>
470 {
Measure a node once, and paint only what is on screen c41903b nandi 15d ago471 let children = tree.children_of(id);
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago472 let spacing = props.cells("spacing", 0);
Measure a node once, and paint only what is on screen c41903b nandi 15d ago473 if horizontal(props) && matches!(tag, Tag::Box) {
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago474 let shares = share(tree, id, inner, true, 0);
475 children
476 .iter()
477 .zip(shares)
478 .map(|(c, w)| min_height_for_width(tree, *c, w))
479 .max()
480 .unwrap_or(0)
481 } else {
482 let gaps = spacing.saturating_mul(children.len().saturating_sub(1) as u16);
483 children
484 .iter()
485 .map(|c| min_height_for_width(tree, *c, inner))
486 .fold(gaps, |a, b| a.saturating_add(b))
487 }
488 }
489 // Everything else is as short as it is tall.
490 _ => return height_for_width(tree, id, avail),
491 };
492 content
493 .saturating_add(pad.saturating_mul(2))
494 .max(props.cells("height-request", 0))
495}
496
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago497/// Share `avail` out among the children of `id` along one axis.
498///
499/// `across` picks the axis: true for a horizontal box sharing columns, false
500/// for a vertical one sharing rows. The rule is the same either way — natural
501/// sizes first, shrink proportionally toward the minimums when short, and the
502/// 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 ago503///
504/// `cross` is the extent on the *other* axis, and sharing rows out cannot be
505/// done without it: how tall a child is depends on how wide it is, because
506/// that is what wrapping means. Passing the rows in its place measures every
507/// label at a column count of two or three, wraps it to a paragraph, and the
508/// overrun is then taken off the end — which paints a box's first child and
509/// drops every sibling after it. Unused when `across`, where a width does not
510/// depend on a height.
511pub 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 15d ago512 let rev = tree.revision_of(id);
513 let key = (id, avail, across, cross);
514 if let Some((then, known)) = SHARES.with(|m| m.borrow().get(&key).cloned()) {
515 if then == rev {
516 return known;
517 }
518 }
519 let shares = share_uncached(tree, id, avail, across, cross);
520 SHARES.with(|m| {
521 let mut map = m.borrow_mut();
522 if map.len() >= KEEP {
523 map.clear();
524 }
525 map.insert(key, (rev, shares.clone()));
526 });
527 shares
528}
529
530fn share_uncached(tree: &Tree, id: u32, avail: u16, across: bool, cross: u16) -> Vec<u16> {
531 let children = tree.children_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago532 if children.is_empty() {
533 return Vec::new();
534 }
Measure a node once, and paint only what is on screen c41903b nandi 15d ago535 let props = tree.props_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago536 let spacing = props.cells("spacing", 0);
537 let gaps = spacing.saturating_mul((children.len() - 1) as u16);
538 let room = avail.saturating_sub(gaps) as i64;
539
540 let measure = |child: u32, minimum: bool| -> i64 {
541 if across {
542 width(tree, child, minimum) as i64
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago543 } else if minimum {
544 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 ago545 } else {
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago546 // A child's height depends on the width it gets, which the caller
547 // 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 ago548 height_for_width(tree, child, cross) as i64
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago549 }
550 };
551
552 let nat: Vec<i64> = children.iter().map(|c| measure(*c, false)).collect();
553 let min: Vec<i64> = children
554 .iter()
555 .zip(&nat)
556 .map(|(c, n)| measure(*c, true).min(*n))
557 .collect();
558 let total: i64 = nat.iter().sum();
559 let mut out = nat.clone();
560
561 if total > room {
562 // Short: take the overrun out of whatever each child is willing to give
563 // up, in proportion to how much that is.
564 let mut over = total - room;
565 let slack: i64 = nat.iter().zip(&min).map(|(n, m)| n - m).sum();
566 if slack > 0 {
567 for i in 0..out.len() {
568 let give = ((nat[i] - min[i]) * over.min(slack)) / slack;
569 out[i] -= give;
570 }
571 over -= nat.iter().zip(&out).map(|(n, o)| n - o).sum::<i64>();
572 }
573 // Rounding, and children with no slack at all: take the rest off the
574 // end, which is where a terminal clips anyway.
575 let mut i = out.len();
576 while over > 0 && i > 0 {
577 i -= 1;
578 let give = (out[i] - min[i]).min(over);
579 out[i] -= give;
580 over -= give;
581 }
582 } else if total < room {
583 let key = if across { "hexpand" } else { "vexpand" };
584 let greedy: Vec<usize> = children
585 .iter()
586 .enumerate()
Measure a node once, and paint only what is on screen c41903b nandi 15d ago587 .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 ago588 .map(|(i, _)| i)
589 .collect();
590 if !greedy.is_empty() {
591 let extra = room - total;
592 let each = extra / greedy.len() as i64;
593 let mut rest = extra % greedy.len() as i64;
594 for i in greedy {
595 out[i] += each + if rest > 0 { 1 } else { 0 };
596 rest -= 1;
597 }
598 }
599 }
600 out.into_iter()
601 .map(|n| n.clamp(0, u16::MAX as i64) as u16)
602 .collect()
603}
604
605/// The rect a child of `size` gets inside `avail` on its cross axis.
606pub fn place(align: Align, size: u16, avail: u16) -> (u16, u16) {
607 match align {
608 Align::Fill => (0, avail),
609 other => {
610 let size = size.min(avail);
611 (other.offset(size, avail), size)
612 }
613 }
614}
615
616/// Lay the children of a box out inside `area`.
617pub fn children_rects(tree: &Tree, id: u32, area: Rect) -> Vec<Rect> {
Measure a node once, and paint only what is on screen c41903b nandi 15d ago618 let props = tree.props_of(id);
619 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 ago620 let spacing = props.cells("spacing", 0);
Measure a node once, and paint only what is on screen c41903b nandi 15d ago621 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 ago622 let shares = share(
623 tree,
624 id,
625 if across { area.w } else { area.h },
626 across,
627 if across { area.h } else { area.w },
628 );
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago629
630 let mut out = Vec::with_capacity(children.len());
631 let mut at = 0u16;
632 for (child, main) in children.iter().zip(shares) {
Measure a node once, and paint only what is on screen c41903b nandi 15d ago633 let cprops = tree.props_of(*child);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago634 let rect = if across {
635 let want = height_for_width(tree, *child, main).max(cprops.cells("height-request", 0));
636 let (dy, h) = place(Align::parse(cprops.str("valign")), want, area.h);
637 Rect::new(
638 area.x.saturating_add(at),
639 area.y.saturating_add(dy),
640 main,
641 h,
642 )
643 } else {
644 let want = width(tree, *child, false);
645 let (dx, w) = place(Align::parse(cprops.str("halign")), want, area.w);
646 Rect::new(
647 area.x.saturating_add(dx),
648 area.y.saturating_add(at),
649 w,
650 main,
651 )
652 };
653 out.push(rect);
654 at = at.saturating_add(main).saturating_add(spacing);
655 }
656 out
657}
658
659#[cfg(test)]
660mod tests {
661 use super::*;
662 use crate::tree::Value;
663
664 fn label(tree: &mut Tree, parent: u32, text: &str) -> u32 {
665 let id = tree.new_node("label");
666 tree.set(id, "label", Value::Str(text.into()));
667 tree.append(parent, id);
668 id
669 }
670
671 #[test]
672 fn wrapping_breaks_on_spaces_and_mid_word_when_it_must() {
673 assert_eq!(wrap("one two three", 7), vec!["one two", "three"]);
674 assert_eq!(
675 wrap("antidisestablishment", 6),
676 vec!["antidi", "sestab", "lishme", "nt"]
677 );
678 assert_eq!(wrap("a\nb", 10), vec!["a", "b"]);
679 }
680
Measure a node once, and paint only what is on screen c41903b nandi 15d ago681 #[test]
682 fn a_size_measured_before_a_change_is_not_the_answer_after_one() {
683 // Sizes are kept between frames, so what has to be right is when they
684 // stop being. A word typed into a label three boxes down changes how
685 // tall the box at the top is, and the answer taken before it has to go
686 // for every one of them — which is what the walk up the parents in
687 // `Tree::touch` is for.
688 let mut tree = Tree::new();
689 let root = tree.root();
690 let outer = tree.new_node("vbox");
691 tree.append(root, outer);
692 let inner = tree.new_node("vbox");
693 tree.append(outer, inner);
694 let text = label(&mut tree, inner, "one");
695 assert_eq!(height_for_width(&tree, outer, 10), 1);
696 tree.set(text, "label", Value::Str("one two three four".into()));
697 assert_eq!(
698 height_for_width(&tree, outer, 10),
699 2,
700 "the label now wraps, and the boxes above it are a row taller"
701 );
702 }
703
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago704 #[test]
705 fn a_label_is_as_wide_as_its_text_and_as_narrow_as_its_longest_word() {
706 let mut tree = Tree::new();
707 let root = tree.root();
708 let id = label(&mut tree, root, "one two three");
709 assert_eq!(width(&tree, id, false), 13);
710 assert_eq!(width(&tree, id, true), 5);
711 assert_eq!(height_for_width(&tree, id, 7), 2);
712 }
713
714 #[test]
715 fn a_width_request_is_a_floor_on_both_sizes() {
716 let mut tree = Tree::new();
717 let root = tree.root();
718 let id = label(&mut tree, root, "hi");
719 tree.set(id, "width-request", Value::Num(20.0));
720 assert_eq!(width(&tree, id, false), 20);
721 assert_eq!(width(&tree, id, true), 20);
722 }
723
724 #[test]
725 fn a_height_request_of_four_rows_gets_four_rows() {
726 let mut tree = Tree::new();
727 let root = tree.root();
728 let id = label(&mut tree, root, "hi");
729 tree.set(id, "height-request", Value::Num(4.0));
730 assert_eq!(height_for_width(&tree, id, 10), 4);
731 }
732
733 #[test]
734 fn a_horizontal_box_gives_the_surplus_to_whoever_expands() {
735 let mut tree = Tree::new();
736 let row = tree.new_node("hbox");
737 tree.set(row, "orientation", Value::Str("horizontal".into()));
738 let root = tree.root();
739 tree.append(root, row);
740 let a = label(&mut tree, row, "aa");
741 let b = label(&mut tree, row, "bb");
742 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 ago743 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 ago744 let _ = a;
745 }
746
747 #[test]
748 fn a_short_box_shrinks_toward_the_minimums_rather_than_clipping_the_first_child() {
749 let mut tree = Tree::new();
750 let row = tree.new_node("hbox");
751 tree.set(row, "orientation", Value::Str("horizontal".into()));
752 let root = tree.root();
753 tree.append(root, row);
754 label(&mut tree, row, "one two");
755 label(&mut tree, row, "three four");
756 // 17 natural, 10 offered: both give up some, neither goes under its
757 // longest word.
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago758 let shares = share(&tree, row, 10, true, 1);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago759 assert_eq!(shares.iter().sum::<u16>(), 10);
760 assert!(shares[0] >= 3 && shares[1] >= 5, "{shares:?}");
761 }
762
763 #[test]
764 fn spacing_comes_off_the_room_before_it_is_shared() {
765 let mut tree = Tree::new();
766 let row = tree.new_node("hbox");
767 tree.set(row, "orientation", Value::Str("horizontal".into()));
768 tree.set(row, "spacing", Value::Num(2.0));
769 let root = tree.root();
770 tree.append(root, row);
771 let a = label(&mut tree, row, "aa");
772 let b = label(&mut tree, row, "bb");
773 tree.set(a, "hexpand", Value::Bool(true));
774 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 ago775 assert_eq!(share(&tree, row, 12, true, 1), vec![5, 5]);
776 }
777
778 #[test]
779 fn a_column_shares_its_rows_out_at_the_width_it_has() {
780 // A column two rows tall and thirty columns wide holds two labels, and
781 // each is one row at that width. Measured against the rows instead —
782 // as this did — "the second line" wraps to five, the overrun comes off
783 // the end, and the second child is handed nothing: a box that paints
784 // its first child and drops the rest, which is what the chats list did
785 // to every Open button in it.
786 let mut tree = Tree::new();
787 let col = tree.new_node("vbox");
788 tree.set(col, "orientation", Value::Str("vertical".into()));
789 let root = tree.root();
790 tree.append(root, col);
791 label(&mut tree, col, "the first line");
792 label(&mut tree, col, "the second line");
793 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 ago794 }
795
796 #[test]
797 fn a_centred_child_sits_in_the_middle_of_its_row() {
798 assert_eq!(place(Align::Center, 4, 10), (3, 4));
799 assert_eq!(place(Align::End, 4, 10), (6, 4));
800 assert_eq!(place(Align::Fill, 4, 10), (0, 10));
801 }
802
803 #[test]
804 fn a_frame_spends_a_cell_a_side_on_its_border() {
805 let mut tree = Tree::new();
806 let frame = tree.new_node("frame");
807 let root = tree.root();
808 tree.append(root, frame);
809 label(&mut tree, frame, "hi");
810 assert_eq!(width(&tree, frame, false), 4);
811 assert_eq!(height_for_width(&tree, frame, 4), 3);
812 }
813}