TweetFollow Us on Twitter

Building a Table View Project in AppleScript Studio

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

AppleScript Essentials

Building a Table View Project in AppleScript Studio

by Benjamin S. Waldie

Back in my April column, I provided an introduction to AppleScript Studio, a technology that is a part of Xcode and Interface Builder, Mac OS X's powerful integrated development environment. Using AppleScript Studio, AppleScript developers are able to create fully native Mac OS X applications, complete with user interfaces. By constructing scripts with interfaces, developers can build complex and powerful user friendly AppleScript solutions that have the same look and feel of any other Mac OS X application.

In addition to building stand-alone AppleScript solutions, AppleScript Studio can also now be used to create Automator actions, for use with Mac OS X 10.4's popular new Automator application. In my August column, I walked through the process of building of a simple AppleScript Studio-based Automator action.

This month, we will create a new AppleScript Studio-based project that is a little more complex, and incorporates a table view into its interface. This application, which I call Enable|Disable Mail Accounts, will display a list of email accounts in Mail to the user, and allow the user to toggle whether the accounts are enabled or disabled.

Table Overview

Before we get started, I would like to briefly discuss the concept of tables. In AppleScript Studio, a table, which is actually referred to as the class table view, may be used to display a list of records, complete with field values, similar to what you might see in a spreadsheet. See figure 1.


Figure 1. An Example of a Table View

While a table view can be placed onto an interface window, or any type of view class for that matter, within AppleScript Studio's class hierarchy, a table view is actually not a direct element of the window itself. Rather, it is an element of a scroll view, which typically is an element of the window. Because of this, when referring to a table, you must do so within its parent scroll view. For example:

table 1 of scroll view 1 of window 1

Much like a spreadsheet, a table view may be configured to display multiple rows of data, in one or more columns. When populating or manipulating the contents of a table view, the preferred and suggested method of doing so is through the use of what is known as a data source. A data source is essentially equivalent to a virtual database within your AppleScript Studio project, complete with records and fields that can hold the values for your table. A data source, which can be created up front in your project, or dynamically through AppleScript code, may be linked to a table view. Once linked, the table view's visual contents on the window will automatically reflect the contents of the data source. So, in other words, as you make changes to the contents of the data source, those changes will automatically translate directly to the linked table view.

There are other ways to populate and manipulate data within a table view, without creating or interacting with a data source. I won't be covering those methods in this month's column, but I want you to be aware that there are multiple ways of accomplishing the same goal when working with table views. However, as I said before, using data sources is the preferred method of populating a table view, as it is typically the most efficient and has some benefits that other methods do not. For example, when using a data source, it is possible to suspend updating of the table view during modification of the data source. This updating can then be re-enabled once the data source is finished being modified, thus allowing the table view's display to update all at once.

Working with table views, scroll views, and data sources can seem complex at first. As we proceed through the remainder of this month's column, hopefully, these classes will begin to make more sense to you. However, for more detailed overviews of these classes, you may want to consult the AppleScript Studio Terminology Reference, which is included with Xcode's documentation, and can also be found in the ADC Reference Library on the Apple Developer Connection website at http://developer.apple.com/.

Now, let's get started on our project.

Building the Project

The first step in building our project is to create a new AppleScript Studio project. As always, begin by launching Xcode. Please note that, for this column, my project was developed using Mac OS X 10.4.2 and Xcode 2.1. That said, the code included in this column may or may not function in older versions of the OS and Xcode. However, 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.

In Xcode, create a new project, by selecting New Project... from the File menu. When prompted, select a project type of AppleScript Application from the list of available project templates, specify a project name of Enable|Disable Mail Accounts, and specify an output folder for the project. Xcode will duplicate the AppleScript Application project template into the specified output folder, and open it before you. See figure 2.


Figure 2. Enable|Disable Mail Accounts Project Window

Building the Interface

The next step in the creation of our AppleScript Studio project will be to design the interface. To do this, 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 Enable|Disable Mail Accounts into the Window Title field in the Inspector palette. See figure 3. If the Inspector palette is not visible, simply select Show Inspector from the Tools menu in Interface Builder.


Figure 3. Assigning a Window Title

While the window is still selected, also de-select the Visible at Launch Time checkbox, if it is selected. This will cause the window to be hidden when the project is first launched. This means that, later, we will need to add code to display the hidden window. The reason we want it to be hidden initially is so that we can populate a table view with data, prior to displaying the window.

Next, click on the Cocoa Data Views 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 NSTableView interface element in the Palettes window, and drag it into your project's window. See figure 4.


