crisol_ui_kit/foundation/
icons.rs1use std::collections::HashMap;
9
10use egui::{Color32, Context, Image, Pos2, Rect, TextureHandle, TextureOptions, Ui, Vec2};
11#[cfg(feature = "svg")]
12use resvg::tiny_skia::{Pixmap, Transform};
13use rust_embed::RustEmbed;
14
15#[derive(RustEmbed)]
16#[folder = "assets/ui-icons"]
17struct UiAssets;
18
19const GLYPH_PIXELS: u32 = 48;
21
22pub const FULL_UV: Rect = Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0));
24
25pub struct Icons {
27 custom: HashMap<String, Vec<u8>>,
28 textures: HashMap<String, TextureHandle>,
29 #[cfg(feature = "material-icons")]
31 pub material: crate::MaterialIcons,
32}
33
34impl Default for Icons {
35 fn default() -> Self {
36 Self::new()
37 }
38}
39
40impl Icons {
41 pub fn new() -> Self {
43 Self {
44 custom: HashMap::new(),
45 textures: HashMap::new(),
46 #[cfg(feature = "material-icons")]
47 material: crate::MaterialIcons::new(),
48 }
49 }
50
51 pub fn bundled() -> Vec<String> {
53 let mut names: Vec<String> = UiAssets::iter()
54 .filter_map(|path| path.strip_suffix(".svg").map(str::to_owned))
55 .collect();
56 names.sort();
57 names
58 }
59
60 pub fn register(&mut self, name: &str, svg: impl Into<Vec<u8>>) {
62 self.custom.insert(name.to_owned(), svg.into());
63 let sized = format!("{name}@");
64 self.textures.retain(|key, _| key != name && !key.starts_with(&sized));
65 }
66
67 #[cfg(feature = "lucide-icons")]
73 pub fn lucide_names() -> Vec<String> {
74 crate::foundation::lucide::names()
75 }
76
77 #[cfg(feature = "lucide-icons")]
80 pub fn lucide_search(query: &str) -> Vec<String> {
81 crate::foundation::lucide::search(query)
82 }
83
84 pub fn texture(&mut self, ctx: &Context, name: &str) -> Option<TextureHandle> {
89 self.texture_px(ctx, name, GLYPH_PIXELS)
90 }
91
92 pub fn texture_sized(&mut self, ctx: &Context, name: &str, size: f32) -> Option<TextureHandle> {
97 let needed = size * ctx.pixels_per_point();
98 let pixels = [GLYPH_PIXELS, GLYPH_PIXELS * 2, GLYPH_PIXELS * 4, GLYPH_PIXELS * 8]
99 .into_iter()
100 .find(|&pixels| pixels as f32 >= needed)
101 .unwrap_or(GLYPH_PIXELS * 8);
102 self.texture_px(ctx, name, pixels)
103 }
104
105 fn texture_px(&mut self, ctx: &Context, name: &str, pixels: u32) -> Option<TextureHandle> {
106 let key = if pixels == GLYPH_PIXELS {
107 name.to_owned()
108 } else {
109 format!("{name}@{pixels}")
110 };
111 if let Some(texture) = self.textures.get(&key) {
112 return Some(texture.clone());
113 }
114 let bytes = match self.custom.get(name) {
115 Some(bytes) => bytes.clone(),
116 None => bundled_svg(name)?,
117 };
118 let image = rasterize(&bytes, pixels)?;
119 let texture = ctx.load_texture(format!("workbench-icon-{key}"), image, TextureOptions::LINEAR);
120 self.textures.insert(key, texture.clone());
121 Some(texture)
122 }
123
124 pub fn paint(&mut self, ui: &Ui, name: &str, center: Pos2, size: f32, color: Color32) -> bool {
126 let Some(texture) = self.texture_sized(ui.ctx(), name, size) else {
127 return false;
128 };
129 let rect = Rect::from_center_size(center, Vec2::splat(size));
130 ui.painter().image(texture.id(), rect, FULL_UV, color);
131 true
132 }
133
134 pub fn put(&mut self, ui: &mut Ui, name: &str, center: Pos2, size: f32, color: Color32) -> bool {
139 let Some(texture) = self.texture_sized(ui.ctx(), name, size) else {
140 return false;
141 };
142 let rect = Rect::from_center_size(center, Vec2::splat(size));
143 ui.put(
144 rect,
145 Image::new(&texture).fit_to_exact_size(Vec2::splat(size)).tint(color),
146 );
147 true
148 }
149
150 pub fn show(&mut self, ui: &mut Ui, name: &str, size: f32) {
153 self.show_tinted(ui, name, size, ui.visuals().text_color());
154 }
155
156 pub fn show_tinted(&mut self, ui: &mut Ui, name: &str, size: f32, color: Color32) {
158 if let Some(texture) = self.texture_sized(ui.ctx(), name, size) {
159 ui.add(Image::new(&texture).fit_to_exact_size(Vec2::splat(size)).tint(color));
160 } else {
161 ui.allocate_exact_size(Vec2::splat(size), egui::Sense::hover());
162 }
163 }
164}
165
166fn bundled_svg(name: &str) -> Option<Vec<u8>> {
167 if let Some(name) = name.strip_prefix("lucide-").or_else(|| name.strip_prefix("lucide/")) {
168 return lucide_svg(name);
169 }
170 if let Some(file) = UiAssets::get(&format!("{name}.svg")) {
171 return Some(file.data.into_owned());
172 }
173 lucide_svg(name)
174}
175
176#[cfg(feature = "lucide-icons")]
177fn lucide_svg(name: &str) -> Option<Vec<u8>> {
178 crate::foundation::lucide::svg(name)
179}
180
181#[cfg(not(feature = "lucide-icons"))]
182fn lucide_svg(_name: &str) -> Option<Vec<u8>> {
183 None
184}
185
186#[doc(hidden)]
191pub fn rasterize(bytes: &[u8], pixels: u32) -> Option<egui::ColorImage> {
192 #[cfg(not(feature = "svg"))]
193 {
194 let _ = (bytes, pixels);
195 None
196 }
197 #[cfg(feature = "svg")]
198 {
199 const MAX_SVG_BYTES: usize = 4 * 1024 * 1024;
202 if bytes.len() > MAX_SVG_BYTES {
203 return None;
204 }
205 let mut options = usvg::Options::default();
208 options.image_href_resolver.resolve_string = Box::new(|_, _| None);
209 let tree = usvg::Tree::from_data(bytes, &options).ok()?;
210 let size = tree.size();
211 let scale = (pixels as f32 / size.width().max(1.0)).min(pixels as f32 / size.height().max(1.0));
212 let width = (size.width() * scale).round().max(1.0) as u32;
213 let height = (size.height() * scale).round().max(1.0) as u32;
214 let mut pixmap = Pixmap::new(width, height)?;
215 resvg::render(&tree, Transform::from_scale(scale, scale), &mut pixmap.as_mut());
216 let mut rgba = pixmap.take();
217 for pixel in rgba.chunks_exact_mut(4) {
218 let alpha = u16::from(pixel[3]);
219 if alpha > 0 && alpha < 255 {
220 for channel in &mut pixel[..3] {
221 *channel = ((u16::from(*channel) * 255 + alpha / 2) / alpha).min(255) as u8;
222 }
223 }
224 }
225 Some(egui::ColorImage::from_rgba_unmultiplied(
226 [width as usize, height as usize],
227 &rgba,
228 ))
229 }
230}
231
232#[cfg(test)]
233mod tests {
234 use super::*;
235
236 #[test]
237 #[cfg(feature = "lucide-icons")]
238 fn lucide_is_available_through_the_same_cache() {
239 let names = Icons::lucide_names();
240 assert!(names.len() > 2000, "{}", names.len());
241 assert!(names.iter().any(|name| name == "trash-2"));
242 let mut icons = Icons::new();
243 let ctx = Context::default();
244 for name in ["save", "lucide-save", "trash-2", "heart", "circle-help"] {
245 let texture = icons.texture(&ctx, name).unwrap_or_else(|| panic!("{name}"));
246 assert!(texture.size()[0] > 0, "{name}");
247 }
248 }
249
250 #[test]
251 #[cfg(feature = "svg")]
252 fn every_bundled_glyph_rasterizes() {
253 let names = Icons::bundled();
254 assert!(names.len() >= 40, "{names:?}");
255 for name in names {
256 let file = UiAssets::get(&format!("{name}.svg")).expect("asset");
257 let image = rasterize(&file.data, GLYPH_PIXELS).unwrap_or_else(|| panic!("{name}"));
258 assert_eq!(image.size, [48, 48], "{name}");
259 assert!(image.pixels.iter().any(|pixel| pixel.a() > 0), "{name} is empty");
260 }
261 }
262}