TweetFollow Us on Twitter

AppleScript in Snow Leopard

Volume Number: 25
Issue Number: 10
Column Tag: AppleScript

AppleScript in Snow Leopard

by Ben Waldie

With the release of Snow Leopard, AppleScript developers will no doubt be in store for a few surprises. While the AppleScript language itself hasn't changed too much, a variety of other enhancements are welcome, but will take some getting used to.

Noticeable Changes

Script Editor

One of the first things you will notice is that Script Editor is no longer found in the /Applications/AppleScript folder on your Mac. Don't worry, though, it hasn't gone away. Apple has just moved it into a new, perhaps more appropriate, location - into the /Applications/Utilities folder. In addition, to help better clarify its purpose to those new to AppleScript, Script Editor has been renamed AppleScript Editor.

The example scripts that once resided alongside Script Editor are not gone either. They're still located in /Library/Scripts (an alias pointing to this folder was previously included in the /Applications/AppleScript folder). Now, you can quickly navigate to them from within AppleScript Editor, by selecting Open Example Scripts Folder from the Help menu.

AppleScript Editor has received a number of other enhancements, too, in addition to its new name. First, you may notice some changes in formatting when you compile your scripts. Command names, parameter names, classes, and more, which were previously grouped under a generic Application keywords category of formatting, now have their own formatting attributes. These attributes can be adjusted in AppleScript Editor's Preferences window, under Formatting.


Figure 1. Formatting Options in AppleScript Editor's Preferences Window

Another visual change is that the event log and result panes at the bottom of the script window have been merged into a single pane, labeled Event Log. Within this new, merged pane, you now have the option to view a list of events, events and replies (replies are more clearly indicated than in previous versions), or the result. See figure 2.


Figure 2. AppleScript Editor's Event Log, Displaying Both Events and Replies

The new event log pane also includes a number of other enhancements, which are sure to make it easier to both develop and troubleshoot your scripts. For advanced scripters, positioning the mouse cursor over an event in the log will now display a tool tip containing the raw Apple Event details for the event. Another very useful enhancement is that the event log now displays error messages, complete with both the error's description and number. This doesn't just occur when a showstopper error occurs either. It happens whenever any error is encountered, even if it's within a try statement. See figure 3 for an example of this.


Figure 3. Error Logging in AppleScript Editor's Event Log

Another useful enhancement for experienced scripters is the new "tell" application pop-up menu, which can be enabled in the Preferences window, under Editing. See figure 4.


Figure 4. Enabling AppleScript Editor's "tell" Menu