Figure 4. Adding an NSTableView

Using the Inspector palette, configure the scroll view to contain two columns. Next, double click on the scroll view to select the table view element. Finish preparing the table view by clicking on each column within the table view, and entering header titles of Account Name and Status for the column headers. See figure 5 for an example of how the table view should appear, once it has been configured with two columns, complete with column headers.


Figure 5. Assigning Table View Column Header Titles

Next, click on the Cocoa Controls and Indicators button in the toolbar of the Palette window, and drag two buttons into your interface window. Enter Quit and Toggle as the titles for these buttons in the Inspector palette.

Arrange the interface elements in the window, and make any necessary adjustments until the window resembles the example shown in figure 6.


Figure 6. The Complete Solution Interface

As you design an interface, always try 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.

Preparing the Interface for AppleScript Interaction

Once you have finished designing the interface, the elements that make up the interface must be prepared for the AppleScript code within your project to interact with them. This task will consist of assigning AppleScript names to various interface elements, as well as configuring 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 Main Window into the Name field. See figure 7. The process of assigning AppleScript names to other interface elements will be the same.


Figure 7. Assigning an AppleScript Name to the Main Window

Next, select the Quit and Toggle buttons that were placed on your window, and assign AppleScript names of Quit and Toggle to these buttons, respectively. For each of these buttons, we will also assign an event handler. A listing of the event handlers to which an interface element can respond are located on the Inspector palette, beneath the Name field. For these two buttons, enable the clicked event handler by selecting the appropriate checkbox. You will then need to link the event handler to the AppleScript file within your project code. So, select the checkbox next to Enable|Disable Mail Accounts.applescript, in the Script area at the bottom of the Inspector palette, beneath the event handler list. See figure 8 for an example of a properly configured button.


Figure 8. Configuring a Button

Select the scroll view in the window, and assign an AppleScript name of Account List to the scroll view. Next, double click on the scroll view to select the enclosed table view. In the Inspector palette again, assign an AppleScript name of Account List to the table view. Also, enable the Awake from Nib event handler for the table view, and link it to the AppleScript in your project. See figure 9.


Figure 9. Configuring the Table View

With the table view still selected, click on each of the Account Name and Status column headers, and assign AppleScript names of Account Names and Status to each of these headers, respectively, using the Inspector palette. No event handler assignments are necessary for these elements.

Finally, as a last step in configuring the interface, select File's Owner in the MainMenu.nib window, enable the launched event handler, and link it to the AppleScript in your project, using the Inspector palette. See figure 10.


Figure 10. Enabling the Launched Event Handler for the Solution

Adding the AppleScript code

Now that you have configured your interface, return to Xcode again, as it is time to begin adding the AppleScript code into your project. Double click on the Enable|Disable Mail Accounts.applescript file in your project to begin editing the AppleScript code.

Building the Data Source

The first AppleScript code that we will add to the project will be code that creates a data source, which will later be populated to update our table view's contents. We want this code to be triggered automatically, prior to actually displaying the interface. Therefore, to do this, we will make use of the awake from nib handler, which will be triggered by the project when the interface is first loaded.

Type the following code into your project:

on awake from nib theObject
   set theDataSource to make new data source at end of data sources with properties 
      {name:"Account Data"}
   tell theDataSource
      make new data column at end of data columns with properties {name:"Account Name"}
      make new data column at end of data columns with properties {name:"Account Status"}
   end tell
   set data source of theObject to theDataSource
end awake from nib

The first line of code within this handler will create a new data source, named Account Data. The next few lines will create columns for the account name and status within this data source, to match our table view configuration.

In our interface, we configured our table view with an awake from nib event handler. Therefore, when this handler is triggered, a reference to the table view will be passed to the handler in the parameter named theObject. The final line of code within the handler will set the data source property of the table view to the newly created data source, thus linking the table to the data source. Once linked, any changes we make to the contents of the data source will be reflected in the table view.

Refreshing the Table

The next code we will add to our project is a custom handler, which I have named refreshAccountListing. This handler will be called by other code within our project, as you will see shortly. The responsibility of this code will be to populate the contents of the data source that will be built with the previous code we discussed.

Type the following code into your project:

on refreshAccountListing()
   tell application "Mail"
      set theAccountNameList to name of every account
      set theAccountStatusList to enabled of every account
   end tell
   tell data source "Account Data"
      set update views to false
      delete every data row
      repeat with a from 1 to length of theAccountNameList
         set theRow to make new data row at end of data rows
         tell theRow
            set contents of data cell "Account Name" to item a of theAccountNameList
            if item a of theAccountStatusList = true then
               set theAccountStatus to "Enabled"
            else
               set theAccountStatus to "Disabled"
            end if
            set contents of data cell "Account Status" to theAccountStatus
         end tell
      end repeat
      set update views to true
   end tell
