views:

108

answers:

2

I'm trying to get a current directory of a finder window that is in focus from another cocoa application that is running in a background. I know that it can be done using an applescript like:

tell application "Finder"
try
  set dir to (the target of the front window) as alias
on error
  set dir to startup disk
end try
end tell

However I was wondering whether there is some more generic way of doing it either using the accessibility API or some other UI scripting with perhaps System Event?

I tried attributes like NSAccessibilityDocumentAttribute or NSAccessibilityURLAttribute but none is set. From other mostly document based applications this works pretty well, but not for finder nor for terminal.app.

+1  A: 

Take a look at the Scripting Bridge framework, that's probably going to be the easiest way to get the info you want directly from your Cocoa application.

Brian Webster
As I don't have votes left, I will virtually give a +1 to the answer.
kiamlaluno
I guess I should have expressed myself better. I know how to execute applescript from within cocoa, the question was whether there is a way how to get the current directory of a finder accessibility API or if there is some more generic way to obtain this information.
fikovnik
A: 

@nkuyu, I just saw your comment that you know how to run an applescript... but for others who don't (and might stumble onto this post) I'll explain.

It's easy to run an applescript from objc using NSApplescript. And if you return a string from your applescript it's even easier to get a result because you can get the "stringValue" from the NSAppleEventDescriptor. As such I return "posix paths" from the applescript. Note that NSApplescript is not thread-safe so in multi-threaded apps you must take care to always run it on the main thread. Try this...

-(IBAction)runApplescript:(id)sender {
    [self performSelectorOnMainThread:@selector(getFrontFinderWindowTarget) withObject:nil waitUntilDone:NO];
}

-(void)getFrontFinderWindowTarget {
    NSString* theTarget = nil;
    NSString* cmd = @"tell application \"Finder\"\ntry\nset dir to the target of the front window\nreturn POSIX path of (dir as text)\non error\nreturn \"/\"\nend try\nend tell";
    NSAppleScript* theScript = [[NSAppleScript alloc] initWithSource:cmd];

    NSDictionary* errorDict = nil;
    NSAppleEventDescriptor* result = [theScript executeAndReturnError:&errorDict];
    [theScript release];
    if (errorDict) {
        theTarget = [NSString stringWithFormat:@"Error:%@ %@", [errorDict valueForKey:@"NSAppleScriptErrorNumber"], [errorDict valueForKey:@"NSAppleScriptErrorMessage"]];
    } else {
        theTarget = [result stringValue];
    }
    [self getFrontFinderWindowTargetResult:theTarget];
}

-(void)getFrontFinderWindowTargetResult:(NSString*)result {
    NSLog(@"result: %@", result);
}
regulus6633