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