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.

19.8 KB
Raw Blame
use gpui_kit::*;

gpui_kit::actions!(
    rustyfiles,
    [
        GoBack,
        BackspaceBack,
        GoForward,
        LeaveTree,
        FocusNextPane,
        FocusPrevPane,
        DialogNext,
        DialogPrev,
        GoUp,
        GoHome,
        Refresh,
        OpenSelected,
        SelectNext,
        SelectPrev,
        SelectFirst,
        SelectLast,
        SelectAll,
        ExtendNext,
        ExtendPrev,
        ExtendFirst,
        ExtendLast,
        ExtendPageDown,
        ExtendPageUp,
        PageDown,
        PageUp,
        NewTab,
        CloseTab,
        NextTab,
        PrevTab,
        ReopenClosedTab,
        SelectTab1,
        SelectTab2,
        SelectTab3,
        SelectTab4,
        SelectTab5,
        SelectTab6,
        SelectTab7,
        SelectTab8,
        SelectTab9,
        FocusAddress,
        FocusSearch,
        ToggleHidden,
        OpenTerminal,
        /// The selected files in the chosen text editor (Settings › Developer tools; Notepad when none), F4 as in Total Commander.
        EditFiles,
        Properties,
        ClearSelection,
        CopyItems,
        CutItems,
        PasteItems,
        PasteIntoSelected,
        PasteShortcut,
        DeleteItems,
        DeletePermanently,
        DuplicateItems,
        CopyToOtherPane,
        MoveToOtherPane,
        RenameItem,
        NewFolder,
        NewTextFile,
        DownloadFromLink,
        ShowContextMenu,
        CopyPath,
        OpenWith,
        SelectLeft,
        SelectRight,
        ExtendLeft,
        ExtendRight,
        ViewDetails,
        ViewGrid,
        TogglePreview,
        ToggleSidebar,
        ToggleDualPane,
        SwitchPane,
        ToggleCommandPalette,
        SearchFolderHistory,
        SearchTabs,
        GoSettings,
        GoRecycleBin,
        ViewColumns,
        ViewCards,
        ViewList,
        Undo,
        MapNetworkDrive,
        RestartApp,
        SaveSession,
        DisconnectNetworkDrive,
        NewWindow,
        ZoomIn,
        ZoomOut,
        AddToShelf,
        InvertSelection,
        ToggleSelection,
        ToggleShelf,
        ToggleFullscreen,
        ToggleAlwaysOnTop,
        ToggleCompactOverlay,
        GoToFolderAlias,
        RotateRight,
        RotateLeft,
        ToggleToolbar,
        Redo,
        DuplicateTab,
        CloseOtherTabs,
        CopyPathQuoted,
        OpenInIde,
        ToggleTheme,
        CloseAllTabs,
        SplitPaneSideBySide,
        SplitPaneStacked,
        CloseActivePane,
        OpenInNewWindow,
        OpenTerminalAdmin,
        OrganizeFolder,
        ToggleAllGroups,
        OpenIconThemesFolder,
        SortNameAToZ,
        SortNameZToA,
        SortModifiedNewestFirst,
        SortModifiedOldestFirst,
        SortCreatedNewestFirst,
        SortCreatedOldestFirst,
        SortTypeAToZ,
        SortTypeZToA,
        SortSizeLargestFirst,
        SortSizeSmallestFirst,
        ToggleFilter,
    ]
);

pub const FOLDER_CTX: &str = "FolderView";
/// The folder tree's key context. Tab is bound in it (to [`LeaveTree`]) because the component library binds Tab at the window's
/// root to "focus the next tab stop": a binding is matched before any key listener is asked, so the tree's own key handler never
/// saw Tab, and the keyboard stayed in the tree (issue 38: "TAB seems to be buggy, mine is not going anywhere"). A binding in a
/// context nearer to the focus wins over the root's.
pub const TREE_CTX: &str = "FolderTree";
/// The question dialog's key context: Tab and Shift+Tab move between its buttons there (bound here for the same reason as the
/// tree's Tab: the root's Tab binding would take the key first).
pub const DIALOG_CTX: &str = "Dialog";

/// Where our own bindings (the built-in ones and the user's) lie in the app's list of bindings: [`rebind`] takes exactly these
/// out before it binds anew, and leaves the component library's alone.
struct Bound(std::ops::Range<usize>);
impl Global for Bound {}

