← develop-23 9509 September 1995

develop-23 9509 September 1995

From the originals

24 scans

Machine-transcribed text and image descriptions. Check the linked original for uncertain words or fine print.

These are transcribed pages from the documents, not the full publications. Open the original for the remaining pages.

PDF page 7

Speeding Up whose Clause Resolution In Your Scriptable Application

The Object Support Library provides convenient mechanisms for scriptable applications to support complex expressions that may return multiple results (such as every item of container "b" whose name contains "a" ). However, the performance of applications that rely on the default behavior is nowhere near what it could be if the application took on some of the work itself. This article shows you how to gain ten- to a hundred-fold increases in the performance of whose clause resolution in your scriptable application. If your application is not yet scriptable, you’ll find that the foundation classes presented in this article do most of the work required to support scripting. One of the greatest strengths of AppleScript is its built-in ability to do complex operations on groups of objects in a single line of script. For example, suppose you have a set of shapes in a scriptable drawing program, and you’d like to change the color of all the red shapes to green. In conventional programming languages, you’d need to write a loop that iterates over each object in the set, tests to see if its color is red, and then does a “set color to green” command for each red object that was found. Using AppleScript, you can do the same operation with the single statement set color of every shape whose color is red to green . In that statement, every shape whose color is red is called a whose clause , and it’s the inclusion of whose clauses that makes AppleScript the powerful language it is. You may at first doubt that using a whose clause is much better than writing the equivalent script with a loop. After all, the direction of modern processor design has been toward simplicity of the instruction set; RISC chips are able to gain incredible performance improvements by doing optimizations that aren’t possible in CISC chips. Also, when all is said and done, the whose clause must finally execute the same loop-and-compare algorithm that you’d be forced to use if you wrote the script with the basic flow-of-control script commands, such as do - while and if - then . Using a whose clause is, however, much more efficient than the alternative. AppleScript is based on the client/server paradigm: typically your script, the client, will be running in one application (usually the Script Editor or a script saved as a miniapplication), with the application being scripted acting as a server. In this GREG ANDERSON Speeding Up whose Clause Resolution In Your Scriptable Application d e v e l o p Issue 24 December 1995 6 GREG ANDERSON is enjoying the hot days of late summer as he writes this, but by the time this issue is in your hands, he should be back on the ski slopes earning his nickname, “Air Bear.” Greg spends most of his skiing time looking for some protrusion to jump or fall off of while wearing his favorite polar bear hat. He sometimes works, too; he recently moved to Japan to work on international software for Apple Technologies in Tokyo.•

Reading notes: Line-break hyphenation in 'ten- to a hundred-fold' and 'hundred-fold' is ambiguous in the extracted text. Author byline and sidebar text appear interleaved with the article body, so reading order around 'GREG ANDERSON' may be uncertain.

Printed product names
AppleScript
Printed dates
December 1995 · Issue 24
Languages
English
PDF page 8

