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}
15
16impl<'a, 'b, 'c, 'd, V: 'static> PaintContext<'a, 'b, 'c, 'd, V> {
17    pub fn new(legacy_cx: &'d mut LegacyPaintContext<'a, 'b, 'c, V>) -> Self {
18        Self { legacy_cx }
19    }
20
21    pub fn on_event<E: 'static>(
22        &mut self,
23        order: u32,
24        handler: impl Fn(&mut V, &E, &mut EventContext<V>) + 'static,
25    ) {
26        let view = self.weak_handle();
27
28        self.scene().event_handlers.push(EventHandler {
29            order,
30            handler: Rc::new(move |event, window_cx| {
31                if let Some(view) = view.upgrade(window_cx) {
32                    view.update(window_cx, |view, view_cx| {
33                        let mut event_cx = EventContext::new(view_cx);
34                        handler(view, event.downcast_ref().unwrap(), &mut event_cx);
35                        event_cx.bubble
36                    })
37                } else {
38                    true
39                }
40            }),
41            event_type: TypeId::of::<E>(),
42        })
43    }
44
45    pub(crate) fn computed_layout(&mut self, layout_id: LayoutId) -> Result<Layout> {
46        self.layout_engine()
47            .ok_or_else(|| anyhow!("no layout engine present"))?
48            .computed_layout(layout_id)
49    }
50}