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

Alfred 4.2 - Quick launcher for apps and...
Alfred is an award-winning productivity application for OS X. Alfred saves you time when you search for files online or on your Mac. Be more productive with hotkeys, keywords, and file actions at... Read more
MenuMeters 2.0.8 - CPU, memory, disk, an...
MenuMeters is a set of CPU, memory, disk, and network monitoring tools for Mac OS X. Although there are numerous other programs which do the same thing, none had quite the feature set I was looking... Read more
ClipGrab 3.8.15 - Download videos from Y...
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
Malwarebytes - Adware remova...
Malwarebytes (was AdwareMedic) helps you get your Mac experience back. Malwarebytes scans for and removes code that degrades system performance or attacks your system. Making your Mac once again your... Read more
Safari Technology Preview 14.1 - The new...
Safari Technology Preview contains the most recent additions and improvements to WebKit and the latest advances in Safari web technologies. And once installed, you will receive notifications of... Read more
Mactracker 7.9.7 - Database of all Mac m...
Mactracker provides detailed information on every Mac computer ever made, including items such as processor speed, memory, optical drives, graphic cards, supported OS X versions, and expansion... Read more
Tor Browser 10.0.2 - Anonymize Web brows...
The Tor Browser Bundle is an easy-to-use portable package of Tor, Vidalia, Torbutton, and a Firefox fork preconfigured to work together out of the box. It contains a modified copy of Firefox that... Read more
iTubeDownloader 6.5.24 - Easily download...
iTubeDownloader is a powerful-yet-simple YouTube downloader for the masses. Because it contains a proprietary browser, you can browse YouTube like you normally would. When you see something you want... Read more
TeamViewer 15.11.6 - Establish remote co...
TeamViewer gives you remote control of any computer or Mac over the Internet within seconds, or can be used for online meetings. Find out why more than 200 million users trust TeamViewer! Free for... Read more
ffWorks 2.1.18 - Convert multimedia file...
ffWorks, focused on simplicity, brings a fresh approach to the use of FFmpeg, allowing you to create ultra-high-quality movies without the need to write a single line of code on the command-line.... Read more

Latest Forum Discussions

See All

Lamplight City is a detective adventure...
Lamplight City is a steampunk adventure game that's available now for iOS after previously launching on PC. It sees players take on the role of private investigator Miles Fordham who is trying to get justice for his clients whilst tracking down... | Read more »
Genshin Impact Progression Guide - Mid-G...
Once you get up to around Adventure Rank 25, Genshin Impact starts to turn into a different thing. What was once a story-driven affair evolves into something more like a traditional MMO. | Read more »
Pixboy, the hit retro-themed platformer,...
Following its successful debut on PC and Nintendo Switch last summer, retro-themed platformer Pixboy has made the lead to mobile devices. The award-winning indie hit, which was developed by a two-person team at Oaky Games, has drawn comparisons to... | Read more »
Raziel: Dungeon Arena's newest char...
Raziel: Dungeon Arena's October update offers a little bit more than usual Halloween-themed outfits you often get this time of year, though those are here too. But beyond that, there is a new character, mercenary system and much more. In need of... | Read more »
Genshin Impact - Marvelous Merchant Even...
We're month since Genshin Impact's initial release, and we're already here at our second event. The Marvelous Merchant event has already been underway for two days and we have just the info you need to complete this silly scavenger hunt each day... | Read more »
Crash Bandicoot: On The Run! spins onto...
There’s a Crash Bandicoot endless runner coming to mobile sometime next spring. [Read more] | Read more »
Mulled 2 is a refreshingly simple ball-p...
Some of the greatest mobile games are actually the simplest ones, and it’s this philosophy that Mulled 2 was built on. Out now for iOS and Android, the puzzle sequel takes the accessible mechanics of its predecessor and builds on them with enticing... | Read more »
Physics-based tower defense game Goblin...
Indie developer Arif Games has released Goblin Raiders on iOS and Android. [Read more] | Read more »
PUBG Mobile has provided yet another upd...
PUBG Mobile has been making a point of publicly mentioning all of their ongoing efforts to vanquish cheating from the popular battle royale. Today two teams within the company have provided updates on their progress. [Read more] | Read more »
Zombieland: AFK Survival is celebrating...
Zombieland: AFK Survival is currently celebrating its one-year anniversary. If you don't quite recognise the name that's because it initially launched as Zombieland: Double Tapper. Anyway, the game is celebrating turning one with two Halloween-... | Read more »