System) and the Free MIDI System (FMS) from Mark of the Unicorn. None of these are practical for adding just a little music to your application. Writing a serial driver to send MIDI output to an Apple MIDI adapter or to any third-party MIDI adapter isn’t that complicated if you enjoy writing low-level code to access hardware registers on the SCC serial chip. I say this in all seriousness: that kind of code really is fun to write! But it’s not the best way to do things, because changes in the OS and hardware can render your work useless. And writing the low- level serial code for MIDI input has additional complexities, primarily because of the interrupt timings in many parts of the Mac OS. The MIDI Manager is a slightly better tool to use for MIDI input and output. Unfortunately, Apple’s support for this product has been less than consistent, and the MIDI Manager itself has some inherent performance limitations, though these are less critical on faster hardware (68030 processor or better). Both OMS and FMS are quite appropriate for professional music scoring and editing products. Among the facilities that these extensions provide is a “studio configuration”; this lets the user describe to the system the various MIDI devices attached to the computer so that different applications can access them. All of these options have drawbacks for making casual use of music: you have to access an external MIDI device, which most users don’t have, and you have to use MIDI protocols to talk to that device. QTMA frees you from both of these constraints. It also frees you from needing to know a lot about MIDI itself; if you want to know anyway, check out the information in “A MIDI Primer.” QTMA’S BASIC COMPONENTS QTMA is implemented in three easy pieces, as QuickTime components for playing individual notes, playing tunes (sequences of notes), and driving MIDI devices. • The note allocator component is used to play individual notes. The calling application can specify which musical instrument sound to use and exactly which musical synthesizer to play the notes on. The note allocator component also includes a utility that allows the user to pick the instrument. • The tune player component can accept entire sequences of musical notes and play them from start to finish, asynchronously, with no further need for application intervention. This is handy if you’d like to play some infernally irritating little melody, or perhaps threnody, during each game level of Boom Three Dee or whenever. • Individual music components act as device drivers for each type of synthesizer attached to a particular computer. Two music components are provided with QuickTime 2.0: the software synthesizer component, to play music out of the built-in speaker, and the General MIDI component, to play music on a General MIDI device attached to a serial port. QuickTime 2.1 supports a small number of other popular synthesizers as well. PLAYING NOTES WITH THE NOTE ALLOCATOR Playing a few notes with the note allocator component is simple. To play notes that have a piano-like sound, you need to open up the note allocator component, allocate a note channel with a request for piano, and play. That’s it! If you’re feeling like a particularly well-behaved software engineer, you might dispose of the note channel and close the note allocator component when you’re done. We’ll get to the code in a moment; first we’ll look at some important related data structures. d e v e l o p Issue 23 September 1995 6

Reading notes: Source text begins mid-sentence and the first product name is truncated at the excerpt boundary. Page footer 'd e v e l o p Issue 23' appears inline within the body text.

Printed product names
Free MIDI System (FMS) · MIDI Manager · QuickTime 2.0 · QuickTime 2.1 · General MIDI · Boom Three Dee · QTMA · Apple MIDI adapter · Mac OS · A MIDI Primer · d e v e l o p
Printed dates
September 1995
Languages
English
PDF page 8

situation, each script command that’s directed at the scriptable application needs to be transferred between the two applications. A whose clause is a single script command, but with the loop approach many commands would need to be sent. Furthermore, AppleScript allows the scriptable application to reside on a different machine than the application running the script; if your script is running on a machine in Cupertino, California, and the server is on, say, Mars, reducing the number of round-trip messages would have a profound impact on the performance of the script. Remember, you can currently get only about 30 round-trip Apple events per second, so even if you aren’t sending data to Mars, you’ll still do a lot better with fewer events than with many. There’s another, similar reason that using whose clauses is superior to the equivalent loop-based script: AppleScript compiles scripts into byte codes that are interpreted during execution, whereas the individual script commands (once interpreted) are processed by a scriptable application typically written in a language that’s compiled into machine code (be it 680x0 or PowerPC™). The loop-and-compare script will execute several lines of script for every item that’s compared, whereas the whose clause is but a single line of script that triggers processing in a compiled application. It should be quite clear which will take less time to execute. The Object Support Library (OSL) — the library that provides the API you use to make your application scriptable — enables your application to support whose clauses without requiring you to write a lot of additional code. You only need to provide an object-counting function and an object comparison function, and the OSL can resolve whose clauses for you. Since supporting whose clauses allows script writers to write more efficient scripts, you should always do at least this much. However, there are two other features of the OSL that can vastly increase the performance of scriptable applications but are often ignored by application writers: whose clause resolution (a way for your application to find the objects that match a whose test without using the OSL) and marking (a mechanism for efficiently handling collections of objects, such as those satisfying a whose clause). Using whose clause resolution, with the help of marking, will enable you to get the most out of your scriptable application. Resolving whose clauses can be a bit tricky, but with a little help from this article, you’ll be on your way in no time. If your application is not yet scriptable, you’ll find the sample code included with this article (and on this issue’s CD) to be invaluable in getting you up and running — particularly since it contains a lot of reusable code. AN OVERVIEW OF THE OSL Good descriptions of the OSL can be found in the develop articles “Apple Event Objects and You” in Issue 10 and “Better Apple Event Coding Through Objects” in Issue 12. If you need a quick review of the OSL and you don’t feel like putting down this issue of develop to dig through your back issues, read on. If you can already generate tokens and resolve object specifiers in your sleep, by all means skip ahead to the next section. When AppleScript is processing a script command such as delete paragraph 2 of document "sample" , it converts the command into an Apple event which it sends to the scriptable application that’s referenced by the script. The Apple event’s event class and message ID together specify the verb of the operation being performed — in this case delete . The object being operated on is passed in the keyDirectObject parameter of the Apple event, which is called, naturally enough, the direct parameter of the event. SPEEDING UP WHOSE CLAUSE RESOLUTION IN YOUR SCRIPTABLE APPLICATION 7

