//
//  NSImage+QuickLook.m
//  QuickLookTest
//
//  Created by Matt Gemmell on 29/10/2007.
//

#import "NSImage+QuickLook.h"
#import <QuickLook/QuickLook.h> // Remember to import the QuickLook framework into your project!

@implementation NSImage (QuickLook)


+ (NSImage *)imageWithPreviewOfFileAtPath:(NSString *)path ofSize:(CGSize)cgsize asIcon:(BOOL)icon
{
    NSURL *fileURL = [NSURL fileURLWithPath:path];
    if (!path || !fileURL) {
        return nil;
    }

    NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:icon]
                                                     forKey:(NSString *)kQLThumbnailOptionIconModeKey];
    // edited by tsawada2 2012-05-28
    CGImageRef ref = QLThumbnailImageCreate(kCFAllocatorDefault,
                                            (CFURLRef)fileURL, 
                                            cgsize,
                                            (CFDictionaryRef)dict);
    
    if (ref != NULL) {
        // edited by tsawada2 2012-05-28
        NSImage *newImage = [[NSImage alloc] initWithCGImage:ref size:NSZeroSize];
        if (newImage) {
            CFRelease(ref);
            return [newImage autorelease];
        }
        CFRelease(ref);
    } else {
        // If we couldn't get a Quick Look preview, fall back on the file's Finder icon.
        NSImage *icon = [[NSWorkspace sharedWorkspace] iconForFile:path];
        if (icon) {
            NSSize size = NSSizeFromCGSize(cgsize);
            [icon setSize:size];
        }
        return icon;
    }
    
    return nil;
}


@end
