canvas.rs

 1use super::Element;
 2use crate::{
 3    json::{self, json},
 4    DebugContext, PaintContext,
 5};
 6use json::ToJson;
 7use pathfinder_geometry::{
 8    rect::RectF,
 9    vector::{vec2f, Vector2F},
10};
11
12pub struct Canvas<F>(F)
13where
14    F: FnMut(RectF, &mut PaintContext);
15
16impl<F> Canvas<F>
17where
18    F: FnMut(RectF, &mut PaintContext),
19{
20    pub fn new(f: F) -> Self {
21        Self(f)
22    }
23}
24
25impl<F> Element for Canvas<F>
26where
27    F: FnMut(RectF, &mut PaintContext),
28{
29    type LayoutState = ();
30    type PaintState = ();
31
32    fn layout(
33        &mut self,
34        constraint: crate::SizeConstraint,
35        _: &mut crate::LayoutContext,
36    ) -> (Vector2F, Self::LayoutState) {
37        let x = if constraint.max.x().is_finite() {
38            constraint.max.x()
39        } else {
40            constraint.min.x()
41        };
42        let y = if constraint.max.y().is_finite() {
43            constraint.max.y()
44        } else {
45            constraint.min.y()
46        };
47        (vec2f(x, y), ())
48    }
49
50    fn paint(
51        &mut self,
52        bounds: RectF,
53        _: &mut Self::LayoutState,
54        cx: &mut PaintContext,
55    ) -> Self::PaintState {
56        self.0(bounds, cx)
57    }
58
59    fn dispatch_event(
60        &mut self,
61        _: &crate::Event,
62        _: RectF,
63        _: &mut Self::LayoutState,
64        _: &mut Self::PaintState,
65        _: &mut crate::EventContext,
66    ) -> bool {
67        false
68    }
69
70    fn debug(
71        &self,
72        bounds: RectF,
73        _: &Self::LayoutState,
74        _: &Self::PaintState,
75        _: &DebugContext,
76    ) -> json::Value {
77        json!({"type": "Canvas", "bounds": bounds.to_json()})
78    }
79}