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

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more

Jobs Board

Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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.