TweetFollow Us on Twitter

Introduction To AppleScript Studio

Volume Number: 21 (2005)
Issue Number: 4
Column Tag: Programming

AppleScript Essentials

by Benjamin S. Waldie

Introduction To AppleScript Studio

In past articles, we have discussed many AppleScript-related topics. However, one of the topics that we have yet to touch on is AppleScript Studio, which is quickly becoming the tool of choice for AppleScript developers.

What Is AppleScript Studio

AppleScript Studio, contrary to what some of you may think, is not an application itself. Rather, it is the AppleScript development environment that is part of the Mac OS X developer tools.


Figure 1. The Interface Builder and Xcode Applications

The two main developer tools that AppleScript developers need to be concerned with in order to get started with AppleScript Studio are Interface Builder and Xcode. If you don't have these applications on your machine, you need to install the Mac OS X developer tools, which you should have gotten along with your Mac OS X system software.

Interface Builder, as the name implies, is what you may use to build interfaces for your scripts. Your interfaces may range from the very simple, to the extremely complex, depending on your programming skill, and the requirements of the task you want to automate. When building an interface in Interface Builder, you will have access to most of the standard interface elements that you see in Mac OS X, allowing you to design your interface with the look and feel of a regular application.

Xcode is the application in which you will write your AppleScript code, and link it to the objects in your interface. Xcode is not for the faint of heart. It is a real, live, professional development environment, and it has a learning curve. However, during this article, we will get started with some basics by creating a very simple AppleScript Studio application. Then, I'll make some suggestions for next steps in the learning process, and in future articles, we'll return to AppleScript Studio to discuss additional topics.

Building a Simple AppleScript Studio Application

For this initial project, we are going to build a fairly basic AppleScript Studio application, complete with an interface. This particular script will be used to select a random number that falls between two user-specified numbers.

Step 1 - Prepare Your Project

First, launch the Xcode application. Depending on whether or not you have launched Xcode before, you may see an initial dialog. Go ahead and dismiss any dialogs that may appear. Next, select New Project from the File menu, and you will be presented with a list of templates from which to choose. In the list, under Application, you will notice that there are a few types of templates with the word AppleScript in the name. In order to develop an AppleScript Studio application, you will want to select one of these. For this initial project, select AppleScript Application, and click the Next button.

The next interface will allow you to specify a name for your project, as well as a location. Enter the name Number Picker, specify a location, and click the Next button. At this time, Xcode will create your project in the specified location, and open the project in an interface window. Depending on the way your Xcode application has been configured, your window may look similar to figure 2.


Figure 2. An Xcode Project Window

An Xcode project contains a variety of components. However, at this initial stage, we are only going to be concerned about the following two:

    Number Picker.applescript - This file, located under the Scripts folder in your project, is your main AppleScript file. Here, you will write the AppleScript code we will be linking to your interface.

    MainMenu.nib - This file, located under the Resources folder in your project, is your interface file. This is where you will design your interface.

Step 2 - Design Your Interface

For this particular project, the next thing we are going to do is build our interface. To begin editing the project's interface, double click on the MainMenu.nib file in Xcode. This should automatically launch Interface Builder, and load the interface. If all goes well, you should see a MainMenu.nib window in Interface Builder, as well as a blank window titled Window. Click on the blank window.

Depending on the way your Interface Builder application is configured, you may or may not see an Info palette. To make this window visible, select Show Info from the Tools menu in the menu bar. If not already selected, choose Attributes from the popup menu at the top of the Info palette. Enter the text Number Picker into the Window Title field in the Info palette.


Figure 3. The Info Palette

Now, it is time to begin adding some interface elements to the window. Depending on the way your Interface Builder application is configured, you may or may not see a palette of interface elements. If this palette is not visible, you can make it visible by selecting Show Palettes from the Tools > Show Palettes menu in the menu bar.


Figure 4. The Interface Builder Object Palette

If you have never worked with Interface Builder before, you may want to browse through the various interface elements under each toolbar button in this palette. This should give you some idea of the types of interfaces you will be able to build in the future.

    NOTE: Holding your mouse over a toolbar button in the interface elements palette will display a tool tip identifying the category of objects associated with the button. Likewise, holding your mouse over an interface object in the palette will display its name.

For this interface, we're going to add only a few basic elements to our Number Picker window. We'll start by adding two text fields. To do this, click on the Cocoa Text Controls button, and select and drag the NSTextField object from the upper left of the palette into your window. Do this again, and you should have two text fields on your window.


Figure 5. Text Fields Added to an Interface Window

Next, select the NSTextField object labeled System Font Text, located in the lower right of the palette, and drag it twice into your window. Double click on each of these text fields that you have added to your window, and set their text to Starting Number and Ending Number.

Select the Cocoa Controls and Indicators button in the toolbar of the interface elements palette, select the NSButton object in the upper left corner of the palette, and drag it into your window. Double click on the button that has been added to the window, and change its name to Pick.

At this point, you may drag the various elements around the window until they are in the desired location. Notice as you drag elements around the window, that Interface Builder will display dashed lines suggesting proper placement of the objects, in relationship to other objects on the window. Try to arrange your interface similar to the one displayed in figure 6.


Figure 6. Interface Window Design

Step 3 - Add AppleScript Names to Inte face Objects

