#import <Foundation/Foundation.h>
#include <Cocoa/Cocoa.h>
const AEEventClass kASAppleScriptSuite = 'ascr';
const AEEventID kASSubroutineEvent = 'psbr';
const AEKeyword keyASSubroutineName = 'snam';
const char* executeAppleScript(const char *script) {
NSString *scriptString = [NSString stringWithUTF8String:script];
NSAppleScript *appleScript = [[NSAppleScript alloc] initWithSource:scriptString];
NSDictionary *errorDict;
NSAppleEventDescriptor *result = [appleScript executeAndReturnError:&errorDict];
if (errorDict) {
NSLog(@"AppleScript Error: %@", errorDict);
return strdup([[errorDict description] UTF8String]);
}
if (result) {
return strdup([[result stringValue] UTF8String]);
}
return strdup("No result");
}
void *compileAppleScript(const char *scriptSource) {
NSString *source = [NSString stringWithUTF8String:scriptSource];
NSAppleScript *appleScript = [[NSAppleScript alloc] initWithSource:source];
NSDictionary *errorDict;
if (![appleScript compileAndReturnError:&errorDict]) {
return NULL;
}
return (__bridge_retained void *)appleScript;
}
const char *executeCompiledAppleScript(void *compiledScript) {
NSAppleScript *appleScript = (__bridge NSAppleScript *)compiledScript;
NSDictionary *errorDict;
NSAppleEventDescriptor *result = [appleScript executeAndReturnError:&errorDict];
if (result) {
return [result.stringValue UTF8String];
} else {
return NULL;
}
}
const char *sendAppleEvent(void *compiledScript, const char *eventCode, const char *parameters) {
NSAppleScript *appleScript = (__bridge NSAppleScript *)compiledScript;
NSString *parameterStr = [NSString stringWithUTF8String:parameters];
NSString *eventCodeStr = [NSString stringWithUTF8String:eventCode];
NSAppleEventDescriptor *handlerNameDescriptor = [NSAppleEventDescriptor descriptorWithString:eventCodeStr];
NSAppleEventDescriptor *parameterDescriptor = [NSAppleEventDescriptor descriptorWithString:parameterStr];
NSAppleEventDescriptor *eventParameter = [NSAppleEventDescriptor listDescriptor];
[eventParameter insertDescriptor:parameterDescriptor atIndex:1];
NSAppleEventDescriptor *event = [NSAppleEventDescriptor appleEventWithEventClass:kASAppleScriptSuite eventID:kASSubroutineEvent targetDescriptor:nil returnID:kAutoGenerateReturnID transactionID:kAnyTransactionID];
[event setParamDescriptor:eventParameter forKeyword:keyDirectObject];
[event setParamDescriptor:handlerNameDescriptor forKeyword:keyASSubroutineName];
NSDictionary *errorDict;
NSAppleEventDescriptor *result = [appleScript executeAppleEvent:event error:&errorDict];
if (result) {
return [result.stringValue UTF8String];
} else {
if (errorDict) {
NSLog(@"AppleScript Execution Error: %@", errorDict);
}
return NULL;
}
}