TweetFollow Us on Twitter

User Interaction Basics

Volume Number: 20 (2004)
Issue Number: 5
Column Tag: Programming

AppleScript Essentials

by Benjamin S. Waldie

User Interaction Basics

Last month, we looked at some of the features of the new Script Editor, which was released with Mac OS X Panther (10.3). Now we are going to get started with actually writing some AppleScript code! This month's article will explain how, with only minimal code, you can update your AppleScripts to interact with the user. We will primarily focus on displaying dialogs and prompting for data.

User interaction options

AppleScript developers frequently have the need to incorporate user interaction into their scripts. Sometimes, this interaction is simply to notify the user of a message or an error. At other times, there is a need to request input from the user. There are several options available to developers who need to incorporate user interaction into their AppleScript solutions.

For this particular article, we are going to stick to the basics. We will focus on the commands that make up the User Interaction suite in the Standard Additions scripting addition. These commands will allow your scripts to display basic dialogs and prompt users for common types of information. Please note that some of the code specified in this article will only function in Mac OS X Panther (10.3), due to changes in the Standard Additions scripting addition terminology.

    The Standard Additions scripting addition is installed by default with Mac OS X, and can be found in the System > Library > Scripting Additions folder.

For those looking to create more robust custom interfaces for their AppleScripts, there are other options available, including the following:

AppleScript Studio - This development environment, which is included on the Xcode Developer Tools CD that ships with Mac OS X, allows users to build interfaces for their AppleScript applications, giving them the look and feel of any other Mac OS X application. For more information about AppleScript Studio, visit - http://www.apple.com/applescript/studio.

FaceSpan - Similar in many respects to AppleScript Studio, this commercial application also allows users to create complete complex interfaces for their AppleScript applications. A key selling point for FaceSpan is it's extreme ease-of-use for novice users. For more information about FaceSpan, visit - http://www.facespan.com.

Smile - This free third-party script editing application allows users to create complex custom dialogs quickly and easily. For more information about Smile, visit - http://www.satimage.fr/software.

3rd Party Scripting Additions - Third-party scripting additions, such as 24U Appearance OSAX, will allow users to dynamically build dialogs and interfaces for scripts during processing. For a comprehensive list of scripting additions, including those providing user interaction features, visit - http://www.osaxen.com.

The above listed tools range in complexity, and while some may be simple for beginners to master, others may be more complex and require more scripting experience. In the future, we will explore aspects of some of these other user interaction options.

Alerts and Messages

Audio Alerts

Sometimes, you may need to provide input to a user without actually displaying a message on the screen. This can be done with an audio alert. Audio alerts are useful in scripts running on unattended machines, as they can easily attract attention from across the room. Audio alerts can also be useful to provide progress updates to the user during processing.

The Standard Additions scripting addition allows for two primary types of audio alerts - a beep, and a spoken message.

    Audio alerts assume that the computer's sound level has been set to an appropriate level. However, this may not always be the case. You can use the set volume command, also available in the Standard Additions scripting addition, to change the volume level. Use this command to specify the desired volume level, from 0 (muted) to 7.

    set volume 7

    Please note that the Standard Additions scripting addition does not currently contain a command to GET the current volume level of the machine. Therefore, to get the volume level, you will need to utilize a third-party scripting addition, such as Jon's Commands http://www.seanet.com/~jonpugh/, or an application such as Extra Suites http://www.kanzu.com.

Beeps may be provided by using the beep command, and you may specify the desired number of beeps to occur with an integer. For example, the following code would beep 5 times:

beep 5

To provide a spoken message, use the say command. The following example shows how to use the say command, using the default voice assigned under Speech in System Preferences.

say "Hello!"

This code shows how you can specify which voice to use. Obviously, the voice specified must exist on your computer.

say "Hello!" using "Zarvox"

The say command also has another very interesting ability. It can actually be used to save a spoken message as a file, in AIFF format. For example, the following code will save the spoken message "Hello!" as an AIFF file, named "alert.aiff", to the user's desktop.

set theOutputFolder to path to desktop folder as string
set theOutputFile to theOutputFolder & "alert.aiff"
say "Hello!" saving to file theOutputFile

Display Dialog

Sometimes, it is necessary to provide more than an audio alert to a user during processing. You may want to provide a visual alert as well. In order to do this, you will need to make use of the display dialog command in the Standard Additions scripting addition.

display dialog  plain text
   [default answer  plain text]
   [buttons  a list of plain text]
   [default button  number or string]
   [with icon  number or string]
   [with icon  stop/note/caution]
   [giving up after  integer]

The display dialog command actually serves multiple purposes. It is used to display a message to the user, and it is used to get information back from the user, in the form of the button clicked, or the text that was entered.

The following code shows how to display a basic dialog to the user:

