8.4. Getting Started with AppleScript

 < Day Day Up > 

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 fanas 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 enjoys its greatest popularity, 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 editorautomatically.

Even if you're not aware of it, you use technology that underlies AppleScript all the time. Behind the scenes, numerous components of your Mac communicate with each other by sending Apple Events , which are messages bearing instructions or data that your programs send to each other. 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.

As described at the beginning of this chapter, AppleScript has several important advantages over Automatornot least of which is its even greater power. Still, AppleScript is a very deep subjectso 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.


Tip: You can also download an entire chapter about AppleScriptthe chapter that appeared in the previous edition of this bookfrom this book's "Missing CD" page at www.missingmanuals.com.

8.4.1. The Script Menu

You don't have to create AppleScripts to get mileage out of this technology. Mac OS X comes with several dozen prewritten scripts that are genuinely usefuland all you have to do is choose their names from a menu. "Playing back" an AppleScript in this way requires about as much technical skill as pressing an elevator button.


Tip: Similarly, you can download all sorts of useful scripts for iCal, iPhoto, iDVD, Mail, and other programs from the Apple Web site (www.apple.com/applescript/ itunes ; substitute the program name for that final part of the address).

To sample some of these cool starter scripts, you should first add the Script menu to your menu bar (see Figure 8-14).

Figure 8-14. Left: Tiger's starter scripts appear in categories.
Right: To make the Script Menu appear, open Applications AppleScript AppleScript Utility; turn on "Show Script Menu in menu bar." AppleScript Utility, new in Tiger, puts all of the AppleScript options in one place.


The Script Menu provides 16 pre-made categories, which incorporate over 100 scripts; just choose a script's name to make it run. Here's a summary of the most useful and fun scripts.


Tip: If you press the Shift key as you choose a script's name from the Script menu, Mac OS X takes you directly to that script's location in the Finder (for example, your Home Library Scripts folder). Better yet, if you press Option as you choose its name, you open the script in Script Editor for inspection or editing.
8.4.1.1. Address Book Scripts

In this submenu, you'll find only one script: Import Addresses , which is designed to move your names and addresses into Tiger's Address Book program from Entourage, Outlook Express, Palm Desktop, Eudora, Claris Emailer, or Netscape. If you've got a lot of friends , use this script; you'll be glad that you won't have to re-enter all their names, phone numbers , and email addresses.

8.4.1.2. Basics

This submenu offers three small, handy scripts related to AppleScript: AppleScript Help (which opens the Help Viewer and searches for the word AppleScript ); AppleScript Website (which opens the AppleScript Web page in your Web browser); and Open Script Editor (opens the Script Editor program, the program you use to read and write AppleScripts).

8.4.1.3. ColorSync

In this folder, you'll find a bunch of ColorSync script droplets (scripts that run when you drop something on their icons) primarily designed for graphic artists , Web site designers, publishers, and so on.

In some cases, choosing a script's name from the menu produces a terse help message and then an Open dialog box for choosing the graphics file you want to process. Others have an immediate effect; the "Mimic PC monitor" script, for example, adjusts the colors of your screen so they closely resemble the slightly different hues of a Windows PC monitor. That's a blessing if you're working on a photo or Web page, and you want to preview how it will look to the unwashed masses. (To restore the original colors, visit the Color tab of the Display pane of System Preferences.)

8.4.1.4. Finder Scripts

All of these scripts have to do with the Finder: manipulating files and windows, for example. A few of the most useful:

POWER USERS' CLINIC
Secrets of the Script Menu

The Script menu reflects the contents of two different Scripts folders: the one in your Home Library Scripts folder, and the one in your main Library folder. The ones in your Home folder are listed below the dotted line in the Script menu.

These scripts aren't just for running. They're also ideal for opening up in Script Editor (just by double-clicking)and analyzing line by line, to learn how they work. Once you understand the syntax, you can then copy bits of the code to modify and use in your own scripts. (Script Editor is a program in your Applications AppleScript folder, which you can use to type up your own scripts.)


  • Add to File Names, Add to Folder Names . These scripts tack on a prefix or suffix to the name of every file or folder in the front most Finder window (or, if no windows are open, on the desktop). You could use this script to add the word draft or final or old to all of the files in a certain folder.

  • Replace Text in Item Names lets you do a search-and-replace of text bits inside file names, folder names, or both. When one publisher rejects your 45-chapter book proposal, you could use this script to change all 45 chapter files from, for example, "A History of Mouse PadsA Proposal for Random House, Chapter 1" to "A History of Mouse PadsA Proposal for Simon & Schuster, Chapter 1."

  • Trim File Names, Trim Folder Names . If you made a mistake in using the Add to File Names script, you can always use the Trim File Names script to undo the damage. This one removes file extensions, suffixes, or prefixes of your choosing.

    For example, suppose you've just made a lot of new folders at once. Mac OS X calls them "untitled folder," "untitled folder 2," and so on. But what if you'd rather have them just called "folder 1," "folder 2," and so on? Run the Trim Folder Names script; when the dialog box asks you what you want trimmed , type untitled and click OK.

