hyprcorrect-ui 0.4.1

egui preferences window and suggestion popup for hyprcorrect.
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! Running-app metadata for the prefs Privacy picker.
//!
//! The picker stores an identifier (the on-disk blocklist key) and the
//! registry maps it to a display name + icon so the user sees "Safari"
//! with a logo instead of a bare `com.apple.Safari`.
//!
//! - **Linux**: identifiers are window classes; names/icons come from
//!   the freedesktop `.desktop` database.
//! - **macOS**: identifiers are bundle ids; names/icons come from
//!   `NSWorkspace` (running apps + `iconForFile`).

use std::collections::HashMap;
#[cfg(target_os = "linux")]
use std::path::{Path, PathBuf};
#[cfg(target_os = "linux")]
use std::sync::Arc;

use eframe::egui;

const ICON_SIZE_PX: u32 = 48;

/// Resolved metadata for a single app: what to show in the picker and
/// what to store in the config blocklist.
#[derive(Clone)]
pub struct AppMeta {
    /// The identifier (window class on Linux, bundle id on macOS) — the
    /// actual blocklist key.
    pub identifier: String,
    /// Friendly display name; falls back to the identifier when nothing
    /// matches.
    pub display_name: String,
    /// 48×48 RGBA texture for the icon, when one was resolvable. Built
    /// lazily by [`AppRegistry::lookup`].
    pub icon: Option<egui::TextureHandle>,
}

impl std::fmt::Debug for AppMeta {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AppMeta")
            .field("identifier", &self.identifier)
            .field("display_name", &self.display_name)
            .field("icon", &self.icon.is_some())
            .finish()
    }
}

/// Build an egui texture from `size × size` unpremultiplied RGBA bytes,
/// or `None` if the buffer is the wrong length. Shared by both backends.
fn texture_from_rgba(
    ctx: &egui::Context,
    cache_key: &str,
    rgba: &[u8],
    size: u32,
) -> Option<egui::TextureHandle> {
    if rgba.len() != (size * size * 4) as usize {
        return None;
    }
    let image = egui::ColorImage::from_rgba_unmultiplied([size as usize, size as usize], rgba);
    Some(ctx.load_texture(
        format!("app-icon:{cache_key}"),
        image,
        egui::TextureOptions::LINEAR,
    ))
}

// ============================================================================
// macOS: NSWorkspace running apps + iconForFile
// ============================================================================

#[cfg(target_os = "macos")]
struct MacApp {
    bundle_id: String,
    name: String,
    bundle_path: Option<String>,
}

#[cfg(target_os = "macos")]
pub struct AppRegistry {
    /// Running apps, sorted by name. Refreshed on each picker tick.
    apps: Vec<MacApp>,
    /// Cached icon textures, keyed by lowercase bundle id. `None` means
    /// "tried and failed" — avoids re-rasterizing every frame.
    icon_cache: HashMap<String, Option<egui::TextureHandle>>,
}

#[cfg(target_os = "macos")]
impl AppRegistry {
    /// Enumerate the currently-running user-facing apps.
    pub fn discover() -> Self {
        let mut registry = Self {
            apps: Vec::new(),
            icon_cache: HashMap::new(),
        };
        registry.refresh();
        registry
    }

    /// Re-enumerate running apps (cheap — names/paths only), preserving
    /// the icon cache so already-rendered icons aren't rebuilt.
    pub fn refresh(&mut self) {
        self.apps = hyprcorrect_platform::macos::apps::list_running_apps()
            .into_iter()
            .map(|a| MacApp {
                bundle_id: a.bundle_id,
                name: a.name,
                bundle_path: a.bundle_path,
            })
            .collect();
    }

    /// Bundle ids of the currently-known running apps (picker order).
    pub fn running_ids(&self) -> Vec<String> {
        self.apps.iter().map(|a| a.bundle_id.clone()).collect()
    }

