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.

10.5 KB
Raw Blame
import AppKit
import UniformTypeIdentifiers

extension Notification.Name {
    static let rfBookmarksChanged = Notification.Name("rustyfiles.bookmarksChanged")
}

/// A bookmarks bar as browsers have one, under the address bar (Windows' bookmarks.rs, issue
/// 694): a bookmark is a folder or file of this Mac, or a web address; bookmarks can be grouped
/// in folders, which open as menus. Kept in Application Support/rustyfiles/bookmarks.json (the
/// Windows app's format), imported from and exported to the bookmark file browsers write.
enum Bookmark: Codable, Equatable {
    case link(name: String, target: String)
    case folder(name: String, children: [Bookmark])

    var name: String {
        switch self {
        case .link(let n, _), .folder(let n, _): n
        }
    }

    func renamed(_ name: String) -> Bookmark {
        switch self {
        case .link(_, let t): .link(name: name, target: t)
        case .folder(_, let c): .folder(name: name, children: c)
        }
    }

    static func forPath(_ url: URL) -> Bookmark {
        .link(name: url.lastPathComponent.isEmpty ? url.path : url.lastPathComponent, target: url.path)
    }

    /// Where a link leads: a path of this Mac, or nil for a web address.
    static func localPath(_ target: String) -> URL? {
        let t = target.trimmingCharacters(in: .whitespaces)
        return t.hasPrefix("/") || t.hasPrefix("~") ? URL(fileURLWithPath: (t as NSString).expandingTildeInPath) : nil
    }

    // the Windows app's JSON: {"kind":"link","name":…,"target":…} / {"kind":"folder","name":…,"children":[…]}
    private enum Keys: String, CodingKey { case kind, name, target, children }

    init(from decoder: Decoder) throws {
        let c = try decoder.container(keyedBy: Keys.self)
        let name = try c.decode(String.self, forKey: .name)
        if try c.decode(String.self, forKey: .kind) == "folder" {
            self = .folder(name: name, children: try c.decodeIfPresent([Bookmark].self, forKey: .children) ?? [])
        } else {
            self = .link(name: name, target: try c.decode(String.self, forKey: .target))
        }
    }

    func encode(to encoder: Encoder) throws {
        var c = encoder.container(keyedBy: Keys.self)
        switch self {
        case .link(let n, let t):
            try c.encode("link", forKey: .kind)
            try c.encode(n, forKey: .name)
            try c.encode(t, forKey: .target)
        case .folder(let n, let ch):
            try c.encode("folder", forKey: .kind)
            try c.encode(n, forKey: .name)
            try c.encode(ch, forKey: .children)
        }
    }
}

@MainActor
enum Bookmarks {
    private static var file: URL {
        let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("rustyfiles", isDirectory: true)
        try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
        return dir.appendingPathComponent("bookmarks.json")
    }

    private static var loaded: [Bookmark]?

    static var items: [Bookmark] {
        if let loaded { return loaded }
        let read = (try? Data(contentsOf: file)).flatMap { try? JSONDecoder().decode([Bookmark].self, from: $0) } ?? []
        loaded = read
        return read
    }

    static func update(_ change: (inout [Bookmark]) -> Void) {
        var list = items
        change(&list)
        loaded = list
        let enc = JSONEncoder()
        enc.outputFormatting = .prettyPrinted
        if let data = try? enc.encode(list) { try? data.write(to: file, options: .atomic) }
        NotificationCenter.default.post(name: .rfBookmarksChanged, object: nil)
    }

    static func add(_ urls: [URL]) {
        update { list in
            for u in urls where !list.contains(where: { if case .link(_, let t) = $0 { return t == u.path } else { return false } }) {
                list.append(.forPath(u))
            }
        }
    }

    static func contains(_ url: URL) -> Bool {
        items.contains { if case .link(_, let t) = $0 { return t == url.path } else { return false } }
    }

    // MARK: the Netscape bookmark file ("bookmarks.html")

    private static func unescape(_ s: String) -> String {
        s.trimmingCharacters(in: .whitespacesAndNewlines)
            .replacingOccurrences(of: "&lt;", with: "<").replacingOccurrences(of: "&gt;", with: ">")
            .replacingOccurrences(of: "&quot;", with: "\"").replacingOccurrences(of: "&#39;", with: "'")
            .replacingOccurrences(of: "&amp;", with: "&")
    }

    private static func escape(_ s: String) -> String {
        s.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
            .replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
    }

    private static func attr(_ tag: String, _ name: String) -> String? {
        guard let r = tag.range(of: name + "=\"", options: .caseInsensitive) else { return nil }
        let rest = tag[r.upperBound...]
        guard let end = rest.firstIndex(of: "\"") else { return nil }
        return String(rest[..<end])
    }

    /// A file's address as a link's target: `file:///Users/a/My%20Folder` is that path; a
    /// Windows path (`file:///D:/…`) stays an address, since it means nothing here.
    private static func target(of href: String) -> String {
        if let u = URL(string: href), u.isFileURL, !u.path.isEmpty, !(u.path.dropFirst().first?.isLetter == true && u.path.dropFirst(2).first == ":") {
            return u.path
        }
        return href
    }

