TweetFollow Us on Twitter

Building An AppleScript-Based Automator Action

Volume Number: 21 (2005)
Issue Number: 8
Column Tag: Programming

AppleScript Essentials

Building An AppleScript-Based Automator Action

by Benjamin S. Waldie

There has been a lot of excitement in the developer community around the release of Mac OS X 10.4. Unique technologies like Automator, Dashboard, and Spotlight are providing new opportunities for Mac developers to build unique tools that appeal to users everywhere. This month, we are going to walk through the process of developing for one of these great new technologies, Automator.

Automator is Apple's new technology that is helping users everywhere to begin automating repetitive and time consuming tasks in their own unique workflows, allowing them to become more efficient. By placing actions, which are single automated tasks, together in a sequence, users are able to construct a fully automated workflow, without the need to write a single line of code. How does this help us, as developers, you may be asking? Well, someone needs to create the actions that give users this power.

Automator actions are built in Xcode, and are typically developed using either Objective-C, AppleScript, or a combination of these, and possibly other languages. Objective-C may be used to develop actions that interact with core components of the OS, or applications with a public API. AppleScript may be used to develop actions that interact with any scriptable application or process on the Mac.

In this article, we will walk through the process of creating a basic Automator action with AppleScript. This brief overview should provide you with a basic understanding of the primary steps involved in creating a simple AppleScript-based action. Once you understand the basic concepts of building an action, then you can take additional steps on your own to begin expanding your knowledge through additional resources. Before long, you will be creating complex actions that interact with a variety of scriptable applications or processes, and sharing those actions with users. Obviously, it should go without saying that you will need Mac OS X 10.4 and Xcode 2 or higher to create an Automator action.

Getting Started

There are a number of steps involved in the creation of an AppleScript-based Automator action, and we will move through the process fairly quickly.

The first step in creating an action is to determine what the action will do. I've done this part for you already. Our action will accept a list of values as input, and then display a choose from list dialog to the user, allowing the user to make a selection. The value specified by the user will then be passed as output on to the next action in an Automator workflow sequence. An action such as this might be used to give a user the opportunity to process only a specified set of data during execution of a workflow.

  • The choose from list command is found in the User Interaction suite in the Standard Additions scripting addition, included with Mac OS X.

Create an Action Project

Once you have determined what your action will do, the next step is to create a new Xcode project. To do this, launch Xcode and select New Project... from the File menu. You will then be prompted to select from a list of pre-existing project templates. Apple has included a handful of Automator action templates with Xcode to get you started. Select the AppleScript Automator Action template, and click the Next button to proceed. See figure 1.


Figure 1. Choosing an Automator Action Project Template

  • If you are feeling adventurous, or if you prefer developing in other languages, be sure to check out the Cocoa Automator Action and Shell Script Automator Action (Xcode 2.1 or higher) templates, also included with Xcode. Also, be sure to check out the example Automator action projects, complete with sample code, located in the Developer > Examples > Automator folder.

Next, specify a name for your Automator action, in this case, Choose List Items. Specify a directory for the project, and click the Finish button to create the action project. See figure 2.


Figure 2. Specifying a Project Name and Directory

You should now have an Automator action project opened in front of you in Xcode. See figure 3. If you are new to Xcode, then the project may look a little overwhelming to you at first glance. However, there are really only a handful of components with which we, as AppleScript developers, will need to interact. These components are:

main.applescript - This is your action's main AppleScript file. It will contain the AppleScript code that will trigger when the action is run in an Automator workflow.

main.nib - This is your action's interface, as it will be displayed when the action is placed into the workflow view in Automator's interface.

info.plist - This is essentially a configuration file. It will indicate how your action should be handled within Automator, and within a workflow sequence.

  • An English instance of an InfoPlist.strings file is also present, and may be used to specify English translations of properties contained within the info.plist file. Optionally, additional versions of this file may be added for additional translations. For this sample action, we will not use the InfoPlist.strings file.

