TweetFollow Us on Twitter

Volume Number:3
Issue Number:9
Column Tag:Bit Map Graphics

A FatBits Editor & Clipboard Viewer in C

By Tom Saxton, University of Utah, Salt Lake City, UT

Editing BitMaps

At the heart of high-speed graphics on the Macintosh is the bitMap structure. Data stored in bitMaps and pushed around with CopyBits form the basis for much of the drawing that occurs on the Macintosh screen. Being able to create bitMaps for inclusion into a program and being able to eidt such things is of great importance in many applications. MacPaint, and offspring, offer a way of doing this which is less than ideal for small bitMaps. The following program sets up a bitMap, allows the user to edit the bitMap in a manner similar to FatBits in MacPaint, then writes out the bitMap data in hexadecimal in a format suitable for RMaker.

Fig. 1 Our bit map editor at work

There are numerous variations possible. With a call to SFGetFile(), followed by some Resource Manager calls, the user could open up any resource file and then open up any of several types of resource based on bitMaps, such as ICONs, and PATs and edit them. It would also be possible to edit objects such as ICN#’s and CURS’s, which consists of slightly more complicated data structures. With some modification, this program could also form the basis for a FatBits feature in a bit-mapped graphics program. One could also give the user a dialog box with which to set the size of the desired bitMap, initialize a data structure to hold the requested bitMap, then let the user edit it. When done, the program would then dump the bitMap out in hex, which could then be put into a program as data for a CopyBits call to draw figures on the screen. Instead of writing the bitMap to a disk file, the edited bitMap could be added to a resource file in an appropriate format. It wouldn’t take much work (in principle at least!) to reproduce the ICON, ICN#, PAT, and CURS editing functions of ResEdit in a much smaller program. Be careful when fiddling around with resource files, Scott Knaster’s “How to Write Macintosh Software,” (Hayden Books) has some invaluable tips and hints. This program was originally written over a year ago with that in mind, but I kept crashing the system with my Resouce manager calls. I’m almost brave enough to give it another try after reading Knaster’s book.

The Bit Map Object

In what follows, we will be working with a bitMap whose number of rows and columns are ‘nRows’ and ‘nCols’ respectively. In C we represent the BitMap structure as

struct BitMap {
 QDPtr  baseAddr;
 short  rowBytes;
 Rect   bounds;
typedef struct BitMap;

“baseAddr” is a pointer to the BitMap’s raw data. “rowBytes” is the number of bytes in each row of the bitMap. There must be an even number of bytes in each row, so we have to pad BitMaps whose width is not a multiple of 16 bits. To calculate rowBytes from the number of columns in a BitMap, we use the following formula:

rowBytes = ( (nCols-1)/16 + 1 ) * 2;

The size needed to store the data for the BitMap is then rowBytes*nRows.

“bounds” is a rectangle which determines the QuickDraw coordinates put onto the BitMap. The coordinates of the upper left corner of bounds become the coordinates of the upper left corner of the BitMap. Also,

bounds.bottom = + nRows;
bounds.right = bounds.left + nCols;

For simplicity, I assign = bounds.left = 0.

Once we know the size of the desired BitMap in terms of nRows and nCols, we know how much memory to allocate and how to fill in the BitMap data structure. The routine getMap() does these things. To alter the size of the BitMap, and/or its initial contents alter getMap(). For this example, I build a 32 x 32 bitMap, then load in ICON #1 (from the System file), which is the ‘NoteIcon’ used in the NoteAlert. Since I call DetachResource() on the handle I get, any editing done on the ICON will have no effect on the actual resource. In a real-life situation, you would probably want to make a copy of the ICON, so as to not clobber something which might be in use by a desk accessory.

Editing the Bit Map

After the BitMap is called, we call editMap() which sets up a window for editing the BitMap then goes into an event loop. Mouse clicks are passed to editBits(), which is the heart of the program. Activate events are handled in a very simplistic way which would need to be beefed up to support multiple windows. Update events for the window are processed by doUpdate(), the other routine of interest. Since there are no other windows with which to generate update events (after the first one), if the user hits the backspace key, an update event is generated, just to make sure doUpdate() works correctly after the bitMap has been edited.

editBits() takes a BitMap and a window pointer. It assumes that the BitMap is currently displayed in the window and that the mouse has just been pressed within the window. It then calculates where the mouse was pressed and what bit of the BitMap is represented by the location of the mouse click. It then accesses the BitMap through GetPixel() to determine if that bit is on or off. If it was off, the routine tracks the mouse and turns on every bit it runs across until the mouse is released. If the first bit was already on, it turns contacted bits off. As the mouse moves around, the routine constantly calculates what bit in the BitMap is being hit. If the current bit needs to be changed, it is changed as is the rectangle that represents it in the window.

When the close box on the window is clicked, the program calls SFPutFile() to get a destination file, then outputs the contents of the bit map in an RMaker format which could then be used to generate a resource with the BitMap data. The resource format is one that I made up. It consists of two two-byte integers representing the the number of rows and columns, followed by the (possibly padded) BitMap data, one row on each line. It would be quite easy to modify this code to put out data for an ICON, or ICN#, or other existing resource type. As mentioned earlier, the edited bitMap could also be put directly into a resource file.

The FatBitsFeature

To implement a FatBits feature into a graphics program, it would probably be easiest to copy the selected bits to a fresh BitMap, let the user edit them, then copy them back into the document. Alternatively, one could edit the larger BitMap directly, but modify editBits() to edit only some sub-rectangle of the BitMap and to deal with the fact that the upper left hand corner of what is being edited may not be the ( 0, 0 ) pixel of the BitMap, and that the boundaries of the window may not coincide with the boundaries of the BitMap (this last item is important when tracking the mouse).

To edit ICN#’s, which consist of two ICON’s, I would put each ICON into a separate BitMap, and then put the two BitMaps in side-by-side FatBits in a common window. Then mouse tracking is a little trickier, you have to figure out which ICON the mouse was pressed in and the upper left corner of the second ICON will not be in the upper left corner of the window. Similar things can be said of CURS’s, with the additional task of figuring our how to deal with the hotSpot.

Add this to the articles on displaying MacPaint files (by Gary Palmer), and drawing with the mouse (by Bob Gordon) from the May ’87 issue, and Joel West’s printing article from March, throw in some mechanism for scrolling and you have just about all of the technology needed to write a Paint program.




#define PixelWidth 4
#define PixelHeight4

WindowPtr theWindow;
EventRecord theEvent;

short   nRows,
char    theString[256];

char  *hexDigits = “0123456789ABCDEF”,
 *string1 = “\Ptype BMAP=GNRL\r,128\r”,
 *string2 = “\P.I ;; nRows \r”,
 *string3 = “\P.I ;; nCols \r”,
 *string4 = “\P\r”,
 *string5 = “\P.H ;; the BitMap data itself \r”;

