TweetFollow Us on Twitter

Studio 54

Volume Number: 19 (2003)
Issue Number: 7
Column Tag: QuickTime

QuickTime Toolkit

Studio 54

by Tom Monroe

Developing QuickTime Applications with AppleScript Studio


In the previous QuickTime Toolkit article, we started building a QuickTime-savvy application using AppleScript Studio. In this article we'll finish up.

Setting Up the Menus

Let's turn to ScripTeez' menus. The Application menu is the easiest to configure, since we simply need to change the name of the application to "ScripTeez" in four instances, as shown in Figure 13. I've also set the keyboard shortcut for the "Hide Others" item to be Command-Option-H, as dictated by the Aqua Human Interface Guidelines.

Figure 13: The Application menu nib

In the Edit menu, we need to remove the items that don't apply to movies (the Find and Spelling menu items) and add the "Select None" item, as shown in Figure 14.

Figure 14: The Edit menu nib

All these items are handled automatically by Cocoa (and in particular, by the NSMovieView instance in our movie window), except for the one we just added. In this case, we need to attach an AppleScript event handler. As before, select the "AppleScript" panel in the Info window and then check the "choose menu item" and "update menu item" handlers, as in Figure 15. Skeletal handlers are automatically added to the specified script file (that is, ScripTeez.applescript); we'll add code to those handlers later.

Figure 15: The Select None menu event handlers

Let's add one more menu to ScripTeez, a Movie menu that allows us to select a looping mode for the movie in the movie window. Figure 16 shows the updated main menu nib.

Figure 16: The Movie menu nib

As you'd guess, we need to attach AppleScript handlers to adjust and handle these menu items. Figure 17 shows the Info window for the third item in the Movie menu, the "Palindrome Looping" item. Notice that the name of the item is "palindromeLooping".

Figure 17: The Palindrome Looping menu event handlers

Adjusting the Project Settings

Before we launch into writing code to handle these events, we need to make a couple of final adjustments to our project. We need to add the QuickTime framework to the project, and we need to specify the kinds of files that our application can open.

To add the QuickTime framework, simply select "Add Frameworks..." in Project Builder's Project menu and then choose the file "QuickTime.framework". It will be added to the list of linked frameworks.

To specify the kinds of files our application can open and hence what kinds of files should be selectable in the file-opening dialog box (displayed at application launch time), select the "Edit Active Target" item in the Project menu. Click the "Document Types" item on the left-hand side and add the desired document types. Figure 18 shows our document types settings. We want ScripTeez to be able to open QuickTime movie files and Flash files.

Figure 18: The openable file types

AppleScript Studio Movie Classes

Now it's time to write some code to load a movie from a movie file and to handle the menu items we've added to the default menu bar. Recall that the only thing we added to the default empty application window was a view of type NSMovieView, which we named "movieView". This name allows us to target AppleScript actions at that movie view. For instance, in the awake-from-nib handler, we might set a local variable theMovieView to point to that view like this:

set theMovieView to the movie view "movieView" of theObject

(Recall that the awake-from-nib handler is passed the object that's being awakened; in this case, it's the movie window.)

But what vocabulary can we use to manipulate the movie view? To find this out, we can double-click the item labeled "AppleScriptKit.asdictionary" in the project window (see Figure 4 again). Expand the item labeled "Control View Suite" in the left-hand column, and then expand the Classes item. We'll see a couple dozen view types, including "movie view". If we click on "movie view", we'll see the list of properties shown in Figure 19.

Figure 19: The movie view properties

This list shows us the built-in properties of movie views currently supported by AppleScript Studio. For instance, we can get and set the movie volume, the looping state, and the playback rate. We can get (but not set) the movie controller identifier. We can also get and set the movie associated with the movie view. So, we might set the movie to palindrome looping like this:

set the loop mode of theMovieView to -
                              looping back and forth playback

