Skip to content

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.

46.1 KB
Raw Blame
//! What the middle island shows and what a click on it does. Pure: the pinned apps, the running windows and the foreground window
//! are arguments, so the merge, its order and the click decisions are tested without a window.

use std::path::{Path, PathBuf};

use crate::tasklist::{Relaunch, Task};

/// How to start an app.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Launch {
    /// Open this shortcut (`.lnk`) like Explorer does: its arguments, working directory and "run as" come along.
    Link(PathBuf),
    /// Start this program.
    Exe { path: PathBuf, args: String },
    /// A packaged (Store) app by its AppUserModelID.
    Packaged(String),
}

impl Launch {
    /// The file on disk this app is started from: the shortcut or the program. `None` for a packaged app, which has no file of its
    /// own to show, to give properties for or to start as administrator.
    pub fn file(&self) -> Option<&std::path::Path> {
        match self {
            Launch::Link(p) | Launch::Exe { path: p, .. } => Some(p),
            Launch::Packaged(_) => None,
        }
    }
}

/// Where an app's icon comes from.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum IconSource {
    /// A program, a document or a folder on disk: the shell's own icon for it.
    File(PathBuf),
    /// An icon stored in a file (a shortcut's own icon location).
    Resource { file: PathBuf, index: i32 },
    /// A packaged app by its AppUserModelID (`shell:AppsFolder`).
    Packaged(String),
    /// A shell place by its parsing name (`shell:RecycleBinFolder`).
    Shell(String),
    /// The icon a running window has set itself (a program with no file the shell can ask).
    Window(isize),
}

/// An app pinned to the Windows taskbar (read from the taskbar's own pin folder, never written).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PinnedApp {
    /// The shortcut's name without `.lnk`, or the packaged app's display name.
    pub name: String,
    /// What a running window is matched against (see [`pin_matches`]): the AppUserModelID, lower case, when the pin has one.
    pub aumid: Option<String>,
    /// The program the pin starts, lower case, when it has one that exists.
    pub exe: Option<String>,
    pub launch: Launch,
    pub icon: IconSource,
}

/// A place the dock links to after the apps.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Place {
    RecycleBin,
    Downloads,
}

/// The Recycle Bin's picture for a state the caller knows (issue 887): the icon Windows keeps for "full" or "empty" under the bin's
/// class (`DefaultIcon`, the user's own choice first), as a resource of its file. The shell's `shell:RecycleBinFolder` picture comes
/// from its icon cache, which can still hold the old state for a while after the bin changed (the dock asked a second after a file
/// was restored from the bin and got the full bin, and kept it). `None` when the registry names no picture: the shell's then.
pub fn recycle_bin_icon(full: bool) -> Option<IconSource> {
    use windows::Win32::System::Registry::{HKEY_CLASSES_ROOT, HKEY_CURRENT_USER};
    const CLSID: &str = "{645FF040-5081-101B-9F08-00AA002F954E}";
    let value = if full { "full" } else { "empty" };
    let user = format!(r"Software\Microsoft\Windows\CurrentVersion\Explorer\CLSID\{CLSID}\DefaultIcon");
    let machine = format!(r"CLSID\{CLSID}\DefaultIcon");
    let text = crate::bench::reg_string(HKEY_CURRENT_USER, &user, value).or_else(|| crate::bench::reg_string(HKEY_CLASSES_ROOT, &machine, value))?;
    // (`reg_string` can hand back what follows the value's end too: an expanded value is shorter than the size Windows reports)
    let text = text.split(char::from(0)).next().unwrap_or_default();
    let (file, index) = crate::tasklist::icon_resource(&crate::localized::expand_env(text))?;
    Some(IconSource::Resource { file, index })
}

impl Place {
    /// The shell parsing name the icon is asked with.
    pub fn icon_source(self) -> IconSource {
        match self {
            Place::RecycleBin => IconSource::Shell("shell:RecycleBinFolder".into()),
            Place::Downloads => match crate::known::KnownFolder::Downloads.path() {
                Some(p) => IconSource::File(p),
                None => IconSource::Shell("shell:Downloads".into()),
            },
        }
    }

    /// The argument rustyfiles opens the place with (the same strings its command line takes): the Recycle Bin's shell name, the
    /// Downloads folder's path.
    pub fn open_argument(self) -> String {
        match self {
            Place::RecycleBin => "shell:RecycleBinFolder".into(),
            Place::Downloads => crate::known::KnownFolder::Downloads.path().map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| "shell:Downloads".into()),
        }
    }
}

/// One app in the dock, pinned or only running.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DockApp {
    /// A stable identity (lower case): the AppUserModelID, else the program path, else the window's process.
    pub key: String,
    pub name: String,
    pub pinned: bool,
    /// How to start it; `None` for a running program that cannot be started again (no known program).
    pub launch: Option<Launch>,
    pub icon: IconSource,
    /// Its task windows, the one used last first (the order [`crate::tasklist::tasks`] gives).
    pub windows: Vec<isize>,
    /// The foreground window is one of them.
    pub active: bool,
}

impl DockApp {
    pub fn running(&self) -> bool {
        !self.windows.is_empty()
    }

    /// Everything its icon can come from, best first: the icon the app was given, then the icon one of its task windows has set itself
    /// (a few windows are tried: the first may be a splash screen with none), then, for a packaged app, the logo of its package. The
    /// dock asks for them in turn and draws a letter only when none gives a picture.
    pub fn icon_chain(&self) -> Vec<IconSource> {
        let mut chain = vec![self.icon.clone()];
        // the same package under another letter case (the key is lower case) is the same logo
        let same = |a: &IconSource, b: &IconSource| match (a, b) {
            (IconSource::Packaged(x), IconSource::Packaged(y)) => x.eq_ignore_ascii_case(y),
            _ => a == b,
        };
        let mut add = |s: IconSource| {
            if !chain.iter().any(|c| same(c, &s)) {
                chain.push(s);
            }
        };
        for &w in self.windows.iter().take(3) {
            add(IconSource::Window(w));
        }
        // (not when the app was given a picture of its own: the package logo is ranked first and would replace it, issue 785)
        let chosen_picture = matches!(&self.icon, IconSource::File(p) if super::iconload::is_picture_file(p));
        if looks_packaged(&self.key) && !chosen_picture {
            add(IconSource::Packaged(self.key.clone()));
        }
        chain
    }
}