We will discuss each of these components in greater detail as we build our action project.


Figure 3. A New AppleScript-Based Automator Action Project

Update the Action's Properties

Once we have created our action project, we need to make some adjustments to the info.plist file within the action project. As previously mentioned, the info.plist file is an XML file, which provides information about the action to the Automator application. There are a number of properties and values included in the info.plist file. For the purposes of the action we are building, we will discuss only a handful. At this time, take care not to make changes to any properties included in this file, which are not specified below.

There are a number of ways that you can edit an action's info.plist file. For this project, we will edit the file's XML code directly. Click on the info.plist file in your action's project to view the file's contents within your Xcode window. Skim the info.plist file, paying special attention to the properties listed below, and making any adjustments indicated.

AMAccepts

This property provides Automator with information about the input that an action will accept. This property contains an XML dictionary, which specifies whether the input for the action is optional, and which types of input are acceptable. If an action is configured to accept a certain type of input, then Automator will generate an error if an incompatible input type is passed to the action.

An action may be configured to accept multiple input types, if desired, and each input type must be specified as a universal type identifier (UTI). A list of valid UTI's is included with the Automator developer documentation. For our action, we will simply make use of the default UTI for this property, com.apple.applescript.object, which indicates a generic AppleScript object. Because this is configured by default, you should not need to modify any aspects of this property. The property should appear as follows within your info.plist file:

<key>AMAccepts</key>
<dict>
   <key>Container</key>
   <string>List</string>
   <key>Optional</key>
   <false/>
   <key>Types</key>
   <array>
      <string>com.apple.applescript.object</string>
   </array>
</dict>

AMApplication

This property specifies the category in which the action will appear in the Library list within Automator's interface. For our action, set this property to a value of Automator. This will cause the action to appear within the Automator category.

<key>AMApplication</key>
<string>Automator</string>

AMCanShowSelectedItemsWhenRun and AMCanShowWhenRun

These properties indicate whether the user should be allowed to configure the action's interface to be displayed when run within a workflow. For our action, set the values of both of these properties to false, as we do not want the user to have the ability to display the action's interface during processing.

<key>AMCanShowSelectedItemsWhenRun</key>
<false/>
<key>AMCanShowWhenRun</key>
<false/>

AMCategory

This property is used to help Automator group similar actions together, internally. Currently, the value of this property is utilized by Automator only when the user performs a search via the search field in Automator's toolbar. For our action, set this property's value to Dialog.

<key>AMCategory</key>
<string>Dialog</string>

AMDefaultParameters

This property is used to link attributes of our action's interface to the action's code. We will revisit this property shortly, once we have created our action's interface, and we will specify its value at that time.

AMDescription

This property contains an XML dictionary, which contains the information that Automator displays in the description area when the action is selected. This value may be used to specify a variety of different types of information. For our action, we will use only a few. Configure this property in your action's info.plist file to match the following:

<key>AMDescription</key>
<dict>
   <key>AMDInput</key>
   <string>A list of values, which may be coerced to text format</string>
   <key>AMDOptions</key>
   <string>Allow multiple selections; allow empty selections</string>
   <key>AMDResult</key>
   <string>Specified list items</string>
   <key>AMDSummary</key>
   <string>This action will prompt the user to select from a list of values.</string>
</dict>

AMIconName

This property is used to specify the name of a graphic file that will serve as the action's icon in Automator's Action list, as well as in the action's description, when the action is selected. You may specify the name of a graphic file within your project, within Automator's bundle, or within the "CoreTypes" bundle (found in System > Library > CoreServices). For our action, we will specify a graphic that is included within Automator's bundle, a standard AppleScript icon:

<key>AMIconName</key>
<string>AppleScriptLarge</string>

AMKeywords

This property is used to specify keywords for an action. These keywords will be accessed by Automator when a user performs a search via the search field in Automator's toolbar. For our action, we will specify select and display as keywords. Feel free to assign other keywords as well, if you would like.

