Source

Murky / Source / HgTempDir.m

Full commit
//
//  HgTempDir.m
//  Murky
//
//  Copyright 2008-2009 Jens Alfke. All rights reserved.
//

#import "HgTempDir.h"

@implementation HgTempDir


static NSString *sRootTempDir;


+ (void) initialize
{
    if( ! sRootTempDir ) {
        sRootTempDir = [NSTemporaryDirectory() stringByAppendingPathComponent: @"Murky"];
        srandomdev();
    }
}


- (id) init
{
    self = [super init];
    if (self != nil) {
        BOOL created;
        do{
            _path = [sRootTempDir stringByAppendingPathComponent: [NSString stringWithFormat: @"temp-%lu", random()]];
            created = [[NSFileManager defaultManager] createDirectoryAtPath: _path
                                                withIntermediateDirectories: YES
                                                                 attributes: nil
                                                                      error: nil];
            //FIX: Should give up if error is not 'duplicate filename'
        }while( ! created );
    }
    return self;
}


- (NSString*) writeData: (id)data toFileNamed: (NSString*)name error: (NSError**)outError
{
    if( ! [data isKindOfClass: [NSData class]] )
        data = [[data description] dataUsingEncoding: NSUTF8StringEncoding];
    NSString *path = [self pathToFileNamed: name];
    if( [data writeToFile: path
                  options: NSAtomicWrite
                    error: outError] )
        return path;
    else
        return nil;
}


- (NSString*) pathToFileNamed: (NSString*)name
{
    return [_path stringByAppendingPathComponent: name];
}


- (BOOL) openFileNamed: (NSString*)name
{
    NSString *bundleID = [[NSUserDefaults standardUserDefaults] stringForKey:kPrefPreferredTextEditorID];
    if (!bundleID)
        bundleID = @"com.apple.TextEdit";
    
    NSArray *urls = [NSArray arrayWithObject: [NSURL fileURLWithPath: [self pathToFileNamed: name]]];
    return [[NSWorkspace sharedWorkspace] openURLs: urls
                           withAppBundleIdentifier: bundleID
                                           options: NSWorkspaceLaunchDefault | NSWorkspaceLaunchWithoutAddingToRecents
                    additionalEventParamDescriptor: nil
                                 launchIdentifiers: nil];
}


- (BOOL) openDataInEditor: (id)data
              asFileNamed: (NSString*)name
                    error: (NSError**)outError
{
    return [self writeData: data toFileNamed: name error: outError]
        && [self openFileNamed: name];
}


@end