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

Persecond 1.4.4 - Timelapse video made e...
Persecond is the easy, fun way to create a beautiful timelapse video. Import an image sequence from any camera, trim the length of your video, adjust the speed and playback direction, and you’re done... Read more
MarsEdit 4.3.1 - Quick and convenient bl...
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
Mindjet MindManager 12.1.177 - Professio...
MindManager is a powerful mind mapping tool that increases your productivity. From business plans or developing a new website, its robust mind maps have all the features you need to accomplish your... Read more
iClock 5.0.2 - Customizable menu bar clo...
iClock replaces the old Apple's default menu bar clock with more features, customization and increases your productivity. Features: Have your Apple or Google calendar instantly available from the... Read more
Vivaldi 2.4.1488.40 - An advanced browse...
Vivaldi is a browser for our friends. We live in our browsers. Choose one that has the features you need, a style that fits and values you can stand by. From the look and feel, to how you interact... Read more
LaunchBar 6.11 - Powerful file/URL/email...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
Dropbox 71.4.108 - Cloud backup and sync...
Dropbox is an application that creates a special Finder folder that automatically syncs online and between your computers. It allows you to both backup files and keeps them up-to-date between systems... Read more
Google Chrome 74.0.3729.108 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Postbox 6.1.15 - Powerful and flexible e...
Postbox is a new email application that helps you organize your work life and get stuff done. It has all the elegance and simplicity of Apple Mail, but with more power and flexibility to manage even... Read more
DiskCatalogMaker 7.4.13 - Catalog your d...
DiskCatalogMaker is a simple disk management tool which catalogs disks. Simple, light-weight, and fast Finder-like intuitive look and feel Super-fast search algorithm Can compress catalog data for... Read more

Latest Forum Discussions

See All

