Introduce Widget::size_hint and fix further layout inconsistencies

This commit is contained in:
Héctor Ramón Jiménez 2024-01-05 17:24:43 +01:00
parent 0322e820eb
commit 22226394f7
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
17 changed files with 210 additions and 123 deletions

View file

@ -91,7 +91,8 @@ where
child.as_widget().height().fill_factor(), child.as_widget().height().fill_factor(),
); );
if fill_main_factor == 0 && fill_cross_factor == 0 { if fill_main_factor == 0 {
if fill_cross_factor == 0 {
let (max_width, max_height) = axis.pack(available, max_cross); let (max_width, max_height) = axis.pack(available, max_cross);
let child_limits = let child_limits =
@ -105,11 +106,45 @@ where
cross = cross.max(axis.cross(size)); cross = cross.max(axis.cross(size));
nodes[i] = layout; nodes[i] = layout;
}
} else { } else {
fill_main_sum += fill_main_factor; fill_main_sum += fill_main_factor;
} }
} }
let intrinsic_cross = match axis {
Axis::Horizontal => match height {
Length::Shrink => cross,
_ => max_cross,
},
Axis::Vertical => match width {
Length::Shrink => cross,
_ => max_cross,
},
};
for (i, (child, tree)) in items.iter().zip(trees.iter_mut()).enumerate() {
let (fill_main_factor, fill_cross_factor) = axis.pack(
child.as_widget().width().fill_factor(),
child.as_widget().height().fill_factor(),
);
if fill_main_factor == 0 && fill_cross_factor != 0 {
let (max_width, max_height) = axis.pack(available, intrinsic_cross);
let child_limits =
Limits::new(Size::ZERO, Size::new(max_width, max_height));
let layout =
child.as_widget().layout(tree, renderer, &child_limits);
let size = layout.size();
available -= axis.main(size);
nodes[i] = layout;
}
}
let remaining = match axis { let remaining = match axis {
Axis::Horizontal => match width { Axis::Horizontal => match width {
Length::Shrink => 0.0, Length::Shrink => 0.0,
@ -121,24 +156,13 @@ where
}, },
}; };
let max_cross = match axis {
Axis::Horizontal => match height {
Length::Shrink if cross > 0.0 => cross,
_ => max_cross,
},
Axis::Vertical => match width {
Length::Shrink if cross > 0.0 => cross,
_ => max_cross,
},
};
for (i, (child, tree)) in items.iter().zip(trees).enumerate() { for (i, (child, tree)) in items.iter().zip(trees).enumerate() {
let (fill_main_factor, fill_cross_factor) = axis.pack( let (fill_main_factor, fill_cross_factor) = axis.pack(
child.as_widget().width().fill_factor(), child.as_widget().width().fill_factor(),
child.as_widget().height().fill_factor(), child.as_widget().height().fill_factor(),
); );
if fill_main_factor != 0 || fill_cross_factor != 0 { if fill_main_factor != 0 {
let max_main = if fill_main_factor == 0 { let max_main = if fill_main_factor == 0 {
available.max(0.0) available.max(0.0)
} else { } else {
@ -151,6 +175,12 @@ where
max_main max_main
}; };
let max_cross = if fill_cross_factor == 0 {
max_cross
} else {
intrinsic_cross
};
let (min_width, min_height) = let (min_width, min_height) =
axis.pack(min_main, axis.cross(limits.min())); axis.pack(min_main, axis.cross(limits.min()));
@ -203,8 +233,12 @@ where
main += axis.main(size); main += axis.main(size);
} }
let (width, height) = axis.pack(main - pad.0, cross); let (intrinsic_width, intrinsic_height) = axis.pack(main - pad.0, cross);
let size = limits.resolve(Size::new(width, height), width, height); let size = limits.resolve(
Size::new(intrinsic_width, intrinsic_height),
width,
height,
);
Node::with_children(size.expand(padding), nodes) Node::with_children(size.expand(padding), nodes)
} }

View file

