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.

8.8 KB
Raw Blame
//! Windows' common file dialogs (IFileOpenDialog / IFileSaveDialog) and the "start with
//! Windows" Run entry. Dialogs are modal to `owner`: call them on the shell STA thread.

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

use windows::Win32::Foundation::HWND;
use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance, CoTaskMemFree};
use windows::Win32::UI::Shell::Common::COMDLG_FILTERSPEC;
use windows::Win32::UI::Shell::{
    FOS_FORCEFILESYSTEM, FOS_OVERWRITEPROMPT, FOS_PICKFOLDERS, FileOpenDialog, FileSaveDialog, IFileDialog, IFileOpenDialog,
    IFileSaveDialog, SIGDN_FILESYSPATH,
};
use windows::core::{Interface, PCWSTR};

use crate::wide::wide;

pub enum Pick<'a> {
    /// Open an existing file; filters are (label, pattern) pairs like ("Ayar dosyası", "*.toml").
    File { filters: &'a [(&'a str, &'a str)] },
    /// Choose a folder.
    Folder,
    /// Save as `default_name`.
    Save { filters: &'a [(&'a str, &'a str)], default_name: &'a str },
}

/// Shows the dialog; `None` when cancelled.
pub fn pick(owner: HWND, title: &str, kind: Pick<'_>) -> Option<PathBuf> {
    unsafe {
        let dialog: IFileDialog = match kind {
            Pick::Save { .. } => CoCreateInstance::<_, IFileSaveDialog>(&FileSaveDialog, None, CLSCTX_INPROC_SERVER).ok()?.cast().ok()?,
            _ => CoCreateInstance::<_, IFileOpenDialog>(&FileOpenDialog, None, CLSCTX_INPROC_SERVER).ok()?.cast().ok()?,
        };
        let mut opts = dialog.GetOptions().ok()? | FOS_FORCEFILESYSTEM;
        // keep the wide strings alive until Show returns
        let mut keep: Vec<Vec<u16>> = Vec::new();
        let mut specs: Vec<COMDLG_FILTERSPEC> = Vec::new();
        let filters: &[(&str, &str)] = match &kind {
            Pick::File { filters } | Pick::Save { filters, .. } => filters,
            Pick::Folder => &[],
        };
        for (label, pattern) in filters {
            keep.push(wide(label));
            let l = PCWSTR(keep.last().unwrap().as_ptr());
            keep.push(wide(pattern));
            let p = PCWSTR(keep.last().unwrap().as_ptr());
            specs.push(COMDLG_FILTERSPEC { pszName: l, pszSpec: p });
        }
        if !specs.is_empty() {
            let _ = dialog.SetFileTypes(&specs);
        }
        match &kind {
            Pick::Folder => opts |= FOS_PICKFOLDERS,
            Pick::Save { default_name, .. } => {
                opts |= FOS_OVERWRITEPROMPT;
                let n = wide(default_name);
                let _ = dialog.SetFileName(PCWSTR(n.as_ptr()));
            }
            Pick::File { .. } => {}
        }
        let _ = dialog.SetOptions(opts);
        let t = wide(title);
        let _ = dialog.SetTitle(PCWSTR(t.as_ptr()));
        dialog.Show(Some(owner)).ok()?;
        let item = dialog.GetResult().ok()?;
        let p = item.GetDisplayName(SIGDN_FILESYSPATH).ok()?;
        let s = p.to_string().ok();
        CoTaskMemFree(Some(p.0 as *const _));
        s.map(PathBuf::from)
    }
}

const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
const RUN_VALUE: &str = "rustyfiles";

/// Whether the app starts with Windows (HKCU Run entry, no admin rights needed).
pub fn starts_with_windows() -> bool {
    starts_with_windows_as(RUN_VALUE)
}

/// [`starts_with_windows`] for another program of the bundle (Run value `name`).
pub fn starts_with_windows_as(name: &str) -> bool {
    windows_registry::CURRENT_USER.open(RUN_KEY).and_then(|k| k.get_string(name)).is_ok()
}

