How to create an application with applescript that will be able to open a file from finder

applescriptapplicationsfinder

I would like to create an application for a command line program I installed with Homebrew. The command's executable is located in /usr/local/bin/ and it accepts files as command line arguments. It's a PDF reader named zathura.

While investigating this topic I learned that an Applescript can be saved as an application. I've managed to do that and I've also managed to make Finder use it primarily as my PDF reader.

I tried writing the following script:

on run argv
    do shell script "/usr/local/bin/zathura " & (item 1 of argv)
end run

If I run this script from the applescript editor, using the play button, the program opens without any file, but that's understandable since I have no way with this interface to specify a file argument.

However, if I save it as an application, put it in the applications folder and click it, I get the error:

Can't make item 1 into type Unicode text (-1700)

Moreover, when I select a file in Finder and try to open it with the new application I just created, nothing happens.

I don't understand why does the script act differently if saved as an application and what are the variables (as argv) that hold the information on the file that Finder would like to open.

Best Answer

Using the argv parameter with the run handler is designed for arguments passed to the script when using it with osascript from the command line. In a regular AppleScript application, an open handler is passed a list of aliases (HFS paths), for example:

on open fileItems
    repeat with anItem in fileItems
        # do something with anItem
    end repeat
end open

From your snippet, you would do something like:

on open fileItems
    do shell script "/usr/local/bin/zathura " & quoted form of POSIX path of item 1 of fileItems
end open

Note that you should use the POSIX path of items when using them with the shell, and the paths should also be quoted or have characters special to the shell escaped.

See the AppleScript Language Guide for more information.