TweetFollow Us on Twitter

FatBits
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 = bounds.top + nRows;
bounds.right = bounds.left + nCols;

For simplicity, I assign bounds.top = 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.

{1}
#include<abc.h>

#include<MacTypes.h>
#include<QuickDraw.h>
#include<EventMgr.h>
#include<WindowMgr.h>
#include<DialogMgr.h>
#include<MemoryMgr.h>
#include<ResourceMgr.h>
#include<StdFilePkg.h>
#include<FileMgr.h>

PtrgetMap();

#define PixelWidth 4
#define PixelHeight4

WindowRecordwRecord;
WindowPtr theWindow;
EventRecord theEvent;

short   nRows,
 nCols;
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”;

main()
{
 Ptr    theData;

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

initialize()
{
 InitGraf ( &thePort );
 InitFonts();
 InitWindows();
 InitMenus();
 TEInit();
 InitDialogs ( NULL );
 InitCursor();
} /* initialize */

/*
 Allocates memory for the requested bitmap
*/
Ptr
getMap()
{
 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 )
PtrtheData;
{
 WindowPtrwWindow;
 BitMap theBitMap;
 Rect   wRect;
 Booleandone;
 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 );
 break;
 case inGoAway:
 if ( TrackGoAway ( wWindow,
 theEvent.where ) ) {
 HideWindow ( wWindow );
 done = TRUE;
 }
 } /* switch ( thePart ) */
 } /* if wWindow EQ theWindow */
 break;

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

 case activateEvt:
 SetPort ( theEvent.message );
 break;

 case updateEvt:
 doUpdate ( theWindow, &theBitMap );
 break;
 } /* 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;
 GrafPtrsavePort;
 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;
 GrafPtrmyPort;
 short  theError;
 Point  mouseLoc;
 Rect   pixelRect;
 short  vHit, hHit,
 dh, dv,
 BorW;
 Booleandone;

 /* 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 );
 SysBeep(2);
 return;
 }
 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 ) *                  
 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;
 SFReplytheReply;
 short  theErr,
 fPathNum;
 long   writeSize;
 unsigned char theChar,
 oneWord[2];

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

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

 }
 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 );
 return;

} /* 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:

SetItemMark(theMenu:MenuHandle,item:INTEGER,markChar:CHAR);
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:

{2}
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 - drawRect.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 
ideas.

#include<abc.h>

#include<MacTypes.h>
#include<Quickdraw.h>
#include<WindowMgr.h>
#include<EventMgr.h>
#include<MenuMgr.h>
#include<DeskMgr.h>
#include<ScrapMgr.h>

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

MenuHandleappleMenu,
 fileMenu,
 editMenu;
EventRecord theEvent;
WindowPtr clipWindow;

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

main()
{
 initialize();
 doEvents();
} /* main */

initialize()
{
 Rect wRect;

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

} /* initialize */

setUpMenus()
{
 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 );
 DrawMenuBar();
 
} /* setUpMenus */

doEvents()
{
 WindowPtrwWindow;
 GrafPtrsavePort;
 INTEGERthePart;
 
 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 );
 break;
 case inMenuBar:
 doMenuClick();
 break;
 case inSysWindow:
 SystemClick ( &theEvent, wWindow );
 break;
 default:
 SysBeep ( 2 );
 break;
 } /* switch thePart */
 break;
 case keyDown:
 done = TRUE;
 break;
 case updateEvt:
 if ( (WindowPtr) theEvent.message EQ  clipWindow )
 updateClipWindow ( clipWindow );
 break;
 case activateEvt:
 if ( (WindowPtr) theEvent.message EQ  clipWindow ) {
 SetPort ( theEvent.message );
 if (theEvent.modifiers bAND activeFlag)
 DisableItem ( editMenu, 0 );
 else
 EnableItem ( editMenu, 0 );
 }
 break;
 } /* switch theEvent.what */
 } /* if GNE */
 } while ( NOT done );
} /* doEvents */

doMenuClick()
{
 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 );
 break;
 case FileID:
 if ( theItem EQ 1 )
 done = TRUE;
 break;
 case EditID:
 if ( NOT SystemEdit ( theItem - 1) )
 SysBeep ( 2 );
 break;
 default:
 break;
 } /* switch */
 
 HiliteMenu ( 0 );
 
} /* doMenuChoice */

updateClipWindow ( badWindow )
WindowPtr badWindow;
{
 GrafPtrsavePort;
 Rect dispRect;
 Handle theHandle;
 long offset,
 theSize;
 
 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;
 else
 index--;
 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, - drawRect.top + 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

Latest Forum Discussions

See All

Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.