Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

29.7 KB
Raw Blame
//! What RustCord's installer and uninstaller share: where things go, the
//! shortcuts, the "Installed apps" entry, finding a running RustCord, and the
//! windows they show. Everything is per user (no administrator rights): the
//! program in `%LOCALAPPDATA%\Programs\RustCord`, shortcuts in the user's
//! Start menu and desktop, and the uninstall entry under HKEY_CURRENT_USER.
#![cfg(windows)]

use std::cell::{Cell, RefCell};
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use windows::core::{w, Interface, GUID, HRESULT, HSTRING, PCWSTR, PWSTR};
use windows::Win32::Foundation::{CloseHandle, BOOL, HWND, LPARAM, S_FALSE, S_OK, WPARAM};
use windows::Win32::Security::Credentials::{CredDeleteW, CredEnumerateW, CredFree, CREDENTIALW, CRED_ENUMERATE_FLAGS, CRED_TYPE_GENERIC};
use windows::Win32::System::SystemInformation::GetSystemDirectoryW;
use windows::Win32::System::Com::{CoCreateInstance, CoInitializeEx, CoTaskMemFree, IPersistFile, CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED};
use windows::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS};
use windows::Win32::System::LibraryLoader::{GetModuleHandleW, SetDefaultDllDirectories, LOAD_LIBRARY_SEARCH_SYSTEM32};
use windows::Win32::System::Registry::{
    RegCloseKey, RegCreateKeyExW, RegDeleteTreeW, RegGetValueW, RegSetValueExW, HKEY, HKEY_CURRENT_USER, KEY_WRITE, REG_DWORD, REG_OPTION_NON_VOLATILE, REG_SZ, REG_VALUE_TYPE, RRF_RT_REG_DWORD, RRF_RT_REG_SZ,
};
use windows::Win32::System::Threading::{OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION};
use windows::Win32::UI::Controls::{
    TaskDialogIndirect, TASKDIALOGCONFIG, TASKDIALOG_BUTTON, TASKDIALOG_NOTIFICATIONS, TDE_CONTENT, TDF_ALLOW_DIALOG_CANCELLATION, TDF_CALLBACK_TIMER, TDF_SHOW_PROGRESS_BAR, TDF_USE_HICON_MAIN,
    TDF_VERIFICATION_FLAG_CHECKED, TDM_ENABLE_BUTTON, TDM_NAVIGATE_PAGE, TDM_SET_ELEMENT_TEXT, TDM_SET_PROGRESS_BAR_POS, TDM_SET_PROGRESS_BAR_RANGE, TDN_BUTTON_CLICKED, TDN_TIMER, TDN_VERIFICATION_CLICKED,
    TD_ERROR_ICON, TD_INFORMATION_ICON, TD_WARNING_ICON,
};
use windows::Win32::UI::Shell::{
    FOLDERID_Desktop, FOLDERID_Programs, FOLDERID_RoamingAppData, FOLDERID_UserProgramFiles, FileOpenDialog, IFileOpenDialog, IShellItem, IShellLinkW, SHCreateItemFromParsingName, SHGetKnownFolderPath,
    SHChangeNotify, ShellLink, SHCNE_ASSOCCHANGED, SHCNF_IDLIST, FOS_FORCEFILESYSTEM, FOS_PICKFOLDERS, KF_FLAG_CREATE, SIGDN_FILESYSPATH,
};
use windows::Win32::UI::WindowsAndMessaging::{FindWindowExW, GetWindowThreadProcessId, LoadIconW, RegisterWindowMessageW, SendMessageTimeoutW, SendMessageW, SMTO_ABORTIFHUNG};

pub const APP: &str = "RustCord";
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const EXE: &str = "rustcord.exe";
pub const UNINSTALLER: &str = "rustcord-uninstall.exe";
const UNINSTALL_KEY: &str = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RustCord";
/// What the installer and RustCord both read: `AutoUpdate` (a DWORD, 0 = off;
/// missing = on).
const SETTINGS_KEY: &str = "Software\\RustCord";
const AUTO_UPDATE: &str = "AutoUpdate";
/// RustCord's Discord logins in Windows' Credential Manager: one per account,
/// `discord-token:<id>.RustCord` (and `discord-token.RustCord` from single-
/// login versions). Found by this prefix and suffix.
const LOGIN_PREFIX: &str = "discord-token";
const LOGIN_SUFFIX: &str = ".RustCord";
/// Don't flash a console window for helper commands.
const CREATE_NO_WINDOW: u32 = 0x0800_0000;

