1use crate::scene::{self, Align, ImageFiles, Layout, Node, Scene, Size as DSize};
5use crate::tree::{Order, OrderKey};
6
7use super::*;
8
9mod run;
10pub(super) use run::*;
11impl Renderer {
12 pub fn layout(&mut self, scene: &Scene) -> Vec<Frame> {
15 self.register(&scene.fonts);
16 let mut l = Laid::build(self, scene);
17 l.settle_top(self);
18 l.frames(self, &scene.root).into_values().collect()
19 }
20
21 pub(super) fn compute(
24 &mut self,
25 runs: &mut Runs,
26 tree: &mut TaffyTree<Option<Leaf>>,
27 root: NodeId,
28 available: Size<AvailableSpace>,
29 ) {
30 tree.compute_layout_with_measure(root, available, |input, _id, ctx, style| {
31 let known = input.known_dimensions;
32 let fixed = |d: Dimension| (!d.is_auto()).then(|| d.value());
33 let known = Size {
34 width: known.width.or(fixed(style.size.width)),
35 height: known.height.or(fixed(style.size.height)),
36 };
37 let size = match ctx {
38 Some(Some(Leaf::Intrinsic(w, h))) => {
39 let (w, h) = (*w, *h);
41 match (known.width, known.height) {
42 (Some(kw), None) => Size {
43 width: kw,
44 height: kw * h / w,
45 },
46 (None, Some(kh)) => Size {
47 width: kh * w / h,
48 height: kh,
49 },
50 (kw, kh) => Size {
51 width: kw.unwrap_or(w),
52 height: kh.unwrap_or(h),
53 },
54 }
55 }
56 Some(Some(Leaf::Run(id))) => {
57 let [t, r, b, l] = runs.get(*id).padding;
61 let own = Size {
62 width: fixed(style.size.width).map(|v| v.max(l + r)),
63 height: fixed(style.size.height).map(|v| v.max(t + b)),
64 };
65 let known = Size {
66 width: input.known_dimensions.width.or(own.width),
67 height: input.known_dimensions.height.or(own.height),
68 };
69 return taffy::LayoutOutput::from_outer_size(self.measure_run(
70 runs,
71 *id,
72 known,
73 input.available_space,
74 ));
75 }
76 Some(Some(Leaf::Text(text, wraps))) => {
77 let width = known.width.or(match input.available_space.width {
78 AvailableSpace::Definite(w) if *wraps => Some(w),
79 _ => None,
80 });
81 let layout = self.text_layout(text, width);
82 Size {
83 width: known.width.unwrap_or(layout.width().ceil()),
84 height: known.height.unwrap_or(layout.height()),
85 }
86 }
87 _ => Size {
88 width: known.width.unwrap_or(0.0),
89 height: known.height.unwrap_or(0.0),
90 },
91 };
92 taffy::LayoutOutput::from_outer_size(size)
93 })
94 .expect("layout");
95 }
96}
97
98impl Renderer {
99 pub(super) fn settle_in(
102 &mut self,
103 runs: &mut Runs,
104 tree: &mut TaffyTree<Option<Leaf>>,
105 root: NodeId,
106 available: Size<AvailableSpace>,
107 hugs: &[(NodeId, bool, bool)],
108 ) {
109 for _ in 0..256 {
113 self.compute(runs, tree, root, available);
114 let mut changed = false;
115 for &(id, w, h) in hugs {
116 let (mut ew, mut eh) = (0.0f32, 0.0f32);
117 for child in tree.children(id).expect("children") {
118 let l = tree.unrounded_layout(child);
119 ew = ew.max(l.location.x + l.size.width);
120 eh = eh.max(l.location.y + l.size.height);
121 }
122 let mut style = tree.style(id).expect("style").clone();
123 let mut ch = false;
124 let mut set = |d: &mut Dimension, v: f32| {
125 if *d != Dimension::length(v) {
126 *d = Dimension::length(v);
127 ch = true;
128 }
129 };
130 if w {
131 set(&mut style.size.width, ew);
132 }
133 if h {
134 set(&mut style.size.height, eh);
135 }
136 if ch {
137 tree.set_style(id, style).expect("style");
138 changed = true;
139 }
140 }
141 if !changed {
142 break;
143 }
144 }
145 }
146}
147
148pub(super) fn find_node<'a>(root: &'a Node, order: &[OrderKey]) -> &'a Node {
150 let mut at = root;
151 for k in order {
152 at = at.children.get(k).expect("a node there");
153 }
154 at
155}
156
157pub(super) fn remove_subtree(tree: &mut TaffyTree<Option<Leaf>>, id: NodeId) {
159 for child in tree.children(id).unwrap_or_default() {
160 remove_subtree(tree, child);
161 }
162 let _ = tree.remove(id);
163}
164
165pub(super) enum Leaf {
168 Text(Box<scene::TextStyle>, bool),
170 Intrinsic(f32, f32),
173 Run(u32),
175 Proxy(OrderKey),
178}
179
180pub(super) struct Laid {
183 pub(super) top: TaffyTree<Option<Leaf>>,
185 pub(super) root: NodeId,
187 pub(super) runs: Runs,
189 pub(super) nodes: BTreeMap<Order, (Owner, NodeId)>,
191 pub(super) run_of: BTreeMap<Order, u32>,
193 pub(super) sens: BTreeMap<Order, Sens>,
197}
198
199#[derive(Clone, Copy, Debug, Default)]
202pub(super) struct Sens {
203 pub(super) me: bool,
205 pub(super) w: bool,
207 pub(super) h: bool,
209 pub(super) kids_w: usize,
211 pub(super) kids_h: usize,
213}
214
215fn room(node: &Node, kids_w: usize, kids_h: usize) -> (bool, bool) {
221 let along = |s: DSize, kids: usize| match s {
222 DSize::Px(_) => false,
223 DSize::Fill => true,
224 DSize::Hug => kids > 0,
225 };
226 (along(node.width, kids_w), along(node.height, kids_h))
227}
228
229impl Laid {
230 pub(super) fn sens_build(&mut self, node: &Node, order: Order) -> (bool, bool) {
233 let (mut kids_w, mut kids_h) = (0, 0);
234 for (k, c) in node.children.entries() {
235 let mut o = order.clone();
236 o.push(k.clone());
237 let (w, h) = self.sens_build(c, o);
238 kids_w += w as usize;
239 kids_h += h as usize;
240 }
241 let (w, h) = room(node, kids_w, kids_h);
242 self.sens.insert(
243 order,
244 Sens {
245 me: w || h,
246 w,
247 h,
248 kids_w,
249 kids_h,
250 },
251 );
252 (w, h)
253 }
254
255 pub(super) fn sensitive(&self, order: &Order) -> bool {
257 self.sens.get(order).is_some_and(|s| s.me)
258 }
259
260 pub(super) fn sens_settle(&mut self, root: &Node, order: &Order, kids: (isize, isize)) {
265 let mut at = order.clone();
266 let mut delta = kids;
267 loop {
268 let node = find_node(root, &at);
269 let s = self.sens.entry(at.clone()).or_default();
270 s.kids_w = (s.kids_w as isize + delta.0).max(0) as usize;
271 s.kids_h = (s.kids_h as isize + delta.1).max(0) as usize;
272 let (was_w, was_h, was) = (s.w, s.h, s.me);
273 let (w, h) = room(node, s.kids_w, s.kids_h);
274 (s.w, s.h, s.me) = (w, h, w || h);
275 if at.is_empty() {
276 return;
277 }
278 let parent = at[..at.len() - 1].to_vec();
279 if was != s.me
280 && let Some(&rid) = self.run_of.get(&parent)
281 {
282 let now = s.me;
283 let k = at.last().expect("a key").clone();
284 let run = self.runs.get_mut(rid);
285 let stretch = run.children.get(&k).is_some_and(|c| c.stretch);
286 run.classify(&k, stretch, now);
287 }
288 if (was_w, was_h) == (w, h) {
289 return;
290 }
291 delta = (w as isize - was_w as isize, h as isize - was_h as isize);
292 at = parent;
293 }
294 }
295
296 pub(super) fn sens_drop(&mut self, root: &Node, order: &Order) {
299 let (w, h) = self.sens.get(order).map_or((false, false), |s| (s.w, s.h));
300 let under: Vec<Order> = self
301 .sens
302 .range(order.clone()..)
303 .take_while(|(o, _)| o.starts_with(order))
304 .map(|(o, _)| o.clone())
305 .collect();
306 for o in under {
307 self.sens.remove(&o);
308 }
309 if (w || h) && !order.is_empty() {
310 let parent = order[..order.len() - 1].to_vec();
311 if self.sens.contains_key(&parent) {
312 self.sens_settle(root, &parent, (-(w as isize), -(h as isize)));
313 }
314 }
315 }
316}
317
318use std::collections::BTreeMap;
319
320impl Laid {
321 pub(super) fn build(_r: &mut Renderer, scene: &Scene) -> Laid {
323 let mut top = TaffyTree::new();
324 top.disable_rounding();
327 let mut l = Laid {
328 top: TaffyTree::new(),
329 root: NodeId::from(0u64),
330 runs: Runs::default(),
331 nodes: BTreeMap::new(),
332 run_of: BTreeMap::new(),
333 sens: BTreeMap::new(),
334 };
335 l.sens_build(&scene.root, Vec::new());
336 let root = l.build_node(
337 &mut top,
338 Owner::Top,
339 None,
340 &scene.root,
341 None,
342 &scene.images,
343 Vec::new(),
344 );
345 l.top = top;
346 l.root = root;
347 l
348 }
349
350 pub(super) fn tree(&self, owner: Owner) -> &TaffyTree<Option<Leaf>> {
352 match owner {
353 Owner::Top => &self.top,
354 Owner::Run(id) => &self.runs.get(id).tree,
355 }
356 }
357
358 pub(super) fn tree_mut(&mut self, owner: Owner) -> &mut TaffyTree<Option<Leaf>> {
360 match owner {
361 Owner::Top => &mut self.top,
362 Owner::Run(id) => &mut self.runs.get_mut(id).tree,
363 }
364 }
365
366 #[allow(clippy::too_many_arguments)]
370 pub(super) fn build_node(
371 &mut self,
372 tree: &mut TaffyTree<Option<Leaf>>,
373 owner: Owner,
374 inside: Option<OrderKey>,
375 node: &Node,
376 parent: Option<&Node>,
377 images: &ImageFiles,
378 order: Order,
379 ) -> NodeId {
380 let style = style_of(node, parent);
381 if let Some(leaf) = leaf_of(node, images) {
382 let id = tree.new_leaf_with_context(style, Some(leaf)).expect("leaf");
383 self.nodes.insert(order, (owner, id));
384 return id;
385 }
386 if is_run(node) {
387 let rid = self.runs.reserve();
388 let leaf = tree
392 .new_leaf_with_context(style, Some(Leaf::Run(rid)))
393 .expect("leaf");
394 let mut run = RunLayout::new(node, order.clone(), owner, leaf, inside);
395 run.hug = hugs_by_extent(node, parent).unwrap_or((false, false));
396 for (k, c) in node.children.entries() {
397 self.add_child(&mut run, rid, k, c, node, images, &order);
398 }
399 self.runs.put(rid, run);
400 self.run_of.insert(order.clone(), rid);
401 self.nodes.insert(order, (owner, leaf));
402 return leaf;
403 }
404 let id = tree.new_leaf(style).expect("leaf");
406 self.nodes.insert(order, (owner, id));
407 id
408 }
409
410 #[allow(clippy::too_many_arguments)]
413 pub(super) fn add_child(
414 &mut self,
415 run: &mut RunLayout,
416 rid: u32,
417 k: &OrderKey,
418 child: &Node,
419 node: &Node,
420 images: &ImageFiles,
421 order: &Order,
422 ) {
423 let mut o = order.clone();
424 o.push(k.clone());
425 let mut tree = std::mem::replace(&mut run.tree, TaffyTree::new());
426 let id = self.build_node(
427 &mut tree,
428 Owner::Run(rid),
429 Some(k.clone()),
430 child,
431 Some(node),
432 images,
433 o,
434 );
435 run.tree = tree;
436 let (along, across) = if run.row {
437 (child.width, child.height)
438 } else {
439 (child.height, child.width)
440 };
441 let mut o = order.clone();
442 o.push(k.clone());
443 let sens = self.sensitive(&o);
444 run.add(k.clone(), id, across == DSize::Fill, sens);
445 if along == DSize::Fill {
446 run.add_fill(k.clone(), style_of(child, Some(node)));
447 }
448 }
449
450 pub(super) fn settle_top(&mut self, r: &mut Renderer) {
452 let root = self.root;
453 r.settle_in(&mut self.runs, &mut self.top, root, Size::MAX_CONTENT, &[]);
454 }
455
456 pub(super) fn run_places(
461 &self,
462 rid: u32,
463 size: Size<f32>,
464 ) -> Option<(&RunLayout, &Asked, f32, f64)> {
465 let run = self.runs.get(rid);
466 let (pa0, pa1) = run.padding_along();
467 let (pc0, pc1) = run.padding_across();
468 let (along, across) = if run.row {
469 (size.width, size.height)
470 } else {
471 (size.height, size.width)
472 };
473 let line = (across - pc0 - pc1).max(0.0);
474 let asked = run.placed(line)?;
475 let free = along - pa0 - pa1 - run.length(asked) as f32;
476 let n = run.children.len();
477 let spread = if run.justify == Align::SpaceBetween && free > 1e-3 && n > 1 {
478 free as f64 / (n - 1) as f64
479 } else {
480 0.0
481 };
482 Some((run, asked, pa0 + run.lead(free), run.gap as f64 + spread))
483 }
484
485 pub(super) fn frames(&mut self, r: &mut Renderer, root: &Node) -> BTreeMap<Order, Frame> {
487 let mut out = BTreeMap::new();
488 let top = self.root;
489 self.frames_of(
490 r,
491 root,
492 Vec::new(),
493 Owner::Top,
494 top,
495 Place::default(),
496 true,
497 &mut out,
498 );
499 out
500 }
501
502 #[allow(clippy::too_many_arguments)]
506 fn frames_of(
507 &mut self,
508 r: &mut Renderer,
509 node: &Node,
510 order: Order,
511 owner: Owner,
512 id: NodeId,
513 parent: Place,
514 root: bool,
515 out: &mut BTreeMap<Order, Frame>,
516 ) {
517 let tree = self.tree(owner);
518 let (frame, place) = placed(tree, id, parent, root);
519 out.insert(order.clone(), frame);
520 if let Some(&rid) = self.run_of.get(&order)
521 && self.runs.get(rid).free
522 {
523 for (k, c) in node.children.entries() {
525 r.relay_free(&mut self.runs, rid, k);
526 let node_id = self.runs.get(rid).children[k].node;
527 let mut o = order.clone();
528 o.push(k.clone());
529 self.frames_of(r, c, o, Owner::Run(rid), node_id, place, false, out);
530 }
531 return;
532 }
533 if let Some(&rid) = self.run_of.get(&order) {
534 let size = tree.unrounded_layout(id).size;
535 let mut before = 0.0f64;
536 for (k, c) in node.children.entries() {
537 let Some((run, asked, lead, step)) = self.run_places(rid, size) else {
538 return;
539 };
540 let line = asked.line;
541 let Some(s) = run.size_of(asked, k) else {
542 continue;
543 };
544 let (pc0, _) = run.padding_across();
545 let stretch = run.children[k].stretch;
546 let across = pc0 + run.across(line, &s, stretch);
547 let item = child_place(place, run.row, lead as f64 + before, across as f64);
548 let node_id = run.children[k].node;
549 r.relay(&mut self.runs, rid, k, line);
550 let mut o = order.clone();
551 o.push(k.clone());
552 self.frames_of(r, c, o, Owner::Run(rid), node_id, item, false, out);
553 before += s.along as f64 + step;
554 }
555 return;
556 }
557 let kids = tree.children(id).unwrap_or_default();
558 for ((k, c), &child) in node.children.entries().zip(&kids) {
559 let mut o = order.clone();
560 o.push(k.clone());
561 self.frames_of(r, c, o, owner, child, place, false, out);
562 }
563 }
564}
565
566pub(super) fn child_place(run: Place, row: bool, along: f64, across: f64) -> Place {
571 let (along, across) = (along as f32, across as f32);
574 let (dx, dy) = if row {
575 (along, across)
576 } else {
577 (across, along)
578 };
579 let raw = (run.raw.0 + dx, run.raw.1 + dy);
580 let at = (
581 run.at.0 + snap(raw.0) - snap(run.raw.0),
582 run.at.1 + snap(raw.1) - snap(run.raw.1),
583 );
584 Place { at, raw }
585}
586
587#[cfg(test)]
591pub(super) fn build_plain(
592 tree: &mut TaffyTree<Option<Leaf>>,
593 node: &Node,
594 parent: Option<&Node>,
595 hugs: &mut Vec<(NodeId, bool, bool)>,
596 images: &ImageFiles,
597) -> NodeId {
598 let style = style_of(node, parent);
599 if let Some(leaf) = leaf_of(node, images) {
600 return tree.new_leaf_with_context(style, Some(leaf)).expect("leaf");
601 }
602 let children: Vec<NodeId> = node
603 .children
604 .iter()
605 .map(|c| build_plain(tree, c, Some(node), hugs, images))
606 .collect();
607 let id = tree.new_with_children(style, &children).expect("node");
608 if let Some((w, h)) = hugs_by_extent(node, parent) {
609 hugs.push((id, w, h));
610 }
611 id
612}
613
614pub(super) fn hugs_by_extent(node: &Node, parent: Option<&Node>) -> Option<(bool, bool)> {
617 if leafy(node) {
618 return None;
619 }
620 let hugs_by = |s: DSize| s == DSize::Hug || (parent.is_none() && s == DSize::Fill);
622 let (w, h) = (hugs_by(node.width), hugs_by(node.height));
623 (node.layout == Layout::None && !node.children.is_empty() && (w || h)).then_some((w, h))
624}
625
626pub(super) fn leafy(node: &Node) -> bool {
628 node.text.is_some() || node.vector.is_some() || node.image.is_some()
629}
630
631pub(super) fn leaf_of(node: &Node, images: &ImageFiles) -> Option<Leaf> {
633 if let Some(text) = &node.text {
634 let wraps = !matches!(node.width, DSize::Hug);
635 return Some(Leaf::Text(Box::new(text.clone()), wraps));
636 }
637 let intrinsic = match (&node.vector, &node.image) {
638 (Some(v), _) => Some((v.view_box[2], v.view_box[3])),
639 (_, Some(i)) => images.get(&i.id).map(|f| (f.width as f32, f.height as f32)),
640 _ => None,
641 };
642 intrinsic.map(|(w, h)| Leaf::Intrinsic(w, h))
643}
644
645pub(super) fn style_of(node: &Node, parent: Option<&Node>) -> Style {
647 let mut style = Style::default();
648 let dir = parent.map(|p| p.layout);
649 let dim = |s: DSize| match s {
650 DSize::Px(v) => Dimension::length(v),
651 _ => Dimension::auto(),
652 };
653 style.size = Size {
654 width: dim(node.width),
655 height: dim(node.height),
656 };
657 let (main, cross) = match dir {
658 Some(Layout::Row) => (node.width, node.height),
659 Some(Layout::Column) => (node.height, node.width),
660 _ => (DSize::Hug, DSize::Hug),
661 };
662 if main == DSize::Fill {
663 style.flex_grow = 1.0;
664 style.flex_basis = Dimension::length(0.0);
665 }
666 if cross == DSize::Fill {
667 style.align_self = Some(AlignSelf::STRETCH);
668 }
669 style.position = Position::Relative;
673 if dir == Some(Layout::None) {
674 style.position = Position::Absolute;
675 style.inset = taffy::Rect {
676 left: LengthPercentageAuto::length(node.x),
677 top: LengthPercentageAuto::length(node.y),
678 right: LengthPercentageAuto::auto(),
679 bottom: LengthPercentageAuto::auto(),
680 };
681 }
682 style.flex_shrink = 0.0;
683 if node.layout == Layout::None && !leafy(node) {
686 let [t, r, b, l] = node.padding;
687 style.min_size = Size {
688 width: LengthPercentageAuto::length(l + r),
689 height: LengthPercentageAuto::length(t + b),
690 };
691 }
692 match node.layout {
693 Layout::Row => style.flex_direction = FlexDirection::Row,
694 Layout::Column => style.flex_direction = FlexDirection::Column,
695 Layout::None => {}
696 }
697 style.gap = Size {
698 width: LengthPercentage::length(node.gap),
699 height: LengthPercentage::length(node.gap),
700 };
701 let [t, r, b, l] = node.padding;
702 style.padding = taffy::Rect {
703 top: LengthPercentage::length(t),
704 right: LengthPercentage::length(r),
705 bottom: LengthPercentage::length(b),
706 left: LengthPercentage::length(l),
707 };
708 style.align_items = match node.align {
709 Align::Center => AlignItems::CENTER,
710 Align::End => AlignItems::FLEX_END,
711 _ => AlignItems::FLEX_START,
712 };
713 style.justify_content = match node.justify {
714 Align::Center => JustifyContent::CENTER,
715 Align::End => JustifyContent::FLEX_END,
716 Align::SpaceBetween => JustifyContent::SPACE_BETWEEN,
717 Align::Start => JustifyContent::FLEX_START,
718 };
719 style
720}
721
722#[cfg(test)]
723mod tests;
724
725pub(super) fn snap(v: f32) -> f32 {
727 (v + 0.5).floor()
728}
729
730#[derive(Clone, Copy, Debug, Default)]
736pub(super) struct Place {
737 pub(super) at: (f32, f32),
739 pub(super) raw: (f32, f32),
741}
742
743pub(super) fn placed(
749 tree: &TaffyTree<Option<Leaf>>,
750 id: NodeId,
751 parent: Place,
752 _root: bool,
753) -> (Frame, Place) {
754 let l = tree.unrounded_layout(id);
755 let base = parent.raw;
756 let (x, y) = (base.0 + l.location.x, base.1 + l.location.y);
757 let frame = Frame {
758 x: parent.at.0 + snap(x) - snap(base.0),
759 y: parent.at.1 + snap(y) - snap(base.1),
760 width: snap(x + l.size.width) - snap(x),
761 height: snap(y + l.size.height) - snap(y),
762 };
763 let place = Place {
764 at: (frame.x, frame.y),
765 raw: (x, y),
766 };
767 (frame, place)
768}