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 icons every app uses for the same thing (Design System, "The frame"): a view that does the
29/// same job has the same icon in every app, and the shared workspaces have theirs. kitchen-ui
30/// always ships them ([`FrameIcons`]), so naming one needs nothing in the app's icon set.
31pub mod standard {
32    use gpui_kit::assets::IconName;
33
34    /// Explore: browse the data (a map).
35    pub const EXPLORE: IconName = IconName::Map;
36    /// Analysis: results in tables and figures (a table).
37    pub const ANALYSIS: IconName = IconName::Table;
38    /// Curation: go through items and accept or reject them (a checklist; not the home icon).
39    pub const CURATION: IconName = IconName::ListChecks;
40    /// Sorting: split a signal into its sources (spike sorting, cell separation).
41    pub const SORTING: IconName = IconName::Split;
42    /// The shared Pipeline workspace.
43    pub const PIPELINE: IconName = IconName::Workflow;
44    /// The shared Code workspace.
45    pub const CODE: IconName = IconName::CodeXml;
46    /// The Panels drawer of a narrow window (the side panes, folded away).
47    pub const PANELS: IconName = IconName::PanelsTopLeft;
48    /// The general menu (File, Edit, View, Help) of a narrow window.
49    pub const MENU: IconName = IconName::Menu;
50    /// File → Open… and the file picker's folders.
51    pub const OPEN: IconName = IconName::FolderOpen;
52    /// The theme switch.
53    pub const THEME: IconName = IconName::SunMoon;
54    /// File picker places: home, desktop, downloads, recent.
55    pub const HOME: IconName = IconName::House;
56    /// File picker place: the desktop.
57    pub const DESKTOP: IconName = IconName::Monitor;
58    /// File picker place: downloads.
59    pub const DOWNLOADS: IconName = IconName::Download;
60    /// File picker place: recent files.
61    pub const RECENT: IconName = IconName::Clock;
62    /// The file picker's "up one folder".
63    pub const UP: IconName = IconName::FolderUp;
64    /// A table file (CSV, Parquet) in the file picker.
65    pub const FILE_TABLE: IconName = IconName::FileSpreadsheet;
66    /// An image or video file in the file picker.
67    pub const FILE_IMAGE: IconName = IconName::FileImage;
68    /// A script in the file picker.
69    pub const FILE_CODE: IconName = IconName::FileCode;
70}
71
72mod frame_icons {
73    #![allow(missing_docs)]
74    gpui_kit::assets::icon_assets!(
75        pub FrameIcons,
76        [Map, Table, ListChecks, Split, Workflow, CodeXml, PanelsTopLeft, SunMoon, House, Monitor, Download, Clock, FolderUp, FileSpreadsheet, FileImage, FileCode]
77    );
78}
79
80/// The standard icons ([`standard`]) that gpui-kit's component set lacks; [`AppAssets`] always
81/// serves them.
82pub use frame_icons::FrameIcons;
83
84/// The assets an app ships: its own files (a logo), then the icon sets it adds, then gpui-kit's
85/// component icons (or the whole Lucide catalog, [`AppAssets::all_icons`]).
86#[derive(Default)]
87pub struct AppAssets {
88    files: Vec<(&'static str, &'static [u8])>,
89    extra: Vec<Box<dyn AssetSource>>,
90    all_icons: bool,
91}
92
93impl AppAssets {
94    /// gpui-kit's component icons alone.
95    pub fn new() -> Self {
96        Self::default()
97    }
98
99    /// Adds a set of icons (one made with `gpui_kit::assets::icon_assets!`), or any other source.
100    pub fn icons(mut self, source: impl AssetSource) -> Self {
101        self.extra.push(Box::new(source));
102        self
103    }
104
105    /// Adds a file served at `path` (for `img(path)`: a logo, a picture in the about dialog).
106    pub fn file(mut self, path: &'static str, bytes: &'static [u8]) -> Self {
107        self.files.push((path, bytes));
108        self
109    }
110
111    /// Ships the whole Lucide catalog instead of the component icons (a larger binary; for an app
112    /// that has not listed its icons yet).
113    pub fn all_icons(mut self) -> Self {
114        self.all_icons = true;
115        self
116    }
117
118    #[cfg(not(target_family = "wasm"))]
119    fn base(&self) -> &dyn AssetSource {
120        if self.all_icons { &gpui_kit::assets::AllAssets } else { &gpui_kit::assets::Assets }
121    }
122
123    /// In a browser gpui-kit's own source downloads each icon when it is first asked for and
124    /// reports an error until it arrives (every frame, for every icon); here the component icons
125    /// are embedded instead ([`ComponentIcons`]), as on the desktop. The whole catalog is not
126    /// offered there: list the icons the app adds.
127    #[cfg(target_family = "wasm")]
128    fn base(&self) -> &dyn AssetSource {
129        let _ = self.all_icons;
130        &ComponentIcons
131    }
132}
133
134// gpui-kit's component icons (its `default-icons.txt`, 0.9.1), embedded for the browser build.
135#[cfg(target_family = "wasm")]
136gpui_kit::assets::icon_assets!(
137    ComponentIcons,
138    [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]
139);
140
141impl AssetSource for AppAssets {
142    fn load(&self, path: &str) -> gpui_kit::Result<Option<Cow<'static, [u8]>>> {
143        if let Some((_, bytes)) = self.files.iter().find(|(p, _)| *p == path) {
144            return Ok(Some(Cow::Borrowed(bytes)));
145        }
146        for source in &self.extra {
147            if let Some(bytes) = source.load(path)? {
148                return Ok(Some(bytes));
149            }
150        }
151        if let Some(bytes) = FrameIcons.load(path)? {
152            return Ok(Some(bytes));
153        }
154        self.base().load(path)
155    }
156
157    fn list(&self, path: &str) -> gpui_kit::Result<Vec<SharedString>> {
158        let mut paths = self.base().list(path)?;
159        paths.extend(FrameIcons.list(path)?);
160        for source in &self.extra {
161            paths.extend(source.list(path)?);
162        }
163        paths.extend(self.files.iter().filter(|(p, _)| p.starts_with(path)).map(|(p, _)| SharedString::from(*p)));
164        paths.sort();
165        paths.dedup();
166        Ok(paths)
167    }
168}
169
170/// The names of the icons the Rust sources under `roots` name: `IconName::Server`, and the same
171/// through an alias (`use gpui_kit::assets::IconName as I;` then `I::Server`, or
172/// `type Icons = IconName;`). Aliases are collected from every file first, so an alias declared
173/// in one module and used in another is found too. Only real icon names are kept, so another
174/// type behind the same alias adds nothing. A glob import (`use IconName::*`) is not seen.
175pub fn icon_names_used(roots: &[impl AsRef<Path>]) -> BTreeSet<String> {
176    let texts: Vec<String> = rust_files(roots).iter().filter_map(|p| std::fs::read_to_string(p).ok()).collect();
177    let mut markers: BTreeSet<String> = BTreeSet::from(["IconName".to_string()]);
178    for text in &texts {
179        markers.extend(aliases_in(text));
180    }
181    let known: BTreeSet<String> = IconName::ALL.iter().map(|i| format!("{i:?}")).collect();
182    let mut used = BTreeSet::new();
183    for text in &texts {
184        used.extend(names_after(text, &markers).into_iter().filter(|n| known.contains(n)));
185    }
186    used
187}
188
189/// The icons named in `used` that `assets` cannot load.
190pub fn missing_icons(assets: &dyn AssetSource, used: &BTreeSet<String>) -> Vec<String> {
191    let mut missing = Vec::new();
192    for name in used {
193        let Some(icon) = IconName::ALL.iter().find(|i| format!("{i:?}") == *name) else { continue };
194        if assets.load(&icon.path()).ok().flatten().is_none() {
195            missing.push(name.clone());
196        }
197    }
198    missing
199}
200
201/// Panics unless every icon the sources under `roots` name is in `assets` (and at least one icon
202/// is found, so a wrong root fails instead of passing empty). For an app's test.
203pub fn assert_icons_bundled(assets: &dyn AssetSource, roots: &[impl AsRef<Path>]) {
204    let used = icon_names_used(roots);
205    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<_>>());
206    let missing = missing_icons(assets, &used);
207    assert!(missing.is_empty(), "icons used but not bundled (add them to the app's icon set): {missing:?}");
208}
209
210/// Every `.rs` file under `roots` (roots that do not exist are skipped).
211fn rust_files(roots: &[impl AsRef<Path>]) -> Vec<PathBuf> {
212    let mut out = Vec::new();
213    let mut stack: Vec<PathBuf> = roots.iter().map(|r| r.as_ref().to_path_buf()).collect();
214    while let Some(path) = stack.pop() {
215        if path.is_dir() {
216            let Ok(entries) = std::fs::read_dir(&path) else { continue };
217            stack.extend(entries.flatten().map(|e| e.path()));
218        } else if path.extension().is_some_and(|x| x == "rs") {
219            out.push(path);
220        }
221    }
222    out.sort();
223    out
224}
225
226/// Names `IconName` goes by in `text`: `IconName as I` (in a `use`, grouped or not) and
227/// `type I = …IconName;`.
228fn aliases_in(text: &str) -> Vec<String> {
229    let mut out = Vec::new();
230    for (at, _) in text.match_indices("IconName") {
231        let rest = text[at + "IconName".len()..].trim_start();
232        if let Some(after) = rest.strip_prefix("as") {
233            if after.starts_with(char::is_whitespace) {
234                let name = ident_at(after.trim_start());
235                if !name.is_empty() && name != "_" {
236                    out.push(name);
237                }
238            }
239        }
240    }
241    for (at, _) in text.match_indices("type ") {
242        if at > 0 && is_ident_char(text[..at].chars().next_back().unwrap_or(' ')) {
243            continue;
244        }
245        let rest = &text[at + 5..];
246        let name = ident_at(rest.trim_start());
247        let Some(eq) = rest.find('=') else { continue };
248        let Some(end) = rest[eq..].find(';') else { continue };
249        let target = rest[eq + 1..eq + end].trim();
250        if !name.is_empty() && (target == "IconName" || target.ends_with("::IconName")) {
251            out.push(name);
252        }
253    }
254    out
255}
256
257/// The capitalised names after `marker::` for each marker, where the marker is a whole word.
258fn names_after(text: &str, markers: &BTreeSet<String>) -> Vec<String> {
259    let mut out = Vec::new();
260    for m in markers {
261        let pat = format!("{m}::");
262        for (at, _) in text.match_indices(&pat) {
263            if text[..at].chars().next_back().is_some_and(is_ident_char) {
264                continue;
265            }
266            let name = ident_at(&text[at + pat.len()..]);
267            if name.starts_with(|c: char| c.is_ascii_uppercase()) {
268                out.push(name);
269            }
270        }
271    }
272    out
273}
274
275fn ident_at(s: &str) -> String {
276    s.chars().take_while(|c| is_ident_char(*c)).collect()
277}
278
279fn is_ident_char(c: char) -> bool {
280    c.is_ascii_alphanumeric() || c == '_'
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    fn markers(text: &str) -> BTreeSet<String> {
288        let mut m = BTreeSet::from(["IconName".to_string()]);
289        m.extend(aliases_in(text));
290        m
291    }
292
293    #[test]
294    fn finds_names_and_aliases() {
295        let text = r#"
296            use gpui_kit::assets::IconName as I;
297            use gpui_kit::{assets::{IconName as Lucide, Assets}, px};
298            type Icons = gpui_kit::assets::IconName;
299            fn f() { (IconName::Plus, I::Server, Lucide::Columns2, Icons::Flame, UI::Nope, I::new()) }
300        "#;
301        let m = markers(text);
302        assert_eq!(m, BTreeSet::from(["IconName", "I", "Lucide", "Icons"].map(String::from)));
303        let mut names = names_after(text, &m);
304        names.sort();
305        // `UI::Nope` is not `I::Nope`; `I::new` is not a name
306        assert_eq!(names, ["Columns2", "Flame", "Plus", "Server"]);
307    }
308
309    #[test]
310    fn an_alias_named_like_a_type_is_filtered_by_real_names() {
311        // dsp-kitchen aliases the enum as `Assets` while `Assets` is also gpui-kit's asset source
312        let text = "use gpui_kit::assets::IconName as Assets; let _ = (Assets::AppWindow, Assets::load);";
313        let names = names_after(text, &markers(text));
314        assert_eq!(names, ["AppWindow"]);
315    }
316
317    /// kitchen-ui's widgets name only icons gpui-kit's component set ships: the check run here as
318    /// an app runs it (over the widget sources; this file's test texts name icons on purpose).
319    #[test]
320    fn every_icon_used_is_bundled() {
321        let root = env!("CARGO_MANIFEST_DIR");
322        assert_icons_bundled(&AppAssets::new(), &[format!("{root}/src/widgets"), format!("{root}/src/param_editor.rs")]);
323    }
324
325    #[test]
326    fn a_missing_icon_is_reported() {
327        let used = BTreeSet::from(["Microscope".to_string(), "Plus".to_string()]);
328        assert_eq!(missing_icons(&AppAssets::new(), &used), ["Microscope"]);
329        gpui_kit::assets::icon_assets!(Extra, [Microscope]);
330        assert!(missing_icons(&AppAssets::new().icons(Extra), &used).is_empty());
331    }
332
333    /// The standard icons come with kitchen-ui: an app names them without adding them.
334    #[test]
335    fn the_standard_icons_are_always_shipped() {
336        let root = env!("CARGO_MANIFEST_DIR");
337        let used = icon_names_used(&[format!("{root}/src/icons.rs")]);
338        let standard: BTreeSet<String> = ["Map", "Table", "ListChecks", "Split", "Workflow", "CodeXml", "PanelsTopLeft", "Menu", "FolderOpen", "SunMoon", "House", "Monitor", "Download", "Clock", "FolderUp", "FileSpreadsheet", "FileImage", "FileCode"].map(String::from).into();
339        for name in &standard {
340            assert!(used.contains(name), "{name} is named in `standard`");
341        }
342        // (this file's own test texts name icons on purpose; only the standard ones are checked)
343        assert_eq!(missing_icons(&AppAssets::new(), &standard), Vec::<String>::new());
344    }
345}