Implement `TaffyLayout` widget (#140)

* Fix text widget layout invalidation

* Gitignore .DS_Store files

* Add downcast_ref method to Pod

* Add compute_max_intrinsic method to Pod

Implement compute_max_intrinsic for Box<dyn AnyWidget>

* Add TaffyLayout view and widget

* Add background_color support to TaffyLayout

* Add taffy example
This commit is contained in:
Nico Burns 2023-11-28 15:26:48 +00:00 committed by GitHub
parent f643dc491b
commit c439885866
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 787 additions and 1 deletions

1
.gitignore vendored
View File

@ -5,3 +5,4 @@ Cargo.lock
.vscode
.cspell
.DS_Store

18
Cargo.lock generated
View File

@ -1167,6 +1167,12 @@ dependencies = [
"bitflags 1.3.2",
]
[[package]]
name = "grid"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1df00eed8d1f0db937f6be10e46e8072b0671accb504cf0f959c5c52c679f5b9"
[[package]]
name = "guillotiere"
version = "0.6.2"
@ -2164,6 +2170,17 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "taffy"
version = "0.3.11"
source = "git+https://github.com/DioxusLabs/taffy?rev=7781c70241f7f572130c13106f2a869a9cf80885#7781c70241f7f572130c13106f2a869a9cf80885"
dependencies = [
"arrayvec",
"grid",
"num-traits",
"slotmap",
]
[[package]]
name = "tempfile"
version = "3.6.0"
@ -3020,6 +3037,7 @@ dependencies = [
"futures-task",
"glazier",
"parley",
"taffy",
"test-log",
"tokio",
"tracing",

View File

@ -41,13 +41,15 @@ default-target = "x86_64-pc-windows-msvc"
cargo-args = ["-Zunstable-options", "-Zrustdoc-scrape-examples"]
[features]
default = ["x11"]
default = ["x11", "taffy"]
x11 = ["glazier/x11"]
wayland = ["glazier/wayland"]
taffy = ["dep:taffy"]
[dependencies]
xilem_core.workspace = true
taffy = { git = "https://github.com/DioxusLabs/taffy", rev = "7781c70241f7f572130c13106f2a869a9cf80885", optional = true }
vello = { git = "https://github.com/linebender/vello", rev = "9d7c4f00d8db420337706771a37937e9025e089c" }
wgpu = "0.17.0"
parley = { git = "https://github.com/dfrg/parley", rev = "2371bf4b702ec91edee2d58ffb2d432539580e1e" }

127
examples/taffy.rs Normal file
View File

@ -0,0 +1,127 @@
use xilem::{view::View, App, AppLauncher};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct AppState {
count: u32,
}
impl AppState {
fn new() -> Self {
Self { count: 1 }
}
}
#[cfg(not(feature = "taffy"))]
fn app_logic(_data: &mut AppState) -> impl View<AppState> {
"Error: this example requires the 'taffy' feature to be enabled"
}
#[cfg(feature = "taffy")]
fn app_logic(state: &mut AppState) -> impl View<AppState> {
use taffy::style::{AlignItems, FlexWrap, JustifyContent};
use taffy::style_helpers::length;
use vello::peniko::Color;
use xilem::view::{button, div, flex_column, flex_row};
const COLORS: [Color; 4] = [
Color::LIGHT_GREEN,
Color::BLACK,
Color::AZURE,
Color::HOT_PINK,
];
// Some logic, deriving state for the view from our app state
let label = if state.count == 1 {
"Square count: 1".to_string()
} else {
format!("Square count: {}", state.count)
};
// The actual UI Code starts here
flex_column((
// Header
div(String::from("Xilem Example"))
.with_background_color(Color::RED)
.with_style(|s| s.padding = length(20.0)),
// Body
flex_column((
// Counter control buttons
flex_row((
label,
button("increase", |state: &mut AppState| {
println!("clicked increase");
state.count += 1;
}),
button("decrease", |state: &mut AppState| {
println!("clicked decrease");
if state.count > 0 {
state.count -= 1;
}
}),
button("reset", |state: &mut AppState| {
println!("clicked reset");
state.count = 1;
}),
))
.with_background_color(Color::BLUE_VIOLET)
.with_style(|s| {
s.gap.width = length(20.0);
s.padding = length(20.0);
s.justify_content = Some(JustifyContent::Start);
s.align_items = Some(AlignItems::Center);
}),
// Description text
div(String::from("The number of squares below is controlled by the counter above.\n\nTry clicking \"increase\" until the square count increases enough that the view becomes scrollable."))
.with_background_color(Color::RED)
.with_style(|s| s.padding = length(20.0)),
// Lorem Ipsum text
div(String::from("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."))
.with_background_color(Color::RED)
.with_style(|s| s.padding = length(20.0)),
// Wrapping container (number of children controlled by counter)
flex_row(
(0..state.count).map(|i| {
div(())
.with_background_color(COLORS[(i % 4) as usize])
.with_style(|s| {
s.size.width = length(200.0);
s.size.height = length(200.0);
})
}).collect::<Vec<_>>()
)
.with_background_color(Color::FOREST_GREEN)
.with_style(|s| {
s.flex_grow = 1.0;
s.flex_wrap = FlexWrap::Wrap;
s.gap = length(20.0);
s.padding = length(20.0);
}),
))
.with_style(|s| {
s.gap.height = length(20.0);
s.padding.left = length(20.0);
s.padding.right = length(20.0);
s.padding.top = length(20.0);
s.padding.bottom = length(20.0);
})
.with_background_color(Color::WHITE)
)).with_style(|s| {
s.padding.left = length(20.0);
s.padding.right = length(20.0);
s.padding.top = length(20.0);
s.padding.bottom = length(20.0);
})
.with_background_color(Color::DARK_GRAY)
}
fn main() {
let app = App::new(AppState::new(), app_logic);
AppLauncher::new(app).run()
}

View File

@ -32,3 +32,8 @@ pub use linear_layout::{h_stack, v_stack, LinearLayout};
pub use list::{list, List};
pub use switch::switch;
pub use view::{Adapt, AdaptState, Cx, Memoize, View, ViewMarker, ViewSequence};
#[cfg(feature = "taffy")]
mod taffy_layout;
#[cfg(feature = "taffy")]
pub use taffy_layout::{div, flex_column, flex_row, grid, TaffyLayout};

154
src/view/taffy_layout.rs Normal file
View File

@ -0,0 +1,154 @@
// Copyright 2022 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{any::Any, marker::PhantomData};
use vello::peniko::Color;
use crate::view::{Id, VecSplice, ViewMarker, ViewSequence};
use crate::widget::{self, ChangeFlags};
use crate::MessageResult;
use super::{Cx, View};
/// TaffyLayout is a container view which does layout for the specified ViewSequence.
///
/// Children are positioned according to the Block, Flexbox or CSS Grid algorithm, depending
/// on the display style set. If the children are themselves instances of TaffyLayout, then
/// they can set styles to control how they placed, sized, and aligned.
pub struct TaffyLayout<T, A, VT: ViewSequence<T, A>> {
children: VT,
style: taffy::Style,
background_color: Option<Color>,
phantom: PhantomData<fn() -> (T, A)>,
}
/// Creates a Flexbox Column [`TaffyLayout`].
pub fn flex_column<T, A, VT: ViewSequence<T, A>>(children: VT) -> TaffyLayout<T, A, VT> {
TaffyLayout::new_flex(children, taffy::FlexDirection::Column)
}
/// Creates a Flexbox Row [`TaffyLayout`].
pub fn flex_row<T, A, VT: ViewSequence<T, A>>(children: VT) -> TaffyLayout<T, A, VT> {
TaffyLayout::new_flex(children, taffy::FlexDirection::Row)
}
/// Creates a Block layout [`TaffyLayout`].
pub fn div<T, A, VT: ViewSequence<T, A>>(children: VT) -> TaffyLayout<T, A, VT> {
TaffyLayout::new(children, taffy::Display::Block)
}
/// Creates a CSS Grid [`TaffyLayout`].
pub fn grid<T, A, VT: ViewSequence<T, A>>(children: VT) -> TaffyLayout<T, A, VT> {
TaffyLayout::new(children, taffy::Display::Grid)
}
impl<T, A, VT: ViewSequence<T, A>> TaffyLayout<T, A, VT> {
pub fn new(children: VT, display: taffy::Display) -> Self {
let phantom = Default::default();
TaffyLayout {
children,
style: taffy::Style {
display,
..Default::default()
},
background_color: None,
phantom,
}
}
pub fn new_flex(children: VT, flex_direction: taffy::FlexDirection) -> Self {
let phantom = Default::default();
let display = taffy::Display::Flex;
TaffyLayout {
children,
style: taffy::Style {
display,
flex_direction,
..Default::default()
},
background_color: None,
phantom,
}
}
pub fn with_style(mut self, style_modifier: impl FnOnce(&mut taffy::Style)) -> Self {
style_modifier(&mut self.style);
self
}
pub fn with_background_color(mut self, color: impl Into<Color>) -> Self {
self.background_color = Some(color.into());
self
}
}
impl<T, A, VT: ViewSequence<T, A>> ViewMarker for TaffyLayout<T, A, VT> {}
impl<T, A, VT: ViewSequence<T, A>> View<T, A> for TaffyLayout<T, A, VT> {
type State = VT::State;
type Element = widget::TaffyLayout;
fn build(&self, cx: &mut Cx) -> (Id, Self::State, Self::Element) {
let mut elements = vec![];
let (id, state) = cx.with_new_id(|cx| self.children.build(cx, &mut elements));
let column = widget::TaffyLayout::new(elements, self.style.clone(), self.background_color);
(id, state, column)
}
fn rebuild(
&self,
cx: &mut Cx,
prev: &Self,
id: &mut Id,
state: &mut Self::State,
element: &mut Self::Element,
) -> ChangeFlags {
let mut scratch = vec![];
let mut splice = VecSplice::new(&mut element.children, &mut scratch);
let mut flags = cx.with_id(*id, |cx| {
self.children
.rebuild(cx, &prev.children, state, &mut splice)
});
if self.background_color != prev.background_color {
element.background_color = self.background_color;
flags |= ChangeFlags::PAINT
}
if self.style != prev.style {
element.style = self.style.clone();
flags |= ChangeFlags::LAYOUT | ChangeFlags::PAINT;
}
// Clear layout cache if the layout ChangeFlag is set
if flags.contains(ChangeFlags::LAYOUT) || flags.contains(ChangeFlags::TREE) {
element.cache.clear()
}
flags
}
fn message(
&self,
id_path: &[Id],
state: &mut Self::State,
event: Box<dyn Any>,
app_state: &mut T,
) -> MessageResult<A> {
self.children.message(id_path, state, event, app_state)
}
}

View File

@ -22,6 +22,7 @@ use vello::kurbo::{Affine, Point, Rect, Size};
use vello::{SceneBuilder, SceneFragment};
use super::widget::{AnyWidget, Widget};
use crate::Axis;
use crate::{id::Id, Bloom};
use super::{
@ -184,6 +185,11 @@ impl Pod {
}
}
/// Returns the wrapped widget.
pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
(*self.widget).as_any().downcast_ref()
}
/// Returns the wrapped widget.
pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
(*self.widget).as_any_mut().downcast_mut()
@ -391,6 +397,19 @@ impl Pod {
self.state.size
}
pub fn compute_max_intrinsic(
&mut self,
axis: Axis,
cx: &mut LayoutCx,
bc: &BoxConstraints,
) -> f64 {
let mut child_cx = LayoutCx {
cx_state: cx.cx_state,
widget_state: &mut self.state,
};
self.widget.compute_max_intrinsic(axis, &mut child_cx, bc)
}
///
pub fn accessibility(&mut self, cx: &mut AccessCx) {
if self.state.flags.intersects(

View File

@ -37,3 +37,8 @@ pub use raw_event::{Event, LifeCycle, MouseEvent, ViewContext};
pub use switch::Switch;
pub use text::TextWidget;
pub use widget::{AnyWidget, Widget};
#[cfg(feature = "taffy")]
mod taffy_layout;
#[cfg(feature = "taffy")]
pub use taffy_layout::TaffyLayout;

445
src/widget/taffy_layout.rs Normal file
View File

@ -0,0 +1,445 @@
// Copyright 2022 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::geometry::Axis;
use crate::widget::{AccessCx, BoxConstraints, Event};
use accesskit::NodeId;
use glazier::kurbo::Affine;
use vello::kurbo::{Point, Size};
use vello::peniko::{Brush, Color, Fill};
use vello::SceneBuilder;
use super::{contexts::LifeCycleCx, EventCx, LayoutCx, LifeCycle, PaintCx, Pod, UpdateCx, Widget};
/// Type inference gets confused because we're just passing None for the measure function. So we give
/// it a concrete type to work with (even though we never construct the inner type)
type DummyMeasureFunction =
fn(taffy::Size<Option<f32>>, taffy::Size<taffy::AvailableSpace>) -> taffy::Size<f32>;
/// Type conversions between Xilem types and their Taffy equivalents
mod convert {
use crate::{widget::BoxConstraints, Axis};
use vello::kurbo::Size;
/// Convert a `xilem::Axis` to a `taffy::AbsoluteAxis`
pub(super) fn to_taffy_axis(axis: Axis) -> taffy::AbsoluteAxis {
match axis {
Axis::Horizontal => taffy::AbsoluteAxis::Horizontal,
Axis::Vertical => taffy::AbsoluteAxis::Vertical,
}
}
/// Convert a `taffy::RequestedAxis` to a `xilem::Axis`
pub(super) fn from_taffy_axis(axis: taffy::RequestedAxis) -> Axis {
match axis {
taffy::RequestedAxis::Horizontal => Axis::Horizontal,
taffy::RequestedAxis::Vertical => Axis::Vertical,
// Taffy only uses "both" axis when run mode is PerformLayout. So as long as we only call this function
// when run mode is ComputeSize (which is the only time we care about axes) then this is unreachable.
taffy::RequestedAxis::Both => unreachable!(),
}
}
/// Convert `xilem::BoxConstraints` to `taffy::LayoutInput`.
pub(super) fn to_taffy_constraints(
bc: &BoxConstraints,
axis: taffy::RequestedAxis,
run_mode: taffy::RunMode,
sizing_mode: taffy::SizingMode,
) -> taffy::LayoutInput {
/// Convert min and max box constraints into a `taffy::AvailableSpace`
fn to_available_space(min: f64, max: f64) -> taffy::AvailableSpace {
if max.is_finite() {
taffy::AvailableSpace::Definite(max as f32)
} else if min.is_sign_negative() {
taffy::AvailableSpace::MinContent
} else {
taffy::AvailableSpace::MaxContent
}
}
let min = bc.min();
let max = bc.max();
taffy::LayoutInput {
known_dimensions: taffy::Size {
width: (min.width == max.width && min.width.is_finite())
.then_some(min.width as f32),
height: (min.height == max.height && min.height.is_finite())
.then_some(min.height as f32),
},
parent_size: taffy::Size {
width: max.width.is_finite().then_some(max.width as f32),
height: max.height.is_finite().then_some(max.height as f32),
},
available_space: taffy::Size {
width: to_available_space(min.width, max.width),
height: to_available_space(min.height, max.height),
},
axis,
run_mode,
sizing_mode,
vertical_margins_are_collapsible: taffy::Line::FALSE,
}
}
/// Convert`taffy::LayoutInput` to `xilem::BoxConstraints`
pub(super) fn to_box_constraints(input: &taffy::LayoutInput) -> BoxConstraints {
/// Converts Taffy's known_dimension and available_spaceinto a min box constraint
fn to_min_constraint(
known_dimension: Option<f32>,
available_space: taffy::AvailableSpace,
) -> f64 {
known_dimension.unwrap_or(match available_space {
taffy::AvailableSpace::Definite(_) => 0.0,
taffy::AvailableSpace::MaxContent => 0.0,
taffy::AvailableSpace::MinContent => -0.0,
}) as f64
}
/// Converts Taffy's known_dimension and available_spaceinto a min box constraint
fn to_max_constraint(
known_dimension: Option<f32>,
available_space: taffy::AvailableSpace,
) -> f64 {
known_dimension.unwrap_or(match available_space {
taffy::AvailableSpace::Definite(val) => val,
taffy::AvailableSpace::MaxContent => f32::INFINITY,
taffy::AvailableSpace::MinContent => f32::INFINITY,
}) as f64
}
BoxConstraints::new(
Size {
width: to_min_constraint(input.known_dimensions.width, input.available_space.width),
height: to_min_constraint(
input.known_dimensions.height,
input.available_space.height,
),
},
Size {
width: to_max_constraint(input.known_dimensions.width, input.available_space.width),
height: to_max_constraint(
input.known_dimensions.height,
input.available_space.height,
),
},
)
}
}
/// TaffyLayout is a container view which does layout for the specified ViewSequence.
///
/// Children are positioned according to the Block, Flexbox or CSS Grid algorithm, depending
/// on the display style set. If the children are themselves instances of TaffyLayout, then
/// they can set styles to control how they placed, sized, and aligned.
pub struct TaffyLayout {
pub children: Vec<Pod>,
pub cache: taffy::Cache,
pub style: taffy::Style,
pub background_color: Option<Color>,
}
impl TaffyLayout {
pub fn new(children: Vec<Pod>, style: taffy::Style, background_color: Option<Color>) -> Self {
TaffyLayout {
children,
cache: taffy::Cache::new(),
style,
background_color,
}
}
}
/// Iterator over the widget's children. Used in the implementation of `taffy::PartialLayoutTree`.
struct ChildIter(std::ops::Range<usize>);
impl Iterator for ChildIter {
type Item = taffy::NodeId;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(taffy::NodeId::from)
}
}
/// A this wrapper view over the widget (`TaffyLayout`) and the Xilem layout context (`LayoutCx`).
/// Implementing `taffy::PartialLayoutTree` for this wrapper (rather than implementing directing on
/// `TaffyLayout`) allows us to access the layout context during the layout process
struct TaffyLayoutCtx<'w, 'a, 'b> {
/// A mutable reference to the widget
widget: &'w mut TaffyLayout,
/// A mutable reference to the layout context
cx: &'w mut LayoutCx<'a, 'b>,
}
impl<'w, 'a, 'b> TaffyLayoutCtx<'w, 'a, 'b> {
/// Create a new `TaffyLayoutCtx`
fn new(widget: &'w mut TaffyLayout, cx: &'w mut LayoutCx<'a, 'b>) -> Self {
TaffyLayoutCtx { widget, cx }
}
}
impl<'w, 'a, 'b> taffy::PartialLayoutTree for TaffyLayoutCtx<'w, 'a, 'b> {
type ChildIter<'c> = ChildIter where Self: 'c;
fn child_ids(&self, _parent_node_id: taffy::NodeId) -> Self::ChildIter<'_> {
ChildIter(0..self.widget.children.len())
}
fn child_count(&self, _parent_node_id: taffy::NodeId) -> usize {
self.widget.children.len()
}
fn get_child_id(&self, _parent_node_id: taffy::NodeId, child_index: usize) -> taffy::NodeId {
taffy::NodeId::from(child_index)
}
fn get_style(&self, node_id: taffy::NodeId) -> &taffy::Style {
let node_id = usize::from(node_id);
if node_id == usize::MAX {
&self.widget.style
} else {
let child = &self.widget.children[node_id];
match child.downcast_ref::<TaffyLayout>() {
Some(child_widget) => &child_widget.style,
None => {
static DEFAULT_STYLE: taffy::Style = taffy::Style::DEFAULT;
&DEFAULT_STYLE
}
}
}
}
fn set_unrounded_layout(&mut self, node_id: taffy::NodeId, layout: &taffy::Layout) {
self.widget.children[usize::from(node_id)].set_origin(
self.cx,
Point {
x: layout.location.x as f64,
y: layout.location.y as f64,
},
);
}
fn get_cache_mut(&mut self, _node_id: taffy::NodeId) -> &mut taffy::Cache {
// We are implementing our own caching strategy rather than using the `taffy::compute_cached_layout` method
// so this method will never be called
unimplemented!()
}
fn compute_child_layout(
&mut self,
node_id: taffy::NodeId,
input: taffy::LayoutInput,
) -> taffy::LayoutOutput {
let box_constraints: BoxConstraints = convert::to_box_constraints(&input);
match input.run_mode {
taffy::RunMode::PerformLayout => {
let child = &mut self.widget.children[usize::from(node_id)];
let size = child.layout(self.cx, &box_constraints);
let taffy_size = taffy::Size {
width: size.width as f32,
height: size.height as f32,
};
taffy::LayoutOutput::from_outer_size(taffy_size)
}
taffy::RunMode::ComputeSize => {
let axis_size = self.widget.children[usize::from(node_id)].compute_max_intrinsic(
convert::from_taffy_axis(input.axis),
self.cx,
&box_constraints,
);
let taffy_size = match input.axis {
taffy::RequestedAxis::Horizontal => taffy::Size {
width: axis_size as f32,
height: 0.0,
},
taffy::RequestedAxis::Vertical => taffy::Size {
width: 0.0,
height: axis_size as f32,
},
taffy::RequestedAxis::Both => unreachable!(),
};
taffy::LayoutOutput::from_outer_size(taffy_size)
}
taffy::RunMode::PerformHiddenLayout => {
// TODO: set size of widget to zero
taffy::LayoutOutput::HIDDEN
}
}
}
}
impl Widget for TaffyLayout {
fn event(&mut self, cx: &mut EventCx, event: &Event) {
for child in &mut self.children {
child.event(cx, event);
}
}
fn lifecycle(&mut self, cx: &mut LifeCycleCx, event: &LifeCycle) {
for child in &mut self.children {
child.lifecycle(cx, event);
}
}
fn update(&mut self, cx: &mut UpdateCx) {
for child in &mut self.children {
child.update(cx);
}
}
fn layout(&mut self, cx: &mut LayoutCx, bc: &BoxConstraints) -> Size {
let display_mode = self.style.display;
let has_children = !self.children.is_empty();
let inputs = convert::to_taffy_constraints(
bc,
taffy::RequestedAxis::Both,
taffy::RunMode::PerformLayout,
taffy::SizingMode::InherentSize,
);
let node_id = taffy::NodeId::from(usize::MAX);
// Check for cached layout. And return it if found.
if let Some(cached_output) = self.cache.get(
inputs.known_dimensions,
inputs.available_space,
taffy::RunMode::PerformLayout,
) {
let max = bc.max();
return Size {
width: (cached_output.size.width as f64).min(max.width),
height: (cached_output.size.height as f64).min(max.height),
};
}
// Dispatch to a layout algorithm based on the node's display style and whether the node has children or not.
let mut layout_ctx = TaffyLayoutCtx::new(self, cx);
let output = match (display_mode, has_children) {
(taffy::Display::None, _) => taffy::compute_hidden_layout(&mut layout_ctx, node_id),
(taffy::Display::Block, true) => {
taffy::compute_block_layout(&mut layout_ctx, node_id, inputs)
}
(taffy::Display::Flex, true) => {
taffy::compute_flexbox_layout(&mut layout_ctx, node_id, inputs)
}
(taffy::Display::Grid, true) => {
taffy::compute_grid_layout(&mut layout_ctx, node_id, inputs)
}
(_, false) => {
let measure_function: Option<DummyMeasureFunction> = None;
taffy::compute_leaf_layout(inputs, &self.style, measure_function)
}
};
// Save output to cache
self.cache.store(
inputs.known_dimensions,
inputs.available_space,
taffy::RunMode::PerformLayout,
output,
);
cx.request_paint();
let max = bc.max();
Size {
width: (output.size.width as f64).min(max.width),
height: (output.size.height as f64).min(max.height),
}
}
fn compute_max_intrinsic(&mut self, axis: Axis, cx: &mut LayoutCx, bc: &BoxConstraints) -> f64 {
let display_mode = self.style.display;
let has_children = !self.children.is_empty();
let node_id = taffy::NodeId::from(usize::MAX);
let taffy_axis = convert::to_taffy_axis(axis);
let inputs = convert::to_taffy_constraints(
bc,
taffy_axis.into(),
taffy::RunMode::ComputeSize,
taffy::SizingMode::InherentSize, // TODO: Support SizingMode::ContentSize
);
// Check for cached size. And return it if found.
if let Some(cached_output) = self.cache.get(
inputs.known_dimensions,
inputs.available_space,
taffy::RunMode::ComputeSize,
) {
return cached_output.size.get_abs(taffy_axis) as f64;
}
// Dispatch to a layout algorithm based on the node's display style and whether the node has children or not.
let mut layout_ctx = TaffyLayoutCtx::new(self, cx);
let output = match (display_mode, has_children) {
(taffy::Display::None, _) => taffy::compute_hidden_layout(&mut layout_ctx, node_id),
(taffy::Display::Block, true) => {
taffy::compute_block_layout(&mut layout_ctx, node_id, inputs)
}
(taffy::Display::Flex, true) => {
taffy::compute_flexbox_layout(&mut layout_ctx, node_id, inputs)
}
(taffy::Display::Grid, true) => {
taffy::compute_grid_layout(&mut layout_ctx, node_id, inputs)
}
(_, false) => {
let measure_function: Option<DummyMeasureFunction> = None;
taffy::compute_leaf_layout(inputs, &self.style, measure_function)
}
};
// Save output to cache
self.cache.store(
inputs.known_dimensions,
inputs.available_space,
taffy::RunMode::ComputeSize,
output,
);
output.size.get_abs(taffy_axis) as f64
}
fn accessibility(&mut self, cx: &mut AccessCx) {
for child in &mut self.children {
child.accessibility(cx);
}
if cx.is_requested() {
let mut builder = accesskit::NodeBuilder::new(accesskit::Role::GenericContainer);
builder.set_children(
self.children
.iter()
.map(|pod| pod.id().into())
.collect::<Vec<NodeId>>(),
);
cx.push_node(builder);
}
}
fn paint(&mut self, cx: &mut PaintCx, builder: &mut SceneBuilder) {
if let Some(color) = self.background_color {
builder.fill(
Fill::NonZero,
Affine::IDENTITY,
&Brush::Solid(color),
None,
&cx.size().to_rect(),
);
}
for child in &mut self.children {
child.paint(cx, builder);
}
}
}

View File

@ -39,6 +39,7 @@ impl TextWidget {
pub fn set_text(&mut self, text: Cow<'static, str>) -> ChangeFlags {
self.text = text;
self.layout = None;
ChangeFlags::LAYOUT | ChangeFlags::PAINT
}

View File

@ -222,6 +222,15 @@ impl Widget for Box<dyn AnyWidget> {
self.deref_mut().layout(cx, bc)
}
fn compute_max_intrinsic(
&mut self,
axis: Axis,
ctx: &mut LayoutCx,
bc: &BoxConstraints,
) -> f64 {
self.deref_mut().compute_max_intrinsic(axis, ctx, bc)
}
fn accessibility(&mut self, cx: &mut AccessCx) {
self.deref_mut().accessibility(cx);
}