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!

 
AAPL
$98.38
Apple Inc.
-0.64
MSFT
$43.89
Microsoft Corpora
-0.09
GOOG
$585.61
Google Inc.
-4.99

MacTech Search:
Community Search:

Software Updates via MacUpdate

Drive Genius 3.2.4 - Powerful system uti...
Drive Genius is an OS X utility designed to provide unsurpassed storage management. Featuring an easy-to-use interface, Drive Genius is packed with powerful tools such as a drive optimizer, a... Read more
Vitamin-R 2.15 - Personal productivity t...
Vitamin-R creates the optimal conditions for your brain to work at its best by structuring your work into short bursts of distraction-free, highly focused activity alternating with opportunities for... Read more
Toast Titanium 12.0 - The ultimate media...
Toast Titanium goes way beyond the very basic burning in the Mac OS and iLife software, and sets the standard for burning CDs, DVDs, and now Blu-ray discs on the Mac. Create superior sounding audio... Read more
OS X Yosemite Wallpaper 1.0 - Desktop im...
OS X Yosemite Wallpaper is the gorgeous new background image for Apple's upcoming OS X 10.10 Yosemite. This wallpaper is available for all screen resolutions with a source file that measures 5,418... Read more
Acorn 4.4 - Bitmap image editor. (Demo)
Acorn is a new image editor built with one goal in mind - simplicity. Fast, easy, and fluid, Acorn provides the options you'll need without any overhead. Acorn feels right, and won't drain your bank... Read more
Bartender 1.2.20 - Organize your menu ba...
Bartender lets you organize your menu bar apps. Features: Lets you tidy your menu bar apps how you want. See your menu bar apps when you want. Hide the apps you need to run, but do not need to... Read more
TotalFinder 1.6.2 - Adds tabs, hotkeys,...
TotalFinder is a universally acclaimed navigational companion for your Mac. Enhance your Mac's Finder with features so smart and convenient, you won't believe you ever lived without them. Tab-based... Read more
Vienna 3.0.0 RC 2 :be5265e: - RSS and At...
Vienna is a freeware and Open-Source RSS/Atom newsreader with article storage and management via a SQLite database, written in Objective-C and Cocoa, for the OS X operating system. It provides... Read more
VLC Media Player 2.1.5 - Popular multime...
VLC Media Player is a highly portable multimedia player for various audio and video formats (MPEG-1, MPEG-2, MPEG-4, DivX, MP3, OGG, ...) as well as DVDs, VCDs, and various streaming protocols. It... Read more
Default Folder X 4.6.7 - Enhances Open a...
Default Folder X attaches a toolbar to the right side of the Open and Save dialogs in any OS X-native application. The toolbar gives you fast access to various folders and commands. You just click... Read more

Latest Forum Discussions

See All

