iconography 0.1.1

A demo program to search for and load Linux icons in an egui/eframe app.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use anyhow::Result;
use egui::ColorImage;
use egui::TextureHandle;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use std::sync::mpsc::Sender;
use std::sync::mpsc::channel;
use std::thread::spawn;
use tracing::{debug, error, info, trace, warn};
use walkdir::WalkDir;

/// Maximum depth to recurse below "icons" or "pixmaps" paths
const MAX_ICON_SEARCH_DEPTH: usize = 4;

pub(crate) struct IconInfo {
    pub(crate) path: PathBuf,
    pub(crate) name: String,
}

#[derive(Clone)]
pub enum Icon {
    Texture {
        path: PathBuf,
        name: String,
        texture: TextureHandle,
    },
    Error {
        path: PathBuf,
        name: String,
        error: String,
    },
}

pub struct IconCache {
    icon_receiver: Receiver<Icon>,
    pub(crate) icons: Vec<Icon>,
    pub(crate) total_icons_discovered: usize,
}

impl IconCache {
    pub fn new(ctx: &egui::Context) -> Self {
        // find icons from the disk, this should be quick, probably don't need to spawn this
        let icon_infos = discover_icons();
        let total_icons_discovered = icon_infos.len();

        // loading images seems to take a lot more time
        let (tx, rx) = channel();
        let moved_ctx = ctx.clone();
        spawn(move || {
            load_icon_textures(icon_infos, &moved_ctx, tx);
        });

        IconCache {
            icon_receiver: rx,
            icons: Default::default(),
            total_icons_discovered,
        }
    }

    fn update_icon_vec(&mut self) {
        // need to be sure to use `try_iter` so this does not block
        for icon in self.icon_receiver.try_iter() {
            self.icons.push(icon);
        }
    }
    fn update_icon_vec_blocking(&mut self) {
        // need to be sure to use `try_iter` so this does not block
        for icon in self.icon_receiver.iter() {
            self.icons.push(icon);
        }
    }

    pub fn len(&mut self) -> usize {
        self.update_icon_vec();
        self.icons.len()
    }

    pub fn icons(&mut self) -> &Vec<Icon> {
        self.update_icon_vec_blocking();
        &self.icons
    }

    // TODO might want to add a method to return a hashmap as well

    pub fn chunks(&mut self, chunk_size: usize) -> std::slice::Chunks<'_, Icon> {
        self.update_icon_vec();
        self.icons.chunks(chunk_size)
    }
}

fn get_icon_search_paths() -> Vec<PathBuf> {
    let mut paths = Vec::new();

    // Paths to search for icons:
    //       /run/current-system/sw/share/icons
    //       /etc/profiles/per-user/egrieco/share/icons
    //       /home/egrieco/.nix-profile/share/icons

    // NixOS-specific paths
    paths.push(PathBuf::from("/run/current-system/sw/share/icons"));
    paths.push(PathBuf::from("/run/current-system/sw/share/pixmaps"));

    // User profile paths for Nix
    if let Ok(user) = std::env::var("USER") {
        paths.push(PathBuf::from(format!(
            "/etc/profiles/per-user/{user}/share/icons"
        )));
        paths.push(PathBuf::from(format!(
            "/etc/profiles/per-user/{user}/share/pixmaps"
        )));
    }
    if let Ok(home) = std::env::var("HOME") {
        paths.push(PathBuf::from(format!("{}/.nix-profile/share/icons", home)));
        paths.push(PathBuf::from(format!(
            "{}/.nix-profile/share/pixmaps",
            home
        )));
    }

    // Common Linux icon directories (still useful for some packages)
    paths.push(PathBuf::from("/usr/share/icons"));
    paths.push(PathBuf::from("/usr/share/pixmaps"));
    paths.push(PathBuf::from("/usr/local/share/icons"));
    paths.push(PathBuf::from("/usr/local/share/pixmaps"));

    // User-specific directories
    if let Ok(home) = std::env::var("HOME") {
        paths.push(PathBuf::from(format!("{}/.local/share/icons", home)));
        paths.push(PathBuf::from(format!("{}/.icons", home)));
    }

    // Flatpak icons
    paths.push(PathBuf::from("/var/lib/flatpak/exports/share/icons"));
    if let Ok(home) = std::env::var("HOME") {
        paths.push(PathBuf::from(format!(
            "{}/.local/share/flatpak/exports/share/icons",
            home
        )));
    }

    // Additional paths to search
    // /nix/store/qg05qi8y7y6jk6ys5fnx6xx4qns2ldhy-ghostty-1.1.3/share/icons
    // /nix/store/rpijzq6c40bdgy0ij7hsz9b2z3a8kbfn-gnome-shell-48.4/share/icons

    paths
}

