Chapter 7. Services, Automator, & AppleScript

Apple’s specialty has always been taking complex, expensive technologies and somehow making them simple, attractive, and magical. They’ve done it with video editing, digital photos, DVD authoring, wireless networking, Web design, music production, podcasting—you name it.

Popularizing one particular task, however, has continued to elude Apple: programming.

Through the years, Apple has introduced various new technologies for helping novices write their own software:

This chapter covers these three build-your-own software technologies: Services, Automator, and AppleScript. True, the latter two require some technical ability. But even if you consider yourself a technophobe, at least read the section about Services. Some real gems await you, and you don’t have to do anything but click them.

Apple has always dreamed of a software architecture that would let you mix and match features from different programs—the Mac’s spell checker in Microsoft Word, the drawing tools of PowerPoint in your email, and so on. (Remember Apple’s OpenDoc software project? Neither does anybody else.)

For several generations of Mac OS X, a menu called Services sat in every single program’s Application menu, listing such interchangeable functions. And for all those years, most people pretty much ignored them.

That’s because the Services menu was baffling. It listed all kinds of weird commands. Most of them, most of the time, were dimmed and unavailable. None of them were described or explained anywhere. They sort of felt like a mistake.

In Snow Leopard, Apple gave Services an extreme makeover, in hopes of making them useful again. They’re still a little baffling, but there have been some forward strides.

For starters, Services commands are now contextual, meaning that they show up only when relevant; when a photo is selected, the text-related commands don’t appear.

They can appear in many more places, too:

Figure 7-2 shows what the Services menu looks like when you’ve highlighted some text in TextEdit.

You can now turn off Services you never use (in System Preferences), thereby hiding them, and you can even assign your own keystrokes to the Services you do use. Finally, you can very easily create your own Services menu items, using Automator.

Now, Services still aren’t first-class Mac citizens. They show up in most of the everyday Apple programs (Safari, Mail, TextEdit, iChat, Stickies, Terminal, and so on). But weirdly enough, they’re not available in any of the commercial Apple programs, like iLife (iPhoto, iMovie, iDVD, GarageBand), iWork (Pages, Keynote, Numbers), or the professional apps like Aperture and Final Cut.

Even so, with any luck, the new “appear only when relevant” approach will give Services another shot at stardom.

If you visit System Preferences→Keyboard→Keyboard Shortcuts, you see that Snow Leopard comes with a big set of starter Services. A lot of them are turned off at the outset (see the checkboxes?). That’s because a lot of them are fairly obscure or technical.

If you’d like a complete catalog of what they are and what they do, download the free bonus PDF appendix to this chapter from this book’s page at www.missingmanuals.com.

In the meantime, here are some examples of what you can do using the built-in Services. These examples also illustrate some of the different ways you can trigger these commands.

The preceding pages describe the best of the built-in Services. But there are hundreds more available on the Web.

Consider visiting www.macosxautomation.com, for example. That’s a Web site maintained by veteran automation fans for the benefit of anyone who’s interested. Here, when you click Services, you can find a Download page filled with useful, ready-made services. A few examples:

Clearly, there’s all kinds of fun (and utility) to be found in Services.

The Services command center is in the System Preferences→Keyboard→Keyboard Shortcuts pane. (You can also get there by choosing Services→Services Preferences from any program’s Application menu.)

Here, turn the checkboxes on or off to choose which Services you want available.

Handier still, you can double-click to the right of a Service’s name and then press a keyboard combination. That will become its new keyboard shortcut, available systemwide. (The usual caveats apply: Any keystroke you make up here overrides the same keystrokes that your programs may use for themselves, so be careful.)

Automator is the Mac OS X program that lets you create your own little programs—and your own Services, if you like. Like most programs on your Mac, it sits waiting in your Applications folder. Double-click its icon to open it for the first time. (Automator’s robot icon is supposedly named Otto. Get it? Otto Matic? Stop, you’re killing us!)

