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.6 KB
Raw Blame
import AppKit
import UniformTypeIdentifiers

/// What another app drops without a file of its own (Windows 0.9.3: pictures from a browser,
/// Outlook's attachments): file promises (Mail, Photos, Safari's pictures) are written into the
/// folder; a bare picture (Chrome) is saved as a PNG; a web link becomes a .webloc.
@MainActor
enum ForeignDrop {
    static let types: [NSPasteboard.PasteboardType] = [.png, .tiff, .URL]

    static func carries(_ info: NSDraggingInfo) -> Bool {
        let pb = info.draggingPasteboard
        if ArchiveDrag.current == nil, pb.canReadObject(forClasses: [NSFilePromiseReceiver.self], options: nil) { return true }
        if pb.data(forType: .png) != nil || pb.data(forType: .tiff) != nil { return true }
        return webLink(pb) != nil
    }

    private static func webLink(_ pb: NSPasteboard) -> URL? {
        guard let u = (pb.readObjects(forClasses: [NSURL.self], options: nil) as? [URL])?.first, !u.isFileURL,
              let scheme = u.scheme?.lowercased(), scheme == "http" || scheme == "https" else { return nil }
        return u
    }

    /// Writes what was dropped into `dest`; `done` gets the new items (on the main thread).
    static func receive(_ info: NSDraggingInfo, into dest: URL, done: @escaping ([URL], Error?) -> Void) {
        let pb = info.draggingPasteboard
        if let receivers = pb.readObjects(forClasses: [NSFilePromiseReceiver.self], options: nil) as? [NSFilePromiseReceiver], !receivers.isEmpty {
            let queue = OperationQueue()
            queue.qualityOfService = .userInitiated
            var made: [URL] = []
            var firstError: Error?
            let group = DispatchGroup()
            for r in receivers {
                group.enter()
                r.receivePromisedFiles(atDestination: dest, options: [:], operationQueue: queue) { url, error in
                    DispatchQueue.main.async {
                        if let error { firstError = firstError ?? error } else { made.append(url) }
                        group.leave()
                    }
                }
            }
            group.notify(queue: .main) { done(made, firstError) }
            return
        }
        let name = suggestedName(pb)
        if let data = pb.data(forType: .png) ?? pb.data(forType: .tiff).flatMap({ NSBitmapImageRep(data: $0)?.representation(using: .png, properties: [:]) }) {
            let to = FileOps.unique(name ?? String(localized: "Picture"), ext: "png", in: dest)
            do {
                try data.write(to: to, options: .withoutOverwriting)
                done([to], nil)
            } catch { done([], error) }
            return
        }
        if let link = webLink(pb) {
            let title = (pb.string(forType: NSPasteboard.PasteboardType("public.url-name")) ?? link.host ?? "Link")
                .replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: ":", with: "-")
            let to = FileOps.unique(title, ext: "webloc", in: dest)
            do {
                let plist = try PropertyListSerialization.data(fromPropertyList: ["URL": link.absoluteString], format: .xml, options: 0)
                try plist.write(to: to, options: .withoutOverwriting)
                done([to], nil)
            } catch { done([], error) }
        }
    }

    /// A picture's name from the link it came from (its last part, without the extension).
    private static func suggestedName(_ pb: NSPasteboard) -> String? {
        guard let u = (pb.readObjects(forClasses: [NSURL.self], options: nil) as? [URL])?.first, !u.isFileURL else { return nil }
        let base = (u.lastPathComponent as NSString).deletingPathExtension
        return base.isEmpty || base == "/" ? nil : base
    }
}