/// The app's own entry starts it with `--background`: no window at sign-in, only what runs in the background (a window at sign-in is more than is wanted).
///
/// Two entries do it. The Run value is the switch's state and the fallback; Windows starts its Run list only after the desktop is
/// up and then late on purpose (about 19 s after Explorer on a desktop PC), so Explorer's taskbar was seen before the Dock every
/// time. A Task Scheduler task with a sign-in trigger starts the app at once, beside Explorer, at normal priority. When both run,
/// the later start only greets the running app and opens nothing, so the Run value costs one short process and keeps the app
/// starting if the task cannot be made or is removed.
pub fn set_start_with_windows(exe: &Path, on: bool) -> windows::core::Result<()> {
    set_start_with_windows_as(RUN_VALUE, exe, &["--background"], on)?;
    if let Err(e) = set_sign_in_task(exe, on) {
        log::warn!("start with Windows: the sign-in task could not be {}: {e}", if on { "made" } else { "removed" });
    }
    Ok(())
}

/// The sign-in task's name: one per user (the root folder of the Task Scheduler is shared by every account of the PC).
fn sign_in_task_name() -> String {
    format!("rustyfiles start ({})", std::env::var("USERNAME").unwrap_or_default())
}

fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}

/// The task's definition: the user's own sign-in, the user's own rights (no administrator), normal priority (a task's default is
/// below normal), no time limit, also on battery.
fn sign_in_task_xml(exe: &Path, user: &str) -> String {
    let (exe, user) = (xml_escape(&exe.to_string_lossy()), xml_escape(user));
    format!(
        r#"<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo><Description>Starts rustyfiles when you sign in, without the delay of Windows' start-up list, so the Dock is there first. Made and removed by Settings in rustyfiles (Start with Windows).</Description></RegistrationInfo>
  <Triggers><LogonTrigger><Enabled>true</Enabled><UserId>{user}</UserId></LogonTrigger></Triggers>
  <Principals><Principal id="Author"><UserId>{user}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <AllowHardTerminate>false</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings><StopOnIdleEnd>false</StopOnIdleEnd><RestartOnIdle>false</RestartOnIdle></IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>4</Priority>
  </Settings>
  <Actions Context="Author"><Exec><Command>{exe}</Command><Arguments>--background</Arguments></Exec></Actions>
</Task>
"#
    )
}

/// Makes (or replaces) or removes the sign-in task, through `schtasks.exe` (no administrator rights needed for a task of one's
/// own account). Removing a task that is not there is not an error.
pub fn set_sign_in_task(exe: &Path, on: bool) -> std::io::Result<()> {
    use std::os::windows::process::CommandExt;
    const CREATE_NO_WINDOW: u32 = 0x0800_0000;
    let schtasks = std::env::var_os("WINDIR").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\Windows")).join(r"System32\schtasks.exe");
    let name = sign_in_task_name();
    if !on {
        let out = std::process::Command::new(&schtasks).args(["/Delete", "/TN", &name, "/F"]).creation_flags(CREATE_NO_WINDOW).output()?;
        let _ = out;
        return Ok(());
    }
    let user = format!("{}\\{}", std::env::var("USERDOMAIN").unwrap_or_default(), std::env::var("USERNAME").unwrap_or_default());
    // schtasks reads the file as UTF-16 (the encoding the XML names)
    let mut bytes = vec![0xFF, 0xFE];
    for u in sign_in_task_xml(exe, &user).encode_utf16() {
        bytes.extend_from_slice(&u.to_le_bytes());
    }
    let file = std::env::temp_dir().join(format!("rustyfiles-sign-in-task-{}.xml", std::process::id()));
    std::fs::write(&file, &bytes)?;
    let out = std::process::Command::new(&schtasks).args(["/Create", "/TN", &name, "/XML"]).arg(&file).arg("/F").creation_flags(CREATE_NO_WINDOW).output();
    let _ = std::fs::remove_file(&file);
    let out = out?;
    if out.status.success() {
        Ok(())
    } else {
        Err(std::io::Error::other(String::from_utf8_lossy(&out.stderr).trim().to_string()))
    }
}

/// Run value `name` → `"exe" args…` (HKCU, no admin rights).
pub fn set_start_with_windows_as(name: &str, exe: &Path, args: &[&str], on: bool) -> windows::core::Result<()> {
    let key = windows_registry::CURRENT_USER.create(RUN_KEY)?;
    if on {
        let mut cmd = format!("\"{}\"", exe.display());
        for a in args {
            cmd.push(' ');
            cmd.push_str(a);
        }
        key.set_string(name, cmd)
    } else {
        match key.remove_value(name) {
            Ok(()) => Ok(()),
            // already absent
            Err(e) if e.code() == windows::Win32::Foundation::ERROR_FILE_NOT_FOUND.to_hresult() => Ok(()),
            Err(e) => Err(e),
        }
    }
}