nandi/jolt-nativepublic Fork 0
6a3304ddddcc7d3e9486b470fea5933a1f81f8e8
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 · 802 lines · 30.1 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
Give the terminal's entry a caret that means what it says 361b4dc nandi 9d ago245/// Whether an entry is a box of text rather than a line of it.
246///
247/// Asked for the rows it was given, and also of the text itself: a field with
248/// a newline in it is a box whatever it was declared as, and drawing that text
249/// on one line would show the newline as a hole and hide everything after it.
250pub fn entry_multiline(props: &Props) -> bool {
251 props.cells("rows", 1) > 1 || props.str("text").contains('\n')
252}
253
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago254/// A node's content size before its own request or inset is applied.
255fn intrinsic_width(tree: &Tree, id: u32, minimum: bool) -> u16 {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago256 let tag = tree.tag_of(id);
257 let props = tree.props_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago258 let text = props.label();
259 match tag {
260 Tag::Button => columns(text).saturating_add(4),
261 Tag::CheckButton => columns(text).saturating_add(4),
262 Tag::Entry => {
Give the terminal's entry a caret that means what it says 361b4dc nandi 9d ago263 // The longest line of it: a box of text is as wide as its widest
264 // row, not as wide as all its rows laid end to end.
265 let text = entry_text(props);
266 let widest = text.split('\n').map(columns).max().unwrap_or(0);
267 let want = widest.saturating_add(1).max(12);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago268 if minimum {
269 want.min(6)
270 } else {
271 want
272 }
273 }
274 Tag::Label | Tag::Title | Tag::DimLabel => {
275 if minimum {
276 longest_word(text)
277 } else {
278 columns(text)
279 }
280 }
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago281 // An unknown tag with nothing under it paints its own text, so it has
282 // to be measured as the label it turns out to be — a widget given no
283 // 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 ago284 //
285 // Unless it names a picture. An `:avatar`'s label is the nick behind
286 // the face and an `:image`'s is its alt text: words for something that
287 // cannot be drawn here, and in frq's case words already on the row
288 // 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 ago289 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 ago290 if minimum {
291 longest_word(props.label())
292 } else {
293 columns(props.label())
294 }
295 }
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago296 Tag::Separator => 1,
297 Tag::Spacer => props.cells("size", 1),
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago298 Tag::Emoji => text_cols(props.str("emoji")),
Measure a node once, and paint only what is on screen c41903b nandi 16d ago299 Tag::Image => image_cells(props, u16::MAX).0,
300 Tag::Reaction => text_cols(&pill_text(props)),
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago301 Tag::Progress => {
302 if minimum {
303 4
304 } else {
305 20
306 }
307 }
308 Tag::Spinner => 1,
309 Tag::Listbox => tree
Measure a node once, and paint only what is on screen c41903b nandi 16d ago310 .children_of(id)
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago311 .iter()
312 .map(|c| intrinsic_width(tree, *c, minimum).saturating_add(2))
313 .max()
314 .unwrap_or(0),
315 // Every container measures its children the same way; only the axis
316 // the sum runs along differs.
317 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 ago318 let children = tree.children_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago319 let spacing = props.cells("spacing", 0);
320 let sizes = children
321 .iter()
322 .map(|c| width(tree, *c, minimum))
323 .collect::<Vec<_>>();
Measure a node once, and paint only what is on screen c41903b nandi 16d ago324 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 ago325 let gaps = spacing.saturating_mul(sizes.len().saturating_sub(1) as u16);
326 sizes.iter().fold(gaps, |a, b| a.saturating_add(*b))
327 } else {
328 sizes.into_iter().max().unwrap_or(0)
329 };
330 // A frame's heading sits in its top edge, so it is part of how wide
331 // the frame has to be — a box narrower than its own label reads as
332 // a truncated one.
333 if matches!(tag, Tag::Frame | Tag::Overlay) {
334 content.max(columns(props.label()).saturating_add(2))
335 } else {
336 content
337 }
338 }
339 }
340}
341
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago342/// True for a node whose label describes a picture rather than being text to
343/// paint — an `:avatar`, an `:image`, a live `:feed`.
344fn has_picture(props: &Props) -> bool {
345 props.has("src") || props.has("feed")
346}
347
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago348/// 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 ago349///
350/// A `width-request` is the width, not a floor under it. In a window it can be
351/// a floor, because a label wraps to whatever it is given and a column's
352/// natural width is therefore whatever the layout decides. Here a label's
353/// natural width is its whole line, so a column that holds one is as wide as
354/// the longest thing anybody ever said in it — and `max` then hands the
355/// sidebar the screen and leaves the conversation beside it ten cells to wrap
356/// in. Asking for a width is the caller saying how wide the column is; nothing
357/// 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 ago358pub fn width(tree: &Tree, id: u32, minimum: bool) -> u16 {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago359 remember(tree, Question::Width { minimum }, id, 0, || {
360 width_uncached(tree, id, minimum)
361 })
362}
363
364fn width_uncached(tree: &Tree, id: u32, minimum: bool) -> u16 {
365 let props = tree.props_of(id);
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago366 let requested = props.cells("width-request", 0);
367 if requested > 0 {
368 return requested;
369 }
Measure a node once, and paint only what is on screen c41903b nandi 16d ago370 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 ago371 intrinsic_width(tree, id, minimum).saturating_add(pad)
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago372}
373
374/// How tall `id` is when laid out `avail` columns wide.
375///
376/// Height depends on width — that is what wrapping means — so there is no
377/// natural height to ask for on its own.
378pub 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 ago379 remember(tree, Question::Height, id, avail, || {
380 height_for_width_uncached(tree, id, avail)
381 })
382}
383
384fn height_for_width_uncached(tree: &Tree, id: u32, avail: u16) -> u16 {
385 let tag = tree.tag_of(id);
386 let props = tree.props_of(id);
387 let pad = inset(tag, props);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago388 let inner = avail.saturating_sub(pad.saturating_mul(2));
389 let content = match tag {
390 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 ago391 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 ago392 wrap(props.label(), inner).len() as u16
393 }
Paint a reaction, and give an emoji the two columns it takes dce285f nandi 16d ago394 Tag::Button
395 | Tag::CheckButton
396 | Tag::Separator
397 | Tag::Progress
398 | Tag::Spinner
399 | Tag::Reaction
400 | Tag::Emoji => 1,
Measure a node once, and paint only what is on screen c41903b nandi 16d ago401 Tag::Image => image_cells(props, inner).1,
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago402 Tag::Entry => props.cells("rows", 1).max(1),
403 Tag::Spacer => props.cells("size", 1),
404 Tag::Listbox => tree.child_count(id) as u16,
405 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 ago406 let children = tree.children_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago407 let spacing = props.cells("spacing", 0);
Measure a node once, and paint only what is on screen c41903b nandi 16d ago408 if horizontal(props) && matches!(tag, Tag::Box) {
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago409 // 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 ago410 let shares = share(tree, id, inner, true, 0);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago411 children
412 .iter()
413 .zip(shares)
414 .map(|(c, w)| height_for_width(tree, *c, w))
415 .max()
416 .unwrap_or(0)
417 } else {
418 let gaps = spacing.saturating_mul(children.len().saturating_sub(1) as u16);
419 children
420 .iter()
421 .map(|c| height_for_width(tree, *c, inner))
422 .fold(gaps, |a, b| a.saturating_add(b))
423 }
424 }
425 };
426 content
427 .saturating_add(pad.saturating_mul(2))
428 .max(props.cells("height-request", 0))
429}
430
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago431/// The least `id` can be squeezed to at `avail` columns wide.
432///
433/// Down the page almost nothing can be shorter than it is: a label wrapped to
434/// four lines needs four. A `:scroll` is the exception, and the reason there is
435/// one — it is a viewport, so its height is whatever it is given and its
436/// content moves inside it.
437///
438/// It has to recurse, because the viewport is rarely the child being measured.
439/// In frq's chat screen the backlog is a scroll inside a column inside a row
440/// inside the screen, and a column that reported its natural height all the
441/// way up gave the layout nothing to take: the backlog kept every row it asked
442/// for and the separator and compose bar under it were painted past the bottom
443/// edge — a conversation you cannot type into.
444pub 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 ago445 remember(tree, Question::MinHeight, id, avail, || {
446 min_height_for_width_uncached(tree, id, avail)
447 })
448}
449
450fn min_height_for_width_uncached(tree: &Tree, id: u32, avail: u16) -> u16 {
451 let tag = tree.tag_of(id);
452 let props = tree.props_of(id);
453 let pad = inset(tag, props);
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago454 let inner = avail.saturating_sub(pad.saturating_mul(2));
455 let content = match tag {
456 Tag::Scroll => 1,
457 Tag::Box | Tag::Window | Tag::Frame | Tag::Overlay | Tag::Unknown(_)
458 if tree.child_count(id) > 0 =>
459 {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago460 let children = tree.children_of(id);
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago461 let spacing = props.cells("spacing", 0);
Measure a node once, and paint only what is on screen c41903b nandi 16d ago462 if horizontal(props) && matches!(tag, Tag::Box) {
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago463 let shares = share(tree, id, inner, true, 0);
464 children
465 .iter()
466 .zip(shares)
467 .map(|(c, w)| min_height_for_width(tree, *c, w))
468 .max()
469 .unwrap_or(0)
470 } else {
471 let gaps = spacing.saturating_mul(children.len().saturating_sub(1) as u16);
472 children
473 .iter()
474 .map(|c| min_height_for_width(tree, *c, inner))
475 .fold(gaps, |a, b| a.saturating_add(b))
476 }
477 }
478 // Everything else is as short as it is tall.
479 _ => return height_for_width(tree, id, avail),
480 };
481 content
482 .saturating_add(pad.saturating_mul(2))
483 .max(props.cells("height-request", 0))
484}
485
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago486/// Share `avail` out among the children of `id` along one axis.
487///
488/// `across` picks the axis: true for a horizontal box sharing columns, false
489/// for a vertical one sharing rows. The rule is the same either way — natural
490/// sizes first, shrink proportionally toward the minimums when short, and the
491/// 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 ago492///
493/// `cross` is the extent on the *other* axis, and sharing rows out cannot be
494/// done without it: how tall a child is depends on how wide it is, because
495/// that is what wrapping means. Passing the rows in its place measures every
496/// label at a column count of two or three, wraps it to a paragraph, and the
497/// overrun is then taken off the end — which paints a box's first child and
498/// drops every sibling after it. Unused when `across`, where a width does not
499/// depend on a height.
500pub 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 ago501 let rev = tree.revision_of(id);
502 let key = (id, avail, across, cross);
503 if let Some((then, known)) = SHARES.with(|m| m.borrow().get(&key).cloned()) {
504 if then == rev {
505 return known;
506 }
507 }
508 let shares = share_uncached(tree, id, avail, across, cross);
509 SHARES.with(|m| {
510 let mut map = m.borrow_mut();
511 if map.len() >= KEEP {
512 map.clear();
513 }
514 map.insert(key, (rev, shares.clone()));
515 });
516 shares
517}
518
519fn share_uncached(tree: &Tree, id: u32, avail: u16, across: bool, cross: u16) -> Vec<u16> {
520 let children = tree.children_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago521 if children.is_empty() {
522 return Vec::new();
523 }
Measure a node once, and paint only what is on screen c41903b nandi 16d ago524 let props = tree.props_of(id);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago525 let spacing = props.cells("spacing", 0);
526 let gaps = spacing.saturating_mul((children.len() - 1) as u16);
527 let room = avail.saturating_sub(gaps) as i64;
528
529 let measure = |child: u32, minimum: bool| -> i64 {
530 if across {
531 width(tree, child, minimum) as i64
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago532 } else if minimum {
533 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 ago534 } else {
Let a backlog keep its place, and leave room for what is under it 68910bd nandi 17d ago535 // A child's height depends on the width it gets, which the caller
536 // 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 ago537 height_for_width(tree, child, cross) as i64
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago538 }
539 };
540
541 let nat: Vec<i64> = children.iter().map(|c| measure(*c, false)).collect();
542 let min: Vec<i64> = children
543 .iter()
544 .zip(&nat)
545 .map(|(c, n)| measure(*c, true).min(*n))
546 .collect();
547 let total: i64 = nat.iter().sum();
548 let mut out = nat.clone();
549
550 if total > room {
551 // Short: take the overrun out of whatever each child is willing to give
552 // up, in proportion to how much that is.
553 let mut over = total - room;
554 let slack: i64 = nat.iter().zip(&min).map(|(n, m)| n - m).sum();
555 if slack > 0 {
556 for i in 0..out.len() {
557 let give = ((nat[i] - min[i]) * over.min(slack)) / slack;
558 out[i] -= give;
559 }
560 over -= nat.iter().zip(&out).map(|(n, o)| n - o).sum::<i64>();
561 }
562 // Rounding, and children with no slack at all: take the rest off the
563 // end, which is where a terminal clips anyway.
564 let mut i = out.len();
565 while over > 0 && i > 0 {
566 i -= 1;
567 let give = (out[i] - min[i]).min(over);
568 out[i] -= give;
569 over -= give;
570 }
571 } else if total < room {
572 let key = if across { "hexpand" } else { "vexpand" };
573 let greedy: Vec<usize> = children
574 .iter()
575 .enumerate()
Measure a node once, and paint only what is on screen c41903b nandi 16d ago576 .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 ago577 .map(|(i, _)| i)
578 .collect();
579 if !greedy.is_empty() {
580 let extra = room - total;
581 let each = extra / greedy.len() as i64;
582 let mut rest = extra % greedy.len() as i64;
583 for i in greedy {
584 out[i] += each + if rest > 0 { 1 } else { 0 };
585 rest -= 1;
586 }
587 }
588 }
589 out.into_iter()
590 .map(|n| n.clamp(0, u16::MAX as i64) as u16)
591 .collect()
592}
593
594/// The rect a child of `size` gets inside `avail` on its cross axis.
595pub fn place(align: Align, size: u16, avail: u16) -> (u16, u16) {
596 match align {
597 Align::Fill => (0, avail),
598 other => {
599 let size = size.min(avail);
600 (other.offset(size, avail), size)
601 }
602 }
603}
604
605/// Lay the children of a box out inside `area`.
606pub 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 ago607 let props = tree.props_of(id);
608 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 ago609 let spacing = props.cells("spacing", 0);
Measure a node once, and paint only what is on screen c41903b nandi 16d ago610 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 ago611 let shares = share(
612 tree,
613 id,
614 if across { area.w } else { area.h },
615 across,
616 if across { area.h } else { area.w },
617 );
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago618
619 let mut out = Vec::with_capacity(children.len());
620 let mut at = 0u16;
621 for (child, main) in children.iter().zip(shares) {
Measure a node once, and paint only what is on screen c41903b nandi 16d ago622 let cprops = tree.props_of(*child);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago623 let rect = if across {
624 let want = height_for_width(tree, *child, main).max(cprops.cells("height-request", 0));
625 let (dy, h) = place(Align::parse(cprops.str("valign")), want, area.h);
626 Rect::new(
627 area.x.saturating_add(at),
628 area.y.saturating_add(dy),
629 main,
630 h,
631 )
632 } else {
633 let want = width(tree, *child, false);
634 let (dx, w) = place(Align::parse(cprops.str("halign")), want, area.w);
635 Rect::new(
636 area.x.saturating_add(dx),
637 area.y.saturating_add(at),
638 w,
639 main,
640 )
641 };
642 out.push(rect);
643 at = at.saturating_add(main).saturating_add(spacing);
644 }
645 out
646}
647
648#[cfg(test)]
649mod tests {
650 use super::*;
651 use crate::tree::Value;
652
653 fn label(tree: &mut Tree, parent: u32, text: &str) -> u32 {
654 let id = tree.new_node("label");
655 tree.set(id, "label", Value::Str(text.into()));
656 tree.append(parent, id);
657 id
658 }
659
660 #[test]
661 fn wrapping_breaks_on_spaces_and_mid_word_when_it_must() {
662 assert_eq!(wrap("one two three", 7), vec!["one two", "three"]);
663 assert_eq!(
664 wrap("antidisestablishment", 6),
665 vec!["antidi", "sestab", "lishme", "nt"]
666 );
667 assert_eq!(wrap("a\nb", 10), vec!["a", "b"]);
668 }
669
Measure a node once, and paint only what is on screen c41903b nandi 16d ago670 #[test]
671 fn a_size_measured_before_a_change_is_not_the_answer_after_one() {
672 // Sizes are kept between frames, so what has to be right is when they
673 // stop being. A word typed into a label three boxes down changes how
674 // tall the box at the top is, and the answer taken before it has to go
675 // for every one of them — which is what the walk up the parents in
676 // `Tree::touch` is for.
677 let mut tree = Tree::new();
678 let root = tree.root();
679 let outer = tree.new_node("vbox");
680 tree.append(root, outer);
681 let inner = tree.new_node("vbox");
682 tree.append(outer, inner);
683 let text = label(&mut tree, inner, "one");
684 assert_eq!(height_for_width(&tree, outer, 10), 1);
685 tree.set(text, "label", Value::Str("one two three four".into()));
686 assert_eq!(
687 height_for_width(&tree, outer, 10),
688 2,
689 "the label now wraps, and the boxes above it are a row taller"
690 );
691 }
692
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago693 #[test]
694 fn a_label_is_as_wide_as_its_text_and_as_narrow_as_its_longest_word() {
695 let mut tree = Tree::new();
696 let root = tree.root();
697 let id = label(&mut tree, root, "one two three");
698 assert_eq!(width(&tree, id, false), 13);
699 assert_eq!(width(&tree, id, true), 5);
700 assert_eq!(height_for_width(&tree, id, 7), 2);
701 }
702
703 #[test]
704 fn a_width_request_is_a_floor_on_both_sizes() {
705 let mut tree = Tree::new();
706 let root = tree.root();
707 let id = label(&mut tree, root, "hi");
708 tree.set(id, "width-request", Value::Num(20.0));
709 assert_eq!(width(&tree, id, false), 20);
710 assert_eq!(width(&tree, id, true), 20);
711 }
712
713 #[test]
714 fn a_height_request_of_four_rows_gets_four_rows() {
715 let mut tree = Tree::new();
716 let root = tree.root();
717 let id = label(&mut tree, root, "hi");
718 tree.set(id, "height-request", Value::Num(4.0));
719 assert_eq!(height_for_width(&tree, id, 10), 4);
720 }
721
722 #[test]
723 fn a_horizontal_box_gives_the_surplus_to_whoever_expands() {
724 let mut tree = Tree::new();
725 let row = tree.new_node("hbox");
726 tree.set(row, "orientation", Value::Str("horizontal".into()));
727 let root = tree.root();
728 tree.append(root, row);
729 let a = label(&mut tree, row, "aa");
730 let b = label(&mut tree, row, "bb");
731 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 ago732 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 ago733 let _ = a;
734 }
735
736 #[test]
737 fn a_short_box_shrinks_toward_the_minimums_rather_than_clipping_the_first_child() {
738 let mut tree = Tree::new();
739 let row = tree.new_node("hbox");
740 tree.set(row, "orientation", Value::Str("horizontal".into()));
741 let root = tree.root();
742 tree.append(root, row);
743 label(&mut tree, row, "one two");
744 label(&mut tree, row, "three four");
745 // 17 natural, 10 offered: both give up some, neither goes under its
746 // longest word.
Share a column's rows out at the width it has, not at its own height 5acc801 nandi 17d ago747 let shares = share(&tree, row, 10, true, 1);
Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 17d ago748 assert_eq!(shares.iter().sum::<u16>(), 10);
749 assert!(shares[0] >= 3 && shares[1] >= 5, "{shares:?}");
750 }
751
752 #[test]
753 fn spacing_comes_off_the_room_before_it_is_shared() {
754 let mut tree = Tree::new();
755 let row = tree.new_node("hbox");
756 tree.set(row, "orientation", Value::Str("horizontal".into()));
757 tree.set(row, "spacing", Value::Num(2.0));
758 let root = tree.root();
759 tree.append(root, row);
760 let a = label(&mut tree, row, "aa");
761 let b = label(&mut tree, row, "bb");
762 tree.set(a, "hexpand", Value::Bool(true));
763 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 ago764 assert_eq!(share(&tree, row, 12, true, 1), vec![5, 5]);
765 }
766
767 #[test]
768 fn a_column_shares_its_rows_out_at_the_width_it_has() {
769 // A column two rows tall and thirty columns wide holds two labels, and
770 // each is one row at that width. Measured against the rows instead —
771 // as this did — "the second line" wraps to five, the overrun comes off
772 // the end, and the second child is handed nothing: a box that paints
773 // its first child and drops the rest, which is what the chats list did
774 // to every Open button in it.
775 let mut tree = Tree::new();
776 let col = tree.new_node("vbox");
777 tree.set(col, "orientation", Value::Str("vertical".into()));
778 let root = tree.root();
779 tree.append(root, col);
780 label(&mut tree, col, "the first line");
781 label(&mut tree, col, "the second line");
782 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 ago783 }
784
785 #[test]
786 fn a_centred_child_sits_in_the_middle_of_its_row() {
787 assert_eq!(place(Align::Center, 4, 10), (3, 4));
788 assert_eq!(place(Align::End, 4, 10), (6, 4));
789 assert_eq!(place(Align::Fill, 4, 10), (0, 10));
790 }
791
792 #[test]
793 fn a_frame_spends_a_cell_a_side_on_its_border() {
794 let mut tree = Tree::new();
795 let frame = tree.new_node("frame");
796 let root = tree.root();
797 tree.append(root, frame);
798 label(&mut tree, frame, "hi");
799 assert_eq!(width(&tree, frame, false), 4);
800 assert_eq!(height_for_width(&tree, frame, 4), 3);
801 }
802}