Copy file to clipboard


(Jonas Whale) #1

When you copy a file on the Finder, the pasteboard not only contains its path but also other infos like the name or the icon in several formats.

Is it possible to have the same result with AppleScriptObjC?


(Shane Stanley) #2

I don’t think you can get exactly the same result — I’m not sure how the Finder is putting icns there. And Finder doesn’t put the path — it puts the name, plus a URL.

This gets you close:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions

set theURL to current application's |NSURL|'s fileURLWithPath:"/Users/shane/Desktop/Sample.svg"
set theIcon to current application's NSWorkspace's sharedWorkspace()'s iconForFile:(theURL's |path|())
set {theResult, theName} to theURL's getResourceValue:(reference) forKey:(current application's NSURLLocalizedNameKey) |error|:(missing value)
set theClip to current application's NSPasteboard's generalPasteboard()
theClip's clearContents()
theClip's writeObjects:{theURL}
theClip's setString:theName forType:(current application's NSPasteboardTypeString)
theClip's setData:(theIcon's TIFFRepresentation()) forType:(current application's NSPasteboardTypeTIFF)
-- show it
clipboard info

(Jonas Whale) #3

Thanks Shane.
I was trying to copy the name with the writeObjects method.
:wink: