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

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

13-inch M2 MacBook Airs in stock today at App...
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 today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.