<key>AMKeywords</key>
<array>
   <string>select</string>
   <string>display</string>
</array>

AMName

This property contains the name of your action, as it will appear in the Action list within Automator. This property should already be populated for you, but it still bears mentioning. It should appear as follows within your action's info.plist file.

<key>AMName</key>
<string>Choose List Items</string>

AMProvides

This property is similar to the AMAccepts property. It contains an XML dictionary, and indicates the type of output that the action will provide to the next action in a workflow sequence. Like the AMAccepts property, the output type must be a valid UTI. By default, this property should already be configured to output a generic AppleScript object, so you should not need to adjust it. This property should appear as follows within your action's info.plist file.

<key>AMProvides</key>
<dict>
   <key>Container</key>
   <string>List</string>
   <key>Types</key>
   <array>
      <string>com.apple.applescript.object</string>
   </array>
</dict>

Localized Strings

As previously mentioned, you may use an InfoPlist.strings file to specify localized versions of strings within your action's info.plist file. However, for the purposes of this example action, we will not perform this task. Therefore, click on the InfoPlist.strings file in your action project, displaying its contents in Xcode. Next, delete the existing text from this file, leaving the InfoPlist.strings file blank.

Build the Action's Interface

The next step in building our Automator action is to create our action's interface. First, double click on the main.nib file in your action project to open the action's nib within Interface Builder. Once opened, double click on the nib's view instance, if it is not already displayed for you.

Assuming that you already have a basic understanding of how to use Interface Builder, then you may begin adding interface elements to your action's view. For our action, add two checkboxes, set their size to small, and title them Allow Multiple Selections and Allow Empty Selections, as shown in figure 4. These checkboxes will be the settings within our action's interface, which the user will be able to configure from within Automator.


Figure 4. Editing an Action's Interface

  • For more complex actions, you may add additional interface elements. However, be sure to adhere to Apple's Aqua human interface design guidelines, taking into account the limited amount of space within Automator's interface.

Bind The Interface to the Action's Code

Once an action's interface has been designed, the interface elements must be linked to the action's code. This will allow the action to detect changes made to the action's settings by the user, and trigger the appropriate processing code.

There are multiple ways of linking interface elements to the code of an action. However, the most straightforward is to make use of Cocoa bindings. This is the method that we will use for our action. The following steps will walk you through the process of creating these bindings.

Create Parameter Keys

The first step in binding interface elements to action code is to assign parameters. These parameters will later be attached to attributes of the interface elements, and inserted into our action's code. By doing this, changes made to the specified interface element attributes will automatically synchronize to the code of our action. Begin by clicking the Parameters instance in the action's nib. See figure 5.


Figure 5. Selecting the Parameters Instance

Next, type command + 1. This will open the Inspector panel, if not already opened, and display the Attributes pane for the selected Parameters instance. Next, click the Add button in the Attributes pane of the Inspector panel, and add two keys. As the new keys are created, double click on each of them, and re-name them allowEmptySelection and allowMultipleSelections, as shown in figure 6.


Figure 6. Interface Parameter Keys

Bind Parameter Keys to Interface Elements

Once you have created parameter keys, select each of the checkboxes in the action's window view, and perform the following steps. Type command + 4 to display the Bindings pane in the Inspector panel for the current checkbox. Click on value in the Bindings panes of the Inspector panel, and select the parameter key that corresponds to the current checkbox in the Model Key Path field. See figure 7 for an example of a properly configured parameter binding for the Allow Multiple Selections checkbox.


Figure 7. Binding Parameter Keys to Interface Element Attributes

Once parameter keys have been bound to the values of both checkboxes, save the action's interface in Interface Builder, and return to Xcode.

Specify Parameters in the info.plist File

Now that we have configured the bindings within our action's interface, we need to link them to our code, so that they will synchronize automatically when modified by the user. Click on the info.plist file again to display the list of properties for the action. Now, we will revisit the AMDefaultParameters property, which we mentioned briefly.

