AppleScript to Cocoa
Volume Number: 16
Issue Number: 7
Column Tag: Mac OS X
Adding AppleScript Support to Cocoa Apps
by Andrew Stone
The divide between user and programmer is effectively bridged with AppleScript -
Apple's scripting language with a natural language syntax. Providing a developer's API
for your application is nice, but far more people will be able to use AppleScript to
interact programmatically with your application. ScriptEditor, the Apple program
which executes AppleScript, ships with OS X in /System/Applications and is available
in BlueBox for OS X Server in the AppleExtras folder.
The good news is that it's very easy to add AppleScript support to Cocoa apps,
especially if you followed my advice last month and designed your application in three
separate pieces: the data model, the view, and the controller. Because AppleScript talks
directly to the data model, most of your work is already done. Cocoa's AppleScript
implementation makes use of the key-value coding that you already have in place, and
it "knows" what methods to call to get and set instance variables of your objects.
This article will explore the basics and then propose a mechanism to add automatic
applescript generation to your application so users can see the script necessary to
create any given document. We'll extend the Sketch application which is provided as
source code in /System/Developer/Examples/AppKit/Sketch. Copy that folder to your
home directory so you can modify it as we go along.
The Basics
There is a complete introduction to AppleScripting in Cocoa in
/System/Documentation/Developer/YellowBox/TasksAndConcepts/
ProgrammingTopics/Scripting/ScriptableApps on OS X Server and
/System/Documentation/Developer/Cocoa/TasksAndConcepts/ProgrammingTopics/
Scripting/ScriptableApps on Developer Preview 3 of Mac OS X. This is a valuable
introduction, but don't get bogged down in the details! What you need to know depends
on how far you want to take it, so let's look at it from a top-down perspective:
There are three major components to your AppleScript implementation: the Script
Suite definition, the Script Terminology, and any additional code required to
implement special commands or special accessor methods. The Script Suite is a
property list which defines the mapping between apple event codes, classes in your
app, and the exposed instance variables of those classes, as well as handled commands.
The Script Terminology is a localized property list which defines the mapping
between your class names and attributes and the actual English (or French, German,
etc) terms used in AppleScript to communicate with the objects in your data model.
Terminology lets AppleScript know what are valid syntactical constructs.
One of your major resources in defining your suite and terminology is the NSCoreSuite