/// Binds the built-in shortcuts and the user's own, from the settings and the keyboard layout as they are now: at startup, and
/// again whenever either changes. The bindings of an earlier call are taken out first.
///
/// WHY. Bindings could only be added, so a change was half done until the next start (a Discord report, 2026-12-04: "The hotkey
/// removed is still active": a shortcut set and then reset in Settings went on working; and a command given new keys kept its
/// built-in ones too). And the layout forms of Ctrl+Shift+digit ([`bind_layout_shifted`]) were made once, for the layout the
/// program started in (the same reporter: "Hotkeys like Ctrl+Shift+digit don't work in Russian layout reliably": Shift+2 is `@`
/// in English and `"` in Russian, so after a switch of layouts the keys were bound to nothing).
pub fn rebind(cx: &mut App) {
    let all: Vec<KeyBinding> = cx.key_bindings().borrow().bindings().cloned().collect();
    let ours = cx.try_global::<Bound>().map(|b| b.0.clone()).filter(|r| r.end <= all.len()).unwrap_or(all.len()..all.len());
    let others: Vec<KeyBinding> = all.into_iter().enumerate().filter(|(i, _)| !ours.contains(i)).map(|(_, b)| b).collect();
    cx.clear_key_bindings();
    let start = others.len();
    cx.bind_keys(others);
    bind(cx);
    bind_user(cx);
    let end = cx.key_bindings().borrow().bindings().len();
    cx.set_global(Bound(start..end));
}

/// User overrides from settings.toml `[keybindings]`. Invalid entries are logged and skipped.
fn bind_user(cx: &mut App) {
    let map = cx.global::<crate::settings::Settings>().keybindings.clone();
    let mut bindings = Vec::new();
    for (keys, action) in map {
        let name = if action.contains("::") { action.clone() } else { format!("rustyfiles::{action}") };
        match cx.build_action(&name, None) {
            Ok(a) => match user_binding(&keys, a, cx) {
                Ok(b) => bindings.push(b),
                Err(e) => log::warn!("keybinding {keys:?}: {e}"),
            },
            Err(e) => log::warn!("keybinding {keys:?} -> {action:?}: {e}"),
        }
    }
    cx.bind_keys(bindings);
}

/// A shortcut of the user's own, bound everywhere. One whose keys type a character ([`types_text`]) is left out while a text box
/// has the keyboard (the rename box, the address bar, a dialog's field), so the character is typed there.
///
/// WHY (issue 1031: "I set F as the shortcut for New folder; typing F in the new folder's name creates another one"). A binding is
/// matched before the text box is asked, and the box has no binding of its own for a letter, so the shortcut took every F typed.
pub(crate) fn user_binding(keys: &str, action: Box<dyn Action>, cx: &App) -> Result<KeyBinding, InvalidKeystrokeError> {
    // ("Input" is the component library's context for every text box; a rule with `!` is false when it is anywhere on the focus path)
    let outside_text = if types_text(keys) { KeyBindingContextPredicate::parse("!Input").ok().map(std::rc::Rc::new) } else { None };
    KeyBinding::load(keys, action, outside_text, false, None, cx)
}

/// Whether pressing these keys types a character into a text box: a single key that is a letter, a digit, a sign or the space bar,
/// with no Ctrl, Alt or Windows key held (Shift only makes another character). Pure.
pub(crate) fn types_text(keys: &str) -> bool {
    let mut strokes = keys.split_whitespace();
    let (Some(stroke), None) = (strokes.next(), strokes.next()) else { return false };
    // ("ctrl--" and "-" end with the minus key itself)
    let (mods, key) = if stroke == "-" {
        ("", "-")
    } else if let Some(m) = stroke.strip_suffix("--") {
        (m, "-")
    } else {
        stroke.rsplit_once('-').unwrap_or(("", stroke))
    };
    let typed = key == "space" || key.chars().count() == 1;
    typed && mods.split('-').all(|m| m.is_empty() || m.eq_ignore_ascii_case("shift"))
}

/// Binds built-in shortcuts, leaving out those of a command the user gave keys of their own in Settings: a custom shortcut
/// replaces the built-in one, as the shortcut editor shows it, so the old keys are free for another command. (With both bound,
/// the built-in one kept working, and in a nearer context such as the file list's it won over a custom one on the same keys.)
/// A shortcut set or reset in Settings binds everything anew ([`rebind`]), so this holds at once.
fn bind_defaults(cx: &mut App, bindings: impl IntoIterator<Item = KeyBinding>) {
    let custom: std::collections::HashSet<String> =
        cx.global::<crate::settings::Settings>().keybindings.values().map(|a| short_name(a).to_string()).collect();
    cx.bind_keys(without_customized(bindings, &custom));
}