The AMDefaultParameters property should contain an XML dictionary, containing key/value combinations for the various parameter keys specified within your action's interface. Values specified for these keys will serve as default values for any bound interface elements. For our action, set the AMDefaultParameters property to contain a key for each of the parameter keys that we specified, along with a value of false for each. The properly configured property should appear as follows within your action's info.plist file:

<key>AMDefaultParameters</key>
<dict>
	<key>allowMultipleSelections</key>
	<false/>
	<key>allowEmptySelection</key>
	<false/>
</dict>

Write the Action's Code

Next, we are finally ready to begin writing the processing code for our action. We will be doing this entirely with AppleScript. Click on the main.applescript file to display the action's AppleScript code within Xcode. Next, specify the following code for the action:

on run {input, parameters}
   if (class of input) is not equal to list then set input to {input}
   if input = {} then return input
	
   set inputStrings to {}
   repeat with a from 1 to length of input
      set end of inputStrings to item a of input as string
   end repeat
	
   set allowMultipleSelections to |allowMultipleSelections| of parameters
   set allowEmptySelection to |allowEmptySelection| of parameters
	
   set outputStrings to choose from list inputStrings multiple selections 
      allowed allowMultipleSelections empty selection allowed allowEmptySelection
   if outputStrings = false then error number -128
	
   set output to {}
   repeat with a from 1 to length of inputStrings
      if outputStrings contains (item a of inputStrings) then set end of output to item a of input
   end repeat
	
   return output
end run

As you write processing code for an action, take care to add protection for scenarios that might cause the action to generate an error during processing. For example, our action expects a list of values to be provided as input. Therefore, I have added code to ensure that the specified value is a list, coercing it to a list if necessary.

Test the Action

Once the action's processing code has been written, you are ready to begin testing your action. You may do so by selecting Build and Run from the Build menu within Xcode. Doing so will launch a temporary instance of the Automator application, and your action should be accessible for testing.

To test our specific action, construct a sample workflow. This workflow may consist of a Run AppleScript action, our Choose List Items action, and a View Results action. See figure 8.


Figure 8. An Example of a Test Workflow

If all goes well, your action should display a list of passed input values when run within a workflow, and output the user-specified values. Inevitably, you may make a mistake, which could prevent your action from appearing within Automator, or from running properly within a workflow sequence. It happens to the best of us. To help resolve any issues that may occur during development of this action, you may download and consult the source code for this example action from the following URL:

http://www. automatedworkflows.com/files/demos/MacTECH.08.05.Example.zip.

In Closing

This article should serve as an initial guide to get you started with building your own AppleScript-based Automator actions. However, it is not meant to serve as a definitive guide to Automator development by any stretch of the imagination. For detailed information about creating Automator actions in AppleScript, as well as Objective-C, please refer to the developer documentation included with Xcode, and also available online via the Apple Developer Connection.

If you prefer a book on Automator, then be sure to check out my comprehensive Mac OS X Technology Guide to Automator, available from SpiderWorks http://www.spiderworks.com in both print and eBook formats. The first section of the book covers using Automator, and the second section covers developing your own custom actions. If you think that you need a refresher on AppleScript itself, be sure to check out Danny Goodman's AppleScript Handbook while you're there as well. Sample chapters of both books are available for download.

Until next time, keep scripting!


Benjamin Waldie, author of the best selling eBooks "AppleScripting the Finder" and "Mac OS X Technology Guide to Automator", available exclusively from www.spiderworks.com, is president of Automated Workflows, LLC, a firm specializing in AppleScript and workflow automation consulting. For years, Benjamin has developed professional AppleScript-based solutions for businesses including Adobe Systems, Apple Computer, NASA, PC World, and TV Guide. In addition to his role as a consultant, Benjamin is an evangelist of AppleScript, and can frequently be seen presenting at Macintosh User Groups, Macworld, and other events. For additional information about Benjamin, please visit www.automatedworkflows.com, or email Benjamin at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

