TweetFollow Us on Twitter

User Interface Scripting

Volume Number: 21 (2005)
Issue Number: 6
Column Tag: Programming

AppleScript Essentials

User Interface Scripting

by Benjamin S. Waldie

As we have seen in the past, AppleScript is a great tool for creating some pretty amazing automated workflows. When implementing an AppleScript-based workflow, you are really only limited by your imagination, and by the AppleScript support that is available in the applications that you want to automate.

Many scriptable applications offer enough AppleScript support for the types of tasks that you would want to automate the most. However, at times, you may find yourself needing to script an application with limited AppleScript support, and that one task you really need to automate just is not accessible through scripting. Or, worse yet, the application you want to automate is not scriptable at all!

How do you handle these limitations? Do you simply give up? I think not. For starters, you might check around to see if there are other scriptable applications that can be substituted to automate the same task.

Another option is to consider trying to automate the application by writing AppleScript code that interacts directly with the application's interface itself. Fortunately, with the release of Mac OS X 10.3, Apple introduced a new AppleScript feature, user interface scripting, or UI Scripting, which can be used to do just that.

What is UI Scripting?

UI Scripting is a feature in Mac OS X that provides a way for AppleScripts to interact directly with interface elements in running applications. For example, you might write a script that clicks a button in a window, selects a menu item in a popup menu, or types text into a text field of a non-scriptable application.

The AppleScript terminology for UI Scripting is not built into AppleScript itself, nor is it included in a scripting addition. Rather, UI Scripting is part of System Events, a background application that provides a central location for interacting with various aspects of Mac OS X itself, including running processes, or applications.

In order to view the AppleScript terminology for UI Scripting, open the dictionary for System Events by double clicking on it in the Script Editor's Library palette.


Figure 1. The Script Editor Library Palette and the System Events Dictionary

If you are using a different script editor, or prefer to open the dictionary by selecting File > Open Dictionary in the Script Editor menu bar, System Events can be found in the System > Library > CoreServices folder on your machine. In the System Events dictionary, UI Scripting-related terminology can be found under the Processes Suite. We will explore the UI Scripting terminology found in this suite shortly.

Enabling UI Scripting

Before writing code that makes use of UI Scripting in Mac OS X, you will first need to manually configure the machine on which the script will run, so that it can respond to UI Scripting commands. To enable UI Scripting, launch the System Preferences application, and click on the Universal Access button. Next, enable the checkbox labeled Enable access for assistive devices. See figure 2.


Figure 2. Universal Access Preference Pane

If the final destination for your script is another user's machine, then you should make sure that you provide that user with instructions for enabling UI Scripting on the machine prior to running the script. In order to ensure that the user actually follows your instructions, you may also want to add some code into your script to verify that UI Scripting has been enabled, and prevent the script from proceeding if it has not been enabled. You can tell if UI Scripting has been enabled by checking the value of the UI elements enabled property of the System Events application. This property will contain a true or false value, indicating whether or not UI Scripting is enabled.

The following example code will check to see if UI Scripting is enabled. If it is not enabled, the script will launch System Preferences, display the Universal Access pane, and notify the user that the Enable access for assistive devices checkbox must be enabled in order to proceed.

tell application "System Events" to set isUIScriptingEnabled to UI elements enabled
if isUIScriptingEnabled = false then
   tell application "System Preferences"
      activate
      set current pane to pane "com.apple.preference.universalaccess"
      display dialog "Your system is not properly configured to run this script.  
         Please select the \"Enable access for assistive devices\" 
         checkbox and trigger the script again to proceed."
      return
   end tell
end if

-- Add your code here, which will be triggered if UI Scripting is enabled

UI Scripting Terminology

As previously mentioned, the AppleScript terminology for UI Scripting is found under the Processes Suite in the System Events dictionary. Here, you will find a variety of classes, or objects, along with a few commands. Let's briefly discuss the commands first. We'll see them in action a little later.

Commands

