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

Minecraft 1.20.2 - Popular sandbox build...
Minecraft allows players to build constructions out of textured cubes in a 3D procedurally generated world. Other activities in the game include exploration, gathering resources, crafting, and combat... Read more
HoudahSpot 6.4.1 - Advanced file-search...
HoudahSpot is a versatile desktop search tool. Use HoudahSpot to locate hard-to-find files and keep frequently used files within reach. HoudahSpot is a productivity tool. It is the hub where all the... Read more
coconutBattery 3.9.14 - Displays info ab...
With coconutBattery you're always aware of your current battery health. It shows you live information about your battery such as how often it was charged and how is the current maximum capacity in... Read more
Keynote 13.2 - Apple's presentation...
Easily create gorgeous presentations with the all-new Keynote, featuring powerful yet easy-to-use tools and dazzling effects that will make you a very hard act to follow. The Theme Chooser lets you... Read more
Apple Pages 13.2 - Apple's word pro...
Apple Pages is a powerful word processor that gives you everything you need to create documents that look beautiful. And read beautifully. It lets you work seamlessly between Mac and iOS devices, and... Read more
Numbers 13.2 - Apple's spreadsheet...
With Apple Numbers, sophisticated spreadsheets are just the start. The whole sheet is your canvas. Just add dramatic interactive charts, tables, and images that paint a revealing picture of your data... Read more
Ableton Live 11.3.11 - Record music usin...
Ableton Live lets you create and record music on your Mac. Use digital instruments, pre-recorded sounds, and sampled loops to arrange, produce, and perform your music like never before. Ableton Live... Read more
Affinity Photo 2.2.0 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
SpamSieve 3.0 - Robust spam filter for m...
SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering. SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more
WhatsApp 2.2338.12 - Desktop client for...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more

Latest Forum Discussions

See All

‘Resident Evil 4’ Remake Pre-Orders Are...
Over the weekend, Capcom revealed the Japanese price points for both upcoming iOS and iPadOS ports of Resident Evil Village and Resident Evil 4 Remake , in addition to confirming the release date for Resident Evil Village. Since then, pre-orders... | Read more »
Square Enix commemorates one of its grea...
One of the most criminally underused properties in the Square Enix roster is undoubtedly Parasite Eve, a fantastic fusion of Resident Evil and Final Fantasy that deserved far more than two PlayStation One Games and a PSP follow-up. Now, however,... | Read more »
Resident Evil Village for iPhone 15 Pro...
During its TGS 2023 stream, Capcom showcased the Following upcoming ports revealed during the Apple iPhone 15 event. Capcom also announced pricing for the mobile (and macOS in the case of the former) ports of Resident Evil 4 Remake and Resident Evil... | Read more »
The iPhone 15 Episode – The TouchArcade...
After a 3 week hiatus The TouchArcade Show returns with another action-packed episode! Well, maybe not so much “action-packed" as it is “packed with talk about the iPhone 15 Pro". Eli, being in a time zone 3 hours ahead of me, as well as being smart... | Read more »
TouchArcade Game of the Week: ‘DERE Veng...
Developer Appsir Games have been putting out genre-defying titles on mobile (and other platforms) for a number of years now, and this week marks the release of their magnum opus DERE Vengeance which has been many years in the making. In fact, if the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 22nd, 2023. I’ve had a good night’s sleep, and though my body aches down to the last bit of sinew and meat, I’m at least thinking straight again. We’ve got a lot to look at... | Read more »
TGS 2023: Level-5 Celebrates 25 Years Wi...
Back when I first started covering the Tokyo Game Show for TouchArcade, prolific RPG producer Level-5 could always be counted on for a fairly big booth with a blend of mobile and console games on offer. At recent shows, the company’s presence has... | Read more »
TGS 2023: ‘Final Fantasy’ & ‘Dragon...
Square Enix usually has one of the bigger, more attention-grabbing booths at the Tokyo Game Show, and this year was no different in that sense. The line-ups to play pretty much anything there were among the lengthiest of the show, and there were... | Read more »
Valve Says To Not Expect a Faster Steam...
With the big 20% off discount for the Steam Deck available to celebrate Steam’s 20th anniversary, Valve had a good presence at TGS 2023 with interviews and more. | Read more »
‘Honkai Impact 3rd Part 2’ Revealed at T...
At TGS 2023, HoYoverse had a big presence with new trailers for the usual suspects, but I didn’t expect a big announcement for Honkai Impact 3rd (Free). | Read more »