end refreshAccountListing

This handler will first retrieve the names and statuses of any email accounts in Mail. Next, the handler will tell the data source to set its update views property to a value of false. This will actually cause the table view to cease updating temporarily, while the data source is being modified.

Next, the handler proceeds to delete any existing data rows from the data source. Within a data source, a data row represents a single row of data within the table. A data row contains data cells, which are essentially fields to hold the data, which translate to the columns within a table view. The reason we want to delete the data rows within the data source first is because we will trigger this handler any time we want to refresh the contents of the data source. Before doing this, we need to delete any existing rows that may have been previously created, so that the data source is completely refreshed, and new data is simply not appended to existing data.

After deleting any existing data rows, the handler will then loop through the retrieved email account names, and create a new data row for each, inserting the account name and its corresponding status into the appropriate data cells for each row.

Finally, the update views property of the data source is set to a value of true, allowing the table view to update to reflect the new contents of the data source.

Initializing the Table

Next, we are going to add the code that will initially trigger the refreshAccountListing handler to populate the data source. Once populated, this code will also make the main window visible to the user.

Type the following code into your project:

on launched theObject
   refreshAccountListing()
   set visible of window "Main Window" to true
end launched

This launched handler will be triggered automatically when the project is run, immediately following the successful execution of the awake from nib handler.

Toggling the Email Account Status

Next, we need to add code to actually toggle the status of any selected email accounts in the table view. To do this, type the following code into your project:

on toggleAccounts()
   set theSelectedRows to selected data rows of table view "Account List" of 
      scroll view "Account List" of window "Main Window"
   repeat with a from 1 to length of theSelectedRows
      set theRow to item a of theSelectedRows
      tell theRow
         set theAccountName to contents of data cell "Account Name"
         set theAccountStatus to contents of data cell "Account Status"
         if theAccountStatus = "Enabled" then
            set theNewAccountStatus to false
         else
            set theNewAccountStatus to true
         end if
         tell application "Mail"
            set enabled of account theAccountName to theNewAccountStatus
         end tell
      end tell
   end repeat
   refreshAccountListing()
end toggleAccounts

This handler will be triggered when the user clicks the Toggle button in the interface. It will retrieve a listing of any selected accounts in the table view, toggle the status of those accounts in Mail, and then trigger the refreshAccountListing handler to update the table view to reflect the newly modified account statuses.

Adding Button Code

Finally, we need to add code to perform the appropriate task when a button in the project's interface is clicked. To do this, type the following code into your project:

on clicked theObject
   if name of theObject = "Toggle" then
      toggleAccounts()
   else
      quit
   end if
end clicked

If you recall, we applied a clicked event handler to each of the buttons in our interface. Therefore, this handler will be triggered whenever the user clicks one of those buttons. This handler will check the name of the button that was clicked. If it was the Toggle button, then the handler will trigger the toggleAccounts handler. If not, it assumes that the user clicked the Quit button, and it simply quits the application entirely.

Testing the Project

Now that our project is complete, it is ready for testing. To test the project, select Build and Run from the Build menu in Xcode. If everything works as expected, your solution should launch, and the interface should be displayed, complete with a table view showing your Mail account names, along with their statuses. See figure 11.


Figure 11. The Completed Application

Select one or more accounts in the table view, and click the Toggle button to verify that the account statuses are toggled in Mail, and the project properly functions.

In Closing

AppleScript Studio provides many possibilities for creating interfaces. As you can see from this relatively simple interface, with the use of table views, you can construct interfaces for your AppleScript Studio projects that will display information to the user in rows and columns, and even allow a user to make selections from this data.

For example, a table view might list file names, email addresses, database fields, etc. The possibilities are virtually limitless. What's more, you can even extend the functionality of table views further by adding embedded buttons, checkboxes, and more to the columns within the table view. See figure 12 for an example of this. Using this type of technique, we could update the Enable|Disable Mail Accounts project to allow a user to toggle email account statuses by making selections from individual popup menus, rather than clicking a Toggle button.


Figure 12. An Example of Embedded Interface Elements within a Table View

Please note that 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.12.05.Example.zip

I encourage you to continue exploring table views on your own, and expanding the sample project discussed in this month's column to include even greater functionality.

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

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.