/// "rustyfiles::DuplicateItems" → "DuplicateItems" (settings.toml may hold either).
fn short_name(action: &str) -> &str {
    action.rsplit("::").next().unwrap_or(action)
}

fn without_customized(bindings: impl IntoIterator<Item = KeyBinding>, custom: &std::collections::HashSet<String>) -> Vec<KeyBinding> {
    bindings.into_iter().filter(|b| !custom.contains(short_name(b.action().name()))).collect()
}

fn bind(cx: &mut App) {
    let f = Some(FOLDER_CTX);
    bind_defaults(cx, [KeyBinding::new("tab", LeaveTree, Some(TREE_CTX))]);
    // Tab and Shift+Tab walk the window's panes: the address bar, the folder tree, the file list (issue 38: "TAB does not work
    // anywhere"), and in the Open / Save dialog the name box after the list, as in Windows' own dialog. In the list's own
    // context, nearer than the root's Tab; the tree's Shift+Tab goes up to the window's handler.
    bind_defaults(cx, [
        KeyBinding::new("tab", FocusNextPane, Some(FOLDER_CTX)),
        KeyBinding::new("shift-tab", FocusPrevPane, Some(FOLDER_CTX)),
        KeyBinding::new("shift-tab", FocusPrevPane, Some(TREE_CTX)),
    ]);
    bind_defaults(cx, [KeyBinding::new("tab", DialogNext, Some(DIALOG_CTX)), KeyBinding::new("shift-tab", DialogPrev, Some(DIALOG_CTX))]);
    bind_defaults(cx, [
        KeyBinding::new("alt-left", GoBack, None),
        KeyBinding::new("alt-right", GoForward, None),
        KeyBinding::new("alt-up", GoUp, None),
        KeyBinding::new("alt-home", GoHome, None),
        // Backspace goes back only from the list itself (issue 171: "after deleting letters rustyfiles navigates up"): a text box
        // in the view (the rename box, the filter) passes Backspace on when its caret is at the start, and that went back
        KeyBinding::new("backspace", BackspaceBack, f),
        KeyBinding::new("f5", Refresh, None),
        KeyBinding::new("ctrl-r", Refresh, None),
        KeyBinding::new("enter", OpenSelected, f),
        KeyBinding::new("down", SelectNext, f),
        KeyBinding::new("up", SelectPrev, f),
        KeyBinding::new("home", SelectFirst, f),
        KeyBinding::new("end", SelectLast, f),
        KeyBinding::new("shift-home", ExtendFirst, f),
        KeyBinding::new("shift-end", ExtendLast, f),
        KeyBinding::new("shift-pagedown", ExtendPageDown, f),
        KeyBinding::new("shift-pageup", ExtendPageUp, f),
        KeyBinding::new("ctrl-a", SelectAll, f),
        KeyBinding::new("shift-down", ExtendNext, f),
        KeyBinding::new("shift-up", ExtendPrev, f),
        KeyBinding::new("pagedown", PageDown, f),
        KeyBinding::new("pageup", PageUp, f),
        KeyBinding::new("escape", ClearSelection, f),
        KeyBinding::new("alt-enter", Properties, f),
        KeyBinding::new("ctrl-c", CopyItems, f),
        KeyBinding::new("ctrl-x", CutItems, f),
        KeyBinding::new("ctrl-v", PasteItems, f),
        KeyBinding::new("ctrl-shift-v", PasteIntoSelected, f),
        // the old Windows chords, as in Explorer, Total Commander and FAR (a discussion of 2026-11-30)
        KeyBinding::new("ctrl-insert", CopyItems, f),
        KeyBinding::new("shift-insert", PasteItems, f),
        KeyBinding::new("delete", DeleteItems, f),
        KeyBinding::new("ctrl-d", DeleteItems, f),
        // (Ctrl+D deletes, as in Explorer; a copy beside the item has its own chord, issue 161)
        KeyBinding::new("ctrl-alt-d", DuplicateItems, f),
        // the selection into the other pane of a split tab (issue 152; F5 and F6 are Refresh and the pane switch here)
        KeyBinding::new("shift-f5", CopyToOtherPane, f),
        KeyBinding::new("shift-f6", MoveToOtherPane, f),
        KeyBinding::new("shift-delete", DeletePermanently, f),
        KeyBinding::new("f2", RenameItem, f),
        KeyBinding::new("f4", EditFiles, f),
        KeyBinding::new("ctrl-shift-n", NewFolder, f),
        KeyBinding::new("shift-f10", ShowContextMenu, f),
        KeyBinding::new("menu", ShowContextMenu, f),
        KeyBinding::new("ctrl-shift-c", CopyPath, f),
        KeyBinding::new("left", SelectLeft, f),
        KeyBinding::new("right", SelectRight, f),
        // (the selection grows sideways in the grid, as Shift+Up / Down grow it by a row: issue 908)
        KeyBinding::new("shift-left", ExtendLeft, f),
        KeyBinding::new("shift-right", ExtendRight, f),
        KeyBinding::new("ctrl-shift-1", ViewDetails, None),
        KeyBinding::new("ctrl-shift-2", ViewGrid, None),
        KeyBinding::new("ctrl-shift-3", ViewColumns, None),
        KeyBinding::new("ctrl-shift-4", ViewCards, None),
        KeyBinding::new("ctrl-shift-5", ViewList, None),
        KeyBinding::new("ctrl-z", Undo, f),
        KeyBinding::new("alt-p", TogglePreview, None),
        KeyBinding::new("ctrl-b", ToggleSidebar, None),
        KeyBinding::new("ctrl-shift-b", ToggleToolbar, None),
        KeyBinding::new("ctrl-y", Redo, f),
        KeyBinding::new("ctrl-shift-k", DuplicateTab, None),
        KeyBinding::new("ctrl-alt-c", CopyPathQuoted, f),
        KeyBinding::new("ctrl-alt-t", ToggleTheme, None),
        KeyBinding::new("ctrl-shift-d", ToggleDualPane, None),
        KeyBinding::new("f6", SwitchPane, None),
        KeyBinding::new("ctrl-shift-p", ToggleCommandPalette, None),
        KeyBinding::new("ctrl-alt-shift-r", RestartApp, None),
        KeyBinding::new("f1", ToggleCommandPalette, None),
        KeyBinding::new("ctrl-p", SearchFolderHistory, None),
        KeyBinding::new("ctrl-shift-a", SearchTabs, None),
        KeyBinding::new("ctrl-,", GoSettings, None),
        KeyBinding::new("ctrl-t", NewTab, None),
        KeyBinding::new("ctrl-n", NewWindow, None),
        KeyBinding::new("ctrl-shift-s", AddToShelf, f),
        KeyBinding::new("ctrl-space", ToggleSelection, f),
        // every group folded, or every group open again (issue 181)
        KeyBinding::new("ctrl-shift-g", ToggleAllGroups, f),
        KeyBinding::new("f11", ToggleFullscreen, None),
        KeyBinding::new("ctrl-=", ZoomIn, f),
        KeyBinding::new("ctrl-+", ZoomIn, f),
        KeyBinding::new("ctrl--", ZoomOut, f),
        KeyBinding::new("ctrl-w", CloseTab, None),
        KeyBinding::new("ctrl-shift-w", CloseActivePane, None),
        KeyBinding::new("ctrl-alt-enter", OpenInNewWindow, f),
        KeyBinding::new("ctrl-tab", NextTab, None),
        KeyBinding::new("ctrl-shift-tab", PrevTab, None),
        // as in browsers (discussion 916: "CTRL+PAGE_UP ... CTRL+PAGE_DOWN ... exactly like the behavior we can see on browser tabs")
        KeyBinding::new("ctrl-pagedown", NextTab, None),
        KeyBinding::new("ctrl-pageup", PrevTab, None),
        KeyBinding::new("ctrl-shift-t", ReopenClosedTab, None),
        KeyBinding::new("ctrl-1", SelectTab1, None),
        KeyBinding::new("ctrl-2", SelectTab2, None),
        KeyBinding::new("ctrl-3", SelectTab3, None),
        KeyBinding::new("ctrl-4", SelectTab4, None),
        KeyBinding::new("ctrl-5", SelectTab5, None),
        KeyBinding::new("ctrl-6", SelectTab6, None),
        KeyBinding::new("ctrl-7", SelectTab7, None),
        KeyBinding::new("ctrl-8", SelectTab8, None),
        KeyBinding::new("ctrl-9", SelectTab9, None),
        KeyBinding::new("ctrl-l", FocusAddress, None),
        KeyBinding::new("alt-d", FocusAddress, None),
        KeyBinding::new("ctrl-f", FocusSearch, None),
        KeyBinding::new("ctrl-e", FocusSearch, None),
        // the "Filter by" strip, which could only be opened with the mouse before
        KeyBinding::new("ctrl-shift-f", ToggleFilter, None),
        KeyBinding::new("ctrl-h", ToggleHidden, None),
        KeyBinding::new("ctrl-shift-`", OpenTerminal, None),
    ]);
    bind_layout_shifted(cx);
}