/// Command-line switches both programs understand.
pub struct Options {
    /// `/S`: no questions, no messages (for scripts).
    pub silent: bool,
    /// `--dir <folder>`: install somewhere other than the default.
    pub dir: Option<PathBuf>,
    /// `--no-desktop`: no desktop shortcut.
    pub no_desktop: bool,
    /// `--no-launch`: don't offer to start RustCord afterwards.
    pub no_launch: bool,
    /// `--auto-update` / `--no-auto-update`: whether RustCord updates itself
    /// (a silent install otherwise keeps what was chosen before).
    pub auto_update: Option<bool>,
    /// Uninstaller: also delete settings, cache and the saved login.
    pub delete_data: bool,
    /// Uninstaller only: the copy in %TEMP% removing this folder.
    pub remove: Option<PathBuf>,
}

impl Options {
    pub fn from_args() -> Self {
        let mut o = Self { silent: false, dir: None, no_desktop: false, no_launch: false, auto_update: None, delete_data: false, remove: None };
        let mut args = std::env::args().skip(1);
        while let Some(a) = args.next() {
            match a.to_ascii_lowercase().as_str() {
                "/s" | "-s" | "--silent" => o.silent = true,
                "--dir" => o.dir = args.next().map(|d| absolute(Path::new(&d))),
                "--no-desktop" => o.no_desktop = true,
                "--no-launch" => o.no_launch = true,
                "--auto-update" => o.auto_update = Some(true),
                "--no-auto-update" => o.auto_update = Some(false),
                "--delete-data" => o.delete_data = true,
                "--remove" => o.remove = args.next().map(PathBuf::from),
                _ => {}
            }
        }
        o
    }
}

fn absolute(p: &Path) -> PathBuf {
    std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf())
}

/// The same folder? (Windows paths: case and a trailing `\` don't matter.)
pub fn same_path(a: &Path, b: &Path) -> bool {
    let norm = |p: &Path| absolute(p).to_string_lossy().trim_end_matches(['\\', '/']).to_lowercase();
    norm(a) == norm(b)
}

/// DLLs that Windows' own parts load by name later on (the dialogs, the shell)
/// come from System32 only, never from the folder this program was saved to
/// (Downloads, %TEMP%). The first thing each program does.
pub fn system_dlls_only() {
    // SAFETY: a process-wide setting with no pointers involved.
    unsafe {
        let _ = SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_SYSTEM32);
    }
}

pub fn init_com() {
    // SAFETY: once per thread that uses COM.
    unsafe {
        let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
    }
}

fn known_folder(id: &GUID) -> Option<PathBuf> {
    // SAFETY: the returned string is copied, then freed as the API requires.
    unsafe {
        let p = SHGetKnownFolderPath(id, KF_FLAG_CREATE, None).ok()?;
        let s = p.to_string().ok();
        CoTaskMemFree(Some(p.0 as *const _));
        s.map(PathBuf::from)
    }
}

/// `%LOCALAPPDATA%\Programs\RustCord`.
pub fn default_dir() -> Option<PathBuf> {
    known_folder(&FOLDERID_UserProgramFiles).map(|p| p.join(APP))
}

pub fn start_menu_link() -> Option<PathBuf> {
    known_folder(&FOLDERID_Programs).map(|p| p.join("RustCord.lnk"))
}

pub fn desktop_link() -> Option<PathBuf> {
    known_folder(&FOLDERID_Desktop).map(|p| p.join("RustCord.lnk"))
}