(The character "-"is AppleScript's line continuation character; we can insert it into a script by typing Option-L; this allows very long statements to occupy several lines in our script files.)

Loading a Movie from a File

ScripTeez, you'll recall, supports only one movie window. We'll display the standard file-opening dialog box at application launch time, to elicit a movie file from the user. We can display that dialog box and get the full pathname of the selected file with this simple command:

set theMoviePath to choose file

Then we can assign the movie in that file to the movie view like this:

set the movie of theMovieView to load movie theMoviePath

Setting the Size of a Movie Window

If you look back at Figure 7, you'll see that the "Visible at launch time" check box in the list of movie window attributes is unselected; this is because we don't want the movie window to be visible while the file-opening dialog is displayed. It's also because, before we display the movie window to the user, we want to adjust the size of the movie window to exactly contain the movie at its natural size and the 20-pixel border on all sides of the movie view.

The only problem is that AppleScript Studio does not (as far as I can determine) include any built-in method for getting the natural size of a movie. The movie rect property returns the current size of the movie rectangle, which will just be the size of the movie view as contained in the nib file once we've assigned the movie to the movie view. Fortunately, AppleScript Studio supports an easy way to call code written in other languages, using the call method command. In ScripTeez, we'll need to use this command twice, first to get the natural size of a movie and second to handle the "Select None" menu item.

Let's look at the menu-handling task first, since it's somewhat simpler than the movie-sizing task. When the user chooses the "Select None" menu item, we'll execute this line of script:

call method "selectNone:" with parameter theMovieView

This call method command tells AppleScript Studio to look for an Objective-C method named "selectNone:" and to call it, passing as its single argument the value of the variable theMovieView.

When we issue the call method command, we can specify the class whose method is to be called. For simplicity, however, we'll implement the selectNone: method (and the movieWindowContentRect: method, which we'll encounter in a moment) as categories on the NSApplication class.

To begin, let's add two new files to the ScripTeez project; let's call them ScrTzMethods.m and ScrTzMethods.h. Listing 10 shows the file ScrTzMethods.h.

Listing 10: Declaring a category on NSApplication


@interface NSApplication (ScrTzMethods)

- (NSRect)movieWindowContentRect:(NSMovieView *)movieView;
- (void)selectNone:(NSMovieView *)movieView;


The file ScrTzMethods.m contains the actual implementation of the ScrTzMethods category. Listing 11 shows our definition of the selectNone: method.

Listing 11: Selecting none of a movie


