import AppKit import PlakServices /// One image on a pasteboard: a file to copy, or raw data to write as PNG. public enum PasteboardImage: Equatable { case file(URL) case data(Data) } /// Reads the images a paste or a drop brings. public enum PasteboardImages { public static let dragTypes: [NSPasteboard.PasteboardType] = [.fileURL, .png, .tiff] /// The images on the pasteboard, empty when it holds none. /// /// File URLs win over data: Finder puts the file icon as TIFF next to a copied file. Rich /// text keeps its picture of the text out, so a paste from a word processor stays text. public static func read(_ pasteboard: NSPasteboard) -> [PasteboardImage] { let urls = fileURLs(pasteboard) if !urls.isEmpty { return urls.filter(ImageStore.isImageFile).map(PasteboardImage.file) } guard hasImageData(pasteboard) else { return [] } if let png = pasteboard.data(forType: .png) { return [.data(png)] } if let tiff = pasteboard.data(forType: .tiff) { return [.data(tiff)] } return [] } /// Whether `read` finds an image, without loading image data, for every move of a drag. public static func contains(_ pasteboard: NSPasteboard) -> Bool { let urls = fileURLs(pasteboard) return urls.isEmpty ? hasImageData(pasteboard) : urls.contains(where: ImageStore.isImageFile) } private static func fileURLs(_ pasteboard: NSPasteboard) -> [URL] { pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? [] } private static func hasImageData(_ pasteboard: NSPasteboard) -> Bool { let types = pasteboard.types ?? [] if types.contains(.rtf) || types.contains(.rtfd) { return false } return types.contains(.png) || types.contains(.tiff) } }