/// A shortcut (.lnk) at `link` to `target`, starting in the target's folder.
pub fn create_shortcut(link: &Path, target: &Path) -> Result<(), String> {
    let wide = |p: &Path| HSTRING::from(p.as_os_str());
    // SAFETY: plain COM calls with valid, NUL-terminated strings.
    unsafe {
        let sl: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).map_err(|e| e.to_string())?;
        sl.SetPath(&wide(target)).map_err(|e| e.to_string())?;
        if let Some(dir) = target.parent() {
            sl.SetWorkingDirectory(&wide(dir)).map_err(|e| e.to_string())?;
        }
        sl.SetDescription(&HSTRING::from("RustCord: a native Discord client")).map_err(|e| e.to_string())?;
        sl.SetIconLocation(&wide(target), 0).map_err(|e| e.to_string())?;
        let file: IPersistFile = sl.cast().map_err(|e| e.to_string())?;
        file.Save(&wide(link), true).map_err(|e| e.to_string())
    }
}

/// Make Explorer drop its cached icons: after an update the shortcuts, the
/// Start menu and the taskbar would otherwise keep showing the old icon of
/// the exe they point at.
pub fn refresh_icons() {
    // SAFETY: a notification with no item lists.
    unsafe { SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, None, None) }
}

fn set_value(key: HKEY, name: &str, kind: REG_VALUE_TYPE, data: &[u8]) -> Result<(), String> {
    // SAFETY: `key` is open for writing; the data slice outlives the call.
    unsafe { RegSetValueExW(key, &HSTRING::from(name), 0, kind, Some(data)).ok().map_err(|e| e.to_string()) }
}

/// The entry in Settings → Apps → Installed apps (and Control Panel).
pub fn register_uninstaller(dir: &Path, size_kb: u32) -> Result<(), String> {
    let mut key = HKEY::default();
    // SAFETY: creates (or opens) a key under the user's own hive.
    unsafe {
        RegCreateKeyExW(HKEY_CURRENT_USER, &HSTRING::from(UNINSTALL_KEY), 0, PCWSTR::null(), REG_OPTION_NON_VOLATILE, KEY_WRITE, None, &mut key, None)
            .ok()
            .map_err(|e| e.to_string())?;
    }
    let exe = dir.join(EXE);
    let uninstall = dir.join(UNINSTALLER);
    let strings = [
        ("DisplayName", APP.to_string()),
        ("DisplayVersion", VERSION.to_string()),
        ("Publisher", "RustCord".to_string()),
        ("DisplayIcon", format!("{},0", exe.display())),
        ("InstallLocation", dir.display().to_string()),
        ("UninstallString", format!("\"{}\"", uninstall.display())),
        ("QuietUninstallString", format!("\"{}\" /S", uninstall.display())),
    ];
    let mut result = Ok(());
    for (name, value) in strings {
        // REG_SZ: UTF-16 with its terminating NUL.
        let bytes: Vec<u8> = value.encode_utf16().chain(std::iter::once(0)).flat_map(u16::to_le_bytes).collect();
        result = result.and(set_value(key, name, REG_SZ, &bytes));
    }
    for (name, value) in [("NoModify", 1u32), ("NoRepair", 1), ("EstimatedSize", size_kb)] {
        result = result.and(set_value(key, name, REG_DWORD, &value.to_le_bytes()));
    }
    // SAFETY: the key opened above.
    unsafe {
        let _ = RegCloseKey(key);
    }
    result
}

pub fn unregister_uninstaller() {
    // SAFETY: removes only RustCord's own key.
    unsafe {
        let _ = RegDeleteTreeW(HKEY_CURRENT_USER, &HSTRING::from(UNINSTALL_KEY));
    }
}

/// Whether RustCord keeps itself up to date (on unless turned off, in the
/// installer or in RustCord's Settings → About).
pub fn auto_update() -> bool {
    let mut value = 1u32;
    let mut bytes = 4u32;
    // SAFETY: a DWORD and its size in bytes.
    let read = unsafe {
        RegGetValueW(HKEY_CURRENT_USER, &HSTRING::from(SETTINGS_KEY), &HSTRING::from(AUTO_UPDATE), RRF_RT_REG_DWORD, None, Some((&mut value as *mut u32).cast()), Some(&mut bytes))
    };
    read.is_err() || value != 0
}