- (void)selectNone:(NSMovieView *)movieView
   MovieController mc = NULL;
   TimeRecord tr;
   mc = (MovieController)[movieView movieController];
   if (mc != NULL) {
      tr.value.hi = 0;
      tr.value.lo = 0;   
      tr.base = 0;
      tr.scale = GetMovieTimeScale(
                                       [[movieView movie] QTMovie]);   
      MCDoAction(mc, mcActionSetSelectionDuration, &tr);

This is easy stuff that we've seen before. We retrieve the movie controller identifier from the movie view object, fill out a time record appropriately, and then call MCDoAction with the mcActionSetSelectionDuration action. Notice that we do not return a value to our caller.

Listing 12 shows our implementation of the movieWindowContentRect: method. As with selectNone:, it takes the movie view as the single input parameter. We retrieve the movie and movie controller identifiers, call GetMovieNaturalBoundsRect to get the natural size of the movie, and then adjust the rectangle to contain the movie controller bar (if it's visible) and the 20-pixel border on all sides of the movie view. The rectangle we pass back to the caller contains the desired size of the entire content region of the movie window.

Listing 12: Getting a movie window's size


- (NSRect)movieWindowContentRect:(NSMovieView *)movieView
   Rect rect = {0, 0, 0, 0};
   Movie movie = NULL;
   MovieController mc = NULL;
   movie = (Movie)[[movieView movie] QTMovie];
   mc = (MovieController)[movieView movieController];
   if (movie != NULL)
      GetMovieNaturalBoundsRect(movie, &rect);
   if (MCGetVisible(mc) == 1)
      rect.bottom += kControllerBarHeight;
   return NSMakeRect(0, 0, 
      (rect.right - rect.left) + (2 * kMovieWindowBorder), 
      (rect.bottom - + (2 * kMovieWindowBorder));

What does our AppleScript call to movieWindowContentRect: look like? As with selectNone:, we want to pass the movie view theMovieView as a parameter. The key difference is that we need to capture the result of the method call, which we can do by copying that result to a local list of values, like this:

copy (call method "movieWindowContentRect:" -
      with parameter theMovieView) to -
      {theIgnoreLeft, theIgnoreTop, theMovieWindWid, -

We are interested only in the third and fourth items in the NSRect structure, which are the desired width and height of the movie window content region. Once we've got those values, we can determine the size and location of the movie window fairly easily. Listing 13 shows our complete calculation here.

Listing 13: Setting a movie window's size

on awake from nib

set theTitleBarHgt to 20
copy (call method "movieWindowContentRect:" -
      with parameter theMovieView) to -
      {theIgnoreLeft, theIgnoreTop, theMovieWindWid, -
copy the bounds of the theWindow to -
      {theWindLeft, theWindBottom, theWindRight, theWindTop}
set the bounds of the theWindow to -
      {theWindLeft, theWindTop - (theMovieWindHgt + - 
         theTitleBarHgt), theWindLeft + theMovieWindWid, - 

Setting the Title of a Movie Window

One task remains to be performed in the awake-from-nib event handler; we need to set the title of the movie window to the basename of the movie's pathname. (The basename is the portion of the pathname that follows the rightmost path separator.) These three lines of AppleScript will do the job:

set the text item delimiters to ":"
set theFileName to (theMoviePath as string)
set the title of the theWindow to - 
               the last word of theFileName

We can now make the window visible:

show the window of theMovieView

Movie Playback

At this point, the user has selected a movie file using the file-opening dialog box; we've loaded the movie in that file into the movie view in the movie window and adjusted the initial size of the movie window as appropriate to display the movie at its natural size. AppleScript Studio, in concert with the relevant Cocoa classes, handles all subsequent user actions like moving or minimizing the window, starting and stopping the movie, editing the movie, and so forth. With very little AppleScript code indeed, and with just a small detour into Objective-C, we've got a fully-functioning movie playback application.

We need to intercede here only to handle the menu items that we added to ScripTeez, namely the "Select None" item and the three looping state items in the Movie menu.

Manipulating a Movie's Looping State

As we saw earlier, a menu item can have two handlers associated with it, one that's called when the state of the menu needs to be adjusted (or "updated") and one that's called when the menu item is actually selected. The update handler is called before the menu item is displayed to the user; typically this occurs when the user clicks somewhere in the menu bar. Listing 14 shows the complete update handler for our custom menu items.

Listing 14: Adjusting the menus

on update menu item

on update menu item theObject
   set theMovieView to movie view "movieView" of -
                                                            front window
   set theLoopMode to loop mode of theMovieView
   set enableItem to 1
   set checkItem to 0
   if name of theObject is "selectNone" then
      if editable of theMovieView is equal to true then -
                                             set enableItem to 1
   else if name of theObject is "noLooping" then
      if theLoopMode is equal to normal playback then -
                                             set checkItem to 1
      set state of theObject to checkItem
   else if name of theObject is "normalLooping" then -
      if theLoopMode is equal to looping playback then -
                                             set checkItem to 1
      set state of theObject to checkItem
   else if name of theObject is "palindromeLooping" then -
      if theLoopMode is equal to -
            looping back and forth playback then -
                                             set checkItem to 1
      set state of theObject to checkItem
      set enableItem to 0
   end if
   return enableItem
end update menu item

Notice that we enable the "Select None" menu item only if the movie is listed as editable. Also, we set the state property of the looping menu items so that a check mark is displayed in the currently-active looping state item.

Handling the selection of one of our custom menu items is even easier than adjusting the menu items. We've already seen that we need to use the call method command to handle the "Select None" item. We can handle the looping menu items with pure AppleScript, as shown in Listing 15.

Listing 15: Handling menu item selections

on choose menu item

on choose menu item theObject
   set theWindow to front window
   set theMovieView to movie view "movieView" of theWindow
   if name of theObject is "selectNone" then
      call method "selectNone:" with parameter theMovieView
   else if name of theObject is "noLooping" then
      set loop mode of theMovieView to normal playback
   else if name of theObject is "normalLooping" then
      set loop mode of theMovieView to looping playback
   else if name of theObject is "palindromeLooping" then
      set loop mode of theMovieView to -
                                       looping back and forth playback
   end if
end choose menu item

Closing a Movie Window

When the user quits ScripTeez, the movie window will close automatically. In an ideal world, we would first look to see whether the movie in the window had been edited and then prompt the user to save or discard any changes. To my knowledge, however, AppleScript does not provide any easy way to update the movie data in a movie file. So we'd need to use the call method command once again to call out to Objective-C methods. I'll leave that as an exercise for the interested reader.

ScripTeez does not provide any way to open a new movie window if we happen to close the movie window that's opened at application launch time. Accordingly, we should probably set things up so that closing the movie window will cause ScripTeez to exit. Listing 16 shows the will-close method of the movie window.

Listing 16: Closing a movie window

on will close

on will close theObject
end will close


AppleScript's English-like language makes our code extremely easy to read; I doubt that anyone would have too much trouble understanding even the most complicated scripts we've encountered in this article. We can use AppleScript Studio's built-in commands and properties to handle a good deal of what's required to open and display QuickTime movies. Moreover, if need be, we can supplement our AppleScript with direct calls to Objective-C code to manipulate the Cocoa classes underlying our AppleScript Studio applications. This high-level scriptability and support for low-level method calling make AppleScript Studio an interesting addition to our QuickTime programming toolbox.

Tim Monroe in a member of the QuickTime engineering team. You can contact him at The views expressed here are not necessarily shared by his employer.


Community Search:
MacTech Search:

Software Updates via MacUpdate

How to build a successful civilisation i...
GodFinger 2 grants you godlike powers, leaving you to raise a civilization of followers. In the spirit of games like Black & White, the GodFinger games will see you building bigger and better villages, developing more advanced technology and... | Read more »
How to get all the crabs in Mr Crab 2
Mr. Crab 2 may look like a cutesy platformer for kids, but if you're the kind of person who likes to complete a game 100%, you'll soon realise that it's a tougher than a crustacean's shell. [Read more] | Read more »
How to be a star in Britney Spears: Amer...
If you've ever wanted to be a star, baby, then you've probably already checked out Britney Spears: American Dream and are happily making your way up the charts. But fame doesn't come easy, and everyone needs a helping hand sometimes. So we've got... | Read more »
AppSpy is hiring a part time Staff Write...
| Read more »
How to save lives in ER Surgery Simulato...
A serious earthquake has struck a nearby town in ER Surgery Simulator - Emergency Doctor, and it’s up to you to save the victims. [Read more] | Read more »
Tips and tricks to get a high score in G...
Ketchapp Games loves the endless runner genre. And its newest game, Gravity Switch, is no exception. Gravity Switch takes a fresh approach, though, as you move a block, suspended in zero gravity, safely through a maze of shifting pillars. If the... | Read more »
Tips and tricks to get a high score in S...
Smash Fu is a high-paced tile-tapping game that requires quick reflexes and some practice. You’ll have to smash bricks with the skill of a seasoned black belt to get a high score. To raise the stakes a bit, you’ll also have to avoid tapping any... | Read more »
How to keep the ball rolling in Dropple
If you're new to the minimalist puzzler Dropple, you may find yourself struggling to make it beyond the first couple of steps before your ball falls into the endless abyss below. [Read more] | Read more »
Game Craft releases new Legend of War ti...
Set for release at the end of this month, real time strategy title Legend of War seems sure to delight with a veritable feast of sweet features to get stuck into. Developed by Game Craft, the game is due for release through both the App Store and... | Read more »
How not to die in Traffic Rider
Traffic Rider, an Out Run-esque game in which your ride a motorcycle recklessly into trffic, might not seem particularly complicated. [Read more] | Read more »

Price Scanner via

Textkraft Professional Becomes A Mobile Produ...
The new update 4.1 of Textkraft Professional for the iPad comes with many new and updated features that will be particularly of interest to self-publishers of e-books. Highlights include import and... Read more
SnipNotes 2.0 – Intelligent note-taking for i...
Indie software developer Felix Lisczyk has announced the release and immediate availability of SnipNotes 2.0, the next major version of his productivity app for iOS devices and Apple Watch.... Read more
Pitch Clock – The Entrepreneur’s Wingman Laun...
Grand Rapids, Michigan based Skunk Tank has announced the release and immediate availability of Pitch Clock – The Entrepreneur’s Wingman 1.1, the company’s new business app available exclusively on... Read more
13-inch 2.9GHz Retina MacBook Pro on sale for...
B&H Photo has the 13″ 2.9GHz Retina MacBook Pro (model #MF841LL/A) on sale for $1599 including free shipping plus NY tax only. Their price is $200 off MSRP. Amazon also has the 13″ 3.9GHz Retina... Read more
Apple price trackers, updated continuously
Scan our Apple Price Trackers for the latest information on sales, bundles, and availability on systems from Apple’s authorized internet/catalog resellers. We update the trackers continuously: - 15″... Read more
Clearance 12-inch Retina MacBooks available s...
B&H Photo has dropped prices on leftover 2015 12″ Retina MacBooks with models now available starting at $999. Shipping is free, and B&H charges NY tax only: - 12″ 1.1GHz Gray Retina MacBook... Read more
Check Apple prices on any device with the iTr...
MacPrices is proud to offer readers a free iOS app (iPhones, iPads, & iPod touch) and Android app (Google Play and Amazon App Store) called iTracx, which allows you to glance at today’s lowest... Read more
New 2016 13-inch 256GB MacBook Air on sale fo...
B&H Photo has the new 13″ 1.6GHz/256GB MacBook Air (model MMGG2LL/A) on sale for $1149 including free shipping plus NY sales tax only. Their price is $50 off MSRP. Amazon has the 13″ 1.6GHz/256GB... Read more
Apple refurbished iPad Air 2s available start...
Apple has Certified Refurbished iPad Air 2 available starting at $339. Apple’s one-year warranty is included with each model, and shipping is free: - 128GB Wi-Fi iPad Air 2: $499 - 64GB Wi-Fi iPad... Read more
Accenture and Vatican Opera Romana Pellegrina...
Accenture has announced that the official mobile application for the Extraordinary Jubilee Year of Mercy declared by Pope Francis has been built and launched by Accenture Mobility, part of Accenture... Read more

Jobs Board

*Apple* Nissan Service Technicians - Apple A...
Apple Automotive is one of the fastest growing dealer...and it shows. Consider making the switch to the Apple Automotive Group today! At Apple Automotive , Read more
ISCS *Apple* ID Site Support Engineer - APP...
…position, we are looking for an individual who has experience supporting customers with Apple ID issues and enjoys this area of support. This person should be Read more
Automotive Sales Consultant - Apple Ford Linc...
…you. The best candidates are smart, technologically savvy and are customer focused. Apple Ford Lincoln Apple Valley is different, because: $30,000 annual salary Read more
*Apple* Support Technician II - Worldventure...
…global, fast growing member based travel company, is currently sourcing for an Apple Support Technician II to be based in our Plano headquarters. WorldVentures is Read more
Restaurant Manager (Neighborhood Captain) - A...
…in every aspect of daily operation. WHY YOU'LL LIKE IT: You'll be the Big Apple . You'll solve problems. You'll get to show your ability to handle the stress and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.