pub(crate) fn discover_icons() -> Vec<IconInfo> {
    info!("Starting icon discovery");
    let icon_paths = get_icon_search_paths();
    let mut found_icons = HashMap::new();

    for search_path in icon_paths {
        if !search_path.exists() {
            warn!("Skipping non-existent path: {}", search_path.display());
            continue;
        }

        debug!("Searching for icons in: {}", search_path.display());

        for entry in WalkDir::new(&search_path)
            .max_depth(MAX_ICON_SEARCH_DEPTH)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            let path = entry.path();
            if let Some(extension) = path.extension() {
                let ext = extension.to_string_lossy().to_lowercase();
                if matches!(
                    ext.as_str(),
                    "png" | "svg" | "ico" | "xpm" | "jpg" | "jpeg" | "gif" | "bmp"
                ) {
                    if let Some(name) = path.file_stem() {
                        let name_str = name.to_string_lossy().to_string();
                        // Avoid duplicates, prefer higher resolution or more common formats
                        if !found_icons.contains_key(&name_str)
                            || matches!(ext.as_str(), "png" | "svg")
                        {
                            trace!("Found icon: {} at {}", name_str, path.display());
                            found_icons.insert(name_str.clone(), path.to_path_buf());
                        }
                    }
                }
            }
        }
    }

    let mut icons: Vec<IconInfo> = found_icons
        .into_iter()
        .map(|(name, path)| IconInfo { path, name })
        .collect();

    // Sort by name for consistent display
    icons.sort_by(|a, b| a.name.cmp(&b.name));

    info!(
        "Icon discovery complete. Found {} unique icons",
        icons.len()
    );

    icons
}

pub(crate) fn load_icon_textures(
    icon_infos: Vec<IconInfo>,
    ctx: &egui::Context,
    sender: Sender<Icon>,
) {
    info!("Loading icon textures for {} icons", icon_infos.len());
    let mut loaded_count = 0;
    let mut error_count = 0;

    for icon in icon_infos {
        match load_icon_image(&icon.path) {
            Ok(color_image) => {
                trace!("Successfully loaded texture for: {}", icon.name);
                loaded_count += 1;

                let texture =
                    ctx.load_texture(&icon.name, color_image, egui::TextureOptions::default());
                sender
                    .send(Icon::Texture {
                        path: icon.path,
                        name: icon.name,
                        texture: texture,
                    })
                    .expect("should be able to send icon texture");
            }
            Err(e) => {
                error!("Failed to load icon {}: {}", icon.name, e);
                error_count += 1;

                sender
                    .send(Icon::Error {
                        path: icon.path,
                        name: icon.name,
                        error: format!("Failed to load: {}", e),
                    })
                    .expect("should be able to send icon error");
            }
        }
    }

    info!(
        "Texture loading complete: {} loaded, {} errors",
        loaded_count, error_count
    );

    drop(sender);
}

fn load_icon_image(path: &Path) -> Result<ColorImage> {
    let extension = path
        .extension()
        .and_then(|ext| ext.to_str())
        .unwrap_or("")
        .to_lowercase();

    debug!("Loading image: {} (type: {})", path.display(), extension);

    match extension.as_str() {
        "svg" => load_svg_image(path),
        "xpm" => load_xpm_image(path),
        _ => load_raster_image(path),
    }
}