pub fn set_auto_update(on: bool) -> Result<(), String> {
    let mut key = HKEY::default();
    // SAFETY: creates (or opens) RustCord's own key under the user's hive.
    unsafe {
        RegCreateKeyExW(HKEY_CURRENT_USER, &HSTRING::from(SETTINGS_KEY), 0, PCWSTR::null(), REG_OPTION_NON_VOLATILE, KEY_WRITE, None, &mut key, None)
            .ok()
            .map_err(|e| e.to_string())?;
    }
    let result = set_value(key, AUTO_UPDATE, REG_DWORD, &u32::from(on).to_le_bytes());
    // SAFETY: the key opened above.
    unsafe {
        let _ = RegCloseKey(key);
    }
    result
}

/// A text value of the Installed apps entry, if RustCord is installed.
fn registered(value: &str) -> Option<String> {
    let mut buf = [0u16; 1024];
    let mut bytes = std::mem::size_of_val(&buf) as u32;
    // SAFETY: the buffer and its size in bytes are passed together.
    unsafe {
        RegGetValueW(HKEY_CURRENT_USER, &HSTRING::from(UNINSTALL_KEY), &HSTRING::from(value), RRF_RT_REG_SZ, None, Some(buf.as_mut_ptr().cast()), Some(&mut bytes)).ok().ok()?;
    }
    let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
    let s = String::from_utf16_lossy(&buf[..len]);
    (!s.is_empty()).then_some(s)
}

/// The folder the Installed apps entry points at: where RustCord was
/// installed last, if it was.
pub fn registered_dir() -> Option<PathBuf> {
    registered("InstallLocation").map(PathBuf::from)
}

/// The version installed in `dir`, when the Installed apps entry is about
/// that folder.
pub fn installed_version(dir: &Path) -> Option<String> {
    registered_dir().filter(|d| same_path(d, dir)).and_then(|_| registered("DisplayVersion"))
}

/// Is version `a` older than `b`? ("0.9.2" is older than "0.10".)
pub fn older(a: &str, b: &str) -> bool {
    let parts = |v: &str| v.split('.').map(|p| p.trim().parse::<u64>().unwrap_or(0)).collect::<Vec<_>>();
    let (mut a, mut b) = (parts(a), parts(b));
    let len = a.len().max(b.len());
    a.resize(len, 0);
    b.resize(len, 0);
    a < b
}

/// The process ids of RustCord running from `dir` (other RustCords, such as
/// a development build elsewhere, are none of the installer's business).
pub fn running_from(dir: &Path) -> Vec<u32> {
    // (One that was open during a silent update runs from the file that was
    // moved aside for it.)
    let files = [dir.join(EXE), dir.join(EXE).with_extension("old")];
    let mut pids = Vec::new();
    // SAFETY: the snapshot and process handles are closed; buffers carry their sizes.
    unsafe {
        let Ok(snap) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) else { return pids };
        let mut entry = PROCESSENTRY32W { dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32, ..Default::default() };
        let mut more = Process32FirstW(snap, &mut entry).is_ok();
        while more {
            let len = entry.szExeFile.iter().position(|&c| c == 0).unwrap_or(entry.szExeFile.len());
            if String::from_utf16_lossy(&entry.szExeFile[..len]).eq_ignore_ascii_case(EXE) {
                if let Ok(process) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, entry.th32ProcessID) {
                    let mut buf = [0u16; 1024];
                    let mut size = buf.len() as u32;
                    if QueryFullProcessImageNameW(process, PROCESS_NAME_WIN32, PWSTR(buf.as_mut_ptr()), &mut size).is_ok() {
                        let image = PathBuf::from(String::from_utf16_lossy(&buf[..size as usize]));
                        if files.iter().any(|f| same_path(&image, f)) {
                            pids.push(entry.th32ProcessID);
                        }
                    }
                    let _ = CloseHandle(process);
                }
            }
            more = Process32NextW(snap, &mut entry).is_ok();
        }
        let _ = CloseHandle(snap);
    }
    pids
}