Printed dates
Issue 10 · Issue 12
Languages
English
PDF page 9

NOTE-RELATED DATA STRUCTURES A note channel is analogous to a sound channel in that you allocate it, issue commands to it to produce sound, and close it when you’re done. To specify details about the note channel, you use a data structure called a NoteRequest (see Listing 1). The NoteRequestInfo structure in the NoteRequest is new in QuickTime 2.1; it simply encapsulates the first few fields of the old NoteRequest structure and splits the first of those fields into two, flags and reserved (which are decribed in the documentation accompanying the QuickTime 2.1 release). The next two fields specify the probable polyphony that the note channel will be used for. Polyphony means, literally, many sounds. A polyphony of 5 means that five notes can be playing simultaneously. The polyphony field enables QTMA to make sure that the allocated note channel can play all the notes you’ll need. The typicalPolyphony field is a fixed-point number that should be set to the average number of voices the note channel will play; it may be whole or fractional. Some music components use this field to adjust the mixing level for a good volume. The ToneDescription structure is used throughout QTMA to specify a musical instrument sound in a device-independent fashion. This structure’s synthesizerType and synthesizerName fields can request a particular synthesizer to play notes on. Usually, they’re set to 0, meaning “choose the best General MIDI synthesizer.” The gmNumber field indicates the General MIDI (GM) instrument or drum kit sound, which may be any of 135 such sounds that are supported by many synthesizer manufacturers. (All these sounds are available on a General MIDI Sound Module.) The GM instruments are numbered 1 through 128, and the seven drum kits are numbered 16385 and higher. A complete list of instrument and drum kit numbers is provided in Table 1. For synthesizers that accept sounds outside the GM library, you MUSIC THE EASY WAY: THE QUICKTIME MUSIC ARCHITECTURE 7 MIDI, or Musical Instrument Digital Interface, uses a serial protocol and a standard 5-pin connector that you’ll find on professional electronic music gear made after 1985 or so. The connector’s relatively large size, about half an inch in diameter, was chosen so that it could withstand the rigors of the road — in other words, so that even drummers could plug it in. Because MIDI cables can carry signals in only one direction, synthesizers have separate connectors for MIDI input and MIDI output. (This differs from modem cables, which carry signals in both directions.) MIDI is a serial protocol running at 31250 baud, 8 data bits, 1 stop bit, no parity. The command structure for a MIDI stream is simple: each byte is either a status byte or a data byte. A status byte establishes a mode for interpreting the data bytes that follow it. The high bit is set, and the next three bits indicate the type of status byte. The low four bits are typically used to specify a MIDI channel. Thus MIDI can address up to 16 unique channels, each of which may play a different musical instrument sound. Later extensions to MIDI let you address more channels through the use of escape codes and bank switching. The most common status message is the Play Note message, which has a value of 0x90 plus the MIDI channel number. Each note is defined by a pitch and velocity. The pitch is an integer from 0 to 127, where 60 is musical middle C (61 is C sharp, 59 is B, 72 is the C above middle C, and so on). The velocity is an integer from 0 to 127 that describes how loud to play the note; 64 is average loudness, 127 is very loud, 1 is nearly inaudible, and 0 means to stop playing the note. So, to play a C-major chord on MIDI channel 0, you send the seven bytes 0x90 0x3C 0x40 0x40 0x40 0x43 0x40 to begin the sound. After a suitable interval, you send 0x90 0x3C 0x00 0x40 0x00 0x43 0x00 to silence it. All of this is exactly the sort of stuff you don’t need to know if you use the QuickTime Music Architecture for your music-playing needs. But you just can’t know too many useless facts, right? A MIDI PRIMER

Reading notes: Source text contains a stray '0x90 0x3C 0x40 0x40 0x40 0x43 0x40' byte sequence whose layout may be a line-break artifact; exact reading order of the chord bytes is uncertain. Typographic artifact 'decribed' appears in the source copy and is preserved as printed.

