TweetFollow Us on Twitter

Providing Progress Feedback During Script Execution

Volume Number: 22 (2006)
Issue Number: 1
Column Tag: Programming

AppleScript Essentials

Providing Progress Feedback During Script Execution

by Benjamin S. Waldie

Many AppleScripts do not provide progress updates to the user during processing. Most of the time, when a script is run, it simply performs the appropriate tasks "behind the scenes," so to speak. If run as an application, a script may appear in the Dock when launched. However, this hardly provides detailed information to the user about what is actually occurring. Sometimes, a script may not need to provide progress updates to the user. However, there are situations when providing such feedback is a good idea.

In this month's column, we will walk through the process of creating a script that will provide visual progress information to the user during processing. The script we will create will save selected email messages in Mail as text files into a user-specified output folder. Since the script will have the ability to process multiple selected email messages, we will write our code to provide a visual indication to the user of which message is currently being processed. Once you learn how to provide this type of feedback, then you can begin integrating this same technique into your other scripts, making them more user friendly.

If you followed along with some of my past AppleScript Essentials columns, then you are probably familiar with AppleScript Studio, a feature set of Xcode and Interface Builder, the Mac OS X developer tools that come with OS X. AppleScript Studio provides a way for developers to build AppleScript-based applications, complete with robust interfaces. In this month's column, we will use AppleScript Studio to add a progress interface to our script, complete with text feedback and a progress bar.

Displaying a Basic Progress Interface with AppleScript

Before we get started with AppleScript Studio, let's discuss how to provide progress information to the user in a non-AppleScript Studio-based script.

In some cases, taking the time to construct an AppleScript Studio application may not be the best solution. For example, your script may be very simple, or it may be an existing script that is too complex to warrant conversion to AppleScript Studio at this time. You may just want a quick and easy way to provide feedback to the user. In these types of situations, the easiest method is to make use of the display dialog command, which can be found in the User Interaction suite of the Standard Additions scripting addition that is installed with Mac OS X.

Using the display dialog command, you can configure a script to display text messages in a no-frills dialog window at various times during script execution. The following example code demonstrates how a display dialog command can be used to provide such feedback.

set theOutputFolder to (choose folder with prompt "Select an output folder:") as string
tell application "Mail"
   set theSelectedMessages to selection
   set theMessageCount to count theSelectedMessages
   repeat with a from 1 to theMessageCount
      display dialog "Processing message " & a & " of " & theMessageCount giving up after 
         1 with icon note
      set theMessageContent to content of item a of theSelectedMessages
      set theArchivePath to theOutputFolder & "Archived Message " & a & ".txt" as string
      set theArchiveFile to open for access theArchivePath with write permission
      set eof of theArchiveFile to 0
      write theMessageContent to theArchiveFile
      close access theArchiveFile
   end repeat
end tell

In the previous code, the first line of the script will prompt the user to select an output folder. Next, the script will retrieve a list of selected email messages in Mail. The script will then proceed to loop through each of these messages. During each repeat loop cycle, the script will retrieve the content of the current message, and save it into a file in the output folder chosen by the user.

As you can see, in order to provide visual feedback to the user during processing, I have made use of a display dialog command within the script's repeat loop. This will cause the script to display a message to the user each time the script begins processing one of the selected email messages. I have configured the display dialog command to indicate the current message count, as well as the total count of selected messages. See figure 1.


Figure 1. A Basic Script Progress Dialog

I have also configured the display dialog command to automatically dismiss the dialog after it has been displayed for 1 second. This will ensure that the script can proceed automatically with further execution, without the user being required to actually click a button in order to proceed.

Upon the successful execution of the previous code, the output folder specified by the user should contain text files containing the contents of the selected email messages. See figure 2.


Figure 2. Archived Email Messages

The display dialog command can also be used independently, rather than within a repeat loop to indicate various tasks that are being performed by the script.

Now that we have discussed providing basic progress information to the user, let's move on to AppleScript Studio. In the remainder of this month's column, we will walk through the process of creating a script that will perform the exact same function as the previous code, only with a more robust interface.

Building the AppleScript Studio Project

You may recall that the first step in building an AppleScript Studio project is to create a new project in Xcode. Begin by launching Xcode.

    Please note that the AppleScript Studio project covered in this article was developed using Mac OS X 10.4.2 and Xcode 2.1. Please be aware that new software versions often result in changes in AppleScript terminology. Therefore, if you are using software versions other than those that I have specified, your required terminology may differ slightly from that which I am using in this article.

    Create a new project by selecting New Project... from the File menu in Xcode. When prompted, select a project type of AppleScript Application from the list of available project templates, enter a project name of Archive Selected Messages, and specify an output folder for the project. Xcode will duplicate the AppleScript Application project template into the specified output folder, and open it for you. See figure 3.


