Overhaul the entire element system

Now the Element trait is designed to be wrapped in a Lifecycle enum that gets placed inside an ElementBox. This allows the framework to store data on behalf of the Element implementation, such as sizes, bounds, and also implementation-specific LayoutState and PaintState types. This makes it easier to reason about which data is available in each Element method.
This commit is contained in:
Nathan Sobo
2021-03-21 20:54:23 -06:00
parent 046fe3fff9
commit 119aa452b6
27 changed files with 931 additions and 642 deletions
+35 -23
View File
@@ -1,65 +1,77 @@
use crate::{
geometry::vector::Vector2F, AfterLayoutContext, AppContext, Element, Event, EventContext,
LayoutContext, MutableAppContext, PaintContext, SizeConstraint,
geometry::vector::Vector2F, AfterLayoutContext, Element, ElementBox, Event, EventContext,
LayoutContext, PaintContext, SizeConstraint,
};
pub struct Stack {
children: Vec<Box<dyn Element>>,
size: Option<Vector2F>,
children: Vec<ElementBox>,
}
impl Stack {
pub fn new() -> Self {
Stack {
children: Vec::new(),
size: None,
}
}
}
impl Element for Stack {
type LayoutState = ();
type PaintState = ();
fn layout(
&mut self,
constraint: SizeConstraint,
ctx: &mut LayoutContext,
app: &AppContext,
) -> Vector2F {
) -> (Vector2F, Self::LayoutState) {
let mut size = constraint.min;
for child in &mut self.children {
size = size.max(child.layout(constraint, ctx, app));
size = size.max(child.layout(constraint, ctx));
}
self.size = Some(size);
size
(size, ())
}
fn after_layout(&mut self, ctx: &mut AfterLayoutContext, app: &mut MutableAppContext) {
fn after_layout(
&mut self,
_: Vector2F,
_: &mut Self::LayoutState,
ctx: &mut AfterLayoutContext,
) {
for child in &mut self.children {
child.after_layout(ctx, app);
child.after_layout(ctx);
}
}
fn paint(&mut self, origin: Vector2F, ctx: &mut PaintContext, app: &AppContext) {
fn paint(
&mut self,
bounds: pathfinder_geometry::rect::RectF,
_: &mut Self::LayoutState,
ctx: &mut PaintContext,
) -> Self::PaintState {
for child in &mut self.children {
child.paint(origin, ctx, app);
child.paint(bounds.origin(), ctx);
}
}
fn dispatch_event(&self, event: &Event, ctx: &mut EventContext, app: &AppContext) -> bool {
for child in self.children.iter().rev() {
if child.dispatch_event(event, ctx, app) {
fn dispatch_event(
&mut self,
event: &Event,
_: pathfinder_geometry::rect::RectF,
_: &mut Self::LayoutState,
_: &mut Self::PaintState,
ctx: &mut EventContext,
) -> bool {
for child in self.children.iter_mut().rev() {
if child.dispatch_event(event, ctx) {
return true;
}
}
false
}
fn size(&self) -> Option<Vector2F> {
self.size
}
}
impl Extend<Box<dyn Element>> for Stack {
fn extend<T: IntoIterator<Item = Box<dyn Element>>>(&mut self, children: T) {
impl Extend<ElementBox> for Stack {
fn extend<T: IntoIterator<Item = ElementBox>>(&mut self, children: T) {
self.children.extend(children)
}
}