September 95 - Macintosh Q & A
Q How do I create a menu with an icon as its title?
A Set the menu title to 0x0501handle, where handle is the result of calling
GetIconSuite. An example snippet of code follows; this code assumes that the
menu title is already five bytes long.
void ChangeToIconMenu()
{
Handle theIconSuite = nil;
MenuHandle menuHandle;
GetIconSuite(&theIconSuite, cIcon, svAllSmallData);
if (theIconSuite) {
menuHandle = GetMenuHandle(mIcon);
if (menuHandle) {
// Second byte must be 1, followed by the icon suite handle.
(**menuHandle).menuData[1] = 0x01;
*((long *)&((**menuHandle).menuData[2]))
= (long)theIconSuite;
// Update display (typically you do this on startup).
DeleteMenu(mIcon);
InsertMenu(menuHandle, 0);
InvalMenuBar();
}
}
}
Q
We're drawing palette icons with a loop that consists basically of the
following:
GetIcon...
HLock...
CopyBits...
ReleaseResource...
Our
native PowerPC version seems to draw these icons a lot more slowly than even
our 680x0 version running under emulation, which suggests a Mixed Mode Manager
slowdown. Which of these routines are currently native on the PowerPC? GetIcon
and ReleaseResource together seem to take over 90% of the time.
A As you suspected, the Resource Manager calls you're using aren't native, and
they generally call File Manager routines, which aren't native either. But be
careful: what's native and what isn't is changing over time, and you shouldn't
design your application based on today's assumptions.
That said, relying on the Resource Manager to be fast is generally not a good
idea, native or not. One approach is to "cache" the icons, making sure they're
in RAM at all times. (In general, you should do this for any user interface
element that will be redrawn repeatedly while your application is open.) You
can load your icons as one of the first few operations in your initialization
code, just after calling MaxApplZone (possibly moving them high and locking
them, since you don't want them to move during a CopyBits operation). This
technique yields very good performance on the redraws that the palette needs,
in exchange for a few kilobytes of memory. Don't forget to mark the resources
as nonpurgeable.
Even better, if it will suit your purposes, would be to use the Icon Utilities
to retrieve and draw your icons (as documented in Inside Macintosh: More
Macintosh Toolbox) and to build an icon cache. Using the Icon Utilities helps
your application do the right thing for different screen depths. Also, the
icon-drawing routines have been optimized to perform well under a variety of
conditions.
Q How can we detect that our application is already running and bring it to the
front?
A Simply iterate through the currently running processes with GetNextProcess,
calling GetProcessInformation for each one and comparing its process signature
with your application's (for an example, see the article "Scripting the Finder
From Your Application" in develop Issue 20, page 67, Listing 1). If your
application is running, call SetFrontProcess to bring it to the front.
Q WindowShade is causing a problem for our application, which saves the window
position and size when it saves a document to disk. If our application's
windows are "rolled up" with WindowShade, its windows appear to have zero
height. Is there any way to determine whether a window is rolled up? If so, can
we determine its true size and the global coordinates of the top left corner of
the content region, so that we can restore and reposition the window when the
document is reloaded from disk?
A When WindowShade "rolls up" a window, it hides the content region of the
window. You can tell a window is rolled up when its content region is set to an
empty region and its structure region is modified to equal the new "shaded"
window outline. WindowShade doesn't do anything with the graphics port, though,
so if you need to store the window's dimensions before closing it, use the
window's portRect.
With regard to the window's position, WindowShade modifies the bottom
coordinates of the structure and content regions of the window, but the top,
left, and right coordinates are not changed. These are global coordinates, so
you can use the top and left coordinates to track and save the global position
of the window on the screen regardless of whether the window is rolled up.
Q Sometimes balloons won't show up when I call HMShowBalloon; I get a paramErr
(-50) instead. The hmmHelpType is khmmTEHandle. HMShowBalloon calls TextWidth
on the hText of my TEHandle (the result of which is 1511, the width of 338
characters), then multiplies that by the lineHeight (12), yielding 18132. It
then compares this to 17000, doesn't like the result, puts -50 into a register,
and backs out of everything it has done previously. What's the Help Manager
doing?
A The Help Manager checks against 17000 to ensure that the Balloon Help window
will always be smaller than a previously determined maximum size. Currently,
you're limited to roughly the same number of characters with a styled TEHandle
as you are with a Pascal string: 255 characters.
Keep your help messages small by using clear, concise phrases. If you
absolutely need more text in a balloon, you can create a picture of it and use
khmmPict or khmmPictHandle to specify it for your help message. This is not
recommended, however; "picture text" has the disadvantage of being difficult to
edit or translate to other languages.
Q Is there any way I can stop LClick from highlighting more cells when the user
drags the cursor outside the list's rView area? My program allows users to
select more than one item from a list and then drag and drop these selected
items into another list. But I run into a problem with the LClick function:
when I drag these items outside the list's rView area, it still highlights
other cells. What can I do?
A If you want to use LClick and not change the highlighting of cells when the
cursor leaves the rView of the list, you should install a click-loop procedure
that tracks the mouse. When the mouse is outside your list's rectangle, return
false to tell the List Manager that the current click should be aborted. It
turns out that this is a nice way to start a drag as well, since you know that
the mouse has left the rectangle. It might look like this:
GetMouse(&localPt);
if (PtInRect(localPt, &(*list)->rView) == false)
return false; // We're out of the list.
else
return true;
Q
I'm developing a Color QuickDraw printer driver and want to match colors using
ColorSync 1.0.5 with a custom CMM. I was told that for efficiency I should
manually match colors inside my Stdxxx bottlenecks, instead of calling
DrawMatchedPicture. Is this really more efficient? Why?
A Surprising as it may be, it is more efficient for printer drivers to manually
match colors inside Stdxxx bottlenecks than to call DrawMatchedPicture. This is
because ColorSync 1.0's DrawMatchedPicture doesn't use bottlenecks as you
expected. It does install a bottleneck routine that intercepts picture comments
(so that it can watch the embedded profiles go by), but it doesn't do the
actual matching in bottleneck routines. Instead, it installs a color search
procedure in the current GDevice. Inside the search procedure, each color is
matched one at a time.
While this implementation has some advantages, it's painfully slow on PixMaps,
because even if the PixMap contains only 16 colors, each pixel is matched
individually. This has been changed in ColorSync 2.0. To boost performance,
PixMaps (which are, after all, quite common) are now matched in the bottlenecks
instead of with a color search procedure. (See the Print Hints column in this
issue of develop for more on ColorSync 2.0.)
Q I need to add some PostScript comments to the beginning of the PostScript
files generated by the LaserWriter GX driver. On page 4-119 of Inside
Macintosh: QuickDraw GX Printing Extensions and Drivers, it says that you can
override the GXPostScriptDoDocumentHeader message to do this. I wrote a
QuickDraw GX printing extension to implement this, assuming that all I had to
do was to override the GXPostScriptDoDocumentHeader message and buffer the
desired data with Send_GXBufferData. Here's an example of my code:
OSErr NewPostScriptDoDocumentHeader
(gxPostScriptImageDataHdl hImageData)
{
OSErr theStatus = noErr;
char dataBuffer[256];
long bufferLen;
strcpy(dataBuffer, "%%DAVE'S TEST DATA");
bufferLen = strlen(dataBuffer);
theStatus = Send_GXBufferData((Ptr) dataBuffer, bufferLen,
gxNoBufferOptions);
if (theStatus != noErr)
return theStatus;
theStatus = Forward_GXPostScriptDoDocumentHeader(hImageData);
return theStatus;
}
Unfortunately,
this causes a bus error when Send_GXBufferData is called, even if I put
Send_GXBufferData after the call to Forward_GXPostScriptDoDocumentHeader. Why
doesn't this work?
A The override in your extension is basically correct, but the order of your
code needs to be slightly different:
// Note that the string is terminated with a return character:
#define kTestStr "%%DAVE'S TEST DATA\n"
OSErr NewPostScriptDoDocumentHeader
(gxPostScriptImageDataHdl hImageData)
{
OSErr theStatus = noErr;
char dataBuffer[256];
long bufferLen;
theStatus = Forward_GXPostScriptDoDocumentHeader(hImageData);
if (theStatus != noErr)
return theStatus;
// Note that we do (sizeof(...) - 1) below to strip off the
// C string null terminator for the string defined.
theStatus = Send_GXBufferData(kTestStr, (sizeof(kTestStr) - 1, 0);
return theStatus;
}
Make
sure that the string is terminated with a return character. If you're using a
#define to allocate static space for the string (which is not recommended),
remember that it allocates the string plus a null terminator; sizeof then
returns the size of the string, so you need to subtract 1 from the total. This
string should come from a resource or a file.
If you want to add to the header from an application (to avoid writing the
extension), you can add an item of type 'post' to the job collection, using the
tag gxPrintingTagID. If the first character of this item is a % character, it
will appear in the job header.
Q Our application has multiple QuickDraw GX shapes layered on top of each
other. The bottom object is a graphic, and the objects on top of it are text
shapes. The text objects are transparent, permitting the underlying graphic to
show through. Are there functions in QuickDraw GX to facilitate refreshing the
background shapes when characters are deleted in the text layout shapes above
it? We need to refresh the graphic with minimal flicker and want to avoid
resorting to the standard CopyBits routing.
A QuickDraw GX doesn't have any direct functions to facilitate refreshing or
redrawing only a portion of a shape covered by another shape. However, there
are a few methods that can be used in conjunction with various QuickDraw GX and
QuickDraw calls to accomplish your goals. Here are three approaches that might
work for you:
- As you know, you can have QuickDraw GX draw directly into a GWorld, and
use CopyBits to update the appropriate area. This approach is good if you need
to draw QuickDraw and QuickDraw GX objects in the same window.
- If you merge multiple shapes into a QuickDraw GX picture, you can use
the picture's clip shape to update the area in question. Make your graphic
shape the bottom shape in the picture's hierarchy. This forces QuickDraw GX to
draw the graphic as the first shape, with the other shapes drawn on top.
QuickDraw GX pictures are smart, in the sense that they respect the clip shapes
associated with the picture and all of the shapes contained within the picture.
- To update the smallest possible area, convert the QuickDraw update
region to a QuickDraw GX path. Then get the current clip shape of the picture
with GXGetShapeClip, and save it for later restoring. Use the path as the "new"
clip shape of the picture and draw. Finally, restore the picture's clip shape.
- Create a QuickDraw GX offscreen bitmap to perform flicker-free updating
in a manner similar to using CopyBits. This method, though, is based completely
on QuickDraw GX. When updating the screen, clip your drawing to the area you
want to update. For an example, see the "3 circles - hit testing" sample that
ships with QuickDraw GX.
Q I'm using a layout shape to represent an area
for editable text that will have a fixed position, style, font, size, and
width. This layout shape has some default text that the user is prompted to
change (text content only, no other attributes). Each time text is added (the
new text replaces the previous text string), the user interface code checks
whether the size of the new string goes beyond the defined width. I do this by
comparing the width of the local bounds with the width given within the layout
shape geometry. In all cases, the justification setting is 0, but the flush
setting varies (left/0, center/0.5, right/1.0).
Sometimes the width of the local bounds reaches a point where it's wider than
the width defined by the shape; in other cases, it approaches the width but
never reaches or surpasses it. In this situation, the text is updated and
begins to compress itself within the defined width. How can I allow text to be
entered till the width is reached, but not compressed?
A The problem you describe was fixed in QuickDraw GX 1.1.1 with a new API call:
Fixed GXGetLayoutJustificationGap (gxShape layout);
This
function returns information that was always generated during layout's
justification processing but was never made publicly visible before. It
represents the signed difference between the specified width for the layout and
the measured (unjustified) width.
By setting a width in the layout options, but leaving the justification factor
at 0, you can keep adding text until the results of the
GXGetLayoutJustificationGap call changes sign from positive to negative. At
that point, the text starts to compress, so you should prohibit new text entry.
It's a very fast call (since its result is cached as part of the layout process
anyway), so calling it on every typed character shouldn't slow things down at
all.
Some examples may help clarify the use of this call: Suppose you create a
layout with the width field of the gxLayoutOptions set to 500 points and the
justification factor set to fract1 (full justification). If the unjustified
width of the layout is only 450 points, GXGetLayoutJustificationGap returns +50
points; if the unjustified width is 525 points, this function returns -25
points. A positive value means the line will be typographically stretched to
fill the specified width, while a negative value means the line will be
typographically condensed.
Note that the justification factor in the gxLayoutOptions doesn't have to be
fract1 in order for this function to return useful results. For instance, if
you set a width value but leave the justification factor at 0, the line will
not be justified unless its unjustified width exceeds the specified width. In
this case, layout will typographically shrink the line. A client program that
wants to determine when the end of a line is reached (for line-breaking
purposes) can call this function after every character is added (as the user
types, for example); as soon as the value becomes negative, the client knows
that the margin has been reached.
Q There are three options on the General panel of the QuickDraw GX Print dialog
-- Collate Copies, Paper Feed, and Quality -- that we would like to move to one
of our own panels. We have solutions that differ from the default ones, and we
want to rename these solutions and associate them with our printer. How can I
eliminate those options from the General panel?
A There's no mechanism in QuickDraw GX to remove panel items from the standard
Print panels, except for the Quality item. The Quality collection item
(gxQualityTag = 'qual'), whose structure is defined in PrintingManager.h, has a
Boolean field called disableQuality. To eliminate the Quality item from the
panel, specify true for the disableQuality field in your driver. Although you
cannot remove the other items, you can disable them (dim them in the panel) by
getting the collection item and setting the locked attribute with
SetCollectionItemInfo.
Q Do I need to call GXCloneColorProfile before calling GXConvertColor? Since
the color passed into GXConvertColor by ColorSync is destroyed, should the
color profile passed in as part of the color be disposed of? If not, isn't that
a memory leak?
A Calling GXCloneColorProfile isn't necessary, and it would require additional
work that doesn't need to be done. The gxColor structure is a public data
structure, not an object: the application, not QuickDraw GX, handles adding and
maintaining references to objects with respect to gxColors (and gxBitmaps).
QuickDraw GX maintains owner counts when the profile is attached to another
QuickDraw GX object (using GXNewBitmap, GXSetInkColor, and so on). This is not
a memory leak.
For example, consider this scenario: When an application gets a shape's color,
the ink's profile has two owners -- the shape and the application. Therefore,
the application can reference the profile in gxColor structures, even if the
shape is disposed of. Once the application calls GXDisposeColorProfile, the
reference is no longer valid. Cloning the color profile does nothing except to
require that GXDisposeColorProfile be called afterward. As a result, all that
happens is that time is wasted as the owner count goes from a positive number
to that number plus 1, and then back down.
Q Does QuickDraw GX send the GXDoesPaperFit message when I'm setting up input
tray dialogs, or is the driver supposed to do this? If QuickDraw GX doesn't,
it's possible for users to request completely invalid paper sizes, which can
violently crash most raster drivers.
A QuickDraw GX sends the GXDoesPaperFit message in the default implementation
of the input trays dialog to constrain the configuration options, and drivers
that perform their own input trays dialog should do the same. A driver should
override this message if it needs other than the default logic, which responds
that everything fits.
The packing buffer size specified in the 'rpck' resource is set to the expected
maximum size needed. Unfortunately, this is far smaller than what's needed when
handling larger than expected paper sizes. To work around this, you can set the
packing buffer size so that it can accommodate the largest paper size the
printer can use.
Q I've been experimenting to see what happens when a print job is canceled part
of the way through. If I cancel when GXOpenConnection and GXStartSendPage have
both completed successfully, I get unexpected GXCleanupOpenConnection and
GXCleanupStartSendPage messages. If I cancel at another point in the job (for
example, during rendering via the Remove button in the desktop printer status
window), GXCleanupStartSendPage and GXCleanupOpenConnection messages are passed
through after ImageDocument exits. This behavior seems very odd, and it doesn't
appear to be discussed anywhere in the documentation. Shouldn't
GXCleanupOpenConnection and GXCleanupStartSendPage be called only if their
respective routines return an error?
A The unexpected GXCleanupOpenConnection and GXCleanupStartSendPage messages
are coming from the default implementations of ImageJob and ImagePage. The
ImageJob code calls Send_GXSetupImageData, and if an error occurs, it sends
GXCleanupOpenConnection. ImagePage calls Send_GXRenderPage and sends
GXCleanupStartSendPage if an error occurs. If GXStartSendPage or
GXOpenConnection doesn't complete successfully, the respective cleanup calls
are not sent. Although the documentation states otherwise, this behavior is
correct.
Q Is the layout of the PostScript printer preferences ('pdip') resource
documented correctly in Inside Macintosh: QuickDraw GX Printing Extensions and
Drivers?
A No. There's a bug in the documentation for the 'pdip' resource on page 6-88
of Inside Macintosh: QuickDraw GX Printing Extensions and Drivers. The render
options field is in fact a long word. The resource is defined correctly in the
interfaces (PrintingRezTypes.r) and in the MPW 411 files for QuickDraw GX.
Q Is there a simple way to detach a QuickTime movie from its original file? I'm
trying to place a copy of a QuickTime movie in my application's resource
fork.
A See John Wang's QuickTime column in develop Issue 17. You can use the
technique presented in that column to extract a movie and put it into the
resource fork of a different file. You'll find the column and the accompanying
sample code, MultipleMovies, on this issue's CD.
Q How can I determine whether QuickTime 2.0's MIDI music function is available
and whether the larger set of 41 instruments is available? If the MIDI function
is available, we need to add code to enable the music portion of our game.
A The QuickTime Music Architecture became available in QuickTime 2.0 (as
described in David Van Brink's article in this issue of develop), so checking
the QuickTime version in a Gestalt call (selector gestaltQuickTimeVersion) will
tell you if the MIDI function is present.
When the QuickTime Musical Instruments Extension is installed in your System
Folder, it gives you the musical instruments supported by Apple. This extension
is actually a component. If you need to know whether the instruments are
present, call FindNextComponent, searching for a component that has a type of
'inst' and a subtype of 'ss '. Here's a code snippet:
pascal Boolean AreQuickTimeMusicInstrumentsPresent(void)
{
ComponentDescription aCD;
aCD.componentType = 'inst';
aCD.componentSubType = 'ss ';
aCD.componentManufacturer = 'appl';
if (FindNextComponent((Component)0, &aCD) != NULL)
return true;
else
return false;
}
Q
Are there any known compatibility problems between QuickTime 2.0 and QuickTime
for Windows? I'm creating a dual-platform application and want to use QuickTime
2.0 for the video. Is there anything that I should avoid on either platform, or
anything I should watch out for?
A In most cases, you don't have to be concerned about using the same movie for
playback on both platforms, as long as the movie is in a flattened format and
in a single-fork file. To be sure your movie files are single-fork files,
select "Make cross-platform" in the MoviePlayer application when saving your
movies (or do something analogous in other applications that produce
cross-platform movies).
QuickTime supports sound, video, text, music (MIDI), and MPEG tracks under both
Windows and the Mac OS. One difference between the two versions is that you can
have only one of each track open under Windows (except for the number of sound
tracks; starting with QuickTime for Windows 2.0.1, you can enable/disable
multiple sound tracks).
The biggest difference between the two versions is the API: QuickTime for
Windows 2.0 doesn't support all the API calls available under the Mac OS.
Nearly all of the movie controller APIs are supported, as well as many of the
basic calls, but the calls to create manipulable movie tracks are missing. You
can't create specific media handlers with QuickTime for Windows 2.0, but you
can write data handlers and codecs for the Windows environment.
While working with QuickTime for Windows, you'll have to keep track of all the
possible configuration issues that users might encounter. We distribute README
files with the latest information about compatibility and configurations
(video/sound cards, drivers, and so on).
For additional information, the Mac OS Software Developer's Kit includes
detailed documentation regarding API and architecture issues concerning
QuickTime and QuickTime for Windows. Also see How to Digitize Video by Weiskamp
and Johnson (Wiley Press) for another good source of information regarding the
practical issues of both QuickTime and AVI movie creation. Although this book
is a bit out of date in the details (it was written to cover QuickTime 1.6.1
and QuickTime for Windows 1.1.1), much of it is still valid.
Q Can we use a different A5 world with QuickTime? Our plug-in architecture uses
A5 for global access, but we allow the A5 world to move. QuickTime doesn't seem
to be able to deal with this, and it doesn't realize that EnterMovies was
called once the A5 world moves. We currently work around this by locking down
our A5 world, but we would rather not do this. If we need to keep doing this,
is locking down the A5 world an adequate fix, and can you recommend another
solution?
A You can use a different A5 world with QuickTime, but whatever A5 world you
use, you'll have to lock it down. QuickTime allocates a new set of state
variables for each A5 world that's active when EnterMovies is called. However,
since QuickTime uses A5 to identify each QuickTime client, if A5 changes (your
A5 world moves), QuickTime won't recognize that you've called EnterMovies for
that client.
Q How do I determine the correct time values to pass to GetMoviePict to get all
the sequential frames of a QuickTime movie?
A The best way to determine the correct time to pass to get movie frames is to
call the GetMovieNextInterestingTime routine repeatedly. The first time you
call GetMovieNextInterestingTime, its flags parameter should have a value of
nextTimeMediaSample + nextTimeEdgeOK to get the first frame. For subsequent
calls, the value of flags should be nextTimeMediaSample, and the
whichMediaTypes parameter should be VisualMediaCharacteristic ('eyes') to
include only tracks with visual information.
Q I noticed that certain commercial candies have no taste when they initially
hit my tongue. It's only after I start sucking them that the flavor appears. I
think there's some sort of coating on them. What is it? Is it harmful?
Also, what is it that creates that beautiful high gloss I get with my car wax
and floor wax? I just love the way it shines after a good hard buffing.
A Carnauba wax is the answer, in both cases. It's a hard wax obtained from the
leaves of a Brazilian palm tree (Copernicia prunifera), and is used a lot in
polishes of all types. It really does buff up beautifully, doesn't it? It also
is completely tasteless and nontoxic, and makes a dandy confectioner's glaze,
used to keep the candy from sticking to itself.
These answers are supplied by the technical gurus in Apple's Developer Support
Center.*
Have more questions? See the new Macintosh Technical Q&As on this issue's
CD. (Older Q&As can be found in the Macintosh Q&A Technical Notes on
the CD.)*