/// Ask the RustCords with these process ids to quit as their tray menu's
/// Quit does, saving their settings: a message to their tray window (see
/// `QUIT_MESSAGE` in apps/rustcord/src/tray.rs). taskkill's polite close
/// can't do that: it only sends RustCord to the tray, and doesn't reach it
/// there. Whether any is quitting (versions before 0.4.41 don't know the
/// message).
fn ask_to_quit(pids: &[u32]) -> bool {
    let mut quitting = false;
    // SAFETY: plain window lookups and a message with no pointers in it.
    unsafe {
        let quit = RegisterWindowMessageW(w!("RustCordQuit"));
        let mut after = HWND::default();
        while let Ok(window) = FindWindowExW(None, after, w!("RustCordTrayWindow"), None) {
            let mut pid = 0;
            GetWindowThreadProcessId(window, Some(&mut pid));
            if pids.contains(&pid) {
                let mut answer = 0;
                SendMessageTimeoutW(window, quit, WPARAM(0), LPARAM(0), SMTO_ABORTIFHUNG, 1000, Some(&mut answer));
                quitting |= answer == 1;
            }
            after = window;
        }
    }
    quitting
}

/// The ways `close_running` tries, in order.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Close {
    Tray,
    Polite,
    Force,
}

/// Close RustCord running from `dir`: asked politely first (so it saves its
/// settings), through its tray window and then with taskkill (versions
/// before 0.4.41), then forced. True once none is left.
pub fn close_running(dir: &Path) -> bool {
    for (step, wait) in [(Close::Tray, 20), (Close::Polite, 20), (Close::Force, 20)] {
        let pids = running_from(dir);
        if pids.is_empty() {
            return true;
        }
        if step == Close::Tray {
            if !ask_to_quit(&pids) {
                continue;
            }
        } else {
            let mut cmd = std::process::Command::new(system_tool("taskkill.exe"));
            for pid in pids {
                cmd.arg("/PID").arg(pid.to_string());
            }
            if step == Close::Force {
                cmd.arg("/F");
            }
            let _ = cmd.creation_flags(CREATE_NO_WINDOW).output();
        }
        for _ in 0..wait {
            if running_from(dir).is_empty() {
                // (Windows lets go of the .exe a moment after the process ends.)
                std::thread::sleep(std::time::Duration::from_millis(150));
                return true;
            }
            std::thread::sleep(std::time::Duration::from_millis(150));
        }
    }
    running_from(dir).is_empty()
}

/// Delete what RustCord saved for this user: settings and cache (the
/// `RustCord` folders under %APPDATA% and %LOCALAPPDATA%, and its registry
/// key) and the Discord login in Windows' Credential Manager.
pub fn delete_user_data() {
    let root = |var: &str| std::env::var_os(var).map(PathBuf::from).filter(|p| p.is_absolute());
    let roaming = root("APPDATA");
    for dir in [&roaming, &root("LOCALAPPDATA")].into_iter().flatten() {
        let _ = std::fs::remove_dir_all(dir.join(APP));
    }
    // The login belongs to the real Windows profile: when %APPDATA% points
    // somewhere else (a sandbox, a test), it isn't this run's to delete.
    if let (Some(roaming), Some(real)) = (roaming, known_folder(&FOLDERID_RoamingAppData)) {
        if same_path(&roaming, &real) {
            // SAFETY: removes only RustCord's own key.
            unsafe {
                let _ = RegDeleteTreeW(HKEY_CURRENT_USER, &HSTRING::from(SETTINGS_KEY));
            }
            for target in saved_logins() {
                // SAFETY: a valid, NUL-terminated name.
                unsafe {
                    let _ = CredDeleteW(&HSTRING::from(target), CRED_TYPE_GENERIC, 0);
                }
            }
        }
    }
}

/// The names of RustCord's saved logins in Credential Manager.
fn saved_logins() -> Vec<String> {
    let mut out = Vec::new();
    let mut count = 0u32;
    let mut list: *mut *mut CREDENTIALW = std::ptr::null_mut();
    // SAFETY: Windows fills `count` and `list` (an array of `count` valid
    // credential pointers), which is read here and then freed with CredFree.
    unsafe {
        if CredEnumerateW(&HSTRING::from(format!("{LOGIN_PREFIX}*")), CRED_ENUMERATE_FLAGS(0), &mut count, &mut list).is_err() || list.is_null() {
            return out;
        }
        for i in 0..count as usize {
            let cred = *list.add(i);
            if cred.is_null() || (*cred).Type != CRED_TYPE_GENERIC {
                continue;
            }
            if let Ok(name) = (*cred).TargetName.to_string() {
                if name.starts_with(LOGIN_PREFIX) && name.ends_with(LOGIN_SUFFIX) {
                    out.push(name);
                }
            }
        }
        CredFree(list as *const _);
    }
    out
}