Price Scanner via

Apple now offering $8000 discount on maxed Ma...
Apple’s powerful Mac Pro can be fully optioned to a max of $53,399 by choosing a 2.5GHz 28-core Xeon W CPU, 1.5TB of memory, Two Radeon Pro Vega II Duo video cards with 2x32GB memory each, 8TB of... Read more
How to save $100-$200 on a new MacBook with A...
Are you a teacher, student, or staff member of any educational institution and need a new Apple MacBook? When you purchase a new MacBook using Apple’s Education discount, Apple will take $100-$200... Read more
Amazon offers Apple Watch Series 6 and SE dis...
Amazon is among the first Apple resellers to offer sale prices on new Apple Watch Series 6 and Apple Watch SE models with models available for up to $25 off Apple’s MSRP. These are the same Watches... Read more
3rd generation 12.9″ iPad Pros available toda...
Apple restocked select 3rd generation 12.9″ WiFi iPad Pros starting at only $699 and up to $380 off original MSRP. Each iPad comes with a standard Apple one-year warranty, outer cases are new, and... Read more
Upgrading To The iPhone 12 And Making The Swi...
FEATURE: 10.28.20 – The future of wireless technology is here but before you can jump onto the 5G bandwagon, you’ll need to upgrade to a compatible device like one of the new iPhones Apple... Read more
Gazelle drops prices on Apple’s iPhone 11 mod...
Gazelle is offering a range of discounted pre-owned unlocked Apple iPhone 11 models starting at $475, with some models seeing price reductions of up to $200. iPhones are offered in Fair, Good, and... Read more
B&H Photo has 2020 13″ Dual-Core MacBook...
B&H Photo has 2020 13″ Dual-Core MacBook Airs on sale today for $100 off Apple’s MSRP, only $899. Expedited shipping is free to many addresses in the US. These MacBook Airs are the same models... Read more
New promo at Verizon: New 64GB iPhone 11 Pro...
Verizon is offering the new 64GB iPhone 11 Pro Max for free for customers switching and opening a new line of service. Qualified trade-in required, worth up to $850 credited to your account over a 24... Read more
Apple has 2020 13″ 1.4GHz MacBook Pros in sto...
Apple has Certified Refurbished 2020 13″ 1.4GHz/256GB 4-Core Touch Bar MacBook Pros available for $1099, $200 off MSRP. Apple’s one-year warranty is included, shipping is free, and each MacBook has a... Read more
Amazon offers $50 discount on all new 2020 12...
Amazon has new 2020 Apple 12.9″ iPad Pros on sale today for $50 off MSRP, with prices starting at $949. Shipping is free. These are the same iPad Pros sold by Apple in their retail and online stores... Read more

Jobs Board

Licensed Dental Hygienist - *Apple* Valley...
Park Dental Apple Valley is seeking a compassionate, professional Dental Hygienist to join our team-oriented practice. Clinical Requirements Minnesota Licensure and Read more
Deskside Support Technician - *Apple* , Wind...
Deskside Support Technician - Apple , Windows **Ref No.:** 20-01859 **Location:** Northridge, California As part of a leading IT managed services specialist with more Read more
*Apple* Computing Specialist - Best Buy (Uni...
**789374BR** **Job Title:** Apple Computing Specialist **Job Category:** Store Associates **Store Number or Department:** 000896-Atlanta GA-Store **Job Read more
Geek Squad Advanced Repair *Apple* Professi...
**789256BR** **Job Title:** Geek Squad Advanced Repair Apple Professional **Job Category:** Store Associates **Store Number or Department:** 001135-Gulf Coast-Store Read more
Cub Foods - *Apple* Valley - Now Hiring Par...
Cub Foods - Apple Valley - Now Hiring Part Time! United States of America, Minnesota, Apple Valley Retail Post Date 1 day ago Requisition # 124800 Sign Up for Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.