Skip to main content

gpui/elements/
canvas.rs

1use refineable::Refineable as _;
2
3use crate::{
4    App, Bounds, Element, ElementId, GlobalElementId, InspectorElementId, Pixels, Style,
5    StyleRefinement, Styled, Window,
6};
7
8/// Construct a canvas element with the given paint callback.
9/// Useful for adding short term custom drawing to a view.
10pub fn canvas<T>(
11    prepaint: impl 'static + FnOnce(Bounds<Pixels>, &mut Window, &mut App) -> T,
12    paint: impl 'static + FnOnce(Bounds<Pixels>, T, &mut Window, &mut App),
13) -> Canvas<T> {
14    Canvas {
15        prepaint: Some(Box::new(prepaint)),
16        paint: Some(Box::new(paint)),
17        style: StyleRefinement::default(),
18    }
19}
20
21/// A canvas element, meant for accessing the low level paint API without defining a whole
22/// custom element
23pub struct Canvas<T> {
24    prepaint: Option<Box<dyn FnOnce(Bounds<Pixels>, &mut Window, &mut App) -> T>>,
25    paint: Option<Box<dyn FnOnce(Bounds<Pixels>, T, &mut Window, &mut App)>>,
26    style: StyleRefinement,
27}
28
29impl<T: 'static> Element for Canvas<T> {
30    type RequestLayoutState = Style;
31    type PrepaintState = Option<T>;
32
33    fn id(&self) -> Option<ElementId> {
34        None
35    }
36
37    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
38        None
39    }
40
41    fn request_layout(
42        &mut self,
43        _id: Option<&GlobalElementId>,
44        _inspector_id: Option<&InspectorElementId>,
45        window: &mut Window,
46        cx: &mut App,
47    ) -> (crate::LayoutId, Self::RequestLayoutState) {
48        let mut style = Style::default();
49        style.refine(&self.style);
50        let layout_id = window.request_layout(style.clone(), [], cx);
51        (layout_id, style)
52    }
53
54    fn prepaint(
55        &mut self,
56        _id: Option<&GlobalElementId>,
57        _inspector_id: Option<&InspectorElementId>,
58        bounds: Bounds<Pixels>,
59        _request_layout: &mut Style,
60        window: &mut Window,
61        cx: &mut App,
62    ) -> Option<T> {
63        Some(self.prepaint.take().unwrap()(bounds, window, cx))
64    }
65
66    fn paint(
67        &mut self,
68        _id: Option<&GlobalElementId>,
69        _inspector_id: Option<&InspectorElementId>,
70        bounds: Bounds<Pixels>,
71        style: &mut Style,
72        prepaint: &mut Self::PrepaintState,
73        window: &mut Window,
74        cx: &mut App,
75    ) {
76        let prepaint = prepaint.take().unwrap();
77        style.paint(bounds, window, cx, |window, cx| {
78            (self.paint.take().unwrap())(bounds, prepaint, window, cx)
79        });
80    }
81}
82
83impl<T> Styled for Canvas<T> {
84    fn style(&mut self) -> &mut crate::StyleRefinement {
85        &mut self.style
86    }
87}