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 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
83pub use frame_icons::FrameIcons;
86
87#[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 pub fn new() -> Self {
99 Self::default()
100 }
101
102 pub fn icons(mut self, source: impl AssetSource) -> Self {
104 self.extra.push(Box::new(source));
105 self
106 }
107
108 pub fn file(mut self, path: &'static str, bytes: &'static [u8]) -> Self {
110 self.files.push((path, bytes));
111 self
112 }
113
114 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 #[cfg(target_family = "wasm")]
131 fn base(&self) -> &dyn AssetSource {
132 let _ = self.all_icons;
133 &ComponentIcons
134 }
135}
136
137#[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
280pub 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
299pub 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
311pub 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
324fn 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
340fn 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
371fn 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 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 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 #[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 #[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 assert_eq!(missing_icons(&AppAssets::new(), &standard), Vec::<String>::new());
482 }
483}