Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
IN THIS CHAPTER
Why is automation important?
Who uses automation?
Introducing Automator
Introducing AppleScript
This book is about making your life easier, at least the part that intersects with your MacBook, MacBook Pro, iMac, or any other kind of computer running Mac OS X 10.6 Snow Leopard. In these pages you can learn how to automate various computing tasks, making yourself more productive and, I hope, happier.
Along the way, you'll get answers to questions like these:
What is automation?
Why care about automation?
What is Automator, and how do you use it?
What is AppleScript, and how do you use it?
How do you use these two technologies together?
No assumptions are made in these pages that you know any of this, so I start from scratch and move ahead. You should find the book's organization intuitive enough that you can skip the parts you're already familiar with.
This chapter, however, is a bit different. It's a quick start, a microcosm if you will, of the entire book. You're probably reading it in the comfort of a book store, or through the Amazon Look Inside feature, trying to decide whether to shell out your hard-earned money for the whole book. A lot of the material in this chapter is covered later in much greater detail, but for now, a brief tour is what you're after, and that's what you'll get.
Without further ado, follow me into the world of automation in Mac OS X.
It's ironic to consider that computers were invented to make our lives easier. They are able to reliably calculate impossible sums, allow us to take on tasks (like page layout, Web design, and video editing) that only the professionals could do before, and store all kinds of data, ranging from mundane receipts all the way to personal collections of photos, songs, and even that novel you've been working on for ten years.
For most of us, computers have brought a new way of working and interacting with others, which means that the whole nature of our society has changed dramatically. A hard day at work for my grandfather meant busting his back in the fields; for my father, it was working in a pre-computer age office; for me, it means manipulating documents and data. A lot of documents and data.
With a lot of anything come a lot of repetitive tasks. Consider the task of renaming one file. Simple, right? All you have to do is open the Finder, browse to the appropriate folder, click the name of the file, watch it become editable (see Figure QS.1), and then type in a new name for the file.
At some point, though, you may encounter a more onerous task: renaming 100 files. It's not really that difficult — it doesn't tax your mental facilities — but it is tedious. If you're not careful, you might not get all of them right, or you might miss a few, or you might get a call from someone and then come back to the task later, not really sure where you left off.
Given this trivial example, I come to the heart of the question: why is automation important? Automation is important because it:
removes the possibility of errors while doing those tasks; and
gives you more time and headspace for tasks that invite your full concentration and skills.
In this book, you can learn how to use two tools for automation in Mac OS X: Automator and AppleScript. The first is an intuitive, wizard-like tool that allows you to put together visual workflows. You'll find that it's useful in about 50 percent of situations where you need to automate a task. The second tool is a scripting language used for many different types of tasks. It does a rather good job of allowing you to customize any automation task and also gives you much finer control over your Mac.
You might think that the primary users of automation technologies are big businesses. In a sense, you're right. The world's largest organizations spend hundreds of millions (if not billions) of dollars each year trying to become more productive. They hire business analysts to figure out how different workers really do their jobs; then they make decisions based on that analysis to purchase tools, software, and training to make those workers more productive.
So it's not surprising that they spend a great deal of money automating all areas of their business. They have warehouse management and fleet management software to keep distribution flowing. They deploy storage devices and the backup software to run nightly backups. They install customer relationship management (CRM) systems and sales force automation (SFA) tools to facilitate the process of turning strangers into paying customers and then keeping those customers happy.
Automation isn't limited to the big guys, though. Small businesses use automation whenever they can — think about the investment the small retailer makes in a point-of-sale system. These systems help store owners keep track of sales, customer accounts, and much, much more. They can be integrated into other systems, like inventory management, to make reordering a lot more streamlined.
Think of the small design agency or software company. They need automated backups of files, as well as tools that help them put the finishing touches on production-ready products. On the design side, this may be a series of filters that convert masses of images into different formats. On the software development side, there are tools that automate builds and aid in the process of finding bugs.
So what about you? You may be a home-based business owner, a consultant, a lone-gun freelancer, or just a Mac owner with 10,000 photos to process. The same rules and processes that make automation a good deal for the big guys also apply to you.
Now take a look at Automator and AppleScript for a working example of what I've been talking about.
Automator is a workflow creation tool that features an easy-to-use interface. It's perfect for the non-programmer, because it allows users to piece together workflows using actions and other automation concepts. You'll be introduced to workflows, actions, and other terms here in this Quick Start chapter; you'll see those terms again later in the book, when the chapters have more space for a longer look.
Before I get started, let me introduce you to the user interface components you'll encounter the first time you open Automator (see Figure QS.2).
Along the top is Automator's Toolbar. The Toolbar gives you quick access to common functions. For example, on the left side you can click the Media button to access any photos, audio files, and other media that you might have stored on your Mac (see Figure QS.3).
On the right side of the Toolbar, you can record manual tasks with the Record button (this is in case the existing actions aren't what you need), and play and stop any workflows you may have built.
The rest of the interface is broken up into two halves. On the left side is the Library. The Library contains a list of available actions and variables that you can use in your workflows. This pane is split into two columns — on the left is a list of content types (each with its own associated application, like Mail or the Finder, and so on) followed by a list of categories (such as Recently Used and Most Relevant).
The right pane is where the workflows that you build reside. A workflow is just a series of steps to automate a process. For example, if you wanted to rename a bunch of files, you'd probably follow this process manually:
Copy those files (in case you make any mistakes) into a new folder, probably on your desktop.
Rename the files.
In Figures QS.2, you can see that the workflow on the right side follows this thinking. To automate, all you have to do is transcribe your manual process into a visual Automator workflow.
Before you go any farther along the actual Automator trail, I'll talk a little more about actions and variables, as they are key to understanding how workflows work.
Most Automator actions are designed to do a specific task: copy a file, open a URL, create an archive, and so on. In some cases, an action might do everything you need, but most of the time, you'll be adding actions together into a linked, multipart, automated process known as a workflow.
In a workflow, an individual action can receive input (or information) from a previous action and then pass along some output (results) to the next action in line. For example, if you're going to build a backup workflow for your documents, your actions might look like this:
Process a list of documents.
Pass the list on to the next action, the archive action.
Create a ZIP file using the archive action.
Pass the ZIP file on to the final action, backing up your documents.
Open an FTP connection to a remote server, or mount an attached drive (either of these could be the backup action).
In Figure QS.4, that's precisely what's happening. First, specify which documents to select in the Home directory, then archive them, and then use a Fetch FTP Upload action to upload the archive to a server. I'm using the Fetch FTP Upload action to make a point: Certain applications (likeFetch) make certain extra actions available to Automator. If you don't have Fetch installed, then you won't have this action available to you.
NOTE
If you install applications with Automator support, or download actions from www.apple.com/downloads/macosx/automator, they will be added to your available list of actions in Automator.
This little example brings up a few points about actions:
Your basic workflows almost always specify certain files to start with. As you get more advanced, you'll learn how to ask the user for their input on which files or items to process.
Actions are usually created by developers and made available to you. The makers of the FTP client Fetch have made a variety of actions available to folks who use their software. I've taken advantage of that generosity here in this sample workflow.
Notice on the workflow how the actions are connected. Normally, you see one action flowing into another by way of a downward-pointing triangle superimposed on a bubble. Later on, as you troubleshoot, the triangle is a good thing to look for. If you don't see the triangle (representing output) and bubble (representing an input channel), then your actions probably aren't connected.
Actions may take in one kind of input and provide a different kind of output. You might start by giving a workflow action a list of URLs, for example, but then end up with a list of images found on those URLs. You have to make sure that an action provides an output that another action can accept as input.
Furthermore, actions have options associated with them, but I'll get into all that when I build a sample workflow later in this Quick Start chapter. For now, it's important to understand that an action is the building block of a workflow and that each action accepts input and generates output. By chaining your actions in different combinations, you can build extremely complex workflows.
Starting with Mac OS X 10.5 (Leopard), Automator added a handy feature known as a variable. If you're a programmer, you know that a variable can hold or store some information, usually a number, name, date, or other string. In Automator, a variable is just that: a placeholder for some kind of information that you might use later on in a workflow. Suppose you want to create a workflow that downloads the text of a Web page to a text file on your computer. Normally, you would start your workflow with a New Folder action, which prompts you for a folder name and location. Then you'd add the other actions that would open the current Web page in Safari, grab the text, and save it to the folder you specified.
What you're going to add is a Set Value of Variable action in between the first two actions. This stores the name of the folder into a variable. You can then use that variable in the final New Text File action. All you have to do to use your new variable is to drag it from the Variable list to the pop-up menu.
|
Admittedly, this is a very simple example, but simple or not, variables can be very handy in making your workflows more flexible.
One more note about variables: Automator has a number of built-in variables that you can use. To see them, simply click the Variables button on the left pane. You'll see variables relating to the following:
Date & Time (such as today's date and current time, both of which are handy if you're doing backups).
Locations (such as your Downloads folder, your Home folder, and so on).
System (such as your computer's name, uptime, host name, IP address, and so on).
Text & Data (for specifying new variables and data).
User (such as a user's first name, e-mail address, and other personalized information).
Now that you have some introductory concepts out of the way, you can learn to create a very basic workflow from start to finish. You've already seen some examples here of different workflows, but this time you can focus not only on building a workflow, but the entire process behind a successful workflow.
This first workflow is pretty basic, and is based on some client tasks that I recently automated. The client had a folder full of eBooks in PDF format. What they wanted was some way to look for certain keywords within each PDF and then to label or tag those PDFs as having those keywords if found.
This is a perfect workflow to start with; everyone knows just how tedious it is to go through a bunch of PDFs and try to tag them in some way. The way this workflow is constructed, you can also reuse it in a variety of other contexts.
The first step is to figure out how to do the search. If you've been using Mac OS X for any length of time, you probably know about Spotlight, the built-in search feature. Lucky for you, there's also a Spotlight action that you can use in your workflows.
So this is what you're going to do:
Add the Spotlight action.
Limit the search to a certain folder (in this case, the client had all his eBooks in a folder named marketingtips).
Run a fixed search for a meaningful phrase like social media, as that's a good place to start.
In Figure QS.6, you can see that I've clicked Results under the Spotlight action. When the workflow runs, I can see exactly what comes back from my query.
The Results button is a handy way to debug your workflows, by the way. You can see your results in Icon, Table, or List view. In this example, the Icon view (shown in Figure QS.6) obviously displays a list of thumbnails. The Table view shows a list of paths formatted as a table (see Figure QS.7), and the List view shows the list of files as an AppleScript array (see Figure QS.8).
The point is that you can view these results in different formats. Not all result sets can display as icons, and in some cases, the List view won't be that useful to you unless you know AppleScript (which you will by the time you finish this book!).
Now that you've found some documents that actually contain the keyword or phrase you're looking for, it's time to do something useful with those documents. What you want to do is label those documents using the Label feature in the Finder. If you're not familiar with labels, they're just colors you can attach to a file in the Finder view (see Figure QS.9).
When this workflow runs, you end up with a blue label on all the PDFs that have the phrase social media in them, as illustrated in Figure QS.10.
This is immediately useful, of course, but isn't very interesting. I also decided to add some metadata to the Spotlight Comments for each of these files; that way, the client could keep better track of them in the future. Why use Spotlight Comments? Well, it's a good way to tag your files so that you can do something useful with them later — like create Smart Folders.
So I added a Set Spotlight Comments for Finder Items action in between the two actions already there, and made sure that I typed in social media. I also checked the box next to Append to existing comments (see Figure QS.11).
Once this workflow runs, you can Ctrl+click (or right-click if you have a two-button mouse) on any of these PDFs and select Get Info. You can see that you now have social media inserted into the Spotlight Comments in Figure QS.12.
So far, you've built a workflow that performs like this:
It takes a hard-coded search phrase (social media).
It finds documents that match that search phrase in a single folder.
It tags those files with that phrase in the Spotlight Comments.
Immediately useful, yes, but it's hardly extensible. What happens if you need to search other files for other phrases, and then apply other labels to them?
To begin customizing this workflow into a more flexible tool, follow these steps:
Delete the phrase social media from the Spotlight action.
Click Options along the bottom of the action.
Check the Show this action when the workflow runs checkbox. This causes the workflow to pause while you enter your own search string. Now when you run the workflow, Automator pauses and displays a dialog. The user can now enter a search phrase and even change the location of their search (see Figure QS.13).
Don't click Continue yet, because the search phrase is still hard-coded in the workflow.
Click Cancel (see Figure QS.14) to go back into Edit mode. What you want is to allow the user to enter whatever comments they feel like entering during the workflow.
Click Options.
Check the Show this action when the workflow runs checkbox (see Figure QS.15). One more bit of customization, and you'll be ready to run your new workflow. Instead of using the same label color, you can allow the user to choose their own label color.
Check the Show this action when the workflow runs checkbox (see Figure QS.16).
The result is a workflow with more interruptions (three, in fact) but with the results you want. As you can see from Figure QS.17, I've run a second search on email marketing and tagged a number of PDFs with the email marketing comment and a yellow label. Because files may exist that contain both social media and email marketing as phrases, the labels become less useful, but the comments are still appended.
Now that some files have Spotlight Comments, you could open a Finder window, select File New Smart Folder from the menu, limit the search to your user's home area, and click the + sign to add another criterion for searching and filtering. Once there, click Other and select Spotlight Comments from the list; then add social media to your match criteria. The result is a list of files in a new Smart Folder (see Figure QS.18).
You can then save this Smart Folder and add it to your Saved Searches, which puts it in the sidebar of your Finder window. If you add more social media Spotlight Comments to other files, they automatically show up in the list. You've just made the job of finding certain files a lot easier, and you didn't have to pick your way through hundreds of files in order to find what you were looking for.
For now, you're going to save your workflow as a workflow. A good suggestion is to create a Workflows folder in your home directory; that way, they stay organized. You can then load the workflow into Automator and run it again.
There are other options for saving your work, like a stand-alone application or plugin, but I'll talk about those later. For now, just know that an application can be invoked independently, while plugins are added to other contexts — for example, to the right-click menu or to the Print options menu.
Being able to save your workflows in different formats gives you a great deal of flexibility, putting your automation solutions closer to where you need them.
AppleScript is a scripting language that comes with your Mac. In fact, it's been available since the days of Mac OS 7, making it a venerable automation tool. So what is AppleScript? Put simply, it is a language you can use to control your operating system, files, and applications using a set of common instructions.
If you're new to programming, don't worry; you'll find AppleScript a pretty easy first language to learn. It uses some pretty intuitive structures and English-like names for operations. For example, you'll find yourself using the tell command a lot – tell application "TextEdit " is simply the way you open a text editor from AppleScript.
If you're an experienced Objective-C or Cocoa coder, you won't have that much trouble with AppleScript, as you'll already have your head wrapped around some of the same concepts. If you're a UNIX shell scripter, a Perl programmer, or a PHP/Ruby Web developer (or even a serious Java coder), then you might have a little transition time. Of all those languages, AppleScript is probably closest (at least in function) to shell scripting, but the way it's put together is very different from what you may be used to.
At its simplest, an AppleScript opens an application, tells it to do certain tasks, and then releases that application. In order for you to understand what that fully means, though, you have to realize the following:
Mac OS X may have a different idea than you of what an application is. For example, many developers who are new to the Mac don't realize that the Finder is an application. If you're in doubt, take a look at the list of applications in your Applications folder.
Not all applications are equally scriptable. Some applications may come with broad support for AppleScript (by way of robust dictionaries; more on this later), while others may have no support or offer only a limited amount of support.
Because you can find a lot more detail about AppleScript in Part III of this book, let's just jump in so that you can start to become familiar with it.
When you're creating an AppleScript, you'll be using the Script Editor, which is available under Applications Utilities
AppleScript Editor. The Script Editor is a lightweight environment in which you can create, edit, compile, debug, and run your AppleScripts (see Figure QS.19).
You enter your script code in the top pane, run it using the Run button on the toolbar, and see results and other data appear in the bottom pane. If the code opens Finder windows or applications like Mail or Address Book, then those events transpire as well.
You can create a very basic script and then add to it as you go along. For this first foray, write a script that opens your user's Documents folder in the Finder. To do that in AppleScript, you would use the following commands:
tell application "Finder"
open "myerman:Users:myerman:Documents"
end tellFigure QS.20 shows what that would look like in the Script Editor.
NOTE
You will need to fine-tune this script on your computer. You may have Macintosh HD as your root, or you may be using some other name. You'll most certainly have a different username.
By the way, another way of running this script in a more universally accepted way is:
tell application "Finder"
open (path to documents folder)
end tellAll you have to do now is click Run (the green button with the arrow pointing right) in the Toolbar or press +R on the keyboard, and you'll see your Mac open the directory specified in the script, as shown in Figure QS.21.
Add another line to the script. What if you wanted to open a certain Web page as well as a Finder window? You can do that with an open location command.
tell application "Finder"
open "myerman:Users:myerman:Documents"
open location "http://www.tripledogs.com"
end tellWhen you run this command, you not only get a Finder window, but a new Safari window (if Safari is your default browser!) with the URL also loads, as shown in Figure QS.22.
As you can see, you can open a lot of things with the Finder application, including applications and documents. Just keep adding them to the list in the Script Editor.
tell application "Finder"
open "myerman:Users:myerman:Documents"
open location "http://www.tripledogs.com"
open "myerman:Applications:Dictionary.app"
open "myerman:Users:myerman:Documents:TDDM:tddm_logo.pdf"
end tellIn Figure QS.23, I've asked for not only a Finder window and a Web document, but also the Dictionary application and a PDF of my company's logo.
This is all very handy, of course, as you can imagine setting this script up as something your Mac runs on start up every morning. However, at the moment all you're doing is filling up the screen with documents, Finder windows, and applications. It's automated, and it's a bit fun, but it isn't very useful.
Instead, get ready to learn more commands. A useful construct in AppleScript is get items of x, where x can be a folder or some other container. An item is just a generic object, something you might expect to find, like a file, folder, or shortcut.
If you go back to the idea of our marketingtips folder, the one that contained all those PDFs, you could run a simple AppleScript to get a list of all the items in that folder.
tell application "Finder" get items of folder "myerman:Users:myerman:Documents:marketingt ips" end tell
The result is a list of files found in the directory, as illustrated in Figure QS.24. As you can see, each item (in this case, a PDF) is listed in this format: document file X of folder A of folder B of folder C of folder D of startup disk of application Finder. Each file is thus marked in reverse path order, with each one culminating at the Finder application (if you're coming from Windows or Linux, you might find this a bit odd; just run with it).
Of course, you could be a little smarter about this and set the name of the folder in a variable. You can do this with the set command.
tell application "Finder"
set foldername to "myerman:Users:myerman:Documents:marketingtips"
get items of folder foldername
end tellThe result is the same, but now you can reuse the variable foldername as needed, without having to type up that entire path each time.
Change the command a bit and ask for item 2 only:
tell application "Finder"
set foldername to "myerman:Users:myerman:Documents:marketingtips"
get item 2 of folder foldername
end tellThe returned list in Figure QS.25 is now pretty short — in fact, it returns only the second file in the folder.
To get a sense of what you can do with AppleScript, select Window Library from the Script Editor menubar. What you see is a library of dictionaries for each application on your Mac. A dictionary in this context is simply a list of available hooks you can script. To find dictionary items available to AppleScript that relate to the Finder, double-click the Finder icon in the Library window.
When you do that, a long list of categorized items appears, as shown in Figure QS.26. Perusing the list should give you a pretty good idea of what's available to AppleScript.
For example, say you wanted to loop through the marketingtips folder and pull out the name and label index of each item you find, as shown in Figure QS.27. In this case, you would use the following script:
tell application "Finder"
set foldername to "myerman:Users:myerman:Documents:marketingtips"
get {name, label index} of items of folder foldername
end tellThe result is pretty straightforward: two lists, one containing the item name, the other containing an index label (where 0 is no label, 1 is red, and so on).
What's next? Well, if you know how to get a value, you can test that value with an if and then use set to change the value. For example, what if you wanted to write a script that would remove any label assigned to a list of files?
The first step in such a script would be to build on what you have. You already have a foldername variable that holds the path to the folder you're working with. The next step is to create a second variable, one called myfiles, that will hold all the items of that folder.
Use the repeat command to go through every file in myfiles, testing to see if the label index of the file is greater than zero. If it is, then you know that the file has a label associated with it, so reset the label index on the file to zero, thereby stripping every single file of its label.
tell application "Finder"
set foldername to myerman:Users:myerman:Documents:marketingtips"
set myfiles to items of folder foldername
repeat with myFile in myfiles
if label index of myFile > 0 then
set label index of myFile to 0
end if
end repeat
end tellOnce this code runs, each file in the folder is stripped of its label, as shown in Figure QS.28.
There is one last step before you move on. Right now, this AppleScript has limited usefulness, as it has a hard-coded variable. What if you could ask the user for a folder to work with? The way to do that is with a choose folder command, which you will use to prompt the user to select a folder (see Figure QS.29) and then capture all the items within it as an alias list.
tell application "Finder"
set myfiles to (entire contents of (choose folder) as alias list)
repeat with myFile in myfiles
if label index of myFile > 0 then
set label index of myFile to 0
end if
end repeat
end tellNotice also that you are setting the value of the myfiles variable right on the same line. This makes for a very long line of code, given all those prepositions, but it's classic AppleScript. It is a lot wordier than Unix shell, Perl, Python, and other languages you may be used to, but it gets the job done.
The only thing that's left is to save your work. You can save your AppleScripts wherever you like, but a good place to put them is in ~/Library/Scripts, where you'll find a lot of other AppleScripts. For example, the label-stripping script you just wrote here would be right at home in ~/Library/Scripts/Finder Scripts. You can save it as Strip Labels and run it by doubleclicking it (or adding it to an Automator workflow, but that would be skipping ahead).
At this point, the rest of AppleScript is in the details. Granted, there are a lot of details, but you won't need to know all of them in order to become productive. The aim of this book is to make you better at automation, so any AppleScript topics tackled in this book all relate to that objective.
So far, you've taken a very quick dive into the world of Automator and AppleScript. You've learned how to put together a simple workflow, and learned how to use actions and variables. On the AppleScript side, you've learned the bare-bones basics of working with the Finder, as well as getting and setting variables, built a simple repeat loop, added a conditional test, and asked for user input.