@ -36,6 +36,12 @@ impl Length {
Length::Fixed(_) => 0, Length::Fixed(_) => 0,
} }
} }
/// Returns `true` iff the [`Length`] is either [`Length::Fill`] or
// [`Length::FillPortion`].
pub fn is_fill(&self) -> bool {
self.fill_factor() != 0
}
} }
impl From<Pixels> for Length { impl From<Pixels> for Length {

View file

@ -15,7 +15,7 @@ use crate::layout::{self, Layout};
use crate::mouse; use crate::mouse;
use crate::overlay; use crate::overlay;
use crate::renderer; use crate::renderer;
use crate::{Clipboard, Length, Rectangle, Shell}; use crate::{Clipboard, Length, Rectangle, Shell, Size};
/// A component that displays information and allows interaction. /// A component that displays information and allows interaction.
/// ///
@ -49,6 +49,14 @@ where
/// Returns the height of the [`Widget`]. /// Returns the height of the [`Widget`].
fn height(&self) -> Length; fn height(&self) -> Length;
/// Returns a [`Size`] hint for laying out the [`Widget`].
///
/// This hint may be used by some widget containers to adjust their sizing strategy
/// during construction.
fn size_hint(&self) -> Size<Length> {
Size::new(self.width(), self.height())
}
/// Returns the [`layout::Node`] of the [`Widget`]. /// Returns the [`layout::Node`] of the [`Widget`].
/// ///
/// This [`layout::Node`] is used by the runtime to compute the [`Layout`] of the /// This [`layout::Node`] is used by the runtime to compute the [`Layout`] of the

View file

@ -73,9 +73,8 @@ impl Application for Example {
} }
fn view(&self) -> Element<Message> { fn view(&self) -> Element<Message> {
let downloads = Column::with_children( let downloads =
self.downloads.iter().map(Download::view).collect(), Column::with_children(self.downloads.iter().map(Download::view))
)
.push( .push(
button("Add another download") button("Add another download")
.on_press(Message::Add) .on_press(Message::Add)

View file

@ -82,8 +82,7 @@ impl Application for Events {
self.last self.last
.iter() .iter()
.map(|event| text(format!("{event:?}")).size(40)) .map(|event| text(format!("{event:?}")).size(40))
.map(Element::from) .map(Element::from),
.collect(),
); );
let toggle = checkbox( let toggle = checkbox(

View file

@ -106,7 +106,7 @@ impl Example {
column![text("Original text")].padding(10), column![text("Original text")].padding(10),
|quotes, i| { |quotes, i| {
column![ column![
row![vertical_rule(2), quotes], row![vertical_rule(2), quotes].height(Length::Shrink),
text(format!("Reply {i}")) text(format!("Reply {i}"))
] ]
.spacing(10) .spacing(10)

View file

@ -178,10 +178,7 @@ impl Sandbox for App {
} }
}); });
column( column(items.into_iter().map(|item| {
items
.into_iter()
.map(|item| {
let button = button("Delete") let button = button("Delete")
.on_press(Message::DeleteItem(item.clone())) .on_press(Message::DeleteItem(item.clone()))
.style(theme::Button::Destructive); .style(theme::Button::Destructive);
@ -190,23 +187,14 @@ impl Sandbox for App {
text(&item.name) text(&item.name)
.style(theme::Text::Color(item.color.into())), .style(theme::Text::Color(item.color.into())),
horizontal_space(Length::Fill), horizontal_space(Length::Fill),
pick_list( pick_list(Color::ALL, Some(item.color), move |color| {
Color::ALL, Message::ItemColorChanged(item.clone(), color)
Some(item.color), }),
move |color| {
Message::ItemColorChanged(
item.clone(),
color,
)
}
),
button button
] ]
.spacing(20) .spacing(20)
.into() .into()
}) }))
.collect(),
)
.spacing(10) .spacing(10)
}); });

View file