    private static func href(of target: String) -> String {
        Bookmark.localPath(target).map { $0.absoluteString } ?? target
    }

    /// The bookmarks of a bookmark file: the folder it marks as the toolbar's first, as browsers
    /// read it, then whatever else it has, its folders as folders.
    static func parse(_ text: String) -> [Bookmark] {
        let s = Array(text.unicodeScalars)
        // (tags and attributes are ASCII: only those letters are lowered, so both have one length)
        let lower = s.map { $0.value >= 65 && $0.value <= 90 ? Unicode.Scalar($0.value + 32)! : $0 }
        func find(_ needle: String, from: Int) -> Int? {
            let n = Array(needle.unicodeScalars)
            guard !n.isEmpty, from <= lower.count - n.count else { return nil }
            var i = from
            while i <= lower.count - n.count {
                if lower[i] == n[0] && Array(lower[i..<(i + n.count)]) == n { return i }
                i += 1
            }
            return nil
        }
        func str(_ a: [Unicode.Scalar], _ r: Range<Int>) -> String { String(String.UnicodeScalarView(a[r])) }
        var stack: [(name: String, children: [Bookmark], toolbar: Bool)] = [("", [], false)]
        var header: (String, Bool)?
        var toolbar: [Bookmark]?
        var i = 0
        func close() {
            let top = stack.removeLast()
            if top.toolbar && toolbar == nil {
                toolbar = top.children
            } else if top.name.isEmpty {
                stack[stack.count - 1].children += top.children
            } else {
                stack[stack.count - 1].children.append(.folder(name: top.name, children: top.children))
            }
        }
        while let start = find("<", from: i) {
            guard let end = find(">", from: start) else { break }
            let tag = str(lower, (start + 1)..<end)
            let raw = str(s, (start + 1)..<end)
            i = end + 1
            if tag.hasPrefix("h3") {
                let c = find("</h3>", from: i) ?? i
                header = (unescape(str(s, i..<c)), tag.contains("personal_toolbar_folder=\"true\""))
                i = c
            } else if tag == "a" || tag.hasPrefix("a ") {
                let c = find("</a>", from: i) ?? i
                let name = unescape(str(s, i..<c))
                if let h = attr(raw, "href") {
                    let t = target(of: unescape(h))
                    stack[stack.count - 1].children.append(.link(name: name.isEmpty ? t : name, target: t))
                }
                i = c
            } else if tag.hasPrefix("dl") {
                let (name, isToolbar) = header ?? ("", false)
                header = nil
                stack.append((name, [], isToolbar))
            } else if tag.hasPrefix("/dl"), stack.count > 1 {
                close()
            }
        }
        while stack.count > 1 { close() }
        return (toolbar ?? []) + stack[0].children
    }

    /// The bar as a bookmark file, its bookmarks in the toolbar's folder (browsers read it back as their bar).
    static func toHTML(_ items: [Bookmark]) -> String {
        func write(_ out: inout String, _ items: [Bookmark], _ depth: Int) {
            let pad = String(repeating: "    ", count: depth)
            for b in items {
                switch b {
                case .link(let n, let t):
                    out += "\(pad)<DT><A HREF=\"\(escape(href(of: t)))\">\(escape(n))</A>\n"
                case .folder(let n, let c):
                    out += "\(pad)<DT><H3>\(escape(n))</H3>\n\(pad)<DL><p>\n"
                    write(&out, c, depth + 1)
                    out += "\(pad)</DL><p>\n"
                }
            }
        }
        let now = Int(Date().timeIntervalSince1970)
        var out = "<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<!-- This is an automatically generated file.\n     It will be read and overwritten.\n     DO NOT EDIT! -->\n<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">\n<TITLE>Bookmarks</TITLE>\n<H1>Bookmarks</H1>\n<DL><p>\n"
        out += "    <DT><H3 ADD_DATE=\"\(now)\" LAST_MODIFIED=\"\(now)\" PERSONAL_TOOLBAR_FOLDER=\"true\">Bookmarks</H3>\n    <DL><p>\n"
        write(&out, items, 2)
        out += "    </DL><p>\n</DL><p>\n"
        return out
    }

    static func importFile(from window: NSWindow?) {
        let panel = NSOpenPanel()
        panel.allowedContentTypes = [.html]
        panel.message = String(localized: "Choose a bookmark file exported from a browser.")
        guard panel.runModal() == .OK, let u = panel.url, let text = try? String(contentsOf: u, encoding: .utf8) else { return }
        let read = parse(text)
        guard !read.isEmpty else {
            NSSound.beep()
            return
        }
        update { $0 += read }
    }

    static func exportFile(from window: NSWindow?) {
        let panel = NSSavePanel()
        panel.allowedContentTypes = [.html]
        panel.nameFieldStringValue = "bookmarks.html"
        guard panel.runModal() == .OK, let u = panel.url else { return }
        try? toHTML(items).write(to: u, atomically: true, encoding: .utf8)
    }
}