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

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

Price Scanner via MacPrices.net

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

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.