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         // The Pipeline workspace (kitchen-pipeline) and the table (kitchen-ui's table)
78         LogIn, LogOut, Copy, Trash, Eye, EyeOff, ZoomIn, ZoomOut, Maximize, Grip, MousePointer2, Hand, Play, Package, PanelRight, Unlink, RotateCcw, Undo2, Redo2, TriangleAlert, ChevronUp, FilePlus, FileText, Save, SquareTerminal, ExternalLink, GitCompare, Folder, PanelLeft, Check,
79         Layers, BookOpen, Cpu, PanelTop, PanelBottom, ChevronRight, ChevronDown]
80    );
81}
82
83/// The standard icons ([`standard`]) that gpui-kit's component set lacks; [`AppAssets`] always
84/// serves them.
85pub use frame_icons::FrameIcons;
86
87/// The assets an app ships: its own files (a logo), then the icon sets it adds, then gpui-kit's
88/// component icons (or the whole Lucide catalog, [`AppAssets::all_icons`]).
89#[derive(Default)]
90pub struct AppAssets {
91    files: Vec<(&'static str, &'static [u8])>,
92    extra: Vec<Box<dyn AssetSource>>,
93    all_icons: bool,
94}
95
96impl AppAssets {
97    /// gpui-kit's component icons alone.
98    pub fn new() -> Self {
99        Self::default()
100    }
101
102    /// Adds a set of icons (one made with `gpui_kit::assets::icon_assets!`), or any other source.
103    pub fn icons(mut self, source: impl AssetSource) -> Self {
104        self.extra.push(Box::new(source));
105        self
106    }
107
108    /// Adds a file served at `path` (for `img(path)`: a logo, a picture in the about dialog).
109    pub fn file(mut self, path: &'static str, bytes: &'static [u8]) -> Self {
110        self.files.push((path, bytes));
111        self
112    }
113
114    /// Ships the whole Lucide catalog instead of the component icons (a larger binary; for an app
115    /// that has not listed its icons yet).
116    pub fn all_icons(mut self) -> Self {
117        self.all_icons = true;
118        self
119    }
120
121    #[cfg(not(target_family = "wasm"))]
122    fn base(&self) -> &dyn AssetSource {
123        if self.all_icons { &gpui_kit::assets::AllAssets } else { &gpui_kit::assets::Assets }
124    }
125
126    /// In a browser gpui-kit's own source downloads each icon when it is first asked for and
127    /// reports an error until it arrives (every frame, for every icon); here the component icons
128    /// are embedded instead ([`ComponentIcons`]), as on the desktop. The whole catalog is not
129    /// offered there: list the icons the app adds.
130    #[cfg(target_family = "wasm")]
131    fn base(&self) -> &dyn AssetSource {
132        let _ = self.all_icons;
133        &ComponentIcons
134    }
135}
136
137// gpui-kit's component icons (its `default-icons.txt`, 0.9.1), embedded for the browser build.
138#[cfg(target_family = "wasm")]
139gpui_kit::assets::icon_assets!(
140    ComponentIcons,
141    [
142        ALargeSmall,
143        ArrowDown,
144        ArrowLeft,
145        ArrowRight,
146        ArrowUp,
147        Asterisk,
148        Ban,
149        BatteryCharging,
150        BatteryFull,
151        BatteryLow,
152        BatteryMedium,
153        BatteryWarning,
154        Battery,
155        Bell,
156        BookOpen,
157        Bot,
158        Building2,
159        Calendar,
160        CaseSensitive,
161        ChartPie,
162        Check,
163        ChevronDown,
164        ChevronLeft,
165        ChevronRight,
166        ChevronUp,
167        ChevronsUpDown,
168        CircleAlert,
169        CircleCheck,
170        CircleUser,
171        CircleX,
172        Close,
173        Copy,
174        Cpu,
175        Dash,
176        Delete,
177        EllipsisVertical,
178        Ellipsis,
179        ExternalLink,
180        EyeOff,
181        Eye,
182        FileText,
183        File,
184        FolderClosed,
185        FolderOpen,
186        Folder,
187        Frame,
188        GalleryVerticalEnd,
189        Github,
190        Globe,
191        HardDrive,
192        HeartOff,
193        Heart,
194        Inbox,
195        Info,
196        Inspector,
197        LayoutDashboard,
198        LoaderCircle,
199        Loader,
200        Map,
201        Maximize,
202        MemoryStick,
203        Menu,
204        Mic,
205        Minimize,
206        Minus,
207        Moon,
208        Network,
209        Palette,
210        PanelBottomOpen,
211        PanelBottom,
212        PanelLeftClose,
213        PanelLeftOpen,
214        PanelLeft,
215        PanelRightClose,
216        PanelRightOpen,
217        PanelRight,
218        Pause,
219        Play,
220        Plus,
221        Redo2,
222        Redo,
223        RefreshCw,
224        Replace,
225        ResizeCorner,
226        RotateCw,
227        Search,
228        Settings2,
229        Settings,
230        SortAscending,
231        SortDescending,
232        SquareTerminal,
233        Square,
234        StarFill,
235        StarOff,
236        Star,
237        Sun,
238        ThumbsDown,
239        ThumbsUp,
240        TriangleAlert,
241        Undo2,
242        Undo,
243        User,
244        WindowClose,
245        WindowMaximize,
246        WindowMinimize,
247        WindowRestore
248    ]
249);
250
251impl AssetSource for AppAssets {
252    fn load(&self, path: &str) -> gpui_kit::Result<Option<Cow<'static, [u8]>>> {
253        if let Some((_, bytes)) = self.files.iter().find(|(p, _)| *p == path) {
254            return Ok(Some(Cow::Borrowed(bytes)));
255        }
256        for source in &self.extra {
257            if let Some(bytes) = source.load(path)? {
258                return Ok(Some(bytes));
259            }
260        }
261        if let Some(bytes) = FrameIcons.load(path)? {
262            return Ok(Some(bytes));
263        }
264        self.base().load(path)
265    }
266
267    fn list(&self, path: &str) -> gpui_kit::Result<Vec<SharedString>> {
268        let mut paths = self.base().list(path)?;
269        paths.extend(FrameIcons.list(path)?);
270        for source in &self.extra {
271            paths.extend(source.list(path)?);
272        }
273        paths.extend(self.files.iter().filter(|(p, _)| p.starts_with(path)).map(|(p, _)| SharedString::from(*p)));
274        paths.sort();
275        paths.dedup();
276        Ok(paths)
277    }
278}
279
280/// The names of the icons the Rust sources under `roots` name: `IconName::Server`, and the same
281/// through an alias (`use gpui_kit::assets::IconName as I;` then `I::Server`, or
282/// `type Icons = IconName;`). Aliases are collected from every file first, so an alias declared
283/// in one module and used in another is found too. Only real icon names are kept, so another
284/// type behind the same alias adds nothing. A glob import (`use IconName::*`) is not seen.
285pub fn icon_names_used(roots: &[impl AsRef<Path>]) -> BTreeSet<String> {
286    let texts: Vec<String> = rust_files(roots).iter().filter_map(|p| std::fs::read_to_string(p).ok()).collect();
287    let mut markers: BTreeSet<String> = BTreeSet::from(["IconName".to_string()]);
288    for text in &texts {
289        markers.extend(aliases_in(text));
290    }
291    let known: BTreeSet<String> = IconName::ALL.iter().map(|i| format!("{i:?}")).collect();
292    let mut used = BTreeSet::new();
293    for text in &texts {
294        used.extend(names_after(text, &markers).into_iter().filter(|n| known.contains(n)));
295    }
296    used
297}
298
299/// The icons named in `used` that `assets` cannot load.
300pub fn missing_icons(assets: &dyn AssetSource, used: &BTreeSet<String>) -> Vec<String> {
301    let mut missing = Vec::new();
302    for name in used {
303        let Some(icon) = IconName::ALL.iter().find(|i| format!("{i:?}") == *name) else { continue };
304        if assets.load(&icon.path()).ok().flatten().is_none() {
305            missing.push(name.clone());
306        }
307    }
308    missing
309}
310
311/// Panics unless every icon the sources under `roots` name is in `assets` (and at least one icon
312/// is found, so a wrong root fails instead of passing empty). For an app's test.
313pub fn assert_icons_bundled(assets: &dyn AssetSource, roots: &[impl AsRef<Path>]) {
314    let used = icon_names_used(roots);
315    assert!(
316        !used.is_empty(),
317        "no icons found in the sources: are the roots right? {:?}",
318        roots.iter().map(|r| r.as_ref().display().to_string()).collect::<Vec<_>>()
319    );
320    let missing = missing_icons(assets, &used);
321    assert!(missing.is_empty(), "icons used but not bundled (add them to the app's icon set): {missing:?}");
322}
323
324/// Every `.rs` file under `roots` (roots that do not exist are skipped).
325fn rust_files(roots: &[impl AsRef<Path>]) -> Vec<PathBuf> {
326    let mut out = Vec::new();
327    let mut stack: Vec<PathBuf> = roots.iter().map(|r| r.as_ref().to_path_buf()).collect();
328    while let Some(path) = stack.pop() {
329        if path.is_dir() {
330            let Ok(entries) = std::fs::read_dir(&path) else { continue };
331            stack.extend(entries.flatten().map(|e| e.path()));
332        } else if path.extension().is_some_and(|x| x == "rs") {
333            out.push(path);
334        }
335    }
336    out.sort();
337    out
338}
339
340/// Names `IconName` goes by in `text`: `IconName as I` (in a `use`, grouped or not) and
341/// `type I = …IconName;`.
342fn aliases_in(text: &str) -> Vec<String> {
343    let mut out = Vec::new();
344    for (at, _) in text.match_indices("IconName") {
345        let rest = text[at + "IconName".len()..].trim_start();
346        if let Some(after) = rest.strip_prefix("as")
347            && after.starts_with(char::is_whitespace)
348        {
349            let name = ident_at(after.trim_start());
350            if !name.is_empty() && name != "_" {
351                out.push(name);
352            }
353        }
354    }
355    for (at, _) in text.match_indices("type ") {
356        if at > 0 && is_ident_char(text[..at].chars().next_back().unwrap_or(' ')) {
357            continue;
358        }
359        let rest = &text[at + 5..];
360        let name = ident_at(rest.trim_start());
361        let Some(eq) = rest.find('=') else { continue };
362        let Some(end) = rest[eq..].find(';') else { continue };
363        let target = rest[eq + 1..eq + end].trim();
364        if !name.is_empty() && (target == "IconName" || target.ends_with("::IconName")) {
365            out.push(name);
366        }
367    }
368    out
369}
370
371/// The capitalised names after `marker::` for each marker, where the marker is a whole word.
372fn names_after(text: &str, markers: &BTreeSet<String>) -> Vec<String> {
373    let mut out = Vec::new();
374    for m in markers {
375        let pat = format!("{m}::");
376        for (at, _) in text.match_indices(&pat) {
377            if text[..at].chars().next_back().is_some_and(is_ident_char) {
378                continue;
379            }
380            let name = ident_at(&text[at + pat.len()..]);
381            if name.starts_with(|c: char| c.is_ascii_uppercase()) {
382                out.push(name);
383            }
384        }
385    }
386    out
387}
388
389fn ident_at(s: &str) -> String {
390    s.chars().take_while(|c| is_ident_char(*c)).collect()
391}
392
393fn is_ident_char(c: char) -> bool {
394    c.is_ascii_alphanumeric() || c == '_'
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400
401    fn markers(text: &str) -> BTreeSet<String> {
402        let mut m = BTreeSet::from(["IconName".to_string()]);
403        m.extend(aliases_in(text));
404        m
405    }
406
407    #[test]
408    fn finds_names_and_aliases() {
409        let text = r#"
410            use gpui_kit::assets::IconName as I;
411            use gpui_kit::{assets::{IconName as Lucide, Assets}, px};
412            type Icons = gpui_kit::assets::IconName;
413            fn f() { (IconName::Plus, I::Server, Lucide::Columns2, Icons::Flame, UI::Nope, I::new()) }
414        "#;
415        let m = markers(text);
416        assert_eq!(m, BTreeSet::from(["IconName", "I", "Lucide", "Icons"].map(String::from)));
417        let mut names = names_after(text, &m);
418        names.sort();
419        // `UI::Nope` is not `I::Nope`; `I::new` is not a name
420        assert_eq!(names, ["Columns2", "Flame", "Plus", "Server"]);
421    }
422
423    #[test]
424    fn an_alias_named_like_a_type_is_filtered_by_real_names() {
425        // dsp-kitchen aliases the enum as `Assets` while `Assets` is also gpui-kit's asset source
426        let text = "use gpui_kit::assets::IconName as Assets; let _ = (Assets::AppWindow, Assets::load);";
427        let names = names_after(text, &markers(text));
428        assert_eq!(names, ["AppWindow"]);
429    }
430
431    /// kitchen-ui's widgets name only icons gpui-kit's component set ships: the check run here as
432    /// an app runs it (over the widget sources; this file's test texts name icons on purpose).
433    #[test]
434    fn every_icon_used_is_bundled() {
435        let root = env!("CARGO_MANIFEST_DIR");
436        assert_icons_bundled(
437            &AppAssets::new(),
438            &[format!("{root}/src/widgets"), format!("{root}/src/param_editor.rs")],
439        );
440    }
441
442    #[test]
443    fn a_missing_icon_is_reported() {
444        let used = BTreeSet::from(["Microscope".to_string(), "Plus".to_string()]);
445        assert_eq!(missing_icons(&AppAssets::new(), &used), ["Microscope"]);
446        gpui_kit::assets::icon_assets!(Extra, [Microscope]);
447        assert!(missing_icons(&AppAssets::new().icons(Extra), &used).is_empty());
448    }
449
450    /// The standard icons come with kitchen-ui: an app names them without adding them.
451    #[test]
452    fn the_standard_icons_are_always_shipped() {
453        let root = env!("CARGO_MANIFEST_DIR");
454        let used = icon_names_used(&[format!("{root}/src/icons.rs")]);
455        let standard: BTreeSet<String> = [
456            "Map",
457            "Table",
458            "ListChecks",
459            "Split",
460            "Workflow",
461            "CodeXml",
462            "PanelsTopLeft",
463            "Menu",
464            "FolderOpen",
465            "SunMoon",
466            "House",
467            "Monitor",
468            "Download",
469            "Clock",
470            "FolderUp",
471            "FileSpreadsheet",
472            "FileImage",
473            "FileCode",
474        ]
475        .map(String::from)
476        .into();
477        for name in &standard {
478            assert!(used.contains(name), "{name} is named in `standard`");
479        }
480        // (this file's own test texts name icons on purpose; only the standard ones are checked)
481        assert_eq!(missing_icons(&AppAssets::new(), &standard), Vec::<String>::new());
482    }
483}