use std::collections::HashMap;
use egui::{Color32, Context, Pos2, Rect, TextureHandle, TextureOptions, Ui, Vec2};
#[cfg(feature = "svg")]
use resvg::tiny_skia::{Pixmap, Transform};
use rust_embed::RustEmbed;
#[derive(RustEmbed)]
#[folder = "assets/ui-icons"]
struct UiAssets;
const GLYPH_PIXELS: u32 = 48;
pub const FULL_UV: Rect = Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0));
pub struct Icons {
custom: HashMap<String, Vec<u8>>,
textures: HashMap<String, TextureHandle>,
#[cfg(feature = "material-icons")]
pub material: crate::MaterialIcons,
}
impl Default for Icons {
fn default() -> Self {
Self::new()
}
}
impl Icons {
pub fn new() -> Self {
Self {
custom: HashMap::new(),
textures: HashMap::new(),
#[cfg(feature = "material-icons")]
material: crate::MaterialIcons::new(),
}
}
pub fn bundled() -> Vec<String> {
let mut names: Vec<String> = UiAssets::iter()
.filter_map(|path| path.strip_suffix(".svg").map(str::to_owned))
.collect();
names.sort();
names
}
pub fn register(&mut self, name: &str, svg: impl Into<Vec<u8>>) {
self.custom.insert(name.to_owned(), svg.into());
let sized = format!("{name}@");
self.textures.retain(|key, _| key != name && !key.starts_with(&sized));
}
#[cfg(feature = "lucide-icons")]
pub fn lucide_names() -> Vec<String> {
crate::foundation::lucide::names()
}
#[cfg(feature = "lucide-icons")]
pub fn lucide_search(query: &str) -> Vec<String> {
crate::foundation::lucide::search(query)
}
pub fn texture(&mut self, ctx: &Context, name: &str) -> Option<TextureHandle> {
self.texture_px(ctx, name, GLYPH_PIXELS)
}
pub fn texture_sized(&mut self, ctx: &Context, name: &str, size: f32) -> Option<TextureHandle> {
self.texture_px(ctx, name, icon_pixels(ctx, size))
}
fn texture_px(&mut self, ctx: &Context, name: &str, pixels: u32) -> Option<TextureHandle> {
let key = if pixels == GLYPH_PIXELS {
name.to_owned()
} else {
format!("{name}@{pixels}")
};
if let Some(texture) = self.textures.get(&key) {
return Some(texture.clone());
}
let bytes = match self.custom.get(name) {
Some(bytes) => bytes.clone(),
None => bundled_svg(name)?,
};
let image = rasterize(&bytes, pixels)?;
let texture = ctx.load_texture(format!("workbench-icon-{key}"), image, TextureOptions::LINEAR);
self.textures.insert(key, texture.clone());
Some(texture)
}
pub fn paint(&mut self, ui: &Ui, name: &str, center: Pos2, size: f32, color: Color32) -> bool {
let Some(texture) = self.texture_sized(ui.ctx(), name, size) else {
return false;
};
let rect = pixel_rect(ui.ctx(), center, size);
ui.painter().image(texture.id(), rect, FULL_UV, color);
true
}
pub fn put(&mut self, ui: &mut Ui, name: &str, center: Pos2, size: f32, color: Color32) -> bool {
let Some(texture) = self.texture_sized(ui.ctx(), name, size) else {
return false;
};
let rect = Rect::from_center_size(center, Vec2::splat(size));
let response = ui.allocate_rect(rect, egui::Sense::hover());
ui.painter().image(
texture.id(),
pixel_rect(ui.ctx(), response.rect.center(), size),
FULL_UV,
color,
);
true
}
pub fn show(&mut self, ui: &mut Ui, name: &str, size: f32) {
self.show_tinted(ui, name, size, ui.visuals().text_color());
}
pub fn show_tinted(&mut self, ui: &mut Ui, name: &str, size: f32, color: Color32) {
let (rect, _) = ui.allocate_exact_size(Vec2::splat(size), egui::Sense::hover());
if let Some(texture) = self.texture_sized(ui.ctx(), name, size) {
ui.painter()
.image(texture.id(), pixel_rect(ui.ctx(), rect.center(), size), FULL_UV, color);
}
}
}
pub fn icon_pixels(ctx: &Context, size: f32) -> u32 {
(size * ctx.pixels_per_point()).round().clamp(8.0, 512.0) as u32
}
pub fn pixel_rect(ctx: &Context, center: Pos2, size: f32) -> Rect {
let ppp = ctx.pixels_per_point();
let side = icon_pixels(ctx, size) as f32;
let min = (center.to_vec2() * ppp - Vec2::splat(side * 0.5)).round();
Rect::from_min_size((min / ppp).to_pos2(), Vec2::splat(side / ppp))
}
fn bundled_svg(name: &str) -> Option<Vec<u8>> {
if let Some(name) = name.strip_prefix("lucide-").or_else(|| name.strip_prefix("lucide/")) {
return lucide_svg(name);
}
if let Some(file) = UiAssets::get(&format!("{name}.svg")) {
return Some(file.data.into_owned());
}
lucide_svg(name)
}
#[cfg(feature = "lucide-icons")]
fn lucide_svg(name: &str) -> Option<Vec<u8>> {
crate::foundation::lucide::svg(name)
}
#[cfg(not(feature = "lucide-icons"))]
fn lucide_svg(_name: &str) -> Option<Vec<u8>> {
None
}
#[doc(hidden)]
pub fn rasterize(bytes: &[u8], pixels: u32) -> Option<egui::ColorImage> {
#[cfg(not(feature = "svg"))]
{
let _ = (bytes, pixels);
None
}
#[cfg(feature = "svg")]
{
const MAX_SVG_BYTES: usize = 4 * 1024 * 1024;
if bytes.len() > MAX_SVG_BYTES {
return None;
}
let mut options = usvg::Options::default();
options.image_href_resolver.resolve_string = Box::new(|_, _| None);
let tree = usvg::Tree::from_data(bytes, &options).ok()?;
let size = tree.size();
let scale = (pixels as f32 / size.width().max(1.0)).min(pixels as f32 / size.height().max(1.0));
let width = (size.width() * scale).round().max(1.0) as u32;
let height = (size.height() * scale).round().max(1.0) as u32;
let mut pixmap = Pixmap::new(width, height)?;
resvg::render(&tree, Transform::from_scale(scale, scale), &mut pixmap.as_mut());
let mut rgba = pixmap.take();
for pixel in rgba.chunks_exact_mut(4) {
let alpha = u16::from(pixel[3]);
if alpha > 0 && alpha < 255 {
for channel in &mut pixel[..3] {
*channel = ((u16::from(*channel) * 255 + alpha / 2) / alpha).min(255) as u8;
}
}
}
Some(egui::ColorImage::from_rgba_unmultiplied(
[width as usize, height as usize],
&rgba,
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg(feature = "lucide-icons")]
fn lucide_is_available_through_the_same_cache() {
let names = Icons::lucide_names();
assert!(names.len() > 2000, "{}", names.len());
assert!(names.iter().any(|name| name == "trash-2"));
let mut icons = Icons::new();
let ctx = Context::default();
for name in ["save", "lucide-save", "trash-2", "heart", "circle-help"] {
let texture = icons.texture(&ctx, name).unwrap_or_else(|| panic!("{name}"));
assert!(texture.size()[0] > 0, "{name}");
}
}
#[test]
#[cfg(feature = "svg")]
fn every_bundled_glyph_rasterizes() {
let names = Icons::bundled();
assert!(names.len() >= 40, "{names:?}");
for name in names {
let file = UiAssets::get(&format!("{name}.svg")).expect("asset");
let image = rasterize(&file.data, GLYPH_PIXELS).unwrap_or_else(|| panic!("{name}"));
assert_eq!(image.size, [48, 48], "{name}");
assert!(image.pixels.iter().any(|pixel| pixel.a() > 0), "{name} is empty");
}
}
#[test]
fn pixel_rects_cover_whole_device_pixels_at_every_zoom() {
for zoom in [0.8_f32, 0.9, 1.0, 1.1, 1.25, 1.3, 1.5, 2.0] {
let ctx = Context::default();
ctx.set_pixels_per_point(zoom);
let rect = pixel_rect(&ctx, Pos2::new(37.37, 11.81), 16.0);
let ppp = ctx.pixels_per_point();
for value in [rect.min.x, rect.min.y, rect.max.x, rect.max.y] {
let px = value * ppp;
assert!((px - px.round()).abs() < 1e-3, "{value} at {zoom}");
}
assert_eq!(
(rect.width() * ppp).round() as u32,
icon_pixels(&ctx, 16.0),
"at {zoom}"
);
}
}
}