There are only a handful of commands that you will use for UI Scripting, and they are click, key code, keystroke, perform, and select. In this article, I am going to touch on the click and keystroke commands, as they are what I have found to be particularly useful, and I have chosen to include them in the examples at the end of this article.

As one would expect, the click command is used to simulate the user clicking on an interface element. For example, you might use the click command to click a button on a window.

click button 1 of window 1

The keystroke command is used to enter keystrokes, as if they were typed by a user. The keystroke command also offers the ability, through an optional parameter, to specify modifier keys that should be invoked when the command is executed. For example, you may need to simulate the process of holding down the command key while typing a key.

keystroke "P" using {command down}

Again, these are just very brief introductions to two commands that can be used to interact with interfaces. You should spend some time exploring the other commands on your own, in order to become familiar with them. Now, let's take a look at some of the classes listed under the Processes suite of the System Events dictionary.

The Process Class

When working with UI Scripting, the top-level class you will address is the process class. A process signifies any process, or application, that is currently running on the machine. To get the names of any currently running processes, use the following syntax:

tell application "System Events" to return name of every process

--> {"loginwindow", "Dock", ... "Finder", "Preview", "Script Editor"}

Processes possess a variety of properties, which can be accessed through AppleScript. One such property is the frontmost property. In some cases, you may need to bring a process to the front in order to interact with its interface. This can be done by setting the frontmost property of the process to a value of true. For example, the following code brings the application Preview to the front.

tell application "System Events" to set frontmost of process "Preview" to true

Note in this example that I refer to the Preview application as a process of the System Events application. Be sure to explore the other properties of processes, as well, as they can provide other important information to your script.

I have chosen to use Preview for the examples in this article, since Preview is not AppleScriptable, and since it is installed with Mac OS X.

UI Element Classes

A process with an interface typically contains a variety of interface elements, such as windows, buttons, text fields, and more. These are the elements with which you will primarily want your script to interact.

In the System Events dictionary, a UI Element is, in itself, a class, and possesses a variety of properties common to most interface elements. For example, since many interface elements possess the ability to be enabled or disabled, an enabled property can be found under the more generic class of UI Element. Processes also inherit some properties from this class.

There are a number of different classes of interface elements in the Processes suite. If you have used AppleScript Studio in the past, then you will no doubt be familiar with the names of at least a few of them, although the exact naming may be slightly different from that of AppleScript Studio. Some of the more commonly accessed classes of interface elements include checkboxes, menus, menu items, pop up buttons, radio buttons, text fields, and windows. As mentioned above, since all interface elements possess certain characteristics, each class of interface element inherits properties from the UI Element class.

Be sure to browse through the various classes of interface elements listed in the Processes suite.

Referring to UI Elements

Just like scripting any object in a scriptable application, when writing code to interact with an interface, you must address the interface elements within their object hierarchy. Deciphering an object's hierarchy within a process' interface is usually no small feat. For basic interfaces, it may be as simple as referring to an interface element on a specific window. However, for more complex interfaces, it can quickly become a long set of nested object references.

Let's take a look at an example. The following code will click the Drawer button in the tool bar of an opened document in Preview, toggling the drawer opened or closed.

tell application "System Events"
   tell process "Preview"
      click button "Drawer" of tool bar 1 of window 1
   end tell
end tell

You can see from this example that in order to interact with the Drawer button, you must indicate specifically where the button is located within the interface. In this case, it is on the tool bar of the front window.

There is some good news, though. Apple doesn't leave you high and dry to figure out these object hierarchies on your own. There is a tool available to help. It is called UI Element Inspector, and it can be downloaded from Apple's AppleScript web site <http://www.apple.com/applescript/uiscripting/>.


Figure 3. UI Element Inspector

When launched, UI Element Inspector floats above all interfaces, and displays information about the interface elements located directly below the mouse pointer. Information displayed includes the location of the interface element, within its object hierarchy, along with values from various properties. In figure 2, UI Element Inspector is indicating the exact location of the Drawer button in a Preview window - within a tool bar, which is within a window of the application. As you can see, the tool bar itself does not possess a specific name, which is why I referred to it as tool bar 1 in my code.

