Mac OSX: interacting with an application programmatically
I am working on a project where I need to call methods for an existing application (my own) and use some of its functionality. Ex. my ThunderBolt app is running on Mac OSX 10.10. It also provides a dictionary of events that can be output externally via Apple Script or in some other way that I don't know yet.
My question is, what are the different (and best) ways for a software application to interact with Mac OSX? If I use something like the following code in Apple Script Editor:
tell application "ThunderBolt"
set open_file to (choose file with prompt "Choose the file you wish to parse")
set theContents to read open_file as data
set retPict to (image convert theContents)
end tell
then it will launch ThunderBolt with a splash screen and then invoke "image conversion". This can be done via NSAppleScript, but it will still launch the application and call methods / events on it.
Is it possible in some way to instantiate (or get a pointer to) one of the classes inside the application and use it? Something similar to COM or automation in Windows?
source to share
If you're working on OS X 10.10, you might want to consider JavaScript for Automation (JXA) .
With it, you can apparently create methods in your application that can be called from client scripts written in JS (although I am not yet familiar with the details on how to deal with implementing such a thing on the application side). But many of the apps that come with OS X Yosemite have APIs that are built-in (like iTunes and Finder).
Here is a great JXA tutorial written by Alex Gaio: http://www.macstories.net/tutorials/getting-started-with-javascript-for-automation-on-yosemite/
The JXA-Cookbook repository also seems to be a good resource: https://github.com/dtinth/JXA-Cookbook/wiki
Here's a quick example - this script makes iTunes go back one track. Try it while iTunes is playing (by placing the text in a script editor, with the language option set to JavaScript, and clicking the Run button):
iTunes = Application('iTunes')
state = iTunes.playerState()
// Console msgs show up in the Messages tab of the bottom view:
console.log("playerState: " + state)
iTunes.backTrack()
Alternatively, you can put the code in a .js file and run it on the command line:
$ osascript itunes-backTrack.js
playerState: playing
source to share