/// An item of the middle island, left to right.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DockItem {
    App(DockApp),
    /// The thin line between the apps and the places.
    Separator,
    Place(Place),
}

/// What a click does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClickAction {
    /// Not running: start it.
    Start,
    /// Running but not in front: bring this window (its last used one) to the front, restoring it if minimised.
    Raise(isize),
    /// In front: minimise this window.
    Minimize(isize),
}

/// The decision for a click on an app whose task windows are `windows` (last used first) while `foreground` is in front.
pub fn click_action(windows: &[isize], foreground: isize) -> ClickAction {
    match windows.first() {
        None => ClickAction::Start,
        Some(&first) => {
            if windows.contains(&foreground) {
                ClickAction::Minimize(foreground)
            } else {
                ClickAction::Raise(first)
            }
        }
    }
}

/// A middle click: another instance, whether or not one is running.
pub fn middle_click_action() -> ClickAction {
    ClickAction::Start
}

/// Whether a pinned app is the same app as a running group. `group` is [`Task::group`] (lower case AppUserModelID, else the
/// program path; the windows of a packaged app are given their process's package id first, see [`super::identity`]), `tasks` the
/// group's windows. They match when the identities agree, or - a pin with no AppUserModelID of its own, or
/// a window that sets another one than its shortcut carries (a program that names itself at run time) - when the program is the
/// same.
pub fn pin_matches(pin: &PinnedApp, group: &str, tasks: &[Task]) -> bool {
    if let Some(id) = &pin.aumid
        && id == group
    {
        return true;
    }
    // A browser's installed site (a Chrome, Edge or Brave web app) is an app of its own, run by the browser's program: its windows are
    // not the browser's, and the browser's windows are not its. Only its own id matches it (issue 150: a web app's window went to the
    // browser's pin, and a closed web app's pin took the browser's windows).
    if is_web_app(group) || pin.aumid.as_deref().is_some_and(is_web_app) {
        return false;
    }
    if let Some(exe) = &pin.exe {
        if exe == group {
            return true;
        }
        // (the program of the window, or the one the window names to be started again: Steam's window is its helper's, the pin is
        // steam.exe)
        let same = |p: &std::path::Path| p.to_string_lossy().to_lowercase() == *exe;
        return tasks.iter().any(|t| t.exe.as_deref().is_some_and(same) || t.relaunch.as_ref().is_some_and(|r| same(&r.program)));
    }
    false
}

/// Whether an AppUserModelID (lower case) is a browser's installed site: `chrome._crx_<app id>`, `msedge._crx_…`, `brave._crx_…`.
pub fn is_web_app(aumid: &str) -> bool {
    aumid.contains("._crx_")
}

/// The AppUserModelID of a packaged app looks like `Package.Name_publisherid!AppId`.
pub fn looks_packaged(aumid: &str) -> bool {
    let Some((family, app)) = aumid.split_once('!') else { return false };
    !app.is_empty() && family.contains('_') && !aumid.contains(char::is_whitespace) && !aumid.contains(['\\', '/', ':'])
}

/// What an app's jump list (and its names) are looked up by: its AppUserModelID when it has one that a jump-list file is named by
/// (the launch is a packaged app, or the key looks like one), and its program when it has one on disk (the launch, else an icon that
/// is a `.exe`). The app menu and the probe that measures it both read this, so a count taken by the probe is the menu's.
pub fn jump_identity(app: &DockApp) -> (Option<String>, Option<PathBuf>) {
    let aumid = match &app.launch {
        Some(Launch::Packaged(id)) => Some(id.clone()),
        _ if looks_packaged(&app.key) => Some(app.key.clone()),
        _ => None,
    };
    let exe = match &app.launch {
        Some(Launch::Exe { path, .. }) => Some(path.clone()),
        _ => match &app.icon {
            IconSource::File(p) if p.extension().is_some_and(|e| e.eq_ignore_ascii_case("exe")) => Some(p.clone()),
            _ => None,
        },
    };
    (aumid, exe)
}

/// A name for a running app that has no pin to take it from: the program's file name, else the first window's title.
pub fn fallback_name(tasks: &[Task]) -> String {
    let t = tasks.first();
    if let Some(name) = t.and_then(|t| t.relaunch.as_ref()).and_then(|r| r.name.clone()) {
        return name;
    }
    // (the program the window names to be started again before the window's own: "Steam", not "Steamwebhelper")
    let program = t.and_then(|t| t.relaunch.as_ref().map(|r| &r.program).or(t.exe.as_ref()));
    if let Some(stem) = program.and_then(|p| p.file_stem()).map(|s| s.to_string_lossy().into_owned()) {
        let mut c = stem.chars();
        return match c.next() {
            Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
            None => stem,
        };
    }
    if let Some(t) = t {
        if !t.title.is_empty() {
            return t.title.clone();
        }
        if let Some(id) = &t.app_id {
            return id.clone();
        }
    }
    String::new()
}

/// The AppUserModelID of the Control Panel's window (Explorer's process shows it).
const CONTROL_PANEL_ID: &str = "microsoft.windows.controlpanel";

/// Whether a running group is an app that Explorer's own process shows under an id of its own (the Control Panel), not a folder
/// window: its program is explorer.exe, so the program's icon and name would be File Explorer's.
fn shown_by_explorer(group: &str, first: &Task) -> bool {
    let explorer = first.exe.as_deref().and_then(|p| p.file_name()).is_some_and(|n| n.eq_ignore_ascii_case("explorer.exe"));
    explorer && first.app_id.is_some() && group != "microsoft.windows.explorer"
}

