theme.rs

  1use gpui2::{
  2    AnyElement, Bounds, Element, Hsla, IntoAnyElement, LayoutId, Pixels, Result, ViewContext,
  3    WindowContext,
  4};
  5use serde::{de::Visitor, Deserialize, Deserializer};
  6use std::collections::HashMap;
  7use std::fmt;
  8use std::sync::Arc;
  9
 10#[derive(Deserialize, Clone, Default, Debug)]
 11pub struct Theme {
 12    pub name: String,
 13    pub is_light: bool,
 14    pub lowest: Layer,
 15    pub middle: Layer,
 16    pub highest: Layer,
 17    pub popover_shadow: Shadow,
 18    pub modal_shadow: Shadow,
 19    #[serde(deserialize_with = "deserialize_player_colors")]
 20    pub players: Vec<PlayerColors>,
 21    #[serde(deserialize_with = "deserialize_syntax_colors")]
 22    pub syntax: HashMap<String, Hsla>,
 23}
 24
 25#[derive(Deserialize, Clone, Default, Debug)]
 26pub struct Layer {
 27    pub base: StyleSet,
 28    pub variant: StyleSet,
 29    pub on: StyleSet,
 30    pub accent: StyleSet,
 31    pub positive: StyleSet,
 32    pub warning: StyleSet,
 33    pub negative: StyleSet,
 34}
 35
 36#[derive(Deserialize, Clone, Default, Debug)]
 37pub struct StyleSet {
 38    #[serde(rename = "default")]
 39    pub default: ContainerColors,
 40    pub hovered: ContainerColors,
 41    pub pressed: ContainerColors,
 42    pub active: ContainerColors,
 43    pub disabled: ContainerColors,
 44    pub inverted: ContainerColors,
 45}
 46
 47#[derive(Deserialize, Clone, Default, Debug)]
 48pub struct ContainerColors {
 49    pub background: Hsla,
 50    pub foreground: Hsla,
 51    pub border: Hsla,
 52}
 53
 54#[derive(Deserialize, Clone, Default, Debug)]
 55pub struct PlayerColors {
 56    pub selection: Hsla,
 57    pub cursor: Hsla,
 58}
 59
 60#[derive(Deserialize, Clone, Default, Debug)]
 61pub struct Shadow {
 62    pub blur: u8,
 63    pub color: Hsla,
 64    pub offset: Vec<u8>,
 65}
 66
 67fn deserialize_player_colors<'de, D>(deserializer: D) -> Result<Vec<PlayerColors>, D::Error>
 68where
 69    D: Deserializer<'de>,
 70{
 71    struct PlayerArrayVisitor;
 72
 73    impl<'de> Visitor<'de> for PlayerArrayVisitor {
 74        type Value = Vec<PlayerColors>;
 75
 76        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 77            formatter.write_str("an object with integer keys")
 78        }
 79
 80        fn visit_map<A: serde::de::MapAccess<'de>>(
 81            self,
 82            mut map: A,
 83        ) -> Result<Self::Value, A::Error> {
 84            let mut players = Vec::with_capacity(8);
 85            while let Some((key, value)) = map.next_entry::<usize, PlayerColors>()? {
 86                if key < 8 {
 87                    players.push(value);
 88                } else {
 89                    return Err(serde::de::Error::invalid_value(
 90                        serde::de::Unexpected::Unsigned(key as u64),
 91                        &"a key in range 0..7",
 92                    ));
 93                }
 94            }
 95            Ok(players)
 96        }
 97    }
 98
 99    deserializer.deserialize_map(PlayerArrayVisitor)
100}
101
102fn deserialize_syntax_colors<'de, D>(deserializer: D) -> Result<HashMap<String, Hsla>, D::Error>
103where
104    D: serde::Deserializer<'de>,
105{
106    #[derive(Deserialize)]
107    struct ColorWrapper {
108        color: Hsla,
109    }
110
111    struct SyntaxVisitor;
112
113    impl<'de> Visitor<'de> for SyntaxVisitor {
114        type Value = HashMap<String, Hsla>;
115
116        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
117            formatter.write_str("a map with keys and objects with a single color field as values")
118        }
119
120        fn visit_map<M>(self, mut map: M) -> Result<HashMap<String, Hsla>, M::Error>
121        where
122            M: serde::de::MapAccess<'de>,
123        {
124            let mut result = HashMap::new();
125            while let Some(key) = map.next_key()? {
126                let wrapper: ColorWrapper = map.next_value()?; // Deserialize values as Hsla
127                result.insert(key, wrapper.color);
128            }
129            Ok(result)
130        }
131    }
132    deserializer.deserialize_map(SyntaxVisitor)
133}
134
135pub fn themed<E, F>(theme: Theme, cx: &mut ViewContext<E::ViewState>, build_child: F) -> Themed<E>
136where
137    E: Element,
138    F: FnOnce(&mut ViewContext<E::ViewState>) -> E,
139{
140    cx.default_global_mut::<ThemeStack>().0.push(theme.clone());
141    let child = build_child(cx);
142    cx.default_global_mut::<ThemeStack>().0.pop();
143    Themed { theme, child }
144}
145
146pub struct Themed<E> {
147    pub(crate) theme: Theme,
148    pub(crate) child: E,
149}
150
151impl<E> IntoAnyElement<E::ViewState> for Themed<E>
152where
153    E: Element,
154{
155    fn into_any(self) -> AnyElement<E::ViewState> {
156        AnyElement::new(self)
157    }
158}
159
160#[derive(Default)]
161struct ThemeStack(Vec<Theme>);
162
163impl<E: Element> Element for Themed<E> {
164    type ViewState = E::ViewState;
165    type ElementState = E::ElementState;
166
167    fn id(&self) -> Option<gpui2::ElementId> {
168        None
169    }
170
171    fn initialize(
172        &mut self,
173        view_state: &mut Self::ViewState,
174        element_state: Option<Self::ElementState>,
175        cx: &mut ViewContext<Self::ViewState>,
176    ) -> Self::ElementState {
177        cx.default_global_mut::<ThemeStack>()
178            .0
179            .push(self.theme.clone());
180        let element_state = self.child.initialize(view_state, element_state, cx);
181        cx.default_global_mut::<ThemeStack>().0.pop();
182        element_state
183    }
184
185    fn layout(
186        &mut self,
187        view_state: &mut E::ViewState,
188        element_state: &mut Self::ElementState,
189        cx: &mut ViewContext<E::ViewState>,
190    ) -> LayoutId
191    where
192        Self: Sized,
193    {
194        cx.default_global_mut::<ThemeStack>()
195            .0
196            .push(self.theme.clone());
197        let layout_id = self.child.layout(view_state, element_state, cx);
198        cx.default_global_mut::<ThemeStack>().0.pop();
199        layout_id
200    }
201
202    fn paint(
203        &mut self,
204        bounds: Bounds<Pixels>,
205        view_state: &mut Self::ViewState,
206        frame_state: &mut Self::ElementState,
207        cx: &mut ViewContext<Self::ViewState>,
208    ) where
209        Self: Sized,
210    {
211        cx.default_global_mut::<ThemeStack>()
212            .0
213            .push(self.theme.clone());
214        self.child.paint(bounds, view_state, frame_state, cx);
215        cx.default_global_mut::<ThemeStack>().0.pop();
216    }
217}
218
219pub fn theme(cx: &WindowContext) -> Arc<Theme> {
220    Arc::new(cx.global::<Theme>().clone())
221}