/// Log every saved account out at Discord (so their tokens stop working)
/// with `rustcord.exe --logout-all` from the install in `dir`. Waits up to
/// 20 seconds; a PC that is offline just keeps going.
pub fn log_out_everywhere(dir: &Path) {
    let exe = dir.join(EXE);
    if !exe.is_file() {
        return;
    }
    let Ok(mut child) = std::process::Command::new(&exe).arg("--logout-all").creation_flags(CREATE_NO_WINDOW).spawn() else { return };
    for _ in 0..80 {
        if child.try_wait().ok().flatten().is_some() {
            return;
        }
        std::thread::sleep(std::time::Duration::from_millis(250));
    }
    let _ = child.kill();
}

/// A program in System32 by its full path: a bare name would also be looked
/// for next to this program first (Downloads, %TEMP%), where anything could
/// have been put.
fn system_tool(name: &str) -> PathBuf {
    let mut buf = [0u16; 260];
    // SAFETY: the buffer is writable and its length is passed.
    let n = unsafe { GetSystemDirectoryW(Some(&mut buf)) } as usize;
    let dir = if n > 0 && n < buf.len() { PathBuf::from(String::from_utf16_lossy(&buf[..n])) } else { PathBuf::from(r"C:\Windows\System32") };
    dir.join(name)
}

/// Delete `path` a little later, once this program has exited (a running
/// .exe can't delete itself).
pub fn delete_after_exit(path: &Path) {
    // (Passed as is: cmd doesn't read the backslash-escaped quotes Rust would add.)
    let ping = system_tool("PING.EXE");
    let script = format!("/c \"\"{}\" -n 3 127.0.0.1 >nul & del /f /q \"{}\"\"", ping.display(), path.display());
    let _ = std::process::Command::new(system_tool("cmd.exe")).raw_arg(script).creation_flags(CREATE_NO_WINDOW).spawn();
}

// ---------------------------------------------------------------------------
// Windows: Windows' own "task dialog", one window whose page can change
// (question → progress → result) without it closing in between.

/// The Cancel button, also what Esc and the window's X send.
pub const CANCEL: i32 = 2;

#[derive(Clone, Copy, PartialEq)]
pub enum Icon {
    /// RustCord's own icon.
    App,
    Info,
    Warning,
    Error,
}

/// One page of a window.
pub struct Page {
    pub icon: Icon,
    pub heading: String,
    pub text: String,
    /// (id, label), left to right; the first is the default. Ids are the
    /// caller's own, except [`CANCEL`].
    pub buttons: Vec<(i32, String)>,
    /// A checkbox above the buttons: (label, ticked).
    pub checkbox: Option<(String, bool)>,
    pub progress: bool,
}

impl Page {
    pub fn new(icon: Icon, heading: impl Into<String>, text: impl Into<String>) -> Self {
        Self { icon, heading: heading.into(), text: text.into(), buttons: Vec::new(), checkbox: None, progress: false }
    }

    pub fn button(mut self, id: i32, label: &str) -> Self {
        self.buttons.push((id, label.to_string()));
        self
    }

    pub fn checkbox(mut self, label: &str, ticked: bool) -> Self {
        self.checkbox = Some((label.to_string(), ticked));
        self
    }

    pub fn progress(mut self) -> Self {
        self.progress = true;
        self
    }
}

/// A page as Windows wants it, with the strings it points into.
struct Built {
    config: TASKDIALOGCONFIG,
    _strings: Vec<HSTRING>,
    _buttons: Vec<TASKDIALOG_BUTTON>,
}