coconutBattery 3.9.14 - Displays info ab...
With coconutBattery you're always aware of your current battery health. It shows you live information about your battery such as how often it was charged and how is the current maximum capacity in... Read more
Keynote 13.2 - Apple's presentation...
Easily create gorgeous presentations with the all-new Keynote, featuring powerful yet easy-to-use tools and dazzling effects that will make you a very hard act to follow. The Theme Chooser lets you... Read more
Apple Pages 13.2 - Apple's word pro...
Apple Pages is a powerful word processor that gives you everything you need to create documents that look beautiful. And read beautifully. It lets you work seamlessly between Mac and iOS devices, and... Read more
Numbers 13.2 - Apple's spreadsheet...
With Apple Numbers, sophisticated spreadsheets are just the start. The whole sheet is your canvas. Just add dramatic interactive charts, tables, and images that paint a revealing picture of your data... Read more
Ableton Live 11.3.11 - Record music usin...
Ableton Live lets you create and record music on your Mac. Use digital instruments, pre-recorded sounds, and sampled loops to arrange, produce, and perform your music like never before. Ableton Live... Read more
Affinity Photo 2.2.0 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
SpamSieve 3.0 - Robust spam filter for m...
SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering. SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more
WhatsApp 2.2338.12 - Desktop client for...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
Fantastical 3.8.2 - Create calendar even...
Fantastical is the Mac calendar you'll actually enjoy using. Creating an event with Fantastical is quick, easy, and fun: Open Fantastical with a single click or keystroke Type in your event details... Read more
iShowU Instant 1.4.14 - Full-featured sc...
iShowU Instant gives you real-time screen recording like you've never seen before! It is the fastest, most feature-filled real-time screen capture tool from shinywhitebox yet. All of the features you... Read more

Latest Forum Discussions

See All

The iPhone 15 Episode – The TouchArcade...
After a 3 week hiatus The TouchArcade Show returns with another action-packed episode! Well, maybe not so much “action-packed" as it is “packed with talk about the iPhone 15 Pro". Eli, being in a time zone 3 hours ahead of me, as well as being smart... | Read more »
TouchArcade Game of the Week: ‘DERE Veng...
Developer Appsir Games have been putting out genre-defying titles on mobile (and other platforms) for a number of years now, and this week marks the release of their magnum opus DERE Vengeance which has been many years in the making. In fact, if the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 22nd, 2023. I’ve had a good night’s sleep, and though my body aches down to the last bit of sinew and meat, I’m at least thinking straight again. We’ve got a lot to look at... | Read more »
TGS 2023: Level-5 Celebrates 25 Years Wi...
Back when I first started covering the Tokyo Game Show for TouchArcade, prolific RPG producer Level-5 could always be counted on for a fairly big booth with a blend of mobile and console games on offer. At recent shows, the company’s presence has... | Read more »
TGS 2023: ‘Final Fantasy’ & ‘Dragon...
Square Enix usually has one of the bigger, more attention-grabbing booths at the Tokyo Game Show, and this year was no different in that sense. The line-ups to play pretty much anything there were among the lengthiest of the show, and there were... | Read more »
Valve Says To Not Expect a Faster Steam...
With the big 20% off discount for the Steam Deck available to celebrate Steam’s 20th anniversary, Valve had a good presence at TGS 2023 with interviews and more. | Read more »
‘Honkai Impact 3rd Part 2’ Revealed at T...
At TGS 2023, HoYoverse had a big presence with new trailers for the usual suspects, but I didn’t expect a big announcement for Honkai Impact 3rd (Free). | Read more »
‘Junkworld’ Is Out Now As This Week’s Ne...
Epic post-apocalyptic tower-defense experience Junkworld () from Ironhide Games is out now on Apple Arcade worldwide. We’ve been covering it for a while now, and even through its soft launches before, but it has returned as an Apple Arcade... | Read more »
Motorsport legends NASCAR announce an up...
NASCAR often gets a bad reputation outside of America, but there is a certain charm to it with its close side-by-side action and its focus on pure speed, but it never managed to really massively break out internationally. Now, there's a chance... | Read more »
Skullgirls Mobile Version 6.0 Update Rel...
I’ve been covering Marie’s upcoming release from Hidden Variable in Skullgirls Mobile (Free) for a while now across the announcement, gameplay | Read more »

