Making A Mac App Scriptable Tutorial

Allow users to write scripts to control your OS X app – giving it unprecedented usability. Discover how in this “Making a Mac App Scriptable Tutorial”. By Sarah Reichelt.

5 (1) · 1 Review

Save for later
Share

Update 9/21/16: This tutorial has been updated for Xcode 8 and Swift 3.

As an app developer, it’s near impossible to think of all the ways people will want to use your app. Wouldn’t it be cool to let your users create scripts to customize your app to their own personal needs?

With Applescript and Javascript for Automation (JXA), you can! In this making a Mac app scriptable tutorial you will discover how to add scripting capabilities to a sample application. You’ll start by learning how to control existing apps with scripting, and then extend a sample app to allow custom script actions.

Getting Started

Download the sample project, open it in Xcode and build and run to see how it looks:

Making a mac app scriptable tutorial: Scriptable Tasks app

The app shows a list of tasks with due dates in the next few days and the tags associated with each task. It uses an outline view to group the tasks by due date.

Note: Want to know more about outline views? Check out the NSOutlineView on OS X Tutorial on this site.

You might have noticed that you can’t add, edit, or delete any tasks. That’s by design – these actions will be handled by your user automation scripts.

Take a a look at the files in the project:

Making a mac app scriptable tutorial: Scriptable Tasks Project

  • There are 2 model class files: Task.swift and Tag.swift. These are the classes that you will be scripting.
  • The ViewController group handles the display and watches for changes in the data.
  • The Data group has a file with the sample tasks and a DataProvider that reads those tasks and handles any edits that arrive.
  • The AppDelegate uses a DataProvider object to keep a record of the app’s tasks.
  • The ScriptableTasks.sdef file is a crucial file…which you will explore in detail later.

There are sample scripts for this tutorial as well; download them here. There are two folders in this package: one for AppleScript and one for JavaScript. Since this tutorial isn’t focused on how to write scripts, you’ll be using each of the downloaded scripts to test the functionality that you’ll add to Scriptable Tasks.

Enough with the talk – time to move on to the scripting! :]

Using the Script Editor

Open up the Script Editor app, found in Applications/Utilities, and open a new document:

Making a mac app scriptable tutorial: Script Editor

You’ll see a set of four buttons in the top toolbar: Record, Stop, Run, and Compile. Compile checks that your scripting is syntactically correct, and Run does pretty much what what you’d expect.

At the bottom of the window, you’ll see three icons which switch between views. Description lets you add some information about your script, while Result shows the final result of running a script. The most useful option is the third button: Log.

The Log offers a further four options: Result, Messages, Events and Replies. Replies is the most informative, as it shows a log of every command and the return value of that command. When testing any scripts, I highly recommend the Log in Replies mode.

Note: If you ever open an AppleScript file and find it contains code like this: «class TaSk» whose «class TrFa» is false and «class CrDa», click Compile and it will be translated to readable AppleScript, provided you have the target app installed.

There are two scripting languages you’ll cover in this tutorial. The first is AppleScript, introduced with Mac System 7 in 1991, which uses an English-like syntax to make it usable by coders and non-coders alike.

The second is JavaScript for Automation (JXA), introduced by OSX Yosemite, which lets coders use the familiar JavaScript syntax to build their automation tasks.

The scripts in this tutorial will be presented in both AppleScript and JXA, so you’re free to wander down the path of whichever language you’d like to explore. :]

Note: Throughout this tutorial, the scripting code snippets are presented in AppleScript first, and immediately followed by the equivalent JavaScript version.

Exploring App Scripting With TextEdit

There’s a great little app already installed on your Mac that supports scripting: TextEdit. In the Script Editor, select Window/Library and look for the TextEdit entry. If it’s not there, click the Plus button at the top, navigate to your Applications folder and add TextEdit. Then double-click the TextEdit entry to open the TextEdit dictionary:

Making a mac app scriptable tutorial: Text Edit Dictionary

