views:

119

answers:

1

Given that NSAppleScript objects are always supposed to run on the main thread, I created a small "proxy" object to use:

@interface AppleScriptProxy : NSObject {
    NSAppleScript *m_script;
    NSDictionary *m_errorDict;
}

- (id) init;

- (void) compileScript:
    (NSString*)script;

- (void) dealloc;

- (NSDictionary*) errorDict;

- (BOOL) failed;

- (void) runScript:
    (id)notUsed;

@end

@implementation AppleScriptProxy

- (id) init
{
    self = [super init];
    m_errorDict = nil;
    m_script = nil;
    return self;
}

- (void) dealloc
{
    //[m_errorDict release];
    [m_script release];
    [super dealloc];
}

- (void) compileScript:
    (NSString*)source
{
    m_script = [[NSAppleScript alloc] initWithSource:source];
    if ( m_script )
        if ( [m_script compileAndReturnError:&m_errorDict] ) {
            cerr << "compiled" << endl;
            [m_script retain];
        } else {
            cerr << "not compiled" << endl;
            m_script = nil;
        }
}

- (NSDictionary*) errorDict
{
    return m_errorDict;
}

- (BOOL) failed
{
    return !m_script || m_errorDict;
}

- (void) runScript:
    (id)notUsed
{
    [m_script executeAndReturnError:nil];
}

@end

Then, to compile and execute an AppleScript:

NSString *const script = /* some script */;

[proxy
    performSelectorOnMainThread:@selector(compileScript:)
    withObject:script waitUntilDone:YES];

if ( [proxy failed] ) {
    NSDictionary *errorDict = [proxy errorDict];
    NSString const *const errorMsg = errorDict ?
        [errorDict objectForKey:NSAppleScriptErrorMessage] :
        @"NSAppleScript initWithSource failed";
    cerr << [errorMsg UTF8String] << endl;
    return 1;
}

[proxy retain];
[proxy
    performSelectorOnMainThread:@selector(runScript:)
    withObject:nil waitUntilDone:NO];
[proxy autorelease];

If I compile a valid script, it works as expected; however, if I compile a gibberish script, e.g., "foo", compileAndReturnError doesn't fail, i.e., it returns YES and m_errorDict is still nil.

Why?

+1  A: 

Try it in Script Editor. “foo” compiles just fine; it just doesn't run.

Try “*” as your compile-test script.

BTW, running a script can raise an error, too (as you can see in Script Editor). Make sure you handle that.

Peter Hosey