//! Two sizes per node, and how a box shares out what it has. //! //! Every node answers a *natural* size — what it would like — and a *minimum* //! — what it can survive on. A container hands out its natural sizes when there //! is room, shrinks them proportionally toward the minimums when there is not, //! and gives the surplus to whoever asked to expand. `:width-request` and //! `:height-request` are a floor on both numbers, so asking for four rows gets //! four rows even when space is short. //! //! Nothing here touches a terminal or the screen grid: sizes are arithmetic on //! the tree, which is why the layout tests below need no TTY. use crate::screen::Rect; use crate::tree::{Props, Tag, Tree}; /// How a child that is not filling its cross axis sits in the space it was /// given. `:halign` and `:valign` in the props. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Align { Fill, Start, Center, End, } impl Align { pub fn parse(text: &str) -> Self { match text { "start" => Self::Start, "center" | "centre" => Self::Center, "end" => Self::End, _ => Self::Fill, } } /// Where a span of `size` sits inside `avail`. fn offset(self, size: u16, avail: u16) -> u16 { let slack = avail.saturating_sub(size); match self { Self::Fill | Self::Start => 0, Self::Center => slack / 2, Self::End => slack, } } } /// Whether a box stacks its children across or down. pub fn horizontal(props: &Props) -> bool { props.str("orientation") == "horizontal" } /// The cells a node gives up on each side before its content starts. `:margin` /// and `:padding` are one inset here — a terminal cell has no border between /// them to tell them apart, and a caller that sets both means both. pub fn inset(tag: &Tag, props: &Props) -> u16 { let own = props.cells("margin", 0) + props.cells("padding", 0); // A frame — and an overlay, which is a frame that floats — spends a cell a // side on its border. own + if matches!(tag, Tag::Frame | Tag::Overlay) { 1 } else { 0 } } /// Break `text` to `width` columns, on spaces where it can and mid-word where /// it must. Explicit newlines are always breaks. pub fn wrap(text: &str, width: u16) -> Vec { if width == 0 { return Vec::new(); } let width = width as usize; let mut lines = Vec::new(); for paragraph in text.split('\n') { let mut line = String::new(); let mut len = 0usize; for word in paragraph.split(' ') { let word_len = word.chars().count(); if len > 0 && len + 1 + word_len > width { lines.push(std::mem::take(&mut line)); len = 0; } if word_len > width { // Longer than the whole line: break it where the line ends // rather than let it run off the edge. for ch in word.chars() { if len == width { lines.push(std::mem::take(&mut line)); len = 0; } line.push(ch); len += 1; } continue; } if len > 0 { line.push(' '); len += 1; } line.push_str(word); len += word_len; } lines.push(line); } lines } fn columns(text: &str) -> u16 { text.split('\n') .map(|line| line.chars().count()) .max() .unwrap_or(0) .min(u16::MAX as usize) as u16 } /// The longest single word — a label cannot usefully be narrower than this. fn longest_word(text: &str) -> u16 { text.split([' ', '\n']) .map(|w| w.chars().count()) .max() .unwrap_or(0) .min(u16::MAX as usize) as u16 } /// The text an entry shows: its own, or its placeholder when it has none. pub fn entry_text(props: &Props) -> String { let text = props.str("text"); if text.is_empty() { props.str("placeholder").to_owned() } else { text.to_owned() } } /// A node's content size before its own request or inset is applied. fn intrinsic_width(tree: &Tree, id: u32, minimum: bool) -> u16 { let tag = tree.tag(id); let props = tree.props(id); let text = props.label(); match tag { Tag::Button => columns(text).saturating_add(4), Tag::CheckButton => columns(text).saturating_add(4), Tag::Entry => { let want = columns(&entry_text(&props)).saturating_add(1).max(12); if minimum { want.min(6) } else { want } } Tag::Label | Tag::Title | Tag::DimLabel => { if minimum { longest_word(text) } else { columns(text) } } // An unknown tag with nothing under it paints its own text, so it has // to be measured as the label it turns out to be — a widget given no // room is as invisible as one that was never painted. // // Unless it names a picture. An `:avatar`'s label is the nick behind // the face and an `:image`'s is its alt text: words for something that // cannot be drawn here, and in frq's case words already on the row // beside it, which is how every sender came out named twice. Tag::Unknown(_) if tree.child_count(id) == 0 && !has_picture(&props) => { if minimum { longest_word(props.label()) } else { columns(props.label()) } } Tag::Separator => 1, Tag::Spacer => props.cells("size", 1), Tag::Progress => { if minimum { 4 } else { 20 } } Tag::Spinner => 1, Tag::Listbox => tree .children(id) .iter() .map(|c| intrinsic_width(tree, *c, minimum).saturating_add(2)) .max() .unwrap_or(0), // Every container measures its children the same way; only the axis // the sum runs along differs. Tag::Box | Tag::Window | Tag::Frame | Tag::Scroll | Tag::Overlay | Tag::Unknown(_) => { let children = tree.children(id); let spacing = props.cells("spacing", 0); let sizes = children .iter() .map(|c| width(tree, *c, minimum)) .collect::>(); let content = if horizontal(&props) && matches!(tag, Tag::Box) { let gaps = spacing.saturating_mul(sizes.len().saturating_sub(1) as u16); sizes.iter().fold(gaps, |a, b| a.saturating_add(*b)) } else { sizes.into_iter().max().unwrap_or(0) }; // A frame's heading sits in its top edge, so it is part of how wide // the frame has to be — a box narrower than its own label reads as // a truncated one. if matches!(tag, Tag::Frame | Tag::Overlay) { content.max(columns(props.label()).saturating_add(2)) } else { content } } } } /// True for a node whose label describes a picture rather than being text to /// paint — an `:avatar`, an `:image`, a live `:feed`. fn has_picture(props: &Props) -> bool { props.has("src") || props.has("feed") } /// A node's natural or minimum width, requests and insets included. /// /// A `width-request` is the width, not a floor under it. In a window it can be /// a floor, because a label wraps to whatever it is given and a column's /// natural width is therefore whatever the layout decides. Here a label's /// natural width is its whole line, so a column that holds one is as wide as /// the longest thing anybody ever said in it — and `max` then hands the /// sidebar the screen and leaves the conversation beside it ten cells to wrap /// in. Asking for a width is the caller saying how wide the column is; nothing /// else in a terminal can say it for them. pub fn width(tree: &Tree, id: u32, minimum: bool) -> u16 { let props = tree.props(id); let requested = props.cells("width-request", 0); if requested > 0 { return requested; } let pad = inset(&tree.tag(id), &props).saturating_mul(2); intrinsic_width(tree, id, minimum).saturating_add(pad) } /// How tall `id` is when laid out `avail` columns wide. /// /// Height depends on width — that is what wrapping means — so there is no /// natural height to ask for on its own. pub fn height_for_width(tree: &Tree, id: u32, avail: u16) -> u16 { let tag = tree.tag(id); let props = tree.props(id); let pad = inset(&tag, &props); let inner = avail.saturating_sub(pad.saturating_mul(2)); let content = match tag { Tag::Label | Tag::Title | Tag::DimLabel => wrap(props.label(), inner).len() as u16, Tag::Unknown(_) if tree.child_count(id) == 0 && !has_picture(&props) => { wrap(props.label(), inner).len() as u16 } Tag::Button | Tag::CheckButton | Tag::Separator | Tag::Progress | Tag::Spinner => 1, Tag::Entry => props.cells("rows", 1).max(1), Tag::Spacer => props.cells("size", 1), Tag::Listbox => tree.child_count(id) as u16, Tag::Box | Tag::Window | Tag::Frame | Tag::Scroll | Tag::Overlay | Tag::Unknown(_) => { let children = tree.children(id); let spacing = props.cells("spacing", 0); if horizontal(&props) && matches!(tag, Tag::Box) { // Across: each child is measured at the width it will get. let shares = share(tree, id, inner, true, 0); children .iter() .zip(shares) .map(|(c, w)| height_for_width(tree, *c, w)) .max() .unwrap_or(0) } else { let gaps = spacing.saturating_mul(children.len().saturating_sub(1) as u16); children .iter() .map(|c| height_for_width(tree, *c, inner)) .fold(gaps, |a, b| a.saturating_add(b)) } } }; content .saturating_add(pad.saturating_mul(2)) .max(props.cells("height-request", 0)) } /// The least `id` can be squeezed to at `avail` columns wide. /// /// Down the page almost nothing can be shorter than it is: a label wrapped to /// four lines needs four. A `:scroll` is the exception, and the reason there is /// one — it is a viewport, so its height is whatever it is given and its /// content moves inside it. /// /// It has to recurse, because the viewport is rarely the child being measured. /// In frq's chat screen the backlog is a scroll inside a column inside a row /// inside the screen, and a column that reported its natural height all the /// way up gave the layout nothing to take: the backlog kept every row it asked /// for and the separator and compose bar under it were painted past the bottom /// edge — a conversation you cannot type into. pub fn min_height_for_width(tree: &Tree, id: u32, avail: u16) -> u16 { let tag = tree.tag(id); let props = tree.props(id); let pad = inset(&tag, &props); let inner = avail.saturating_sub(pad.saturating_mul(2)); let content = match tag { Tag::Scroll => 1, Tag::Box | Tag::Window | Tag::Frame | Tag::Overlay | Tag::Unknown(_) if tree.child_count(id) > 0 => { let children = tree.children(id); let spacing = props.cells("spacing", 0); if horizontal(&props) && matches!(tag, Tag::Box) { let shares = share(tree, id, inner, true, 0); children .iter() .zip(shares) .map(|(c, w)| min_height_for_width(tree, *c, w)) .max() .unwrap_or(0) } else { let gaps = spacing.saturating_mul(children.len().saturating_sub(1) as u16); children .iter() .map(|c| min_height_for_width(tree, *c, inner)) .fold(gaps, |a, b| a.saturating_add(b)) } } // Everything else is as short as it is tall. _ => return height_for_width(tree, id, avail), }; content .saturating_add(pad.saturating_mul(2)) .max(props.cells("height-request", 0)) } /// Share `avail` out among the children of `id` along one axis. /// /// `across` picks the axis: true for a horizontal box sharing columns, false /// for a vertical one sharing rows. The rule is the same either way — natural /// sizes first, shrink proportionally toward the minimums when short, and the /// surplus to whoever set `:hexpand` / `:vexpand`. /// /// `cross` is the extent on the *other* axis, and sharing rows out cannot be /// done without it: how tall a child is depends on how wide it is, because /// that is what wrapping means. Passing the rows in its place measures every /// label at a column count of two or three, wraps it to a paragraph, and the /// overrun is then taken off the end — which paints a box's first child and /// drops every sibling after it. Unused when `across`, where a width does not /// depend on a height. pub fn share(tree: &Tree, id: u32, avail: u16, across: bool, cross: u16) -> Vec { let children = tree.children(id); if children.is_empty() { return Vec::new(); } let props = tree.props(id); let spacing = props.cells("spacing", 0); let gaps = spacing.saturating_mul((children.len() - 1) as u16); let room = avail.saturating_sub(gaps) as i64; let measure = |child: u32, minimum: bool| -> i64 { if across { width(tree, child, minimum) as i64 } else if minimum { min_height_for_width(tree, child, cross) as i64 } else { // A child's height depends on the width it gets, which the caller // has already fixed by the time it asks. height_for_width(tree, child, cross) as i64 } }; let nat: Vec = children.iter().map(|c| measure(*c, false)).collect(); let min: Vec = children .iter() .zip(&nat) .map(|(c, n)| measure(*c, true).min(*n)) .collect(); let total: i64 = nat.iter().sum(); let mut out = nat.clone(); if total > room { // Short: take the overrun out of whatever each child is willing to give // up, in proportion to how much that is. let mut over = total - room; let slack: i64 = nat.iter().zip(&min).map(|(n, m)| n - m).sum(); if slack > 0 { for i in 0..out.len() { let give = ((nat[i] - min[i]) * over.min(slack)) / slack; out[i] -= give; } over -= nat.iter().zip(&out).map(|(n, o)| n - o).sum::(); } // Rounding, and children with no slack at all: take the rest off the // end, which is where a terminal clips anyway. let mut i = out.len(); while over > 0 && i > 0 { i -= 1; let give = (out[i] - min[i]).min(over); out[i] -= give; over -= give; } } else if total < room { let key = if across { "hexpand" } else { "vexpand" }; let greedy: Vec = children .iter() .enumerate() .filter(|(_, c)| tree.props(**c).bool(key, false)) .map(|(i, _)| i) .collect(); if !greedy.is_empty() { let extra = room - total; let each = extra / greedy.len() as i64; let mut rest = extra % greedy.len() as i64; for i in greedy { out[i] += each + if rest > 0 { 1 } else { 0 }; rest -= 1; } } } out.into_iter() .map(|n| n.clamp(0, u16::MAX as i64) as u16) .collect() } /// The rect a child of `size` gets inside `avail` on its cross axis. pub fn place(align: Align, size: u16, avail: u16) -> (u16, u16) { match align { Align::Fill => (0, avail), other => { let size = size.min(avail); (other.offset(size, avail), size) } } } /// Lay the children of a box out inside `area`. pub fn children_rects(tree: &Tree, id: u32, area: Rect) -> Vec { let props = tree.props(id); let across = horizontal(&props) && matches!(tree.tag(id), Tag::Box); let spacing = props.cells("spacing", 0); let children = tree.children(id); let shares = share( tree, id, if across { area.w } else { area.h }, across, if across { area.h } else { area.w }, ); let mut out = Vec::with_capacity(children.len()); let mut at = 0u16; for (child, main) in children.iter().zip(shares) { let cprops = tree.props(*child); let rect = if across { let want = height_for_width(tree, *child, main).max(cprops.cells("height-request", 0)); let (dy, h) = place(Align::parse(cprops.str("valign")), want, area.h); Rect::new( area.x.saturating_add(at), area.y.saturating_add(dy), main, h, ) } else { let want = width(tree, *child, false); let (dx, w) = place(Align::parse(cprops.str("halign")), want, area.w); Rect::new( area.x.saturating_add(dx), area.y.saturating_add(at), w, main, ) }; out.push(rect); at = at.saturating_add(main).saturating_add(spacing); } out } #[cfg(test)] mod tests { use super::*; use crate::tree::Value; fn label(tree: &mut Tree, parent: u32, text: &str) -> u32 { let id = tree.new_node("label"); tree.set(id, "label", Value::Str(text.into())); tree.append(parent, id); id } #[test] fn wrapping_breaks_on_spaces_and_mid_word_when_it_must() { assert_eq!(wrap("one two three", 7), vec!["one two", "three"]); assert_eq!( wrap("antidisestablishment", 6), vec!["antidi", "sestab", "lishme", "nt"] ); assert_eq!(wrap("a\nb", 10), vec!["a", "b"]); } #[test] fn a_label_is_as_wide_as_its_text_and_as_narrow_as_its_longest_word() { let mut tree = Tree::new(); let root = tree.root(); let id = label(&mut tree, root, "one two three"); assert_eq!(width(&tree, id, false), 13); assert_eq!(width(&tree, id, true), 5); assert_eq!(height_for_width(&tree, id, 7), 2); } #[test] fn a_width_request_is_a_floor_on_both_sizes() { let mut tree = Tree::new(); let root = tree.root(); let id = label(&mut tree, root, "hi"); tree.set(id, "width-request", Value::Num(20.0)); assert_eq!(width(&tree, id, false), 20); assert_eq!(width(&tree, id, true), 20); } #[test] fn a_height_request_of_four_rows_gets_four_rows() { let mut tree = Tree::new(); let root = tree.root(); let id = label(&mut tree, root, "hi"); tree.set(id, "height-request", Value::Num(4.0)); assert_eq!(height_for_width(&tree, id, 10), 4); } #[test] fn a_horizontal_box_gives_the_surplus_to_whoever_expands() { let mut tree = Tree::new(); let row = tree.new_node("hbox"); tree.set(row, "orientation", Value::Str("horizontal".into())); let root = tree.root(); tree.append(root, row); let a = label(&mut tree, row, "aa"); let b = label(&mut tree, row, "bb"); tree.set(b, "hexpand", Value::Bool(true)); assert_eq!(share(&tree, row, 20, true, 1), vec![2, 18]); let _ = a; } #[test] fn a_short_box_shrinks_toward_the_minimums_rather_than_clipping_the_first_child() { let mut tree = Tree::new(); let row = tree.new_node("hbox"); tree.set(row, "orientation", Value::Str("horizontal".into())); let root = tree.root(); tree.append(root, row); label(&mut tree, row, "one two"); label(&mut tree, row, "three four"); // 17 natural, 10 offered: both give up some, neither goes under its // longest word. let shares = share(&tree, row, 10, true, 1); assert_eq!(shares.iter().sum::(), 10); assert!(shares[0] >= 3 && shares[1] >= 5, "{shares:?}"); } #[test] fn spacing_comes_off_the_room_before_it_is_shared() { let mut tree = Tree::new(); let row = tree.new_node("hbox"); tree.set(row, "orientation", Value::Str("horizontal".into())); tree.set(row, "spacing", Value::Num(2.0)); let root = tree.root(); tree.append(root, row); let a = label(&mut tree, row, "aa"); let b = label(&mut tree, row, "bb"); tree.set(a, "hexpand", Value::Bool(true)); tree.set(b, "hexpand", Value::Bool(true)); assert_eq!(share(&tree, row, 12, true, 1), vec![5, 5]); } #[test] fn a_column_shares_its_rows_out_at_the_width_it_has() { // A column two rows tall and thirty columns wide holds two labels, and // each is one row at that width. Measured against the rows instead — // as this did — "the second line" wraps to five, the overrun comes off // the end, and the second child is handed nothing: a box that paints // its first child and drops the rest, which is what the chats list did // to every Open button in it. let mut tree = Tree::new(); let col = tree.new_node("vbox"); tree.set(col, "orientation", Value::Str("vertical".into())); let root = tree.root(); tree.append(root, col); label(&mut tree, col, "the first line"); label(&mut tree, col, "the second line"); assert_eq!(share(&tree, col, 2, false, 30), vec![1, 1]); } #[test] fn a_centred_child_sits_in_the_middle_of_its_row() { assert_eq!(place(Align::Center, 4, 10), (3, 4)); assert_eq!(place(Align::End, 4, 10), (6, 4)); assert_eq!(place(Align::Fill, 4, 10), (0, 10)); } #[test] fn a_frame_spends_a_cell_a_side_on_its_border() { let mut tree = Tree::new(); let frame = tree.new_node("frame"); let root = tree.root(); tree.append(root, frame); label(&mut tree, frame, "hi"); assert_eq!(width(&tree, frame, false), 4); assert_eq!(height_for_width(&tree, frame, 4), 3); } }