Note Review
Note Review By Jennifer Allen on July 29th, 2014 Our Rating: :: TOO SIMPLEiPhone App - Designed for the iPhone, compatible with the iPad Note is a note taking app that’s a little too short on features to be worth its asking price... | Read more »
Chainsaw Warrior Goes on Sale & Ther...
Chainsaw Warrior Goes on Sale & There’s a Chance to Win a Copy of the Original Board Game Posted by Jennifer Allen on July 29th, 2014 [ permalink | Read more »
It Came From Canada: Tiny Tower Vegas
If you go to a casino, you might make a lot of money. If you run a casino, you’re guaranteed to make a lot of money. The choice seems pretty obvious. So while waiting for your shady real estate deals to move forward, get prepared with Tiny Tower... | Read more »
Z Hunter Review
Z Hunter Review By Lee Hamlet on July 29th, 2014 Our Rating: :: RIGHT ON TARGETUniversal App - Designed for iPhone and iPad While it might not necessarily break new ground, Z Hunter has enough tricks up its sleeve to ensure that... | Read more »
Huge Update Comes To Duet, Adding 48 New...
Huge Update Comes To Duet, Adding 48 New Stages Posted by Jennifer Allen on July 29th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Sharknado: The Video Game Available Now....
Sharknado: The Video Game Available Now. Seriously. Posted by Rob Rich on July 29th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Frog Orbs 2 Review
Frog Orbs 2 Review By Nadia Oxford on July 29th, 2014 Our Rating: :: THIS MAGIC IS A TAD MONOTONOUS Universal App - Designed for iPhone and iPad Frog Orbs 2 is repetitive, but younger players should enjoy it nonetheless.   | Read more »
Puzzix Review
Puzzix Review By Jennifer Allen on July 29th, 2014 Our Rating: :: NICE IDEAUniversal App - Designed for iPhone and iPad A little like Tetris, Puzzix is all about piecing together blocks and watching them vanish. It could do with... | Read more »
Cannonball eMail is Now Live – Works Wit...
Cannonball eMail is Now Live – Works With Gmail, Yahoo, Outlook, Hotmail, and AOL Posted by Jessica Fisher on July 29th, 2014 [ permalink ] | Read more »
To The End Review
To The End Review By Lee Hamlet on July 29th, 2014 Our Rating: :: A VICIOUS CYCLEUniversal App - Designed for iPhone and iPad To The End will test players’ patience, timing, and dedication as they try to navigate all 13 levels in... | Read more »

Price Scanner via MacPrices.net

The lowest prices on leftover Retina MacBook...
Best Buy has dropped prices on leftover 13″ and 15″ Retina MacBook Pros by up to $300 off original MSRP on their online store for a limited time. Choose free local store pickup (if available) or free... Read more
Apple Updates MacBook Pro with Retina Display...
Apple today updated its MacBook Pro with Retina display with faster processors and double the amount of memory in both entry-level configurations. MacBook Pro with Retina display features a Retina... Read more
Up to $250 price drop on leftover 15-inch Mac...
B&H Photo has dropped prices on 2013 15″ Retina MacBook Pros by as much as $250 off original MSRP. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.3GHz Retina MacBook Pro: $2349... Read more
Updated MacBook Pro Price Trackers
We’ve updated our MacBook Pro Price Trackers with the latest information on prices, bundles, and availability on the new 2014 models from Apple’s authorized internet/catalog resellers as well as... Read more
Apple updates MacBook Pros with slightly fast...
Apple updated 13″ and 15″ Retina MacBook Pros today with slightly faster Haswell processors. 13″ models now ship with 8GB of RAM standard, while 15″ MacBook Pros ship with 16GB across the board. Most... Read more
Apple drops price on 13″ 2.5GHz MacBook Pro b...
The Apple Store has dropped their price for the 13″ 2.5GHz MacBook Pro by $100 to $1099 including free shipping. Read more
Apple drops prices on refurbished 2013 MacBoo...
The Apple Store has dropped prices on Apple Certified Refurbished 13″ and 15″ 2013 MacBook Pros, with model now available starting at $929. Apple’s one-year warranty is standard, and shipping is free... Read more
iOS 8 and OS X 10.10 To Support DuckDuckGo As...
Writing for Quartz, Dan Frommer reports that Apple’s forthcoming iOS 8 and OS X 10.10 operating systems version updates will allow users to select DuckDuckGo as their default search engine. He notes... Read more
U.K. Hospital Using iPods and iPads To Record...
British news journal GazetteLive’s. Ian McNeal notes that the old “an apple a day keeps the doctor away” proverb is being turned on its head at http://southtees.nhs.uk/hospitals/james-cook/ James... Read more
13-inch 2.5GHz MacBook Pro on sale for $1099,...
Best Buy has the 13″ 2.5GHz MacBook Pro available for $1099.99 on their online store. Choose free shipping or free instant local store pickup (if available). Their price is $100 off MSRP. Price is... Read more

Jobs Board

Sr Software Lead Engineer, *Apple* Online S...
Sr Software Lead Engineer, Apple Online Store Publishing Systems Keywords: Company: Apple Job Code: E3PCAK8MgYYkw Location (City or ZIP): Santa Clara Status: Full Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Sr. Product Leader, *Apple* Store Apps - Ap...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.