/// The icon of a running app whose window names a program to start again: that program, unless its file has no icon of its own -
/// the shell then draws its generic document picture, so the window's own program is used instead (issue 436).
fn relaunch_icon(r: &Relaunch, exe: Option<&PathBuf>, has_icon: impl FnOnce(&Path) -> bool) -> IconSource {
    // the icon the window asks for comes first: a browser's installed web app is the browser's program with its own icon (issue 689)
    if let Some((file, index)) = &r.icon {
        return IconSource::Resource { file: file.clone(), index: *index };
    }
    let path = if has_icon(&r.program) || exe.is_none() { &r.program } else { exe.unwrap() };
    IconSource::File(path.clone())
}

/// The app for a running group, with the reading of a program's resource directory given, so the icon choice is tested without the disk.
fn running_app_with(group: &str, tasks: &[Task], foreground: isize, has_icon: impl Fn(&Path) -> bool) -> DockApp {
    let first = &tasks[0];
    let windows: Vec<isize> = tasks.iter().map(|t| t.hwnd).collect();
    if shown_by_explorer(group, first) {
        // (the Control Panel showed with File Explorer's icon and name; Windows' taskbar gives it its own)
        let control_panel = group == CONTROL_PANEL_ID;
        let icon = if control_panel { IconSource::Shell("shell:ControlPanelFolder".into()) } else { IconSource::Window(first.hwnd) };
        let launch = control_panel.then(|| Launch::Exe { path: first.exe.clone().unwrap_or_default(), args: "shell:ControlPanelFolder".into() });
        let name = if first.title.is_empty() { fallback_name(tasks) } else { first.title.clone() };
        return DockApp { key: group.to_string(), name, pinned: false, launch, icon, active: windows.contains(&foreground), windows };
    }
    let packaged = first.app_id.as_deref().filter(|id| looks_packaged(id));
    // what the window asks to be started again with comes before its own program (see `tasklist::Relaunch`)
    let again = first.relaunch.as_ref();
    let launch = match (packaged, again, &first.exe) {
        (Some(id), _, _) => Some(Launch::Packaged(id.to_string())),
        (None, Some(r), _) => Some(Launch::Exe { path: r.program.clone(), args: r.args.clone() }),
        (None, None, Some(exe)) => Some(Launch::Exe { path: exe.clone(), args: String::new() }),
        (None, None, None) => None,
    };
    let icon = match (packaged, again, &first.exe) {
        (Some(id), _, _) => IconSource::Packaged(id.to_string()),
        (None, Some(r), _) => relaunch_icon(r, first.exe.as_ref(), has_icon),
        (None, None, Some(exe)) => IconSource::File(exe.clone()),
        (None, None, None) => IconSource::Window(first.hwnd),
    };
    DockApp { key: group.to_string(), name: fallback_name(tasks), pinned: false, launch, icon, active: windows.contains(&foreground), windows }
}

/// The middle island's items: the pinned apps in their given order (each with its windows when it is running), then the running apps
/// that are not pinned in the order of `groups` (the order the windows first appeared in), then a separator, then the Recycle Bin
/// and the Downloads folder. A group is taken by the first pin that matches it and by no other.
pub fn merge(pins: &[PinnedApp], groups: Vec<(String, Vec<Task>)>, foreground: isize) -> Vec<DockItem> {
    merge_with(pins, groups, foreground, super::iconload::has_own_icon_cached)
}

/// `merge` with the choice of which program files have an icon of their own injected (issue 436: a pin can name a launcher stub
/// whose shell picture is the generic document icon while its running window knows the real program).
fn merge_with(pins: &[PinnedApp], groups: Vec<(String, Vec<Task>)>, foreground: isize, has_icon: impl Fn(&Path) -> bool) -> Vec<DockItem> {
    let mut groups: Vec<Option<(String, Vec<Task>)>> = groups.into_iter().filter(|(_, t)| !t.is_empty()).map(Some).collect();
    let mut items = Vec::new();
    for pin in pins {
        let hit = groups.iter().position(|g| g.as_ref().is_some_and(|(k, t)| pin_matches(pin, k, t)));
        let (key, windows, running_icon) = match hit {
            Some(i) => {
                let (k, t) = groups[i].take().unwrap_or_default();
                let running_icon = if t.is_empty() { None } else { Some(running_app_with(&k, &t, foreground, &has_icon).icon) };
                (k, t.iter().map(|t| t.hwnd).collect::<Vec<_>>(), running_icon)
            }
            None => (pin.aumid.clone().or_else(|| pin.exe.clone()).unwrap_or_else(|| pin.name.to_lowercase()), Vec::new(), None),
        };
        // A pin's own icon still wins when it is a real icon (a shortcut's icon location, a program with resources). Only a file
        // without any icon of its own - the shell then hands out its generic document picture - yields to the running app's icon.
        let icon = match (&pin.icon, running_icon) {
            (IconSource::File(p), Some(better)) if !has_icon(p) => better,
            _ => pin.icon.clone(),
        };
        items.push(DockItem::App(DockApp {
            key,
            name: pin.name.clone(),
            pinned: true,
            launch: Some(pin.launch.clone()),
            icon,
            active: windows.contains(&foreground),
            windows,
        }));
    }
    for (k, t) in groups.into_iter().flatten() {
        items.push(DockItem::App(running_app_with(&k, &t, foreground, &has_icon)));
    }
    items.push(DockItem::Separator);
    items.push(DockItem::Place(Place::RecycleBin));
    items.push(DockItem::Place(Place::Downloads));
    drop_lone_separator(&mut items);
    items
}