    /// Display name + icon for `identifier` (a bundle id). Falls back to
    /// the identifier itself when the app isn't currently running.
    pub fn lookup(&mut self, ctx: &egui::Context, identifier: &str) -> AppMeta {
        let found = self
            .apps
            .iter()
            .find(|a| a.bundle_id.eq_ignore_ascii_case(identifier));
        let display_name = found
            .map(|a| a.name.clone())
            .unwrap_or_else(|| identifier.to_string());
        let bundle_path = found.and_then(|a| a.bundle_path.clone());
        let icon = self.icon_for(ctx, identifier, bundle_path.as_deref());
        AppMeta {
            identifier: identifier.to_string(),
            display_name,
            icon,
        }
    }

    fn icon_for(
        &mut self,
        ctx: &egui::Context,
        bundle_id: &str,
        bundle_path: Option<&str>,
    ) -> Option<egui::TextureHandle> {
        let cache_key = bundle_id.to_ascii_lowercase();
        if let Some(slot) = self.icon_cache.get(&cache_key) {
            return slot.clone();
        }
        // Resolve the icon by bundle id through LaunchServices — works for
        // any installed app, including background agents that don't appear
        // in the running-app list (e.g. 1Password). Fall back to the
        // running app's own bundle path if LS can't resolve it.
        use hyprcorrect_platform::macos::apps as macapps;
        let rgba = macapps::icon_rgba_for_bundle_id(bundle_id, ICON_SIZE_PX)
            .or_else(|| bundle_path.and_then(|p| macapps::app_icon_rgba(p, ICON_SIZE_PX)));
        let texture = rgba.and_then(|r| texture_from_rgba(ctx, &cache_key, &r, ICON_SIZE_PX));
        self.icon_cache.insert(cache_key, texture.clone());
        texture
    }
}

// ============================================================================
// Linux: freedesktop .desktop database
// ============================================================================

/// One parsed `[Desktop Entry]` block — only the fields the picker uses.
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Default)]
struct DesktopEntry {
    name: Option<String>,
    icon: Option<String>,
    wm_class: Option<String>,
    /// `.desktop` filename stem (e.g. `firefox.desktop` → `firefox`).
    stem: String,
    no_display: bool,
}

#[cfg(target_os = "linux")]
pub struct AppRegistry {
    /// Indexed by lowercase identifier — both the `StartupWMClass` and
    /// the filename stem land here.
    by_identifier: HashMap<String, Arc<DesktopEntry>>,
    /// Cached icon textures, keyed by lowercase identifier.
    icon_cache: HashMap<String, Option<egui::TextureHandle>>,
    /// Standard freedesktop icon directories.
    icon_dirs: Vec<PathBuf>,
}

#[cfg(target_os = "linux")]
impl AppRegistry {
    /// Build the registry by walking the standard application dirs.
    pub fn discover() -> Self {
        let mut by_identifier: HashMap<String, Arc<DesktopEntry>> = HashMap::new();
        for dir in desktop_dirs() {
            let Ok(entries) = std::fs::read_dir(&dir) else {
                continue;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().and_then(|e| e.to_str()) != Some("desktop") {
                    continue;
                }
                let Ok(text) = std::fs::read_to_string(&path) else {
                    continue;
                };
                let Some(parsed) = parse_desktop(&text, &path) else {
                    continue;
                };
                if parsed.no_display {
                    continue;
                }
                let arc = Arc::new(parsed);
                if let Some(wm) = &arc.wm_class {
                    by_identifier
                        .entry(wm.to_ascii_lowercase())
                        .or_insert_with(|| arc.clone());
                }
                by_identifier
                    .entry(arc.stem.to_ascii_lowercase())
                    .or_insert(arc);
            }
        }
        Self {
            by_identifier,
            icon_cache: HashMap::new(),
            icon_dirs: icon_dirs(),
        }
    }

    /// Look up display name + icon for the given identifier. Always
    /// returns something — falls back to the identifier itself.
    pub fn lookup(&mut self, ctx: &egui::Context, identifier: &str) -> AppMeta {
        let key = identifier.to_ascii_lowercase();
        let entry = self.by_identifier.get(&key).cloned();
        let display_name = entry
            .as_ref()
            .and_then(|e| e.name.clone())
            .unwrap_or_else(|| identifier.to_string());
        let icon = self.icon_for(ctx, &key, entry.as_deref());
        AppMeta {
            identifier: identifier.to_string(),
            display_name,
            icon,
        }
    }

