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

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Senior Product Associate - *Apple* Pay (AME...
…is seeking a Senior Associate of Digital Product Management to support our Apple Pay product team. Labs drives innovation at American Express by originating, Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.