TweetFollow Us on Twitter

Volume Number:6
Issue Number:7
Column Tag:Jörg's Folder

C++ micro-Draw

By Jörg Langowski, MacTutor Editorial Board

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

C++ micro-Draw

We’re going to expand on the Object Lists demo from V6#2 this month. You’ll probably have noted quite a few deficiencies to that example - it would be nice to be able to draw not only three objects at fixed places within the window, but create some kind of ‘micro-Draw’ utility where you could place as many ovals and rectangles where you like in the window, and also change their aspect.

This example, over the months, will (hopefully) evolve into a useful Draw utility. The first step towards that is to add some code which will allow us to move objects around in the window, change their drawing pattern, delete them etc. At the end of this example you will see that there are still many things left to do - we will add them in the course of the following columns. You should have copies of the preceding example code ready at hand, because we don’t want to reprint everything from scratch each time. The listing at the end gives only the changes that were made compared to the code in V6#2.

Cleaning up the lists

The first thing that we have to take care of is the removal of objects and lists when a document is closed. This was not done in the original example. When a window is closed, the document destructor is called:


{delete fObjList;
 HideWindow(fDocWindow);  }

and thus, the associated object list will be deleted. However, the objects in it still float around in the heap, since they have been created with new and have not been deleted explicitly! Therefore, we have to define a destructor for the object list as well, in which each object in the list is deleted:


 TObjLink* temp;
 while (fHeader != nil) 
 temp = fHeader->GetNext();
 delete fHeader->GetmyObj();
 delete fHeader;
 fHeader = temp;
 fNumObjs = 0;

This code will clean up properly after us when we close a window.

Creating and Deleting Objects

The next feature that we’d like to add is to be able to position objects by clicking in the window. We can select from the menu what type of object we want; the cursor will then change to a cross, and the object will be placed in the window at the point where we clicked.

To do this, we first define a new routine, ClickInWindow() (see listing); this function waits for a mouse down event and returns the location of the mouse click in the current port’s local coordinates. This routine is called by the menu selection handlers (DoMenuCommand) at the appropriate selections. The center of the object’s bounds rectangle is then set to the position of the mouse click, and the window redrawn. We have not added any means to change the size of an object yet; take this as an exercise, or wait until we give an example in this column.

To erase an object from the window, we simply click on it after the menu selection “Erase”. For implementing this behavior, we define the method FindObj(Point theLoc) which finds the object corresponding to a mouse click at a certain point in the window. This routine returns a pointer to a TDisplObj; to remove the object which we clicked at, we simply write

// 3


A good example how compact some operations can be expressed in C++.

Changing draw patterns of objects is easy, too; I have added three menu selections that allow to draw objects in either black, gray or white. Again, we find the object that was clicked at, and then set the draw pattern to a new value. For this, we need to define a new instance variable fObjPat in TDisplObj which holds the drawing pattern, and the new method SetObjPat(Pattern pat) which sets this pattern. Caution: a pattern can’t be simply assigned to another pattern variable as in


Pattern myPat = yourPat;

because Pattern is an array, it is defined as unsigned char[8]. We have to write a little loop to do the job (see listing).

Moving objects around

The last method that we add to our example this time is one that allows us to drag an object around in the window. We define a method DragObj(Point *theLoc, Rect theRect) which is called right after the mouse has been clicked at theLoc and an object has been found there. We also need to define a method that allows us to set the bounds rectangle of the object, so it can actually be moved.

DragObj will first create a new region that corresponds to the outline of the object to be dragged. It will then call the Window Manager routine DragGrayRgn to move this outline around the window. The limit and slop rectangles for the dragging routine are set to the port rectangle of the document window, passed through the parameter theRect to DragObj. This means that we cannot exceed the window’s boundaries when we drag the object.

DragGrayRgn waits until the mouse button is released and then returns a longint that contains the distances moved in the vertical and horizontal directions in its high and low words. This information is used to change the value of theLoc. When DragObj returns, theLoc will contain the new mouse coordinates. The main routine then resets the center of the object’s bounds rectangle to this position. The window is redrawn, and the object will have moved.