Figure 3. Archive Selected Messages Project Window

Building the Interface

Next, we will create an interface for providing progress information during processing. Double click on the MainMenu.nib file within your Xcode project window. This will open the project's default view in the Interface Builder application.

Designing the Window

By default, the project's interface should already contain an empty window view. This window will be the basis for our interface. Click on the window, and give the window a name by entering Archive Selected Messages Progress into the Window Title field in the Inspector palette. See figure 4. If the Inspector palette is not visible, select Show Inspector from the Tools menu in Interface Builder.


Figure 4. Preparing the Progress Window

Once you have specified the title for the window, de-select the Visible at launch time checkbox in the Inspector palette. This will cause the window to be hidden when the project is first launched.

You may want to make some other adjustments to the window configuration at this time, as well. For example, you may want to disable the ability for the user to close or zoom the window. Refer to figure 4 for the settings that I have specified for my progress window.

Next, click on the Cocoa Controls and Indicators tab in the toolbar of the Palettes window. If the Palettes window is not visible, select Palettes > Show Palettes from the Tools menu. Next, locate an NSProgressIndicator progress bar interface element in the Palettes window, and drag it into your project's window. See figure 5.


Figure 5. Adding an NSProgressIndicator

Next, click on the Cocoa Text Controls button in the toolbar of the Palette window, and drag an NSTextField into your interface window. Enter some default text, such as Waiting to process... into the text field's contents.

Continue to arrange and design the interface, making sure to adhere to Apple's standards for human user interface guidelines, which can be found in the ADC Reference Library, both online and in Xcode's documentation. See figure 6 for an example of my completed interface design.


Figure 6. Example Progress Interface Design

Preparing the Interface for AppleScript Interaction

Once you have finished designing your progress interface, the elements that make up the interface must be prepared to interact with the AppleScript code within your project. To do this, you must assign AppleScript names to various interface elements, as well as configure certain elements of the interface to respond to event handlers.

First, we will assign an AppleScript name to the main window itself. To do this, click on the window to select it. Next, choose AppleScript from the popup button at the top of the Inspector palette, and enter the name Progress Window into the Name field. See figure 7. The process of assigning AppleScript names to the other interface elements will be the same.


Figure 7. Assigning an AppleScript Name to the Progress Window

Select the progress indicator bar and text field in the window, and assign AppleScript names of Progress Bar and Progress Text, respectively.

As the last step in configuring the progress interface, we must configure the solution to run our AppleScript code when launched. This will be done by enabling an event handler. To do this, first select File's Owner in the MainMenu.nib window. A list of available event handlers will be visible on the Inspector palette, beneath the Name field. Enable the launched event handler by selecting its checkbox in the list of event handlers. Next, link the event handler to the AppleScript code in your project by selecting the checkbox next to Archive Selected Messages.applescript in the Script area at the bottom of the Inspector palette, beneath the event handler list. See figure 8.


Figure 8. Enabling the Launched Event Handler

Adding the AppleScript code

Now that you have configured your interface, it is time to begin adding the AppleScript code into your project. Return to Xcode, and double click on Archive Selected Messages.applescript file in your project to begin editing the AppleScript code.

Preparing the Launched Event Handler

Since we configured our interface to respond to the launched event handler, we will need to add this handler to our project's code. If you saved your project's interface in Interface Builder, then this code may have been automatically inserted for you within your main project script in Xcode. If it does not exist, enter it as follows:

on launched theObject

end launched

Any code that is entered into this launched handler will be executed when our project application is launched. As we proceed, enter all code below within the launched handler.

Get the Output Folder

It is now time to begin adding the processing code to our project. Begin by entering the following code, which will prompt the user to select an output folder. Take note that this code is identical to that used in our non-AppleScript Studio example.

set theOutputFolder to (choose folder with prompt "Select an output folder:") as string

Get the Selected Messages

Next, add the following code, which will retrieve a list of any selected email messages in Mail, and will then count the detected messages.

tell application "Mail"
   set theSelectedMessages to selection
end tell
set theMessageCount to count theSelectedMessages

Show the Progress Window

You may recall that we configured our progress window to not be visible on launch. The following code will now make this window visible to the user.

set visible of window "Progress Window" to true

Prepare the Progress Bar

We are now ready to begin preparing the progress bar within our window. First, we will set the maximum value property of the progress bar to the number of detected email messages.

