Figure 23-1.Otto, the mascot and application icon for Automator
Figure 23-2.Creating a new Automator workflow
Workflows
A program written in Automator is called a workflow. A workflow is a step-by-step list of simple instructions, called actions. Workflows can also contain small bits of reusable data, called variables, but we’ll return to that. Actions resemble windows in that they contain a title bar, a content view, and a tabbed details view.
The title bar, which has the action’s name and icon, has a disclosure triangle on the left that will collapse and expand the action. Double-clicking the title bar has the same effect. On the right side of the title bar is an X icon. Clicking this icon will remove the action from the workflow.
CAUTION Clicking the X icon removes the action without warning or confirmation. You can undo this by selecting Undo from the Edit menu or by pressing Cmd+Z.
The action’s content view will typically contain preferences or other configuration options in the form of drop-down boxes, text fields, table views, and so forth. Your workflow contains a single action, Ask for Text, as shown in Figure 23-3. This action will prompt the user to enter some text. Set the question text to “What keyword shall I search for?” Leave Default Answer empty, but check the “Require an answer” box. Leave the buttons labeled as Cancel and OK.
To run this simple workflow, click the Run button in the toolbar. You’ll be presented with the dialog you designed, as shown in Figure 23-4. Automator will pause execution of your work- flow and wait for you to deal with the dialog. Enter a search term, and click the OK button.
Figure 23-3.Configuring an Automator action
Figure 23-4.Running an Automator workflow
Once the dialog is dismissed, Automator moves to the next action. Since there are no more actions, the workflow stops. Below the content view is a tabbed details view. Clicking a tab will expand the details view, while clicking the tab again will collapse it. Clicking the Results tab will show you your search term, as shown in Figure 23-5.
CHAPTER 23MAC OS X AUTOMATION WITH AUTOMATOR AND APPLESCRIPT 403
Figure 23-5.Examining the results of an Automator action
There are three tabs:
Results: When you run a workflow within Automator, you can examine the results of an action on this tab. This can include complex results such as images. There are several views within the Results tab, though which ones are available will vary depending on the type of data produced.
Options: Unlike the action’s own options, which are presented in the content view, these options are Automator preferences. Usually the only option will be to show the action occurring when the workflow is run, which can be useful when testing the workflow but would probably be annoying when actually using it.
Description: This is the same information presented in the sidebar’s detail pane when an action is selected. It gives the name and icon of the action, a description of what it does, and details such as the kind of input it requires, the kind of output it produces, its version, its copyright information, and so on.
So, you ask the user for a search term, but it’s not very interesting as it is. You need more actions so you can do something with this data.
Actions
Actions are the basic unit of work in Automator. The typical action takes some piece of data, asks an application to perform some task with that data, and produces the results. The results can then be fed into the next action until the work is done.
Actions that are available to you are contained in the Library sidebar. You can hide or show the sidebar with the Hide/Show Library button in Automator’s toolbar. You can also select Hide/Show Library from the View menu.
The Library sidebar has two tabs: Actions and Variables. Each tab has two columns. The leftmost column has folder-like groups. Selecting a group will show its contents in the right column.
You can filter the items showing in the right column by typing in the search field at the top of the column. Selecting an item in the right column will show a description in the details pane at the bottom of the sidebar. The details pane can be shown or hidden by clicking the disclosure button in the lower-left corner of the window.
You can create your own groups and smart groups from the group view’s context menu or from the action (gear) menu in the lower-left corner of the Automator window.
In Tiger, actions were grouped by which application provided them. In Leopard, the actions are grouped by the category of data they work on:
Calendar: iCal calendars, events, and To Do items.
Contacts: Address Book contacts information.
Developer: Xcode, SQL, CVS, and other developer tools.
File & Folders: Finder items and tasks, including moving, copying, and deleting items;
setting the desktop picture; and setting Spotlight comments.
Fonts: Font Book management tasks and metadata.
Internet: Web and RSS data, including extracting, filtering, and loading URLs.
Mail: Mail tasks, such as getting, filtering, displaying, and sending e-mail messages.
Movies: QuickTime, iMovie, iDVD, and DVD Player actions.
Music: iTunes and iPod actions, as well as the immensely useful Text to Audio File action.
PDFs: Preview actions for creating, controlling, or extracting data from PDF documents.
Photos: iPhoto, Preview, and QuickTime actions for getting, manipulating, and organizing photos. This also includes actions for controlling digital cameras and the iSight web camera.
Presentations: Keynote actions for controlling slide show presentations.
Text: TextEdit actions for creating, editing, and working with text documents.
Utilities: System services and Automator control actions, such as burning a disk and presenting different kinds of dialogs, as well as the immensely useful Run AppleScript, Run Shell Script, and Run Workflow actions.
Other: Theoretically, this group would contain actions that somehow don’t fit into other groups. In practice, it’s up to developers to define which groups their actions should be sorted into. If this information is not provided, the action ends up here.
NOTE Your categories may differ based on which applications you’ve installed. For example, the Developer category probably won’t exist if you haven’t installed any developer tools.
With the default actions, grouping by application or grouping by category is a largely irrel- evant distinction. Apple’s included applications tend to center around a specific type of data anyway.
However, when you install third-party applications, they will often add actions to Automa- tor. You can also download actions from the Web that may or may not use applications to do their heavy lifting.
The more actions you have, the more the category grouping becomes useful. You can toggle between application or category grouping from the “Arrange Actions by” submenu of the View menu.
CHAPTER 23MAC OS X AUTOMATION WITH AUTOMATOR AND APPLESCRIPT 405
Using Actions
Let’s use our keyword to do a Google image search. There are lots of actions for working with web data, but there’s no action to turn our keyword into a URL. However, there is a Run Shell Script action, and you can easily create a URL string in a shell script.
To add an action to your workflow, drag it from the sidebar’s right column. When it is over the workflow area, the action will expand into a full panel. To rearrange actions within the workflow, simply drag them around.
From the Utilities group, drag the Run Shell Script action to the workflow. The Ask for Text action automatically connects to the Run Shell Script action. When a workflow runs, it executes each action sequentially, from top to bottom. If an action generates output, it’s assumed to be the next action’s input. This relationship is represented by the connection between the two actions.
If two actions do not connect, no data will flow between them. If you want an action to ignore the data coming from the action above it, select Ignore Input from the receiving action’s context menu.
Select “/bin/bash” from the Shell drop-down and “as arguments” from the “Pass input”
drop-down. Enter the following simple shell script in the text area:
echo "http://images.google.com/images?q="$1
This simple script will return the beginning of a Google image query URL (as determined experimentally in Safari), plus the first argument, which will be the output of the Ask for Text action: the user’s keyword input. Running the workflow will produce the completed URL, as shown in Figure 23-6.
Figure 23-6.Running a shell script in Automator
NOTE Shell scripting is covered in Chapter 19. Apple also provides a shell scripting primer, available online: http://developer.apple.com/documentation/OpenSource/Conceptual/
ShellScripting/.
Once we have the URL to the search, we’ll want to get the results. A Google image search will return a page of links. To extract the links from the page, drag the Get Link URLs from Webpages action from the Internet group. You might as well check the “Only return URLs in the same domain as the starting page” option.
The Google results page will have a lot of links besides the image results, so you’ll want to apply a filter. Drag over a Filter URLs action from the Internet group. This uses a rule editor, similar to the one used in Mail. Again, by experiment, we determined we want links with URLs that begin with the following:
http://images.google.com/imgres?imgurl=
Running the workflow will show 20 URLs, as shown in Figure 23-7. Loading one of these URLs in Safari, you can see that these don’t lead to the image directly. Rather, they lead to a multiframe Google results page that requires some clicking to get the image.
Figure 23-7.Filtering URLs in Automator
However, the URLs themselves contain the link to the image. Once again, you will have to turn to a simple shell script to extract the text you need. Add another Run Shell Script action, just as before, and enter this script:
for url in $@
do
url=${url##*imgurl=}
url=${url%%&*}
echo $url done
This script loops through the arguments and extracts the text between imgurl=and &, return- ing the image URL.
TIP If you find it confusing having two actions called Run Shell Script, you can rename any action from its context menu.
To download the image, drag a Download URLs action from the Internet group, as shown in Figure 23-8. Note that when presented with a list of inputs, rather than a single input, Automator actions will automatically loop over the list item, eliminating most of the need for this most common programming control structure.
CHAPTER 23MAC OS X AUTOMATION WITH AUTOMATOR AND APPLESCRIPT 407
Figure 23-8.Downloading URLs in Automator
You could just download the images and open them in Preview, but that’s boring. With a lit- tle more work, you can build a dynamic screen saver to present your downloaded images.
Setting Up the Keyword Screen Saver
You could try to do all this in Automator, but since it has to be done only once, you can just set up the screen saver manually and use the Automator workflow to generate the dynamic content.
In the Finder, create a new folder in your Picturesfolder called Keyword Screensaver, as shown in Figure 23-9.
Figure 23-9.Creating the Keyword Screensaver folder in the Finder
Rather than write a screen saver, you can just use the photo screen saver already built into Mac OS X. Select System Preferences... from the Apple menu, select the Desktop & Screen Saver preference pane, and then select the Screen Saver tab, as shown in Figure 23-10.
Figure 23-10.Setting up the Keyword screen saver in System Preferences
From the Screen Savers list on the left, select Choose Folder.... This will present you with a standard open sheet. Select the Keyword Screensaverfolder, and click the Choose button. Finally, set up the photo screen saver as you want it. We recommend the new “falling pictures” display style, which is the second of the three styles.
With that set up, return to Automator. Drag the Get Specified Finder Items action from the Files & Folders group. You should do this before you actually download the images, so drag it to the top of the list. Click the Add... button, and find the Keyword Screensaverfolder.
This new action connects to the Ask for Text action. This is not what you want. Rather, you want to store the value until you’re ready to download the items. This is a perfect chance to use Automator’s new variables.
Variables
Like actions, variables are grouped by category. Since they typically have nothing to do with applications, there is no by-application grouping option.
Date & Time: The current year, month, day, day of the week, and of course the date and time
Locations: Known folders, such as Applications, Documents, Downloads, and the current user’s home directory
System: System information such as the computer’s name, IP address, and operating system version
Text & Data: Generic variables for storing text and data
CHAPTER 23MAC OS X AUTOMATION WITH AUTOMATOR AND APPLESCRIPT 409
User: User information such as username, first name, last name, e-mail address, and .Mac account name
Utilities: Other useful values such as an AppleScript variable or a random number
User-definable variables in the sidebar will have a blue icon with a V on them. They will also appear blue in the workflow. Variables whose contents are determined entirely by the computer will have a purple icon with a gear on it in the sidebar and will appear purple in the workflow.
Just like with the sidebar, you can drag variables from the list into actions or the workflow.
Variables are contained by the workflow but are used by actions, rather than accessed directly.
As such, dragging a variable from the sidebar into an action will add it to that action, but drag- ging a variable into the workflow itself will create an action, Get Value of Variable.
NOTE The Get Value of Variable action and the Set Value of Variable action are available from the Actions pane, in the Utilities category.
The bottom of the workflow pane contains a list of all its variables and their values, if appli- cable. Adding variables to the workflow automatically adds them to this list, but you can also create them in the list directly via the context menu. You can also edit variable names and values in the list.
From the Utilities group, drag in a Set Value of Variable action. From the Variable drop- down list, select “New variable...” and name it Image Folder, as shown in Figure 23-11. This will save the value of the Get Specified Finder Items action in the Image Folder variable, but you can also use the value immediately.
Figure 23-11.Setting the value of a variable in Automator
When you type a keyword and download images, they are going to be saved in the same folder as previous runs. Thus, your screen saver is going to remember all your previous key- words, diminishing the effect. Instead, you should clear the folder between runs so you always start fresh.
Drag a Get Folder Contents action from the Files & Folders group and then a Move Finder Items to Trash action. This will delete the folder’s contents. Since Move Finder Items to Trash does not produce output, this also solves the problem of feeding bad information into the Ask for Text action, as shown in Figure 23-12.
Figure 23-12.Emptying a folder in Automator
Now that you have a place to download your URLs, you can set the Where drop-down of your Download URLs action to Image Folder. Unfortunately, it’s not in the drop-down. That’s not a problem; simply drag the Image Folder variable from the variables list onto the drop-down, and it will be set for you, as shown in Figure 23-13.
Figure 23-13.Using a variable in Automator
CHAPTER 23MAC OS X AUTOMATION WITH AUTOMATOR AND APPLESCRIPT 411
Finally, drag a Start Screen Saver action from the Utilities group, and click Run. Pretty cool, right? You can save your workflow and open it in Automator any time, or you can save it as application, as shown in Figure 23-14. Now you can keep it in the Dock and, whenever you want, launch a new screen saver depending on your mood.
Figure 23-14.Saving an Automator workflow as an application
TIP You can drag the title of your newly minted application directly from the Automator win- dow’s title bar into the Dock.
When you’re running an Automator workflow in Automator, it’s pretty obvious what’s hap- pening. You can watch each action execute sequentially, examine the results, and watch the actions add messages to Automator’s log.
When Automator is closed and you launch your application from the Dock, it’s not imme- diately obvious that anything is happening. Since it takes a while to download all those images, it would be nice to have a status report. Fortunately, the Automator runtime does this for you automatically. When you run your new application, check out the status (and Cancel button) in the menu bar, as shown in Figure 23-15.
Figure 23-15.Automator workflow status in the menu bar
How Automator Works
Automator actions are actually tiny applications. They can be written as shell scripts, or they can be full-fledged programs written in Objective-C (and by extension, plain C). However, most Automator actions don’t do very much, instead deferring to existing applications on the system.
Automator doesn’t have any kind of magical ability to control other applications. It simply puts a convenient UI on an existing technology, the Mac OS X Open Scripting Architecture (OSA). You don’t need to use Automator to take advantage of the OSA. You can also address it in its native language: AppleScript.
AppleScript
AppleScript is a simple programming language for controlling applications. Although Apple- Script and Automator are different around the edges, it’s not a bad metaphor to think of AppleScript as writing Automator workflows in longhand.
To demonstrate that point, here is our Keyword Screensaver application written entirely in AppleScript:
-- Remove any existing images tell application "Finder"
set _imageFolder to path to pictures folder
set _imageFolder to folder "Keyword Screensaver" of folder _imageFolder delete every file in _imageFolder
end tell -- Ask for Text
display dialog "What keyword shall I search for?" default answer ""
set _keyword to text returned of result
set _queryURL to "http://images.google.com/images?q=" & _keyword -- Query Google
tell application "Safari"
open location _queryURL set _timeoutInSeconds to 20 delay 2
repeat with _waitInSeconds from 1 to _timeoutInSeconds
if (do JavaScript "document.readyState" in document 1) is "complete" then exit repeat
else if _waitInSeconds is _timeoutInSeconds then number -128
else delay 1 end if end repeat
set _searchResults to source of document 1 end tell
-- Extract image URLs from page source, then download them set AppleScript's text item delimiters to "\",\""
set _rawResults to text items in _searchResults set AppleScript's text item delimiters to ""
repeat with _text in _rawResults
if _text starts with "http://" and _text does not end with "/images" then do shell script "cd ~/Pictures/Keyword\\ Screensaver;
curl -sO " & quoted form of (_text as string) end if
end repeat
-- Activate screen saver
tell application "ScreenSaverEngine"
activate end tell
To use this script, open the Script Editor application in /Applications/AppleScript. The Script Editor is extremely simple. AppleScript goes in the main window, with runtime logging occurring below. The Run button in the toolbar parses, formats, corrects, compiles, and runs the script.
Even its biggest fans have to admit that AppleScript is a quirky language. Its English-like syntax makes it friendly to look at but tricky to write. Unlike C, which is rigid in its syntax,
CHAPTER 23MAC OS X AUTOMATION WITH AUTOMATOR AND APPLESCRIPT 413