    fn icon_for(
        &mut self,
        ctx: &egui::Context,
        key: &str,
        entry: Option<&DesktopEntry>,
    ) -> Option<egui::TextureHandle> {
        if let Some(slot) = self.icon_cache.get(key) {
            return slot.clone();
        }
        let icon_name = entry.and_then(|e| e.icon.clone()).unwrap_or_default();
        let texture = if icon_name.is_empty() {
            None
        } else {
            resolve_icon_path(&icon_name, &self.icon_dirs).and_then(|p| load_icon(ctx, &p, key))
        };
        self.icon_cache.insert(key.to_string(), texture.clone());
        texture
    }
}

#[cfg(target_os = "linux")]
fn desktop_dirs() -> Vec<PathBuf> {
    let mut dirs = vec![
        PathBuf::from("/usr/share/applications"),
        PathBuf::from("/usr/local/share/applications"),
    ];
    if let Some(home) = std::env::var_os("HOME") {
        let mut p = PathBuf::from(home);
        p.push(".local/share/applications");
        dirs.push(p);
    }
    if let Some(home) = std::env::var_os("HOME") {
        let mut p = PathBuf::from(home);
        p.push(".local/share/flatpak/exports/share/applications");
        dirs.push(p);
    }
    dirs.push(PathBuf::from("/var/lib/flatpak/exports/share/applications"));
    dirs
}

#[cfg(target_os = "linux")]
fn icon_dirs() -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    if let Some(home) = std::env::var_os("HOME") {
        let mut p = PathBuf::from(&home);
        p.push(".icons");
        dirs.push(p);
        let mut p = PathBuf::from(&home);
        p.push(".local/share/icons");
        dirs.push(p);
        let mut p = PathBuf::from(&home);
        p.push(".local/share/flatpak/exports/share/icons");
        dirs.push(p);
    }
    dirs.push(PathBuf::from("/usr/share/icons"));
    dirs.push(PathBuf::from("/usr/local/share/icons"));
    dirs.push(PathBuf::from("/var/lib/flatpak/exports/share/icons"));
    dirs
}

#[cfg(target_os = "linux")]
fn parse_desktop(text: &str, path: &Path) -> Option<DesktopEntry> {
    let stem = path.file_stem().and_then(|s| s.to_str())?.to_string();
    let mut entry = DesktopEntry {
        stem,
        ..Default::default()
    };
    let mut in_main = false;
    for line in text.lines() {
        let line = line.trim();
        if line.starts_with('[') {
            in_main = line == "[Desktop Entry]";
            continue;
        }
        if !in_main || line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        let key = key.trim();
        let value = value.trim();
        match key {
            "Name" if entry.name.is_none() => entry.name = Some(value.to_string()),
            "Icon" => entry.icon = Some(value.to_string()),
            "StartupWMClass" => entry.wm_class = Some(value.to_string()),
            "NoDisplay" if value == "true" => entry.no_display = true,
            _ => {}
        }
    }
    Some(entry)
}

/// Resolve an `Icon=` value against the freedesktop icon search path.
#[cfg(target_os = "linux")]
fn resolve_icon_path(icon: &str, dirs: &[PathBuf]) -> Option<PathBuf> {
    let trimmed = icon.trim();
    if trimmed.is_empty() {
        return None;
    }
    let candidate = Path::new(trimmed);
    if candidate.is_absolute() && candidate.exists() {
        return Some(candidate.to_path_buf());
    }
    let themes = ["hicolor", "Adwaita", "breeze", "Papirus", "gnome", "Yaru"];
    let sizes = [
        "scalable", "256x256", "128x128", "96x96", "64x64", "48x48", "256", "128", "64", "48",
        "symbolic",
    ];
    let exts = ["svg", "png"];
    for dir in dirs {
        for theme in &themes {
            for size in &sizes {
                for ext in &exts {
                    let mut p = dir.clone();
                    p.push(theme);
                    p.push(size);
                    p.push("apps");
                    p.push(format!("{trimmed}.{ext}"));
                    if p.exists() {
                        return Some(p);
                    }
                }
            }
        }
        for ext in &exts {
            let mut p = PathBuf::from("/usr/share/pixmaps");
            p.push(format!("{trimmed}.{ext}"));
            if p.exists() {
                return Some(p);
            }
        }
    }
    None
}

