Skip to main content

kitchen_ui/
icons.rs

1//! Icons: what an app ships ([`AppAssets`]: gpui-kit's component icons, the few Lucide icons the
2//! app adds, and its own files), and the check that every icon its code names is shipped
3//! ([`assert_icons_bundled`]): an icon missing from the assets draws nothing and logs an error.
4//!
5//! An app lists the icons it adds with gpui-kit's macro, so the binary carries those alone rather
6//! than the whole catalog:
7//!
8//! ```ignore
9//! gpui_kit::assets::icon_assets!(pub ExtraIcons, [AudioWaveform, Workflow, Microscope]);
10//!
11//! let assets = kitchen_ui::icons::AppAssets::new().icons(ExtraIcons).file(LOGO, LOGO_PNG);
12//! gpui_kit::application().with_assets(assets).run(|cx| { /* … */ });
13//!
14//! #[test]
15//! fn every_icon_used_is_bundled() {
16//!     let assets = kitchen_ui::icons::AppAssets::new().icons(ExtraIcons);
17//!     kitchen_ui::icons::assert_icons_bundled(&assets, &[concat!(env!("CARGO_MANIFEST_DIR"), "/src")]);
18//! }
19//! ```
20
21use std::borrow::Cow;
22use std::collections::BTreeSet;
23use std::path::{Path, PathBuf};
24
25use gpui_kit::assets::IconName;
26use gpui_kit::{AssetSource, SharedString};
27
28/// The assets an app ships: its own files (a logo), then the icon sets it adds, then gpui-kit's
29/// component icons (or the whole Lucide catalog, [`AppAssets::all_icons`]).
30#[derive(Default)]
31pub struct AppAssets {
32    files: Vec<(&'static str, &'static [u8])>,
33    extra: Vec<Box<dyn AssetSource>>,
34    all_icons: bool,
35}
36
37impl AppAssets {
38    /// gpui-kit's component icons alone.
39    pub fn new() -> Self {
40        Self::default()
41    }
42
43    /// Adds a set of icons (one made with `gpui_kit::assets::icon_assets!`), or any other source.
44    pub fn icons(mut self, source: impl AssetSource) -> Self {
45        self.extra.push(Box::new(source));
46        self
47    }
48
49    /// Adds a file served at `path` (for `img(path)`: a logo, a picture in the about dialog).
50    pub fn file(mut self, path: &'static str, bytes: &'static [u8]) -> Self {
51        self.files.push((path, bytes));
52        self
53    }
54
55    /// Ships the whole Lucide catalog instead of the component icons (a larger binary; for an app
56    /// that has not listed its icons yet).
57    pub fn all_icons(mut self) -> Self {
58        self.all_icons = true;
59        self
60    }
61
62    #[cfg(not(target_family = "wasm"))]
63    fn base(&self) -> &dyn AssetSource {
64        if self.all_icons { &gpui_kit::assets::AllAssets } else { &gpui_kit::assets::Assets }
65    }
66
67    /// In a browser gpui-kit's own source downloads each icon when it is first asked for and
68    /// reports an error until it arrives (every frame, for every icon); here the component icons
69    /// are embedded instead ([`ComponentIcons`]), as on the desktop. The whole catalog is not
70    /// offered there: list the icons the app adds.
71    #[cfg(target_family = "wasm")]
72    fn base(&self) -> &dyn AssetSource {
73        let _ = self.all_icons;
74        &ComponentIcons
75    }
76}
77
78// gpui-kit's component icons (its `default-icons.txt`, 0.9.1), embedded for the browser build.
79#[cfg(target_family = "wasm")]
80gpui_kit::assets::icon_assets!(
81    ComponentIcons,
82    [ALargeSmall, ArrowDown, ArrowLeft, ArrowRight, ArrowUp, Asterisk, Ban, BatteryCharging, BatteryFull, BatteryLow, BatteryMedium, BatteryWarning, Battery, Bell, BookOpen, Bot, Building2, Calendar, CaseSensitive, ChartPie, Check, ChevronDown, ChevronLeft, ChevronRight, ChevronUp, ChevronsUpDown, CircleAlert, CircleCheck, CircleUser, CircleX, Close, Copy, Cpu, Dash, Delete, EllipsisVertical, Ellipsis, ExternalLink, EyeOff, Eye, FileText, File, FolderClosed, FolderOpen, Folder, Frame, GalleryVerticalEnd, Github, Globe, HardDrive, HeartOff, Heart, Inbox, Info, Inspector, LayoutDashboard, LoaderCircle, Loader, Map, Maximize, MemoryStick, Menu, Mic, Minimize, Minus, Moon, Network, Palette, PanelBottomOpen, PanelBottom, PanelLeftClose, PanelLeftOpen, PanelLeft, PanelRightClose, PanelRightOpen, PanelRight, Pause, Play, Plus, Redo2, Redo, RefreshCw, Replace, ResizeCorner, RotateCw, Search, Settings2, Settings, SortAscending, SortDescending, SquareTerminal, Square, StarFill, StarOff, Star, Sun, ThumbsDown, ThumbsUp, TriangleAlert, Undo2, Undo, User, WindowClose, WindowMaximize, WindowMinimize, WindowRestore]
83);
84
85impl AssetSource for AppAssets {
86    fn load(&self, path: &str) -> gpui_kit::Result<Option<Cow<'static, [u8]>>> {
87        if let Some((_, bytes)) = self.files.iter().find(|(p, _)| *p == path) {
88            return Ok(Some(Cow::Borrowed(bytes)));
89        }
90        for source in &self.extra {
91            if let Some(bytes) = source.load(path)? {
92                return Ok(Some(bytes));
93            }
94        }
95        self.base().load(path)
96    }
97
98    fn list(&self, path: &str) -> gpui_kit::Result<Vec<SharedString>> {
99        let mut paths = self.base().list(path)?;
100        for source in &self.extra {
101            paths.extend(source.list(path)?);
102        }
103        paths.extend(self.files.iter().filter(|(p, _)| p.starts_with(path)).map(|(p, _)| SharedString::from(*p)));
104        paths.sort();
105        paths.dedup();
106        Ok(paths)
107    }
108}
109
110/// The names of the icons the Rust sources under `roots` name: `IconName::Server`, and the same
111/// through an alias (`use gpui_kit::assets::IconName as I;` then `I::Server`, or
112/// `type Icons = IconName;`). Aliases are collected from every file first, so an alias declared
113/// in one module and used in another is found too. Only real icon names are kept, so another
114/// type behind the same alias adds nothing. A glob import (`use IconName::*`) is not seen.
115pub fn icon_names_used(roots: &[impl AsRef<Path>]) -> BTreeSet<String> {
116    let texts: Vec<String> = rust_files(roots).iter().filter_map(|p| std::fs::read_to_string(p).ok()).collect();
117    let mut markers: BTreeSet<String> = BTreeSet::from(["IconName".to_string()]);
118    for text in &texts {
119        markers.extend(aliases_in(text));
120    }
121    let known: BTreeSet<String> = IconName::ALL.iter().map(|i| format!("{i:?}")).collect();
122    let mut used = BTreeSet::new();
123    for text in &texts {
124        used.extend(names_after(text, &markers).into_iter().filter(|n| known.contains(n)));
125    }
126    used
127}
128
129/// The icons named in `used` that `assets` cannot load.
130pub fn missing_icons(assets: &dyn AssetSource, used: &BTreeSet<String>) -> Vec<String> {
131    let mut missing = Vec::new();
132    for name in used {
133        let Some(icon) = IconName::ALL.iter().find(|i| format!("{i:?}") == *name) else { continue };
134        if assets.load(&icon.path()).ok().flatten().is_none() {
135            missing.push(name.clone());
136        }
137    }
138    missing
139}
140
141/// Panics unless every icon the sources under `roots` name is in `assets` (and at least one icon
142/// is found, so a wrong root fails instead of passing empty). For an app's test.
143pub fn assert_icons_bundled(assets: &dyn AssetSource, roots: &[impl AsRef<Path>]) {
144    let used = icon_names_used(roots);
145    assert!(!used.is_empty(), "no icons found in the sources: are the roots right? {:?}", roots.iter().map(|r| r.as_ref().display().to_string()).collect::<Vec<_>>());
146    let missing = missing_icons(assets, &used);
147    assert!(missing.is_empty(), "icons used but not bundled (add them to the app's icon set): {missing:?}");
148}
149
150/// Every `.rs` file under `roots` (roots that do not exist are skipped).
151fn rust_files(roots: &[impl AsRef<Path>]) -> Vec<PathBuf> {
152    let mut out = Vec::new();
153    let mut stack: Vec<PathBuf> = roots.iter().map(|r| r.as_ref().to_path_buf()).collect();
154    while let Some(path) = stack.pop() {
155        if path.is_dir() {
156            let Ok(entries) = std::fs::read_dir(&path) else { continue };
157            stack.extend(entries.flatten().map(|e| e.path()));
158        } else if path.extension().is_some_and(|x| x == "rs") {
159            out.push(path);
160        }
161    }
162    out.sort();
163    out
164}
165
166/// Names `IconName` goes by in `text`: `IconName as I` (in a `use`, grouped or not) and
167/// `type I = …IconName;`.
168fn aliases_in(text: &str) -> Vec<String> {
169    let mut out = Vec::new();
170    for (at, _) in text.match_indices("IconName") {
171        let rest = text[at + "IconName".len()..].trim_start();
172        if let Some(after) = rest.strip_prefix("as") {
173            if after.starts_with(char::is_whitespace) {
174                let name = ident_at(after.trim_start());
175                if !name.is_empty() && name != "_" {
176                    out.push(name);
177                }
178            }
179        }
180    }
181    for (at, _) in text.match_indices("type ") {
182        if at > 0 && is_ident_char(text[..at].chars().next_back().unwrap_or(' ')) {
183            continue;
184        }
185        let rest = &text[at + 5..];
186        let name = ident_at(rest.trim_start());
187        let Some(eq) = rest.find('=') else { continue };
188        let Some(end) = rest[eq..].find(';') else { continue };
189        let target = rest[eq + 1..eq + end].trim();
190        if !name.is_empty() && (target == "IconName" || target.ends_with("::IconName")) {
191            out.push(name);
192        }
193    }
194    out
195}
196
197/// The capitalised names after `marker::` for each marker, where the marker is a whole word.
198fn names_after(text: &str, markers: &BTreeSet<String>) -> Vec<String> {
199    let mut out = Vec::new();
200    for m in markers {
201        let pat = format!("{m}::");
202        for (at, _) in text.match_indices(&pat) {
203            if text[..at].chars().next_back().is_some_and(is_ident_char) {
204                continue;
205            }
206            let name = ident_at(&text[at + pat.len()..]);
207            if name.starts_with(|c: char| c.is_ascii_uppercase()) {
208                out.push(name);
209            }
210        }
211    }
212    out
213}
214
215fn ident_at(s: &str) -> String {
216    s.chars().take_while(|c| is_ident_char(*c)).collect()
217}
218
219fn is_ident_char(c: char) -> bool {
220    c.is_ascii_alphanumeric() || c == '_'
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    fn markers(text: &str) -> BTreeSet<String> {
228        let mut m = BTreeSet::from(["IconName".to_string()]);
229        m.extend(aliases_in(text));
230        m
231    }
232
233    #[test]
234    fn finds_names_and_aliases() {
235        let text = r#"
236            use gpui_kit::assets::IconName as I;
237            use gpui_kit::{assets::{IconName as Lucide, Assets}, px};
238            type Icons = gpui_kit::assets::IconName;
239            fn f() { (IconName::Plus, I::Server, Lucide::Columns2, Icons::Flame, UI::Nope, I::new()) }
240        "#;
241        let m = markers(text);
242        assert_eq!(m, BTreeSet::from(["IconName", "I", "Lucide", "Icons"].map(String::from)));
243        let mut names = names_after(text, &m);
244        names.sort();
245        // `UI::Nope` is not `I::Nope`; `I::new` is not a name
246        assert_eq!(names, ["Columns2", "Flame", "Plus", "Server"]);
247    }
248
249    #[test]
250    fn an_alias_named_like_a_type_is_filtered_by_real_names() {
251        // dsp-kitchen aliases the enum as `Assets` while `Assets` is also gpui-kit's asset source
252        let text = "use gpui_kit::assets::IconName as Assets; let _ = (Assets::AppWindow, Assets::load);";
253        let names = names_after(text, &markers(text));
254        assert_eq!(names, ["AppWindow"]);
255    }
256
257    /// kitchen-ui's widgets name only icons gpui-kit's component set ships: the check run here as
258    /// an app runs it (over the widget sources; this file's test texts name icons on purpose).
259    #[test]
260    fn every_icon_used_is_bundled() {
261        let root = env!("CARGO_MANIFEST_DIR");
262        assert_icons_bundled(&AppAssets::new(), &[format!("{root}/src/widgets"), format!("{root}/src/param_editor.rs")]);
263    }
264
265    #[test]
266    fn a_missing_icon_is_reported() {
267        let used = BTreeSet::from(["Microscope".to_string(), "Plus".to_string()]);
268        assert_eq!(missing_icons(&AppAssets::new(), &used), ["Microscope"]);
269        gpui_kit::assets::icon_assets!(Extra, [Microscope]);
270        assert!(missing_icons(&AppAssets::new().icons(Extra), &used).is_empty());
271    }
272}