Examples

Now, let's take a look at some examples of UI Scripting in action. The following example code assumes that you have a document opened in Preview. When this code is run, it will bring Preview to the front and print the front window.

tell application "System Events"
   tell process "Preview"
      set frontmost to true
      click menu item "Print..." of menu "File" of menu bar 1
      repeat until sheet "Print" of window 1 exists
      end repeat
      keystroke return
   end tell
end tell

The following example code assumes that you have a document opened in Preview. When this code is run, it will bring Preview to the front and export the front window to the desktop in TIFF format.

tell application "System Events"
   tell process "Preview"
      set frontmost to true
      keystroke "E" using {command down, shift down}
      repeat until sheet 1 of window 1 exists
      end repeat
      tell sheet 1 of window 1
         keystroke "Output"
         keystroke "D" using command down
         tell pop up button 1 of group 1
            click
            tell menu 1
               click menu item "TIFF"
            end tell
         end tell
         delay 1
         click button "Save"
      end tell
   end tell
end tell

Limitations

UI Scripting is based on Mac OS X's accessibility framework, which is why it must be enabled from the Universal Access preference pane. Because it is based on the accessibility framework, UI Scripting can only interact with applications that have been updated to support this framework. The accessibility framework was first released with Mac OS X 10.2, so many applications have accessibility support built-in by now. However, some applications do not, and may not respond to UI Scripting terminology. To automate applications that do not support UI Scripting, you may need to turn to other tools, such as QuicKeys <http://www.quickeys.com>.

A Third Party Assistant

While UI Element Inspector provides some much needed input for writing your AppleScript code, a third-party application takes it a step further.

PreFab UI Browser, a commercial application available from PreFab Software, Inc., offers all of the functionality of the UI Element Inspector, and a lot more. PreFab UI Browser provides robust interfaces designed for the serious scripter, making it easy to access information about the complete interface of any accessible running application. Other features of PreFab UI Browser include the ability to trigger hot keys to enable and disable interface element browsing, auto-generation of AppleScript code to interact with interface elements, and much more. Be sure to visit the PreFab Software, Inc. web site <http://www.prefab.com> for more information about this tool, or to download a demo version. While you're there, be sure to check out another product - PreFab UI Actions. This tool will allow you to configure AppleScripts to trigger automatically whenever specific user interface actions occur in an application. For example, you could configure an application to trigger a script whenever a user selects the Save As from the File menu. The possibilities are limitless.

In Closing

As you can see, UI Scripting can be quite a useful tool when trying to automate an application that doesn't provide the AppleScript support that you need. So, before you decide that just because an application isn't scriptable, it can't be automated with AppleScript, be sure to check out its interaction with UI Scripting.

In my experience, there is not much on the Mac that can't be automated... one way or another. Until next time, keep scripting!


Benjamin Waldie is president of Automated Workflows, LLC, a firm specializing in AppleScript and workflow automation consulting. In addition to his role as a consultant, Benjamin is an author for SpiderWorks, LLC and an evangelist of AppleScript. He can often be seen presenting at Macintosh User Groups, Macworld Expos, and more. For additional information about Benjamin, please visit http://www.automatedworkflows.com, or email Benjamin at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