Price Scanner via MacPrices.net

New low price: 13″ M2 MacBook Pro for $1049,...
Amazon has the Space Gray 13″ MacBook Pro with an Apple M2 CPU and 256GB of storage in stock and on sale today for $250 off MSRP. Their price is the lowest we’ve seen for this configuration from any... Read more
Apple AirPods 2 with USB-C now in stock and o...
Amazon has Apple’s 2023 AirPods Pro with USB-C now in stock and on sale for $199.99 including free shipping. Their price is $50 off MSRP, and it’s currently the lowest price available for new AirPods... Read more
New low prices: Apple’s 15″ M2 MacBook Airs w...
Amazon has 15″ MacBook Airs with M2 CPUs and 512GB of storage in stock and on sale for $1249 shipped. That’s $250 off Apple’s MSRP, and it’s the lowest price available for these M2-powered MacBook... Read more
New low price: Clearance 16″ Apple MacBook Pr...
B&H Photo has clearance 16″ M1 Max MacBook Pros, 10-core CPU/32-core GPU/1TB SSD/Space Gray or Silver, in stock today for $2399 including free 1-2 day delivery to most US addresses. Their price... Read more
Switch to Red Pocket Mobile and get a new iPh...
Red Pocket Mobile has new Apple iPhone 15 and 15 Pro models on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide service using all the major... Read more
Apple continues to offer a $350 discount on 2...
Apple has Studio Display models available in their Certified Refurbished store for up to $350 off MSRP. Each display comes with Apple’s one-year warranty, with new glass and a case, and ships free.... Read more
Apple’s 16-inch MacBook Pros with M2 Pro CPUs...
Amazon is offering a $250 discount on new Apple 16-inch M2 Pro MacBook Pros for a limited time. Their prices are currently the lowest available for these models from any Apple retailer: – 16″ MacBook... Read more
Closeout Sale: Apple Watch Ultra with Green A...
Adorama haș the Apple Watch Ultra with a Green Alpine Loop on clearance sale for $699 including free shipping. Their price is $100 off original MSRP, and it’s the lowest price we’ve seen for an Apple... Read more
Use this promo code at Verizon to take $150 o...
Verizon is offering a $150 discount on cellular-capable Apple Watch Series 9 and Ultra 2 models for a limited time. Use code WATCH150 at checkout to take advantage of this offer. The fine print: “Up... Read more
New low price: Apple’s 10th generation iPads...
B&H Photo has the 10th generation 64GB WiFi iPad (Blue and Silver colors) in stock and on sale for $379 for a limited time. B&H’s price is $70 off Apple’s MSRP, and it’s the lowest price... Read more

Jobs Board

Optometrist- *Apple* Valley, CA- Target Opt...
Optometrist- Apple Valley, CA- Target Optical Date: Sep 23, 2023 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 796045 At Target Read more
Senior *Apple* iOS CNO Developer (Onsite) -...
…Offense and Defense Experts (CODEX) is in need of smart, motivated and self-driven Apple iOS CNO Developers to join our team to solve real-time cyber challenges. Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Child Care Teacher - Glenda Drive/ *Apple* V...
Child Care Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Share on Facebook Apply Read more
Machine Operator 4 - *Apple* 2nd Shift - Bon...
Machine Operator 4 - Apple 2nd ShiftApply now " Apply now + Start apply with LinkedIn + Apply Now Start + Please wait Date:Sep 22, 2023 Location: Swedesboro, NJ, US, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.