set maximum value of progress indicator "Progress Bar" of window 
   "Progress Window" to theMessageCount

Next, in order to ensure that our progress bar will display incremental progress, we will set the indeterminate property of the progress bar to a value of false. A progress bar with an indeterminate property value of true will appear as a blue and white striped bar, as can be seen in figure 6, and this is not desirable for providing incremental progress.

set indeterminate of progress indicator "Progress Bar" of window 
   "Progress Window" to false

Looping Through the Selected Messages

We will now add code to loop through the selected email messages. Enter the following code into the script:

repeat with a from 1 to theMessageCount

end repeat

Updating the Progress Text

The following code should be added immediately within the repeat statement. It will update the text field in our interface to indicate the current message being processed. As in our non-AppleScript Studio example, this text will tell the user the current message count, as well as the total message count.

set contents of text field "Progress Text" of window "Progress Window" to 
   "Processing message " & a & " of " & theMessageCount

Getting the Current Message's Contents

Next, add the code below, which will retrieve the content of the current email message.

tell application "Mail"
      set theMessageContent to content of item a of theSelectedMessages
end tell

Saving the Contents to a File

Again, using the exact code from our non-AppleScript Studio example, add the following to your script. This code will write the content of the current message to a text file in the specified output folder.

set theArchivePath to theOutputFolder & "Archived Message " & a & ".txt" as string
set theArchiveFile to open for access theArchivePath with write permission
set eof of theArchiveFile to 0
write theMessageContent to theArchiveFile
close access theArchiveFile

Updating the Progress Bar

Finally, for the last section of code within the repeat loop, add the following code. This code will set the content of the progress bar to the current repeat loop increment, thus increasing the progress bar's display to accurately reflect the current number of messages processed.

set content of progress indicator "Progress Bar" of window "Progress Window" to a
update window "Progress Window"

Please note that the last line in the preceding code will update the window, ensuring that the progress bar's interface is refreshed each time its content value is changed.

Completing the Code

To complete the handler, add a quit command at the end of the handler, just outside of the repeat statement. This will ensure that the application quits, once processing is complete.

quit

Next, wrap all of the code within the handler inside of a try statement, configured as follows:

try

on error theErrorMessage number theErrorNumber
   if theErrorNumber = -128 then quit
   error theErrorMessage number theErrorNumber
end try

This try statement will trap for a user cancelled error, error number -128, which would occur if the user clicks the Cancel button when prompted to select an output folder.

Now that your script is complete, the following example code shows how the completed launched handler should appear within your main project script.

