Skip to main content

gpui_component/
icon.rs

1use std::{rc::Rc, sync::Arc};
2
3use crate::{ActiveTheme, Sizable, Size};
4use gpui::{
5    AnyElement, App, AppContext, Context, Entity, Global, Hsla, IntoElement, Pixels, Radians,
6    Render, RenderOnce, SharedString, StyleRefinement, Styled, Svg, Transformation, Window,
7    prelude::FluentBuilder as _, svg,
8};
9pub use gpui_kit_assets::IconNamed;
10
11// Preserve the original enum (including exhaustive matches and inherent view)
12// while the complete, shared catalog is owned by gpui-kit-assets.
13macro_rules! component_icon_names {
14    ($($name:ident => $path:literal,)*) => {
15        /// Default component icon names, retained for source compatibility.
16        /// For the complete Lucide catalog, use `gpui_kit_assets::IconName`.
17        #[derive(Clone, IntoElement)]
18        pub enum IconName {
19            $($name,)*
20        }
21
22        impl From<IconName> for gpui_kit_assets::IconName {
23            fn from(name: IconName) -> Self {
24                match name {
25                    $(IconName::$name => Self::$name,)*
26                }
27            }
28        }
29
30        impl IconNamed for IconName {
31            fn path(self) -> SharedString {
32                match self { $(Self::$name => $path,)* }.into()
33            }
34        }
35    };
36}
37
38gpui_kit_assets::__component_icon_names!(component_icon_names);
39
40impl IconName {
41    /// Return the icon as an Entity<Icon>.
42    pub fn view(self, cx: &mut App) -> Entity<Icon> {
43        Icon::build(self).view(cx)
44    }
45}
46
47impl From<IconName> for AnyElement {
48    fn from(name: IconName) -> Self {
49        Icon::build(name).into_any_element()
50    }
51}
52
53impl RenderOnce for IconName {
54    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
55        Icon::build(self)
56    }
57}
58
59impl<T: IconNamed> From<T> for Icon {
60    fn from(value: T) -> Self {
61        Icon::build(value)
62    }
63}
64
65/// Component view construction for the shared `gpui_kit_assets::IconName`.
66/// The legacy component `IconName` retains its inherent `view` method.
67pub trait IconNameExt {
68    fn view(self, cx: &mut App) -> Entity<Icon>;
69}
70
71impl IconNameExt for gpui_kit_assets::IconName {
72    fn view(self, cx: &mut App) -> Entity<Icon> {
73        Icon::build(self).view(cx)
74    }
75}
76
77struct IconResolver(Rc<dyn Fn(&str, &App) -> Option<SharedString>>);
78
79impl Global for IconResolver {}
80
81/// Set the hook every [`Icon`] drawn from an asset path asks for the path to draw,
82/// including the icons components draw inside their own controls.
83///
84/// The resolver receives the icon's path (for example `icons/check.svg`) and returns
85/// the path to draw in its place, or `None` to keep it. GPUI caches a rendered SVG by
86/// its path, so returning a new path is how an application switches icon styles at
87/// runtime; the application's [`gpui::AssetSource`] must load the returned path.
88/// Icons created with [`Icon::data`] are not resolved.
89///
90/// The resolver runs every time an icon is drawn and should be cheap. Call
91/// [`App::refresh_windows`] after changing what it returns.
92pub fn set_icon_resolver(
93    cx: &mut App,
94    resolver: impl Fn(&str, &App) -> Option<SharedString> + 'static,
95) {
96    cx.set_global(IconResolver(Rc::new(resolver)));
97}
98
99/// Return the path to draw for the icon at `path`: the answer of the resolver set with
100/// [`set_icon_resolver`], or `path` itself.
101pub fn resolve_icon_path(path: SharedString, cx: &App) -> SharedString {
102    match cx.try_global::<IconResolver>() {
103        Some(resolver) if !path.is_empty() => (resolver.0)(&path, cx).unwrap_or(path),
104        _ => path,
105    }
106}
107
108/// Warn once per path when the application's asset source cannot load an icon.
109///
110/// GPUI draws nothing for an SVG path its asset source does not resolve, and does
111/// not log it, so a missing `.with_assets(gpui_kit::assets::Assets)` or an
112/// incomplete custom source otherwise shows up as blank space. The check runs only
113/// for icons that are actually drawn, so applications that draw no icons never pay
114/// for it or see it, and only in debug builds, so release rendering is unchanged.
115#[cfg(debug_assertions)]
116fn warn_missing_icon(path: &SharedString, cx: &App) {
117    use std::{cell::RefCell, collections::HashSet};
118
119    thread_local! {
120        static CHECKED: RefCell<HashSet<SharedString>> = RefCell::default();
121    }
122
123    if path.is_empty() || !CHECKED.with(|checked| checked.borrow_mut().insert(path.clone())) {
124        return;
125    }
126    if let Ok(None) = cx.asset_source().load(path) {
127        tracing::warn!(
128            "icon `{path}` renders blank: the asset source does not load it. \
129             Add `.with_assets(gpui_kit::assets::Assets)` to `gpui_kit::application()`, \
130             or make your own `AssetSource` serve this path."
131        );
132    }
133}
134
135#[derive(Clone)]
136pub(crate) enum IconSource {
137    Path(SharedString),
138    Data(Arc<[u8]>),
139}
140
141#[derive(Clone, IntoElement)]
142pub struct Icon {
143    style: StyleRefinement,
144    source: IconSource,
145    text_color: Option<Hsla>,
146    size: Option<Size>,
147    transformation: Option<Transformation>,
148}
149
150impl Default for Icon {
151    fn default() -> Self {
152        Self {
153            style: StyleRefinement::default(),
154            source: IconSource::Path("".into()),
155            text_color: None,
156            size: None,
157            transformation: None,
158        }
159    }
160}
161
162impl Icon {
163    pub fn new(icon: impl Into<Icon>) -> Self {
164        icon.into()
165    }
166
167    fn build(name: impl IconNamed) -> Self {
168        Self::default().path(name.path())
169    }
170
171    /// Set the icon path of the Assets bundle
172    ///
173    /// For example: `icons/foo.svg`
174    /// Replaces any previously set path or SVG data.
175    pub fn path(mut self, path: impl Into<SharedString>) -> Self {
176        self.source = IconSource::Path(path.into());
177        self
178    }
179
180    /// Set raw SVG bytes without registering an asset path.
181    ///
182    /// Copies the bytes into shared storage; the input need not be static.
183    /// Cloning the icon shares those bytes. Replaces any previously set path or data.
184    /// Parsing and rendering follow GPUI's SVG behavior.
185    ///
186    /// ```
187    /// use gpui_component::Icon;
188    ///
189    /// let bytes = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
190    ///     <path d="M4 12h16" stroke="currentColor"/>
191    /// </svg>"#;
192    /// let icon = Icon::default().data(bytes);
193    /// ```
194    pub fn data(mut self, data: &[u8]) -> Self {
195        self.source = IconSource::Data(Arc::from(data));
196        self
197    }
198
199    #[cfg(any(target_os = "macos", target_os = "windows", test))]
200    pub(crate) fn source_ref(&self) -> &IconSource {
201        &self.source
202    }
203
204    /// Whether `other` takes up exactly the same space as this icon. The
205    /// source, color and transformation change only what it paints.
206    pub(crate) fn same_layout(&self, other: &Self) -> bool {
207        self.style == other.style && self.size == other.size
208    }
209
210    /// Create a new view for the icon
211    pub fn view(self, cx: &mut App) -> Entity<Icon> {
212        cx.new(|_| self)
213    }
214
215    /// Set the SVG transformation, replacing any previous transformation or rotation.
216    pub fn transform(mut self, transformation: gpui::Transformation) -> Self {
217        self.transformation = Some(transformation);
218        self
219    }
220
221    pub fn empty() -> Self {
222        Self::default()
223    }
224
225    /// Rotate the icon by the given angle
226    ///
227    /// Replaces any previous transformation or rotation.
228    pub fn rotate(mut self, radians: impl Into<Radians>) -> Self {
229        self.transformation = Some(Transformation::rotate(radians));
230        self
231    }
232
233    fn resolved(mut self, cx: &App) -> Self {
234        if let IconSource::Path(path) = self.source {
235            let path = resolve_icon_path(path, cx);
236            #[cfg(debug_assertions)]
237            warn_missing_icon(&path, cx);
238            self.source = IconSource::Path(path);
239        }
240        self
241    }
242
243    fn into_svg(self, text_size: Pixels, fallback_color: Hsla) -> Svg {
244        let text_color = self.text_color.unwrap_or(fallback_color);
245        let has_base_size = self.style.size.width.is_some() || self.style.size.height.is_some();
246
247        svg()
248            .map(|mut this| {
249                *this.style() = self.style;
250                this
251            })
252            .flex_shrink_0()
253            .text_color(text_color)
254            .when(!has_base_size, |this| this.size(text_size))
255            .when_some(self.size, |this, size| match size {
256                Size::Size(px) => this.size(px),
257                Size::XSmall => this.size_3(),
258                Size::Small => this.size_3p5(),
259                Size::Medium => this.size_4(),
260                Size::Large => this.size_6(),
261            })
262            .map(|this| match self.source {
263                IconSource::Path(path) => this.path(path),
264                IconSource::Data(data) => this.data(&data),
265            })
266            .when_some(self.transformation, |this, transformation| {
267                this.with_transformation(transformation)
268            })
269    }
270}
271
272impl Styled for Icon {
273    fn style(&mut self) -> &mut StyleRefinement {
274        &mut self.style
275    }
276
277    fn text_color(mut self, color: impl Into<Hsla>) -> Self {
278        self.text_color = Some(color.into());
279        self
280    }
281}
282
283impl Sizable for Icon {
284    fn with_size(mut self, size: impl Into<Size>) -> Self {
285        self.size = Some(size.into());
286        self
287    }
288}
289
290impl RenderOnce for Icon {
291    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
292        let text_size = window.text_style().font_size.to_pixels(window.rem_size());
293        self.resolved(cx)
294            .into_svg(text_size, window.text_style().color)
295    }
296}
297
298impl From<Icon> for AnyElement {
299    fn from(val: Icon) -> Self {
300        val.into_any_element()
301    }
302}
303
304impl Render for Icon {
305    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
306        let text_size = window.text_style().font_size.to_pixels(window.rem_size());
307        self.clone()
308            .resolved(cx)
309            .into_svg(text_size, cx.theme().foreground)
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316    use gpui::{px, size};
317
318    const SVG: &[u8] = include_bytes!("../../assets/assets/icons/arrow-up.svg");
319
320    #[test]
321    fn test_icon_builder_preserves_owned_data_and_transform_on_clone() {
322        let transformation = Transformation::scale(size(0.5, 0.5))
323            .with_rotation(gpui::radians(std::f32::consts::FRAC_PI_2));
324        let icon = {
325            let bytes = SVG.to_vec();
326            Icon::default()
327                .data(&bytes)
328                .large()
329                .text_color(gpui::red())
330                .transform(transformation)
331        };
332        let cloned = icon.clone();
333        let (IconSource::Data(original), IconSource::Data(copy)) = (&icon.source, &cloned.source)
334        else {
335            panic!("cloning must preserve the data source");
336        };
337        assert_eq!(copy.as_ref(), SVG);
338        assert!(Arc::ptr_eq(original, copy));
339        assert_eq!(cloned.transformation, Some(transformation));
340        assert_eq!(cloned.size, icon.size);
341        assert_eq!(cloned.text_color, icon.text_color);
342
343        let mut svg = cloned.into_svg(px(12.), gpui::blue());
344        assert_eq!(svg.style().text.color, Some(gpui::red()));
345        assert_eq!(svg.style().size.width, Some(gpui::rems(1.5).into()));
346
347        let rotated = icon.rotate(gpui::radians(std::f32::consts::PI));
348        assert_eq!(
349            rotated.transformation,
350            Some(Transformation::rotate(gpui::radians(std::f32::consts::PI)))
351        );
352    }
353
354    #[test]
355    fn test_icon_source_builders_replace_previous_source() {
356        let icon = Icon::new(IconName::Search).data(SVG);
357        assert!(matches!(icon.source_ref(), IconSource::Data(bytes) if bytes.as_ref() == SVG));
358
359        let icon = icon.path("icons/replacement.svg");
360        assert!(
361            matches!(icon.source_ref(), IconSource::Path(path) if path == "icons/replacement.svg")
362        );
363
364        let icon = icon.data(SVG).data(b"replacement");
365        assert!(
366            matches!(icon.source_ref(), IconSource::Data(bytes) if bytes.as_ref() == b"replacement")
367        );
368
369        let icon = icon.path("");
370        assert!(matches!(icon.source_ref(), IconSource::Path(path) if path.is_empty()));
371    }
372
373    #[gpui::test]
374    fn test_icon_resolver_replaces_the_path_to_draw(cx: &mut gpui::TestAppContext) {
375        fn drawn_path(icon: Icon, cx: &App) -> SharedString {
376            match icon.resolved(cx).source {
377                IconSource::Path(path) => path,
378                IconSource::Data(_) => panic!("resolving must keep the source type"),
379            }
380        }
381
382        cx.update(|cx| {
383            let search = IconName::Search.path();
384            assert_eq!(drawn_path(Icon::new(IconName::Search), cx), search);
385
386            let asked = Rc::new(std::cell::RefCell::new(Vec::<String>::new()));
387            set_icon_resolver(cx, {
388                let asked = asked.clone();
389                let search = search.clone();
390                move |path, _| {
391                    asked.borrow_mut().push(path.to_string());
392                    (path == search.as_ref()).then(|| "icons/alt/search.svg".into())
393                }
394            });
395
396            assert_eq!(
397                drawn_path(Icon::new(IconName::Search), cx),
398                "icons/alt/search.svg"
399            );
400            assert_eq!(
401                drawn_path(Icon::new(IconName::Check), cx),
402                IconName::Check.path()
403            );
404            assert_eq!(drawn_path(Icon::empty(), cx), "");
405            assert!(matches!(
406                Icon::default().data(SVG).resolved(cx).source,
407                IconSource::Data(_)
408            ));
409            assert_eq!(
410                *asked.borrow(),
411                [search.to_string(), IconName::Check.path().to_string()]
412            );
413        });
414    }
415}