As you’ll soon discover, building an Automator workflow is a satisfying intellectual exercise and a delicious talent to acquire. But if the point of all the effort is to create a timesaving, step-saving software robot, you’ll need some way to trigger it—to run it, just the way you run an email program or a Web browser.

Fortunately, you can save a workflow as a regular, double-clickable application, if you like, or turn it into a Service, as described above, or embed it in shortcut menus all over your Mac. In fact, when you fire up Automator, the first thing it wants to know is: What is the desired destination for this workflow?

You’re offered seven options in the template screen shown in Figure 7-5:

Now, go forth and automate!

Once you’ve chosen a finished format for the workflow you’re about to create, you wind up in Automator itself. A tour may be in order:

At the top of the Automator window, the toolbar offers five fairly self-explanatory buttons. From left to right (Figure 7-7):

Under the Workflow pane on the left are two tiny buttons, identified in Figure 7-8. They hide and show two useful pop-up panels that contain logs (mini-reports): the Workflow log, which shows which actions ran successfully, which failed (if any), what each action did, and so on; and the Variables log (Figure 7-9), which shows all the variables used in your workflow. When you run the workflow, the Value list shows you what information was stored in each variable after the workflow finishes.

Automator comes with four prebuilt workflows that show off its capabilities. Find them by clicking Help→Open Examples Folder; open one of these workflows for inspection by double-clicking it.

Tip

In Snow Leopard, you don’t actually have to open an Automator document to see how it’s set up. Simply select a workflow in the Finder and hit the space bar to activate Quick Look (Quick Look), which gives you a preview of the entire workflow—actions and all.

(This doesn’t work on workflows saved in the old Mac OS X 10.4 format, though, at least not until you open them and re-save them in Snow Leopard.)

To many people’s surprise, the included workflows are quite useful:

Tip

There are two more great Automator examples at the Ground Zero of Automator, www.macosxautomation.com. “Welcome to the Party!” for example, cleverly demos two new features of Automator—variables and the Loop action—by showing you how to create a workflow that takes photos of your friends and turns them into a cool, party-ready screen saver.

Before you build your own workflows, it’s a good idea to understand how actions work together to process information. Here’s a step-by-step analysis of the Process Images workflow described above (Figure 7-10), which will give you deeper insight into building your own workflows.

  1. Ask for Confirmation.

    This common action, available in the Utilities category (in the Library list), produces a dialog box that tells the innocent bystander what’s about to happen (Figure 7-11). It’s often smart to begin each of your own workflows with a box like this, to remind yourself (or your minimum-wage minions) what the workflow actually does.

    In this case, the message informs your audience that the workflow is about to open a folder full of pictures, apply some wacko effects to them, and then open them up in Preview to display the results.

  2. Get Specified Finder Items.

    The next step in the Process Images workflow comes from the Files & Folders Library category. Here’s where you specify which files you want your workflow to operate on. You can use the Add and Remove buttons to edit the list—to add your own images to be mirrored, for example—or you can drag files straight from the Finder into this list.

    When this action is finished, it passes on a list of files and/or folders to the next action, ready for further processing.

  3. Copy Finder Items.

    This is a very important Files & Folders action: It makes a copy of the specified files and folders (in this case, the ones you identified in step 2) so you don’t gum up the originals. You can change where you want the copies stored by editing the “To” pop-up menu in the action. The menu lists obvious locations like Pictures and Desktop, or you can choose Other to select any folder you like.

    If you click Options in the action, you see that the “Show this action when the workflow runs” checkbox is turned on. That way, when your workflow runs, Automator will ask where to store the copies, so that the destination can be different each time. Otherwise, the files will automatically be copied to whatever folder you select in the pop-up menu right now.

  4. Apply Quartz Composition Filter to Image Files.

    This action (which came from the Photos category folder) processes the newly duplicated images from step 3; in this case, it applies a mirror filter to them. The action then passes the newly mirrored images on to step 5. If you prefer, you can choose a different filter from the pop-up menu—to make the image look like a comic-book drawing, for example—instead of applying the mirror filter.

    Since “Show this action when the workflow runs” under Options is turned on, you’ll have the chance to choose a different filter each time this workflow runs.

    (By the way, the image of the beach is intended to demonstrate the filter’s effect; it’s not actually one of your photos.)

  5. Open Images in Preview.

    This final action, which also comes from the Photos category, takes the post-filter images from step 4 and opens them in Preview. From there, you can flip, resize, or resave the images.

