paint_context.rs

 1use anyhow::{anyhow, Result};
 2use derive_more::{Deref, DerefMut};
 3pub use gpui::taffy::tree::NodeId;
 4use gpui::{
 5    scene::EventHandler, EventContext, Layout, LayoutId, PaintContext as LegacyPaintContext,
 6};
 7use std::{any::TypeId, rc::Rc};
 8
 9#[derive(Deref, DerefMut)]
10pub struct PaintContext<'a, 'b, 'c, 'd, V> {
11    #[deref]
12    #[deref_mut]
13    pub(crate) legacy_cx: &'d mut LegacyPaintContext<'a, 'b, 'c, V>,
14    pub(crate) scene: &'d mut gpui::SceneBuilder,
15}
16
17impl<'a, 'b, 'c, 'd, V: 'static> PaintContext<'a, 'b, 'c, 'd, V> {
18    pub fn new(
19        legacy_cx: &'d mut LegacyPaintContext<'a, 'b, 'c, V>,
20        scene: &'d mut gpui::SceneBuilder,
21    ) -> Self {
22        Self { legacy_cx, scene }
23    }
24
25    pub fn on_event<E: 'static>(
26        &mut self,
27        order: u32,
28        handler: impl Fn(&mut V, &E, &mut EventContext<V>) + 'static,
29    ) {
30        let view = self.weak_handle();
31
32        self.scene.event_handlers.push(EventHandler {
33            order,
34            handler: Rc::new(move |event, window_cx| {
35                if let Some(view) = view.upgrade(window_cx) {
36                    view.update(window_cx, |view, view_cx| {
37                        let mut event_cx = EventContext::new(view_cx);
38                        handler(view, event.downcast_ref().unwrap(), &mut event_cx);
39                        event_cx.bubble
40                    })
41                } else {
42                    true
43                }
44            }),
45            event_type: TypeId::of::<E>(),
46        })
47    }
48
49    pub(crate) fn computed_layout(&mut self, layout_id: LayoutId) -> Result<Layout> {
50        self.layout_engine()
51            .ok_or_else(|| anyhow!("no layout engine present"))?
52            .computed_layout(layout_id)
53    }
54}