on launched theObject
   try
      set theOutputFolder to (choose folder with prompt "Select an 
         output folder:") as string
      tell application "Mail"
         set theSelectedMessages to selection
      end tell
      set theMessageCount to count theSelectedMessages
      set visible of window "Progress Window" to true
      set maximum value of progress indicator "Progress Bar" of window 
         "Progress Window" to theMessageCount
      set indeterminate of progress indicator "Progress Bar" of window 
         "Progress Window" to false
      repeat with a from 1 to theMessageCount
         set contents of text field "Progress Text" of window "Progress Window" 
            to "Processing message " & a & " of " & theMessageCount
         tell application "Mail"
            set theMessageContent to content of item a of theSelectedMessages
         end tell
         set theArchivePath to theOutputFolder & "Archived Message " & a & ".txt" as string
         set theArchiveFile to open for access theArchivePath with write permission
         set eof of theArchiveFile to 0
         write theMessageContent to theArchiveFile
         close access theArchiveFile
         set content of progress indicator "Progress Bar" of window "Progress Window" to a
         update window "Progress Window"
      end repeat
      quit
   on error theErrorMessage number theErrorNumber
      if theErrorNumber = -128 then quit
      error theErrorMessage number theErrorNumber
   end try
end launched

Testing the Project

Now that our project is complete, it is ready for testing. To test the project, first launch Mail, and select multiple email messages. For best results, you may want to select a large number of messages, in order to ensure that the progress bar will increment properly. Next, select Build and Run from the Build menu in Xcode. If everything works as expected, your solution should launch, and you should be prompted to select an output folder. After choosing a folder, the project's interface should be displayed, and the selected messages should be processed and saved into the specified output folder.


Figure 9. The Completed Progress Interface

Other Options

In AppleScript Studio, a progress indicator may be displayed as a bar, as we have seen. However, a progress indicator may also be displayed as a spinner. See figure 10.


Figure 10. Example of a Progress Spinner

A progress spinner may be useful in situations where your code does not warrant providing incremental feedback to the user, yet you still wish to indicate that processing is occurring.

In Closing

The project discussed in this month's column should give you some basic ways to implement progress feedback in your scripts. Now, it is up to you to begin making your scripts more user friendly by providing such feedback to your users.

If you have difficulty getting any of the specified code to work, or if you prefer to review the actual project files, you may wish to download the example code. I have made the sample project discussed in this article available for download from my web site at the following URL:

http://www.automatedworkflows.com/files/demos/MacTECH.01.06.Example.zip

Until next time, keep scripting!


Ben Waldie is author of the best selling books "AppleScripting the Finder" and the "Mac OS X Technology Guide to Automator", available from http://www.spiderworks.com. Ben is also president of Automated Workflows, LLC, a firm specializing in AppleScript and workflow automation consulting. For years, Ben has developed professional AppleScript-based solutions for businesses including Adobe, Apple, NASA, PC World, and TV Guide. For more information about Ben, please visit http://www.automatedworkflows.com, or email Ben at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Adobe Creative Cloud 2.2.0.129 - Access...
Adobe Creative Cloud costs $49.99/month (or less if you're a previous Creative Suite customer). Creative Suite 6 is still available for purchase (without a monthly plan) if you prefer. Introducing... Read more
Tower 2.2.3 - Version control with Git m...
Tower is a powerful Git client for OS X that makes using Git easy and more efficient. Users benefit from its elegant and comprehensive interface and a feature set that lets them enjoy the full power... Read more
Apple Java 2015-001 - For OS X 10.7, 10....
Apple Java for OS X 2015-001 installs the legacy Java 6 runtime for OS X 10.11 El Capitan, OS X 10.10 Yosemite, OS X 10.9 Mavericks, OS X 10.8 Mountain Lion, and OS X 10.7 Lion. This package is... Read more
Adobe Muse CC 2015 2015.0.1 - Design and...
Muse CC 2015 is available as part of Adobe Creative Cloud for as little as $14.99/month (or $9.99/month if you're a previous Muse customer). Muse CS6 is still available for purchase (without a... Read more
Adobe Illustrator CC 2015 19.1.0 - Profe...
Illustrator CC 2015 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous Illustrator customer). Illustrator CS6 is still available for... Read more
Corel Painter 14.1.0.1105 - Digital art...
Corel Painter helps you create astonishing art in a variety of media. Paint with vivid oil paints, fluid water colors, and earthy charcoals. Corel Painter flawlessly recreates the tones and textures... Read more
Pacifist 3.5.4 - Install individual file...
Pacifist opens up .pkg installer packages, .dmg disk images, .zip, .tar. tar.gz, .tar.bz2, .pax, and .xar archives and more, and lets you extract or install individual files out of them. This is... Read more
Merlin Project 3.1.0.40305 - Project man...
Merlin Project is for those of you who are responsible for complex projects. Simple lists of tasks won't suffice. Good planning raises questions about the dependencies of activities on each other,... Read more
DM1 2.0 - Advanced drum machine. (Commer...
DM1 is an advanced Drum Machine. It turns your computer into a fun and creative beat making machine. Easy and fast to use, loaded with 86 superb electronic drum kits and beautiful hyper-realistic... Read more
Posterino 3.2.1 - Create posters, collag...
Posterino offers enhanced customization and flexibility including a variety of new, stylish templates featuring grids of identical or odd-sized image boxes. You can customize the size and shape of... Read more

Mazes of Karradash (Games)
Mazes of Karradash 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: The city of Karradash is under attack: the monsters of the Shadow Realms are emerging from the depths.No adventurer is... | Read more »
Battle Golf is the Newest Game from the...
Wrassling was a pretty weird - and equally great - little wressling game. Now the developers, Folmer Kelly and Colin Lane, have turned their attention to a different sport: golfing. This is gonna be weird. [Read more] | Read more »
Qbert Rebooted has the App Store Going...
The weird little orange... whatever... is back, mostly thanks to that movie which shall remain nameless (you know the one). But anyway it's been "rebooted" and now you can play the fancy-looking Qbert Rebooted on iOS devices. [Read more] | Read more »
Giant Monsters Run Amok in The Sandbox...
So The Sandbox has just hit version number 1.99987 (seriously), and it's added a lot more stuff. Just like every other update, really. [Read more] | Read more »
Fish Pond Park (Games)
Fish Pond Park 1.0.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.0 (iTunes) Description: Nurture an idyllic slice of tourist's heaven into the top nature spot of the nation, furnishing it with a variety of... | Read more »
Look after Baby Buddy on your Apple Watc...
Parigami Gold is the new premium version of the match three puzzler that includes Apple Watch support and all new content. You won't simply be sliding tiles around on your wrist, the Apple Watch companion app is an all new mini-game in itself. You'... | Read more »
Swallow all of your opponents as the big...
Eat all of the opposition and become the largest ball in Battle of Balls now available in the App Store and Google Play. Battle of Balls pits you against other opponents in real time and challenges you to eat more balls and grow larger than all of... | Read more »
PAC-MAN Championship Edition DX (Games)
PAC-MAN Championship Edition DX 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: It’s Your World. EAT IT! Get ready for more ghost chain gobbling and frantic action in PAC-MAN® CE-DX! The... | Read more »
incurve (Games)
incurve 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: Get ready for 2 different gravities Goal is to hit as many white dots on your way up.When you're touching the screen, the dots have a... | Read more »
Crossy Road has its Own Merch Store Now....
Do you like Crossy Road? I mean do you really like Crossy Road? Well then you're in luck! Hipster Whale has opened up a Crossy Road store, so you can show off your fandom via official T-shirts. [Read more] | Read more »

Price Scanner via MacPrices.net

Apple restocks refurbished Mac minis for up t...
The Apple Store has restocked Apple Certified Refurbished 2014 Mac minis, with models available starting at $419. Apple’s one-year warranty is included with each mini, and shipping is free: - 1.4GHz... Read more
13-inch 2.5GHz MacBook Pro on sale for $899,...
Best Buy has the 13″ 2.5GHz MacBook Pro available for $899.99 on their online store. Choose free shipping or free instant local store pickup (if available). Their price is $200 off MSRP. Price is... Read more
21-inch 2.9GHz iMac on sale for $1299, save $...
Best Buy has the 21″ 2.9GHz iMac on sale today for $1299.99 on their online store. Choose free shipping or free local store pickup (if available). Their price is $200 off MSRP, and it’s the lowest... Read more
Free Image Sizer 1.3 for iOS Offers Photo Edi...
Xi’An, China based G-Power has announced the release of Image Sizer 1.3 for the iPhone, iPad, and iPod touch, an important update to their free photo editing app. Image Sizer’s collection of easy to... Read more
Sale! 13″ 1.6GHz/128GB MacBook Air for $899,...
B&H Photo has the 13″ 1.6GHz/128GB MacBook Air on sale for $899 including free shipping plus NY tax only. Their price is $100 off MSRP, and it’s the lowest price available for this model. Read more
13-inch Retina MacBook Pros on sale for $100...
Best Buy has 13-inch Retina MacBook Pros on sale for $100 off MSRP on their online store. Choose free shipping or free local store pickup (if available). Prices are for online orders only, in-store... Read more
Will BMW’s i3 Electric Vehicle Be The Automo...
The German-language business journal Manager Magazin’s Michael Freitag reports that Apple and the German performance/luxury automaker Bayerishe Motoren Werke (BMW) are back at far-reaching... Read more
Sale! $250 off 15-inch Retina MacBook Pro, $2...
B&H Photo has lowered their price for the 15″ 2.2GHz Retina MacBook Pro to $1749, or $250 off MSRP. Shipping is free, and B&H charges NY sales tax only. They have the 27″ 3.3GHz 5K iMac on... Read more
Global Smartphone Market Posts 11.6% Year-Ove...
According to the latest preliminary data released from the International Data Corporation (IDC) Worldwide Quarterly Mobile Phone Tracker, smartphone vendors shipped a total of 337.2 million units... Read more
15-inch and 13-inch Retina MacBook Pros on sa...
B&H Photo has 15″ & 13″ Retina MacBook Pros on sale for up to $180 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1819 save $180 - 15″ 2.... Read more

Jobs Board

*Apple* Customer Experience (ACE) Leader - A...
…management to deliver on business objectives Training partner store staff on Apple products, services, and merchandising guidelines Coaching partner store staff on Read more
Project Manager - *Apple* Pay Security - Ap...
**Job Summary** The Apple Pay Security team is seeking a highly organized, results-driven Project Manager to drive the development of Apple Pay Security. If you are Read more
*Apple* TV Product Design Internship (Spring...
…the mechanical design effort associated with creating world-class products with the Apple TV PD Group. Responsibilities will include working closely with manufacturing, Read more
*Apple* Watch SW Application Project Manager...
**Job Summary** The Apple Watch software team is looking for an Application Engineering Project Manager to work on new projects for Apple . The successful candidate Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.