Try running the workflow by clicking Run. The bottom of the Workflow pane tells you which step of the workflow is running at the moment. As each action finishes, a green checkmark appears in its lower-left corner.

Unfortunately, if your workflow shuts down in the middle, you can’t restart it from there. When you click Run the next time, the workflow plays from the beginning.

You could spend all day playing with the workflows Apple gives you, making minor tweaks and seeing how they affect the workflow’s progress. You could even download more preassembled workflows from www.automatorworld.com, http://macscripter.net, or www.macosxautomation.com, if you were so inclined.

Still, those options don’t give you the kind of hands-on experience you need to automate your Mac on your own.

That’s why the following pages walk you through building two different Automator workflows from scratch. Along the way, you’ll learn several tricks that you’ll find handy when you start building your own workflows.

Wouldn’t it be cool if you could just click a file’s icon in the Finder—and choose “Send This File as an Email Attachment” right from its shortcut menu? One step, instead of the tedious business of opening your mail program, creating a new message, clicking Attach, finding the file, choosing it, and so on. Windows has had this feature for years, and it’s absolutely indispensable.

And now you can have it, too. A couple of steps in Automator, and this little gem is yours forever.

  1. In Automator, choose File→New (or press ⌘-N).

    The templates dialog box appears (shown back in Figure 7-5).

  2. Double-click Service.

    You want this puppy to be available from any Finder icon’s shortcut menu—and that’s the beauty of the Service.

    You wind up with a new panel at the top of the workflow, bearing the peculiar legend, “Service receives selected text in any application” (where the underlined phrases are pop-up menus).

    Remember, Services are contextual; they’re smart enough to know when to show up in your menus. That’s the purpose of these two pop-up menus: to let you specify when your new Service should appear. In this case, you want the menu to appear only if you’ve opened the shortcut menu for a file icon, in the Finder.

  3. From the first pop-up menu, choose “files or folders.” From the second, choose Finder (Figure 7-12, top).

    In future experiments, you could choose, from the first menu, “image files,” “PDF files,” “movie files,” or whatever; the Service would then appear only when you’ve right-clicked that kind of file.

    OK: You’ve now established what kind of file the Service will work on, and in which program. Now you have to tell Automator what you want to do with that file: attach it to a new, outgoing email message.

  4. In the Library list at left, click the Mail category.

    (Make sure the Actions button is clicked above the list.) You’ve just narrowed down the list of available actions to those that pertain to Apple’s email program.

  5. From the Actions column, drag the action called New Mail Message into the Workflow pane.

    (Use the Search box at the top if you don’t feel like reading through the list of Actions.)

    If you leave this action as it is, your workflow will autocreate an empty, unaddressed outgoing mail message; you’ll fill in the recipient name, subject line, and so on, when you run it. Which is fine.

    But you could, if you liked, take a moment now to pre-specify the recipient, subject, and body message for your new email message—great if you have to send the same stuff to the same people every week, for example. (You can even add an email address straight from your Address Book. Just click the address-card button in the upper-right corner.)

    If you look at the description for this action, you’ll see that the Input accepts “(Files/ Folders, Text).” It explains that if a file is passed from the previous action, it will automatically be attached to the email.

  6. Choose FileSave. In the dialog box, name your new Service command. Click Save.

    You can call it “Send As Attachment,” or “Send By Email,” or “Send This Baby Off!” Whatever you like.

That’s actually all there is to it. Now for the testing. Switch to the Finder and Control-click (or right-click) any file icon (Figure 7-12, bottom). From the shortcut menu, choose Send As Attachment (or whatever you called your Service).

Instantly, the Mac opens your email program and creates a new outgoing message—with your selected file already attached. You just saved about 35 steps.