#[cfg(target_os = "linux")]
fn load_icon(ctx: &egui::Context, path: &Path, cache_key: &str) -> Option<egui::TextureHandle> {
    let bytes = std::fs::read(path).ok()?;
    let rgba = match path.extension().and_then(|e| e.to_str()) {
        Some("svg") => rasterize_svg(&bytes, ICON_SIZE_PX),
        Some("png") => rasterize_png(&bytes, ICON_SIZE_PX),
        _ => None,
    }?;
    texture_from_rgba(ctx, cache_key, &rgba, ICON_SIZE_PX)
}

#[cfg(target_os = "linux")]
fn rasterize_svg(bytes: &[u8], size: u32) -> Option<Vec<u8>> {
    let opts = usvg::Options::default();
    let tree = usvg::Tree::from_data(bytes, &opts).ok()?;
    let mut pixmap = tiny_skia::Pixmap::new(size, size)?;
    let svg_size = tree.size();
    let scale = (size as f32 / svg_size.width()).min(size as f32 / svg_size.height());
    let dx = (size as f32 - svg_size.width() * scale) / 2.0;
    let dy = (size as f32 - svg_size.height() * scale) / 2.0;
    let transform = tiny_skia::Transform::from_scale(scale, scale).post_translate(dx, dy);
    resvg::render(&tree, transform, &mut pixmap.as_mut());
    Some(pixmap.take())
}

#[cfg(target_os = "linux")]
fn rasterize_png(bytes: &[u8], size: u32) -> Option<Vec<u8>> {
    let img = image::load_from_memory_with_format(bytes, image::ImageFormat::Png).ok()?;
    let scaled = img.resize(size, size, image::imageops::FilterType::Lanczos3);
    let rgba = scaled.to_rgba8();
    let (w, h) = (rgba.width(), rgba.height());
    if w == size && h == size {
        return Some(rgba.into_raw());
    }
    let mut canvas: Vec<u8> = vec![0u8; (size * size * 4) as usize];
    let dx = (size - w) / 2;
    let dy = (size - h) / 2;
    for y in 0..h {
        let dst_row = (dy + y) as usize * size as usize * 4;
        let src_row = y as usize * w as usize * 4;
        let dst_off = dst_row + dx as usize * 4;
        let len = w as usize * 4;
        canvas[dst_off..dst_off + len].copy_from_slice(&rgba.as_raw()[src_row..src_row + len]);
    }
    Some(canvas)
}

#[cfg(all(test, target_os = "linux"))]
mod tests {
    use super::*;

    #[test]
    fn parse_desktop_picks_main_section_only() {
        let text = "\
[Desktop Action New]
Name=Wrong

[Desktop Entry]
Name=Discord
Icon=discord
StartupWMClass=discord
Type=Application
NoDisplay=false
";
        let entry = parse_desktop(text, Path::new("/x/discord.desktop")).unwrap();
        assert_eq!(entry.name.as_deref(), Some("Discord"));
        assert_eq!(entry.icon.as_deref(), Some("discord"));
        assert_eq!(entry.wm_class.as_deref(), Some("discord"));
        assert_eq!(entry.stem, "discord");
        assert!(!entry.no_display);
    }

    #[test]
    fn parse_desktop_honors_nodisplay() {
        let text = "[Desktop Entry]\nName=Hidden\nNoDisplay=true\n";
        let entry = parse_desktop(text, Path::new("/x/hidden.desktop")).unwrap();
        assert!(entry.no_display);
    }
}