A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.
Rust archive-managerdesktop-appdual-paneexplorer-alternativefile-browserfile-explorerfile-managerfluent-designgpu-acceleratedgpuimacosmicaproductivityquick-lookrustrust-guitabswindowswindows-11windows-explorer
//! The commands packaged apps add to Windows 11's new right-click menu (`IExplorerCommand`): "Open in Terminal", "Edit in Notepad",
//! "Edit with Notepad++", NanaZip, PowerToys, VS Code, WhatsApp's "Send with", ... Explorer shows them; the classic menu that
//! rustyfiles reads (`ctxmenu`) never had them.
//!
//! WHY (issue 107: "Edit with Notepad++ ... is one of the commands that newer apps add only to Windows 11's new right-click menu";
//! PR 123 added one such app by hand). An app declares them in its package manifest, `AppxManifest.xml`:
//!
//! ```xml
//! <desktop4:Extension Category="windows.fileExplorerContextMenus">
//! <desktop4:FileExplorerContextMenus>
//! <desktop5:ItemType Type="Directory">
//! <desktop5:Verb Id="OpenTerminalHere" Clsid="9f156763-7844-4dc4-b2b1-901f640f5155" />
//! ```
//!
//! The class is a packaged COM class, which any process can create (Windows starts it in its package). Its `IExplorerCommand` gives
//! the title, the icon and whether it shows for the items (`GetState`), may have commands under it (`EnumSubCommands`), and runs
//! with `Invoke`. The packages of this account and their folders are listed under
//! `HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\Repository\Packages`
//! (`PackageRootFolder`); only the newest version of each package family is read.
//!
//! THREAD. Everything that touches a command runs on the shell STA (`crate::sta`): [`for_items`] keeps the commands it made for
//! the open menu there, and [`invoke`] runs one of them by its number.
use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CLSCTX_LOCAL_SERVER, CoCreateInstance, CoTaskMemFree};
use windows::Win32::UI::Shell::Common::ITEMIDLIST;
use windows::Win32::UI::Shell::{IExplorerCommand, IShellItemArray, ILCreateFromPathW, ILFree, SHCreateShellItemArrayFromIDLists};
use windows::core::{GUID, PCWSTR};
const PACKAGES: &str = r"Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\Repository\Packages";
/// One command an app declared: its class, the kinds of items it is for, and the package it came from.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Declared {
pub clsid: GUID,
/// The manifest's `ItemType` values: `*` (every file), `.txt`, `Directory`, `Directory\Background`, `Drive`, ...
pub types: Vec<String>,
/// Package full name (`Name_1.2.3.4_x64__publisher`) when read from an installed package.
pub package_full: String,
/// Package install directory (`PackageRootFolder`) when read from an installed package.
pub package_root: PathBuf,
}
// ------------------------------------------------------------------ pure: the manifest, the package names, the item kinds
/// The value of attribute `name` in the tag text `tag` (`Type="Directory"`).
fn attr<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
let mut rest = tag;
while let Some(i) = rest.find(name) {
let before = rest[..i].chars().last();
let after = &rest[i + name.len()..];
if before.is_some_and(|c| c.is_whitespace()) && let Some(v) = after.trim_start().strip_prefix('=') {
let v = v.trim_start();
let q = v.chars().next()?;
if q == '"' || q == '\'' {
let v = &v[1..];
return v.find(q).map(|end| &v[..end]);
}
}
rest = after;
}
None
}
/// A tag's local name (`desktop5:Verb` -> `Verb`) and whether it closes (`</...>`).
fn tag_name(tag: &str) -> (&str, bool) {
let closing = tag.starts_with('/');
let t = tag.trim_start_matches('/');
let name = t.split(|c: char| c.is_whitespace() || c == '/' || c == '>').next().unwrap_or("");
(name.rsplit(':').next().unwrap_or(name), closing)
}
/// The commands of a manifest's `windows.fileExplorerContextMenus` extensions, one per class (a class declared for several item
/// kinds is one command with all of them).
pub fn parse_manifest(xml: &str) -> Vec<Declared> {
let mut out: Vec<Declared> = Vec::new();
let mut in_menus = false;
let mut item_type: Option<String> = None;
let mut rest = xml;
while let Some(start) = rest.find('<') {
let Some(len) = rest[start..].find('>') else { break };
let tag = &rest[start + 1..start + len];
rest = &rest[start + len + 1..];
let (name, closing) = tag_name(tag);
match (name, closing) {
("Extension", false) if attr(tag, "Category") == Some("windows.fileExplorerContextMenus") => in_menus = true,
("Extension", true) => {
in_menus = false;
item_type = None;
}
("ItemType", false) if in_menus => item_type = attr(tag, "Type").map(str::to_string),
("ItemType", true) => item_type = None,
("Verb", false) if in_menus => {
let (Some(t), Some(id)) = (item_type.clone(), attr(tag, "Clsid")) else { continue };
let Ok(clsid) = GUID::try_from(id.trim_matches(|c| c == '{' || c == '}')) else { continue };
match out.iter_mut().find(|d| d.clsid == clsid) {
Some(d) if !d.types.contains(&t) => d.types.push(t),
Some(_) => {}
None => out.push(Declared { clsid, types: vec![t], package_full: String::new(), package_root: PathBuf::new() }),
}
}
_ => {}
}
}
out
}
/// A package's full name split: (family name, version). `Name_1.2.3.4_x64__publisherid` -> (`Name_publisherid`, [1, 2, 3, 4]).
pub fn family_and_version(full: &str) -> Option<(String, Vec<u32>)> {
let parts: Vec<&str> = full.split('_').collect();
if parts.len() != 5 {
return None;
}
let version = parts[1].split('.').map(|n| n.parse().unwrap_or(0)).collect();
Some((format!("{}_{}", parts[0], parts[4]), version))
}
/// The newest version of each package family among `full_names`.
pub fn newest_of_each(full_names: Vec<String>) -> Vec<String> {
let mut best: Vec<(String, Vec<u32>, String)> = Vec::new();
for f in full_names {
let Some((family, version)) = family_and_version(&f) else { continue };
match best.iter_mut().find(|(fam, ..)| *fam == family) {
Some(b) if version > b.1 => *b = (family, version, f),
Some(_) => {}
None => best.push((family, version, f)),
}
}
best.into_iter().map(|(.., f)| f).collect()
}
/// Whether a command declared for `types` is for these items: the folder's background, or every item (a file by `*` or its
/// extension, a folder by `Directory`, a drive's root by `Drive` or `Directory`).
pub fn applies(types: &[String], items: &[PathBuf], background: bool) -> bool {
let has = |t: &str| types.iter().any(|x| x.eq_ignore_ascii_case(t));
if background {
return has("Directory\\Background");
}
!items.is_empty()
&& items.iter().all(|p| {
let root = p.parent().is_none();
if root {
return has("Drive") || has("Directory");
}
if p.is_dir() {
return has("Directory") || has("Folder");
}
has("*") || p.extension().is_some_and(|e| has(&format!(".{}", e.to_string_lossy())))
})
}
// ------------------------------------------------------------------ the packages of this account
struct Cache {
at: Instant,
declared: Vec<Declared>,
}
static CACHE: Mutex<Option<Cache>> = Mutex::new(None);
/// The packages are read again after this long (an app installed meanwhile shows up in the next menu after it).
const FRESH: Duration = Duration::from_secs(60);
/// Every command the newest packages of this account declare.
pub fn declared() -> Vec<Declared> {
let mut c = CACHE.lock().unwrap_or_else(|e| e.into_inner());
if let Some(c) = c.as_ref().filter(|c| c.at.elapsed() < FRESH) {
return c.declared.clone();
}
let declared = read_packages();
*c = Some(Cache { at: Instant::now(), declared: declared.clone() });
declared
}
fn read_packages() -> Vec<Declared> {
let Ok(key) = windows_registry::CURRENT_USER.open(PACKAGES) else { return Vec::new() };
let Ok(names) = key.keys() else { return Vec::new() };
let mut out: Vec<Declared> = Vec::new();
for full in newest_of_each(names.collect()) {
let Ok(root) = key.open(&full).and_then(|k| k.get_string("PackageRootFolder")) else { continue };
let Ok(xml) = std::fs::read_to_string(Path::new(&root).join("AppxManifest.xml")) else { continue };
if !xml.contains("windows.fileExplorerContextMenus") {
continue;
}
for mut d in parse_manifest(&xml) {
if !out.iter().any(|o| o.clsid == d.clsid) {
d.package_full = full.clone();
d.package_root = PathBuf::from(&root);
out.push(d);
}
}
}
out
}
// ------------------------------------------------------------------ the commands (shell STA)
/// Where a packaged command's icon lives, as returned by `IExplorerCommand::GetIcon`.
///
/// Packaged commands return icon specs in several forms (issue 397):
/// - `C:\...\Notepad/Notepad.exe,-2` (forward slashes + negative resource id)
/// - `C:\...\Photos.ShellExtension.dll,-112` (DLL + negative resource id)
/// - `C:\...\Assets\icon.png` or `icon.svg` (direct image or vector asset, sometimes MRT scale-qualified)
/// - `@{PackageFullName?ms-resource://...}` or `ms-resource://...` (PRI indirect asset reference)
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IconSpec {
pub path: PathBuf,
pub index: Option<i32>,
}
/// One command as the menu shows it.
#[derive(Clone, Debug)]
pub struct Shown {
/// The number [`invoke`] takes.
pub id: usize,
pub title: String,
/// Where the command's icon lives (`path` and optional resource `index`), when `GetIcon` gave one.
pub icon: Option<IconSpec>,
pub enabled: bool,
/// The commands under it (a submenu).
pub sub: Vec<Shown>,
}
thread_local! {
/// The commands of the menu that is open, by number, and the items they are for.
static SESSION: RefCell<(Vec<IExplorerCommand>, Vec<PathBuf>)> = const { RefCell::new((Vec::new(), Vec::new())) };
}
/// The items as the shell's array (real item ids, so the command sees what Explorer would give it).
fn item_array(items: &[PathBuf]) -> windows::core::Result<IShellItemArray> {
let mut ids: Vec<*mut ITEMIDLIST> = Vec::new();
for p in items {
let w = crate::wide::wide(p);
let id = unsafe { ILCreateFromPathW(PCWSTR(w.as_ptr())) };
if !id.is_null() {
ids.push(id);
}
}
let consts: Vec<*const ITEMIDLIST> = ids.iter().map(|p| *p as *const _).collect();
let r = unsafe { SHCreateShellItemArrayFromIDLists(&consts) };
for id in ids {
unsafe { ILFree(Some(id)) };
}
r
}
fn take_string(p: windows::core::PWSTR) -> Option<String> {
if p.is_null() {
return None;
}
let s = unsafe { p.to_string() }.ok();
unsafe { CoTaskMemFree(Some(p.0 as *const _)) };
s.filter(|s| !s.is_empty())
}
fn load_indirect_string(spec: &str) -> Option<String> {
use windows::Win32::UI::Shell::SHLoadIndirectString;
let from = crate::wide::wide(spec);
let mut buf = [0u16; 1024];
unsafe { SHLoadIndirectString(PCWSTR(from.as_ptr()), &mut buf, None).ok()? };
let out = crate::wide::from_wide(&buf);
(!out.is_empty()).then_some(out)
}
/// Resolves an unscaled MRT package asset path (`Assets\icon.png`) to the best scale/targetsize
/// sibling on disk (`Assets\icon.scale-200.png`, `Assets\icon.targetsize-48_altform-unplated.png`).
fn resolve_mrt_asset(path: &Path, want_px: u32) -> Option<PathBuf> {
let dir = path.parent()?;
let stem = path.file_stem()?.to_str()?;
let ext = path.extension()?.to_str()?;
let entries = std::fs::read_dir(dir).ok()?;
let mut files = Vec::new();
let mut variants = Vec::new();
for entry in entries.flatten() {
let p = entry.path();
let Some(name) = p.file_name().and_then(|n| n.to_str()) else { continue };
if let Some(v) = crate::dock::iconpick::parse_asset(name, stem, ext, 44) {
files.push(p);
variants.push(v);
}
}
let best = crate::dock::iconpick::choose_asset(&variants, want_px)?;
files.into_iter().nth(best)
}
/// Parses a packaged command's `GetIcon` string into a normalized file path and optional resource index.
///
/// Normalizes forward slashes to backslashes (Windows Notepad and Paint return paths such as
/// `...\Notepad/Notepad.exe,-2` which `SHCreateItemFromParsingName` rejects), preserves `,index`,
/// resolves `ms-resource:` PRI strings via `SHLoadIndirectString`, and falls back to MRT
/// scale-qualified sibling files when an unscaled asset path does not exist verbatim.
fn parse_icon_spec(raw: &str, package_full: &str, package_root: Option<&Path>) -> Option<IconSpec> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return None;
}
let resolved = if trimmed.starts_with("@{") {
load_indirect_string(trimmed)?
} else if trimmed.get(..12).is_some_and(|p| p.eq_ignore_ascii_case("ms-resource:")) {
if package_full.is_empty() {
return None;
}
load_indirect_string(&format!("@{{{package_full}?{trimmed}}}"))?
} else {
trimmed.to_string()
};
let s = resolved.trim().trim_start_matches('@').trim();
let (path_str, index) = match s.rfind(',') {
Some(i) => match s[i + 1..].trim().parse::<i32>() {
Ok(idx) => (&s[..i], Some(idx)),
Err(_) => (s, None),
},
None => (s, None),
};
let expanded = crate::localized::expand_env(path_str.trim().trim_matches('"'));
let normalized = expanded.trim().trim_matches('"').replace('/', "\\");
if normalized.is_empty() {
return None;
}
let mut p = PathBuf::from(&normalized);
if !p.is_absolute() {
let root = package_root.filter(|r| !r.as_os_str().is_empty())?;
p = root.join(normalized.trim_start_matches('\\'));
}
if !p.exists() {
if index.is_none() {
p = resolve_mrt_asset(&p, 32)?;
} else {
return None;
}
}
Some(IconSpec { path: p, index })
}
fn decode_raster(path: &Path, size: u32) -> Option<crate::thumbs::Bgra> {
let img = image::open(path).ok()?.into_rgba8();
let (width, height) = img.dimensions();
if width == 0 || height == 0 {
return None;
}
let mut data = img.into_raw();
for px in data.chunks_exact_mut(4) {
px.swap(0, 2);
}
Some(crate::dock::icons::fit_square(&crate::thumbs::Bgra { width, height, data }, size))
}
fn decode_svg(path: &Path, size: u32) -> Option<crate::thumbs::Bgra> {
use resvg::{tiny_skia, usvg};
let bytes = std::fs::read(path).ok()?;
let mut opt = usvg::Options::default();
if bytes.windows(5).any(|w| w == b"<text") {
static FONTS: std::sync::OnceLock<std::sync::Arc<usvg::fontdb::Database>> = std::sync::OnceLock::new();
opt.fontdb = FONTS
.get_or_init(|| {
let mut db = usvg::fontdb::Database::new();
db.load_system_fonts();
std::sync::Arc::new(db)
})
.clone();
}
let tree = usvg::Tree::from_data(&bytes, &opt).ok()?;
let tsize = tree.size();
let (w, h) = (tsize.width().max(1.0), tsize.height().max(1.0));
let scale = (size as f32 / w.max(h)).max(0.01);
let (pw, ph) = ((w * scale).round().max(1.0) as u32, (h * scale).round().max(1.0) as u32);
let mut pix = tiny_skia::Pixmap::new(pw, ph)?;
resvg::render(&tree, tiny_skia::Transform::from_scale(scale, scale), &mut pix.as_mut());
// tiny-skia outputs premultiplied RGBA; convert to straight BGRA
let mut data = pix.take();
for px in data.chunks_exact_mut(4) {
let a = px[3] as u32;
if a > 0 && a < 255 {
for c in &mut px[..3] {
*c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
}
}
px.swap(0, 2);
}
Some(crate::dock::icons::fit_square(&crate::thumbs::Bgra { width: pw, height: ph, data }, size))
}
/// Loads a packaged command's icon as a `size` x `size` straight-alpha BGRA image (issue 397).
///
/// Extracts embedded resources (`exe`/`dll`/`ico`, including negative resource IDs) with
/// `PrivateExtractIconsW`, renders `.svg` directly via `resvg`, and decodes raster image assets
/// directly with `image`. Asking the shell for `Kind::Icon` on `.dll`/`.svg`/`.png` instead
/// returned the user's file-type association icon (such as Notepad++ for `.svg`) and ignored
/// `,index` on binaries.
pub fn load_icon(spec: &IconSpec, size: u32) -> Option<crate::thumbs::Bgra> {
let size = size.clamp(16, 256);
let ext = spec.path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
if let Some(index) = spec.index {
if let Some(bgra) = crate::dock::icons::extract_resource(&spec.path, index, size) {
return Some(crate::dock::icons::fit_square(&bgra, size));
}
if matches!(ext.as_str(), "exe" | "ico") {
if let Some(bgra) = crate::dock::icons::extract_resource(&spec.path, 0, size) {
return Some(crate::dock::icons::fit_square(&bgra, size));
}
}
return None;
}
match ext.as_str() {
"svg" => decode_svg(&spec.path, size),
"png" | "jpg" | "jpeg" | "bmp" | "webp" | "gif" | "tif" | "tiff" => decode_raster(&spec.path, size),
"ico" => crate::dock::icons::extract_resource(&spec.path, 0, size)
.map(|b| crate::dock::icons::fit_square(&b, size))
.or_else(|| decode_raster(&spec.path, size)),
"dll" | "mun" => crate::dock::icons::extract_resource(&spec.path, 0, size)
.map(|b| crate::dock::icons::fit_square(&b, size)),
"exe" => crate::dock::icons::extract_resource(&spec.path, 0, size)
.map(|b| crate::dock::icons::fit_square(&b, size))
.or_else(|| crate::thumbs::get_image(&spec.path, size, crate::thumbs::Kind::Icon).ok()),
_ => crate::thumbs::get_image(&spec.path, size, crate::thumbs::Kind::Icon).ok(),
}
}
const ECS_HIDDEN: u32 = 0x2;
const ECS_DISABLED: u32 = 0x1;
const ECF_HASSUBCOMMANDS: u32 = 0x1;
const ECF_HIDELABEL: u32 = 0x2;
const ECF_ISSEPARATOR: u32 = 0x8;
/// What `cmd` shows for `array` (None: it hides itself, is a separator, or has no title), with its commands below, numbered into
/// `keep`.
fn shown(
cmd: &IExplorerCommand,
array: &IShellItemArray,
package_full: &str,
package_root: &Path,
keep: &mut Vec<IExplorerCommand>,
depth: u8,
) -> Option<Shown> {
let state = unsafe { cmd.GetState(array, true) }.unwrap_or(0);
if state & ECS_HIDDEN != 0 {
return None;
}
let flags = unsafe { cmd.GetFlags() }.unwrap_or(0);
if flags & (ECF_ISSEPARATOR | ECF_HIDELABEL) != 0 {
return None;
}
let title = take_string(unsafe { cmd.GetTitle(array) }.ok()?)?;
let root = (!package_root.as_os_str().is_empty()).then_some(package_root);
let icon = unsafe { cmd.GetIcon(array) }.ok().and_then(take_string).and_then(|s| parse_icon_spec(&s, package_full, root));
let mut sub = Vec::new();
if flags & ECF_HASSUBCOMMANDS != 0 && depth < 2 && let Ok(e) = unsafe { cmd.EnumSubCommands() } {
loop {
let mut got = [None];
let mut n = 0u32;
if unsafe { e.Next(&mut got, Some(&mut n)) }.is_err() || n == 0 {
break;
}
if let Some(c) = got[0].take() && let Some(s) = shown(&c, array, package_full, package_root, keep, depth + 1) {
sub.push(s);
}
}
if sub.is_empty() {
return None;
}
}
keep.push(cmd.clone());
Some(Shown { id: keep.len() - 1, title, icon, enabled: state & ECS_DISABLED == 0, sub })
}
/// Windows Terminal's "Open in Terminal" (its release, Preview and Canary builds): the menu has its own, which opens the terminal
/// the user chose, so the packaged one is left out (issue 273: the menu had it twice).
const TERMINAL_HERE: [&str; 3] = ["9f156763-7844-4dc4-b2b1-901f640f5155", "02db545a-3e20-46de-83a5-1329b1e88b6b", "52065414-e077-47ec-a3ac-1cc5455e1b54"];
fn is_terminal_here(clsid: &GUID) -> bool {
TERMINAL_HERE.iter().any(|t| GUID::try_from(*t).is_ok_and(|g| g == *clsid))
}
const BLOCKED_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked";
/// Classes listed under `Shell Extensions\Blocked` (the user's and the machine's): Explorer leaves them out of its menu, and tools
/// such as ContextMenuManager hide a packaged command by adding it there (issue 241).
fn blocked() -> Vec<GUID> {
blocked_in(&[windows_registry::CURRENT_USER, windows_registry::LOCAL_MACHINE], BLOCKED_KEY)
}
fn blocked_in(hives: &[&windows_registry::Key], path: &str) -> Vec<GUID> {
hives
.iter()
.filter_map(|hive| hive.open(path).ok())
.flat_map(|key| key.values().map(|v| v.map(|(name, _)| name).collect::<Vec<_>>()).unwrap_or_default())
.filter_map(|name| parse_clsid(&name))
.collect()
}
fn parse_clsid(name: &str) -> Option<GUID> {
GUID::try_from(name.trim().trim_matches(|c| c == '{' || c == '}')).ok()
}
/// The packaged apps' commands for `items` (the folder itself with `background`), as the menu shows them. On the shell STA.
pub fn for_items(items: &[PathBuf], background: bool) -> Vec<Shown> {
let blocked = blocked();
let wanted: Vec<Declared> = declared()
.into_iter()
.filter(|d| applies(&d.types, items, background) && !is_terminal_here(&d.clsid) && !blocked.contains(&d.clsid))
.collect();
let mut keep = Vec::new();
let mut out = Vec::new();
if !wanted.is_empty() && let Ok(array) = item_array(items) {
for d in wanted {
let made: windows::core::Result<IExplorerCommand> = unsafe { CoCreateInstance(&d.clsid, None, CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER) };
match made {
Ok(cmd) => out.extend(shown(&cmd, &array, &d.package_full, &d.package_root, &mut keep, 0)),
Err(e) => log::debug!("packaged menu command {:?}: {e}", d.clsid),
}
}
}
SESSION.with(|s| *s.borrow_mut() = (keep, items.to_vec()));
out
}
/// Runs command `id` of the menu [`for_items`] was last asked for. On the shell STA.
pub fn invoke(id: usize) -> anyhow::Result<()> {
let (cmd, items) = SESSION.with(|s| {
let s = s.borrow();
(s.0.get(id).cloned(), s.1.clone())
});
let cmd = cmd.ok_or_else(|| anyhow::anyhow!("the menu's commands are gone"))?;
let array = item_array(&items)?;
// The program the command starts may come to the front. WHY (issue 1104: "Edit in Notepad" from the menu opened Notepad
// behind rustyfiles every time, while "Open" and "Open with" brought it to the front). ShellExecute, which those two go
// through, hands our right to the foreground to what it starts; a packaged command is activated by Windows' broker
// instead, which gets no such right, so the window it opened stayed behind ours.
// SAFETY: a plain call; it only widens who may take the foreground until the next input.
unsafe {
let _ = windows::Win32::UI::WindowsAndMessaging::AllowSetForegroundWindow(windows::Win32::UI::WindowsAndMessaging::ASFW_ANY);
}
unsafe { cmd.Invoke(&array, None) }?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
const TERMINAL: &str = r#"<Package><Extensions>
<desktop4:Extension Category="windows.fileExplorerContextMenus">
<desktop4:FileExplorerContextMenus>
<desktop5:ItemType Type="Directory">
<desktop5:Verb Id="OpenTerminalHere" Clsid="9f156763-7844-4dc4-b2b1-901f640f5155" />
</desktop5:ItemType>
<desktop5:ItemType Type="Directory\Background">
<desktop5:Verb Id="OpenTerminalHere" Clsid="9f156763-7844-4dc4-b2b1-901f640f5155" />
</desktop5:ItemType>
</desktop4:FileExplorerContextMenus>
</desktop4:Extension>
<uap:Extension Category="windows.fileTypeAssociation"><uap:FileTypeAssociation Name="x"><desktop5:Verb Id="No" Clsid="11111111-1111-1111-1111-111111111111"/></uap:FileTypeAssociation></uap:Extension>
<desktop4:Extension Category='windows.fileExplorerContextMenus'><desktop4:FileExplorerContextMenus>
<desktop5:ItemType Type="*"><desktop5:Verb Id="Edit" Clsid="{B298D29A-A6ED-11DE-BA8C-A68E55D89593}"/></desktop5:ItemType>
</desktop4:FileExplorerContextMenus></desktop4:Extension>
</Extensions></Package>"#;
#[test]
fn a_blocked_entry_names_its_class_with_or_without_braces() {
let t = GUID::try_from("9f156763-7844-4dc4-b2b1-901f640f5155").unwrap();
assert_eq!(parse_clsid("{9F156763-7844-4DC4-B2B1-901F640F5155}"), Some(t));
assert_eq!(parse_clsid("9f156763-7844-4dc4-b2b1-901f640f5155"), Some(t));
assert_eq!(parse_clsid(""), None);
assert_eq!(parse_clsid("not a class"), None);
}
#[test]
fn classes_on_the_blocked_list_are_read_from_the_registry() {
let path = format!(r"Software\rustyfiles-test\blocked-{}", std::process::id());
let key = windows_registry::CURRENT_USER.create(&path).unwrap();
key.set_string("{9F156763-7844-4DC4-B2B1-901F640F5155}", "Open in Terminal").unwrap();
key.set_string("junk", "").unwrap();
let got = blocked_in(&[windows_registry::CURRENT_USER], &path);
let _ = windows_registry::CURRENT_USER.remove_tree(r"Software\rustyfiles-test");
assert_eq!(got, [GUID::try_from("9f156763-7844-4dc4-b2b1-901f640f5155").unwrap()]);
assert!(blocked_in(&[windows_registry::CURRENT_USER], r"Software\rustyfiles-test\none").is_empty());
}
#[test]
fn a_manifests_menu_commands_are_read_with_the_kinds_they_are_for() {
let d = parse_manifest(TERMINAL);
assert_eq!(d.len(), 2, "{d:?}");
assert_eq!(d[0].clsid, GUID::try_from("9f156763-7844-4dc4-b2b1-901f640f5155").unwrap());
assert_eq!(d[0].types, ["Directory", "Directory\\Background"]);
assert_eq!(d[1].types, ["*"], "single quotes and braces around the class are fine");
assert!(!d.iter().any(|x| x.clsid == GUID::try_from("11111111-1111-1111-1111-111111111111").unwrap()), "only the menu extension counts");
}
#[test]
fn only_the_newest_version_of_a_package_is_read() {
let names = ["5319275A.WhatsAppDesktop_2.2644.101.0_x64__cv1g1gvanyjgm", "5319275A.WhatsAppDesktop_2.2645.101.0_x64__cv1g1gvanyjgm", "Microsoft.Paint_11.2609.441.0_x64__8wekyb3d8bbwe", "odd"];
let newest = newest_of_each(names.map(String::from).to_vec());
assert_eq!(newest, ["5319275A.WhatsAppDesktop_2.2645.101.0_x64__cv1g1gvanyjgm", "Microsoft.Paint_11.2609.441.0_x64__8wekyb3d8bbwe"]);
}
#[test]
fn a_command_shows_for_the_items_it_was_declared_for() {
let dir = std::env::temp_dir();
let file = dir.join("rf-pkgverbs-test.TXT");
std::fs::write(&file, b"x").unwrap();
let t = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert!(applies(&t(&["*"]), std::slice::from_ref(&file), false));
assert!(applies(&t(&[".txt"]), std::slice::from_ref(&file), false), "an extension, whatever its case");
assert!(!applies(&t(&[".md"]), std::slice::from_ref(&file), false));
assert!(!applies(&t(&["*"]), std::slice::from_ref(&dir), false), "a folder is not a file");
assert!(applies(&t(&["Directory"]), std::slice::from_ref(&dir), false));
assert!(applies(&t(&["Directory\\Background"]), &[], true));
assert!(!applies(&t(&["Directory"]), &[], true), "the background is its own kind");
assert!(!applies(&t(&["*"]), &[file.clone(), dir.clone()], false), "every item must fit");
assert!(applies(&t(&["Drive"]), &[PathBuf::from("C:\\")], false));
let _ = std::fs::remove_file(file);
}
#[test]
fn an_icon_spec_normalizes_slashes_and_keeps_resource_index() {
let exe = std::env::current_exe().unwrap();
let with_forward_slashes = exe.display().to_string().replace('\\', "/");
assert_eq!(
parse_icon_spec(&format!("{with_forward_slashes},-2"), "", None),
Some(IconSpec { path: exe.clone(), index: Some(-2) })
);
assert_eq!(
parse_icon_spec(&format!("\"{}\"", exe.display()), "", None),
Some(IconSpec { path: exe.clone(), index: None })
);
assert_eq!(
parse_icon_spec(&format!("@{},0", exe.display()), "", None),
Some(IconSpec { path: exe, index: Some(0) })
);
assert_eq!(parse_icon_spec("ms-resource://x/y", "", None), None);
// Byte 12 lands inside the second 'Ö' (bytes 11..13): must not panic on UTF-8 boundary
let non_ascii = r"C:\Users\ÖÖzz\app.exe";
assert!(!non_ascii.is_char_boundary(12));
assert_eq!(parse_icon_spec(non_ascii, "", None), None);
}
#[test]
fn relative_and_mrt_scaled_package_icon_assets_resolve_and_decode_directly() {
let dir = std::env::temp_dir().join(format!("rf-pkgverbs-icons-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let assets = dir.join("Assets");
std::fs::create_dir_all(&assets).unwrap();
// 1) Pure red 8x8 PNG with MRT scale-200 name (unscaled Assets/logo.png does not exist)
let scaled_png = assets.join("logo.scale-200.png");
let img = image::RgbaImage::from_pixel(8, 8, image::Rgba([220, 30, 40, 255]));
img.save(&scaled_png).unwrap();
let spec = parse_icon_spec("Assets/logo.png", "", Some(&dir)).expect("relative MRT asset resolves");
assert_eq!(spec, IconSpec { path: scaled_png, index: None });
let bgra = load_icon(&spec, 32).expect("PNG asset decodes directly");
assert_eq!((bgra.width, bgra.height), (32, 32));
// BGRA center pixel should match the red PNG (B=40, G=30, R=220, A=255), not a file-type icon
let center = ((16 * 32 + 16) * 4) as usize;
assert_eq!(&bgra.data[center..center + 4], &[40, 30, 220, 255]);
// 2) Pure green SVG rendered directly via resvg (never the user's .svg editor icon)
let svg_path = assets.join("clip.svg");
std::fs::write(&svg_path, r##"<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#10c020"/></svg>"##).unwrap();
let svg_spec = parse_icon_spec(&svg_path.display().to_string().replace('\\', "/"), "", None).expect("SVG path parses");
let svg_bgra = load_icon(&svg_spec, 32).expect("SVG renders directly");
assert_eq!((svg_bgra.width, svg_bgra.height), (32, 32));
assert_eq!(&svg_bgra.data[center..center + 4], &[0x20, 0xc0, 0x10, 255]);
// 3) DLL resource icon extraction (shell32.dll,-3 is the standard folder icon on every Windows)
let shell32 = PathBuf::from(crate::localized::expand_env(r"%SystemRoot%\System32\shell32.dll"));
if shell32.exists() {
let dll_spec = parse_icon_spec(r"%SystemRoot%/System32/shell32.dll,-3", "", None).expect("DLL resource spec parses");
assert_eq!(dll_spec.index, Some(-3));
let dll_bgra = load_icon(&dll_spec, 32).expect("DLL resource icon extracts");
assert_eq!((dll_bgra.width, dll_bgra.height), (32, 32));
assert!(dll_bgra.data.chunks_exact(4).any(|p| p[3] > 0), "extracted icon is not blank");
}
let _ = std::fs::remove_dir_all(&dir);
}
}
#[cfg(test)]
mod manual {
/// This account's real packages: the commands for a folder, a text file and a folder's background (titles only; nothing runs).
#[test]
#[ignore]
fn manual_list_this_pcs_packaged_commands() {
use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};
unsafe {
let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
}
let dir = std::env::temp_dir().join("rf-pkgverbs-manual");
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("note.txt");
std::fs::write(&file, b"x").unwrap();
println!("declared: {}", super::declared().len());
for (what, items, bg) in [("folder", vec![dir.clone()], false), ("text file", vec![file.clone()], false), ("background", vec![dir.clone()], true)] {
let shown = super::for_items(&items, bg);
let line: Vec<String> = shown
.iter()
.map(|s| {
let loaded = s.icon.as_ref().and_then(|spec| super::load_icon(spec, 32)).is_some();
format!("{} (spec {}, loaded {}, {} below)", s.title, s.icon.is_some(), loaded, s.sub.len())
})
.collect();
println!("{what}: {line:?}");
}
let _ = std::fs::remove_dir_all(dir);
}
}