/// The middle island's items as the user wants them (a Discord request, 2026-11-28): the Recycle Bin and Downloads left out
/// (`hide_places`), the apps named in `ignored` left out ("chrome.exe, Spotify": a program's file name or the app's name, any case,
/// separated by commas or semicolons), and a line between the pinned apps and the running ones that are not pinned (`divider`). Pure.
pub fn shape(items: Vec<DockItem>, hide_places: bool, ignored: &str, divider: bool) -> Vec<DockItem> {
    let ignored: Vec<String> = ignored.split([',', ';']).map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty()).collect();
    let is_ignored = |a: &DockApp| {
        let file = match &a.launch {
            Some(Launch::Exe { path, .. }) => path.file_name().map(|n| n.to_string_lossy().to_lowercase()),
            Some(Launch::Link(path)) => path.file_stem().map(|n| n.to_string_lossy().to_lowercase()),
            _ => None,
        };
        let name = a.name.to_lowercase();
        ignored.iter().any(|i| {
            // (a Store app has no program file to match: "spotify.exe" is matched by its name too)
            *i == name
                || i.strip_suffix(".exe") == Some(name.as_str())
                || file.as_deref().is_some_and(|f| f == i || f.strip_suffix(".exe") == Some(i.as_str()))
                || a.key.ends_with(&format!("\\{i}"))
                || a.key.ends_with(&format!("\\{i}.exe"))
        })
    };
    let mut out: Vec<DockItem> = items
        .into_iter()
        .filter(|i| match i {
            DockItem::Place(_) => !hide_places,
            DockItem::App(a) => !is_ignored(a),
            DockItem::Separator => true,
        })
        .collect();
    if hide_places {
        // (the line before the places separates nothing now)
        while matches!(out.last(), Some(DockItem::Separator)) {
            out.pop();
        }
    }
    if divider {
        let last_pinned = out.iter().rposition(|i| matches!(i, DockItem::App(a) if a.pinned));
        let first_running = out.iter().position(|i| matches!(i, DockItem::App(a) if !a.pinned));
        if let (Some(lp), Some(fr)) = (last_pinned, first_running)
            && fr == lp + 1
        {
            out.insert(fr, DockItem::Separator);
        }
    }
    out
}

/// The separator stands between the apps and the places: with no app before it, it separates nothing and goes (issue 160).
pub fn drop_lone_separator(items: &mut Vec<DockItem>) {
    if !items.iter().any(|i| matches!(i, DockItem::App(_))) {
        items.retain(|i| !matches!(i, DockItem::Separator));
    }
}

/// Puts the running groups in the order they were FIRST SEEN in, whatever order they come in now. The task list comes in Z order
/// (the active window first), so without this every click on a running app that is not pinned moved it to the front of the
/// running ones and its neighbours shifted. `seen` is the
/// island's memory: a group that is gone leaves it (and takes the end if it comes back, as on the taskbar), a new one joins at the
/// end, several new ones in the order given.
pub fn keep_order(seen: &mut Vec<String>, groups: Vec<(String, Vec<Task>)>) -> Vec<(String, Vec<Task>)> {
    seen.retain(|k| groups.iter().any(|(g, t)| g == k && !t.is_empty()));
    for (k, t) in &groups {
        if !t.is_empty() && !seen.contains(k) {
            seen.push(k.clone());
        }
    }
    let place = |k: &str| seen.iter().position(|s| s == k).unwrap_or(usize::MAX);
    let mut groups = groups;
    // (stable: groups with no window keep their place among themselves at the end; `merge` drops them)
    groups.sort_by_key(|(k, _)| place(k));
    groups
}

/// The `hover` slots of an item list: one per item, icons for apps and places, a separator for the line.
pub fn slots(items: &[DockItem]) -> Vec<super::hover::Slot> {
    items.iter().map(|i| if matches!(i, DockItem::Separator) { super::hover::Slot::Separator } else { super::hover::Slot::Icon }).collect()
}

#[cfg(test)]
mod shape_tests {
    use super::*;

    fn app(name: &str, exe: &str, pinned: bool) -> DockItem {
        DockItem::App(DockApp {
            key: format!("c:\\apps\\{exe}"),
            name: name.into(),
            pinned,
            launch: Some(Launch::Exe { path: PathBuf::from(format!("C:\\Apps\\{exe}")), args: String::new() }),
            icon: IconSource::Window(0),
            windows: Vec::new(),
            active: false,
        })
    }

    fn names(items: &[DockItem]) -> Vec<String> {
        items
            .iter()
            .map(|i| match i {
                DockItem::App(a) => a.name.clone(),
                DockItem::Separator => "|".into(),
                DockItem::Place(p) => format!("{p:?}"),
            })
            .collect()
    }

