Skip to main content

agentmux_srv_core/backend/file_icons/
assoc.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A fingerprint of whatever decides which icon a file type has, so a changed
5//! default app or icon theme makes a new cache entry instead of needing a
6//! notification (srv has no window to receive one). Spec ยง4.4.
7
8use super::request::{IconRequest, Kind};
9
10/// Join what decides the icon into one string; the cache hashes it.
11#[cfg(windows)]
12pub fn fingerprint(req: &IconRequest) -> String {
13    use windows::Win32::System::Registry::{HKEY_CLASSES_ROOT, HKEY_CURRENT_USER};
14    let reg = |root, path: &str, value: &str| registry_string(root, path, value).unwrap_or_default();
15    if req.kind == Kind::Dir {
16        return format!("dir|{}", reg(HKEY_CLASSES_ROOT, "Folder\\DefaultIcon", ""));
17    }
18    let dotted = format!(".{}", req.ext);
19    // The extension's own ProgID, and the one the user chose over it (Open with > Always).
20    let class = reg(HKEY_CLASSES_ROOT, &dotted, "");
21    let chosen = reg(
22        HKEY_CURRENT_USER,
23        &format!("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\{dotted}\\UserChoice"),
24        "ProgId",
25    );
26    let prog = if chosen.is_empty() { class.clone() } else { chosen.clone() };
27    let icon = if prog.is_empty() { String::new() } else { reg(HKEY_CLASSES_ROOT, &format!("{prog}\\DefaultIcon"), "") };
28    let handler = if prog.is_empty() { String::new() } else { reg(HKEY_CLASSES_ROOT, &format!("{prog}\\ShellEx\\IconHandler"), "") };
29    format!("file|{class}|{chosen}|{icon}|{handler}")
30}
31
32#[cfg(not(windows))]
33pub fn fingerprint(req: &IconRequest) -> String {
34    format!("{}|none", req.kind.as_str())
35}
36
37/// A string value (the default value when `value` is empty), or `None` when it isn't there.
38#[cfg(windows)]
39pub(crate) fn registry_string(root: windows::Win32::System::Registry::HKEY, path: &str, value: &str) -> Option<String> {
40    use windows::core::PCWSTR;
41    use windows::Win32::System::Registry::{RegGetValueW, RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ};
42    let wide = |s: &str| -> Vec<u16> { s.encode_utf16().chain(std::iter::once(0)).collect() };
43    let (path, value) = (wide(path), wide(value));
44    let value_ptr = if value.len() == 1 { PCWSTR::null() } else { PCWSTR(value.as_ptr()) };
45    let flags = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ;
46    let mut bytes: u32 = 0;
47    // SAFETY: the pointers are to NUL-terminated buffers that outlive the call; the size
48    // is asked for first, then the buffer is sized to it.
49    unsafe {
50        if RegGetValueW(root, PCWSTR(path.as_ptr()), value_ptr, flags, None, None, Some(&mut bytes)).is_err() || bytes == 0 {
51            return None;
52        }
53        let mut buf = vec![0u16; (bytes as usize).div_ceil(2)];
54        if RegGetValueW(root, PCWSTR(path.as_ptr()), value_ptr, flags, None, Some(buf.as_mut_ptr().cast()), Some(&mut bytes))
55            .is_err()
56        {
57            return None;
58        }
59        let len = buf.iter().position(|c| *c == 0).unwrap_or(buf.len());
60        Some(String::from_utf16_lossy(&buf[..len]))
61    }
62}
63
64#[cfg(all(test, windows))]
65mod tests {
66    use super::*;
67
68    fn req(kind: Kind, ext: &str) -> IconRequest {
69        IconRequest { kind, ext: ext.to_string(), px: 16 }
70    }
71
72    #[test]
73    fn the_fingerprint_reads_the_registry_and_differs_by_type() {
74        let txt = fingerprint(&req(Kind::File, "txt"));
75        assert!(txt.starts_with("file|"), "{txt}");
76        assert_eq!(txt, fingerprint(&req(Kind::File, "txt")), "stable between calls");
77        assert!(txt.len() > "file|||| ".len(), "Windows has an association for .txt: {txt}");
78        assert_ne!(txt, fingerprint(&req(Kind::File, "nope_zz")));
79        assert!(fingerprint(&req(Kind::Dir, "")).starts_with("dir|"));
80    }
81}