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.

3.0 KB
Raw Blame
import AppKit

/// "Programs using it" (Windows' lockers, the reason a delete or a move says another program
/// uses a file): the processes that have the items open, or work in a folder, from lsof. GUI
/// apps among them can be asked to quit.
enum Lockers {
    struct Holder: Hashable, Sendable {
        let pid: Int32
        let name: String
    }

    /// The processes holding `urls` open (a folder: its own files and processes working in it).
    nonisolated static func holders(_ urls: [URL]) -> [Holder] {
        var args = ["-F", "pc", "-w"]
        for u in urls {
            var dir: ObjCBool = false
            if FileManager.default.fileExists(atPath: u.path, isDirectory: &dir), dir.boolValue {
                args += ["+d", u.path]
            } else {
                args += ["--", u.path]
            }
        }
        let p = Process()
        p.executableURL = URL(fileURLWithPath: "/usr/sbin/lsof")
        p.arguments = args
        let out = Pipe()
        p.standardOutput = out
        p.standardError = FileHandle.nullDevice
        guard (try? p.run()) != nil else { return [] }
        let data = out.fileHandleForReading.readDataToEndOfFile()
        p.waitUntilExit()
        var found: [Holder] = []
        var pid: Int32?
        for line in String(decoding: data, as: UTF8.self).split(separator: "\n") {
            if line.hasPrefix("p") { pid = Int32(line.dropFirst()) }
            if line.hasPrefix("c"), let pid, pid != getpid() {
                let app = NSRunningApplication(processIdentifier: pid)?.localizedName
                found.append(Holder(pid: pid, name: app ?? String(line.dropFirst())))
            }
        }
        return Array(Set(found)).sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
    }

    @MainActor
    static func show(_ urls: [URL], window: NSWindow?) {
        Task.detached(priority: .userInitiated) {
            let found = holders(urls)
            await MainActor.run {
                let alert = NSAlert()
                let what = urls.count == 1 ? "“\(urls[0].lastPathComponent)”" : String(localized: "\(urls.count) items")
                if found.isEmpty {
                    alert.messageText = String(localized: "No program is using \(what)")
                    alert.informativeText = String(localized: "Nothing has it open right now.")
                    alert.runModal()
                    return
                }
                alert.messageText = String(localized: "Programs using \(what)")
                alert.informativeText = found.map { "\($0.name) (\($0.pid))" }.joined(separator: "\n")
                let apps = found.compactMap { NSRunningApplication(processIdentifier: $0.pid) }.filter { $0.activationPolicy == .regular }
                alert.addButton(withTitle: String(localized: "OK"))
                if !apps.isEmpty { alert.addButton(withTitle: String(localized: "Quit the apps")) }
                if alert.runModal() == .alertSecondButtonReturn { apps.forEach { $0.terminate() } }
            }
        }
    }
}