Languages
English
PDF page 9

The direct parameter is almost always an object specifier — a descriptor of type typeObjectSpecifier — although in some cases it may be something else. For example, in addition to object specifiers, the Scriptable Finder accepts alias records and file specifications in the direct parameter of events sent to it. If the direct parameter of an event is not of type typeObjectSpecifier, you’re on your own to convert it into some format that’s understood by your event handler. For descriptors that are of this type, though, all you need to do is call the function AEResolve, and the OSL will step in and help your application resolve the object specifier — that is, locate the Apple event objects it describes. Object specifiers are resolved through object accessor callbacks that your application installs to allow the OSL to communicate with your application during object resolution. The accessor callbacks must take the description of the object requested by the OSL (for example, document "sample" ) and return a token that describes the object in terms that the application can understand (for example, a pointer to a TDocument object). Tokens are passed back to the OSL in an AEDesc, a structure that contains a 32-bit descriptor type and a handle. Your application has complete control over what it stores in the token, as long as the AEDesc is valid (that is, it was created with AECreateDesc). When the OSL calls your application’s object accessor callbacks, it always passes either a token that represents the containing object (which it got from an earlier call to one of your object accessors) or a representation of the default container of the application, which is also called the null container of the application. So, to resolve the object specifier paragraph 2 of document "sample" , the OSL first asks for document "sample" from the null container. Then it asks the application to provide a token for paragraph 2 from the token the application provided in response to the request for document "sample" . The token that the application provides for paragraph 2 is returned as the result of the AEResolve call; the application will presumably use this token to process the Delete event. Resolving object specifiers is explained in Chapter 6 of Inside Macintosh: Interapplication Communication. A figure illustrating the process of resolving object specifiers is on page 6-6.• MARKING Inside Macintosh: Interapplication Communication describes marking as a mechanism whereby items to be operated on are marked with some flag during resolution (that is, from the callbacks made by the AEResolve function); then, during execution, each marked item is processed and the mark is cleared. As described, marking doesn’t sound very interesting and appears to be useful only in fringe cases. Marking is actually very well suited for use as a general-purpose collection mechanism whenever the OSL needs to group tokens together to process an object resolution. For example, if the OSL is resolving the whose clause every shape whose color is red and there are multiple red shapes, the result of the call to AEResolve must be a collection of all the tokens that represent red objects. If your application supports marking, the OSL asks your application to create a special mark token to represent this collection. After your application provides the OSL with a mark token, the OSL will ask your application to add the tokens it provided for the red shapes to the mark token’s collection. When AEResolve completes, the mark token is returned as the result of the resolution. If your application doesn’t support marking, the OSL will create collections of tokens for you by copying the data from your tokens into a descriptor list (an AEDescList). d e v e l o p Issue 24 December 1995 8

Reading notes: Source ends with a page marker and footer 'd e v e l o p Issue 24 December 1995 8' that may not be part of the body text.

Printed dates
1995
Languages
English
PDF page 10

