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

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 »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »

Price Scanner via MacPrices.net

You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more

Jobs Board

Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.