    #[test]
    fn the_middle_island_follows_the_users_choices() {
        let items = || vec![app("Code", "code.exe", true), app("Chrome", "chrome.exe", false), app("Spotify", "spotify.exe", false), DockItem::Separator, DockItem::Place(Place::RecycleBin), DockItem::Place(Place::Downloads)];
        assert_eq!(names(&shape(items(), false, "", false)), names(&items()), "nothing asked: as it was");
        assert_eq!(names(&shape(items(), true, "", false)), ["Code", "Chrome", "Spotify"], "no places, and no line before them");
        assert_eq!(names(&shape(items(), false, "chrome.exe; SPOTIFY", false)), ["Code", "|", "RecycleBin", "Downloads"], "by file name or by name");
        assert_eq!(names(&shape(items(), true, "chrome", true)), ["Code", "|", "Spotify"], "a line between the pinned and the running");
        assert_eq!(names(&shape(items(), true, "spotify, chrome", true)), ["Code"], "no running app left: no line");
        let store = || {
            vec![DockItem::App(DockApp {
                key: "SpotifyAB.SpotifyMusic_zpdnekdrzrea0!Spotify".into(),
                name: "Spotify".into(),
                pinned: true,
                launch: Some(Launch::Packaged("SpotifyAB.SpotifyMusic_zpdnekdrzrea0!Spotify".into())),
                icon: IconSource::Window(0),
                windows: Vec::new(),
                active: false,
            })]
        };
        assert!(shape(store(), true, "Spotify.exe", false).is_empty(), "a Store app by the program name people know");
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Issue 887: Windows keeps a picture for each state of the bin, and they are not the same one.
    #[test]
    fn the_recycle_bin_has_its_own_picture_for_full_and_for_empty() {
        let (full, empty) = (recycle_bin_icon(true), recycle_bin_icon(false));
        let (Some(IconSource::Resource { file: ff, index: fi }), Some(IconSource::Resource { file: ef, index: ei })) = (full, empty) else {
            panic!("no DefaultIcon for the bin's states");
        };
        assert!(ff.exists() && ef.exists(), "{ff:?} {ef:?}");
        assert!(!ff.to_string_lossy().contains('%'), "environment variables expanded");
        assert_ne!((&ff, fi), (&ef, ei));
        // and the picture itself comes from the file, not from the shell's icon cache
        let got = crate::dock::iconload::load_levels(&[IconSource::Resource { file: ff, index: fi }], &[64]).expect("the full bin's picture");
        assert_eq!(got.levels[0].width, 64);
    }

    fn task(hwnd: isize, exe: &str, id: Option<&str>) -> Task {
        Task { hwnd, title: format!("w{hwnd}"), pid: hwnd as u32, exe: Some(PathBuf::from(exe)), app_id: id.map(String::from), minimized: false, relaunch: None }
    }

    fn group(tasks: Vec<Task>) -> (String, Vec<Task>) {
        let k = tasks[0].group();
        (k, tasks)
    }

    fn pin(name: &str, exe: Option<&str>, id: Option<&str>) -> PinnedApp {
        PinnedApp {
            name: name.into(),
            aumid: id.map(|s| s.to_lowercase()),
            exe: exe.map(|s| s.to_lowercase()),
            launch: Launch::Link(PathBuf::from(format!(r"C:\pins\{name}.lnk"))),
            icon: IconSource::File(PathBuf::from(exe.unwrap_or("x.exe"))),
        }
    }

    #[test]
    fn running_apps_keep_the_order_they_were_first_seen_in_when_one_is_activated() {
        let keys = |g: &[(String, Vec<Task>)]| g.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>();
        let terminal = || group(vec![task(1, r"C:\t\terminal.exe", None)]);
        let discord = || group(vec![task(2, r"C:\d\discord.exe", None)]);
        let notepad = || group(vec![task(3, r"C:\n\notepad.exe", None)]);
        let mut seen = Vec::new();
        // first look: the Z order of that moment is the order
        let first = keep_order(&mut seen, vec![terminal(), discord()]);
        let order = keys(&first);
        // Discord is clicked: it is now first in Z order, and nothing moves
        assert_eq!(keys(&keep_order(&mut seen, vec![discord(), terminal()])), order);
        // a new app joins at the end, wherever it is in Z order
        let with_new = keep_order(&mut seen, vec![notepad(), discord(), terminal()]);
        assert_eq!(keys(&with_new)[..2], order[..]);
        assert_eq!(keys(&with_new).len(), 3);
        // the first app closes: the others close the gap in the same order; when it comes back it takes the end
        let without = keep_order(&mut seen, vec![notepad(), discord()]);
        assert_eq!(keys(&without), vec![order[1].clone(), keys(&with_new)[2].clone()]);
        let back = keep_order(&mut seen, vec![terminal(), notepad(), discord()]);
        assert_eq!(keys(&back)[2], order[0]);
        // the same list twice changes nothing; a group with no window is not remembered
        assert_eq!(keys(&keep_order(&mut seen, vec![discord(), terminal(), notepad()])), keys(&back));
        let mut empty_seen = Vec::new();
        keep_order(&mut empty_seen, vec![("x".to_string(), Vec::new())]);
        assert!(empty_seen.is_empty());
    }

    fn app_of(key: &str, launch: Option<Launch>, icon: IconSource) -> DockApp {
        DockApp { key: key.into(), name: "x".into(), pinned: false, launch, icon, windows: vec![1], active: false }
    }

    #[test]
    fn a_launcher_without_an_icon_does_not_hide_the_window_programs_icon() {
        let r = Relaunch { program: PathBuf::from(r"C:\apps\argus-launcher.exe"), args: String::new(), name: None, icon: None };
        let exe = PathBuf::from(r"C:\apps\argus-admin.exe");
        assert_eq!(relaunch_icon(&r, Some(&exe), |p| p == exe.as_path()), IconSource::File(exe.clone()), "a stub yields to the window's program");
        assert_eq!(relaunch_icon(&r, Some(&exe), |_| true), IconSource::File(r.program.clone()), "a launcher with its own icon still wins");
        assert_eq!(relaunch_icon(&r, None, |_| false), IconSource::File(r.program.clone()), "with no window program there is nothing better");
    }

    #[test]
    fn a_pin_to_an_iconless_launcher_uses_the_running_programs_icon() {
        let stub = r"C:\apps\argus-launcher.exe";
        let real = r"C:\apps\argus-admin.exe";
        let window = || {
            let mut t = task(7, real, Some("dev.argus.taskmanager"));
            t.relaunch = Some(Relaunch { program: PathBuf::from(stub), args: String::new(), name: None, icon: None });
            t
        };
        let pins = vec![pin("Argus", Some(stub), None)];
        let items = merge_with(&pins, vec![group(vec![window()])], 0, |p| !p.to_string_lossy().contains("launcher"));
        assert_eq!(apps(&items)[0].icon, IconSource::File(PathBuf::from(real)), "a pinned stub yields to the window's program");
        let items = merge_with(&pins, vec![group(vec![window()])], 0, |_| true);
        assert_eq!(apps(&items)[0].icon, IconSource::File(PathBuf::from(stub)), "a launcher with its own icon keeps the pin's");
    }

    #[test]
    fn a_jump_list_is_looked_up_by_the_packaged_id_and_the_program_whichever_the_app_has() {
        let exe = PathBuf::from(r"C:\a\Code.exe");
        // a classic program started from its file
        let (aumid, found) = jump_identity(&app_of(r"c:\a\code.exe", Some(Launch::Exe { path: exe.clone(), args: String::new() }), IconSource::Window(1)));
        assert_eq!((aumid, found), (None, Some(exe.clone())));
        // a packaged app: its id, and no program
        let (aumid, found) = jump_identity(&app_of("microsoft.paint_8wekyb3d8bbwe!app", Some(Launch::Packaged("Microsoft.Paint_8wekyb3d8bbwe!App".into())), IconSource::Window(1)));
        assert_eq!((aumid.as_deref(), found), (Some("Microsoft.Paint_8wekyb3d8bbwe!App"), None));
        // a running app whose launch is not known: the id from its key, the program from an icon that is an .exe (not from any other file)
        let (aumid, found) = jump_identity(&app_of("vendor.app_abc!main", None, IconSource::File(exe.clone())));
        assert_eq!((aumid.as_deref(), found), (Some("vendor.app_abc!main"), Some(exe)));
        let (aumid, found) = jump_identity(&app_of("pid:42", None, IconSource::File(PathBuf::from(r"C:\a\doc.txt"))));
        assert_eq!((aumid, found), (None, None));
    }

    fn apps(items: &[DockItem]) -> Vec<&DockApp> {
        items.iter().filter_map(|i| if let DockItem::App(a) = i { Some(a) } else { None }).collect()
    }

    #[test]
    fn pinned_first_in_their_order_then_the_other_running_apps_then_the_places() {
        let pins = vec![pin("Chrome", Some(r"C:\a\chrome.exe"), None), pin("Code", Some(r"C:\b\code.exe"), Some("Microsoft.VisualStudioCode")), pin("Paint", Some(r"C:\c\mspaint.exe"), None)];
        let groups = vec![
            group(vec![task(10, r"C:\z\notepad.exe", None)]),
            group(vec![task(11, r"C:\b\code.exe", Some("Microsoft.VisualStudioCode")), task(12, r"C:\b\code.exe", Some("Microsoft.VisualStudioCode"))]),
            group(vec![task(13, r"C:\a\Chrome.exe", None)]),
            group(vec![task(14, r"C:\y\other.exe", None)]),
        ];
        let items = merge(&pins, groups, 12);
        let a = apps(&items);
        assert_eq!(a.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), vec!["Chrome", "Code", "Paint", "Notepad", "Other"]);
        assert_eq!(a.iter().map(|a| a.pinned).collect::<Vec<_>>(), vec![true, true, true, false, false]);
        assert_eq!(a[0].windows, vec![13]);
        assert_eq!(a[1].windows, vec![11, 12]);
        assert!(a[2].windows.is_empty(), "Paint is pinned and not running");
        assert!(a[1].active && !a[0].active && !a[3].active);
        assert_eq!(items[5], DockItem::Separator);
        assert_eq!(items[6], DockItem::Place(Place::RecycleBin));
        assert_eq!(items[7], DockItem::Place(Place::Downloads));
        assert_eq!(items.len(), 8);
    }