CloudApp (Business) 6.5.2 - Video screen...
CloudApp is an instant video and image sharing platform for professionals. CloudApp is the fastest way to capture and embed video, GIFs, screencasts, and marked-up images throughout business... Read more
MarsEdit 4.4.13 - Quick and convenient b...
MarsEdit is a blog editor for OS X that makes editing your blog like writing email, with spell-checking, drafts, multiple windows, and even AppleScript support. It works with with most blog services... Read more
Hype 4.1.6 - $49.99
Create stunning animated and interactive web content with Hype. Hype’s HTML5 output works on all modern browsers and mobile devices like iPhones and iPads. No coding required. Hype’s free download... Read more
LibreOffice 7.1.3.2 - Free, open-source...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
War Thunder 2.5.1.111 - Multiplayer war...
In War Thunder, aircraft, attack helicopters, ground forces and naval ships collaborate in realistic competitive battles. You can choose from over 1,500 vehicles and an extensive variety of combat... Read more
djay Pro 3.1 - Transform your Mac into a...
djay Pro provides a complete toolkit for performing DJs. Its unique modern interface is built around a sophisticated integration with iTunes and Spotify, giving you instant access to millions of... Read more
OmniPlan 4.2.6 - Professional-grade proj...
With OmniPlan, you can create logical, manageable project plans with Gantt charts, schedules, summaries, milestones, and critical paths. Break down the tasks needed to make your project a success,... Read more
Visual Studio Code 1.56.0 - Cross-platfo...
Visual Studio Code provides developers with a new choice of developer tool that combines the simplicity and streamlined experience of a code editor with the best of what developers need for their... Read more
Opera 76.0.4017.107 - High-performance W...
Opera is a fast and secure browser trusted by millions of users. With the intuitive interface, Speed Dial and visual bookmarks for organizing favorite sites, news feature with fresh, relevant content... Read more
Duet 2.3.3.3 - Use your iPad as an exter...
Duet is the first app that allows you to use your iDevice as an extra display for your Mac using the Lightning or 30-pin cable. Note: This app requires a $9.99 iOS companion app. Version 2.3.3.3:... Read more

Latest Forum Discussions

See All