There is still a small bug in the dragging code; when you drag outside the limit rectangle, the object will disappear. I encourage you to find the reason for this; the bug will be resolved in the next column.

Wish list

We’re on our way to create a ‘MacTutorDraw’ application; but we still have a long way to go, of course. Things that should be added in the future are:

• scrap handling, so that copy, cut and paste are implemented;

• replacement of the selection menu by a palette window;

• changing the size and order of objects;

• implementing more objects, such as lines, arcs, polygons and text boxes;

• code for saving/restoring/printing documents.

Don’t expect all this to happen in the next column, though...

More on Forth

At the end, I would like to tell the remaining Forth enthusiasts that there is very good news regarding object-oriented extensions to Forth. I have now seen three different ways to implement NEON-compatible systems, two of which use fast subroutine-threaded code. I’ll give you news very soon. Until then, happy hacking.

Listing: Changes to the V6#2 example code

void TDocListApp::AdjustMenus(void)
 MenuHandle menu;
 Boolean undo,cutCopyClear,paste;

 TListDoc* fCurListDoc = (TListDoc*) fCurDoc;

 frontmost = FrontWindow();

 menu = GetMHandle(mFile);
 if ( fDocList->NumDocs() < kMaxOpenDocuments )
   EnableItem(menu, iNew);// New is enabled when we can open more documents 

 else DisableItem(menu, iNew);
 if ( frontmost != (WindowPtr) nil )
   EnableItem(menu, iClose);
 // Close is enabled when there is a window to close 
 else DisableItem(menu, iClose);

 undo = false; cutCopyClear = false; paste = false;
 if ( fCurListDoc == nil )
   {  // all editing is enabled for DA windows 
 undo = true;  cutCopyClear = true;
 paste = true;  }
 menu = GetMHandle(mEdit);
 if ( undo )EnableItem(menu, iUndo);
 else   DisableItem(menu, iUndo);
 if ( cutCopyClear )
   {  EnableItem(menu, iCut);
 EnableItem(menu, iCopy);
 EnableItem(menu, iClear);} 
   {  DisableItem(menu, iCut);
 DisableItem(menu, iCopy);
 DisableItem(menu, iClear); }
 if ( paste )  EnableItem(menu, iPaste);
 else   DisableItem(menu, iPaste);
 menu = GetMHandle(myMenu);
 EnableItem(menu, item1);
 EnableItem(menu, item2);
 EnableItem(menu, item3);
 EnableItem(menu, item5);
 EnableItem(menu, item7);
 EnableItem(menu, item8);
 EnableItem(menu, item9);
 EnableItem(menu, item11);
} // AdjustMenus

Point ClickInWindow()
 Point  theLoc;
 CursHandle hCurs;
 hCurs = GetCursor(crossCursor);
 while (!(Button())) {} ;
 ev = WaitNextEvent(mDownMask,&theEvent,0,0);
 theLoc = theEvent.where;
 return theLoc;