iPhoto is a fantastic program for organizing digital photos. It even has its own photo-backup feature, which burns selected albums’ photos to a blank CD or DVD.

However, those backup discs maintain iPhoto’s complex and user-hostile Library folder structure. That’s great if you expect one day to restore the backup to iPhoto, because the backup maintains all your keywords, ratings, albums, comments, and other iPhoto data.

But it’s not so great if you want to hand the CD or DVD to anyone who doesn’t use iPhoto (like an OS 9 or Windows person), because they’ll have a devil of a time figuring out where the photos are in the convoluted Library folder structure.

If you build an Automator workflow to back up your photos instead, you (a) can burn a disc containing only the photos in one simple folder; (b) have more control over which photos are backed up; and (c) learn even more tricks for automating sophisticated operations. Figure 7-13 shows what the final workflow looks like.

Here’s how to put it together:

  1. Create a new Automator workflow (⌘-N).

    The template screen appears. In this example, you’ll create a standalone, double-clickable program. You’re a programmer now, baby! (Well, sort of.)

  2. Double-click Application.

    You arrive at the main workflow-construction area.

  3. Click the Photos category folder. In the list of available actions, find Ask for Photos. Drag it into the empty workflow area.

    Your newly hatched workflow, when it runs, will begin by asking you which photos you want to back up.

  4. In the Library list, click the Utilities folder. Drag the Ask for Confirmation action into the Workflow pane, above the Ask for Photos action. Fill in the text as shown at the top of Figure 7-13.

    Be sure to drag it above the Ask for Photos action so it’s the first thing that happens when you run your workflow. Now you’ve just directed Automator to begin its work by displaying a dialog box (Figure 7-14).

  5. Drag the “Burn a Disc” action to the bottom of the Workflow pane.

    Just to make this extra nice, why not make an options box pop up at the time of burning?

  6. Click Options, and turn on “Show this action when the workflow runs.”

    The options box will ask you to name the CD, choose a burning speed, and so on.

  7. In the Disc Name field of the Burn a Disc action, type “iPhoto Backup from” (that’s a space after “from”).

    This is going to be the proposed name for the CD.

  8. Click Variables above the Library list.

    Those variables are about to come in handy. You’re going to complete the phrase “iPhoto Backup from” with whatever the date of the backup is.

  9. Click the Date & Time folder in the Library list. Drag the “Today’s date” variable into the Disc Name field after “from.”

    The CD or DVD’s name will be something like “iPhoto Backup from 4/9/10,” making it easy for you to see when you made the backup disk. The date automatically changes whenever you run the workflow.

  10. Choose File→Save. Type a name for your new program (like Back Up This Month’s iPhoto Pix to CD), and save it wherever you like (on the desktop, for example).

    Now try it out. Double-click your newly forged program; your workflow springs into action, asking you to specify the photos you want, asking for a blank disc, and then burning it!

Automator is not a static, this-or-nothing program: It’s a versatile, expandable tool with ever-increasing potential. There are two especially good ways to increase Automator’s power beyond using the factory-installed actions: adding more actions yourself, and using the new Watch Me Do feature.

Automator comes with dozens of actions, but you’re bound—eventually—to find yourself wishing there were a few more. Perhaps you’d like some Automator actions to control non-Apple programs like Photoshop, or you’d just like to have a few extra actions to control Mac OS X itself.

Fortunately, Automator can handle actions written by non-Apple programmers, too. Just visit any of the Web sites devoted to Automator actions (like www.automatorworld.com. or www.macosxautomation.com), and download any actions you’d like.

If the action’s programmers did their jobs right, you can just download the action, run the installer, and sit back and watch as Mac OS X unpacks, copies, and installs the action automatically. The next time you open Automator, the new action will be listed in the correct folder in the Library list.

If, on the other hand, the action’s programmer did not create a self-installing action, you may have to manually double-click the .dmg, .sit, or .zip file you downloaded. Inside the folder or disk image that results, you should find a file ending in .action. Drag that file into either your Home→Library→Automator folder (to install the action for use under only your account) or to your Library→Automator folder (to install the action for all users on your Mac). In either case, if this is the first time you’re installing an Automator action by hand, you may have to create the folder yourself.

