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

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.