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.

Mac: your own command bar buttons

gelenmedya37ad05e3fe98
diff --git a/macos/Sources/RustyFiles/FileList.swift b/macos/Sources/RustyFiles/FileList.swift
index deef3d68..63db4ce6 100644
--- a/macos/Sources/RustyFiles/FileList.swift
+++ b/macos/Sources/RustyFiles/FileList.swift
@@ -35,6 +35,21 @@ final class CommandBarView: FlippedView {
/// Folds every group or opens them all; only while the folder is shown in groups.
let groups = IconButton(icon: "chevrons-down-up", size: NSSize(width: 36, height: 32), tooltip: String(localized: "Collapse all groups"))
var showsGroups = false { didSet { if showsGroups != oldValue { needsLayout = true } } }
+ /// Your own buttons (Settings › Your commands), after the others on the left.
+ private(set) var custom: [IconButton] = []
+ var onCustom: ((Int) -> Void)?
+
+ func reloadCustom() {
+ custom.forEach { $0.removeFromSuperview() }
+ custom = QuickCommands.all.enumerated().map { i, c in
+ let b = IconButton(icon: "zap", size: NSSize(width: 0, height: 32), tooltip: c.program)
+ b.label = c.name
+ b.action = { [weak self] _ in self?.onCustom?(i) }
+ addSubview(b)
+ return b
+ }
+ needsLayout = true
+ }
private let sepLeft = Divider()
private let sepRight = Divider()
@@ -118,6 +133,12 @@ final class CommandBarView: FlippedView {
place(b, x, 36)
x += 36 + 2
}
+ for b in custom {
+ let w = b.intrinsicContentSize.width
+ guard x + w <= r - 8 else { break }
+ place(b, x, w)
+ x += w + 2
+ }
}
override func draw(_ dirtyRect: NSRect) {
diff --git a/macos/Sources/RustyFiles/FileListController.swift b/macos/Sources/RustyFiles/FileListController.swift
index 468989b2..9d8ed0ee 100644
--- a/macos/Sources/RustyFiles/FileListController.swift
+++ b/macos/Sources/RustyFiles/FileListController.swift
@@ -786,6 +786,8 @@ final class FileListController: NSObject, NSTableViewDataSource, NSTableViewDele
if folder != nil { reloadItems() }
case "tileNameLines", "videoBadge":
tileSizeChanged()
+ case "toolbarCommands":
+ commandBar.reloadCustom()
case "showSystemFiles":
setShowSystemFiles(show: AppSettings.showSystemFiles)
rearrange()
@@ -1040,6 +1042,8 @@ final class FileListController: NSObject, NSTableViewDataSource, NSTableViewDele
private func wireCommandBar() {
let b = commandBar
+ b.reloadCustom()
+ b.onCustom = { [weak self] i in self?.runQuickCommand(i) }
b.newFolder.action = { [weak self] _ in self?.newFolder() }
b.terminal.action = { [weak self] _ in if let u = self?.url { MenuActions.openInTerminal(u) } }
b.hiddenItems.action = { _ in AppSettings.showHidden.toggle() }
@@ -1876,6 +1880,9 @@ final class FileListController: NSObject, NSTableViewDataSource, NSTableViewDele
}
b.sub(String(localized: "Tags"), "tag") { MenuActions.tagsMenu(urls, $0) }
selectMenu(b)
+ for (i, c) in QuickCommands.all.enumerated() where c.inMenu && archive == nil {
+ b.add(c.name, "zap") { [weak self] in self?.runQuickCommand(i) }
+ }
b.menu.addItem(FerryMenu.make(for: urls))
if singleDir, let u = urls.first {
b.separator()
@@ -1947,6 +1954,13 @@ final class FileListController: NSObject, NSTableViewDataSource, NSTableViewDele
}
}
+ /// Runs your command `i` on the folder shown and the selection.
+ func runQuickCommand(_ i: Int) {
+ let all = QuickCommands.all
+ guard all.indices.contains(i) else { return }
+ QuickCommands.run(all[i], folder: url?.isFileURL == true ? url : nil, selection: archive == nil ? selectedURLs : []) { [weak self] e in self?.onError?(e) }
+ }
+
/// "Select": all, none, invert, as the command bar's buttons do (Windows' `select` menu part).
private func selectMenu(_ b: MenuBuilder) {
b.sub(String(localized: "Select"), "list-checks") { m in
diff --git a/macos/Sources/RustyFiles/QuickCommands.swift b/macos/Sources/RustyFiles/QuickCommands.swift
new file mode 100644
index 00000000..10539e46
--- /dev/null
+++ b/macos/Sources/RustyFiles/QuickCommands.swift
@@ -0,0 +1,154 @@
+import AppKit
+
+/// Your own command bar buttons (Windows' quick_commands.rs, toolbar_commands): each runs a
+/// program or opens an app, with {folder} and {selection} in its arguments standing for the
+/// folder shown and the selected items. One marked "in the menu" is in the right-click menu too.
+struct QuickCommand: Codable, Equatable {
+ var label: String
+ /// An app (/Applications/X.app), a program's path, or a command found on the PATH.
+ var program: String
+ var arguments: String
+ var inMenu: Bool
+
+ var name: String {
+ if !label.trimmingCharacters(in: .whitespaces).isEmpty { return label }
+ return ((program as NSString).lastPathComponent as NSString).deletingPathExtension
+ }
+}
+
+@MainActor
+enum QuickCommands {
+ private static let key = "toolbarCommands"
+
+ static var all: [QuickCommand] {
+ get { UserDefaults.standard.data(forKey: key).flatMap { try? JSONDecoder().decode([QuickCommand].self, from: $0) } ?? [] }
+ set {
+ if let data = try? JSONEncoder().encode(newValue) { UserDefaults.standard.set(data, forKey: key) }
+ NotificationCenter.default.post(name: .rfSettingsChanged, object: nil, userInfo: ["key": key])
+ }
+ }
+
+ /// The words of an argument line, "quoted parts" kept together.
+ nonisolated static func split(_ line: String) -> [String] {
+ var out: [String] = [], cur = "", quoted = false, any = false
+ for c in line {
+ if c == "\"" { quoted.toggle(); any = true; continue }
+ if c.isWhitespace && !quoted {
+ if any || !cur.isEmpty { out.append(cur) }
+ cur = ""; any = false
+ continue
+ }
+ cur.append(c)
+ }
+ if any || !cur.isEmpty { out.append(cur) }
+ return out
+ }
+
+ /// The arguments with {folder} and {selection} (%sel%) filled in; nil and a reason when one is missing.
+ nonisolated static func arguments(_ line: String, folder: URL?, selection: [URL]) -> Result<[String], QuickCommandError> {
+ var out: [String] = []
+ for w in split(line) {
+ switch w {
+ case "{folder}":
+ guard let folder else { return .failure(.noFolder) }
+ out.append(folder.path)
+ case "{selection}", "%sel%":
+ guard !selection.isEmpty else { return .failure(.noSelection) }
+ out += selection.map(\.path)
+ default:
+ out.append(w)
+ }
+ }
+ return .success(out)
+ }
+
+ static func run(_ c: QuickCommand, folder: URL?, selection: [URL], onError: @escaping (String) -> Void) {
+ let args: [String]
+ switch arguments(c.arguments, folder: folder, selection: selection) {
+ case .success(let a): args = a
+ case .failure(let e): return onError(e.text)
+ }
+ let program = (c.program.trimmingCharacters(in: .whitespaces) as NSString).expandingTildeInPath
+ if program.hasSuffix(".app") {
+ let app = URL(fileURLWithPath: program)
+ let config = NSWorkspace.OpenConfiguration()
+ // an app given only files opens them; anything else goes to it as arguments
+ let files = args.map { URL(fileURLWithPath: $0) }
+ if !args.isEmpty, args.allSatisfy({ FileManager.default.fileExists(atPath: $0) }) {
+ NSWorkspace.shared.open(files, withApplicationAt: app, configuration: config) { _, e in
+ if let e { DispatchQueue.main.async { onError(e.localizedDescription) } }
+ }
+ } else {
+ config.arguments = args
+ NSWorkspace.shared.openApplication(at: app, configuration: config) { _, e in
+ if let e { DispatchQueue.main.async { onError(e.localizedDescription) } }
+ }
+ }
+ return
+ }
+ let p = Process()
+ if program.contains("/") {
+ p.executableURL = URL(fileURLWithPath: program)
+ p.arguments = args
+ } else {
+ // a name: found on the PATH, as a shell would
+ p.executableURL = URL(fileURLWithPath: "/usr/bin/env")
+ p.arguments = [program] + args
+ }
+ if let folder { p.currentDirectoryURL = folder }
+ p.standardOutput = FileHandle.nullDevice
+ p.standardError = FileHandle.nullDevice
+ do { try p.run() } catch { onError(error.localizedDescription) }
+ }
+
+ /// Adds a command, or changes command `index`.
+ static func edit(_ index: Int?) {
+ let current = index.flatMap { all.indices.contains($0) ? all[$0] : nil }
+ let alert = NSAlert()
+ alert.messageText = current == nil ? String(localized: "New command") : String(localized: "Edit command")
+ alert.informativeText = String(localized: "In the arguments, {folder} is the folder shown and {selection} the selected items.")
+ func field(_ value: String, _ placeholder: String) -> NSTextField {
+ let f = NSTextField(frame: NSRect(x: 0, y: 0, width: 320, height: 24))
+ f.stringValue = value
+ f.placeholderString = placeholder
+ return f
+ }
+ let label = field(current?.label ?? "", String(localized: "Button label"))
+ let program = field(current?.program ?? "", "/Applications/Visual Studio Code.app")
+ let args = field(current?.arguments ?? "", "{selection}")
+ let choose = ClosureButton(title: String(localized: "Choose…"), action: {
+ let panel = NSOpenPanel()
+ panel.directoryURL = URL(fileURLWithPath: "/Applications")
+ panel.treatsFilePackagesAsDirectories = false
+ if panel.runModal() == .OK, let u = panel.url { program.stringValue = u.path }
+ })
+ let menu = NSButton(checkboxWithTitle: String(localized: "In the right-click menu too"), target: nil, action: nil)
+ menu.state = current?.inMenu == true ? .on : .off
+ let stack = NSStackView(views: [label, NSStackView(views: [program, choose]), args, menu])
+ stack.orientation = .vertical
+ stack.alignment = .leading
+ stack.spacing = 8
+ stack.frame = NSRect(x: 0, y: 0, width: 400, height: 130)
+ alert.accessoryView = stack
+ alert.addButton(withTitle: String(localized: "Save"))
+ alert.addButton(withTitle: String(localized: "Cancel"))
+ alert.window.initialFirstResponder = label
+ guard alert.runModal() == .alertFirstButtonReturn else { return }
+ let p = program.stringValue.trimmingCharacters(in: .whitespaces)
+ guard !p.isEmpty else { return }
+ let c = QuickCommand(label: label.stringValue, program: p, arguments: args.stringValue, inMenu: menu.state == .on)
+ var list = all
+ if let index, list.indices.contains(index) { list[index] = c } else { list.append(c) }
+ all = list
+ }
+}
+
+enum QuickCommandError: Error {
+ case noFolder, noSelection
+ var text: String {
+ switch self {
+ case .noFolder: String(localized: "Open a folder first.")
+ case .noSelection: String(localized: "Select files first.")
+ }
+ }
+}
diff --git a/macos/Sources/RustyFiles/SelfTest.swift b/macos/Sources/RustyFiles/SelfTest.swift
index 63618758..3fc00913 100644
--- a/macos/Sources/RustyFiles/SelfTest.swift
+++ b/macos/Sources/RustyFiles/SelfTest.swift
@@ -75,6 +75,12 @@ enum SelfTest {
Thread.sleep(forTimeInterval: 0.3)
check(Lockers.holders([held]).contains { $0.pid == holder.processIdentifier }, "\"Programs using it\" finds a program that has the file open")
holder.terminate()
+ let qa = QuickCommands.arguments("--open \"two words\" {selection} -C {folder}", folder: URL(fileURLWithPath: "/tmp/d"),
+ selection: [URL(fileURLWithPath: "/a b"), URL(fileURLWithPath: "/c")])
+ check((try? qa.get()) == ["--open", "two words", "/a b", "/c", "-C", "/tmp/d"], "a command's arguments get the folder and the selection")
+ if case .failure(.noSelection) = QuickCommands.arguments("{selection}", folder: nil, selection: []) {
+ check(true, "a command that needs a selection says so when there is none")
+ } else { check(false, "a command that needs a selection says so when there is none") }
// 0. the Git look-up ends at the disk's root and finds a repository from inside it (issue 429)
check(GitRepo.repoRoot(URL(fileURLWithPath: "/")) == nil, "no repository above the root")
diff --git a/macos/Sources/RustyFiles/SettingsAppearance.swift b/macos/Sources/RustyFiles/SettingsAppearance.swift
index 028e32c5..effc2b88 100644
--- a/macos/Sources/RustyFiles/SettingsAppearance.swift
+++ b/macos/Sources/RustyFiles/SettingsAppearance.swift
@@ -345,6 +345,18 @@ extension SettingsContent {
rows += AppSettings.ToolbarButton.allCases.map { b in
.card(title: b.title, detail: nil, icon: nil, control: .toggle(get: { AppSettings.showsButton(b) }, set: { AppSettings.setShowsButton(b, $0) }))
}
+ let commands = QuickCommands.all
+ rows.append(.table(
+ title: String(localized: "Your commands"),
+ detail: String(localized: "Buttons of your own after the others: each opens an app or runs a program, with {folder} and {selection} in its arguments."),
+ icon: "zap",
+ entries: commands.map { ($0.name, $0.program + ($0.arguments.isEmpty ? "" : " " + $0.arguments), nil) },
+ empty: String(localized: "No commands yet"),
+ rowActions: [
+ (String(localized: "Edit…"), { QuickCommands.edit($0) }),
+ (String(localized: "Remove"), { i in var l = QuickCommands.all; if l.indices.contains(i) { l.remove(at: i); QuickCommands.all = l } }),
+ ],
+ buttons: [(String(localized: "Add command…"), { QuickCommands.edit(nil) })]))
rows.append(.section(String(localized: "Sidebar sections")))
rows += AppSettings.SidebarSection.allCases.filter { $0 != .tags || TagsSupport.ready }.map { s in
.card(title: s.title, detail: nil, icon: nil, control: .toggle(get: { AppSettings.showsSection(s) }, set: { AppSettings.setShowsSection(s, $0) }))