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

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 »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »

Price Scanner via MacPrices.net

You can save $300-$480 on a 14-inch M3 Pro/Ma...
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
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer 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 MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more

Jobs Board

IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
Top Secret *Apple* System Admin - Insight G...
Job Description Day to Day: * Configure and maintain the client's Apple Device Management (ADM) solution. The current solution is JAMF supporting 250-500 end points, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.