fn build(page: &Page, data: isize) -> Box<Built> {
    let mut strings = Vec::new();
    let mut keep = |s: &str| {
        let h = HSTRING::from(s);
        // (An HSTRING's characters live on the heap: moving it keeps the pointer good.)
        let p = PCWSTR(h.as_ptr());
        strings.push(h);
        p
    };
    let buttons: Vec<TASKDIALOG_BUTTON> = page.buttons.iter().map(|(id, label)| TASKDIALOG_BUTTON { nButtonID: *id, pszButtonText: keep(label) }).collect();
    let mut config = TASKDIALOGCONFIG { cbSize: std::mem::size_of::<TASKDIALOGCONFIG>() as u32, ..Default::default() };
    let mut flags = TDF_CALLBACK_TIMER;
    if page.buttons.iter().any(|(id, _)| *id == CANCEL) {
        flags = flags | TDF_ALLOW_DIALOG_CANCELLATION;
    }
    if page.progress {
        flags = flags | TDF_SHOW_PROGRESS_BAR;
    }
    // SAFETY: this program's own module and its icon resource (number 1).
    let app_icon = unsafe { GetModuleHandleW(None).ok().and_then(|module| LoadIconW(module, PCWSTR(1 as *const u16)).ok()) };
    match (page.icon, app_icon) {
        (Icon::App, Some(icon)) => {
            flags = flags | TDF_USE_HICON_MAIN;
            config.Anonymous1.hMainIcon = icon;
        }
        (Icon::App | Icon::Info, _) => config.Anonymous1.pszMainIcon = TD_INFORMATION_ICON,
        (Icon::Warning, _) => config.Anonymous1.pszMainIcon = TD_WARNING_ICON,
        (Icon::Error, _) => config.Anonymous1.pszMainIcon = TD_ERROR_ICON,
    }
    if let Some((label, ticked)) = &page.checkbox {
        config.pszVerificationText = keep(label);
        if *ticked {
            flags = flags | TDF_VERIFICATION_FLAG_CHECKED;
        }
    }
    config.dwFlags = flags;
    config.pszWindowTitle = keep(&format!("{APP} Setup"));
    config.pszMainInstruction = keep(&page.heading);
    config.pszContent = keep(&page.text);
    config.cButtons = buttons.len() as u32;
    config.pButtons = buttons.as_ptr();
    config.nDefaultButton = page.buttons.first().map_or(0, |(id, _)| *id);
    config.pfCallback = Some(callback);
    config.lpCallbackData = data;
    Box::new(Built { config, _strings: strings, _buttons: buttons })
}

/// What a window does when something happens in it.
pub trait Handler {
    /// A button was pressed: true closes the window.
    fn clicked(&mut self, ui: &Ui, button: i32) -> bool;
    /// The checkbox was ticked or cleared.
    fn checkbox(&mut self, _ticked: bool) {}
    /// Called about five times a second.
    fn tick(&mut self, _ui: &Ui) {}
}

/// The open window, as a [`Handler`] sees it.
pub struct Ui<'a> {
    hwnd: HWND,
    pages: &'a RefCell<Vec<Box<Built>>>,
    data: isize,
}

impl Ui<'_> {
    fn send(&self, message: i32, wparam: usize, lparam: isize) {
        // SAFETY: a message to the task dialog this callback belongs to.
        unsafe {
            SendMessageW(self.hwnd, message as u32, WPARAM(wparam), LPARAM(lparam));
        }
    }

    /// Replace the window's page.
    pub fn navigate(&self, page: Page) {
        let built = build(&page, self.data);
        let config: *const TASKDIALOGCONFIG = &built.config;
        // (Kept until the window closes: Windows reads it after this returns.)
        self.pages.borrow_mut().push(built);
        self.send(TDM_NAVIGATE_PAGE.0, 0, config as isize);
    }

    pub fn set_text(&self, text: &str) {
        let text = HSTRING::from(text);
        self.send(TDM_SET_ELEMENT_TEXT.0, TDE_CONTENT.0 as usize, text.as_ptr() as isize);
    }

    /// The progress bar, 0 to 1000.
    pub fn set_progress(&self, thousandths: u32) {
        self.send(TDM_SET_PROGRESS_BAR_RANGE.0, 0, 1000 << 16);
        self.send(TDM_SET_PROGRESS_BAR_POS.0, thousandths.min(1000) as usize, 0);
    }

    pub fn enable(&self, button: i32, enabled: bool) {
        self.send(TDM_ENABLE_BUTTON.0, button as usize, enabled as isize);
    }

    /// For windows opened on top of this one.
    pub fn hwnd(&self) -> HWND {
        self.hwnd
    }
}