@ -96,15 +96,14 @@ impl Application for LoadingSpinners {
container( container(
column.push( column.push(
row(vec![ row![
text("Cycle duration:").into(), text("Cycle duration:"),
slider(1.0..=1000.0, self.cycle_duration * 100.0, |x| { slider(1.0..=1000.0, self.cycle_duration * 100.0, |x| {
Message::CycleDurationChanged(x / 100.0) Message::CycleDurationChanged(x / 100.0)
}) })
.width(200.0) .width(200.0),
.into(), text(format!("{:.2}s", self.cycle_duration)),
text(format!("{:.2}s", self.cycle_duration)).into(), ]
])
.align_items(iced::Alignment::Center) .align_items(iced::Alignment::Center)
.spacing(20.0), .spacing(20.0),
), ),

View file

@ -172,23 +172,21 @@ impl Application for ScrollableDemo {
] ]
.spacing(10); .spacing(10);
let scroll_alignment_controls = column(vec![ let scroll_alignment_controls = column![
text("Scrollable alignment:").into(), text("Scrollable alignment:"),
radio( radio(
"Start", "Start",
scrollable::Alignment::Start, scrollable::Alignment::Start,
Some(self.alignment), Some(self.alignment),
Message::AlignmentChanged, Message::AlignmentChanged,
) ),
.into(),
radio( radio(
"End", "End",
scrollable::Alignment::End, scrollable::Alignment::End,
Some(self.alignment), Some(self.alignment),
Message::AlignmentChanged, Message::AlignmentChanged,
) )
.into(), ]
])
.spacing(10); .spacing(10);
let scroll_controls = row![ let scroll_controls = row![
@ -226,6 +224,7 @@ impl Application for ScrollableDemo {
.padding([40, 0, 40, 0]) .padding([40, 0, 40, 0])
.spacing(40), .spacing(40),
) )
.width(Length::Fill)
.height(Length::Fill) .height(Length::Fill)
.direction(scrollable::Direction::Vertical( .direction(scrollable::Direction::Vertical(
Properties::new() Properties::new()
@ -251,6 +250,7 @@ impl Application for ScrollableDemo {
.padding([0, 40, 0, 40]) .padding([0, 40, 0, 40])
.spacing(40), .spacing(40),
) )
.width(Length::Fill)
.height(Length::Fill) .height(Length::Fill)
.direction(scrollable::Direction::Horizontal( .direction(scrollable::Direction::Horizontal(
Properties::new() Properties::new()
@ -293,6 +293,7 @@ impl Application for ScrollableDemo {
.padding([0, 40, 0, 40]) .padding([0, 40, 0, 40])
.spacing(40), .spacing(40),
) )
.width(Length::Fill)
.height(Length::Fill) .height(Length::Fill)
.direction({ .direction({
let properties = Properties::new() let properties = Properties::new()
@ -333,19 +334,11 @@ impl Application for ScrollableDemo {
let content: Element<Message> = let content: Element<Message> =
column![scroll_controls, scrollable_content, progress_bars] column![scroll_controls, scrollable_content, progress_bars]
.height(Length::Fill)
.align_items(Alignment::Center) .align_items(Alignment::Center)
.spacing(10) .spacing(10)
.into(); .into();
Element::from( Element::from(container(content).padding(40).center_x().center_y())
container(content)
.width(Length::Fill)
.height(Length::Fill)
.padding(40)
.center_x()
.center_y(),
)
} }
fn theme(&self) -> Self::Theme { fn theme(&self) -> Self::Theme {

View file

@ -509,7 +509,6 @@ impl<'a> Step {
) )
}) })
.map(Element::from) .map(Element::from)
.collect()
) )
.spacing(10) .spacing(10)
] ]

View file

@ -3,7 +3,7 @@ mod echo;
use iced::alignment::{self, Alignment}; use iced::alignment::{self, Alignment};
use iced::executor; use iced::executor;
use iced::widget::{ use iced::widget::{
button, column, container, row, scrollable, text, text_input, Column, button, column, container, row, scrollable, text, text_input,
}; };
use iced::{ use iced::{
Application, Color, Command, Element, Length, Settings, Subscription, Theme, Application, Color, Command, Element, Length, Settings, Subscription, Theme,
@ -108,13 +108,8 @@ impl Application for WebSocket {
.into() .into()
} else { } else {
scrollable( scrollable(
Column::with_children( column(
self.messages self.messages.iter().cloned().map(text).map(Element::from),
.iter()
.cloned()
.map(text)
.map(Element::from)
.collect(),
) )
.spacing(10), .spacing(10),
) )

View file

@ -22,16 +22,12 @@ pub struct Column<'a, Message, Renderer = crate::Renderer> {
children: Vec<Element<'a, Message, Renderer>>, children: Vec<Element<'a, Message, Renderer>>,
} }
impl<'a, Message, Renderer> Column<'a, Message, Renderer> { impl<'a, Message, Renderer> Column<'a, Message, Renderer>
where
Renderer: crate::core::Renderer,
{
/// Creates an empty [`Column`]. /// Creates an empty [`Column`].
pub fn new() -> Self { pub fn new() -> Self {
Self::with_children(Vec::new())
}
/// Creates a [`Column`] with the given elements.
pub fn with_children(
children: Vec<Element<'a, Message, Renderer>>,
) -> Self {
Column { Column {
spacing: 0.0, spacing: 0.0,
padding: Padding::ZERO, padding: Padding::ZERO,
@ -39,10 +35,17 @@ impl<'a, Message, Renderer> Column<'a, Message, Renderer> {
height: Length::Shrink, height: Length::Shrink,
max_width: f32::INFINITY, max_width: f32::INFINITY,
align_items: Alignment::Start, align_items: Alignment::Start,
children, children: Vec::new(),
} }
} }
/// Creates a [`Column`] with the given elements.
pub fn with_children(
children: impl Iterator<Item = Element<'a, Message, Renderer>>,
) -> Self {
children.fold(Self::new(), |column, element| column.push(element))
}
/// Sets the vertical spacing _between_ elements. /// Sets the vertical spacing _between_ elements.
/// ///
/// Custom margins per element do not exist in iced. You should use this /// Custom margins per element do not exist in iced. You should use this
@ -88,12 +91,26 @@ impl<'a, Message, Renderer> Column<'a, Message, Renderer> {
mut self, mut self,
child: impl Into<Element<'a, Message, Renderer>>, child: impl Into<Element<'a, Message, Renderer>>,
) -> Self { ) -> Self {
self.children.push(child.into()); let child = child.into();
let size = child.as_widget().size_hint();
if size.width.is_fill() {
self.width = Length::Fill;
}
if size.height.is_fill() {
self.height = Length::Fill;
}
self.children.push(child);
self self
} }
} }
impl<'a, Message, Renderer> Default for Column<'a, Message, Renderer> { impl<'a, Message, Renderer> Default for Column<'a, Message, Renderer>
where
Renderer: crate::core::Renderer,
{
fn default() -> Self { fn default() -> Self {
Self::new() Self::new()
} }

View file

@ -46,11 +46,22 @@ where
where where
T: Into<Element<'a, Message, Renderer>>, T: Into<Element<'a, Message, Renderer>>,
{ {
let content = content.into();
let size = content.as_widget().size_hint();
Container { Container {
id: None, id: None,
padding: Padding::ZERO, padding: Padding::ZERO,
width: Length::Shrink, width: if size.width.is_fill() {
height: Length::Shrink, Length::Fill
} else {
Length::Shrink
},
height: if size.height.is_fill() {
Length::Fill
} else {
Length::Shrink
},
max_width: f32::INFINITY, max_width: f32::INFINITY,
max_height: f32::INFINITY, max_height: f32::INFINITY,
horizontal_alignment: alignment::Horizontal::Left, horizontal_alignment: alignment::Horizontal::Left,

View file

@ -34,7 +34,7 @@ macro_rules! column {
$crate::Column::new() $crate::Column::new()
); );
($($x:expr),+ $(,)?) => ( ($($x:expr),+ $(,)?) => (
$crate::Column::with_children(vec![$($crate::core::Element::from($x)),+]) $crate::Column::with_children([$($crate::core::Element::from($x)),+].into_iter())
); );
} }
@ -47,7 +47,7 @@ macro_rules! row {
$crate::Row::new() $crate::Row::new()
); );
($($x:expr),+ $(,)?) => ( ($($x:expr),+ $(,)?) => (
$crate::Row::with_children(vec![$($crate::core::Element::from($x)),+]) $crate::Row::with_children([$($crate::core::Element::from($x)),+].into_iter())
); );
} }
@ -65,9 +65,12 @@ where
} }
/// Creates a new [`Column`] with the given children. /// Creates a new [`Column`] with the given children.
pub fn column<Message, Renderer>( pub fn column<'a, Message, Renderer>(
children: Vec<Element<'_, Message, Renderer>>, children: impl Iterator<Item = Element<'a, Message, Renderer>>,
) -> Column<'_, Message, Renderer> { ) -> Column<'a, Message, Renderer>
where
Renderer: core::Renderer,
{
Column::with_children(children) Column::with_children(children)
} }
@ -84,9 +87,12 @@ where
/// Creates a new [`Row`] with the given children. /// Creates a new [`Row`] with the given children.
/// ///
/// [`Row`]: crate::Row /// [`Row`]: crate::Row
pub fn row<Message, Renderer>( pub fn row<'a, Message, Renderer>(
children: Vec<Element<'_, Message, Renderer>>, children: impl Iterator<Item = Element<'a, Message, Renderer>>,
) -> Row<'_, Message, Renderer> { ) -> Row<'a, Message, Renderer>
where
Renderer: core::Renderer,
{
Row::with_children(children) Row::with_children(children)
} }

View file

@ -150,6 +150,13 @@ where
self.with_element(|element| element.as_widget().height()) self.with_element(|element| element.as_widget().height())
} }
fn size_hint(&self) -> Size<Length> {
Size {
width: Length::Shrink,
height: Length::Shrink,
}
}
fn layout( fn layout(
&self, &self,
tree: &mut Tree, tree: &mut Tree,

View file

@ -252,6 +252,13 @@ where
self.with_element(|element| element.as_widget().height()) self.with_element(|element| element.as_widget().height())
} }
fn size_hint(&self) -> Size<Length> {
Size {
width: Length::Shrink,
height: Length::Shrink,
}
}
fn layout( fn layout(
&self, &self,
tree: &mut Tree, tree: &mut Tree,

View file

@ -21,26 +21,31 @@ pub struct Row<'a, Message, Renderer = crate::Renderer> {
children: Vec<Element<'a, Message, Renderer>>, children: Vec<Element<'a, Message, Renderer>>,
} }
impl<'a, Message, Renderer> Row<'a, Message, Renderer> { impl<'a, Message, Renderer> Row<'a, Message, Renderer>
where
Renderer: crate::core::Renderer,
{
/// Creates an empty [`Row`]. /// Creates an empty [`Row`].
pub fn new() -> Self { pub fn new() -> Self {
Self::with_children(Vec::new())
}
/// Creates a [`Row`] with the given elements.
pub fn with_children(
children: Vec<Element<'a, Message, Renderer>>,
) -> Self {
Row { Row {
spacing: 0.0, spacing: 0.0,
padding: Padding::ZERO, padding: Padding::ZERO,
width: Length::Shrink, width: Length::Shrink,
height: Length::Shrink, height: Length::Shrink,
align_items: Alignment::Start, align_items: Alignment::Start,
children, children: Vec::new(),
} }
} }
/// Creates a [`Row`] with the given elements.
pub fn with_children(
children: impl Iterator<Item = Element<'a, Message, Renderer>>,
) -> Self {
children
.into_iter()
.fold(Self::new(), |column, element| column.push(element))
}
/// Sets the horizontal spacing _between_ elements. /// Sets the horizontal spacing _between_ elements.
/// ///
/// Custom margins per element do not exist in iced. You should use this /// Custom margins per element do not exist in iced. You should use this
@ -80,12 +85,26 @@ impl<'a, Message, Renderer> Row<'a, Message, Renderer> {
mut self, mut self,
child: impl Into<Element<'a, Message, Renderer>>, child: impl Into<Element<'a, Message, Renderer>>,
) -> Self { ) -> Self {
self.children.push(child.into()); let child = child.into();
let size = child.as_widget().size_hint();
if size.width.is_fill() {
self.width = Length::Fill;
}
if size.height.is_fill() {
self.height = Length::Fill;
}
self.children.push(child);
self self
} }
} }
impl<'a, Message, Renderer> Default for Row<'a, Message, Renderer> { impl<'a, Message, Renderer> Default for Row<'a, Message, Renderer>
where
Renderer: crate::core::Renderer,
{
fn default() -> Self { fn default() -> Self {
Self::new() Self::new()
} }