layout_context.rs

 1use crate::{element::LayoutId, style::Style};
 2use anyhow::{anyhow, Result};
 3use derive_more::{Deref, DerefMut};
 4use gpui::{geometry::Size, MeasureParams, RenderContext, ViewContext};
 5pub use gpui::{taffy::tree::NodeId, LayoutContext as LegacyLayoutContext};
 6
 7#[derive(Deref, DerefMut)]
 8pub struct LayoutContext<'a, 'b, 'c, 'd, V> {
 9    #[deref]
10    #[deref_mut]
11    pub(crate) legacy_cx: &'d mut LegacyLayoutContext<'a, 'b, 'c, V>,
12}
13
14impl<'a, 'b, V> RenderContext<'a, 'b, V> for LayoutContext<'a, 'b, '_, '_, V> {
15    fn text_style(&self) -> gpui::fonts::TextStyle {
16        self.legacy_cx.text_style()
17    }
18
19    fn push_text_style(&mut self, style: gpui::fonts::TextStyle) {
20        self.legacy_cx.push_text_style(style)
21    }
22
23    fn pop_text_style(&mut self) {
24        self.legacy_cx.pop_text_style()
25    }
26
27    fn as_view_context(&mut self) -> &mut ViewContext<'a, 'b, V> {
28        &mut self.view_context
29    }
30}
31
32impl<'a, 'b, 'c, 'd, V: 'static> LayoutContext<'a, 'b, 'c, 'd, V> {
33    pub fn new(legacy_cx: &'d mut LegacyLayoutContext<'a, 'b, 'c, V>) -> Self {
34        Self { legacy_cx }
35    }
36
37    pub fn add_layout_node(
38        &mut self,
39        style: Style,
40        children: impl IntoIterator<Item = NodeId>,
41    ) -> Result<LayoutId> {
42        let rem_size = self.rem_pixels();
43        let id = self
44            .legacy_cx
45            .layout_engine()
46            .ok_or_else(|| anyhow!("no layout engine"))?
47            .add_node(style.to_taffy(rem_size), children)?;
48
49        Ok(id)
50    }
51
52    pub fn add_measured_layout_node<F>(&mut self, style: Style, measure: F) -> Result<LayoutId>
53    where
54        F: Fn(MeasureParams) -> Size<f32> + Sync + Send + 'static,
55    {
56        let rem_size = self.rem_pixels();
57        let layout_id = self
58            .layout_engine()
59            .ok_or_else(|| anyhow!("no layout engine"))?
60            .add_measured_node(style.to_taffy(rem_size), measure)?;
61
62        Ok(layout_id)
63    }
64}