display dialog "Hello!"


Figure 1. A basic display dialog window

The code above will display a dialog box containing the text "Hello!" along with a "Cancel" and an "OK" button. In some cases, it may be necessary to customize certain aspects of the dialog. For example, you may need to include more than two buttons, specify the names of the buttons, or include an icon.

The following code shows how to display a dialog containing custom buttons.

display dialog "How are you today?" buttons {"Lousy", "Good", "Great!"}


Figure 2. A multi-button display dialog window

You will notice, when running the code above, that the dialog does not contain a default button. If desired, you can specify which button should be used as the default button in the dialog.

display dialog "How are you today?" buttons {"Lousy", "Good", "Great!"} 
default button 3

Or...

display dialog "How are you today?" buttons {"Lousy", "Good", "Great!"} 
default button "Great!"


Figure 3. A multi-button display dialog window with a default button

A dialog can also be configured to display a stop, note, or caution icon. This can be done by specifying the icon's type, or its ID - stop (0), note (1), caution (2).

display dialog "How are you today?" buttons {"Lousy", "Good", "Great!"} 
default button "Great!" with icon 1

Or...

display dialog "How are you today?" buttons {"Lousy", "Good", "Great!"} 
default button "Great!" with icon note


Figure 4. A display dialog window with an icon

In some cases, you may need your dialog to automatically dismiss. This is useful when displaying messages in scripts that must remain processing at all times, such as scripts running on unattended machines. The following code illustrates how to make your dialog automatically dismiss after a specified number of seconds.

display dialog "An error has occurred." giving up after 5

To prompt the user to enter text into your dialog, simply add the default answer parameter.

display dialog "Please enter a number:" default answer "5"


Figure 5. A display dialog window with return text

When displaying a dialog, you will generally want to have information returned to you for further processing. For example, you may need to determine which button the user clicked, or what text the user entered, and then take an appropriate course of action. Regardless of the type of dialog displayed, the display dialog command will always return a value. This value will indicate, in the form of an AppleScript record, the text that was entered (if relevant), which button was clicked, and whether the dialog was automatically dismissed (if relevant).

{text returned:"5", button returned:"OK", gave up:false}

By adding repeat loops, try statements, etc., you can begin to create more complex dialogs that will check the results entered by the user. For example, the following code will prompt the user to enter a number, and will keep re-displaying the prompt until a number is entered.

set thePrefix to ""
set theNumber to ""
set theIcon to note
repeat
   display dialog thePrefix & "Please enter a 
      number:" default answer theNumber with icon theIcon
   set theNumber to text returned of result
   try
      if theNumber = "" then error
      set theNumber to theNumber as number
      exit repeat
   on error
      set thePrefix to "INVALID ENTRY! "
      set theIcon to stop
   end try
end repeat
display dialog "Thank you for entering the number " & theNumber & "."

Prompts

The Standard Additions scripting addition also contains several other user interaction commands, which will allow you to prompt a user for various types of specific information.

Selecting Files or Folders

In some cases, you may need your script to prompt the user to select one or more files or folders. This may be done to determine which files to process, or to select an input or output folder. To prompt the user to select a file, use the choose file command. To prompt the user to select a folder, use the choose folder command.

For folders, you can optionally specify a prompt, a default location, whether or not the dialog should allow a user to select invisible folders, and whether the user should be allowed to make multiple selections.

choose folder
   [with prompt  plain text]
   [default location  alias]
   [invisibles  boolean]
   [multiple selections allowed  boolean]

For files, you have the option to specify generally the same information you can specify for folders, along with a list of acceptable file types, if desired. By specifying a list of file types, you can limit the files that the user may select.

choose file
   [with prompt  plain text]
   [of type  a list of plain text]
   [default location  alias]
   [invisibles  boolean]
   [multiple selections allowed  boolean]

It is important to note that both the choose folder and choose file commands are set to not allow for multiple selections by default. In addition, the choose file command is set to display invisible files by default, and the choose folder command is set to not display invisible folders by default. Therefore, you will need to add the appropriate optional parameters if the default behavior is not desired.

choose file without invisibles
choose folder with multiple selections allowed

The following code will prompt the user to select one or more PDF files, using the Documents folder as the default directory.

choose file with prompt "Please select a PDF document:" of type 
{"PDF "} default location (path to documents folder) with multiple selections allowed


Figure 6. A choose file prompt

Both the choose file and choose folder commands will return either an alias, or a list of aliases (if multiple selections were allowed). For example:

alias "Macintosh HD:Users:bwaldie:Documents: PDF Files:Job 1.pdf"

Or...

{alias "Macintosh HD:Users:bwaldie:Documents: PDF Files:Job 1.pdf", 
alias "Macintosh HD:Users:bwaldie:Documents: PDF Files:Job 2.pdf"}