Once in Automator, you can use your new actions just as you’d use the ones that came bundled with your Mac: dragging and dropping them in whatever order you want, customizing their settings, and so on.

Before you run any new actions, though, look at the Description field to discover the actions’ inputs and outputs. With that information in hand, you’ll never accidentally connect, say, your new Sauté Vegetables action to an unrelated action like Burn a Disc.

And finally, if you’re interested in writing your own Automator actions (warning: programming experience necessary), visit http://developer.apple.com/documentation/AppleApplications/Conceptual/AutomatorConcepts/Automator.html for an introduction.

Sometimes, you’ll run into a task that Automator can’t accomplish with any action, no matter how nicely you ask: opening multiple folders of bookmarks in several Safari windows, for example, or automating some no-name program that doesn’t know anything about Automator and doesn’t come with any actions.

Enter Watch Me Do. In this mode, you click a Record button. The Automator window disappears, and a black “Automator: Recording” window takes its place. From now until you hit the Stop button, every mouse click and keystroke is recorded, step by step, into Automator. Later, you can survey the list of steps you took and clean them up.

When you run the workflow, your mouse actually moves to reproduce your clicks, and the Mac actually types the same keystrokes you did. It’s like watching a ghost control your computer, or maybe a really annoying little brother who won’t stop mimicking you.

You can even manipulate the individual steps—delete one, for example, edit the playback speed, or change how long it takes before the step “times out” (gives up).

It’s far easier to create workflows using Watch Me Do than having to drag the correct actions into the correct sequence; you’re leaving even more of the programming to Automator.

Unfortunately, there are drawbacks to Watch Me Do, too:

That’s why Watch Me Do may seem incredibly flaky. For best results, use keystrokes and keyboard shortcuts as much as possible, and avoid the mouse.

Here’s an example:

If you use Boot Camp to run Windows on your Mac (Chapter 8), you may find yourself having to open the Startup Disk pane of System Preferences with alarming frequency. And unfortunately, there’s no Change Startup Disk action in Automator to make that job less repetitive.

Fortunately, Watch Me Do can automate the process, so you can switch your startup disk with one click on an Automator-created application on your desktop or Dock. Creating the workflow is simple:

  1. Create a new workflow (⌘-N). Double-click Application in the template-selection panel.

    Since you’re just going to work with Watch Me Do, you won’t be messing with any predefined actions this time.

  2. Click the Record button.

    The Automator window disappears, and the black Recording window pops up. Everything you do is being recorded right into Automator.

  3. Click System Preferences in the Dock.

    If System Preferences isn’t in your Dock, put it there before beginning the recording. (It’s in your Applications folder.) Choosing its name from the menu generally doesn’t work, thanks to some typical Watch Me Do flakiness.

  4. In System Preferences, click Startup Disk, and then click either your Windows partition or your Mac partition.

    Later, you can create a second workflow to choose your other disk, if you want.

  5. Click Restart. In the confirmation box, click Restart again.

    Don’t worry; you’re not actually going to restart right now. Instead, Automator pops to the front, nagging you about the fact that it has an open document with unsaved changes—that is, the workflow you’re in the middle of making!

  6. Click Cancel.

    Now Mac OS X tells you that Automator canceled the restart you had asked for. Which, of course, you already know.

  7. Click OK. Click Stop in the Recording window.

    The Automator window reopens with a new Watch Me Do action in your workflow (Figure 7-15). The Events list shows you everything you did, step by step—right down to the clicking of the OK button in step 7. And that step should not be part of the workflow.

  8. Click the final step in the workflow action (which says “Click the ‘OK’ button”) and press Delete.

When you run the workflow, you’ll see your cursor magically move from one step to the next, all by itself (well, with a little help from Automator). It repeats every hesitation, misstep, and pause in your original mouse motion. Fortunately, you can speed up a particular step by up to 10 times using the Speed slider (also shown in Figure 7-15).

