2021-03-10 04:00:51 +00:00
|
|
|
use crate::{
|
2021-03-22 02:54:23 +00:00
|
|
|
geometry::vector::Vector2F, AfterLayoutContext, Element, ElementBox, Event, EventContext,
|
|
|
|
LayoutContext, PaintContext, SizeConstraint,
|
2021-03-10 04:00:51 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
pub struct EventHandler {
|
2021-03-22 02:54:23 +00:00
|
|
|
child: ElementBox,
|
|
|
|
mouse_down: Option<Box<dyn FnMut(&mut EventContext) -> bool>>,
|
2021-03-10 04:00:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl EventHandler {
|
2021-03-22 02:54:23 +00:00
|
|
|
pub fn new(child: ElementBox) -> Self {
|
2021-03-10 04:00:51 +00:00
|
|
|
Self {
|
|
|
|
child,
|
|
|
|
mouse_down: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn on_mouse_down<F>(mut self, callback: F) -> Self
|
|
|
|
where
|
2021-03-22 02:54:23 +00:00
|
|
|
F: 'static + FnMut(&mut EventContext) -> bool,
|
2021-03-10 04:00:51 +00:00
|
|
|
{
|
2021-03-22 02:54:23 +00:00
|
|
|
self.mouse_down = Some(Box::new(callback));
|
2021-03-10 04:00:51 +00:00
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Element for EventHandler {
|
2021-03-22 02:54:23 +00:00
|
|
|
type LayoutState = ();
|
|
|
|
type PaintState = ();
|
|
|
|
|
2021-03-10 04:00:51 +00:00
|
|
|
fn layout(
|
|
|
|
&mut self,
|
|
|
|
constraint: SizeConstraint,
|
|
|
|
ctx: &mut LayoutContext,
|
2021-03-22 02:54:23 +00:00
|
|
|
) -> (Vector2F, Self::LayoutState) {
|
|
|
|
let size = self.child.layout(constraint, ctx);
|
|
|
|
(size, ())
|
2021-03-10 04:00:51 +00:00
|
|
|
}
|
|
|
|
|
2021-03-22 02:54:23 +00:00
|
|
|
fn after_layout(
|
|
|
|
&mut self,
|
|
|
|
_: Vector2F,
|
|
|
|
_: &mut Self::LayoutState,
|
|
|
|
ctx: &mut AfterLayoutContext,
|
|
|
|
) {
|
|
|
|
self.child.after_layout(ctx);
|
2021-03-10 04:00:51 +00:00
|
|
|
}
|
|
|
|
|
2021-03-22 02:54:23 +00:00
|
|
|
fn paint(
|
|
|
|
&mut self,
|
|
|
|
bounds: pathfinder_geometry::rect::RectF,
|
|
|
|
_: &mut Self::LayoutState,
|
|
|
|
ctx: &mut PaintContext,
|
|
|
|
) -> Self::PaintState {
|
|
|
|
self.child.paint(bounds.origin(), ctx);
|
2021-03-10 04:00:51 +00:00
|
|
|
}
|
|
|
|
|
2021-03-22 02:54:23 +00:00
|
|
|
fn dispatch_event(
|
|
|
|
&mut self,
|
|
|
|
event: &Event,
|
|
|
|
bounds: pathfinder_geometry::rect::RectF,
|
|
|
|
_: &mut Self::LayoutState,
|
|
|
|
_: &mut Self::PaintState,
|
|
|
|
ctx: &mut EventContext,
|
|
|
|
) -> bool {
|
|
|
|
if self.child.dispatch_event(event, ctx) {
|
|
|
|
true
|
|
|
|
} else {
|
|
|
|
match event {
|
|
|
|
Event::LeftMouseDown { position, .. } => {
|
|
|
|
if let Some(callback) = self.mouse_down.as_mut() {
|
|
|
|
if bounds.contains_point(*position) {
|
|
|
|
return callback(ctx);
|
|
|
|
}
|
2021-03-10 04:00:51 +00:00
|
|
|
}
|
2021-03-22 02:54:23 +00:00
|
|
|
false
|
2021-03-10 04:00:51 +00:00
|
|
|
}
|
2021-03-22 02:54:23 +00:00
|
|
|
_ => false,
|
2021-03-10 04:00:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|