Prompting for a File Name

The choose file name command in the Standard Additions scripting addition may be used to prompt the user to enter a name, and specify a location for a file. This can be useful if you need your script to create or save a document in a user-specified location.

choose file name
   [with prompt  plain text]
   [default name  plain text]
   [default location  alias]

The prompt that will be displayed as a result of the choose file name command will even handle the task of asking the user whether to replace an existing item with the same name. However, please keep in mind that the prompt will not actually overwrite or delete the existing file. You must write AppleScript code to perform this function.

The choose file name command will allow you to optionally specify a prompt, a default file name, and a default location.

choose file name with prompt "Where would you like to save your 
PDF file?" default name "Job 1.pdf"


Figure 7. A choose file name prompt

The result of the choose file name command will be a file reference.

file "Macintosh HD:Users:bwaldie:Documents: PDF Files:Job 1.pdf"

Selecting Items in a List

One of the more common tasks that you may need to perform, is to have the user make a selection from a list. This can be done using the choose from list command.

choose from list  a list of plain text
   [with prompt  plain text]
   [default items  a list of plain text]
   [OK button name  plain text]
   [cancel button name  plain text]
   [multiple selections allowed  boolean]
   [empty selection allowed  boolean]

The choose from list command will allow you to optionally specify a prompt, the item(s) that should be selected by default, and the OK and Cancel button names. You may also optionally indicate whether the user should be allowed to make multiple selections, or make an empty selection.

The following code will prompt the user to select a favorite type of fruit:

choose from list {"Apples", "Oranges", "Peaches"} with prompt 
"Please select your favorite type of fruit:" default items {"Apples"}


Figure 8. A choose from list window

If the user makes a selection, the choose from list command will return the user's selection(s), in list format.

{"Apples"}

Please note that while most dialogs and prompts will return a user interaction error (error number -128) if the user clicks the Cancel button, the choose from list command will return a value of false instead.

Selecting an Application

The User Interaction suite in the Standard Additions scripting addition also contains a command that will allow you to prompt a user to select an application - choose application.

choose application
   [with title  plain text]
   [with prompt  plain text]
   [multiple selections allowed  boolean]
   [as  type class]

The choose application command will allow you to optionally specify a window title, a prompt, and whether the user should be able to select multiple applications.

By default, the choose application command will return a reference to the chosen application. However, you may optionally specify that the command should return an alias to the application instead. In addition, if the user is allowed to select multiple applications, the result of this command will be a list.

choose application
--> application "Mail"
choose application as alias
--> alias "Macintosh HD:Applications:Mail.app:"
choose application with multiple selections allowed
--> {application "iChat", application "Mail"}
choose application as alias with multiple selections allowed
--> {alias "Macintosh HD:Applications:iChat.app:", alias "Macintosh HD:Applications:Mail.app:"}

Selecting a Color

A command that is new to Mac OS X Panther (10.3) is the choose color command. Invoking this command will display the standard Mac OS X color picker palette. Once the user has made a selection, it will be returned as a list of RGB values, i.e. {0, 9820, 65535}.

You may optionally specify a default color to display.

choose color
   [default color  RGB color]


Figure 9. A choose color dialog

Prompting for a URL

The choose url command may be used to prompt the user to select a network service, such as a server. This command will allow you to optionally specify which network services to display to the user, and whether or not the user should be allowed to manually enter a URL. Please note that this command does not actually connect to a chosen network service. Instead, it will simply return the user's selection as a URL string.

choose URL
   [showing  a list of Web servers/FTP Servers/Telnet hosts/File servers/News servers
      /Directory services/Media servers/Remote applications]
   [editable URL  boolean]


Figure 10. A choose url dialog

In Closing

One final command that I would like to mention is the delay command. While I am not sure that I would consider this to be a user interaction command, it has been placed in the User Interaction suite of the Standard Additions scripting addition. It is also a very useful command, and is certainly worth mentioning. The delay command can be used to make your script pause for a desired number of seconds. For example, the following code would pause the script for 60 seconds.

delay 60

Hopefully, this in-depth look at the commands in the User Interaction suite of the Standard Additions scripting addition will encourage you to begin adding more user interaction into your scripts. By adding this functionality into your AppleScripts, you will not only make your scripts feel more like "real" applications, but you will also begin to eliminate those hard-coded folder and file paths, names, and more. This will also help to make your script more portable, and reduce the possibility of errors.

In next month's article, we will start looking at some other basic AppleScript functionality, and, in the future, we will try to touch on some of the other, more robust user interaction options. 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 evangelist of AppleScript, and can frequently be seen presenting at Macintosh User Groups, Seybold Seminars, and MacWorld. 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

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.