Skip to main content

gpui/elements/
canvas.rs

1use refineable::Refineable as _;
2
3use crate::{
4    App, Bounds, Element, ElementId, GlobalElementId, InspectorElementId, IntoElement, Pixels,
5    Style, StyleRefinement, Styled, Window,
6};
7
8/// Creates a [`Canvas`] that draws with the painting methods on [`Window`].
9///
10/// Use it for custom drawing that doesn't need its own element type, such as a chart or a debug
11/// overlay. `prepaint` runs once the canvas's bounds are known, and returns a value. `paint` runs
12/// later in the same frame, with the same bounds and that value. Draw in `paint`, with calls such
13/// as [`Window::paint_quad`]. Use `prepaint` for work that needs the bounds, such as computing
14/// points from them.
15///
16/// The canvas has no content to size it, so give it a size with a [`Styled`] method, such as
17/// `.size_full()`. For a reusable drawing with its own state, implement [`Element`] instead.
18///
19/// # Example
20///
21/// ```
22/// use std::{cell::Cell, rc::Rc};
23///
24/// use gpui::{
25///     Context, IntoElement, PaintQuad, Point, Pixels, Render, TestApp, Window, canvas, point, prelude::*,
26///     px, rgb,
27/// };
28///
29/// struct Swatch {
30///     origin: Rc<Cell<Option<Point<Pixels>>>>,
31///     painted: Rc<Cell<bool>>,
32/// }
33///
34/// impl Render for Swatch {
35///     fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
36///         let origin = self.origin.clone();
37///         let painted = self.painted.clone();
38///         canvas(
39///             move |bounds, _window, _cx| origin.set(Some(bounds.origin)),
40///             move |bounds, _prepaint_result, window, _cx| {
41///                 window.paint_quad(PaintQuad::new(bounds).background(rgb(0x2563eb)));
42///                 painted.set(true);
43///             },
44///         )
45///         .size_full()
46///     }
47/// }
48///
49/// let origin = Rc::new(Cell::new(None));
50/// let painted = Rc::new(Cell::new(false));
51/// let mut app = TestApp::new();
52/// let mut window = app.open_window({
53///     let origin = origin.clone();
54///     let painted = painted.clone();
55///     move |_window, _cx| Swatch { origin, painted }
56/// });
57///
58/// window.draw();
59/// assert_eq!(origin.get(), Some(point(px(0.), px(0.))));
60/// assert!(painted.get());
61/// ```
62pub fn canvas<T>(
63    prepaint: impl 'static + FnOnce(Bounds<Pixels>, &mut Window, &mut App) -> T,
64    paint: impl 'static + FnOnce(Bounds<Pixels>, T, &mut Window, &mut App),
65) -> Canvas<T> {
66    Canvas {
67        prepaint: Some(Box::new(prepaint)),
68        paint: Some(Box::new(paint)),
69        style: StyleRefinement::default(),
70    }
71}
72
73/// An element that runs custom drawing code, created with [`canvas`].
74///
75/// Its two callbacks run once each, in the `prepaint` and `paint` phases of the frame that
76/// created it. Use a canvas when a callback is enough. Implement [`Element`] when the drawing needs
77/// its own state across frames.
78pub struct Canvas<T> {
79    prepaint: Option<Box<dyn FnOnce(Bounds<Pixels>, &mut Window, &mut App) -> T>>,
80    paint: Option<Box<dyn FnOnce(Bounds<Pixels>, T, &mut Window, &mut App)>>,
81    style: StyleRefinement,
82}
83
84impl<T: 'static> IntoElement for Canvas<T> {
85    type Element = Self;
86
87    fn into_element(self) -> Self::Element {
88        self
89    }
90}
91
92impl<T: 'static> Element for Canvas<T> {
93    type RequestLayoutState = Style;
94    type PrepaintState = Option<T>;
95
96    fn id(&self) -> Option<ElementId> {
97        None
98    }
99
100    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
101        None
102    }
103
104    fn request_layout(
105        &mut self,
106        _id: Option<&GlobalElementId>,
107        _inspector_id: Option<&InspectorElementId>,
108        window: &mut Window,
109        cx: &mut App,
110    ) -> (crate::LayoutId, Self::RequestLayoutState) {
111        let mut style = Style::default();
112        style.refine(&self.style);
113        let layout_id = window.request_layout(style.clone(), [], cx);
114        (layout_id, style)
115    }
116
117    fn prepaint(
118        &mut self,
119        _id: Option<&GlobalElementId>,
120        _inspector_id: Option<&InspectorElementId>,
121        bounds: Bounds<Pixels>,
122        _request_layout: &mut Style,
123        window: &mut Window,
124        cx: &mut App,
125    ) -> Option<T> {
126        Some(self.prepaint.take().unwrap()(bounds, window, cx))
127    }
128
129    fn paint(
130        &mut self,
131        _id: Option<&GlobalElementId>,
132        _inspector_id: Option<&InspectorElementId>,
133        bounds: Bounds<Pixels>,
134        style: &mut Style,
135        prepaint: &mut Self::PrepaintState,
136        window: &mut Window,
137        cx: &mut App,
138    ) {
139        let prepaint = prepaint.take().unwrap();
140        style.paint(bounds, window, cx, |window, cx| {
141            (self.paint.take().unwrap())(bounds, prepaint, window, cx)
142        });
143    }
144}
145
146impl<T> Styled for Canvas<T> {
147    fn style(&mut self) -> &mut crate::StyleRefinement {
148        &mut self.style
149    }
150}