Skip to main content

fc_ui/capabilities/media/
canvas_component.rs

1//! Direct GPUI painting surface with Styled support.
2
3use gpui::{prelude::FluentBuilder as _, *};
4use std::rc::Rc;
5
6type PaintCallback = Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App)>;
7type PrepareCallback = Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App)>;
8
9#[derive(IntoElement)]
10pub struct CanvasComponent {
11    id: ElementId,
12    on_paint: Option<PaintCallback>,
13    on_prepare: Option<PrepareCallback>,
14    style: StyleRefinement,
15}
16
17impl CanvasComponent {
18    pub fn new(id: impl Into<ElementId>) -> Self {
19        Self {
20            id: id.into(),
21            on_paint: None,
22            on_prepare: None,
23            style: StyleRefinement::default(),
24        }
25    }
26
27    pub fn on_paint(
28        mut self,
29        callback: impl Fn(Bounds<Pixels>, &mut Window, &mut App) + 'static,
30    ) -> Self {
31        self.on_paint = Some(Rc::new(callback));
32        self
33    }
34
35    pub fn on_prepare(
36        mut self,
37        callback: impl Fn(Bounds<Pixels>, &mut Window, &mut App) + 'static,
38    ) -> Self {
39        self.on_prepare = Some(Rc::new(callback));
40        self
41    }
42}
43
44impl Styled for CanvasComponent {
45    fn style(&mut self) -> &mut StyleRefinement {
46        &mut self.style
47    }
48}
49
50impl RenderOnce for CanvasComponent {
51    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
52        let user_style = self.style;
53        let paint_cb = self.on_paint;
54        let prepare_cb = self.on_prepare;
55
56        div()
57            .id(self.id)
58            .relative()
59            .child(
60                canvas(
61                    move |bounds, window, cx| {
62                        if let Some(ref cb) = prepare_cb {
63                            cb(bounds, window, cx);
64                        }
65                    },
66                    move |bounds, _, window, cx| {
67                        if let Some(ref cb) = paint_cb {
68                            cb(bounds, window, cx);
69                        }
70                    },
71                )
72                .absolute()
73                .inset_0()
74                .size_full(),
75            )
76            .map(|this| {
77                let mut el = this;
78                el.style().refine(&user_style);
79                el
80            })
81    }
82}