thread_local! {
    /// The layout forms last written to the log (written again only when they change).
    static LAYOUT_FORMS: std::cell::RefCell<String> = const { std::cell::RefCell::new(String::new()) };
}

/// GPUI reports Shift+digit as the layout's shifted character without Shift (Turkish Q:
/// Ctrl+Shift+2 arrives as `ctrl-'`), so `ctrl-shift-2` alone never fires. Bind the
/// layout-specific form too. It is the form of the layout in use now: [`rebind`] runs this again when the layout changes.
fn bind_layout_shifted(cx: &mut App) {
    // (virtual key, action)
    let wanted: [(u16, Box<dyn Fn() -> Box<dyn Action>>); 6] = [
        (0x31, Box::new(|| Box::new(ViewDetails))),
        (0x32, Box::new(|| Box::new(ViewGrid))),
        (0x33, Box::new(|| Box::new(ViewColumns))),
        (0x34, Box::new(|| Box::new(ViewCards))),
        (0x35, Box::new(|| Box::new(ViewList))),
        (0xC0, Box::new(|| Box::new(OpenTerminal))), // VK_OEM_3 (` on US layouts)
    ];
    let mut bindings = Vec::new();
    let mut forms = Vec::new();
    for (vk, action) in wanted {
        let Some(ch) = rf_win::keys::shifted_char(vk) else { continue };
        // AZERTY: Shift+& gives "1"; binding ctrl-1 would steal a plain ctrl+digit shortcut
        if ch.chars().any(|c| c.is_alphanumeric()) {
            continue;
        }
        // Turkish Q: Shift+4 is "+" — Ctrl++ stays zoom
        if matches!(ch.as_str(), "+" | "-" | "=") {
            continue;
        }
        let keys = format!("ctrl-{ch}");
        match KeyBinding::load(&keys, action(), None, false, None, cx) {
            Ok(b) => {
                bindings.push(b);
                forms.push(keys);
            }
            Err(e) => log::debug!("layout binding {keys:?}: {e}"),
        }
    }
    // (one line a layout: a report of "Ctrl+Shift+2 does nothing" can be read against it)
    let forms = forms.join(" ");
    let said = LAYOUT_FORMS.with(|f| f.replace(forms.clone()));
    if said != forms {
        log::info!(target: "rustyfiles::start", "shortcuts: Ctrl+Shift+1..5 and the terminal's keys arrive as [{forms}] on this keyboard layout");
    }
    bind_defaults(cx, bindings);
}

