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
28#[derive(Default)]
31pub struct AppAssets {
32 files: Vec<(&'static str, &'static [u8])>,
33 extra: Vec<Box<dyn AssetSource>>,
34 all_icons: bool,
35}
36
37impl AppAssets {
38 pub fn new() -> Self {
40 Self::default()
41 }
42
43 pub fn icons(mut self, source: impl AssetSource) -> Self {
45 self.extra.push(Box::new(source));
46 self
47 }
48
49 pub fn file(mut self, path: &'static str, bytes: &'static [u8]) -> Self {
51 self.files.push((path, bytes));
52 self
53 }
54
55 pub fn all_icons(mut self) -> Self {
58 self.all_icons = true;
59 self
60 }
61
62 #[cfg(not(target_family = "wasm"))]
63 fn base(&self) -> &dyn AssetSource {
64 if self.all_icons { &gpui_kit::assets::AllAssets } else { &gpui_kit::assets::Assets }
65 }
66
67 #[cfg(target_family = "wasm")]
72 fn base(&self) -> &dyn AssetSource {
73 let _ = self.all_icons;
74 &ComponentIcons
75 }
76}
77
78#[cfg(target_family = "wasm")]
80gpui_kit::assets::icon_assets!(
81 ComponentIcons,
82 [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]
83);
84
85impl AssetSource for AppAssets {
86 fn load(&self, path: &str) -> gpui_kit::Result<Option<Cow<'static, [u8]>>> {
87 if let Some((_, bytes)) = self.files.iter().find(|(p, _)| *p == path) {
88 return Ok(Some(Cow::Borrowed(bytes)));
89 }
90 for source in &self.extra {
91 if let Some(bytes) = source.load(path)? {
92 return Ok(Some(bytes));
93 }
94 }
95 self.base().load(path)
96 }
97
98 fn list(&self, path: &str) -> gpui_kit::Result<Vec<SharedString>> {
99 let mut paths = self.base().list(path)?;
100 for source in &self.extra {
101 paths.extend(source.list(path)?);
102 }
103 paths.extend(self.files.iter().filter(|(p, _)| p.starts_with(path)).map(|(p, _)| SharedString::from(*p)));
104 paths.sort();
105 paths.dedup();
106 Ok(paths)
107 }
108}
109
110pub fn icon_names_used(roots: &[impl AsRef<Path>]) -> BTreeSet<String> {
116 let texts: Vec<String> = rust_files(roots).iter().filter_map(|p| std::fs::read_to_string(p).ok()).collect();
117 let mut markers: BTreeSet<String> = BTreeSet::from(["IconName".to_string()]);
118 for text in &texts {
119 markers.extend(aliases_in(text));
120 }
121 let known: BTreeSet<String> = IconName::ALL.iter().map(|i| format!("{i:?}")).collect();
122 let mut used = BTreeSet::new();
123 for text in &texts {
124 used.extend(names_after(text, &markers).into_iter().filter(|n| known.contains(n)));
125 }
126 used
127}
128
129pub fn missing_icons(assets: &dyn AssetSource, used: &BTreeSet<String>) -> Vec<String> {
131 let mut missing = Vec::new();
132 for name in used {
133 let Some(icon) = IconName::ALL.iter().find(|i| format!("{i:?}") == *name) else { continue };
134 if assets.load(&icon.path()).ok().flatten().is_none() {
135 missing.push(name.clone());
136 }
137 }
138 missing
139}
140
141pub fn assert_icons_bundled(assets: &dyn AssetSource, roots: &[impl AsRef<Path>]) {
144 let used = icon_names_used(roots);
145 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<_>>());
146 let missing = missing_icons(assets, &used);
147 assert!(missing.is_empty(), "icons used but not bundled (add them to the app's icon set): {missing:?}");
148}
149
150fn rust_files(roots: &[impl AsRef<Path>]) -> Vec<PathBuf> {
152 let mut out = Vec::new();
153 let mut stack: Vec<PathBuf> = roots.iter().map(|r| r.as_ref().to_path_buf()).collect();
154 while let Some(path) = stack.pop() {
155 if path.is_dir() {
156 let Ok(entries) = std::fs::read_dir(&path) else { continue };
157 stack.extend(entries.flatten().map(|e| e.path()));
158 } else if path.extension().is_some_and(|x| x == "rs") {
159 out.push(path);
160 }
161 }
162 out.sort();
163 out
164}
165
166fn aliases_in(text: &str) -> Vec<String> {
169 let mut out = Vec::new();
170 for (at, _) in text.match_indices("IconName") {
171 let rest = text[at + "IconName".len()..].trim_start();
172 if let Some(after) = rest.strip_prefix("as") {
173 if after.starts_with(char::is_whitespace) {
174 let name = ident_at(after.trim_start());
175 if !name.is_empty() && name != "_" {
176 out.push(name);
177 }
178 }
179 }
180 }
181 for (at, _) in text.match_indices("type ") {
182 if at > 0 && is_ident_char(text[..at].chars().next_back().unwrap_or(' ')) {
183 continue;
184 }
185 let rest = &text[at + 5..];
186 let name = ident_at(rest.trim_start());
187 let Some(eq) = rest.find('=') else { continue };
188 let Some(end) = rest[eq..].find(';') else { continue };
189 let target = rest[eq + 1..eq + end].trim();
190 if !name.is_empty() && (target == "IconName" || target.ends_with("::IconName")) {
191 out.push(name);
192 }
193 }
194 out
195}
196
197fn names_after(text: &str, markers: &BTreeSet<String>) -> Vec<String> {
199 let mut out = Vec::new();
200 for m in markers {
201 let pat = format!("{m}::");
202 for (at, _) in text.match_indices(&pat) {
203 if text[..at].chars().next_back().is_some_and(is_ident_char) {
204 continue;
205 }
206 let name = ident_at(&text[at + pat.len()..]);
207 if name.starts_with(|c: char| c.is_ascii_uppercase()) {
208 out.push(name);
209 }
210 }
211 }
212 out
213}
214
215fn ident_at(s: &str) -> String {
216 s.chars().take_while(|c| is_ident_char(*c)).collect()
217}
218
219fn is_ident_char(c: char) -> bool {
220 c.is_ascii_alphanumeric() || c == '_'
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226
227 fn markers(text: &str) -> BTreeSet<String> {
228 let mut m = BTreeSet::from(["IconName".to_string()]);
229 m.extend(aliases_in(text));
230 m
231 }
232
233 #[test]
234 fn finds_names_and_aliases() {
235 let text = r#"
236 use gpui_kit::assets::IconName as I;
237 use gpui_kit::{assets::{IconName as Lucide, Assets}, px};
238 type Icons = gpui_kit::assets::IconName;
239 fn f() { (IconName::Plus, I::Server, Lucide::Columns2, Icons::Flame, UI::Nope, I::new()) }
240 "#;
241 let m = markers(text);
242 assert_eq!(m, BTreeSet::from(["IconName", "I", "Lucide", "Icons"].map(String::from)));
243 let mut names = names_after(text, &m);
244 names.sort();
245 assert_eq!(names, ["Columns2", "Flame", "Plus", "Server"]);
247 }
248
249 #[test]
250 fn an_alias_named_like_a_type_is_filtered_by_real_names() {
251 let text = "use gpui_kit::assets::IconName as Assets; let _ = (Assets::AppWindow, Assets::load);";
253 let names = names_after(text, &markers(text));
254 assert_eq!(names, ["AppWindow"]);
255 }
256
257 #[test]
260 fn every_icon_used_is_bundled() {
261 let root = env!("CARGO_MANIFEST_DIR");
262 assert_icons_bundled(&AppAssets::new(), &[format!("{root}/src/widgets"), format!("{root}/src/param_editor.rs")]);
263 }
264
265 #[test]
266 fn a_missing_icon_is_reported() {
267 let used = BTreeSet::from(["Microscope".to_string(), "Plus".to_string()]);
268 assert_eq!(missing_icons(&AppAssets::new(), &used), ["Microscope"]);
269 gpui_kit::assets::icon_assets!(Extra, [Microscope]);
270 assert!(missing_icons(&AppAssets::new().icons(Extra), &used).is_empty());
271 }
272}