fn load_svg_image(path: &Path) -> Result<ColorImage> {
    trace!("Loading SVG image: {}", path.display());
    let svg_data = std::fs::read_to_string(path)?;
    debug!("Parsing SVG tree...");
    let usvg_tree = usvg::Tree::from_str(&svg_data, &usvg::Options::default())?;

    let size = usvg_tree.size();
    let width = size.width() as u32;
    let height = size.height() as u32;

    // Limit size to prevent memory issues
    let (width, height) = if width > 256 || height > 256 {
        let scale = 256.0 / width.max(height) as f32;
        debug!(
            "Scaling SVG from {}x{} to {}x{}",
            size.width() as u32,
            size.height() as u32,
            (width as f32 * scale) as u32,
            (height as f32 * scale) as u32
        );
        (
            (width as f32 * scale) as u32,
            (height as f32 * scale) as u32,
        )
    } else {
        (width, height)
    };

    let mut pixmap = resvg::tiny_skia::Pixmap::new(width, height)
        .ok_or_else(|| anyhow::anyhow!("Failed to create pixmap"))?;

    resvg::render(
        &usvg_tree,
        resvg::tiny_skia::Transform::from_scale(
            width as f32 / size.width(),
            height as f32 / size.height(),
        ),
        &mut pixmap.as_mut(),
    );

    let pixels = pixmap.data();
    let mut rgba_pixels = Vec::with_capacity(pixels.len());

    // Convert BGRA to RGBA
    for chunk in pixels.chunks_exact(4) {
        rgba_pixels.push(chunk[2]); // R
        rgba_pixels.push(chunk[1]); // G
        rgba_pixels.push(chunk[0]); // B
        rgba_pixels.push(chunk[3]); // A
    }

    Ok(ColorImage::from_rgba_unmultiplied(
        [width as usize, height as usize],
        &rgba_pixels,
    ))
}

fn load_raster_image(path: &Path) -> Result<ColorImage> {
    trace!("Loading raster image: {}", path.display());
    let img = image::open(path)?;

    // Limit size to prevent memory issues
    let img = if img.width() > 256 || img.height() > 256 {
        debug!(
            "Resizing raster image from {}x{} to max 256x256",
            img.width(),
            img.height()
        );
        img.resize(256, 256, image::imageops::FilterType::Lanczos3)
    } else {
        img
    };

    let img = img.to_rgba8();
    let (width, height) = img.dimensions();

    Ok(ColorImage::from_rgba_unmultiplied(
        [width as usize, height as usize],
        img.as_raw(),
    ))
}

fn load_xpm_image(path: &Path) -> Result<ColorImage> {
    // For XPM files, we'll create a placeholder icon since the image crate doesn't support XPM
    // In a full implementation, you'd want to use a dedicated XPM parser
    warn!(
        "XPM format not fully supported, creating placeholder for: {}",
        path.display()
    );
    let content = std::fs::read_to_string(path)?;

    // Try to extract dimensions from XMP header if possible
    let (width, height) =
        if let Some(width_line) = content.lines().find(|line| line.contains("width")) {
            // Simple parsing - this is a basic implementation
            let width = width_line
                .chars()
                .filter(|c| c.is_ascii_digit())
                .collect::<String>()
                .parse::<u32>()
                .unwrap_or(32);
            let height = content
                .lines()
                .find(|line| line.contains("height"))
                .and_then(|line| {
                    line.chars()
                        .filter(|c| c.is_ascii_digit())
                        .collect::<String>()
                        .parse::<u32>()
                        .ok()
                })
                .unwrap_or(32);
            (width.min(64), height.min(64)) // Limit size
        } else {
            (32, 32) // Default size
        };

    // Create a simple placeholder pattern for XMP files
    let mut pixels = Vec::with_capacity((width * height * 4) as usize);
    for y in 0..height {
        for x in 0..width {
            // Create a simple checkerboard pattern to indicate it's an XMP file
            let is_dark = (x / 4 + y / 4) % 2 == 0;
            if is_dark {
                pixels.extend_from_slice(&[100, 100, 100, 255]); // Dark gray
            } else {
                pixels.extend_from_slice(&[200, 200, 200, 255]); // Light gray
            }
        }
    }

    Ok(ColorImage::from_rgba_unmultiplied(
        [width as usize, height as usize],
        &pixels,
    ))
}