8.4.1.5. Folder Actions

In Tiger, you probably won't use these much, since Control-clicking a folder (or inside its window) offers the same access to folder actions (Section 8.3.2).

8.4.1.6. Font Book

These scripts are intended to be demonstrations of how you might automate certain font-oriented tasks .

8.4.1.7. FontSync Scripts

FontSync is a noble Apple attempt to solve an old problem for desktop publishers. You finish designing some beautiful newsletter, take it to the local printing shop for printing on a high-quality press, and then have to throw out the entire batchall because the fonts didn't come out right. The printing shop didn't have exactly the same fonts you had when you prepared the document. Or, worse , it did have the same fontbut from a different font company, with the same name but slightly different type characteristics.

FontSync is designed to give you early warning for such disasters. When you run the Create FontSync Profile script, several minutes elapseand then the Mac generates a FontSync Profile document. This file contains staggering amounts of information about the design, spacing, and curlicues of every font installed in your system. When you hand that profile over to your print shop, they can drop it onto the accompanying script, called Match FontSync Profile. It tells them precisely what fonts are different on their Macs and yours.

The wishful -thinking aspect of this technology is, of course, that it assumes a lot: that your print shop uses a Mac; that the print shop knows how to use FontSync, and that you remember to create the profile and submit it.

8.4.1.8. Info Scripts

These two scripts offer minor usefulness . Current Date & Time displays the current date and time in a dialog box, complete with a Clipboard button that copies the information, ready for pasting. Font Sampler creates a handy printable cheat sheet, suitable for posting on your wall, that includes every one of your fonts illustrated in a sentence (Figure 8-15).

