Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
197 changes: 70 additions & 127 deletions src/builder.rs

Large diffs are not rendered by default.

49 changes: 24 additions & 25 deletions src/collapse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@

use core::time::Duration;

use taffy::{Dimension, NodeId, TaffyTree, style_helpers::length};
use taffy::{Dimension, NodeId, style_helpers::length};

use crate::builder::{Builder, NodeHandle, Scope, Slot};
use crate::pipeline::{DismissFn, Node};
use crate::layout_tree::LayoutTree;
use crate::pipeline::DismissFn;
use crate::presence::Shown;
use crate::tw::{Easing, Progress, Tw, tw};

Expand Down Expand Up @@ -221,37 +222,37 @@ impl<'b, 'f, A> CollapsibleChain<'b, 'f, A> {
}

/// The wrappers in motion under `root`, with how far each has opened.
fn in_motion(tree: &TaffyTree<Node>, root: NodeId) -> Vec<(NodeId, CollapseAxis, Progress)> {
fn in_motion(tree: &LayoutTree, root: NodeId) -> Vec<(NodeId, CollapseAxis, Progress)> {
let mut found = Vec::new();
let mut stack = vec![root];
while let Some(node) = stack.pop() {
if let Some((axis, progress)) = tree
.get_node_context(node)
.node(node)
.and_then(|context| context.collapse)
.and_then(|collapse| Some((collapse.axis, collapse.motion?)))
{
found.push((node, axis, progress));
}
stack.extend(tree.children(node).expect("node exists"));
stack.extend(tree.children(node));
}
found
}

fn set_extent(tree: &mut TaffyTree<Node>, node: NodeId, axis: CollapseAxis, extent: Dimension) {
let mut style = tree.style(node).expect("node exists").clone();
fn set_extent(tree: &mut LayoutTree, node: NodeId, axis: CollapseAxis, extent: Dimension) {
let mut style = tree.style(node).clone();
match axis {
CollapseAxis::Height => style.size.height = extent,
CollapseAxis::Width => style.size.width = extent,
}
tree.set_style(node, style).expect("node exists");
tree.set_style(node, style);
}

/// Lays out the tree under `root` with `compute`, and again if a wrapper is
/// in motion, with it at its fraction of the size the first layout gave it.
pub(crate) fn solve_in_motion(
tree: &mut TaffyTree<Node>,
tree: &mut LayoutTree,
root: NodeId,
mut compute: impl FnMut(&mut TaffyTree<Node>),
mut compute: impl FnMut(&mut LayoutTree),
) {
let moving = in_motion(tree, root);
for &(node, axis, _) in &moving {
Expand All @@ -262,15 +263,15 @@ pub(crate) fn solve_in_motion(
return;
}
for &(node, axis, progress) in &moving {
let natural = tree.layout(node).expect("node exists").size;
let natural = tree.layout(node).size;
let natural = match axis {
CollapseAxis::Height => natural.height,
CollapseAxis::Width => natural.width,
};
let current = natural * f32::from(progress);
set_extent(tree, node, axis, length(current));
if let Some(collapse) = tree
.get_node_context_mut(node)
.node_mut(node)
.and_then(|context| context.collapse.as_mut())
{
collapse.flight = Some(Flight {
Expand All @@ -287,19 +288,19 @@ pub(crate) fn solve_in_motion(
/// than they have gone: the sum of target − current. What a container whose
/// height is cached while it is laid out (a virtual list's row) adds to its
/// measured size to know where it is going. Valid once the tree is solved.
pub(crate) fn flight_in(tree: &TaffyTree<Node>, node: NodeId, axis: CollapseAxis) -> f32 {
pub(crate) fn flight_in(tree: &LayoutTree, node: NodeId, axis: CollapseAxis) -> f32 {
let mut remaining = 0.0;
let mut stack = vec![node];
while let Some(at) = stack.pop() {
if let Some(flight) = tree
.get_node_context(at)
.node(at)
.and_then(|context| context.collapse)
.and_then(|collapse| collapse.flight)
.filter(|flight| flight.axis == axis)
{
remaining += flight.target - flight.current;
}
stack.extend(tree.children(at).expect("node exists"));
stack.extend(tree.children(at));
}
remaining
}
Expand All @@ -310,7 +311,7 @@ mod tests {
use taffy::Style;

use super::*;
use crate::pipeline::NodeKind;
use crate::pipeline::{Node, NodeKind};
use crate::text::{TextSpec, TextStyle, Weight};

fn node(flight: Option<Flight>) -> Node {
Expand Down Expand Up @@ -342,19 +343,17 @@ mod tests {

#[test]
fn the_flight_in_a_subtree_sums_what_is_left_along_the_axis() {
let mut tree = TaffyTree::<Node>::new();
let mut leaf = |f| {
tree.new_leaf_with_context(Style::default(), node(f))
.expect("leaf")
};
let mut tree = LayoutTree::new();
let mut leaf = |f| tree.new_node(Style::default(), &[], node(f));
let opening = leaf(flight(CollapseAxis::Height, 100.0, 30.0));
let closing = leaf(flight(CollapseAxis::Height, 50.0, 80.0));
let sideways = leaf(flight(CollapseAxis::Width, 40.0, 0.0));
let still = leaf(None);
let row = tree
.new_with_children(Style::default(), &[opening, closing, sideways, still])
.expect("row");
tree.set_node_context(row, Some(node(None))).expect("row");
let row = tree.new_node(
Style::default(),
&[opening, closing, sideways, still],
node(None),
);
assert_eq!(flight_in(&tree, row, CollapseAxis::Height), 70.0 - 30.0);
assert_eq!(flight_in(&tree, row, CollapseAxis::Width), 40.0);
assert_eq!(flight_in(&tree, still, CollapseAxis::Height), 0.0);
Expand Down
249 changes: 249 additions & 0 deletions src/layout_tree.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
//! The taffy tree a frame is laid out in, behind accessors that cannot fail.
//!
//! Every node is made by [`LayoutTree::new_node`] with its [`Node`], so a
//! node is in the tree exactly when it has one: that is the check made
//! before each taffy call, whose own indexing panics on a missing node. A
//! miss is a bug of the library: it is reported as
//! [`Problem::Internal`] and the accessor falls back to a default.

use std::panic::Location;

use egui::Context;
use taffy::{AvailableSpace, Layout, LayoutInput, LayoutOutput, NodeId, Size, Style, TaffyTree};

use crate::Problem;
use crate::pipeline::Node;

const DEFAULT_STYLE: &Style = &Style::DEFAULT;

/// The id [`LayoutTree::new_node`] gives when taffy refuses a node: one that
/// no tree holds, so every accessor treats it as missing.
const DANGLING: NodeId = NodeId::new(u64::MAX);

pub(crate) struct LayoutTree {
taffy: TaffyTree<Node>,
/// Where misses are reported: the context of the build that last reset
/// the tree.
ctx: Option<Context>,
}

impl LayoutTree {
pub(crate) fn new() -> Self {
let mut taffy = TaffyTree::new();
taffy.disable_rounding();
Self { taffy, ctx: None }
}

/// An empty tree reporting where this one does.
pub(crate) fn scratch(&self) -> Self {
Self {
ctx: self.ctx.clone(),
..Self::new()
}
}

/// Drops every node, and reports to `ctx` from now on.
pub(crate) fn reset(&mut self, ctx: &Context) {
self.taffy.clear();
self.ctx = Some(ctx.clone());
}

/// A node of `style` holding `node`, with `kids` as its children.
#[track_caller]
pub(crate) fn new_node(&mut self, style: Style, kids: &[NodeId], node: Node) -> NodeId {
let at = Location::caller();
let kept: Vec<NodeId> = kids
.iter()
.copied()
.filter(|&kid| {
let has = self.has(kid);
if !has {
self.missing(at, kid);
}
has
})
.collect();
let made = self.taffy.new_with_children(style, &kept).and_then(|id| {
self.taffy.set_node_context(id, Some(node))?;
Ok(id)
});
made.unwrap_or_else(|error| {
self.failed(at, &error);
DANGLING
})
}

#[track_caller]
pub(crate) fn node(&self, id: NodeId) -> Option<&Node> {
let node = self.taffy.get_node_context(id);
if node.is_none() {
self.missing(Location::caller(), id);
}
node
}

#[track_caller]
pub(crate) fn node_mut(&mut self, id: NodeId) -> Option<&mut Node> {
if !self.has(id) {
self.missing(Location::caller(), id);
}
self.taffy.get_node_context_mut(id)
}

/// The node's layout from the last solve; zero if it is missing.
#[track_caller]
pub(crate) fn layout(&self, id: NodeId) -> Layout {
self.checked(Location::caller(), id, |taffy| taffy.layout(id).copied())
.unwrap_or_default()
}

#[track_caller]
pub(crate) fn style(&self, id: NodeId) -> &Style {
self.checked(Location::caller(), id, |taffy| taffy.style(id))
.unwrap_or(DEFAULT_STYLE)
}

#[track_caller]
pub(crate) fn set_style(&mut self, id: NodeId, style: Style) {
let at = Location::caller();
if !self.has(id) {
self.missing(at, id);
} else if let Err(error) = self.taffy.set_style(id, style) {
self.failed(at, &error);
}
}

#[track_caller]
pub(crate) fn children(&self, id: NodeId) -> Vec<NodeId> {
self.checked(Location::caller(), id, |taffy| taffy.children(id))
.unwrap_or_default()
}

/// Solves the tree under `root` in the room `available`, measuring each
/// leaf with `measure`.
#[track_caller]
pub(crate) fn compute(
&mut self,
root: NodeId,
available: Size<AvailableSpace>,
measure: impl FnMut(LayoutInput, NodeId, Option<&mut Node>, &Style) -> LayoutOutput,
) {
let at = Location::caller();
if !self.has(root) {
self.missing(at, root);
} else if let Err(error) = self
.taffy
.compute_layout_with_measure(root, available, measure)
{
self.failed(at, &error);
}
}

fn has(&self, id: NodeId) -> bool {
self.taffy.get_node_context(id).is_some()
}

fn checked<'t, T>(
&'t self,
at: &'static Location<'static>,
id: NodeId,
read: impl FnOnce(&'t TaffyTree<Node>) -> taffy::TaffyResult<T>,
) -> Option<T> {
if !self.has(id) {
self.missing(at, id);
return None;
}
read(&self.taffy)
.inspect_err(|error| self.failed(at, error))
.ok()
}

fn missing(&self, at: &'static Location<'static>, id: NodeId) {
if let Some(ctx) = &self.ctx {
crate::report::report_at(
ctx,
Problem::Internal("taffy: missing node"),
None,
at,
|| format!("taffy: node {id:?} is not in the layout tree; it is skipped"),
);
}
}

fn failed(&self, at: &'static Location<'static>, error: &taffy::TaffyError) {
if let Some(ctx) = &self.ctx {
crate::report::report_at(ctx, Problem::Internal("taffy: refused"), None, at, || {
format!("taffy: {error}")
});
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::pipeline::NodeKind;
use crate::testing::{assert_no_reports, assert_reported};
use taffy::prelude::TaffyMaxContent;

fn node() -> Node {
Node::bare(NodeKind::Div, String::new(), crate::text::tests::base())
}

/// A tree reporting to a context of its own, and a node that was in it
/// before it was reset.
fn with_gone() -> (Context, LayoutTree, NodeId) {
let ctx = Context::default();
let mut tree = LayoutTree::new();
tree.reset(&ctx);
let gone = tree.new_node(Style::default(), &[], node());
tree.reset(&ctx);
assert!(!tree.has(gone), "the reset dropped the node");
assert_no_reports(&ctx);
(ctx, tree, gone)
}

#[test]
fn a_node_made_with_children_holds_them_and_its_node() {
let ctx = Context::default();
let mut tree = LayoutTree::new();
tree.reset(&ctx);
let leaf = tree.new_node(Style::default(), &[], node());
let parent = tree.new_node(Style::default(), &[leaf], node());
assert_eq!(tree.children(parent), vec![leaf]);
assert!(tree.node(parent).is_some());
tree.set_style(leaf, Style::DEFAULT);
tree.compute(parent, Size::MAX_CONTENT, |_, _, _, _| LayoutOutput::HIDDEN);
assert_no_reports(&ctx);
}

#[test]
fn reading_a_missing_node_gives_defaults_and_reports() {
let (ctx, tree, gone) = with_gone();
assert_eq!(tree.layout(gone), Layout::new());
assert_eq!(*tree.style(gone), Style::DEFAULT);
assert!(tree.children(gone).is_empty());
assert!(tree.node(gone).is_none());
assert_reported(&ctx, Problem::Internal("taffy: missing node"));
}

#[test]
fn writing_to_a_missing_node_does_nothing_and_reports() {
let (ctx, mut tree, gone) = with_gone();
tree.set_style(gone, Style::default());
assert!(tree.node_mut(gone).is_none());
tree.compute(gone, Size::MAX_CONTENT, |_, _, _, _| LayoutOutput::HIDDEN);
let reports = crate::testing::reports(&ctx);
assert_eq!(reports.len(), 3, "one per call site: {reports:#?}");
assert_reported(&ctx, Problem::Internal("taffy: missing node"));
}

#[test]
fn a_missing_child_is_left_out_and_reported() {
let (ctx, mut tree, gone) = with_gone();
let kept = tree.new_node(Style::default(), &[], node());
let parent = tree.new_node(Style::default(), &[gone, kept], node());
assert_eq!(tree.children(parent), vec![kept]);
assert_reported(&ctx, Problem::Internal("taffy: missing node"));
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ pub mod icons;
mod input_trace;
mod kept;
mod key;
mod layout_tree;
mod measure;
mod nav;
pub mod overlay;
Expand Down
Loading
Loading