AFK Arena - Arcane Labyrinth guide
Looking for more tips and tricks for AFK Arena? Check out our AFK Arena Guide Compendium! | Read more »
What to expect from MU Origin’s April up...
The 1,000th day since MU Origin hit global stores is just around the corner — so what better time for another update? This April, players can expect fresh content to delve into, including new ways to fight rival players and a new realm to go... | Read more »
AFK Arena - Guide Compendium
AFK Arena has a lot going on in it, to the point that it can be pretty confusing. To help you on your journey from AFK zero to AFK hero, we've put together a collection of guides on this game so you know what to do when, what pitfalls to look out... | Read more »
AFK Arena guide - Tips and tricks for th...
Want to know where to begin with AFK Arena? Check out our AFK Arena beginner's guide! | Read more »
Mobile games you probably haven't p...
The App Store is bursting at the seams with all kinds of apps and games of varying quality, but one of the most consistent issues with it is discoverability. Despite having what seems like unlimited money and a full App Store editorial team, Apple... | Read more »
AFK Arena guide - Tips and tricks for be...
AFK Arena may be a less intense form of a gacha game, but that doesn’t mean it’s totally straightforward. As with other games in this genre, there’s a bevy of systems, modes, currencies, etc. that you’ll want to be familiar with as soon as you... | Read more »
Spellsword Cards: Demontide guide - Tips...
Spellsword Cards: Demontide is a wonderful little single-player card game, but it can also be quite unforgiving. Parts of it definitely look and feel like Hearthstone, but you can’t just play this game like its your favorite collectible card game (... | Read more »
The best driving games on iOS
With the recent release of Rush Rally 3, it's easy to be excited about mobile driving games. Figuring out what games in this genre are worth picking up, on the other hand, is a whole other story. [Read more] | Read more »
Construction Simulator returns to Europe...
German publisher astragon Entertainment and developer weltenbauer. SE have just released the third installment of Construction Simulator. Unlike Construction Simulator 2, which was set in the U.S., Construction Simulator 3 returns to its roots in... | Read more »
The best superhero game on mobile
I don't know if you know this, but superheroes are Kind of A Big Deal. Every other week it feels like a new Marvel movie is coming out and the hype train for each release is undeniable. Just look at how the upcoming Avengers: Endgame broke sales... | Read more »

Price Scanner via MacPrices.net

Amazon has base 15″ 2.2GHz 6-Core MacBook Pro...
Amazon is once again offering sale prices on new 2018 15″ 6-Core Touch Bar MacBook Pros with base 2.2GHz models now on sale for $300 off Apple’s MSRP, starting at $2099. These are the same models... Read more
Sale! New 2018 13″ 2.3GHz Quad Core MacBook P...
Amazon has new 13″ Quad-Core Touch Bar MacBook Pros on sale up to $500 off Apple’s MSRP today. Shipping is free. Select Amazon as the seller, rather than a third-party, to claim these discounts.... Read more
HomePod Sale! Get one today for $50 off Apple...
Walmart has new Apple HomePods on sale today for $299 on their online store. That’s $50 off MSRP and the lowest price available for a HomePod anywhere. Choose free shipping or free local store pickup... Read more
Verizon is offering the new 2019 10″ iPad Air...
Verizon is taking $200 off the cost of a new 2019 10.5″ Apple Pad Air or 7.9″ iPad mini for a limited time. Their discount includes $100 off Apple’s MSRP when you choose a 2-year contract with your... Read more
Save $200-$240 on a 12″ Retina MacBook with o...
Apple has Certified Refurbished 2017 12″ Retina MacBooks available for $200-$240 off the cost of new models. Apple will include a standard one-year warranty with each MacBook, and shipping is free.... Read more
Adorama offers Silver 15″ 6-Core MacBook Pros...
Adorama has new 2018 Silver 15″ 6-Core Touch Bar MacBook Pros on sale today for $250-$300 off MSRP. Shipping is free, and Adorama charges sales tax for NY & NJ residents only: – 2018 15″ 2.2GHz... Read more
Save $750 on an iMac Pro with this Certified...
Apple has Certified Refurbished 3.2GHz 8-Core iMac Pros available for $4249 including free shipping. Their price is $750 off the cost of new models. A standard Apple one-year warranty is included.... Read more
People Profiles: Saving The Planet In Turn Th...
FEATURE: 04.22.19- Earth Day falls on this day once a year but for one environmentally conscious user of older Apple computers, saving the planet is always on the back of their mind, the perfect... Read more
Apple has clearance 2017 27″ iMacs available...
Apple has Certified Refurbished 2017 27″ 5K iMacs available starting at $1439. Apple’s one-year warranty is standard, shipping is free, and each iMac features a new outer shell. The following models... Read more
Today on Amazon: New 2018 13″ MacBook Airs fo...
Amazon has lowered prices on new 2018 13″ MacBook Airs with models now on sale for up to $150 off Apple’s MSRP, each including free shipping. Be sure to select Amazon as the seller during checkout,... Read more

Jobs Board

Part Time Help / *Apple* Orchard - Iowa Sta...
Employer is looking for apple sorters and apple pickers. Applicants must be able to pay close attention to detail and have confidence around mechanical Read more
*Apple* Mobile Master - Best Buy (United Sta...
**688874BR** **Job Title:** Apple Mobile Master **Job Category:** Store Associates **Location Number:** 001013-Virginia Commons-Store **Job Description:** **Req #:** Read more
Best Buy *Apple* Computing Master - Best Bu...
**688696BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Sales **Location Number:** 000567-Worcester-Store **Job Description:** **Req #:** Read more
Best Buy *Apple* Computing Master - Best Bu...
**688464BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Store Associates **Location Number:** 000480-Muskegon-Store **Job Description:** The Read more
*Apple* Mobile Master - Best Buy (United Sta...
**679221BR** **Job Title:** Apple Mobile Master **Job Category:** Store Associates **Location Number:** 000138-Pinole-Store **Job Description:** **What does a Best Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.