In order for the AppleScript code we are about to write to interact with the objects in our interface, we will first need to assign names to these objects. Sure, we could interact with objects by their index reference, such as text field 1 of window 1. However, when you start getting lots of interface elements, it becomes difficult to keep track of which objects are which. To assign a name to an object, first, select the object. Next, select AppleScript from the popup menu in the Info palette. You may then enter the desired name for the object into the Name field in the Info palette. For our interface, assign the name Main Window to the window. Next, assign the names Starting Number and Ending Number to the two empty text fields. Finally, assign the name Pick Number to the button in the window.

Step 4 - Link Interface Objects to AppleScript Code

Since we would like AppleScript code to trigger when we click the Pick button in our interface, we now need to link the button to our script. To do this, select the Pick button in the interface. Next, select AppleScript from the popup menu in the Info palette. You may have noticed already that when you have selected AppleScript from this popup menu, various event handlers appear below the Name field in the Info palette. These event handlers are actions that may be configured to cause the corresponding object to trigger specific AppleScript code. For example, for a button, the clicked event handler would cause the button to trigger AppleScript code whenever it is clicked by a user. Select the checkbox next to the clicked option.

Once you have selected the clicked event handler, you need to specify which AppleScript file to which the event handler will link. In this case, we only have one AppleScript file. However, for complex projects, we may have multiple files from which to choose. To specify our AppleScript file, select the checkbox next to Number Picker.applescript under Script at the bottom of the Info palette.


Figure 7. The Properly Configured Info Window for the Pick Button

Step 5 - Adding AppleScript Code

Now that we have created our interface, and linked the interface elements to our AppleScript file, it is time to begin editing our AppleScript code. Since we have configured our interface to trigger code when a user clicks the Pick button, we are going to edit the code that will trigger when this action occurs. To get started, ensure that the Pick button is still selected, and click the Edit Script button at the bottom of the Info palette. This should bring Xcode back to the front, and display the Number Picker.applescript script. You should notice that the script already contains some initial AppleScript code.

The first thing that we need to do is get the values entered by the user into the Starting Number and Ending Number fields in our interface. Next, we are going to want to select a number in between those two numbers.

tell window "Main Window"
   set theStartingNumber to contents of text field "Starting Number"
   set theEndingNumber to contents of text field "Ending Number"
   set theNumberList to {}
   repeat with i from theStartingNumber to theEndingNumber
      set end of theNumberList to i
   end repeat
   display dialog "And the number is... " & some item of theNumberList
end tell

Add the above code to the on clicked theObject event handler in your script.


Figure 8. AppleScript Code in the Xcode Script

Step 6 - Building and Testing the Project

Now that we have added our AppleScript code, it's time to build and test our project. To do this, click the Build and Go button in the toolbar of your Xcode window. If all goes well, your application should build and launch. Test the application by entering a starting number and an ending number, and then click the Pick button.


Figure 9. Our Completed Application

Step 7 - Expand Your Application

Obviously, the example application we created during this article is very simple, to say the least. In a real-world solution, you would want to add much more functionality. For example, we did not add any kind of protection to ensure that a user actually enters a number into the Starting Number and Ending Number text fields. Right now, a user could enter text, and the solution would produce an error.

There are many other things you could do to make this solution more robust, and I encourage you to explore ways that you can expand and enhance it. I also invite you to download an application that I created and released as a freeware tool. My application, titled Ticket Picker, was the basis for this exercise. I created the application to distribute to Macintosh User Groups for use during raffles and drawings. You can download the application from the Freeware Products section of my website at http://www.automatedworkflows.com.

Next Steps

So, where do you go from here? Well, as I mentioned before, AppleScript Studio has a lot to learn. However, there are some good resources that can help you in your journey. For one, when you install the Mac OS X developer tools, Apple provides numerous AppleScript Studio examples. These examples are completely unlocked and fully editable, and I encourage you to explore them. They can be found in the Developer > Examples > AppleScript Studio folder. Additional example scripts can be found on the AppleScript website at http://www.apple.com/applescript/studio/.

Another good way to learn about AppleScript Studio is to look over the extensive documentation provided by Apple. For the most up to date documentation, visit http://developer.apple.com/documentation/AppleScript/.

I've said it before, and I'll say it again. One of the best resources for learning about AppleScript is the growing community of developers. If you are interested in learning AppleScript Studio, you should consider joining the AppleScript Studio Mailing List, hosted by Apple at http://lists.apple.com/mailman/listinfo/applescript-studio. The thousands of developers who currently subscribe to this list will no doubt be a valuable resource as you get started.

In Closing

As the title of this article indicates, this article is by no means meant to serve as a comprehensive tutorial on AppleScript Studio. It is simply meant to serve as an introduction, and to show how it is not too complicated to begin putting together your own applications with interfaces. Of course, creating more complex applications in AppleScript Studio requires some hard work and dedication. However, with a little practice, you will be on your way in no time. In future articles, we'll delve deeper into the AppleScript Studio world, and explore some more exciting things that you can do.

Until next time, keep scripting!


Benjamin Waldie is president of Automated Workflows, LLC, a firm specializing in AppleScript and workflow automation consulting. In addition to his role as a consultant, Benjamin is an evangelist of AppleScript, and can frequently be seen presenting at Macintosh User Groups, Seybold Seminars, and MacWorld. For additional information about Benjamin, please visit http://www.automatedworkflows.com, or email Benjamin at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more
Hopper Disassembler 5.14.1 - Binary disa...
Hopper Disassembler is a binary disassembler, decompiler, and debugger for 32- and 64-bit executables. It will let you disassemble any binary you want, and provide you all the information about its... Read more

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill WellSpan Medical Group, York, PA | Nursing | Nursing Support | FTE: 1 | Regular | Tracking Code: 200555 Apply Now Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.