|< Day Day Up >|
Creating Advanced Automation with AppleScript
Although Automator is a great tool for stringing together prebuilt actions to create an automated workflow, it is neither the first nor the only means of automating actions on your Macintosh. AppleScript, originally introduced in the early '90s, provides much greater control over your entire system.
AppleScript is intended to provide a means for Macintosh users to develop complex scripts with the ability to evaluate conditions and branch, if needed. The syntax is surprisingly simple and can be understood even if you've never seen a programming language before. For example, consider the following code:
tell application "Finder" activate close window "Applications" end tell
It doesn't look like a programming language, but it is. This small example instructs Tiger to activate the Finder application and then close an open window with the title Applications.
Using a language that can almost be read aloud and understood, normal users can write scripts that combine the capabilities of multiple applications.
Using the Script Editor
The easiest way to get started with AppleScript is with the Script Editor. In addition to being a context-sensitive programming editor, it also acts as a script recorder. A user can open the Script Editor, click Record, and generate an AppleScript by using the editor to monitor his actions while interacting with a recordable application unfortunately, very few are.
The Script Editor serves as your primary entry and testing point for any AppleScript development, either recorded or entered by hand.
Script Editor Controls
Launch the Script Editor (/Applications/AppleScript/Script Editor) to begin scripting. Figure 4.8 shows the initial editor window.
Figure 4.8. The Script Editor is used when editing or recording AppleScripts.
The Script Editor recording and editing tools include
To start using the editor, click the Record button, switch to the Finder, and then open and drag a few windows around. As you work in the Finder, an AppleScript will build in the editor window. Click Stop to finish the code block and prepare it for execution. Figure 4.9 displays a script that has just finished generating.
Figure 4.9. Click Record to monitor your actions and build an AppleScript; click Stop to finish the script.
You can immediately replay the recorded actions by clicking the Run button.
Exploring the Scripting Dictionary
Obviously, the biggest draw to AppleScript is the capability to create scripts from scratch. Recording is a good way to get a quick start, but it can't be used to generate anything truly useful. The basic AppleScript syntax is covered later in this chapter in the section "Understanding AppleScript Syntax." Even this, however, is useless without knowledge of what commands an application can accept. Thankfully, each scriptable application contains a dictionary that shows the scripting features it supports.
To access a scripting dictionary for any application or scripting addition, choose File, Open Dictionary from the menu. A list of the available scriptable applications is displayed, as demonstrated by Figure 4.10. You can select multiple applications by holding down the Apple key.
Figure 4.10. Choose from the available scriptable applications.
Be aware that some applications might not be shown. The Browse button at the bottom of the window opens a standard File Open dialog for choosing an arbitrary file. After you've picked an application from the default or browse view, a dictionary browser window appears, as shown in Figure 4.11.
Figure 4.11. The dictionary documents the available AppleScript functions.
The browser toolbar works like many of Apple's other applications: The arrows move back and forth through dictionary entries and the search field provides an instant lookup of any key term you might need.
Below the toolbar are several columns. In the default view mode, the first column allows you to select suites of dictionary entries. A suite is simply a categorization for a certain types of AppleScript functionality. The DVD Player, for example, has a DVD Suite that contains all the necessary information for working with DVDs. Some applications might include other suites as well, such as a Standard Suite that provides everything you need to open and close documents, print, and so on. These additional suites are shared throughout the system and enable programmers to use a common syntax when doing everything from creating a new web browser window to creating a new text document.
When a suite is selected, all the available entries within that suite appear to the right and a complete summary of all suite keywords is displayed in the pane below the columns, as shown in Figure 4.12.
Figure 4.12. When a suite is selected, all entries are displayed in the lower pane.
To show a given entry within a suite, select it in the second pane and only its description will appear.
So, what are these entries? What do they represent? Each item within a suite is labeled as either a noun (n.) or a verb (v.); that is, a command or an event. Nouns are classes that you can either get information about or act on in some way. A class is an abstraction of a component of an application you work with, such as a file. When you work with a class, you work with an instance of a class, which is called an object. Objects can have properties that can be set or modified to effect changes to the object. In some cases, you might notice additional entries in the far-right column after you've selected an object. These entries are properties of the noun.
Since suites contain classes, commands, and objects contain properties and other objects, and because Apple has decided to refer to commands as commands, verbs, and events, and classes as nouns…things can get pretty confusing. To help make some sense of it, Apple adds one of five icons to the right of a dictionary entry to help quickly define its role:
For example, the Address Book suite contains a Person object. For a given Person, there are many different properties that can be assigned, as can be shown in Figure 4.13, as well as other objects contained within the Person.
Figure 4.13. The Person object contains many attributes that describe a person.
Each property is has a certain data type, such as an integer, image, text string, and so on. In this example, the title attribute of a person is a Unicode text string, whereas the image attribute is a TIFF.
By digging even further through the dictionary, we can find that there is a specific property of the Address Book application called my card, which, in turn, is an instance of the Person class representing the current user, as shown in Figure 4.14.
Figure 4.14. The my card object represents the currently active user.
The only way to find everything you can do with AppleScript is to dig and experiment. The dictionary browser provides two other browsing modes to help.
Using Alternative Browsing Modes
By default, the dictionary browser shows suites. In some cases, however, you might be more interested in seeing a hierarchical view of what is contained within a given set of objects, or viewing the entire inheritance tree for the application from top to bottom.
The Containment view, the middle button in the view controls of the toolbar, bases its display on how objects are contained within one another. For example, the Address Book application starts with an Application container. Within that container are documents, groups, people, and windows each of which, in turn, can contain additional elements. Groups, for example, can contain people and more groups. Because groups can contain groups, you could find yourself browsing an infinite loop, as seen in Figure 4.15.
Figure 4.15. The Containment view displays elements based on what other elements they contain.
The last viewing mode, Inheritance, uses the object hierarchy of the system to browse a dictionary. AppleScript is an object-oriented environment. This means that the classes you browse can inherit information and features from parent classes and subclasses can, in turn, inherit information from them. Remember earlier we mentioned that the Address Book application object contains a property called my card that, in turn, is a Person object describing the currently active user. Although this property is specific to the Address Book application, there are other generic properties, such as the application name and version, that are automatically inherited from a parent application object. A view of this inheritance can be seen in Figure 4.16.
Figure 4.16. Objects inherit properties from parent classes.
Unfortunately, object-oriented programming is a bit beyond the scope of this book. If you find these views at all confusing, stick to the Suites view, which provides a much cleaner organization for most users.
Entering a Sample Script
Let's see how the Person class can be used to return an attribute about someone in the Address book. Go back to the main Script Editor window and enter the following code:
1: tell application "Address Book" 2: get the job title of my card 3: set myTitle to the result 4: display dialog myTitle 5: end tell
When finished, click the Run button and a dialog box will appear with your Address Book title as the contents. Note that if you don't have a Job Title set, you'll need to choose Card, Add Field, Job Title within the Address Book application.
Line 1 indicates that instructions will be sent to the Address Book application. Line 2 gets the job title for the Person object contained in the special property "my card" (me). Line 3 sets a variable called myTitle to the results of the previous get command. Line 4 displays a dialog box containing the contents of myTitle. Finally, line 5 stops talking to Address Book.
This example introduces the structure you will see in most AppleScript programs. The tell, set, and get statements form the basis of scripts. The objects and the parameters that can be modified, however, must be looked up in the application's dictionary.
As you saw in the preceding sample script, when an AppleScript function returns a result, it is stored in a special temporary variable called result. This variable can be used to access a value without the need for additional variables. For example, lines 3 and 4 of the preceding script could be condensed to
display dialog the result
To display the contents of the result container within the Script Editor, choose View, Show Result (Command-2) from the menu, or click the Result button at the bottom of the Script Editor window. Tiger displays the current value of result below the script.
To trace the execution of a script as it runs, use the event log. This log keeps track of the events (commands) sent to an application and displays the results that are returned immediately. Click the Event Log button or press Command-3 to show the event log in the lower pane of the Script Editor window. Figure 4.17 shows the event log after replaying a simple script to get the location of a Finder window.
Figure 4.17. The event log can be used to monitor script execution.
After you've created a script that functions the way you want, you can save it in several different ways. Select File, Save As, and then choose from the following options, depending on what you want to do with the script:
There are five possible file formats for scripts:
In addition to the file format, you can also choose the line ending format if saving to a text file, and whether the file should be run only (not allow editing), display a startup screen, and stay open (after it has finished executing).
Changing Scripting Preferences
The Script Editor automatically highlights and formats AppleScript as you type. To change the default font styles and formatting, choose Preferences from the application menu.
The five categories of Script Editor preferences are as follows:
|< Day Day Up >|