    #[test]
    fn the_control_panel_is_not_file_explorer() {
        let explorer = r"C:\Windows\explorer.exe";
        let items = merge(&[], vec![group(vec![task(1, explorer, Some("Microsoft.Windows.ControlPanel"))]), group(vec![task(2, explorer, None)])], 0);
        let apps: Vec<&DockApp> = items.iter().filter_map(|i| if let DockItem::App(a) = i { Some(a) } else { None }).collect();
        assert_eq!(apps[0].icon, IconSource::Shell("shell:ControlPanelFolder".into()));
        assert_eq!(apps[0].name, "w1", "the window's title, not \"Explorer\"");
        assert_eq!(apps[1].icon, IconSource::File(PathBuf::from(explorer)), "a folder window stays File Explorer");
    }

    #[test]
    fn a_running_group_is_taken_by_one_pin_only() {
        // two pins of the same program (two profiles): the first takes the windows, the second is just a launcher
        let pins = vec![pin("Chrome", Some(r"C:\a\chrome.exe"), None), pin("Chrome (work)", Some(r"C:\a\chrome.exe"), None)];
        let items = merge(&pins, vec![group(vec![task(1, r"C:\a\chrome.exe", None)])], 0);
        let a = apps(&items);
        assert_eq!(a.len(), 2);
        assert_eq!(a[0].windows, vec![1]);
        assert!(a[1].windows.is_empty());
    }

    #[test]
    fn a_pin_matches_by_app_id_then_by_program() {
        let t = |exe: &str, id: Option<&str>| vec![task(1, exe, id)];
        let p = pin("X", Some(r"C:\x\x.exe"), Some("Vendor.X"));
        assert!(pin_matches(&p, "vendor.x", &t(r"C:\other.exe", Some("Vendor.X"))), "same app id");
        assert!(pin_matches(&p, "something.else", &t(r"C:\X\x.exe", Some("Something.Else"))), "the window names itself differently: same program");
        assert!(!pin_matches(&p, "vendor.y", &t(r"C:\y\y.exe", Some("Vendor.Y"))));
        let no_exe = pin("Store app", None, Some("Pkg_abc!App"));
        assert!(pin_matches(&no_exe, "pkg_abc!app", &[]));
        assert!(!pin_matches(&no_exe, r"c:\x\x.exe", &t(r"C:\x\x.exe", None)));
        // a pin with a program path equal to the group key (a window without an app id)
        let q = pin("Q", Some(r"C:\q\q.exe"), None);
        assert!(pin_matches(&q, r"c:\q\q.exe", &t(r"C:\q\q.exe", None)));
    }

