Automator AppleScript Actions Tutorial
Automator AppleScript Actions Tutorial
2007-07-18
IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR
Apple Inc. CONSEQUENTIAL DAMAGES RESULTING FROM ANY
© 2005, 2007 Apple Inc. DEFECT OR INACCURACY IN THIS DOCUMENT, even
if advised of the possibility of such damages.
All rights reserved.
THE WARRANTY AND REMEDIES SET FORTH ABOVE
ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL
No part of this publication may be reproduced, OR WRITTEN, EXPRESS OR IMPLIED. No Apple
stored in a retrieval system, or transmitted, in dealer, agent, or employee is authorized to make
any modification, extension, or addition to this
any form or by any means, mechanical, warranty.
electronic, photocopying, recording, or Some states do not allow the exclusion or limitation
otherwise, without prior written permission of of implied warranties or liability for incidental or
consequential damages, so the above limitation or
Apple Inc., with the following exceptions: Any exclusion may not apply to you. This warranty gives
person is hereby authorized to store you specific legal rights, and you may also have
documentation on a single computer for other rights which vary from state to state.
personal use only and to print copies of
documentation for personal use provided that
the documentation contains Apple’s copyright
notice.
The Apple logo is a trademark of Apple Inc.
Use of the “keyboard” Apple logo
(Option-Shift-K) for commercial purposes
without the prior written consent of Apple may
constitute trademark infringement and unfair
competition in violation of federal and state
laws.
No licenses, express or implied, are granted
with respect to any of the technology described
in this document. Apple retains all intellectual
property rights associated with the technology
described in this document. This document is
intended to assist application developers to
develop applications only for Apple-labeled
computers.
Every effort has been made to ensure that the
information in this document is accurate. Apple
is not responsible for typographical errors.
Apple Inc.
1 Infinite Loop
Cupertino, CA 95014
408-996-1010
Bindings in an Action 23
Establishing the Bindings of the Action 24
Alternatives to Bindings 27
3
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
CONTENTS
4
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
Figures
Figure 3-1 The nib file window, initial action view, and palette 17
Figure 3-2 Automator icon 18
Figure 3-3 Placing a text field by dragging it from the palette 19
Figure 3-4 Setting the size attribute of the text field 20
Figure 3-5 Resizing the text field 20
Figure 3-6 Changing the string in a in a non-editable text field (a label) 21
Figure 3-7 Changing the number of radio buttons in a matrix (radio buttons) 22
Figure 3-8 Changing the title of a button 22
Figure 3-9 Final user interface of Pass Random Items action 22
Figure 4-1 Binding between the pop-up list and a property of the parameter dictionary 24
Figure 4-2 Adding keys as attributes of the Parameters instance. 25
Figure 4-3 Binding between the controller and the parameters dictionary 26
Figure 4-4 The selectedIndex attribute in the bindings inspector 27
Figure 5-1 The property inspector for Automator actions (general collection) 30
Figure 5-2 The completed General collection of Automator properties) 31
Figure 5-3 Automator property inspector—Input collection 32
Figure 5-4 The default parameters for the Pass Random Items action 34
Figure 5-5 The description for the Pass Random Items action 34
5
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
FIGURES
Figure 7-1 Executable settings for the Pass Random Items action 41
Figure 7-2 Testing the Pass Random Items action in a workflow 42
Figure 7-3 The AppleScript debugger 43
6
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
INTRODUCTION
Important: Some of the Xcode features mentioned in this tutorial, such as the AppleScript debugger and
the property inspector, were introduced with Xcode 2.1. If you have an earlier version of Xcode, you do not
have access to these features.
The tutorial assumes that you are familiar with AppleScript, but otherwise has no other prerequisites. It is
helpful, however, if you have some experience with AppleScript Studio.
This tutorial has the following chapters, which are meant to be read in the given order:
1. “Before You Start” (page 9) gives an overview of Automator actions and workflows. It also describes
the action that you will create in the tutorial.
2. “Creating the Project” (page 13) explains how to create an AppleScript action project and identifies the
key elements of such projects.
3. “Creating the User Interface” (page 17) shows you how to create the user interface of the action using
the Interface Builder application.
4. “Establishing Bindings” (page 23) explains what Cocoa bindings are and describes how you establish
bindings for the action.
5. “Configuring the Action” (page 29) discusses how to set the properties of the action in its Info.plist
file.
6. “Writing the Action Script” (page 37) shows the script that you write for the action and explains the
general structure and behavior of all such scripts.
7. “Building and Testing the Action” (page 41) describes techniques for testing and debugging an action
after it is built.
In this tutorial you are going to learn the basic steps for constructing an Automator action using AppleScript
as the development language. In the process of learning, you will create a action that you can productively
use in workflows. But before you begin, let’s take a moment to review what an action is and to look at the
action you will create.
Most people are familiar with the notion of building blocks. By placing small but well-defined units in certain
relationships with each other, one can compose complex and even elegant structures. An Automator action
is such a building block. An action is a small, discrete functional unit; it performs a well-defined operation
usually on data of a specific type, such as copying a file or adding photos to an iPhoto album. It often offers
the user a simple user interface for setting certain parameters of the operation. For example, the action in
Figure 1-1 selects certain Mail messages based on specified criteria.
By itself, an action cannot do much. For one thing, it requires the Automator application to provide the
context for its execution. But, more importantly, an action’s very discreteness limits its usefulness; an action
is designed to complete a small, well-defined task, and nothing more. To be effective, an action must be
placed in a meaningful sequence of other actions. This sequence of actions is called a workflow. In a workflow
the output of one action is usually (but not always) passed to the next action in the workflow as input.
Automator orchestrates this process by starting each action in turn and passing it the output of the previous
action. A workflow expresses a operation that can be arbitrarily complex, and the final product of that
operation is usually the output of the last action. For example, the workflow in Figure 1-2 gets a user’s unread
mail and downloads the messages to the Notes section of a connected iPod.
As an Automator workflow (such as the one above) illustrates, an action is usually designed to accept input
and produce output of specific data types (although some actions will take and provide any type of data).
Thus some actions may be incompatible with other actions; the Combine Mail Messages action, for instance,
could not accept Address Book data. But there can be what are called conversion actions to bridge between
actions with incompatible types of data.
From a development perspective, an action is a loadable bundle installed in one of four locations:
The action bundle can contain executable code, AppleScript scripts, shell scripts, and localized strings, nib
files, and other resources. When Automator is launched, the application extracts configuration information
from the action bundles and displays some of this information in its user interface. It also loads the bundles
of the actions placed in a workflow at some point before the execution of the workflow (the exact moment
differs for actions based on Objective-C and actions based on AppleScript). For a complete description of
the architecture of Automator actions and workflows, see “How Automator Works” in the Automator
Programming Guide.
In this tutorial you will create an action named Pass Random Items. The action accepts a list of items (of any
type) from the previous action and passes a random subset of those items to the next action. Users can
specify the number or percentage of items to pass in the action’s user interface. Figure 1-3 shows the Pass
Random Items action in a workflow.
Note: The project for the Pass Random Items action is installed as an example (under the name Randomizer)
in /Developer/Examples/Automator.
In this workflow, the Filter Photos in iPhoto action passes all selected photos taken within the last two months
to Pass Random Items. This action, in turn, passes 20 random photos from that initial selection to an action
that plays them in a slide show.
After you complete this tutorial and before you attempt developing any action on your own, you should take
time to consider the design of the action. Read “Design Guidelines for Actions” in Automator Programming
Guide for a summary of pertinent design guidelines.
When you create an AppleScript action project, you start by selecting an Xcode template that provides all
necessary project files and initial project settings.
The steps for creating a AppleScript action project are few and simple:
Xcode displays the New Project assistant (see Figure 2-1). The Automator action project templates are
near the top of the displayed list.
4. In the New AppleScript Automator Action assistant, enter a project name and select a file-system location
for the project (see Figure 2-2).
13
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
CHAPTER 2
Creating the Project
For the tutorial project, the project name is Pass Random Items.
After you complete this step, Xcode displays the new project in its window, shown in Figure 2-3.
14
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
CHAPTER 2
Creating the Project
Almost all of the items in the project folder have special significance in the development process.
Frameworks
Any action project must import the Cocoa umbrella framework, which includes the Foundation and
Application Kit frameworks. It also imports the Automator framework, which defines the programmatic
interface for all Automator actions. See Automator Framework Reference for documentation of this
interface.
main.applescript
The main AppleScript script file whose on run handler is called by Automator when the action runs
in a workflow. You will write your AppleScript code in this file. An AppleScript action project can also
have other (“helper”) AppleScript scripts, often to manually synchronize user settings with the action
internal record of those settings.
Info.plist and InfoPlist.strings (English)
The Info.plist file is the information property list for the action bundle. It contains configuration
information that is generally related to the bundle and more specifically related to the action. The
InfoPlist.strings file contains English translations of items in Info.plist that might be displayed
to the user. If your action is to be localized for languages or locales besides English, you will have to
add an InfoPlist.strings file to the project for each additional translation.
main.nib (English)
The nib file for the English version of the action. A nib file is an archive containing the view, controls,
and other user-interface objects used by an executable, as well as the connections between those
objects. You use the Interface Builder to create and maintain nib files. If your action is to be localized
for languages or locales besides English, you will have to add a main.nib file for each additional
localization.
The Pass Random Items.action item shown in the project window is the action bundle. When the action
project is built, the text color of the item will change from red to black to indicate that the bundle now exists
in the build directory. All Automator action bundles must have an extension of action.
15
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
CHAPTER 2
Creating the Project
16
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
CHAPTER 3
In this part of the tutorial, you will create the user interface of the Pass Random Items action. This phase of
development includes not only placing, resizing, and configuring the objects of the user interface, but
establishing the bindings between those objects and the parameters property of the action.
The nib file is an Interface Builder archive holding the objects of a user interface and any connections between
those objects. (A nib file can also contain custom class definitions and resources such as images and sounds,
but the Pass Random Items action doesn’t use these things, so we’ll leave it at that.) The nib file for an action
has the default name main.nib.
To open main.nib, double-click the icon next to the file in the project window for Pass Random Items
(see Figure 2-3 (page 15). The Interface Builder launches (if it isn’t running already) and displays the windows
related to the nib file (see. Figure 3-1).
Figure 3-1 The nib file window, initial action view, and palette
The nib file window in this illustration is the one containing the File’s Owner, First Responder, View, and
Parameters icons in the Instance pane. (There are other panes for classes, images, and sounds, but you can
ignore those for now.) The window with the grey rectangular area is the view of the action; here is where
you will place the fields, controls, and other objects of the action view. The third window is the palette window
containing palettes with various kinds of objects.
Before you start adding objects to the action view, however, make sure that the Cocoa-Automator palette
is loaded. This palette contains several kinds of user-interface objects that are special to Automator. You
won’t need these objects for this tutorial, but you might need them for other actions. At the top of the palette
window is a row of icon buttons. See if the Automator icon is one of them.
2. Click the Palettes button to display the list of currently loaded palettes.
The user interface of the Pass Random Items action is simple, consisting of only a few text fields and one
matrix object holding two radio buttons. Simplicity is one of the design principles for all actions. “Design
Guidelines for Actions in the Automator Programming Guide discusses guidelines for action views.
Let’s begin. Select the text palette by clicking the text button icon at the top of the palette window:
The text palette contains various types of objects related to text: editable text fields, labels, token fields,
search fields, forms, and so on. First place a text field on the action view; users will enter a number or a
percentage in this field, depending on the radio button selected.
1. Drag the text field from the palette to the upper-left corner of the action view.
Interface Builder uses blue lines to show you the proper location for object placement according to Apple
Human Interface Guidelines. Make sure the top and left side of the text field are adjacent to the blue lines
that appear (see Figure 3-3 (page 19)).
Note that after you drop an object in a view, you can still select it and move it within the view.
Many of the objects in a user interface—for example, text fields, buttons, and table columns—have three
predefined sizes: mini, small, and regular (or system). Objects in an action view should always be small. The
text field that you just placed is not. To change the text field to a small size, do the following;
3. Select the Attributes pane from the pop-up list of the inspector.
The Attributes pane shows all of the configurable options for whatever object is selected. For text fields,
these options include color, alignment, and the fields enabled and editable states.
4. Choose Small from the Size pop-up list (see Figure 3-4).
A couple of other things are not quite right with the text field. It is wider than we need for a simple number
or percentage. And the field should have the label “Pass:” just to its left. We can solve these problems by
resizing the text field to the right.
When it’s selected, you see tiny round handles on each side and on each corner. You can use these
handles to make an object larger or smaller in the given horizontal, vertical, or diagonal direction.
2. Press the mouse pointer down on the handle on the left side of the text field (not the corner handles).
3. Drag the handle toward the right until the text field is about half the original size (see Figure 3-5).
A label is a text field that has a neutral background and that is non-editable. To create the label for the text
field:
1. Drag the object on the text palette that reads “Small System Font Text” and drop it in the upper-left
corner of the action view.
2. Double click this generic label to select the text (see Figure 3-6).
The next step is adding the radio buttons labeled “Number” and “Percentage”. Radio buttons are on the
Cocoa Controls and Indicators palette. You can access this palette by clicking the following icon button at
the top of the palette window:
Radio buttons are preconfigured compound objects. They are designed to work with a group of identical
buttons in a way that ensures only one of them is enabled at any time. The object that holds these multiple
objects together is a matrix.
1. Drag the palette object with two “Radio” buttons onto the action view just to the right of the text field.
Even though the objects are labeled “Radio”, this is a matrix object.
2. With the radio-button matrix selected, press the middle handle on the right side of the matrix.
3. Option-drag the matrix to the right until two more “Radio” buttons appear (see Figure 3-7).
“Option-drag” means to press the option key while dragging the object handle.
5. Option-drag the matrix upward until the two bottom “Radio” buttons disappear.
Figure 3-7 Changing the number of radio buttons in a matrix (radio buttons)
The user interface is looking much better, but you still have some work to do. The buttons are too large, and
they need the correct titles. Fortunately, you can solve both of these problems at the same time for each
button:
3. In the Attributes pane of the inspector for the button cell, change the size to Small.
The user interface of the Pass Random Items action needs one final object. Add a small label after the
“Percentage” radio button that reads “items”.
But you’re not finished yet. The action view is too big for the objects it contains. To resize the view, click and
press the lower-right corner of the view window, then move the window in toward the upper left corner of
the view until all objects are just contained. Make sure that the objects on the view conform to the blue
guidance lines. Then add back a 10-pixel border around the user-interface objects on all sides; this border is
required by the user-interface guidelines for actions. The final action view should look like the example in
Figure 3-9.
Establishing Bindings
The objects on an action view are only part of what’s involved in creating the user interface of an action. If
users click a button or enter something into a text field, nothing much happens until you communicate those
events to other objects in the action that know how to deal with the events. Even though you are creating
an AppleScript action, the underlying framework of Automator is Cocoa-based. Cocoa gives you two general
mechanisms for enabling communication between view objects and other objects in a action:
■ Outlets and target-action (“action” here does not denote an Automator action)
■ Bindings
The preferred approach for managing an action’s user interface is to use the Cocoa bindings technology;
that is how actions projects are initially configured in the project templates and that is the procedure this
tutorial shows. But you can manage the user interface using an alternate approach that makes use of outlets
and possibly target-action. “Alternatives to Bindings” (page 27) summarizes this approach.
Note: The technology of Cocoa bindings relies on a number of APIs and mechanisms that this tutorial won’t
go into. If you are interested in learning about them, read Cocoa Bindings Programming Topics.
Bindings in an Action
A binding in Cocoa automatically synchronizes the value between an attribute of a user-interface object (say,
the displayed value of a text field) and a property of a data-bearing object (usually termed a model object).
This means that whenever a user edits a control or clicks a button, that change is automatically communicated
to the bound property of the object maintaining that value internally. And whenever that internal value
changes, the change is automatically communicated to the bound attribute of a user-interface object that
then displays it.
Note: This part of the tutorial frequently talks about the properties of objects. “Property” in this sense means
an essential characteristic of the object that it encapsulates. A property can either be an attribute, such as a
color or a person’s name, or a relationship—that is, a reference to one or more other objects. In Cocoa
bindings, the values of properties are accessed using their names as keys.
For actions the data-bearing object is a dictionary owned by the action object itself. For AppleScript actions,
the action object is almost always an instance of AMAppleScriptAction. Every action, regardless of the
programming or scripting language it uses, maintains an internal dictionary that captures the choices users
have made in the user interface. (The AppleScript equivalent for a dictionary is a record.) This dictionary is
called the parameters dictionary. It stores values users make in the user interface along with an arbitrary key
for each value. When Automator runs an AppleScript action in a workflow, it passes it a parameters record
in the on run handler in main.applescript (See “Writing the Action Script” (page 37) for more about the
on run handler.)
Bindings in an Action 23
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
CHAPTER 4
Establishing Bindings
When you establish a binding between a user-interface control and a property of the action’s parameters
dictionary, the binding is made through a property of an intermediary object called a controller. In the
main.nib file for an action, this intermediary object appears in the Instance view of the nib file window as
the Parameters instance. When you look at a binding in Interface Builder in the Bindings pane of the inspector
(see Figure 4-4 (page 27) for an example), you can see it as a combination of user-interface attribute, controller
property, and parameters property.
Figure 4-1 illustrates the case of the radio-button matrix of the Pass Random Items action; here the matrix
attribute selectionIndex is connected to the controller’s selection property, which is connected to the
numberMethod property of the parameters dictionary. The value of numberMethod reflects the zero-based
index of the selected radio button in the matrix (1 indicates the “Percentage” button in the example).
Figure 4-1 Binding between the pop-up list and a property of the parameter dictionary
parameters Dictionary
Key Value
numberToChoose 20
numberMethod 1
selectionIndex selection
Parameters
To establish bindings for the Pass Random Items action, complete the following steps with the action’s
main.nib file open in Interface Builder:
2. Open the inspector window (Tools > Show Inspector) and choose Attributes from the pop-up list.
The Parameters controller instance is now initialized with the keys that will be used in the bindings between
attributes of two of the user-interface objects and properties of the parameters dictionary. Note that the
project template for all types of actions is preconfigured to make a binding between the Parameters instance
and the action’s parameters dictionary. To see this binding:
Figure 4-3 shows the binding between the controller object and the parameters property of the action
object (File’s Owner).
Figure 4-3 Binding between the controller and the parameters dictionary
The final stage of establishing bindings requires you to bind the attributes of two of the user-interface objects
to the corresponding properties of the parameters dictionary via the selection property of the Parameters
controller.
3. Click the disclosure triangle next to the selectedIndex attribute of the matrix.
6. Set the value of the Model Key Path combo box to numberMethod.
7. Make sure the Bind check box in the upper-right corner of the selectedIndex view is checked.
The Bindings inspector pane should look like the example in Figure 4-4 (page 27) at this point.
9. In the Bindings pane of the inspector, click the disclosure triangle next to the value attribute.
10. Make sure the Bind to combo box contains Parameters and the Controller Key combo box contains
selection.
12. Make sure the Continuously Updates Value check box is checked.
Checking this control tells the bindings mechanism to synchronize the value in the text field without
waiting for the user to press the Return or Tab keys.
Alternatives to Bindings
Although bindings are the preferred technique for enabling communication the objects of an action, there
are alternatives to bindings. For example, you can use outlets and target-action to facilitate the communication
of data between objects in the action view and the parameters dictionary owned by the action object. In
this case you also use a controller object, but instead of bindings it maintains persistent references to other
objects known as outlets. Thus it can always send a message to, say, a text field to obtain its value.
User-interface objects and controllers can also be set up to use target-action. In this mechanism a control
object (such as a button) is configured with a target of a message—usually the controller—and a selector
that designates the message to send. When users activate the control object, a message is automatically sent
to the controller. You can establish outlet and target-action connections in Interface Builder, which archives
these connections in the nib file.
Alternatives to Bindings 27
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
CHAPTER 4
Establishing Bindings
Note: To learn more about outlets and target-action, see Cocoa Fundamentals Guide.
Automator provides a third alternative for synchronizing the values in the parameters and the settings users
make in the action’s user interface. It defines the update parameters and parameters updated commands,
which you can attach to an action’s view using AppleScript Studio. Automator sends the update parameters
command when an action’s parameters need to be refreshed from the values on the user interface. It sends
parameters updated when there are any changes to the action’s parameters dictionary. “Implementing
an AppleScript Action” in Automator Programming Guide describes this procedure in detail.
28 Alternatives to Bindings
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
CHAPTER 5
Every bundle in Mac OS X—and that includes applications, frameworks, and loadable bundles such as
actions—has an information property list. This property list, which is contained in a file named Info.plist,
is a series of key-value pairs in XML format. The standard information property list defines such properties
of the bundle as its identifier, its type code, and its main class.
Information property lists can contain properties other than the standard ones. Such is the case with Automator.
In the Info.plist file of an action project you can (and in some cases must) specify properties that
characterize the action, enabling Automator to display information about the action and handle it properly.
For example, some Automator properties provide the name and description of an action and others indicate
what types of data the action operates on (or produces). The following sections describe the basic approach
to completing the action-specific properties and steps you through the properties that you must specify for
Pass Random Items.
For complete descriptions of the Automator properties, see “Automator Action Property Reference” in
Automator Programming Guide.
Note: The inspector for Automator properties was first introduced in Xcode 2.1. If you have an earlier version
of Xcode, you have to edit the properties in the Info.plist file manually.
Automator action projects take advantage of a special inspector built into Xcode for viewing and editing the
action’s information property list. To access this editor, choose Edit Active Target ‘Pass Random Items’ from
the Project menu. Then, click the Properties tab in the Target Info window to display the property inspector,
which is shown in Figure 5-1.
Figure 5-1 The property inspector for Automator actions (general collection)
The first thing to note about the property inspector for actions is that it is divided into two parts. The upper
half of the window contains general bundle properties, such as the name of the executable, the bundle
identifier, and the principal class. You shouldn’t have to change any of these values.
The lower half of the window is the area for viewing and editing Automator-specific properties. The Collection
pop-up list displays various groupings of properties. The first displayed is the General group. Note that the
action name (and the last part of the bundle identifier) are automatically assigned the name of the Xcode
project. (This automatic name assignment was introduced in Xcode 2.1.) You are going to keep the name
for the action, but assign values to the Application, Category, and Icon name properties.
Note: In the Info.plist file the property keys are different from the strings displayed in the inspector. The
keys have “AM” prefixes and no spaces between words, for example, AMActionName, AMApplication,
AMCategory, and AMIconName.
1. Double-click the cell under Value containing the comment for the Application property. This selects the
cell and makes it editable.
The application named here is either the one that the action primarily sends scripting commands to or
the application that the action is most closely associated with.
This value requests a generic icon for actions to be displayed next to the action name in Automator.
5. Uncheck the check box labeled “Can show selected items when run.” Leave the check box “Can show
when run” checked.
This pair of settings allows you to specify values in the action’s user interface when the workflow
containing it is executed; the entire user interface is displayed, not a subset of it. For more on the
show-when-run feature, see “Show When Run” in Automator Programming Guide.
When you have finished these steps, the General collection of properties should look like the example in
Figure 5-2.
Every action must specify what types of data it accepts from the action before it in the workflow and what
types of data it provides to the next action in the workflow. The AMAccepts and AMProvides properties of
the information property list allow you to do this. The Automator property inspector of Xcode shows these
properties as the Input and Output collections.
Choose the Input collection from the pop-up list to display the view of the inspector shown in Figure 5-3.
The main view for the Input collection is a single-column, headingless table. You click the plus (+) button to
add a cell for a new entry and click the minus button (-) to delete the selected entry. The entries in this table
are UTI-style type identifiers specifying the types of data the action can accept. The Types subproperty of
the AMAccepts property for AppleScript action projects is initialized to com.apple.applescript.object,
which means that the action can accept any type of AppleScript object as input. Since this fits the type of
data that the Pass Random Items action can process—it merely passes on a random subset of the items
passed it—you do not need to modify contents of the table.
When you are developing your own actions, you will probably want to specify different types of identifiers.
For example, if your action handles iTunes songs, you would specify com.apple.itunes.track-object.
If your action can handle URLs, you would enter public.url in the Input table. It’s best to be as specific as
possible about the types of data that your action can accept and provide. For a listing of supported type
identifiers for actions, see “Automator Action Property Reference” in Automator Programming Guide.
The Input collection part of the inspector has two additional controls: a Container pop-up list and an Optional
check box. These controls correspond to two subproperties of AMAccepts: Container and Optional. The
former indicates whether the input data is a single item or a list of items; this control is almost always left as
List. The latter control indicates whether input is optional for the action. Leave both controls unchanged.
The settings of the Output collection for Pass Random Items are identical to those for the Input collection.
The type identifier is com.apple.applescript.object and Container is set to List.
The AMDefaultParameters property allows you to specify initial values for action controls when the action
first appears in a workflow. In the Automator property inspector, you edit this property through the Parameters
collection. The table for this property has three columns:
■ Name — the key identifying the control and its associated property in the parameters dictionary
■ Type — the type of data represented by the control
■ Value — the initial value for the control
To set the initial value for the text field containing the number or percentage, do the following:
1. Click the plus button (+) below the table to insert a new row into the table.
2. Double-click the cell under the Name column to open it for editing.
3. Type “numberToChoose” in the cell; this is the same name that you gave the binding key in Interface
Builder.
4. In the Type column of the same row, select “integer” from the pop-up list attached to the cell.
5. Double-click the cell under Value in the same row and type “1”.
Repeat the same procedure for the radio-button matrix, entering “numberMethod” for the name, “integer”
for the type, and “0” for the value. When you are finished, the inspector window should look like the example
in Figure 5-4.
Figure 5-4 The default parameters for the Pass Random Items action
When users browse through the actions available for Automator, they can see a brief description for each
selected action in a small view in the lower-left corner of the application. When users select the Pass Random
Items action, you want them to see the description shown in Figure 5-5.
Figure 5-5 The description for the Pass Random Items action
Descriptions can be simple like this one, or they can include things like requirements and warnings. The
Automator property for descriptions is AMDescription; it has several subproperties for the various
components of description: AMDAlert, AMDInput, AMDNote, AMDOptions, AMDRelatedActions, AMDResult,
and AMDSummary.
For the Pass Random Items action you need only set one of these subproperties, AMDSummary, which is the
short description of what the action does. The icon, title, Input, and Result parts of the description are
automatically supplied by, respectively, the AMIconName, AMActionName, AMAccepts, and AMProvides
properties. (You can provide your own description for the latter two properties in addition to the defaults,
if you want.)
2. Double-click the cell under the Value column for the Summary row.
3. Replace the comment with the sentence shown in Figure 5-5 (page 34).
Other Settings
There are several other Automator properties which you can access through the Collection pop-up list. One
very useful property to supply values for is the Keywords property (AMKeywords). The Keywords collection
part of the inspector provides a simple table to which you can add a list of words that identify the action in
Automator searches for actions. Other collections are Required Resources (AMRequiredResources), Warning
(AMWarning), and Related Actions (AMRelatedActions). Read “Automator Action Property Reference” in
Automator Programming Guide to learn more about these properties.
Other Settings 35
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
CHAPTER 5
Configuring the Action
36 Other Settings
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
CHAPTER 6
The next stage of developing the Pass Random Items action is writing the script itself. This chapter describes
how to write the command handler that all AppleScript actions must implement and discusses subroutines
and other aspects of scripting for actions.
For more information on this subject, see “Implementing an AppleScript Action” in Automator Programming
Guide.
In the Xcode project window for the Pass Random Items action project, locate the main.applescript file
and double-click it. The file opens in an editor much like Script Editor. It contains a “skeleton” on run
command handler, as shown in Figure 6-1.
Let’s briefly look at this command handler before writing anything. Automator invokes the handler when it
is an action’s turn in a workflow to run. The handler has two parameters: input and parameters. The input
parameter is the data provided by the previous action in the workflow. The template on run handler simply
returns the input as its output. The parameters parameter is a record that contains the settings users have
made in the action’s view.
Start by initializing a list of items to return as output and extracting the settings users have made from the
parameters record. Figure 6-2 shows you the scripting code to write.
The first line initializes a list named output_items and the last line returns this list. In between, the script
tests whether the input object is an empty list or is a single item instead of list and returns that as output (if
a single item, it adds it to the output_items list first).
The other lines of the script in Figure 6-2 assign to local variables the values in the parameters record that
are bound to the action’s user-interface controls. Note that in the expression
(|numberToChoose| of parameters)
that numberToChoose is one of the keys you added to the attributes of the Parameters instance in Interface
Builder when you established the bindings of the action. In the script you are using this key to access the
value corresponding to the choice the user made in the user interface.
Finally, add the remaining lines shown in Figure 6-3 to complete the on run command handler.
These lines of the script test whether the user selected the Number or Percentage radio button in the user
interface; if it is Percentage, the script calls a subroutine to get the specified percentage of the input items
as a number. Then in a loop it adds a random selection of input items—limited by the specified or computed
number—to the output items.
The main.applescript file for the Pass Random Items action includes two subroutines. The first,
convert_percentage_to_number, you have already encountered when writing the on run handler script.
This subroutine performs the simple calculation shown in Figure 6-4.
The second subroutine, localized_string, does something very important despite the fact that it’s not
called by the on run command handler you have written. Through the localized string command, the
subroutine returns a string (identified by key_string) for a preferred localization specified by the current
user in System Preferences. You can use this string in dialogs and error messages. To use this subroutine
effectively you must first internationalize your action for all supported localizations. To find out how to do
this, see the relevant section in Developing Actions of the Automator Programming Guide.
You have completed the steps required to develop the Pass Random Items action. You’ve created the user
interface, established bindings, specified the Info.plist properties, and written the script. It’s time to build
and test the action.
But before you begin, look at how an action project sets up its executable for testing. Choose Edit Active
Executable ‘Automator’ from the Project menu to display the Executable Info window. In the General pane
of this window, you can see that the executable path is initialized to /Applications/Automator.app. Then click
the tab for the Arguments pane; as Figure 7-1 shows, the -action argument passed to Automator tells it
to load the Pass Random Items action.
Figure 7-1 Executable settings for the Pass Random Items action
To build and test the action in Xcode, choose Build and Run from the Build menu. Xcode builds the action
and then launches Automator. As part of the build process, Xcode runs the amlint utility to perform a
number of action-specific tests. The results of these tests appear along with all other build results.
41
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
CHAPTER 7
Building and Testing the Action
Assuming the action builds without error or warning and Automator launches, the next thing you should do
is compose a workflow in which users would likely include the Pass Random Items action. Figure 7-2 shows
a possible workflow. The Get Specified Finder Items actions allows you to select a collection of Finder items
and then passes it to the Pass Random Items action. You can view the output of your action using the View
Results action. Check to see if the correct number or percentage was passed and if the selection is truly
random.
Automator has its own set of actions that are useful in testing. To see them, disclose the Applications folder
under the Library column of the application and select Automator. View Results is one of these actions. Others
that you might find useful in action development and testing are the following:
If Xcode displays errors and warnings when you attempt to build the action, or if the action doesn’t behave
as expected, and you cannot readily pinpoint the cause of the problem, you can either debug the action
(using a special AppleScript debugger) or add log statements. To debug an AppleScript action:
42
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
CHAPTER 7
Building and Testing the Action
Click in the gray strip next to the line you want the debugger to break on. A black breakpoint indicator
appears in the gray strip.
3. When Automator launches, construct a workflow with your action in it and execute it.
When your action runs, the Xcode AppleScript debugger shows a debugging window similar to the one
in Figure 7-3.
The debugger lets you step through the script and shows the values of globals, locals, and properties.
You can also insert log or display dialog statements in the script at points where you want to display
current values. If the log statement is inside an application tell block, use the tell me to log expression
instead of the simple log. The output of these statements appears in the Console log (not in the Automator
log).
43
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
CHAPTER 7
Building and Testing the Action
For additional debugging information, see the section “Frequently Asked Questions About Debugging
Automator Actions” in “Developing an Action” in Automator Programming Guide.
44
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
REVISION HISTORY
Date Notes
In “Building and Testing the Action” (page 41), added information about logging,
as well as a link to the section “Frequently Asked Questions About Debugging
Automator Actions” in “Developing an Action” in Automator Programming Guide.
2005-06-06 New tutorial showing how to create an Automator action using AppleScript.
45
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.
REVISION HISTORY
Document Revision History
46
2007-07-18 | © 2005, 2007 Apple Inc. All Rights Reserved.