can use the instrumentName and instrumentNumber fields to specify some other sound. THE NOTE-PLAYING CODE The routine in Listing 2 plays notes in a piano-like sound with the note allocator component. We start by calling OpenDefaultComponent to open up the component. If this routine returns 0, the component wasn’t opened, most likely because QTMA wasn’t present. Next we fill in the NoteRequestInfo and ToneDescription structures, calling the note allocator’s NAStuffToneDescription routine and passing it the GM instrument number for piano. This routine fills in the gmNumber field and also fills in the other ToneDescription fields with sensible values, such as the instrument’s name in text form in the instrumentName field. (The routine can be useful for converting a GM instrument number to its text equivalent.) After allocating the note channel with NANewNoteChannel, we call NAPlayNote to play each note. Notice the last two parameters to NAPlayNote: ComponentResult NAPlayNote(NoteAllocator na, NoteChannel nc, long pitch, long velocity); The value of the pitch parameter is an integer from 1 to 127, where 60 is middle C, 61 is C sharp, and 59 is C flat, or B. Similarly, 69 is concert A, and is played at a nominal audio frequency of 440 Hz. The velocity parameter’s value is also an integer from 1 to 127, or 0. A velocity of 1 corresponds to just barely touching the musical keyboard, and 127 indicates that the key was struck as hard as possible. Different velocities produce tones of different volumes from the synthesizer. A velocity of 0 means the key was released; the note stops or fades out, as appropriate to the kind of sound being played. Here we stop the notes after delaying an appropriate amount of time with a call to the Delay routine. d e v e l o p Issue 23 September 1995 8 Listing 1. Note-related data structures struct NoteRequest { NoteRequestInfo info; // • in post-QuickTime 2.0 only ToneDescription tone; }; struct NoteRequestInfo { UInt8 flags; UInt8 reserved; short polyphony; Fixed typicalPolyphony; }; struct ToneDescription { OSType synthesizerType; Str31 synthesizerName; Str31 instrumentName; long instrumentNumber; long gmNumber; };

Reading notes: Source appears to be a magazine article excerpt; headline not identifiable from supplied copy Date 1995 appears only in the issue line 'Issue 23 September 1995'

Printed dates
1995
Languages
English
PDF page 10

It calls the standard Apple Event Manager routines for creating descriptor lists, which copy the data out of the data handle of the AEDesc and then store the token data somewhere inside the data handle of the descriptor list; the descriptor type of the AEDesc is similarly encapsulated. Dealing with descriptor lists of tokens can be inconvenient, particularly if your application already supports collections of objects in some other way. The OSL marking mechanism gives you the flexibility to handle collections in any way that’s convenient for your application. To support marking, you must pass the flag kAEIDoMarking to AEResolve and implement the three marking callbacks that are passed to AESetObjectCallbacks: the create-mark-token callback (called just a “mark-token callback” in Inside Macintosh ), the object-marking callback, and the mark-adjusting callback. The create-mark-token callback doesn’t need to do anything more than create an empty mark token. The OSL will dispose of this token as usual by calling your token disposal callback when the token is no longer needed. Listing 1 shows an example implementation of a create-mark-token callback. The object-marking callback is passed a mark token created from the create-mark- token callback and some other token created by one of your application’s object accessor callbacks. Your object-marking callback should add a copy of the other token into the mark token (or apply a reference count to the token being added), because the OSL will dispose of the token added to your collection shortly after calling your object-marking callback. Listing 2 shows one implementation of an object-marking callback. The mark-adjusting callback is called to remove (“unmark”) tokens from the collection. Oddly enough, its parameters specify which tokens in the range to keep; all tokens outside the specified range should be discarded. Implementing the marking callbacks is trivial. The only real work involved in supporting marking is handling collections of tokens when they’re ultimately received by one of your event handlers (handling Move events, for example). The amount of code required to handle the marking callbacks and maintain your own collections is minimal; in fact, the time you’ll save by not having to hassle with descriptor lists of tokens will more than make up for the implementation cost. You’ll find more information on handling collections of tokens later in this article. Don’t put off SPEEDING UP WHOSE CLAUSE RESOLUTION IN YOUR SCRIPTABLE APPLICATION 9 Listing 1. Create-mark-token callback pascal OSErr CreateMark(AEDesc containerToken, DescType desiredClass, AEDesc* markTokenDesc) { TMarkToken* markToken; markToken = new TMarkToken; markToken->IMarkToken(); markTokenDesc->descriptorType = typeTokenObject; markTokenDesc->dataHandle = markToken; return noErr; }

Reading notes: Listing 1 code excerpt is mid-article and its surrounding context is not fully legible in the supplied copy

Languages
English
PDF page 11

MUSIC THE EASY WAY: THE QUICKTIME MUSIC ARCHITECTURE 9 Table 1. The General MIDI instruments and drum kits Piano Bass Reed Synth Effect • 1 Acoustic Grand Piano 33 Acoustic Fretless Bass 65 Soprano Sax 97 Ice Rain 2 Bright Acoustic Piano • 34 Electric Bass Fingered • 66 Alto Sax 98 Sound Tracks 3 Electric Grand Piano 35 Electric Bass Picked 67 Tenor Sax 99 Crystal 4 Honky-tonk Piano 36 Fretless Bass 68 Baritone Sax 100 Atmosphere • 5 Rhodes Piano • 37 Slap Bass 1 • 69 Oboe 101 Brightness 6 Chorused Piano 38 Slap Bass 2 70 English Horn 102 Goblins • 7 Harpsichord 39 Synth Bass 1 71 Bassoon 103 Echoes • 8 Clavinet 40 Synth Bass 2 • 72 Clarinet 104 Space Chromatic Percussion Strings and Orchestra Pipe Ethnic 9 Celesta • 41 Violin 73 Piccolo • 105 Sitar 10 Glockenspiel 42 Viola • 74 Flute • 106 Banjo 11 Music Box 43 Cello 75 Recorder 107 Shamisen • 12 Vibraphone 44 Contrabass • 76 Pan Flute 108 Koto • 13 Marimba 45 Tremolo Strings 77 Bottle Blow 109 Kalimba 14 Xylophone 46 Pizzicato Strings 78 Shakuhachi 110 Bagpipe 15 Tubular bells 47 Orchestral Harp • 79 Whistle 111 Fiddle 16 Dulcimer • 48 Timpani 80 Ocarina 112 Shanai Organ Ensemble Synth Lead Percussive • 17 Hammond Organ • 49 Acoustic String Ensemble 1 81 Square Wave 113 Tinkle Bell 18 Percussive Organ 50 Acoustic String Ensemble 2 • 82 Saw Wave • 114 Agogo 19 Rock Organ 51 SynthStrings 1 83 Calliope • 115 Steel Drums 20 Church Organ 52 SynthStrings 2 84 Chiffer 116 Woodblock • 21 Reed Organ • 53 Aah Choir 85 Charang 117 Taiko Drum 22 Accordion 54 Ooh Choir 86 Solo Vox • 118 Melodic Tom 23 Harmonica 55 Synth Vox • 87 5th Saw Wave 119 Synth Drum 24 Tango Accordion • 56 Orchestra Hit 88 Bass and Lead • 120 Reverse Cymbal Guitar Brass Synth Pad Sound Effects • 25 Acoustic Nylon Guitar • 57 Trumpet • 89 Fantasy 121 Guitar Fret Noise 26 Acoustic Steel Guitar 58 Trombone • 90 Warm 122 Breath Noise 27 Electric Jazz Guitar 59 Tuba • 91 Polysynth • 123 Seashore 28 Electric Clean Guitar 60 Muted Trumpet 92 Choir • 124 Bird Tweet 29 Electric Muted Guitar • 61 French Horn 93 Bowed • 125 Telephone Ring 30 Overdriven Guitar 62 Brass Section 94 Metal • 126 Helicopter • 31 Distortion Guitar 63 Synth Brass 1 95 Halo 127 Applause 32 Guitar Harmonics 64 Synth Brass 2 96 Sweep • 128 Gunshot GM Drum Kits • 16385 Standard Kit • 16393 Room Kit (a memory-reduced version of the Standard Kit) 16401 Power Kit 16409 Electronic Kit 16410 Analog Kit 16425 Brush Kit 16433 Orchestra Kit • Bullets indicate the instruments and drum kits that are available for playing on the built-in synthesizer.

Reading notes: Bullet markers in the table denote built-in synthesizer availability and may not be fully reliable in extraction.

Languages
English
PDF page 11

marking as an optimization to be done later; incorporate it into the design of your application from the very beginning. For more details on the marking callbacks, see Inside Macintosh: Interapplication Communication, pages 6-53 to 6-54.• WHOSE CLAUSE RESOLUTION The only thing that a scriptable application needs to do to support whose clauses is provide an object-counting function and an object comparison function — the OSL will do the rest of the work. When the OSL does a whose clause resolution, however, it has no choice but to iterate over every element in the search set, repeatedly calling your application’s object accessor, object comparison, and token disposal callbacks. Huge performance gains can be realized if you resolve whose clauses yourself, because you’ll avoid the overhead the OSL requires to make these callbacks. Passing the flag kAEIDoWhose to AEResolve tells the OSL that you’ll resolve the whose clause yourself. The OSL calls your object accessor with the key form formWhose (see Listing 3). The key data is a whose descriptor — that is, an AERecord that describes the comparison to be performed in the search. Your application should interpret the whose descriptor and test every element of the container token to see if it matches the specified criteria. If the whose descriptor is too complex for your application, you can return the error code errAEEventNotHandled from your object accessor, and the OSL will do the resolution for you with the default techniques. This is very useful, as it allows you to maximize the performance of the most common whose clauses, yet still support complex whose descriptors that are likely to be encountered only rarely. The astute reader will notice that the scheme presented in Listing 3 is very similar to the process that the OSL goes through to resolve whose clauses. There are still optimizations that could be made to speed up the resolution further, but we’ll get to those later. To resolve whose clauses as shown in Listing 3, your application must be able to do the following: d e v e l o p Issue 24 December 1995 10 Listing 2. Object-marking callback pascal OSErr TAccessor::AddToMark(AEDesc tokenToAdd, AEDesc markTokenDesc, long markCount) { AEDesc copyOfToken; TMarkToken* markToken; // We know that the OSL will only give us mark tokens created with // our create-mark-token callback, but real code would do a test // before typecasting. markToken = (TMarkToken*) markTokenDesc.TokenObject(); // Add a copy of the token to the collection, because the OSL will // dispose of tokenToAdd after passing it to you. A reference- // counting scheme is good here. copyOfToken = CloneToken(tokenToAdd); markToken->AddToCollection(copyOfToken); return noErr; }

Reading notes: Source text is a technical programming article excerpt with no advertised products, prices, or headline. Printed date 'Issue 24 December 1995' appears in running footer.

Printed dates
1995
Languages
English
PDF page 12

d e v e l o p Issue 23 September 1995 10 Listing 2. Playing notes with the note allocator component void PlaySomeNotes(void) { NoteAllocator na; NoteChannel nc; NoteRequest nr; ComponentResult thisError; long t, i; na = 0; nc = 0; // • Open up the note allocator. na = OpenDefaultComponent(kNoteAllocatorType, 0); if (!na) goto goHome; // • Fill out a NoteRequest using NAStuffToneDescription to help, and // • allocate a NoteChannel. nr.info.flags = 0; nr.info.reserved = 0; nr.info.polyphony = 2; // • simultaneous tones nr.info.typicalPolyphony = 0x00010000; // • usually just one note thisError = NAStuffToneDescription(na, 1, &nr.tone); // • 1 is piano thisError = NANewNoteChannel(na, &nr, &nc); if (thisError || !nc) goto goHome; // • If we've gotten this far, OK to play some musical notes. Lovely. NAPlayNote(na, nc, 60, 80); // • middle C at velocity 80 Delay(40, &t); // • delay 2/3 of a second NAPlayNote(na, nc, 60, 0); // • middle C at velocity 0: end note Delay(40, &t); // • delay 2/3 of a second // • Obligatory do-loop of rising tones for (i = 60; i <= 84; i++) { NAPlayNote(na, nc, i, 80); // • pitch i at velocity 80 NAPlayNote(na, nc, i+7, 80); // • pitch i+7 (musical fifth) at // • velocity 80 Delay(10, &t); // • delay 1/6 of a second NAPlayNote(na, nc, i, 0); // • pitch i at velocity 0: end note NAPlayNote(na, nc, i+7, 0); // • pitch i+7 at velocity 0: // • end note } goHome: if (nc) NADisposeNoteChannel(na, nc); if (na) CloseComponent(na); }

Reading notes: Source is C code listing from a magazine article rather than advertising copy; no headline or advertised products present.

Printed dates
September 1995
Languages
English
PDF page 12

• Iterate over the elements of any token. • Determine class membership of any token. • Compare properties of the elements of any token. • Convert a whose clause into some internal representation usable by your application. The first two operations are required of any scriptable application, so yours probably can already do them. Comparing properties is something your application probably doesn’t do yet, but in the worst case you could always write a few lines of code that call your property object accessor function, retrieve the data from the resulting property token, and then compare the descriptor that was returned. Obviously you can do better than this in terms of performance, and later on we’ll investigate how. First, though, we’ll look at how to interpret the contents of a whose descriptor. THE CONTENTS OF A WHOSE DESCRIPTOR Earlier I claimed that a whose descriptor was an AERecord, but I lied. A whose descriptor is actually a descriptor of type typeWhoseDescriptor. Internally, a whose descriptor is stored just like an AERecord, but you can’t extract its parameters unless you first coerce it to type typeAERecord. In Apple events parlance, this type of descriptor is called a coerced record ; its basic type is typeAERecord, and its coerced type is typeWhoseDescriptor. SPEEDING UP WHOSE CLAUSE RESOLUTION IN YOUR SCRIPTABLE APPLICATION 11 Listing 3. Handling formWhose in the object accessor pascal OSErr MyObjectAccessor(DescType desiredClass, AEDesc container, DescType /*containerClass*/, DescType keyForm, AEDesc keyData, AEDesc* resultToken, long /*hRefCon*/) { switch (keyForm) { // case formAbsolutePosition, and so on ... case formWhose: // TWhoseDescriptor is a class that knows how to interpret // a whose descriptor and test tokens for membership in the // search set defined by the desired class and the whose // descriptor. TWhoseDescriptor whoseDesc(desiredClass, keyData); // TTokenIterator is a class that knows how to iterate // over the elements of a token. TTokenIterator iter(container); for (iter.Reset(); iter.More(); iter.Next()) { AEDesc token = iter.Current(); if (whoseDesc.Compare(token) == kTokenIsInSearchSet) { // Add token to the collection stored in resultToken. AddTokenToResult(token, resultToken); } } break; } return noErr; }

Languages
English
PDF page 131 · PDF page 3

A R T I C L E S 5 Music the Easy Way: The QuickTime Music Architecture by David Van Brink The QuickTime Music Architecture lets you easily add music to your application, without having to learn the intricacies of MIDI or sound production. Unleash the orchestra! 30 The Basics of QuickDraw 3D Geometries by Nick Thompson and Pablo Fernicola Geometries are the backbone of any 3D graphics system. This article shows how the geometries in QuickDraw 3D fit in with the rest of the system, and how to make good use of them. 55 Implementing Shared Internet Preferences With Internet Config by Quinn “The Eskimo!” This article examines a shared preferences solution for Internet applications: how to use it in your applications, and also how it works, using the Component Manager as a robust shared library mechanism. 77 Multipane Dialogs by Norman Franke Dialog boxes with multiple panes are becoming more and more common. This implementation uses a scrolling list of icons to select panes. 94 Document Synchronization and Other Human Interface Issues by Mark H. Linton The Macintosh Human Interface Guidelines say that a window’s title should match the corresponding document’s name at all times. Here’s some code that will help you do that. C O L U M N S 25 PRINT HINTS Syncing Up With ColorSync 2.0 by David Hayward ColorSync version 2.0 dramatically improves the quality and performance of color management. 52 BALANCE OF POWER Power Macintosh: The Next Generation by Dave Evans The latest Power Macintosh computers are better than ever, as you’ll see from this overview of new features. 72 MPW TIPS AND TRICKS Customizing Source Control With SourceServer by Tim Maroney SourceServer is a “scriptable Projector,” allowing extensive source control customization. 90 ACCORDING TO SCRIPT Thinking About Dictionaries by Cal Simone Tips on organizing your dictionary, and other assorted bits of wisdom and advice. 103 MACINTOSH Q & A Apple’s Developer Support Center answers queries about Macintosh product development. 112 THE VETERAN NEOPHYTE A Feel for the Thing by Dave Johnson Computers are getting more and more like boomerangs. Goody. 114 NEWTON Q & A: ASK THE LLAMA Answers to Newton-related development questions, along with a bit of llama lore. Send in your own questions for a chance at a T-shirt. 117 KON & BAL’S PUZZLE PAGE Video Nightmare by Ian Hendry and Eric Anderson Another intricate and entertaining enigma, this time from a pseudo KON & BAL. Issue 23 September 1995 CONTENTS 1 2 EDITOR’S NOTE 3 LETTERS 123 INDEX

Reading notes: Heading "A R T I C L E S" is a section label rather than a true primary headline; the headline value uses it as printed. Reading order of the table of contents mixes article and column entries; treat entries as listed sequentially.

Printed product names
QuickTime Music Architecture · QuickDraw 3D · Internet Config · Component Manager · Macintosh Human Interface Guidelines · ColorSync 2.0 · Power Macintosh · SourceServer · Projector · Newton
Printed dates
September 1995
Languages
English