1use std::borrow::Cow;
22use std::collections::BTreeSet;
23use std::path::{Path, PathBuf};
24
25use gpui_kit::assets::IconName;
26use gpui_kit::{AssetSource, SharedString};
27
28pub mod standard {
32 use gpui_kit::assets::IconName;
33
34 pub const EXPLORE: IconName = IconName::Map;
36 pub const ANALYSIS: IconName = IconName::Table;
38 pub const CURATION: IconName = IconName::ListChecks;
40 pub const SORTING: IconName = IconName::Split;
42 pub const PIPELINE: IconName = IconName::Workflow;
44 pub const CODE: IconName = IconName::CodeXml;
46 pub const PANELS: IconName = IconName::PanelsTopLeft;
48 pub const MENU: IconName = IconName::Menu;
50 pub const OPEN: IconName = IconName::FolderOpen;
52 pub const THEME: IconName = IconName::SunMoon;
54 pub const HOME: IconName = IconName::House;
56 pub const DESKTOP: IconName = IconName::Monitor;
58 pub const DOWNLOADS: IconName = IconName::Download;
60 pub const RECENT: IconName = IconName::Clock;
62 pub const UP: IconName = IconName::FolderUp;
64 pub const FILE_TABLE: IconName = IconName::FileSpreadsheet;
66 pub const FILE_IMAGE: IconName = IconName::FileImage;
68 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
80pub use frame_icons::FrameIcons;
83
84#[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 pub fn new() -> Self {
96 Self::default()
97 }
98
99 pub fn icons(mut self, source: impl AssetSource) -> Self {
101 self.extra.push(Box::new(source));
102 self
103 }
104
105 pub fn file(mut self, path: &'static str, bytes: &'static [u8]) -> Self {
107 self.files.push((path, bytes));
108 self
109 }
110
111 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 #[cfg(target_family = "wasm")]
128 fn base(&self) -> &dyn AssetSource {
129 let _ = self.all_icons;
130 &ComponentIcons
131 }
132}
133
134#[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
170pub 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
189pub 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
201pub 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
210fn 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
226fn 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
257fn 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 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 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 #[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 #[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 assert_eq!(missing_icons(&AppAssets::new(), &standard), Vec::<String>::new());
344 }
345}