I'm using Scripting Bridge to implement some behavior in an Objective-C program. Much of it works, but I'm having trouble creating Scripting Bridge code that implements the following AppleScript behavior:
set previousApp to the name of the current application -- some stuff happens here that includes "activating" an app tell application previousApp to activate
I want to write two Objective-C methods, one to implement that first line and one to implement that last line. I Google'd a bit, and even used the ASTranslate program, and came up with the following Scripting Bridge code:
#import "SystemEvents.h"
@implementation WindowManagerFunctions
static SystemEventsApplication *systemEventsApp; static SBApplication *previousApp;
int getPreviousApp(void) { NSString *systemEventsAppName = @"com.apple.SystemEvents"; systemEventsApp = [SBApplication applicationWithBundleIdentifier:systemEventsAppName]; if (systemEventsApp == nil) { prependMessageToErrorChain("couldn't find an app named \"%s\"", [systemEventsAppName UTF8String]); return FAILURE; } if ( [systemEventsApp isRunning] ) { for (SystemEventsItem *systemEventsProcess in [systemEventsApp processes]) { NSDictionary *processProperties = [systemEventsProcess properties]; NSString *processName = [processProperties objectForKey:@"name"]; NSString *processIsFront = [processProperties objectForKey:@"frontmost"]; NSLog(@"getPreviousApp: processName = \"%@\", processIsFront = \"%@\"", processName, processIsFront); // here's where I'd set previousApp to the app that has processIsFront == YES } } return SUCCESS; }
int reactivatePreviousApp(void) { [previousApp activate]; return SUCCESS; }
This "works" as far as it goes. It logs a message for each running process, and all of them have a "processIsFront" value of "0" except for one, which has "1".
But it feels like I'm working too hard. When I run the program the first time, it pauses for 5 seconds at the top of the loop. The next time through, no pause. Also, midway through the loop, it pauses on one of the processes for about 8 seconds. I think the process it pauses on is Textexpander or OmniFocus. Anyway, these pauses make getPreviousApp run too slow for my needs. The AppleScript that I'm emulating doesn't pause at all, so I think I'm on the wrong track.
Also, I'm not sure what code I'll use to replace the comment that starts with "here's where" in the code. In other words, given a process represented as a SystemEventsItem, how would I get the corresponding SBApplication?
I'd appreciate any comments, thanks.
-- Pete
|