When one copies a file in Finder, the pasteboard contains a 'icns' type with the various icon descriptions of the copied item(s).
I need to accomplish the same effect in my code, i.e. generate the data I can put into the pasteboard for the com.apple.icns
type.
How do I collect the data for this type? All I can find in AppKit are functions for getting an NSImage for a file, but nothing that gives me the icns resource.
Here's code, using deprecated functions (but there's no modern alternative, apparently):
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
NSData* icnsOfFileAtPath (NSString *path)
{
// based on https://github.com/sveinbjornt/IconFamily
CFURLRef urlRef = CFURLCreateWithFileSystemPath (kCFAllocatorDefault, (CFStringRef)path, kCFURLPOSIXPathStyle, false);
if (!urlRef) {
return nil;
}
FSRef fsRef;
bool ok = CFURLGetFSRef (urlRef, &fsRef);
CFRelease (urlRef);
if (!ok) {
return nil;
}
IconRef iconRef;
SInt16 label;
OSStatus res = GetIconRefFromFileInfo (&fsRef, 0, NULL, kFSCatInfoNone, NULL, kIconServicesNormalUsageFlag, &iconRef, &label);
if (res) {
return nil;
}
IconFamilyHandle ifh;
res = IconRefToIconFamily (iconRef, kSelectorAllAvailableData, &ifh);
ReleaseIconRef (iconRef);
NSData *icns = [NSData dataWithBytes:*ifh length:GetHandleSize((Handle)ifh)];
DisposeHandle ((Handle)ifh);
return icns;
}
#pragma clang diagnostic pop