Figure 8-15. Mac OS X can generate a handy sampler chart of all your fonts. You can even specify what the sample sentence is, just by opening up the script in Script Editor and retyping it. (Optionclick the script's name in the Script menu to open it.)


8.4.1.9. Internet Services

Two scripts in this submenu merit special mention. Current Temperature by Zipcode gives you the temperature outside your housein Fahrenheit and Celsius. It's just one more reason to stay inside all day.

Stock Quote fetches a 20-minute delayed stock quote for the company of your choice. It's not as good as getting real-time quotes, but hey, it's free.

8.4.1.10. Mail Scripts

Most of the scripts in this submenu do nuts-and-bolts things like counting messages in your mailboxes or setting up a new email account. The one that's the most fun, though, is Crazy Message Text (Figure 8-16).

8.4.1.11. Navigation Scripts

This subfolder's scripts let you jump to special folders in the Finder, right from the menu bar within any program. If the folder you want to open doesn't have its own dedicated script, choose from the listing in Open Special Folder .


Tip: If you're game to edit this script in Script Editor, you can modify it to let you choose and open more than one folder simultaneously (by -clicking them, for example). Just type multiple selections allowed true right after the text Choose folder to open : (which appears at the end of a line about a third of the way down the script). Save your changes.

Figure 8-16. Top: Enter your text in the Crazy Message Text dialog box. You can customize the range of font sizes in the message by clicking Set Prefs.
Bottom: Once you click Continue, you end up with a randomly -formatted jumble of text, perfect for avoiding handwriting detection. This script offers a great way to send electronic greeting cards, birthday wishes, or ransom notes. Getting Started with AppleScript


8.4.1.12. Printing Scripts

These scripts, new to Tiger, are designed to illustrate the power of AppleScript when it comes to printing and generating PostScript or PDF documents.

One of them, Print Window, plugs a long-standing hole in Mac OS X. It's designed to print a textual list of what's in any folder you choose. (It's a tad buggy , however.)

8.4.1.13. Script Editor Scripts

As the About these scripts command tells you, these 48 canned scripts can help you write faster and more accurate scripts, because the code chunks are free of typos and syntax errors. As you progress, you can add your own code-building scripts here, customized for the kind of scripts you like to build, to make you even more productive. (While writing your script in Script Editor, you insert one of these code chunks by Control-clicking and choosing from the shortcut menu.)

8.4.1.14. Sherlock Scripts

This script, which uses the old program Sherlock to search the Internet, was designed to serve primarily as an example for scripting hopefuls to study.

8.4.1.15. UI Element Scripts

Much of the time, scripts perform their magic quietly in the background, out of sight. But if you're trying to automate a program that doesn't respond to the usual AppleScript commands, your scripts can now " operate " them manually by making your Mac think you've clicked menu commands, clicking buttons , and so on.


Note: This feature, called UI ( user -interface ) scripting, doesn't work until you first open the Universal Access panel of System Preferences and make sure that "Enable access for assistive devices" is turned on.

You wouldn't want to run the scripts in the UI Element Scripts folder just as they are; they're simply samples that show you the correct syntax.

GEM IN THE ROUGH
Text to Audio Files

Your Mac can perform an astonishing feat: It can convert a text file into a spoken digital recording in AIFF audio format.

This is a twist with huge implications. If you transfer these files to your iPod, you can listen to your documentsemail, Web pages, reports , e-books, or anything else you can type or downloadas you commute, work out, or work outside.

Of course, commuters and joggers have been listening to Books on Tape for years , and companies like Audible.com create what you might call Books on MP3. But those products are expensive, and you can't listen to your own stuff.

To pull this off, just download the two sample scripts at www.apple.com/applescript/macosx/text2audio.html.


8.4.2. URLs

This final set of scripts provides quick links to common Web sites. All, that is, except Download Weather Map , which fetches an up-to-the-minute weather map of the continental United States and saves it on your desktop as weathermap.jpg .


Tip: You can add scripts, files, and even Internet location files (Section 19.9) to the Script Menu, so you can easily launch them all from the menu bar. Anything you drop into the Library Scripts folder automatically shows up in the Script menu.
Scripts Navigation Scripts folder.) Either way, Script Editor opens the file in a new window (Figure 8-17).

Figure 8-17. If you've never seen an AppleScript before, you may be surprised at how simple it looks. As you can probably guess from the commands in the window, this script simply opens the Applications folder in the Finder.


Here's how the script works:

  • tell application "Finder" tells Mac OS X which program is supposed to obey the following commands.

  • activate brings the Finder to the foreground, much as you would by clicking its Dock icon.

  • open folder "Applications" of the startup disk tells the Finder to open a new window, displaying the Applications folder on your main hard drive.

  • end tell directs the Finder to go about its regular business, ignoring further AppleScript commands.

To test the script out, just click the Run button, or press -R.


Tip: You can also edit this script to suit your needs. Try replacing "Applications" with "Users," for example, to make the script open the Users folder instead.

8.4.4. Writing Your Own Scripts

Mac OS X comes stocked with dozens of programseverything 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 


Note: Don't actually type the character. That's programmerese for, "This is really all supposed to be on the same line, but I ran out of space on the page."

When you run this script, you'll 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 variablea temporary holding tank within the scriptthat you've named bpm . (A variable in AppleScript is just like one in algebraa name given to something that can hold any value).

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.


Tip: To make your script even cooler , turn on the System Preferences Universal Access Hearing "Flash the screen when an alert sound occurs checkbox. Now when you run your script, you'll get both an audible beep and a visual flash. If you're recording music, just mute your Mac; you'll keep the visual metronome but you won't hear the beeps anymore.

8.4.5. AppleScript vs. Automator

AppleScript has hundreds and hundreds of uses: automating layout workflows that are too complicated for Automator, controlling programs that Automator doesn't recognize, and programming things like looping commands that Automator can't handle.

Yet if all you do is look at AppleScript as a second choice to Automator, you're missing out on a lot of power. Truth is, AppleScript lets you do more than Automator will probably let you do in the next 10 years; it's just a lot geekier.

In the end, stick with Automator for simple things. If you need to use AppleScript to automate some aspect of your Mac, though, don't despair. You're stepping up to a true power tool. (You can even combine the two, building AppleScripts right into your Automator workflows, thanks to the Run AppleScript action.)

Happy automating!

DAVE'S FAVES
One-Click Attachments from the Desktop

Here's a little Automator trick that can be a life saver for anyone who must frequently send documents by email. (It simulates the Send To command in the shortcut menus of Windows machineswhich is very, very handy.)

In Automator, build a workflow consisting of only two steps: Get Selected Finder Items (in the Finder category) and New Mail Message (in the Mail category). (If you're always sending files to the same personyour boss, sayyou can even pre-specify the address, right there in the Automator workflow pane. You can even set up the subject line and message ahead of time, if your job is really that repetitive.)

Now choose File Save As Plug-In. Name it Email This, or something.

From now on, you can email a document in the Finder just by Control-clicking it and, from the shortcut menu, choosing Automator Email This.

Bingo: Mac OS X fires up Mail and creates an outgoing message with the file already attached.

Bonus tip: If you insert another Automator step in between the other twoa Create Archive action (from the Finder category), your shortcut menu will compress the file or folder as a .zip file before emailing it!


 < Day Day Up > 


Mac OS X. The Missing Manual
Mac OS X Snow Leopard: The Missing Manual (Missing Manuals)
ISBN: 0596153287
EAN: 2147483647
Year: 2005
Pages: 506
Authors: David Pogue

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net