struct Context<'a> {
    handler: RefCell<&'a mut dyn Handler>,
    pages: RefCell<Vec<Box<Built>>>,
    /// A handler is running (it may have a window of its own open, during
    /// which the timer keeps firing): don't start another.
    busy: Cell<bool>,
}

unsafe extern "system" fn callback(hwnd: HWND, message: TASKDIALOG_NOTIFICATIONS, wparam: WPARAM, _lparam: LPARAM, data: isize) -> HRESULT {
    // SAFETY: `data` is the Context `run` keeps alive for as long as the window exists.
    let context = unsafe { &*(data as *const Context) };
    let is_click = message == TDN_BUTTON_CLICKED;
    if context.busy.replace(true) {
        return if is_click { S_FALSE } else { S_OK };
    }
    let ui = Ui { hwnd, pages: &context.pages, data };
    let mut handler = context.handler.borrow_mut();
    let mut close = true;
    if is_click {
        close = handler.clicked(&ui, wparam.0 as i32);
    } else if message == TDN_VERIFICATION_CLICKED {
        handler.checkbox(wparam.0 != 0);
    } else if message == TDN_TIMER {
        handler.tick(&ui);
    }
    drop(handler);
    context.busy.set(false);
    if is_click && !close {
        S_FALSE
    } else {
        S_OK
    }
}

/// Show a window starting at `page` until a button closes it; returns that
/// button ([`CANCEL`] if it couldn't be shown) and whether the last page's
/// checkbox was ticked.
pub fn run(page: Page, handler: &mut dyn Handler) -> (i32, bool) {
    let context = Context { handler: RefCell::new(handler), pages: RefCell::new(Vec::new()), busy: Cell::new(false) };
    let first = build(&page, &context as *const Context as isize);
    let (mut button, mut ticked) = (CANCEL, BOOL(0));
    // SAFETY: the page and the context outlive the call, which returns when the window closes.
    let shown = unsafe { TaskDialogIndirect(&first.config, Some(&mut button), None, Some(&mut ticked)) };
    if shown.is_ok() {
        (button, ticked.as_bool())
    } else {
        (CANCEL, false)
    }
}

/// A one-page window: the button that closed it, and whether its checkbox
/// was ticked.
pub fn show(page: Page) -> (i32, bool) {
    struct Simple;
    impl Handler for Simple {
        fn clicked(&mut self, _ui: &Ui, _button: i32) -> bool {
            true
        }
    }
    run(page, &mut Simple)
}

pub fn info(heading: &str, text: &str) {
    show(Page::new(Icon::App, heading, text).button(1, "Close"));
}

pub fn error(heading: &str, text: &str) {
    show(Page::new(Icon::Error, heading, text).button(1, "Close"));
}

/// Retry / Cancel.
pub fn retry(heading: &str, text: &str) -> bool {
    show(Page::new(Icon::Warning, heading, text).button(1, "Retry").button(CANCEL, "Cancel")).0 == 1
}

/// Let the user pick a folder, starting at `start` (or the nearest folder
/// above it that exists).
pub fn pick_folder(owner: HWND, start: &Path) -> Option<PathBuf> {
    // SAFETY: plain COM calls; the returned string is copied, then freed.
    unsafe {
        let dialog: IFileOpenDialog = CoCreateInstance(&FileOpenDialog, None, CLSCTX_INPROC_SERVER).ok()?;
        dialog.SetOptions(dialog.GetOptions().ok()? | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM).ok()?;
        let _ = dialog.SetTitle(&HSTRING::from(format!("Where should {APP} be installed?")));
        if let Some(existing) = start.ancestors().find(|p| p.is_dir()) {
            if let Ok(item) = SHCreateItemFromParsingName::<_, _, IShellItem>(&HSTRING::from(existing.as_os_str()), None) {
                let _ = dialog.SetFolder(&item);
            }
        }
        dialog.Show(owner).ok()?;
        let name = dialog.GetResult().ok()?.GetDisplayName(SIGDN_FILESYSPATH).ok()?;
        let path = name.to_string().ok();
        CoTaskMemFree(Some(name.0 as *const _));
        path.map(PathBuf::from)
    }
}