#[cfg(test)]
mod tests {
    // (not `super::*`: gpui's `test` macro would take the place of `#[test]`)
    use super::{DuplicateItems, FOLDER_CTX, NewTab, ZoomIn, short_name, types_text, without_customized};
    use gpui_kit::KeyBinding;

    #[test]
    fn a_custom_shortcut_takes_the_place_of_the_built_in_one() {
        let defaults = || {
            [
                KeyBinding::new("ctrl-alt-d", DuplicateItems, Some(FOLDER_CTX)),
                KeyBinding::new("ctrl-=", ZoomIn, Some(FOLDER_CTX)),
                KeyBinding::new("ctrl-+", ZoomIn, Some(FOLDER_CTX)),
                KeyBinding::new("ctrl-t", NewTab, None),
            ]
        };
        let names = |b: Vec<KeyBinding>| b.iter().map(|b| short_name(b.action().name()).to_string()).collect::<Vec<_>>();
        // nothing customized: every built-in binding stays
        assert_eq!(without_customized(defaults(), &Default::default()).len(), 4);
        // settings.toml may name the action with or without its namespace; all of its built-in keys go
        let custom = ["DuplicateItems".to_string(), short_name("rustyfiles::ZoomIn").to_string()].into_iter().collect();
        assert_eq!(names(without_customized(defaults(), &custom)), ["NewTab"]);
    }

    #[test]
    fn a_shortcut_that_types_a_character_is_known_from_one_that_does_not() {
        // (issue 1031: F as the shortcut for a new folder)
        for keys in ["f", "F", "shift-f", "1", "-", "shift--", "/", "space", "shift-space", "ğ"] {
            assert!(types_text(keys), "{keys}");
        }
        for keys in ["ctrl-f", "alt-f", "ctrl-shift-n", "win-e", "ctrl--", "f2", "f12", "delete", "enter", "shift-f10", "ctrl-k ctrl-f", "g g", ""] {
            assert!(!types_text(keys), "{keys}");
        }
    }
}