    #[test]
    fn a_window_that_names_what_starts_it_again_is_that_program() {
        use crate::tasklist::relaunch_of;
        // Steam: the window is the helper's, it names steam.exe
        let mut w = task(7, "C:/Steam/bin/cef/steamwebhelper.exe", Some("Valve.Steam.Client"));
        w.relaunch = relaunch_of(r#""C:/Steam/steam.exe" -foreground"#, Some("@C:/Steam/steam.exe,-1".into()));
        let items = merge(&[], vec![group(vec![w.clone()])], 0);
        let DockItem::App(a) = &items[0] else { panic!("an app") };
        assert_eq!(a.launch, Some(Launch::Exe { path: PathBuf::from("C:/Steam/steam.exe"), args: "-foreground".into() }));
        assert_eq!(a.name, "Steam", "named after what is started, not after the helper");
        let chosen = |has_icon: fn(&Path) -> bool| running_app_with("valve.steam.client", &[w.clone()], 0, has_icon).icon;
        assert_eq!(chosen(|_| true), IconSource::File(PathBuf::from("C:/Steam/steam.exe")), "a launcher with an icon still supplies it");
        assert_eq!(chosen(|_| false), IconSource::File(PathBuf::from("C:/Steam/bin/cef/steamwebhelper.exe")), "a stub without one does not");
        // a pin of steam.exe (Steam's own shortcut) takes that window: not a pin and a second, running Steam
        let steam = pin("Steam", Some("c:/steam/steam.exe"), None);
        assert!(pin_matches(&steam, "valve.steam.client", &[w.clone()]));
        let other = pin("Other", Some("c:/o/o.exe"), None);
        assert!(!pin_matches(&other, "valve.steam.client", &[w]));
    }

    #[test]
    fn packaged_apps_start_by_their_id_and_others_by_their_program() {
        let items = merge(
            &[],
            vec![
                group(vec![task(1, r"C:\Windows\System32\ApplicationFrameHost.exe", Some("Microsoft.WindowsCalculator_8wekyb3d8bbwe!App"))]),
                group(vec![task(2, r"C:\p\chrome.exe", Some("Chrome"))]),
            ],
            0,
        );
        let a = apps(&items);
        assert_eq!(a[0].launch, Some(Launch::Packaged("Microsoft.WindowsCalculator_8wekyb3d8bbwe!App".into())));
        assert_eq!(a[0].icon, IconSource::Packaged("Microsoft.WindowsCalculator_8wekyb3d8bbwe!App".into()));
        assert_eq!(a[1].launch, Some(Launch::Exe { path: PathBuf::from(r"C:\p\chrome.exe"), args: String::new() }));
        assert_eq!(a[1].icon, IconSource::File(PathBuf::from(r"C:\p\chrome.exe")));
        assert_eq!(a[1].name, "Chrome");
    }

    #[test]
    fn a_program_nobody_can_name_still_gets_a_button() {
        let t = Task { hwnd: 5, title: "Secret".into(), pid: 9, exe: None, app_id: None, minimized: false, relaunch: None };
        let items = merge(&[], vec![group(vec![t])], 0);
        let a = apps(&items);
        assert_eq!(a.len(), 1);
        assert_eq!(a[0].launch, None);
        assert_eq!(a[0].icon, IconSource::Window(5));
        assert_eq!(a[0].name, "Secret");
        assert_eq!(a[0].key, "pid:9");
    }

    #[test]
    fn a_web_app_and_its_browser_keep_their_own_windows() {
        const CHROME: &str = r"C:\Program Files\Google\Chrome\Application\chrome.exe";
        let browser = pin("Chrome", Some(CHROME), Some("Chrome"));
        let web = pin("NotebookLM", Some(r"C:\Program Files\Google\Chrome\Application\chrome_proxy.exe"), Some("Chrome._crx_abcdefghijklmnop"));
        let app_window = task(1, CHROME, Some("Chrome._crx_abcdefghijklmnop"));
        let tab = task(2, CHROME, Some("Chrome"));
        // the web app's window goes to its own pin, though the browser's pin comes first and runs the same program
        let items = merge(&[browser.clone(), web.clone()], vec![group(vec![tab.clone()]), group(vec![app_window])], 0);
        let windows = |i: usize| match &items[i] {
            DockItem::App(a) => a.windows.clone(),
            _ => panic!("not an app"),
        };
        assert_eq!(windows(0), vec![2], "the browser has its own window only");
        assert_eq!(windows(1), vec![1], "the web app has its window");
        // the web app closed: its pin does not take the browser's window
        let items = merge(&[web, browser], vec![group(vec![tab])], 0);
        assert!(matches!(&items[0], DockItem::App(a) if a.windows.is_empty()));
        assert!(matches!(&items[1], DockItem::App(a) if a.windows == vec![2]));
    }

    #[test]
    fn no_pins_no_windows_leaves_the_places_alone() {
        // (no app: nothing for the separator to separate, issue 160)
        let items = merge(&[], vec![], 0);
        assert_eq!(items, vec![DockItem::Place(Place::RecycleBin), DockItem::Place(Place::Downloads)]);
    }

    #[test]
    fn click_decision() {
        assert_eq!(click_action(&[], 7), ClickAction::Start, "not running: start it");
        assert_eq!(click_action(&[3, 4], 9), ClickAction::Raise(3), "running, not in front: its last used window");
        assert_eq!(click_action(&[3, 4], 4), ClickAction::Minimize(4), "in front: minimise the one in front");
        assert_eq!(click_action(&[3, 4], 3), ClickAction::Minimize(3));
        assert_eq!(click_action(&[3], 0), ClickAction::Raise(3), "nothing in front at all");
        assert_eq!(middle_click_action(), ClickAction::Start, "middle click: another instance");
    }

    // The shapes below are what this machine has: the taskbar pins Telegram and Spotify by package id; their windows set no id of their
    // own, their processes' packages carry it (`identity::process_aumid`); WhatsApp is running and not pinned.
    const TELEGRAM: &str = "TelegramMessengerLLP.TelegramDesktop_t4vj0pshhgkwm!Telegram.TelegramDesktop.Store";
    const SPOTIFY: &str = "SpotifyAB.SpotifyMusic_zpdnekdrzrea0!Spotify";
    const WHATSAPP: &str = "5319275A.WhatsAppDesktop_cv1g1gvanyjgm!App";

    fn packaged_pin(name: &str, id: &str) -> PinnedApp {
        PinnedApp { name: name.into(), aumid: Some(id.to_lowercase()), exe: None, launch: Launch::Packaged(id.into()), icon: IconSource::Packaged(id.into()) }
    }

    #[test]
    fn a_packaged_app_is_one_item_whether_pinned_or_not() {
        let pins = vec![packaged_pin("Telegram Desktop", TELEGRAM), packaged_pin("Spotify", SPOTIFY)];
        let tasks = vec![
            task(10, r"C:\Program Files\WindowsApps\telegrammessengerllp.telegramdesktop_7.3.3.0_x64__t4vj0pshhgkwm\telegram.exe", None),
            task(11, r"C:\Program Files\WindowsApps\spotifyab.spotifymusic_1.308.620.0_x64__zpdnekdrzrea0\spotify.exe", None),
            task(12, r"C:\Program Files\WindowsApps\5319275a.whatsappdesktop_2.2642.101.0_x64__cv1g1gvanyjgm\whatsapp.root.exe", None),
        ];
        let ids = |pid: u32| match pid {
            10 => Some(TELEGRAM.to_string()),
            11 => Some(SPOTIFY.to_string()),
            12 => Some(WHATSAPP.to_string()),
            _ => None,
        };
        let items = merge(&pins, crate::tasklist::grouped(super::super::identity::with_process_ids(tasks, ids)), 0);
        let a = apps(&items);
        assert_eq!(a.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), vec!["Telegram Desktop", "Spotify", "Whatsapp.root"], "no second Telegram or Spotify");
        assert_eq!(a[0].windows, vec![10]);
        assert_eq!(a[1].windows, vec![11]);
        assert!(a[0].pinned && a[1].pinned && !a[2].pinned);
        // WhatsApp's icon is its package's logo, not the picture of an exe the shell cannot open
        assert_eq!(a[2].icon, IconSource::Packaged(WHATSAPP.into()));
        assert_eq!(a[2].launch, Some(Launch::Packaged(WHATSAPP.into())));
        // the same windows WITHOUT the process ids are the bug that was seen: two items for each app
        let tasks = vec![task(10, r"C:\Program Files\WindowsApps\telegrammessengerllp.telegramdesktop_7.3.3.0_x64__t4vj0pshhgkwm\telegram.exe", None)];
        let items = merge(&pins[..1], crate::tasklist::grouped(tasks), 0);
        assert_eq!(apps(&items).len(), 2, "the id is what lets the pin and the window meet");
    }