All in all, the mantra to use when dealing with Automator and Watch Me Do is simple: If you can perform a task with a specific action, use the action. Use the Watch Me Do mode sparingly.

AppleScript is a powerful computer language that’s been around since the days of Mac OS 7. Despite its maturity, however, AppleScript is often criticized by seasoned Mac programmers for being too simple, too easy to learn, and too much like English.

Of course, those are precisely the traits you want in a computer language—assuming, of course, that you want to use a computer language at all. If you’re an everyday Mac fan—as opposed to some computer-science Ph.D.—AppleScript is by far the easiest programming language to use for automating your Mac.

You can think of AppleScript programs (called scripts) as software robots. A simple AppleScript might perform some daily task, like backing up your Documents folder. A more complex script can be pages long. In professional printing and publishing, where AppleScript has hard-core fans, a script might connect to a photographer’s hard drive elsewhere on the Internet, download a photo from a predetermined folder, color-correct it in Photoshop, import it into a specified page-layout document, print a proof copy, and send a notification email to the editor—automatically.

Even if you’re not aware of it, you use the technology that underlies AppleScript all the time. Behind the scenes, numerous components of your Mac communicate by sending Apple Events, which are messages bearing instructions or data that your programs send to one another. When you use the Show Original command for an alias, or the Get Info command for a file or folder, an Apple Event tells the Finder how to respond.

AppleScript has several important advantages over Automator—not least of which is its even greater power. It comes with a dedicated program just for writing out these scripts. It’s the AppleScript Editor program that’s sitting in your Applications→Utilities folder. (It was called Script Editor before Snow Leopard.)

Still, AppleScript is a very deep subject—so deep, in fact, that you’d need an entire book to do it justice. This chapter is an appetizer; a book like AppleScript: The Missing Manual is the seven-course meal.

Here are a couple of very simple AppleScripts, just to give you a taste.

The first one opens your Applications folder. Sure, you can do that in the Finder easily enough, but this one works no matter what program you’re in.

Open up AppleScript Editor (which is in your Applications→Utilities folder). Type this:

tell application "Finder"
activate
open folder "Applications" of the startup disk
end tell

The result looks like Figure 7-16.

Now try it. Click the Run button. The first thing AppleScript Editor does is check your script for typos and syntax; if all is well, you’ll see the script format itself, putting the verbs in bold, indenting pairs of matched commands, and so on. If that part went well, the script runs—and your Applications folder appears before you. Woo-hoo!

Now you can save your script (File→Save); choose Application as the file type. In the unlikely event that this were an actual useful script, instead of a lame sample, you could stash the new program on your Dock for anytime access.

So what do those commands mean? Here’s the rundown:

Mac OS X comes stocked with dozens of programs—everything but the kitchen sink. All right, everything but the kitchen sink and a metronome. How are you ever going to play the piano in even rhythm without a steady clicking sound provided by your Mac? Sure, sure, you can use GarageBand’s metronome in a pinch, but that’s like using an industrial pile driver to kill an ant.

Instead, you can use AppleScript to do the job for you. Open a new document in Script Editor (File→New, or ⌘-N), and type this:

display dialog "Welcome to the AppleScript Metronome"
set bpm to the text returned of (display dialog ¬
"How many beats per minute?" default answer 60)
set pauseBetweenBeeps to (60 / bpm)
repeat
beep
delay pauseBetweenBeeps
end repeat

When you run this script, you see a dialog box that asks how many beats per minute you want the metronome to tick. Whatever number you type (for example, 120) gets stored in a variable—a temporary holding tank within the script—that you’ve named bpm.

Next, the script calculates how long it must pause between beeps, and puts that fraction of a second into the “pauseBetweenBeeps.” If you told the script to beep 120 times per minute, for example, “pauseBetweenBeeps” would be 0.5, since the script would have to pause half a second between beeps.

Finally, the script creates an endlessly repeating loop: beeping, pausing for the proper period, and then repeating.

Click Run to test out your script, and click Stop when you’ve had enough beeping.