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

Introduction

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

ScrTzMethods.h

@interface NSApplication (ScrTzMethods)

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

@end

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

selectNone

- (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

movieWindowContentRect

- (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 - rect.top) + (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, -
                                                      theMovieWindHgt}

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, -
                                                      theMovieWindHgt}
copy the bounds of the theWindow to -
      {theWindLeft, theWindBottom, theWindRight, theWindTop}
set the bounds of the theWindow to -
      {theWindLeft, theWindTop - (theMovieWindHgt + - 
         theTitleBarHgt), theWindLeft + theMovieWindWid, - 
                                                      theWindTop}

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
   else
      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
   quit
end will close

Conclusion

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 monroe@apple.com. The views expressed here are not necessarily shared by his employer.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.