Price Scanner via MacPrices.net

New low price: 13″ M2 MacBook Pro for $1049,...
Amazon has the Space Gray 13″ MacBook Pro with an Apple M2 CPU and 256GB of storage in stock and on sale today for $250 off MSRP. Their price is the lowest we’ve seen for this configuration from any... Read more
Apple AirPods 2 with USB-C now in stock and o...
Amazon has Apple’s 2023 AirPods Pro with USB-C now in stock and on sale for $199.99 including free shipping. Their price is $50 off MSRP, and it’s currently the lowest price available for new AirPods... Read more
New low prices: Apple’s 15″ M2 MacBook Airs w...
Amazon has 15″ MacBook Airs with M2 CPUs and 512GB of storage in stock and on sale for $1249 shipped. That’s $250 off Apple’s MSRP, and it’s the lowest price available for these M2-powered MacBook... Read more
New low price: Clearance 16″ Apple MacBook Pr...
B&H Photo has clearance 16″ M1 Max MacBook Pros, 10-core CPU/32-core GPU/1TB SSD/Space Gray or Silver, in stock today for $2399 including free 1-2 day delivery to most US addresses. Their price... Read more
Switch to Red Pocket Mobile and get a new iPh...
Red Pocket Mobile has new Apple iPhone 15 and 15 Pro models on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide service using all the major... Read more
Apple continues to offer a $350 discount on 2...
Apple has Studio Display models available in their Certified Refurbished store for up to $350 off MSRP. Each display comes with Apple’s one-year warranty, with new glass and a case, and ships free.... Read more
Apple’s 16-inch MacBook Pros with M2 Pro CPUs...
Amazon is offering a $250 discount on new Apple 16-inch M2 Pro MacBook Pros for a limited time. Their prices are currently the lowest available for these models from any Apple retailer: – 16″ MacBook... Read more
Closeout Sale: Apple Watch Ultra with Green A...
Adorama haș the Apple Watch Ultra with a Green Alpine Loop on clearance sale for $699 including free shipping. Their price is $100 off original MSRP, and it’s the lowest price we’ve seen for an Apple... Read more
Use this promo code at Verizon to take $150 o...
Verizon is offering a $150 discount on cellular-capable Apple Watch Series 9 and Ultra 2 models for a limited time. Use code WATCH150 at checkout to take advantage of this offer. The fine print: “Up... Read more
New low price: Apple’s 10th generation iPads...
B&H Photo has the 10th generation 64GB WiFi iPad (Blue and Silver colors) in stock and on sale for $379 for a limited time. B&H’s price is $70 off Apple’s MSRP, and it’s the lowest price... Read more

Jobs Board

Housekeeper, *Apple* Valley Villa - Cassia...
Apple Valley Villa, part of a 4-star senior living community, is hiring entry-level Full-Time Housekeepers to join our team! We will train you for this position and Read more
Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a 4-star rated senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! Read more
Optometrist- *Apple* Valley, CA- Target Opt...
Optometrist- Apple Valley, CA- Target Optical Date: Sep 23, 2023 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 796045 At Target Read more
Senior *Apple* iOS CNO Developer (Onsite) -...
…Offense and Defense Experts (CODEX) is in need of smart, motivated and self-driven Apple iOS CNO Developers to join our team to solve real-time cyber challenges. 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.