    #[test]
    fn a_pin_and_a_window_that_name_the_same_id_in_other_case_still_meet() {
        let p = packaged_pin("Spotify", SPOTIFY);
        assert!(pin_matches(&p, &SPOTIFY.to_lowercase(), &[]));
        assert!(!pin_matches(&p, &TELEGRAM.to_lowercase(), &[]), "another package");
        assert!(!pin_matches(&p, "spotifyab.spotifymusic_zpdnekdrzrea0!other", &[]), "another app of the same package is another app");
    }

    #[test]
    fn the_icon_chain_tries_the_app_then_its_windows_then_its_package() {
        let t = |h: isize| task(h, r"C:\x\a.exe", None);
        let app = |a: Vec<DockItem>| match a.into_iter().next() {
            Some(DockItem::App(a)) => a,
            _ => panic!("an app"),
        };
        // a plain program: its icon, then up to three of its windows
        let plain = app(merge(&[], vec![group(vec![t(1), t(2), t(3), t(4)])], 0));
        assert_eq!(plain.icon_chain(), vec![IconSource::File(PathBuf::from(r"C:\x\a.exe")), IconSource::Window(1), IconSource::Window(2), IconSource::Window(3)]);
        // a packaged app: its logo is the app's own icon, so it is not asked for twice
        let pk = app(merge(&[], vec![group(vec![task(9, r"C:\p\telegram.exe", Some(TELEGRAM))])], 0));
        assert_eq!(pk.icon_chain(), vec![IconSource::Packaged(TELEGRAM.into()), IconSource::Window(9)]);
        // a pinned program that is not running: only its own icon
        let idle = app(merge(&[pin("Idle", Some(r"C:\i\i.exe"), None)], vec![], 0));
        assert_eq!(idle.icon_chain().len(), 1);
        // a pin with a program path whose windows can supply what the shell cannot: its package logo comes last
        let mut packaged_pin_running = app(merge(&[pin("P", Some(r"C:\i\i.exe"), Some("Pkg.Name_abcdefghijklm!App"))], vec![group(vec![t(5)])], 0));
        packaged_pin_running.windows = vec![5];
        assert_eq!(packaged_pin_running.icon_chain().last(), Some(&IconSource::Packaged("pkg.name_abcdefghijklm!app".into())));
        // ... but a picture the user gave the pin is never replaced by the package logo (issue 785)
        packaged_pin_running.icon = IconSource::File(PathBuf::from(r"C:\icons\mine.ico"));
        assert!(!packaged_pin_running.icon_chain().iter().any(|s| matches!(s, IconSource::Packaged(_))));
    }

    #[test]
    fn a_pin_with_a_picture_of_its_own_keeps_it_while_the_app_runs() {
        // issue 785: the .ico has no icon resources; the merge must not take it for a file without an icon
        let mut p = pin("Firefox", Some(r"C:\f\firefox.exe"), None);
        p.icon = IconSource::File(PathBuf::from(r"C:\icons\fox.ico"));
        let picture_is_an_icon = |f: &Path| super::super::iconload::is_picture_file(f);
        let items = merge_with(&[p], vec![group(vec![task(7, r"C:\f\firefox.exe", None)])], 0, picture_is_an_icon);
        match items.into_iter().next() {
            Some(DockItem::App(a)) => assert_eq!(a.icon, IconSource::File(PathBuf::from(r"C:\icons\fox.ico"))),
            _ => panic!("an app"),
        }
        assert!(super::super::iconload::is_picture_file(Path::new(r"C:\a\B.ICO")));
        assert!(!super::super::iconload::is_picture_file(Path::new(r"C:\a\b.exe")));
    }

    #[test]
    fn packaged_ids_are_recognised() {
        assert!(looks_packaged("Microsoft.WindowsCalculator_8wekyb3d8bbwe!App"));
        assert!(looks_packaged("SpotifyAB.SpotifyMusic_zpdnekdrzrea0!Spotify"));
        assert!(!looks_packaged("Chrome"));
        assert!(!looks_packaged("Microsoft.Windows.Explorer"));
        assert!(!looks_packaged(r"C:\Program Files\x_y!z.exe"));
        assert!(!looks_packaged("Pkg_abc!"));
    }

    #[test]
    fn slots_follow_the_items() {
        let items = merge(&[pin("A", Some("a.exe"), None)], vec![], 0);
        use super::super::hover::Slot::*;
        assert_eq!(slots(&items), vec![Icon, Separator, Icon, Icon]);
    }

    #[test]
    fn places_know_their_icon_and_open_argument() {
        assert_eq!(Place::RecycleBin.open_argument(), "shell:RecycleBinFolder");
        assert!(!Place::Downloads.open_argument().is_empty());
        assert!(matches!(Place::RecycleBin.icon_source(), IconSource::Shell(_)));
    }
}