24.2. Getting Started with Accessibility
The prerequisite for GUI scripting to work is that the Accessibility API must be turned on. This may be done through the "Enable access for assistive devices" checkbox in the Universal Access system preferences. Unless this checkbox is checked, the scripts in this chapter will fail.
Now examine System Events's dictionary; in particular, look at the Processes Suite. Here you'll find events such as click and keystroke and classes such as radio button and menu item. The classes in question are all UI element subclasses. So your task is to use these events to operate on these classes, as a way of simulating clicks and keystrokes in the target application. The target application itself is expressed as an application process element of System Events. Thus, AppleScript code that does GUI scripting will have a structure similar to the following:
tell application "TextEdit" to activate tell application "System Events" tell application process "TextEdit" tell menu 1 of menu bar item "Format" of menu bar 1 click menu item 4 end tell end tell end tell
If you try that script, you'll see that it toggles the format of the frontmost TextEdit document between plain text and rich text (RTF). And you can see why: it literally chooses the fourth menu item of the Format menu. Observe that the target here is not TextEdit! It's System Events. The phrase tell application process "TextEdit" is not the same as tell application "TextEdit"it isn't an application specifier, it's merely an element specifier sent to System Events as part of the chain of ofs and tells specifying the complete target (see "The Chain of Ofs and Tells" in Chapter 11).
The problem now, for any given task you'd like to perform by means of GUI scripting, is to express each desired interface element in terms of the UI element object model. This is not at all easy; ultimately, you must probably resign yourself to a certain amount of experimentation. There are, however, some utilities that can help you. These take advantage the fact that the Accessibility API can not only drive interface elements; it can also see them.
Figure 24-1. PreFab UI Browser exploring TextEdit's menu