Once enabled, a new pop-up menu appears in the navigation bar above the script window's editing area (if this bar isn't visible, select Show Navigation Bar from the View menu). This pop-up menu may be used to set the target of the script to a specified application. For example, setting this pop-up menu to the Finder will instruct AppleScript Editor that all code within the script should be sent to the Finder application, thus eliminating the need to implicitly use a "tell" statement. This capability would be useful for running quick application terminology tests during development, or for testing scripts that will be run from within an application (which serves as the script's target). For example, a FileMaker developer might use this feature to write a script that will eventually run within a FileMaker database's Perform AppleScript script step. See figure 5.


Figure 5. Targeting the Finder with AppleScript Editor's "tell" Menu

Changing a script's target with the "tell" application pop-up menu will only affect the script's behavior when it is compiled and run within AppleScript Editor, or when run from within the target application. If you change a script's target and then save the script as a stand-alone application, you will receive an error when you attempt to run it, as the script application becomes the target of the script.

Another more advanced enhancement is the AppleScript Editor's ability to run scripts on background threads. This means that you can now run multiple opened scripts at once. For example, you could be testing a lengthy script, while editing and testing a smaller, second script at the same time. You can also force a script to run on the main thread by holding down the Control key and selecting Run in Foreground from the Script menu. This may be necessary if your script interacts with a scripting addition that's not thread-safe.

Finally, another change to AppleScript Editor is that there is no longer an option to save a "flat" script application. Rather, all applications are saved as bundles, and are, therefore, not compatible with systems prior to 10.3.

AppleScript Utility

In previous versions of Mac OS X, an AppleScript Utility application, located in the /Applications/AppleScript folder, provided a central location for managing various OS-level AppleScript settings. This application has been moved into the /System/Library/CoreServices folder, and now operates as a background application, in order to provide backward compatibility with older scripts. Settings previously found in the AppleScript Utility, such as enabling, disabling, and configuring the system-wide script menu, can now be found in AppleScript Editor's Preferences window, under General. See figure 6.


Figure 6. Script Menu and Other System-Wide Options in AppleScript Editor's Preferences Window

Folder Actions Setup

Another application that has been moved from /Applications/AppleScript to the /System/Library/CoreServices folder is Folder Actions Setup. This application, which allows you to enable and configure Folder Action scripts in Mac OS X, can now be launched by selecting Folder Actions Setup... from the Finder's contextual menu (see figure 7), or from the Finder > Services menu in the menu bar.


Figure 7. Launching Folder Actions Setup from the Finder's Contextual Menu

Folder Actions themselves have also received some upgrades. For one, they now support attaching Automator workflows directly to folders. Previously, a secondary AppleScript component was required to launch Automator workflows attached to folders. Another change, which I'm sure will prove a welcome enhancement for many, is that Folder Actions will now attempt to wait for an item to finish writing to the attached folder, before processing it. This is done by checking the size of the detected item until it remains static for at least three seconds. In the past, Folder Actions were notorious for triggering when an item first appeared in the folder, thus causing errors if the item was still being copied or saved.

Changes Under the Hood

Scripting Addition Calls

Snow Leopard introduces a number of other noticeable AppleScript changes. First, calls to scripting additions are now a bit finicky, and most will produce a privilege error when issued within an application "tell" statement. According to Apple, this is done for security purposes. Instead, scripting addition calls should be sent to the current application, i.e. the script itself or the process running the script.

To provide backward compatibility with older scripts, AppleScript automatically tries to capture this error, and redirect the problematic call to the current application. This is evident in figure 8's event log, where the do shell script call is first sent to the Finder, and then to the current application.


Figure 8. Redirected Scripting Addition Calls

For optimal results and to ensure future compatibility, however, developers should try to avoid including calls to scripting additions within application "tell" statements. For example, change:

tell application "Some App"
   do some scripting addition command
   do some application command
end tell
... to:
some scripting addition command
tell application "Some App"
   do some application command
end tell

Alternately, you can implicitly target the current application in your scripting addition call. For example:

tell application "Some App"
   tell current application to do some scripting addition command
   do some application command
end tell

Date Handling

Coercions from strings to dates are also a bit finicky in Snow Leopard. Previous versions of AppleScript were fairly forgiving when attempting to coerce a string to a date. For example, in Mac OS X 10.5, the following script ran successfully on my machine:

set theDate to "03, September, 2009"
date theDate
-> date "Thursday, September 3, 2009 12:00:00 AM"

In Snow Leopard, however, the same script fails with the following error message:

-> error "Invalid date and time date 03, September, 2009 of «script»." number -30720

To prevent these types of errors, Apple recommends ensuring that any string being coerced to a date match one of the system date formats found in System Preferences, under Language and Text (formerly International) > Formats. For example:

set theDate to "September 3, 2009"
date theDate
-> date "Thursday, September 3, 2009 12:00:00 AM"

Standard Additions Changes

Only a few minor changes have been made to the Standard Additions scripting addition. The do shell script command now provides better error reporting, and the say command includes some interesting new parameters for controlling the pitch, modulation, and rate of spoken text. So, you can now have your script sound more like Darth Vader, for example:

say "No, 'Luke'! 'I' 'am' your father!" using "Bruce" speaking rate 200 pitch 25 modulation 20

System Events Changes

The System Events background application has also received a few updates, such as providing access to screen savers. And, menu bar transparency is now accessible via scripting. For example:

tell application "System Events"
   set translucent menu bar of current desktop to false
end tell

Application Scripting Changes

As with any major system update, scripters should also be on the lookout for AppleScript terminology changes in updated Snow Leopard applications. As one example, QuickTime Player has received some fairly hefty enhancements in Snow Leopard. As a result, its AppleScript terminology has changed substantially too. Users with existing QuickTime scripts should take a careful look at this updated terminology, and make any necessary adjustments to their scripts.

AppleScript Studio Changes

Perhaps the most significant AppleScript change in Snow Leopard involves AppleScript Studio, which has officially been deprecated. Yep, you read that correct, deprecated, as in obsolete and discontinued.

AppleScript Studio was a subset of features in Apple's Xcode development environment, which allowed scripters to build AppleScript-based applications, complete with Cocoa interfaces (created in Interface Builder).

For those scripters who have created countless AppleScript Studio applications, don't freak out just yet. First, Apple says that AppleScript Studio is still supported in Snow Leopard, and existing applications should continue to function. You should also be able to continue opening your existing AppleScript Studio projects and editing them in Xcode.

You will not, however, be able to create new AppleScript Studio projects in Xcode, as the templates for doing so have been removed. In addition, the handy AppleScript palette you're used to seeing in Interface Builder is now hidden by default. You can re-enable it, however, by running the following command in Terminal:

defaults write com.apple.InterfaceBuilder3 IBEnableAppleScriptStudioSupport -bool YES

Another option may be to install a second, older version of Xcode, alongside Snow Leopard's Xcode, thus allowing you to continue developing new AppleScript Studio applications. Installing multiple versions of Xcode was supported in the past, though I have yet to test it for myself in Snow Leopard, and I can't say whether it will continue to be supported in the future.

Regardless, there will come a day when AppleScript Studio is no longer supported. So, developers should start thinking about this now, and begin creating new applications and migrating existing ones to AppleScript Studio's successor - AppleScriptObjC - as soon as possible. AppleScriptObjC is a new framework in Mac OS X, which provides a bridge between AppleScript and the Objective-C runtime, thus allowing AppleScript to interact with any Cocoa framework.

For scripters without a background in Cocoa and Objective-C, AppleScriptObjC will take some time to master. However, there are some resources that can help get you started. For one, Xcode includes a new project template, named Cocoa-AppleScript Application. See figure 9. There's a Cocoa-AppleScript Automator action template too, for those Automator developers.


Figure 9. Creating a Cocoa-AppleScript Application in Xcode

You can also browse the Mac OS X reference library for Snow Leopard, which, at the time I wrote this column, included some preliminary AppleScriptObjC release notes, as well as a brief, though informative, Objective-C/AppleScript Quick Translation Guide. If you're new to Objective-C and Cocoa, I'd also recommend checking out the Cocoa Fundamentals Guide and the Introduction to The Objective-C 2.0 Programming Language. All of these documents are available on the Apple Developer Connection website at http://developer.apple.com.

In Closing

Overall, the AppleScript changes in Snow Leopard come as welcome improvements. That said, some changes are likely to cause compatibility issues with existing scripts. As with any Mac OS X update, AppleScript developers should take the time to test existing scripts thoroughly, and make any necessary changes to ensure compatibility.

AppleScriptObjC will likely require a bit more time and effort to upgrade existing scripts, and there will be a learning curve. That said, scripters adopted AppleScript Studio fairly quickly when it was first introduced, and I have no doubt that they will do the same for AppleScriptObjC. Once the migration is complete, however, the power and reach of AppleScript will be greater than ever before.

Until next time, keep scripting!


Ben Waldie (ben@automatedworkflows.com) is president of Automated Workflows, LLC (www.automatedworkflows.com), a company offering AppleScript, Automator, and workflow consulting services to Mac-based businesses. For years, Ben has developed professional automated solutions for companies such as Abercrombie & Fitch, Adobe Systems, Apple Inc., CNN, Microsoft, NASA, PC World, and Time Magazine. Ben is the author of "Automator for Mac OS X 10.5 Leopard Visual QuickStart Guide" (Peachpit Press) and "AppleScripting the Finder", has written AppleScript and Automator content for Apple.com, Macworld, MacTech, MacScripter.net, and X-Ray Magazine, and is the host of the "Mac Automation Made Simple" video podcast (Peachpit Press). Ben has also released hundreds of Automator actions for use with Adobe Illustrator, InDesign, Photoshop, FileMaker, QuarkXPress, Twitter, and more.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

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

Price Scanner via MacPrices.net

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

Jobs Board

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