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 [
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
277pub 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
296pub 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
308pub 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
321fn 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
337fn 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
368fn 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 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 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 #[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 #[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 assert_eq!(missing_icons(&AppAssets::new(), &standard), Vec::<String>::new());
479 }
480}