Bike Baron 2 opens pre-orders for iOS wi...
Whether it’s dodging spiky death traps or spinning through gigantic loops in the air, Bike Baron 2 has enough action to keep both newbie and veteran players hanging onto the edge of their seats. The much-awaited sequel to Cornfox & Brothers’s... | Read more »
MU Archangel: Everything we know about M...
As if the global release of MU Archangel isn’t exciting enough, we’ve got even more reasons to get hyped for Webzen’s mobile spin-off to MU Online. If you just can’t wait to pour out blood, sweat, and tears in strategizing your character’s best... | Read more »
Wild Rift will have a global esports tou...
Riot Games has announced that there will be a global esports tournament for their popular mobile MOBA, League of Legends: Wild Rift, later this year. This will see regional teams across the globe competing to earn a place in a tourney in late 2021... | Read more »
A Scrub's Guide to League of Legend...
Like all popular competitions, League of Legends: Wild Rift has developed a set of unwritten rules about how to play it well. These rules are known as the metagame or "meta," and understanding why they exist and how to take advantage of them is a... | Read more »
A Scrub's Guide to League of Legend...
I'm relatively new to League of Legends, but have played a fair amount of MOBAs in the past. Wild Rift has really captured my attention, though, and I've found myself sinking a lot of time into practicing and reading up on how to improve my game. | Read more »
Golf Impact is a new mobile sports game...
Neowiz has launched Golf Impact, a new competitive sports game for iOS and Android devices. [Read more] | Read more »
The best run-based games on iOS
The release of Returnal has caused me to revisit this list of the best run-based games on mobile. For the most part, run-based games are really great for mobile, because they provide a lot of depth and satisfying gameplay in a relatively bite-... | Read more »
Immersive horror game Under: Depths of F...
Rogue Games has released Under: Depths of Fear, its immersive first-person survival horror game for iOS devices. The game had previously been released on PC via Steam late last year, and is now available as paid title on the iOS App Store. [Read... | Read more »
A Scrub's Guide to League of Legend...
MOBAs are nothing new. They aren't even new to me. I've played just about every MOBA there is (mobile or otherwise) with varying amounts of time investment, with my previous favorites being Vainglory and Arena of Valor. But League of Legends: Wild... | Read more »
AFK Arena's latest collaboration wi...
Lilith Games and Ubisoft have announced another collaboration today that will see the Prince of Persia added to the popular idle RPG, AFK Arena. He is available in the game from today, and players can add him to their collection until the end of... | Read more »

Price Scanner via MacPrices.net

Amazon drops AirPods price to only $119 this...
Amazon has dropped prices on Apple AirPods (wired charging case) this weekend to a low of only $119.99 shipped. Amazon’s price is $40 off Apple’s MSRP, and it’s the lowest price available for new... Read more
10.9″ WiFi iPad Airs on sale for $50 off Appl...
Apple reseller Datavision has new 2020 10.9″ WiFi iPad Airs in stock today and on sale for $50 off Apple’s MSRP, starting at $549, each including free shipping. In addition, DataVision charges sales... Read more
Week’s Best MacBook Deals: 13″ M1 MacBook Air...
Apple resellers are offering sale prices on M1-powered 13″ MacBook Airs ranging up to $190 off MSRP this weekend. Get one today starting as low as $849: 8-Core M1 Silicon CPU, 7-Core GPU. MSRP: $999... Read more
Week’s Best Deals: 13″ M1 MacBook Pros for up...
Apple and its resellers are offering sale prices on new and refurbished M1-powered 13″ MacBook Pros ranging up to $230 off MSRP. Here are this week’s best deals: 13″ M1 MacBook Pro/256GB SSD. MSRP: $... Read more
Sams Club Sales Event: $50-$70 off Apple Watc...
Sams Club has Apple Watch Series 6 GPS models on sale for $50-$70 off Apple’s MSRP this week. $45 Sams Club Membership required. Note that sale prices are for online orders only, in-store prices may... Read more
Apple has iPhones available starting at $469...
Apple has a range of Certified Refurbished iPhones available today starting at only $469. Apple includes a standard one-year warranty, new outer shell, and shipping is free. According to Apple, “Each... Read more
M1 Mac minis in stock and on sale for up to $...
Apple reseller Expercom has M1 Mac minis in stock and on sale today for up to $46 off MSRP, starting at $663. Shipping is free. Purchase an AppleCare+ plan along with your mini for only $82, save $70... Read more
M1 Mac minis available for as little as $589...
Apple has a full line of standard configuration M1 Mac minis available in their Certified Refurbished section starting at only $589 and up to $140 off MSRP. Each mini comes with Apple’s one-year... Read more
Here’s how to save $400 on an Apple Pro Displ...
Expercom has Apple’s Pro Display XDR models on sale for $350-$400 off Apple’s MSRP, starting at $4649. They’re also offering a $100 discount on the Pro Stand: – Pro Display XDR Standard Glass: $4649... Read more
Sunday Sale: Save up to $420 on a 16″ MacBook...
Apple has a full line of Certified Refurbished 16″ 6-Core & 8-Core MacBook Pros available for up to $420 off the cost of new models, starting at $2039. Each model features a new outer case,... Read more

Jobs Board

*Apple* Mac Infrastructure Design & Deli...
The CTI End User Services Desktop OS Engineering team is seeking an Apple Mac Infrastructure Design & Delivery Engineer responsible for the end-to-end architecture Read more
Geek Squad *Apple* Consultation Professiona...
**805203BR** **Job Title:** Geek Squad Apple Consultation Professional **Job Category:** Store Associates **Store Number or Department:** 000238-Beaumont-Store **Job Read more
*Apple* Computing Specialist - Best Buy (Uni...
**805008BR** **Job Title:** Apple Computing Specialist **Job Category:** Store Associates **Store Number or Department:** 000201-San Antonio-Store **Job Read more
Teller at *Apple* Valley (40 hours) - Wells...
…+ Ability to work weekends and holidays as needed or scheduled **Street Address** **MN- Apple Valley:** 14325 Cedar Ave - Apple Valley, MN **Disclaimer** All Read more
Cub Foods - *Apple* Valley - Now Hiring Par...
Cub Foods - Apple Valley - Now Hiring Part Time! United States of America, Minnesota, Apple Valley New Retail Post Date 2 days ago Requisition # 131583 Sign Up Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.