macOS paste: read more image and file kinds, never fail silently
The pasteboard reader now also takes any image AppKit can read (JPEG, HEIC, PDF and others, converted to PNG) and the legacy Finder filenames list. A paste with no files, no image and no text now shows which types the clipboard held instead of doing nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -40,10 +40,17 @@ enum ClipboardFiles {
|
||||
static func read(_ board: NSPasteboard) -> [String: Any] {
|
||||
var files: [[String: Any]] = []
|
||||
var errors: [String] = []
|
||||
let urls =
|
||||
board.readObjects(
|
||||
var urls =
|
||||
(board.readObjects(
|
||||
forClasses: [NSURL.self],
|
||||
options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []
|
||||
options: [.urlReadingFileURLsOnly: true]) ?? []).compactMap { $0 as? URL }
|
||||
// Older apps put a Finder copy only in the legacy filenames list.
|
||||
if urls.isEmpty,
|
||||
let paths = board.propertyList(
|
||||
forType: NSPasteboard.PasteboardType("NSFilenamesPboardType")) as? [String]
|
||||
{
|
||||
urls = paths.map { URL(fileURLWithPath: $0) }
|
||||
}
|
||||
for url in urls {
|
||||
var isDirectory: ObjCBool = false
|
||||
if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory),
|
||||
@@ -67,13 +74,23 @@ enum ClipboardFiles {
|
||||
if urls.isEmpty, let png = image(board) {
|
||||
files.append(["name": "", "mime": "image/png", "bytes": FlutterStandardTypedData(bytes: png)])
|
||||
}
|
||||
return ["files": files, "errors": errors]
|
||||
// What the pasteboard held, so an unreadable paste can say so.
|
||||
let types = (board.types ?? []).map { $0.rawValue }
|
||||
return ["files": files, "errors": errors, "types": types]
|
||||
}
|
||||
|
||||
/// The pasteboard's image as PNG: its own PNG, else its TIFF converted.
|
||||
/// The pasteboard's image as PNG: its own PNG, else its TIFF converted,
|
||||
/// else any image AppKit can read from it (JPEG, HEIC, PDF, ...).
|
||||
private static func image(_ board: NSPasteboard) -> Data? {
|
||||
if let png = board.data(forType: .png) { return png }
|
||||
guard let tiff = board.data(forType: .tiff),
|
||||
if let tiff = board.data(forType: .tiff),
|
||||
let rep = NSBitmapImageRep(data: tiff),
|
||||
let png = rep.representation(using: .png, properties: [:])
|
||||
{
|
||||
return png
|
||||
}
|
||||
guard let image = NSImage(pasteboard: board),
|
||||
let tiff = image.tiffRepresentation,
|
||||
let rep = NSBitmapImageRep(data: tiff)
|
||||
else { return nil }
|
||||
return rep.representation(using: .png, properties: [:])
|
||||
|
||||
Reference in New Issue
Block a user