Every scriptable app has a dictionary, stored in a scripting definition (SDEF) file. The dictionary tells you what objects the app has, what properties the objects have and what commands the app responds to. In the above screen shot, you can see that TextEdit has paragraphs, and paragraphs have color and font properties. You will use this information to style some text.

Open 1. TextEdit Write.scpt from either the AppleScript or the JavaScript folder. Run the script; you’ll see TextEdit create and save a document.

You now have a new document, but it needs a bit of styling. Open 2. TextEdit Read Edit.scpt, run this script and you’ll see the document re-opened and styled as per the script.

Although delving into the actual script is beyond the scope of this tutorial, feel free to read the scripts in detail to see how they act on the TextEdit document.

As mentioned in the introduction, all apps are scriptable to some extent. To see this in action, ensure Scriptable Tasks is running. Next, open a new script window in Script Editor and enter one of the following scripts, depending on which language you’re using:

-- AppleScript
tell application "Scriptable Tasks" to quit

or

// JavaScript
Application("Scriptable Tasks"). quit();

Click Run and Scriptable Tasks should quit. Change the script to the following and click Run again:

tell application "Scriptable Tasks" to launch

or

Application("Scriptable Tasks").launch();

The app restarts, but doesn’t come to the foreground. To bring the app into focus, change launch to activate in the script above and click Run.

Now that you’ve seen that apps can respond to scripting commands, it’s time to add this ability to your app.

Making Your App Scriptable

The scripting definition file of your app defines what the app can do; it’s a little like an API. This file lives in your app project and specifies several things:

  • Standard scripting objects and commands, such as window, make, delete, count, open and quit.
  • Your own scriptable objects, properties and custom commands.

In order to make classes in your app scriptable, there are a few changes you’ll need to make to the app.

First, the scripting interface uses Key-Value-Coding to get and set the properties of objects. In Objective-C, all objects conformed to the KVC protocol automatically, but Swift objects don’t do so unless you make them subclasses of NSObject.

Next, scriptable classes need an Objective-C name that the scripting interface can recognize. To avoid namespace conflicts, Swift object names are mangled to give a unique representation. By prefixing the class definitions with @objc(YourClassName), you give them a name that can be used by the scripting engine.

Scriptable classes need object specifiers to help locate a particular object within the application or parent object, and finally, the app delegate must have access to the data store so it can return the application’s data to the scripts.

You don’t necessarily have to start your own scripting definition file from scratch, as Apple provides a standard SDEF file that you can use. Look in the /System/Library/ScriptingDefinitions/ directory for CocoaStandard.sdef. Open this file in Xcode and have a look; it’s XML with specific headers, a dictionary and inside that, the Standard Suite.

This is a useful starting point, and you could copy and paste this XML into your own SDEF file. However, in the interest of clean code, it’s not a good idea to leave your SDEF file full of commands and objects that your app does not support. To this end, the sample project contains a starter SDEF file with all unnecessary entries removed.

Close CocoaStandard.sdef and open ScriptableTasks.sdef. Add the following code near the end at the Insert Scriptable Tasks suite here comment:

<!-- 1 -->
<suite name="Scriptable Tasks Suite" code="ScTa" description="Scriptable Tasks suite.">
  <!-- 2 -->
  <class name="application" code="capp" description="An application's top level scripting object.">
    <cocoa class="NSApplication"/>

    <!-- 3 -->
    <element type="task" access="r">
      <cocoa key="tasks"/>
    </element>
  </class>

  <!-- Insert command here -->

  <!-- 4 -->
  <class name="task" code="TaSk" description="A task item" inherits="item" plural="tasks">
      <cocoa class="Task"/>

      <!-- 5 -->
      <property name="id" code="ID  " type="text" access="r"
          description="The unique identifier of the task.">
          <cocoa key="id"/>
      </property>

      <property name="name" code="pnam" type="text" access="rw"
          description="The title of the task.">
          <cocoa key="title"/>
      </property>

      <!-- 6 -->
      <property name="daysUntilDue" code="CrDa" type="number" access="rw"
      description="The number of days before this task is due."/>
      <property name="completed" code="TrFa" type="boolean" access="rw"
      description="Has the task been completed?"/>
      
      <!-- 7 -->
      <!-- Insert element of tags here -->
      
      <!-- Insert responds-to command here -->
      
  </class>
  
  <!-- Insert tag class here -->
  
