PICT Comments
Volume Number: | | 4
|
Issue Number: | | 6
|
Column Tag: | | Resource Roundup
|
Comments About PICTs
By Joel West, Palomar Software, Inc., MacTutor Contributing Editor
Joel West is the author of the best selling MPW book titled Programming with Macintosh Programmers Workshop. He is also the principle in Palomar Software, which produced the popular Colorizer DA and recently, the Pict Detective utility. In this column he continues his Resource Roundup with some expert insights into PICT resources.
PICTs
This months focus will be on PICT resources, handles and documents. These QuickDraw pictures are the lingua franca of Macintosh graphics, the common ground between diverse applications.
As Im always fond of emphasizing, software developers (yes, that means you!) must support compatibility and standards to keep the users and marketing types happy. Whatever other graphics formats you prefer, the standard user interface requires you to support PICTs in some form or another.
Besides, PICTs are the native format of QuickDraw, a mere transcription of the various QD calls. In practical terms, PICTs are what you get for free with your Macintosh graphics, so if you can display it on the screen, you can record it in a PICT.
Now while Im big on standards, Im not so dogmatic as to ignore the reality that PICTs are often the lowest common denominator, such as when youre writing a complex PostScript-based program. Still, that doesnt mean you should ignore PICTs, or make them look like heck--since thats also what youll get on the many non-PostScript printers.
What kind are there?
Our Mac world is divided into two classes of people: those own Macintosh IIs, and the impoverished masses. (Before anyone starts flaming, let me say that Im writing this with the SE on my desk at Palomar, and with my Plus at home, since other people are using my Mac II.)
Anyway, there are the original, classic, or PICT-1 pictures that were defined with the Macintosh 128, and unchanged by the Plus and SE. Any Macintosh can generate these and display them accurately.
The Macintosh II can also generate and display new, color, or PICT-2 pictures that require Color QuickDraw. The main differences are that you get more than 8 colors, and you can have color bit images.
Fig. 1 Our sample PICT object parsed with Pict Detective
You can use a PICT-2 on a Plus or an SE, thanks to a clever DrawPicture() patch in System 4.1 and later. (See Sleuthing the New System File in the August 1987 edition of Resource Roundup.). The patch draws a PICT-1 approximation of the color picture. Unfortunately, in doing so, the patch throws all the interesting information on the floor.
There is a reasonable way to preserve this information (Palomar would be glad to provide it to any developer upon request), but interest in doing this seems to be underwhelming. My conclusion is that we will have to live with this lobotimized approximation of PICT-2s for as long as applications must support machines without Color QuickDraw. (Three years? Five years?) [At the recent Developer Conference, MacTutor asked the Apple gurus why Apple didnt simply create one version of quickdraw for all machines so developers would not have to support multiple window, menu and PICT data structures. The answer was Quickdraw requires the 68020. Now I know that! But they could have written a 68000 version for the SE that allowed color quickdraw calls which defaulted to black and white, presenting to the developer a single programming model. It appears Apple intends to upgrade the SE to a 68020 and solve the problem that way. Incidently, there was some controversey over letting me ask that question, as the panel moderator said I was Press, a dirty word at Apple, I guess. I would like to thank all the friends of MacTutor who hooted down the Apple representative so I could ask my question. -Ed]
Where do you find them?
QuickDraw pictures are usually found in one of three places:
In a resource of type PICT;
In the clipboard; or
In the data fork of a file of type PICT.
All three usages can be found in a typical PICT-oriented application. Resources are created when the user copies a PICT into the Scrapbook; theyre also used by applications that need to display a PICT in a dialog, since one of the predefined dialog item types is a PICT resource.
The other two formats are directly employed by users to interchange graphics between two programs. As documented with the Scrap Manager, the standard user interface requires all programs to be able to import a PICT clipboard entry, while all but the most brain-damaged of graphics programs can also open and save PICT files.
How do you get one?
Finding a PICT resource is criminally easy; depending on what youre up to, youre likely to try
ph: PicHandle;
ph := PicHandle(
GetResource(PICT, resno));
FailNIL(ph);
or maybe
ph := PicHandle(
Get1IndResource(PICT, 1));
FailNIL(ph);
(All examples shown here are in MPW Pascal, with a MacAppish flavor. I find myself re-implementing functions like FailOSErr and FailNIL for my non-MacApp programs, just to keep consistent.)
The clipboard is a pretty easy place to grab a picture, too:
ph: PicHandle;
len: LONGINT;
ph := NewHandle(0);
len := GetScrap(Handle(ph),
PICT, offset);
IF len < 0 THEN
BEGIN
IF len = noTypeErr THEN
(* there wasnt one *)
ELSE
FailOSErr(OSErr(len));
EXIT(ThisRoutine);
END;
Reading a PICT from the data fork of a file is also childs play. Like most of Apples early formats, the first 512 bytes are a header; for now, we ignore them, but if you really care, the format is described in Macintosh Technical Note #27, MacDraws PICT File Format and Comments.
Anyway, this is all it takes to figure how long the picture is and read it into a new handle:
FailOSErr(GetEOF(docrefno, filelen));
FailOSErr(SetFPos(docrefno,
fsFromStart, 512));
piclen := filelen - 512;
phand := NewPermHandle(piclen);
FailNIL(phand);
HLock(phand);
FailOSErr(FSRead(docrefno,
piclen, phand^));
HUnlock(phand);
Of course, Im oversimplifying--or, as Kurt Schmucker used to say in his courses, Im lying to you just a little. This all assumes that you have lots of memory (always a bad assumption) and that every picture is small (even worse.) More on that in a minute. Suffice it to say that, if you have large pictures and not much memory, the above code will give up.
What do you do with them?
Each picture has one piece of useful information directly readable by any application: its bounding rectangle. This is read by the code
arect := ph^^.picFrame;
The original documentation also says theres a size in the picture (picSize), but thats a big lie, not a small one. Nowadays, there are lots of big pictures, those longer than the 32,767 limit of a signed 16-bit integer. For reliable results, you must get the size from some other means (if you dont have it already), such as from the Memory Manager:
piclen := GetHandleSize(ph);
Of course, theres really only one good thing to do with a picture: draw it. This is probably the simplest thing you can do with a picture:
DrawPicture(ph);
(This is another little lie, since QuickDraw can fail and not tell you about it, particularly with a big picture, but finding out whether QuickDraw is failing is beyond the scope of this article.)
Of course, you can also invert all the previous steps for finding a picture: create a new resource, write the PICT to the clipboard, or write it to the data fork.
Creating a new resource is a matter of two calls,
resid := Unique1ID(PICT);
AddResource(ph, PICT, resid, );
FailOSErr(ResError);
Writing it to the clipboard is also pretty easy:
FailOSErr(ZeroScrap);
HLock(ph);
FailOSErr(PutScrap(piclen,
PICT, ph^));
HUnlock(ph);
Writing it to disk is also easy; just dont forget to zero the 512-byte header if you dont have something interesting to put in the header (a reasonable simplifying assumption). Shown below is also one of the ugliest ways to generate the zerod header, but is included to keep the code easy to follow:
FailOSErr(SetEOF(docrefno,
piclen+512));
long := 0;
FOR i:=1 TO 128 DO
FailOSErr(FSWrite(docrefno,
SIZEOF(LONGINT), @long));
HLock(phand);
FailOSErr(FSWrite(docrefno,
piclen, phand^));
HUnlock(phand);
PICT Sleuthing
Regular readers of Resource Roundup will recall previous articles that talked about keyboard sleuthing, printer sleuthing, and system file sleuthing.
Unfortunately, the format of pictures is so complicated that sleuthing an arbitrary picture a byte at a time is a very involved process. Just when I thought I had a handle on it, along came PICT-2, making it even worse.
At one point, Id hoped to finish my program by August 1987, but that was not to be. Instead, a local Mac developer, Marshall Clow, finished up the work and made a product out of something that Id started, so we could release PICT Detective to the world at Januarys Expo in San Francisco. The response has been suprisingly strong for such a specialized tool--proof positive how many developers are doing graphics development.
PICT Detective is a set of utility programs for the MPW programs. It consists of three MPW tools:
DePict decompiles PICT resources and documents into Rez source form
PictFork moves a PICT from a resource to a PICT document, or vice versa.
ShowPict puts up a modal dialog to allow you to peek at the PICT while within MPW.
In addition, Pict.r contains enough declarations to be able to recompile any DePictd data back to a picture. An earlier version was included in Chapter 9 of Programming with Macintosh Programmers Workshop, but it has two severe limitations: it fails badly with bitmaps, and it doesnt support the PICT-2 format.
You can also fiddle with the source before recompiling, or define new pictures completely from scratch using the Rez source form. Of course, Rez only compiles to the resource fork, but PictFork will move the compiled picture back to the data fork.
For the duration of this article, Ill be illustrating the contents of PICTs using the DePict format, the only form I know of today for describing pictures.
To give you some idea of what the output can look like, first take a look at the picture shown in Figure 1, which was created using SuperPaint. Now look at is its description of a simple picture in DePict form:
resource PICT (0, purgeable) {
194, /* Actual length: 194 */
{0, 0, 720, 576},
{Version{ 1};
ShortComment{ picDwgBeg };
ClipRgn{ 10, {0, 0, 720, 576},
$};
PnPat{ $88 00 22 00 88 00 22 00"};
OvSize{ {18, 18}};
PaintRRect{ {57, 40, 133, 425}};
PnSize{ {4, 4}};
PnPat{ $FF FF FF FF FF FF FF FF};
FrameSameRRect{ };
LongComment{ picTextBegin{
6, 0, 0, 2, 0x00}};
LongComment{ picTextCenter{
0xFFF40000, 0x00608000}};
ShortComment{ picStringBegin };
TxFont{ times};
TxSize{ 48};
DHDVText{ -120, 102, MacTutor};
ShortComment{ picStringEnd };
ShortComment{ picTextEnd };
LongComment{ picTextBegin{
6, 0, 0, 2, 0x00}};
LongComment{ picTextCenter{
0xFFFC0000, 0x00628000}};
ShortComment{ picStringBegin };
TxSize{ 13};
LongText{ {116, 134},
The Macintosh Programming Journal};
ShortComment{ picStringEnd };
ShortComment{ picTextEnd };
ShortComment{ picDwgEnd };
EndOfPicture{ }
}
};
Note that the length shown is the 16-bit picSize length, while the actual length is the length of the resource--usually the same for resources less than 32K long.
Otherwise, if you know QuickDraw, the description is nearly self-explanatory. About the only opcodes that might not be familiar are ShortComment and LongComment, which brings us to
PICT Comments
Lots of the interesting stuff in a picture wont fit in QuickDraws mindset. Some of this stuff doesnt belong in QuickDraw, other probably did belong, but didnt make it in time.
But there is a portable way for applications to share meta-information with other code: via picture comments. These are portions of a picture that are recorded and replayed by QuickDraw, but, by default, have no effect on the displayed image.
Picture comments have three principal uses:
To convey additional information that is useful for an application that is reading a picture previously saved to the clipboard or a document. An example of this is grouping objects, alá MacDraw.
To communicate information from an application to the current printer driver. An example of this is including PostScript output for the LaserWriter.
To get around some implementation limitation in QuickDraw. This was particularly severe with the stack-based algorithms of the 64K ROM (which worked around the puny heap of a 128K Mac, but prone to stack overflow), but still required for large bit images.
Of course, theres an overlap between these categories. Printer drivers can ignore some of the comments, but applications typically generate (and must recognize) all three categories.
Table 1 shows a list of the most common and important picture comments. Again, the names are those used by DePict; the main difference is that any comment that didnt start with pic had it added as a prefix, for consistencys sake and to make it easy to distinguish picture comments from opcodes.
Banding Bits
When you draw a bit image on the screen with CopyBits(), QuickDraw uses roughly the same amount of memory as your bitmap (or pixmap) as a temporary scratch memory. This is sometimes too much for your Mac to tolerate.
Clever programs break larger bit images into a series of horizontal bands, as illustrated by Figure 2. Each band is drawn with a separate CopyBits(), one below another, until the entire image is covered.
Fig. 2 PixMap
The picBitBeg and picBitEnd comments indicate to an aware application that the intervening bits are bands of a single image, not separate images. Your code looks something like:
PicComment(picBitBeg, 0, NIL);
FOR i := 1 TO nbands DO
BEGIN
...
CopyBits(...);
END;
PicComment(picBitEnd, 0, NIL);
This is one case where an application must understand an input picture comment. Otherwise, your user will see a series of separate images from any program that is kind enough to band the data into reasonable-size pieces.
At Palomar, we live by the gospel we preach. When it came time to do the Colorizer package for the Mac II, we made sure that the Color SaveScreen screen dump FKEY outputs bands. The Colorizer application recognizes a series of bands between picBitBeg and picBitEnd as being a single bitmap object.
How small should thou makest thine bands? Once upon a time, in the days of olden ROM, very tiny 3.5K bands were recommended. Thou must forsake this ancient ritual, since thou shalt fail miserably with the images of Color QuickDraw, which art 300K or more.
As long as youre stick with a Macintosh Plus or later, a size of 20K-40K seems about right, according to Apple technoid, and MacTutor Founding Board Member, Chris Derossi, whos researched the subject. Some people like 32,768 (or slightly less). I happen to insist on a minimum of 21,888, so that a standard-screen Plus or SE screen dump is never banded.
Note that the sizes measure the size of the bit image in memory, or height*width*depth / 8. The actual size in the picture will be somewhat less, due to the PackBits compression performed by QuickDraw when recording the picture.
Realize that the larger the band size, the more temporary memory will be necessary to display your picture. On the other hand, the smaller the band size, the more bands you have; because each band has a fixed overhead, this can increase the size of your picture. For example, a 256-color PixMap has an overhead of about 1,100 bytes for each band; if memory serves me, Chris Derossi was able to save about 30K out of a 300K image by increasing the 20K bands to 40K.
Whoa, Trigger!
While were on the subject of bits, Id also like to remark on a truly under-documented picture comment, picLasso. How did the original MacPaint tell the difference between a bitmap selected with the rectangular selection tool and one selected with the lasso? (The tools shown below.)
With a picture comment, of course. This same picture comment is also used by HyperCard and SuperPaint, and probably some other applications I dont know about.
I went ahead and selected a small image in SuperPaint and put it into the Scrapbook. This is what it looked like in DePict form:
resource PICT (-32766, purgeable) {
93,/* Actual length: 93 */
{0, 0, 14, 16},
{Version{ 1};
ShortComment{ picDwgBeg };
ShortComment{ picBitBeg };
ClipRgn{ 10, {0, 0, 720, 576}, $};
BitsRect{
2,
{0, 0, 14, 16},
{0, 0, 14, 16},
{0, 0, 14, 16},
srcOr,
$03F8"
$1C06"
$2001"
$4001"
$8001"
$8006"
$8038"
$71C0"
$CE00"
$A800"
$7000"
$1000"
$1000"
$2000"
};
ShortComment{ picBitEnd };
ShortComment{ picDwgEnd };
EndOfPicture{ }
}
};
Now, if the same image is lassod, there is one main difference. The first few opcodes include the picLasso comment, as in:
Version{ 1};
ShortComment{ picDwgBeg };
ShortComment{ picLasso };
ShortComment{ picBitBeg };
ClipRgn{ 10, {0, 0, 720, 576}, $};
BitsRect{/* etc. etc. */
Tallying Text
When youre including text in a drawing, a group of comments allow you to both exchange data with other applications and take full advantage of the high-resolution LaserWriter text placement.
The picTextBegin comment allows including the following information:
Left, right, center or full justification
Rotation of text, 0-360° (although usually a multiple of 90°)
Flipping coordinate system along horizontal or vertical axis
Single, 1.5 or double spacing
This affects all the text objects up until the picTextEnd comment. The picTextCenter comment specifies the center of rotation for this group of text.
If you want to see more code demonstrating these picture comments, look at Editing Rotated Text by John D. Olsen in the February 1988 issue of MacTutor. The picTextBegin comment is also important when it comes to talking about application compatibility with printer drivers.
Incidentally, the old ROM also required banding pieces of strings with picStringBegin and picStringEnd. On reading a commented PICT, you should strip out these archaic comments and reassemble into a single string. On output, dont bother to put them in.
Pacifying MacDraw
MacDraw has its own set of picture comments. Some of them are useful to other graphics programs, or to printer drivers; others are just odd MacDrawisms.
The first such comment is picDwgBeg. Dont ask me why, but MacDraw wants to see this comment. However, it must be the very thing you add to the picture, and it must be closed with picDwgEnd as the very last thing you put in the picture. For example,
ph := OpenPicture(somerect)
PicComment(picDwgBeg, 0, NIL);
(* other drawing here ... *)
PicComment(picDwgEnd, 0, NIL);
ClosePicture;
More useful information is contained in the grouping comments picDwgBeg and picDwgEnd, which bracket objects that have been grouped together to act like one object. This concept (and the associated comments) is useful for any graphics program, which is why we made it one of the few comments supported by the initial version of our Colorizer application.
Other comments are related to arrowheads on lines. MacDraw provides arrowhead information in a PICT two ways. For it own use, it includes picture comments indicating what sort of arrowhead should be drawn on the beginning or end of the line, or both. For other programs, it includes a screen representation of the arrowheads, as in
ShortComment{ picArrw1 };
ClipRgn{ 10, {0, 0, 720, 540}, $};
PaintArc{ {35, 288, 55, 308}, 246, 48};
Line{ {45, 36}, {45, 289}};
ShortComment{ picArrwEnd };
MacDraw II has fancier arrowheads, but I havent laid my hands on a copy yet, so I can say how it represents those arrowheads in a PICT.
Finally, MacDraw has a really wierd way of defining polygons. So wierd, in fact, that many third-party applications receive polygons from MacDraw and dont realize it.
Instead of using QuickDraw polygon calls, MacDraw represents all polygons by bracketing a series of line segments with picPolyBegin and picPolyEnd picture comments. A simple MacDraw polygon looks like:
resource PICT (0, purgeable) {
60,/* Actual length: 60 */
{0, 0, 720, 540},
{Version{ 1};
ShortComment{ picDwgBeg };
ShortComment{ picPolyBegin };
ShortComment{ picPlyClo };
ClipRgn{ 10, {0, 0, 720, 540}, $};
Line{ {27, 45}, {135, 288}};
ShortLineFrom{ -126, 36};
ShortLineFrom{ -99, -63};
ShortLineFrom{ 0, -9};
ShortLineFrom{ -18, -72};
ShortComment{ picPolyEnd };
ShortComment{ picDwgEnd };
EndOfPicture{ }
}
};
Roll Your Own Comment
Finally, there is a portable way to define your own picture comments and include information private to your application. You might want to do this when copying an image to the clipboard, if your application wanted to keep some information beyond the standard QuickDraw definition.
As described in Macintosh Technical Note #181, Every Picture [Comment] Tells Its Story, the new picAppComment includes the application signature and a variable amount of data. Since every good developer registers his/her unique application signature with Macintosh Developer Technical Support, this means there will never be a conflict with other applications, right?
I included an example of using this application-specific comment in the PICT Detective manual. To my knowledge, none of the software released as of this writing uses this comment, but such software will definitely be hitting the streets later in 1988.
P.S. on PostScript
In a future article, Ill talk a little more about how picture comments are used to communicate between an application and a printer driver.
Many of the comments that are defined have to do with PostScript. Do you want to output direct PostScript to a printer? You have a lot of choices on how to throw it into a picture comment.
However, one comment is so standard that even a cursory discussion of comments would be incomplete without it.
The comment, picPostScriptHandle, is also one of the easiest to use: the remainder of the comment is nothing more than raw PostScript. When you see it in DePict output, the name seems a little odd, but it makes sense when you see the code to generate it .
To take an extremely trivial example, suppose you want to precede any of your custom PostScript with your own proprietary notice, defined by a string resource:
resource STR (1024) {
%Copyright 1988 FooBar Software};
To add this to your PostScript output, you merely need the code:
hand: Handle;
siz: LONGINT;
hand := Handle(GetString(1024));
siz := GetHandleSize(hand);
PicComment(picPostScriptHandle,
siz, hand);
Later, you might take the picture file and disassemble it with DePict. The data would look something like:
resource PICT (0, purgeable) {
4062,
{0, 0, 342, 512},
{Version{ 1};
ClipRgn{ 10, {0, 0, 342, 512},
$},
LongComment{
picPostScriptHandle{
%Copyright 1988 FooBar Software}};
...
Finding PICT Comments
As noted before, analyzing a picture a byte at a time is very complicated and requires that you build a complete parser similar to Apples.
The simple way is to let QuickDraw do the parsing for you, and then have your own code called just for what you want to look at.
All you have to do is install your own commentProc in the bottleneck procs, as in:
qdp := NewPtr(SIZEOF(QDProcs));
SetStdProcs(qdp^);
(* set default values *)
qdp^.commentProc := @MyComment;
(* install our interpreting routine *)
grafPort^.grafProcs := qdp;
The calling sequence for your comment-interpreting proc is the same as for the StdComment procedure:
PROCEDURE MyComment(kind,
dataSize: INTEGER;
dataHandle: Handle);
BEGIN
CASE kind OF
END
END; {MyComment}
As you can see, this is just the inverse of the PicComment() call, with each of the parameters having the same significance.
While youre writing your own comment-reading routine, you might as well include the call
StdComment(kind, dataSize, dataHandle);
at the end of your code, just in case. You have no way of knowing what else has been installed there, but its possible some future system software might patch this to catch the sorts of things currently not supported by QuickDraw pictures.
The same process of installing your code in grafProcs is also used if you must display or record larger pictures than can be stored in memory at one time. The getPicProc and putPicProc fields redefine whats done by DrawPicture() and OpenPicture(), respectively. The correct use of spooling pictures like this is left for another time.
Conclusion
PICT resources are the standard format for Macintosh graphics, and, as such, QuickDraw provides tools that make it easier for your application to use PICTs.
The PICT format can also be expanded beyond QuickDraws definition via the use of picture comments. These can be used for portably exchanging data between applications, or for storing information specific to a particular application.
If you want to know more about picture comments, see:
Macintosh Technical Note #27 (mentioned above)
Macintosh Technical Note #91, Optimizing for the LaserWriter--Picture Comments
Macintosh Technical Note #181 (mentioned above)
LaserWriter Reference (APDA, 1987)
[At the printing session of the Developer Conference, Apple reps made the strange comment that they wished the PicComment would go away. Yet they had no alternative in mind to how Quickdraw limitations could be circumvented without PicComments. They also denied any interest in Display Postscript. Finally, they had no comment on any future Apple enhancements for Quickdraw that would provide an alternative to PicComments. The print gurus inside Apple seem to be saying we should all use normal quickdraw so Apple can continue its printer independence myth, dont use PicComments, and forget that Quickdraw by itself is inadequate for todays sophisticated graphics requirements. We find this either a head in the sand attitude or Apple is working on something they dont want us to know about. Other Apple reps, when asked about this, said they may wish PicComments would go away, but they wont because they are necessary and everything would break if they did. -Ed]
Num Name Description
100 picAppComment Application-specific comment
130 picDwgBeg Beginning and end
131 picDwgEnd of a MacDraw picture
140 picGrpBeg Beginning and end
141 picGrpEnd of grouped objects
142 picBitBeg Beginning and end of
143 picBitEnd a banded bitmap
150 picTextBegin Beginning of text string
Specify text rotation
151 pictTextEnd End of a text string
154 picTextCenter Specify center of rotation
152 picStringBegin Beginning and end of
153 picStringEnd a banded string (archaic)
160 picPolyBegin Beginning and end of a
161 picPolyEnd MacDraw-style polygon
170 picArrw1 Arrowhead on 2nd point of line
171 picArrw2 Arrowhead on 1nd point of line
172 picArrw3 Arrowhead on both endpoints
173 picArrwEnd End of arrowhead comment
192 picPostScriptHandle PostScript picture comments
12345 picLasso Selected bitmap is lassod
Table 1: Application picture comments