void TDocListApp::DoMenuCommand(short menuID, short menuItem)
 short  itemHit;
 Str255 daName;
 short  daRefNum;
 Rect   brect;
 Point  theLoc;
 TListDoc* fCurListDoc = (TListDoc*) fCurDoc;

 window = FrontWindow();
 switch ( menuID )
   {  case mApple:
 switch ( menuItem )
   {  case iAbout: // About box
 itemHit = Alert(rAboutAlert, nil);
 default: // DAs etc.
 GetItem(GetMHandle(mApple), menuItem, daName);
 daRefNum = OpenDeskAcc(daName);
 break; }
 case mFile:
 switch ( menuItem )
   {  case iNew: DoNew(); break;
 case iClose:
 if (fCurListDoc != nil)
   {  fDocList->RemoveDoc
 delete fCurListDoc; }
 else CloseDeskAcc(((WindowPeek)
 case iQuit:Terminate();  break; }
 case mEdit:
 // call SystemEdit for DA editing & MultiFinder 
 if ( !SystemEdit(menuItem-1) )
   {  switch ( menuItem )
   {  case iCut: break;
 case iCopy: break;
 case iPaste: break;
 case iClear: break; }
 case myMenu:
 if (fCurListDoc != nil) 
 { switch ( menuItem )
   { case item1: // TRoundRect
 theLoc.v-20, theLoc.h+40, theLoc.v+20);
 new TRoundRect(brect));
 case item2: // TOval
 theLoc.v-20, theLoc.h+40, theLoc.v+20);
 new TOval(brect));
 case item3:  // TRect
 theLoc.v-20, theLoc.h+40,
 new TRect(brect));
 case item5: // Erase
 case item7: // White
 theObj = fCurListDoc->fObjList->
 if (theObj != nil) 
 case item8: // Gray
 theObj = fCurListDoc->fObjList->
 if (theObj != nil) 
 case item9: // Black
 theObj = fCurListDoc->fObjList->
 if (theObj != nil) 
 case item11: // Move
 theObj = fCurListDoc->fObjList->
 if (theObj != nil)
 { theObj->DragObj(
 theLoc.v-20, theLoc.h+40, 
} // DoMenuCommand

// List document class
class TListDoc : public TDocument {
 void DrawWindow(void);

 TObjList*fObjList;// list of objects to be drawn
 TListDoc(short resID);
 // methods from TDocument we override
 void DoUpdate(void);

const int kMinDocDim = 40;

// create and delete the document window

TListDoc::TListDoc(short resID) : (resID)
 fObjList = new TObjList();

void TListDoc::DrawWindow(void)
{TObjLink* temp;
 if (fObjList->NumObjs() != 0)
 for (temp = fObjList->Header(); 
 temp != nil; temp = temp->GetNext())
} // DrawWindow

class TDisplObj {
 Boolean HiLiteState;// true : highlighted
 TDisplObj(Rect r);
 Rect fBoundRect;
 Pattern fObjPat;
 virtual void Draw(Pattern) 
 {DebugStr(“\pCall to TDisplObj::Draw”);}
 virtual void Erase()     
 {DebugStr(“\pCall to TDisplObj::Erase”);}
 virtual void DoContent()   
 {DebugStr(“\pCall to TDisplObj::DoContent”);}
 virtual void DoIdle() { /* do nothing by default*/ }
 Rect GetBoundRect() {return fBoundRect;}
 void SetBoundRect(Rect theRect) 
 {fBoundRect = theRect;}
 Pattern GetObjPat() {return fObjPat;}
 void SetObjPat(Pattern pat); 
 void DragObj(Point*, Rect); 

class TObjList {
 int    fNumObjs;
 TObjList(void);  ~TObjList(void);
 inline TObjLink* Header() { return fHeader; }
 inline int NumObjs() { return fNumObjs; }

 void   AddObj(TDisplObj* obj);
 void   RemoveObj(TDisplObj* obj);
 TDisplObj* FindObj(Point theLoc);

 TObjLink* temp;
 while (fHeader != nil) 
 temp = fHeader->GetNext();
 delete fHeader->GetmyObj();
 delete fHeader;
 fHeader = temp;
 fNumObjs = 0;

TDisplObj* TObjList::FindObj(Point theLoc)
 TObjLink* temp;
 Rect theRect;

 for (temp = fHeader; temp != nil; 
 temp = temp->GetNext())
 { theRect = temp->GetmyObj()->GetBoundRect();
 if (PtInRect(theLoc,&theRect))
   return (temp->GetmyObj());
 return nil;

TDisplObj::TDisplObj(Rect r)  
 { fBoundRect = r; SetObjPat(qd.gray); }

void TDisplObj::SetObjPat(Pattern pat)  
 { for (int i=0; i<8; i++) fObjPat[i] = pat[i]; }

void TDisplObj::DragObj(Point *theLoc, Rect theRect)  
 RgnHandle theRgn = NewRgn();
 long res=DragGrayRgn(theRgn,*theLoc, &theRect,&theRect,0,0);
 if (res != 0x8000)
 { theLoc->v += HiWord(res);
 theLoc->h += LoWord(res);


Community Search:
MacTech Search:

Software Updates via MacUpdate

BBEdit 11.1.1 - Powerful text and HTML e...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
CrossOver 14.1.3 - Run Windows apps on y...
CrossOver can get your Windows productivity applications and PC games up and running on your Mac quickly and easily. CrossOver runs the Windows software that you need on Mac at home, in the office,... Read more
Little Snitch 3.5.3 - Alerts you about o...
Little Snitch gives you control over your private outgoing data. Track background activity As soon as your computer connects to the Internet, applications often have permission to send any... Read more
OmniGraffle Pro 6.2.3 - Create diagrams,...
OmniGraffle Pro helps you draw beautiful diagrams, family trees, flow charts, org charts, layouts, and (mathematically speaking) any other directed or non-directed graphs. We've had people use... Read more
OmniFocus 2.2 - GTD task manager with iO...
OmniFocus helps you manage your tasks the way that you want, freeing you to focus your attention on the things that matter to you most. Capturing tasks and ideas is always a keyboard shortcut away in... Read more
Cocktail 8.4 - General maintenance and o...
Cocktail is a general purpose utility for OS X that lets you clean, repair and optimize your Mac. It is a powerful digital toolset that helps hundreds of thousands of Mac users around the world get... Read more
PDFKey Pro 4.3 - Edit and print password...
PDFKey Pro can unlock PDF documents protected for printing and copying when you've forgotten your password. It can now also protect your PDF files with a password to prevent unauthorized access and/... Read more
Kodi 15.0.beta1 - Powerful media center...
Kodi (was XBMC) is an award-winning free and open-source (GPL) software media player and entertainment hub that can be installed on Linux, OS X, Windows, iOS, and Android, featuring a 10-foot user... Read more
DiskCatalogMaker 6.4.12 - Catalog your d...
DiskCatalogMaker is a simple disk management tool which catalogs disks. Simple, light-weight, and fast. Finder-like intuitive look and feel. Super-fast search algorithm. Can compress catalog data... Read more
Macs Fan Control - Monitor and c...
Macs Fan Control allows you to monitor and control almost any aspect of your computer's fans, with support for controlling fan speed, temperature sensors pane, menu-bar icon, and autostart with... Read more

MooVee - Your Movies Guru (Entertainmen...
MooVee - Your Movies Guru 1.0 Device: iOS iPhone Category: Entertainment Price: $1.99, Version: 1.0 (iTunes) Description: MooVee helps you effortlessly manage your movies, on your iPhone. | Read more »
Geometry Wars 3: Dimensions (Games)
Geometry Wars 3: Dimensions 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: Enjoy the next chapter in the award-winning Geometry Wars franchise and enjoy stunning, console-quality... | Read more »
CHAOS RINGS Ⅲ 1.0.0 Device: iOS Universal Category: Games Price: $19.99, Version: 1.0.0 (iTunes) Description: The newest addition to the popular smartphone RPG series is finally here! ・CHAOS RINGS Overview | Read more »
The Popular Insight Series of Travel Gui...
Getting around in a country when you can't understand the primary language can be tough. Fortunately there are several options available to help wold travellers with the important stuff like giving directions to a cab driver or asking where the... | Read more »
Desktop Dungeons is Now on the iPad Desp...
Desktop Dungeons has been a well-loved roguelike on PC for quite some time, and now it's finally available for the iPad! Just the iPad, though. Sorry iPhone users. [Read more] | Read more »
Moleskine Timepage – Calendar for iCloud...
Moleskine Timepage – Calendar for iCloud, Google & Exchange 1.0 Device: iOS iPhone Category: Productivity Price: $4.99, Version: 1.0 (iTunes) Description: The most elegant calendar for your pocket and wrist, Timepage is a... | Read more »
QuizUp Gets Social in its New Update
Plain Vanilla Corp has released a new and improved version of their popular trivia game, QuizUp. The app now emphasizes social play so you can challenge friends from all over the world. [Read more] | Read more »
The Deep (Games)
The Deep 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Swipe Controls Delve into the deep in this retro rogue-like! Swipe to move your diver around and keep away from the enemies as you... | Read more »
Sproggiwood (Games)
Sproggiwood 1.2.8 Device: iOS Universal Category: Games Price: $9.99, Version: 1.2.8 (iTunes) Description: Sproggiwood was developed for devices with at least 1GB of RAM. We recommend you only download Sproggiwood if your device... | Read more »
Battle of Gods: Ascension (Games)
Battle of Gods: Ascension 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: TURN-BASED TACTICAL COMBATFight tactical battles against the forces of Hades! In Battle of Gods: Ascension you play... | Read more »

Price Scanner via

Apple refurbished 2014 13-inch Retina MacBook...
The Apple Store has Apple Certified Refurbished 2014 13″ Retina MacBook Pros available for up to $400 off original MSRP, starting at $979. An Apple one-year warranty is included with each model, and... Read more
What Would the ideal Apple Productivity Platf...
For the past four years I’ve kept a foot in both the Mac and iPad camps respectively. my daily computing hours divided about 50/50 between the two devices with remarkable consistency. However, there’... Read more
PageMeUp 1.2.1 Ten Dollar Page Layout Applica...
Paris, France-based Softobe, an OS X software development company, has announced that their PageMeUp v. 1.2.1, is available on the Mac App Store for $9.99. The license can be installed on up to 5... Read more
Eight New Products For USB Type-C Application...
Fresco Logic, specialists in advanced connectivity technologies and ICs, has introduced two new product families targeting the Type-C connector recently introduced across a number of consumer... Read more
Scripps National Spelling Bee Launches Buzzwo...
Scripps National Spelling Bee fans can monitor the action at the 2015 Spelling Bee with the new Buzzworthy app for iOS, Android and Windows mobile devices. The free Buzzworthy app provides friendly... Read more
13-inch 2.5GHz MacBook Pro on sale for $120 o...
B&H Photo has the 13″ 2.5GHz MacBook Pro on sale for $979 including free shipping plus NY sales tax only. Their price is $120 off MSRP, and it’s the lowest price for this model (except for Apple’... Read more
27-inch 3.3GHz 5K iMac on sale for $1899, $10...
B&H Photo has the new 27″ 3.3GHz 5K iMac on sale for $1899.99 including free shipping plus NY tax only. Their price is $100 off MSRP. Read more
Save up to $50 on iPad Air 2, NY tax only, fr...
B&H Photo has iPad Air 2s on sale for up to $50 off MSRP including free shipping plus NY sales tax only: - 16GB iPad Air 2 WiFi: $469 $30 off - 64GB iPad Air 2 WiFi: $549.99 $50 off - 128GB iPad... Read more
Updated Mac Price Trackers
We’ve updated our Mac Price Trackers with the latest information on prices, bundles, and availability on systems from Apple’s authorized internet/catalog resellers: - 15″ MacBook Pros - 13″ MacBook... Read more
New 13-inch 2.9GHz Retina MacBook Pro on sale...
B&H Photo has the 13″ 2.9GHz/512GB Retina MacBook Pro on sale for $1699.99 including free shipping plus NY tax only. Their price is $100 off MSRP, and it’s the lowest price for this model from... Read more

Jobs Board

*Apple* Solutions Consultant - Retail Sales...
**Job Summary** As an Apple Solutions Consultant (ASC) you are the link between our customers and our products. Your role is to drive the Apple business in a retail Read more
*Apple* Watch SW Application Project Manager...
**Job Summary** The Apple Watch software team is looking for an Application Engineering Project Manager to work on new projects for Apple . The successful candidate Read more
Engineering Manager for *Apple* Maps on the...
…the Maps App Team get to take part in just about any new feature in Apple Maps, often contributing a majority of the feature work. In our day-to-day engineering work, we Read more
Senior Software Engineer - *Apple* SIM - Ap...
Changing the world is all in a day039s work at Apple . If you love innovation, here039s your chance to make a career of it. You039ll work hard. But the job comes with Read more
Lead *Apple* Solutions Consultant - Retail...
**Job Summary** Job Summary The Lead ASC is an Apple employee who serves as the Apple business manager and influencer in a hyper-business critical Reseller's store Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.