</suite>

This chunk of XML does a lot of work. Taking it bit by bit:

"ID " is read-only, as scripts should not change a unique identifier, but "pnam" is read-write. Both of these are text properties. The "pnam" property maps to the title property of the Task object.

  1. The outermost element is a suite, so your SDEF file now has two suites: Standard Suite and Scriptable Tasks Suite. Everything in the SDEF file needs a four-character code. Apple codes are nearly always in lower-case and you will use a few of them for specific purposes. For your own suites, classes and properties, it’s best to use a random mix of upper-case, lower-case and symbols to avoid conflicts.
  2. The next section defines the application and must use the code "capp". You must specify the class of the application; if you had subclassed NSApplication, you would use your subclass name here.
  3. The application contains elements. In this app, the elements are stored in an array called tasks in the app delegate. In scripting terms, elements are the objects that the app or other objects can contain.
  4. The last chunk defines the Task class that the application contains. The plural name for accessing multiples is tasks. The class in the app that backs this object type is Task.
  5. The first two properties are special. Look at their codes: "ID " and "pnam". "ID " (note the two spaces after the letters) identifies the unique identifier of the object. "pnam" specifies the name property of the object. You can access objects directly using either of these properties.
  6. The remaining two properties are a number property for daysUntilDue and a Boolean for completed. They use the same name in the object and the script, so you don’t need to specify the cocoa key.
  7. The “Insert…” comments are placeholders for when you need to add more to this file.

Open Info.plist, right-click in the blank space below the entries and select Add Row. Type an upper-case S and the list of suggestions will scroll to Scriptable. Select it and change the setting to YES.

Repeat this process to select the next item down: Scripting definition file name. Set this to the name of your SDEF file: ScriptableTasks.sdef

If you prefer to edit the Info.plist as source code, you can alternatively add the following entries inside the main dict:

<key>NSAppleScriptEnabled</key>
<true/>
<key>OSAScriptingDefinition</key>
<string>ScriptableTasks.sdef</string>

Now you have to modify the app delegate to handle requests that come via script.

Open AppDelegate.swift file and add the following to the end of the file:

extension AppDelegate {
  // 1
  override func application(_ sender: NSApplication, delegateHandlesKey key: String) -> Bool {
    return key == "tasks"
  }

  // 2
  func insertObject(_ object: Task, inTasksAtIndex index: Int) {
    tasks = dataProvider.insertNew(task: object, at: index)
  }

  func removeObjectFromTasksAtIndex(_ index: Int) {
    tasks = dataProvider.deleteTask(at: index)
  }
}

Here’s what’s going on in the code above:

  1. When a script asks for tasks data, this method will confirm that the app delegate can handle it.
  2. If a script tries to insert, edit or delete data, these methods will pass those requests along to dataProvider.

To make the Task model class available to the scripts, you have to do a bit more coding.

Open Task.swift and change the class definition line to the following:

@objc(Task) class Task: NSObject {

Xcode will immediately complain that init requires the override keyword, so let Fix-It do that. This is required as this class now has a superclass:

override init() {

Task.swift needs one more change: an object specifier. Insert the following method into the Task class:

override var objectSpecifier: NSScriptObjectSpecifier {
  // 1
  let appDescription = NSApplication.shared().classDescription as! NSScriptClassDescription

  // 2
  let specifier = NSUniqueIDSpecifier(containerClassDescription: appDescription,
                                      containerSpecifier: nil, key: "tasks", uniqueID: id)
  return specifier
}

Taking each numbered comment in turn:

  1. Get a description of the app’s class since the app is the container for tasks.
  2. Get a description of the task by id within the app. This is why the Task class has an id property – so that each task can be correctly specified.

You’re finally ready to start scripting your app!