 Ptr    theData;

 theData = getMap();
 if ( theData NEQ NULL ) {
 editMap( theData );
 writeMap( theData );
} /* main */

 InitGraf ( &thePort );
 InitDialogs ( NULL );
} /* initialize */

 Allocates memory for the requested bitmap
 register Ptr  theData;
 register short  i;
 Handle tempHandle;
 Size theMapSize;
 nRows = nCols = 32;

 tempHandle = GetResource ( ‘ICON’, noteIcon );
 if ( tempHandle EQ NULL )
 return NULL;
 DetachResource ( tempHandle );
 HLock ( tempHandle );
 return *tempHandle;

} /* getMap */

editMap ( theData )
 BitMap theBitMap;
 Rect   wRect;
 short  thePart;
 char   theChar;

 /*Create window to display BitMap in FatBits*/
 SetRect ( &wRect, 50, 50, 50+nCols*PixelWidth,
 50+nRows*PixelHeight );
 theWindow = NewWindow ( &wRecord, &wRect,
 “\PBitMap Editor”, TRUE, 4, -1L, TRUE, 0L );

 /*initialize the BitMap record using the theData */
 theBitMap.baseAddr = theData;
 theBitMap.rowBytes = ( ((nCols - 1) / 16) + 1) * 2;
 SetRect ( &theBitMap.bounds, 0, 0, nCols, nRows );

 /* process mouse until user dismisses window */
 done = FALSE;
 do {
 if ( GetNextEvent ( everyEvent, &theEvent ) ) {
 switch ( theEvent.what ) {
 case mouseDown:
 thePart = FindWindow ( theEvent.where,
 &wWindow );
 if ( wWindow EQ theWindow ) {
 switch ( thePart ) {
 case inContent:
 editBits ( theWindow, &theBitMap );
 case inGoAway:
 if ( TrackGoAway ( wWindow,
 theEvent.where ) ) {
 HideWindow ( wWindow );
 done = TRUE;
 } /* switch ( thePart ) */
 } /* if wWindow EQ theWindow */

 case keyDown:
 theChar = theEvent.message; 
 switch ( theChar ) {
 case BS:
 /* force update event */
 EraseRect ( &theWindow->portRect );
 InvalRect ( &theWindow->portRect );
 case RETURN:
 case ENTER:
 done = TRUE;

 case activateEvt:
 SetPort ( theEvent.message );

 case updateEvt:
 doUpdate ( theWindow, &theBitMap );
 } /* switch ( theEvent.what ) */
 } /* if GetNextEvent() */
 } while ( NOT done );

} /* editMap */

doUpdate ( badWindow, theBitMap )
WindowPtr badWindow;
BitMap  *theBitMap;
 register char *theData;
 register short  j, k, rowBytes;
 register char tempChar;
 short  i;
 Rect pixelRect;
 GetPort ( &savePort );
 SetPort ( badWindow );

SetRect ( &pixelRect, 1, 1, PixelWidth, PixelHeight );

 theData = theBitMap->baseAddr;
 rowBytes = theBitMap->rowBytes;
 BeginUpdate ( badWindow );
 /* Draw grid dots  */
 for ( k = 0; k <= nRows; k++ ) {
 MoveTo ( 0, k*PixelHeight );
 for ( i = nCols; i >= 0; i-- ) {
 Move ( PixelWidth, 0 );
 Line   ( 0, 0 );
 /* Fill in contents of current BitMap */
 for ( j = 0; j < nRows; j++ ) {
 for ( i = 0; i < rowBytes; i++ ) {
 tempChar = theData[i+j*rowBytes];
 for ( k = 0; k < 8; k++ ) {
 if ( tempChar bAND 0x80  )
 PaintRect ( &pixelRect );
 OffsetRect ( &pixelRect, PixelWidth, 0 );
 tempChar = tempChar << 1;
 } /* for (k) */
 } /* for (i) */
 OffsetRect ( &pixelRect, -rowBytes*8*PixelWidth,PixelHeight );
 } /* for (j) */

 EndUpdate ( badWindow );

} /* doUpdate */

editBits ( bitWindow, theBitMap )
WindowPtr bitWindow;
BitMap  *theBitMap;
 register char *theData;
 short  theError;
 Point  mouseLoc;
 Rect   pixelRect;
 short  vHit, hHit,
 dh, dv,

 /* rectangle for drawing “Fat” pixel  */
SetRect ( &pixelRect, 1, 1, PixelWidth, PixelHeight );

 /* make a register copy of theBitMap->baseAddr */
 theData = theBitMap->baseAddr;
 /* get memory for the GrafPort */
 myPort = (GrafPtr) NewPtr ( SIZEOF(GrafPort) );
 if ( MemError() ) { SysBeep(2); return; }
 /* Initialize “myPort” and install “theBitMap” */
 OpenPort ( myPort );
 SetPort  ( myPort ); /* Is this necessary? */
 SetPortBits ( theBitMap );

 mouse location is recorded and tested.  If it is
 in the active area, drawing begins, else return.
 SetPort ( bitWindow );

 GetMouse ( &mouseLoc );
 dh = ( hHit = ( mouseLoc.h )/PixelWidth ) * PixelWidth;
 dv = ( vHit = ( mouseLoc.v )/PixelHeight ) * PixelHeight;
 if(vHit < 0 OR vHit >= nRows OR hHit < 0 OR hHit >= nCols){
  /* mouseDown was not in active area */ 
 ClosePort ( myPort );
 DisposPtr ( myPort );
 SetPort ( myPort );
 BorW = GetPixel ( hHit, vHit ) ? patBic : patCopy;
 PenMode ( BorW );
 SetPort ( bitWindow );
 PenMode ( BorW );

 /* The drawing begins... */
 done = FALSE;
 do {
 if ( NOT Button() )
 done = TRUE;
 else {
 GetMouse ( &mouseLoc );
 dv = ( vHit = ( mouseLoc.v )/PixelHeight ) *                  
 dh = ( hHit = ( mouseLoc.h )/PixelWidth ) *                   PixelWidth;
 if ( vHit < 0 OR vHit >= nRows
 OR hHit < 0 OR hHit >= nCols )
 else  /* the mouse is in the drawing area  */{
 SetPort ( myPort );
 /* Does hit bit need to be modified?  */
 if ( BorW EQ (GetPixel(hHit,vHit)
 ? patBic : patCopy) ) {
 /* First, modify the “theData” 
 through “myPort” */
 MoveTo ( hHit, vHit ); Line ( 0, 0 );
 /* Then modify the (visible) window */
 SetPort ( bitWindow );
 OffsetRect ( &pixelRect, dh, dv);
 PaintRect ( &pixelRect );
 OffsetRect ( &pixelRect, -dh, -dv);
 } else
 /* For next time through the loop */ 
 SetPort ( bitWindow );
 } while ( NOT done );
 SetPort ( bitWindow );
 PenMode ( patCopy );
 ClosePort ( myPort );
 DisposPtr ( myPort );

} /* editBits */

 This routine writes out contents of the bitMap in
 hexadecimal in a format which RMaker will take.
writeMap ( theData )
register unsigned char  *theData;
 register i, j, rowBytes;
 short  theErr,
 long   writeSize;
 unsigned char theChar,

 SFPutFile ( 0x00640064,”\PSave Data File As ”,
 “\PUntitled”, NULL,&theReply);
 if ( NOT theReply.good )

 if ( theErr = FSOpen ( theReply.fName, theReply.vRefNum,&fPathNum ) 
) {
 if ( theErr NEQ fnfErr )
 if ( theErr = Create ( theReply.fName,
 theReply.vRefNum, ‘BmEd’, ‘TEXT’ ) )
 if ( theErr = FSOpen ( theReply.fName,
 theReply.vRefNum, &fPathNum ) )

 if ( theErr = SetEOF ( fPathNum, 0L ) )
 goto err;
 if (theErr = SetFPos(fPathNum, fsFromStart, 0L))
 goto err;

 /* write type and ID number  */
 writeSize = string1[0];
 if (theErr = FSWrite (fPathNum, &writeSize, string1+1))
 goto err;

 /* write number of rows  */
 writeSize = string2[0];
if (theErr=FSWrite (fPathNum,&writeSize,string2+1))
 goto err;
 NumToString ( (long) nRows, theString );
 writeSize = theString[0];
if (theErr=FSWrite (fPathNum,&writeSize,theString+1))
 goto err;
 writeSize = string4[0];
 if (theErr=FSWrite(fPathNum,&writeSize,string4+1))
 goto err;

 /* write number of cols  */
 writeSize = string3[0];
 if (theErr=FSWrite(fPathNum,&writeSize,string3+1))
 goto err;
 NumToString ( (long) nCols, theString );
 writeSize = theString[0];
if (theErr=FSWrite(fPathNum,&writeSize,theString+1))
 goto err;
 writeSize = string4[0];
 if (theErr=FSWrite(fPathNum,&writeSize,string4+1))
 goto err;

 rowBytes = ( ( nCols - 1 ) / 16 + 1 ) * 2;
 writeSize = string5[0];
 if (theErr=FSWrite(fPathNum,&writeSize,string5+1))
 goto err;
 for (i = 0; i < nRows; i++ ) {
 writeSize = 2;
 for ( j = 0; j < rowBytes; j++ ) {
 theChar = theData[i*rowBytes+j];
 oneWord[1] = hexDigits [ theChar bAND 0x0F ];
 oneWord[0] = hexDigits [ theChar >> 4 ];
 if (theErr=FSWrite(fPathNum,&writeSize, oneWord))
 goto err;
 writeSize = string4[0];
 if (theErr=FSWrite(fPathNum,&writeSize, string4+1))
 goto err;
 writeSize = string4[0];
 if (theErr=FSWrite(fPathNum,&writeSize,string4+1))
 goto err;

 I hate goto’s but seemed slickest way to do
 what I wanted with minimal effort.
 err: /* close the file and return */
 FSClose ( fPathNum );

} /* writeMap */

/* #definitions to make life easier and C more readable */

/* Inside Macintosh #defines not in MacTypes  */
typedef short  INTEGER;
typedef longLONGINT;

/* Constants */
#define NULL0L

/* Logical Operators */
#define NOT !
#define AND &&
#define OR||
#define MOD %
#define EQ==
#define NEQ !=
#define bAND&
#define bOR |
#define bXOR^

/* Misc Operators */
#define SIZEOF(x) (long)sizeof(x)

/* Math things */
#define abs(x) (((x)<0)?-(x):(x))

/* these are defined in LightSpeed’s math.h
#define PI3.14159265358979323846
#define E 2.71828182845904523536

/* special character codes  */
#define CR0x0D
#define RETURN CR
#define CLOVER 0x11
#define TAB 0x09
#define BS0x08
#define ENTER  0x03
#define APPLE  0x14
#define SPACE  0x20
#define DIAMOND  0x13

Comments on Past Issues

Several things in the last few months of “Letters” and “Mousehole Report” departments have caught my eye and seemed in need of a comment or two. I have also had a bug/feature of the dialog manager brought to my attention in the form of an annoying side-effect in one of my ShareWare programs.

In the February ’87 MacTutor, there was a letter from Jean-Michael Decombe that came complete with a couple of very handy routines. His method for writing to the data fork of the current application is much slicker than what I have been using. His routine for zooming rects is also pretty handy, with a couple of caveats. According to IM, p. I-282, thou shalt not change any regions of the Window Manager Port, else “overlapping windows may not be handled properly.” I think his call to InitPort ( deskPort ) violates that commandment. Also, he returns the wMgrPort’s pen to what we all expect it should be, which seems a bit dangerous. I use the following:

GetPort ( &savePort );  /* get current port */
GetWMgrPort ( &deskPort ); /* get wMgrPort */
SetPort ( deskPort );   /* make it ‘thePort’ */
GetPenState ( &savePen ); /* save pen character */
PenMode ( notPatXor ); /* modify pen for our needs */
PenPat ( &gray );

/* zoom those rects  */

SetPenState ( &savePen ); /*retore penState*/
SetPort ( savePort );   /* restore original port */

Thanks to Jean-Michael for a couple of otherwise great routines.

In the Mousehole Report of that same issue, “Beaker” asked for a ‘TE TextBox routine’ that does not share the inefficiencies of the ROM routine. I wrote a portable “Show Clipboard” function which does its own word-wrapping which will probably fit the bill, with minor modification, shown in the next few pages.

In the May ’87 MacTutor, there was a commentary from “Zenomorph” concerning disk interleaving on the Mac II. It is my understanding that SCSI disks have to be interleaved on the Mac because they tend to send information faster than the Mac can keep up with for more than a sector at a time. Floppy drives are apparently much slower and don’t need to be artificially slowed down by interleaving. Thus it is not surprising that a Mac, a Mac SE and a Mac II can all read the same floppies. Am I off track (pardon the pun)? Has anyone tried running a SCSI drive off of a Mac, Mac SE and a Mac II? Will a SCSI drive intended for a Mac+ automatically change its interleaving if reformatted on an SE or a II?

In the June ’87 issue, “Chief Wizard” responds to a question concerning _SystemTask. He states that _SystemTask handles blinking the cursor. While this is true, indirectly, of dialog boxes owned by Desk Accessories, _TEIdle handles blinking the caret in TextEdit records managed by the application.

Also in the June issue, “Ram Warrior” asks questions concerning MPW and the Font Manager. The problem seemed to deal more directly with the Menu Manager, in particular the SetItemMark() routine. I ran into a problem with GetItemMark() that took some time to figure out, and resulted in symptoms similar to those described by Ram Warrior. According to IM, page I-359, the calls to the two routines look like:

GetItemMark ( theMenu:MenuHandle,
 item:INTEGER, VAR markChar:CHAR );

This isn’t quite the case. It is impossible to put a single byte onto the stack; markChar will be extended to a word before being pushed onto the stack. Since compilers do this automatically, you’ll never notice this. On the other hand, if you declare markChar to be a one-byte variable, then pass a pointer to it, some compilers will do exactly that: allocate one byte of space on the local stack frame and pass a pointer to that byte. However, GetItemMark() actually expects to be handed a pointer to a word, with markChar to be placed in the high (least significant) byte. So passing a pointer to a single byte, results in the item’s mark information being stuffed into the next byte of memory, whatever that happens to be. The upshot is that you have to declare markChar to be a 2-byte quantity (INTEGER, for instance), and look for the item’s mark information in the high byte, otherwise not only do you not get the information you requested, you trash some innocent bystander, which most likely will cause you grief elsewhere. I don’t know if this has any bearing on Ram Warrior’s problem, but others may find this bit of MacTrivia helpful.

Finally, a problem of my own. I have a program, “GraphToolz,” that allows the user to type in an equation for a function, which may then be graphed (among other things). To enter the function, the user is presented with a dialog box which contains an EditText item. In order to make as many people comfortable with the program as possible, I allow BASIC-style formulas to be entered, in particular exponentiation may be denoted by the ‘^’ character. Thus someone may enter “x^2+3”, meaning x squared plus three. This works just fine until we switch to another dialog box which displays the user’s function in a StaticText item; it appears as “x+3”; the ^ and the 2 disappear. This is cosmetic only, and the same thing may be entered in the Fortran style as “x**2+3” but it is sort of annoying. After not thinking about it for a while, I realized that the Dialog Manager saw the ^2 as an invitation to do a little text substitution ala ParamText(). So, I did the obvious thing inserted the following lines just before opening the offending dialog box:

ParamText ( “\P^0”, “\P^1”, “\P^2”, “\P^3” );

I figured that I could trick the Dialog Manager into substituting in exactly what it was replacing. But no, the ROMs are smarter than that and caused the Mac to hang. So I ended up adding the (mathematically equivalent)

ParamText ( “\P**0”, “\P**1”, “\P**2”, “\P**3” );

which sort of solves the immediate problem. I am in the midst of writing a routine to support real TextEdit records in a dialog box via the userItem mechanism.

Show Clipboard Function with Custom TextBox Routine

by Tom Saxton

In several situations it is desirable to avoid TextEdit when displaying text. As an application of the necessary technology, I have written a Show Clipboard function which displays text without any help from the TE routines. Basically the only trick is to write your own word-wrapping routine.

Once this is done, you have a fairly compact little routine which then opens itself to easy modification. So, for instance, you may want to do something smart with tabs. This would be much easier than rebuilding the TE routines (see Bradley Nedrud’s, “Extending Text Edit for TABS” in the Nov. 1986 issue of MacTutor.) Of course, this is handy only for displaying text, you lose the ability to edit the text.

The following program is pretty simple. It builds the •, File and Edit Menus, then opens a window in which the Clipboard is displayed. Any editing operations from the DAs which change the contents of the Clipboard will be noticed and the window updated.

The word wrapping does the following. Beginning with the first character it is handed, it marches through the text character-by-character. It first checks for a carriage return. If it finds one, it prints the characters looked at so far and starts the process over, beginning with the next character. If the current character is not a carriage return, it adds the width of the current character to a running total. If that running total exceeds the width of the text rectangle, it backs up to the last word break and prints the line, then starts the process over. If the current character is not a CR and the accumulated length is not too long, then it decides if the current character is a break between words. If so, it stores the current position as a place to break. In this simple case, a character is a break between words if it is a space or a tab.

This process is repeated line-by-line until the text is exhausted, or until the bottom of the text box is reached. In the event that a line runs off the right edge of the text Rect without ever encountering a word boundary, as much of the string as possible is printed (all but the last character of the current line), and the next line is started.

Finally, since supporting the drawing of PICTs on the Clipboard adds all of about 10 lines to the code, I do that as well. The only trickery is to move the upper left corner of the picFrame to the upper left corner of hte display Rect. Alternatively, one could center the PICT in the display Rect, or scale it to fit in the display Rect. To center the PICT, do this:

drawACenteredPicture ( textWindow, dispRect, thePicture )
WindowPtr textWindow;
Rect    *dispRect;
PicHandle thePicture;
 Rect drawRect;  
 short  hMove, vMove;
 drawRect = (*thePicture)->picFrame;
 hMove = dispRect->left - drawRect.left;
 hMove += dispRect->right - drawRect.right;
 hMove /= 2;

 vMove = dispRect->top -;
 vMove += dispRect->bottom - drawRect.bottom;
 vMove /= 2;
 OffsetRect ( &drawRect, hMove, vMove );     
 DrawPicture ( thePicture, &drawRect );
} /* drawACenteredPicture */

To scale it is even easier, no OffsetRect(), just:

 DrawPicture ( thePicture, &dispRect );

A scroll bar and some I/O and one could easily write a ScrapBook-like application. 
Add horizontal and vertical scroll bars and add a couple of paramters to the drawing routines 
and you have a scrolling ScrapBook. No doubt there are many other applications of these 



#define AppleID  30
#define FileID   31
#define EditID   32

EventRecord theEvent;
WindowPtr clipWindow;

short   scrapCompare;
char    theString[256];
Boolean done;

} /* main */

 Rect wRect;

 InitDialogs( NULL );
 FlushEvents ( everyEvent, 0 );
 SetRect ( &wRect, 60, 50, 450, 250 );
 clipWindow = NewWindow( NULL, &wRect, “\PClipboard”,TRUE, 0, -1L, FALSE, 
 /* force an initial update of Clipboard window */
 scrapCompare = InfoScrap()->scrapCount + 1;
 done = FALSE;

} /* initialize */

 appleMenu = NewMenu ( AppleID, “\P\024” );
 AddResMenu ( appleMenu, ‘DRVR’);
 InsertMenu ( appleMenu, 0 );
 fileMenu = NewMenu ( FileID, “\PFile” );
 AppendMenu ( fileMenu, “\PQuit” );
 InsertMenu ( fileMenu, 0 );
 editMenu = NewMenu ( EditID, “\PEdit” );
 AppendMenu ( editMenu, “\PUndo;(-;Cut;Copy;Paste; Clear” );
 InsertMenu ( editMenu, 0 );
} /* setUpMenus */

 done = FALSE;
 do {
 /* see if scrap has changed recently  */
 if (scrapCompare NEQ InfoScrap()->scrapCount) {
 GetPort ( &savePort );
 SetPort ( clipWindow );
 InvalRect ( &clipWindow->portRect );
 SetPort ( savePort );
 scrapCompare = InfoScrap()->scrapCount;
 if (GetNextEvent ( everyEvent, &theEvent )) {
 switch ( theEvent.what ) {
 case mouseDown:
 thePart = FindWindow ( theEvent.where,                        
 &wWindow );
 switch ( thePart ) {
 case inContent:
 if ( FrontWindow() NEQ wWindow )
 SelectWindow ( wWindow );
 case inMenuBar:
 case inSysWindow:
 SystemClick ( &theEvent, wWindow );
 SysBeep ( 2 );
 } /* switch thePart */
 case keyDown:
 done = TRUE;
 case updateEvt:
 if ( (WindowPtr) theEvent.message EQ  clipWindow )
 updateClipWindow ( clipWindow );
 case activateEvt:
 if ( (WindowPtr) theEvent.message EQ  clipWindow ) {
 SetPort ( theEvent.message );
 if (theEvent.modifiers bAND activeFlag)
 DisableItem ( editMenu, 0 );
 EnableItem ( editMenu, 0 );
 } /* switch theEvent.what */
 } /* if GNE */
 } while ( NOT done );
} /* doEvents */

 long menuChoice;

 menuChoice = MenuSelect ( theEvent.where );
 doMenuChoice ( menuChoice );
} /* doMenuClick */

doMenuChoice( theMenu, theItem )
short theMenu, theItem;
 short  accNumber;
 switch ( theMenu ) {
 case AppleID:
 GetItem ( appleMenu, theItem, theString );
 accNumber = OpenDeskAcc ( theString );
 case FileID:
 if ( theItem EQ 1 )
 done = TRUE;
 case EditID:
 if ( NOT SystemEdit ( theItem - 1) )
 SysBeep ( 2 );
 } /* switch */
 HiliteMenu ( 0 );
} /* doMenuChoice */

updateClipWindow ( badWindow )
WindowPtr badWindow;
 Rect dispRect;
 Handle theHandle;
 long offset,
 theHandle = NewHandle ( 8L );
 GetPort ( &savePort );
 SetPort ( badWindow );
 BeginUpdate ( badWindow );
 EraseRect ( &badWindow->portRect );
 dispRect = badWindow->portRect;
 InsetRect ( &dispRect, 5, 5 );
 if ( (theSize = GetScrap ( theHandle,
 ‘TEXT’, &offset )) > 0 ) {
 HLock ( theHandle );
 myTextBox ( badWindow, &dispRect,
 *theHandle, theSize );
 HUnlock ( theHandle );
 } else if ( (theSize = GetScrap ( theHandle,
 ‘PICT’, &offset )) > 0 ) {
 drawAPicture ( badWindow, &dispRect,
 theHandle );
 EndUpdate ( badWindow );
 DisposHandle ( theHandle );
} /* updateClipWindow */

myTextBox (textWindow,textRect,textPtr,textLength)
WindowPtr textWindow;
Rect    *textRect;
register char  textPtr[];
long    textLength;
 register long   index;
 FontInfo theFontInfo;
 short  textHeight,
 boxWidth, boxHeight,
 theHeight, strLength;
 long   startLine, canBreak;
 TextFont ( 3 ); /* Geneva */
 TextSize ( 12 );/* 12 point */
 TextFace ( 0 ); /* Plain Text */

 GetFontInfo ( &theFontInfo );
 textHeight = theFontInfo.ascent + theFontInfo.descent+theFontInfo.leading;
 boxWidth = textRect->right - textRect->left;
 boxHeight = textRect->bottom - textRect->top;

 theHeight = textRect->top - theFontInfo.descent;
 strLength = 0;
 startLine = canBreak = -1;

 for ( index = 0; index < textLength AND theHeight <           
 boxHeight; index++ ) {
 if ( textPtr[index] EQ CR ) /* if char CR */ {
 theHeight += textHeight;
 MoveTo ( textRect->left, theHeight );
 DrawText ( textPtr, startLine+1,
 index-startLine-1 );
 strLength = 0;
 startLine = canBreak = index;
 } else /* check for word wrap */ {
 strLength += CharWidth ( textPtr[index] );
 if ( strLength > boxWidth ) {
 if ( canBreak > startLine )
 index = canBreak;
 theHeight += textHeight;
 MoveTo ( textRect->left, theHeight );
 DrawText ( textPtr, startLine+1,index-startLine-1 );
 strLength = 0;
 startLine = canBreak = index;
 } else if ( textPtr[index] EQ ‘ ‘ OR
 textPtr[index] EQ TAB )
 canBreak = index;
 } /* for index loop */
 theHeight += textHeight;
 MoveTo ( textRect->left, theHeight );
 DrawText ( textPtr, (short) (startLine+1),
 (short) (index-startLine-1) );
} /* myTextBox */
drawAPicture ( textWindow, dispRect, thePicture )
WindowPtr textWindow;
Rect    *dispRect;
PicHandle thePicture;
 Rect drawRect;
 drawRect = (*thePicture)->picFrame;
 OffsetRect ( &drawRect, - drawRect.left + 
dispRect->left, - + dispRect->top );
 DrawPicture ( thePicture, &drawRect );
} /* drawAPicture */

Fig. 2 Our show clipboard function shows what a Mac II does to cmd-shift-3 picts!


Community Search:
MacTech Search:

Software Updates via MacUpdate

Navicat Premium Essentials 12.1.25 - Pro...
Navicat Premium Essentials is a compact version of Navicat which provides basic and necessary features you will need to perform simple administration on a database. It supports the latest features... Read more
Sketch 58 - Design app for UX/UI for iOS...
Sketch is an innovative and fresh look at vector drawing. Its intentionally minimalist design is based upon a drawing space of unlimited size and layers, free of palettes, panels, menus, windows, and... Read more
ClipGrab 3.8.5 - Download videos from Yo...
ClipGrab is a free downloader and converter for YouTube, Vimeo, Facebook and many other online video sites. It converts downloaded videos to MPEG4, MP3 or other formats in just one easy step Version... Read more
Dash 4.6.6 - Instant search and offline...
Dash is an API documentation browser and code snippet manager. Dash helps you store snippets of code, as well as instantly search and browse documentation for almost any API you might use (for a full... Read more
FotoMagico 5.6.8 - Powerful slideshow cr...
FotoMagico lets you create professional slideshows from your photos and music with just a few, simple mouse clicks. It sports a very clean and intuitive yet powerful user interface. High image... Read more
Civilization VI 1.2.4 - Next iteration o...
Sid Meier’s Civilization VI is the next entry in the popular Civilization franchise. Originally created by legendary game designer Sid Meier, Civilization is a strategy game in which you attempt to... Read more
Skype - Voice-over-internet p...
Skype allows you to talk to friends, family and co-workers across the Internet without the inconvenience of long distance telephone charges. Using peer-to-peer data transmission technology, Skype... Read more
Bookends 13.2.6 - Reference management a...
Bookends is a full-featured bibliography/reference and information-management system for students and professionals. Bookends uses the cloud to sync reference libraries on all the Macs you use.... Read more
BusyContacts 1.4.0 - Fast, efficient con...
BusyContacts is a contact manager for OS X that makes creating, finding, and managing contacts faster and more efficient. It brings to contact management the same power, flexibility, and sharing... Read more
Chromium 77.0.3865.75 - Fast and stable...
Chromium is an open-source browser project that aims to build a safer, faster, and more stable way for all Internet users to experience the web. Version 77.0.3865.75: A list of changes is available... Read more

Latest Forum Discussions

See All

Yoozoo Games launches Saint Seiya Awaken...
If you’re into your anime, you’ve probably seen or heard of Saint Seiya. Based on a shonen manga by Masami Kurumada, the series was massively popular in the 1980s – especially in its native Japan. Since then, it’s grown into a franchise of all... | Read more »
Five Nights at Freddy's AR: Special...
Five Nights at Freddy's AR: Special Delivery is a terrifying new nightmare from developer Illumix. Last week, FNAF fans were sent into a frenzy by a short teaser for what we now know to be Special Delivery. Those in the comments were quick to... | Read more »
Rush Rally 3's new live events are...
Last week, Rush Rally 3 got updated with live events, and it’s one of the best things to happen to racing games on mobile. Prior to this update, the game already had multiplayer, but live events are more convenient in the sense that it’s somewhat... | Read more »
Why your free-to-play racer sucks
It’s been this way for a while now, but playing Hot Wheels Infinite Loop really highlights a big issue with free-to-play mobile racing games: They suck. It doesn’t matter if you’re trying going for realism, cart racing, or arcade nonsense, they’re... | Read more »
Steam Link Spotlight - The Banner Saga 3
Steam Link Spotlight is a new feature where we take a look at PC games that play exceptionally well using the Steam Link app. Our last entry talked about Terry Cavanaugh’s incredible Dicey Dungeons. Read about how it’s a great mobile experience... | Read more »
PSA: GRIS has some issues
You may or may not have seen that Devolver Digital just released GRIS on the App Store, but we wanted to do a quick public service announcement to say that you might not want to hop on buying it just yet. The puzzle platformer has come to small... | Read more »
Combo Quest (Games)
Combo Quest 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: Combo Quest is an epic, time tap role-playing adventure. In this unique masterpiece, you are a knight on a heroic quest to retrieve... | Read more »
Hero Emblems (Games)
Hero Emblems 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: ** 25% OFF for a limited time to celebrate the release ** ** Note for iPhone 6 user: If it doesn't run fullscreen on your device... | Read more »
Puzzle Blitz (Games)
Puzzle Blitz 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Puzzle Blitz is a frantic puzzle solving race against the clock! Solve as many puzzles as you can, before time runs out! You have... | Read more »
Sky Patrol (Games)
Sky Patrol 1.0.1 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0.1 (iTunes) Description: 'Strategic Twist On The Classic Shooter Genre' - Indie Game Mag... | Read more »

Price Scanner via

Preorder your Apple Watch Series 5 today at A...
Amazon has Apple Watch Series 5 GPS models available for preorder and on sale today for $15 off Apple’s MSRP. Shipping is free and starts on September 20th: – 40mm Apple Watch Series 5 GPS: $384.99 $... Read more
21″ iMacs on sale for $100 off Apple’s MSRP,...
B&H Photo has new 21″ Apple iMacs on sale for $100 off MSRP with models available starting at $999. These are the same iMacs offered by Apple in their retail and online stores. Overnight shipping... Read more
2018 4 and 6-Core Mac minis on sale today for...
Apple resellers are offering new 2018 4-Core and 6-Core Mac minis for $100-$150 off MSRP for a limited time. B&H Photo has the new 2018 4-Core and 6-Core Mac minis on sale for up to $150 off... Read more
Save $150-$250 on 10.2″ WiFi + Cellular iPads...
Verizon is offering $150-$250 discounts on Apple’s new 10.2″ WiFi + Cellular iPad with service. Buy the iPad itself and save $150. Save $250 on the purchase of an iPad along with an iPhone. The fine... Read more
Apple continues to offer 13″ 2.3GHz Dual-Core...
Apple has Certified Refurbished 2017 13″ 2.3GHz Dual-Core non-Touch Bar MacBook Pros available starting at $1019. An standard Apple one-year warranty is included with each model, outer cases are new... Read more
Apple restocks 2018 MacBook Airs, Certified R...
Apple has restocked Certified Refurbished 2018 13″ MacBook Airs starting at only $849. Each MacBook features a new outer case, comes with a standard Apple one-year warranty, and is shipped free. The... Read more
Sunday Sale! 2019 27″ 5K 6-Core iMacs for $20...
B&H Photo has the new 2019 27″ 5K 6-Core iMacs on stock today and on sale for up to $250 off Apple’s MSRP. Overnight shipping is free to many locations in the US. These are the same iMacs sold by... Read more
Weekend Sale! 2019 13″ MacBook Airs for $200...
Amazon has new 2019 13″ MacBook Airs on sale for $200 off Apple’s MSRP, with prices starting at $899, each including free shipping. Be sure to select Amazon as the seller during checkout, rather than... Read more
2019 15″ MacBook Pros now on sale for $350-$4...
B&H Photo has Apple’s 2019 15″ 6-Core and 8-Core MacBook Pros on sale today for $350-$400 off MSRP, starting at $2049, with free overnight shipping available to many addresses in the US: – 2019... Read more
Buy one Apple Watch Series 5 at Verizon, get...
Buy one Apple Watch Series 5 at Verizon, and get a second Watch for 50% off. Plus save $10 on your first month of service. The fine print: “Buy Apple Watch, get another up to 50% off on us. Plus $10... Read more

Jobs Board

*Apple* Mobility Pro-Store 149 - Best Buy (U...
**731985BR** **Job Title:** Apple Mobility Pro-Store 149 **Job Category:** Store Associates **Location Number:** 000149-Towson-Store **Job Description:** At Best Read more
Student Employment (Blue *Apple* Cafe) Spri...
Student Employment (Blue Apple Cafe) Spring 2019 Penn State University Campus/Location: Penn State Brandywine Campus City: Media, PA Date Announced: 12/20/2018 Date Read more
Windows/ *Apple* Technical Support Engineer...
Windows/ Apple Technical Support Engineer McLean , VA , US Apply + Be you + Be Booz Allen + Be empowered + Learn More Job Description Location: McLean, VA, US Job Read more
*Apple* Mobile Master - Best Buy (United Sta...
**725617BR** **Job Title:** Apple Mobile Master **Job Category:** Store Associates **Location Number:** 001095-Chesterfield-Store **Job Description:** **What does a Read more
Geek Squad *Apple* Master Consultation Agen...
**732415BR** **Job Title:** Geek Squad Apple Master Consultation Agent **Job Category:** Services/Installation/Repair **Location Number:** 000425-Hickory-Store **Job Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.