TweetFollow Us on Twitter

Color Basics
Column TabGetting Started

Related Info: Color QuickDraw Control Panel Gestalt Manager

The Basics of Color Quickdraw

Using a color grafport and multiple monitors

By Dave Mark, MacTech Magazine Regular Contributing Author

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

Last month’s column introduced some of the basics of C++ and object programming. This month, we’ll turn our attention back to C and the Macintosh Toolbox. This month’s column introduces one of the most enjoyable parts of the Mac Toolbox, Color QuickDraw. Along the way, we’ll learn how to use Gestalt(), the Toolbox function that knows everything there is to know about the current state of your Macintosh.

So far, about the only real experience we’ve had with color has been with a program that displayed a color PICT in a window. Since any possible color work was handled by the routine DrawPicture(), we won’t even count that as color experience. This month’s program is called ColorMondrian, a colorized version of an early Mac Primer program called Mondrian.

Mondrian created a window and drew a never-ending series of randomly generated QuickDraw shapes in the window. All this was done in the plain old black-and-white of QuickDraw version 1, the version of QuickDraw that shipped with the original 128K Macintosh.

Ever since the introduction of the Macintosh II, all Macs have shipped with a new version of QuickDraw known as Color QuickDraw, also known as 8-bit Color QuickDraw. As the technology marched on, 24-bit and then 32-bit Color QuickDraw made their way into the Toolbox. For now, we’ll concentrate on the features common to all flavors of Color QuickDraw.

ColorMondrian starts by checking to see if Color QuickDraw is available on the current Macintosh. If so, it looks at each of the displays connected to the Mac (remember, your Mac can have multiple monitors hooked up at the same time!) to determine which display is the deepest, that is, can display the largest number of colors. For example, if you have an 8-bit monitor (256 simultaneous colors) and a 1-bit monitor (black and white only), ColorMondrian will identify the 8-bit monitor as the deepest.

Next, ColorMondrian will open a color window on the specified monitor and start drawing randomly sized QuickDraw shapes in randomly selected colors. If your deepest monitor is gray-scale, don’t worry. Shades of gray count as colors too!

Let’s get started. As has been the case of late, we’ll get the program running this month, then walk through the code next month.

Creating the ColorMondrian Resources

Start by creating a folder labeled ColorMondrian in your Development folder. Next, launch ResEdit and create a new file called ColorMondrian.Π.rsrc in the ColorMondrian folder.

Create a new MBAR resource with a resource id of 128. Enter the MENU ids 128, 129, 130, and 131 as shown in Figure 1.

Figure 1. The MBAR resource.

Next, create four MENU resources. The first, having a resource id of 128, will match the menu shown in Figure 2. It’s an • menu with a single item, About ColorMondrian....

Figure 2. The • menu.

The second menu should match the one shown in Figure 3. The title is File with a single item, Be sure to add the command-key equivalent, Q.

Figure 3. The File menu.

The third menu should match the one shown in Figure 4. It’s a standard Edit menu with a single separator line and all the standard command-key equivalents.

Figure 4. The Edit menu.

The fourth menu consists of a title and no items. The title is Devices, as shown in Figure 5.

Figure 5. The Devices menu.

Next you’ll create two ALRT resources along with their respective DITLs, one for displaying error messages, and one to bring up when About ColorMondrian... is selected from the • menu. First the error ALRT. Create an ALRT resource with a resource id of 128, using the sizing info in Figure 6.

Figure 6. Specifications for the error ALRT.

Double-click on the alert window to bring up a DITL editor. Create two items, an OK button (Figure 7) and a static text item (Figure 8).

Figure 7. Specifications for the OK button.

Figure 8. Specification for the static text item.

Now create a second ALRT with a resource id of 129. using the sizing info in Figure 9.

Figure 9. Specifications for the about ALRT.

Double-click on the alert window to bring up a DITL editor. Create two items, an OK button (Figure 10) and a static text item (Figure 11).

Figure 10. Specifications for the OK button.

Figure 11. Specification for the static text item.

Creating the ColorMondrian Project

Quit ResEdit, being sure to Save your changes. Now launch THINK C and create a new project named ColorMondrian.Π in the ColorMondrian folder. Add the MacTraps and ANSI libraries to the project (In THINK 6, ANSI is inthe Standard Libraries folder - add it in its own segment), then create a new source code window. Save the window as ColorMondrian.c and Add it to the project as well.

Type in this source code, being sure to save periodically:

/* 1 */

#include <stdio.h>
#include <GestaltEqu.h>

#define kMBARResID 128
#define kErrorAlertID128
#define kAboutALRTid 129

#define kSleep   0L

#define kAutoStorage NULL
#define kVisible true
#define kWindowTitle "\pColor Mondrian"
#define kMoveToFront (WindowPtr)-1
#define kNoGoAwayfalse
#define kNULLRefCon60L

#define mApple   128
#define iAbout   1

#define mFile    129
#define iQuit    1

#define mDevice  131

#define kWindowMargin5

#define kRandomUpperLimit 32768

#define kEmptyString "\p"
#define kNULLFilterProc   NULL

/*  Globals  */

Boolean gDone;

/*  Functions  */

void    ToolboxInit( void );
void    MenuBarInit( void );
void    CreateWindow( GDHandle device );
void    EventLoop( void );
void    DoEvent( EventRecord *eventPtr );
void    HandleMouseDown( EventRecord *eventPtr );
void    HandleMenuChoice( long menuChoice );
void    HandleAppleChoice( short item );
void    HandleFileChoice( short item );
void    HandleDeviceChoice( short item );
Boolean HasColorQD( void );
GDHandleGetDeepestDevice( void );
short   GetDeviceDepth( GDHandle device );
void    DrawRandomRect( void );
void    RandomColor( RGBColor *colorPtr );
void    RandomRect( Rect *rectPtr );
short Randomize( short range );
void    DoError( Str255 errorString );

/****************** main ***************************/

void main( void )
 if ( ! HasColorQD() )
 "\pThis machine doesn't support Color Quickdraw!" );
 CreateWindow( GetDeepestDevice() );

/****************** ToolboxInit *********************/

void ToolboxInit( void )
 InitGraf( &thePort );
 InitDialogs( nil );

/****************** MenuBarInit ***********************/

void MenuBarInit( void )
 Handle menuBar;
 MenuHandle menu;
 GDHandle device, deepestDevice;
 Str255 itemStr;
 short  curDeviceNumber = 1;
 menuBar = GetNewMBar( kMBARResID );
 SetMenuBar( menuBar );

 menu = GetMHandle( mApple );
 AddResMenu( menu, 'DRVR' );
 menu = GetMHandle( mDevice );
 deepestDevice = GetDeepestDevice();
 device = GetDeviceList();
 while ( device != NULL )
 itemStr[0] = 10;
 sprintf( (char *)(&(itemStr[1])), "0x%08lX", 
 (unsigned long)device );
 AppendMenu( menu, itemStr );
 if ( device == deepestDevice )
 CheckItem( menu, curDeviceNumber, true );
 device = GetNextDevice( device );

/****************** CreateWindow ***********************/

void CreateWindow( GDHandle device )
 Rect   wBounds;
 wBounds = (**device).gdRect;
 if ( device == GetMainDevice() ) += GetMBarHeight();
 InsetRect( &wBounds, kWindowMargin, kWindowMargin );
 window = NewCWindow( kAutoStorage, &wBounds, kWindowTitle, 
 kVisible, altDBoxProc, kMoveToFront, 
 kNoGoAway, kNULLRefCon );
 if ( window == nil )
 DoError( "\pCouldn't create window!" );
 ShowWindow( window );
 SetPort( window );

/******************************** EventLoop *********/

void EventLoop( void )
 GetDateTime( (unsigned long *)(&randSeed) );
 gDone = false;
 while ( gDone == false )
 if ( WaitNextEvent( everyEvent, &event, kSleep, nil ) )
 DoEvent( &event );

/************************************* DoEvent *********/

void DoEvent( EventRecord *eventPtr )
 char   theChar;
 switch ( eventPtr->what )
 case mouseDown: 
 HandleMouseDown( eventPtr );
 case keyDown:
 case autoKey:
 theChar = eventPtr->message & charCodeMask;
 if ( (eventPtr->modifiers & cmdKey) != 0 ) 
 HandleMenuChoice( MenuKey( theChar ) );

/****************************** HandleMouseDown *********/

void HandleMouseDown( EventRecord *eventPtr )
 short  thePart;
 long   menuChoice;
 thePart = FindWindow( eventPtr->where, &window );

 switch ( thePart )
 case inMenuBar:
 menuChoice = MenuSelect( eventPtr->where );
 HandleMenuChoice( menuChoice );
 case inSysWindow : 
 SystemClick( eventPtr, window );

/****************** HandleMenuChoice ***********************/

void HandleMenuChoice( long menuChoice )
 short  menu;
 short  item;
 if ( menuChoice != 0 )
 menu = HiWord( menuChoice );
 item = LoWord( menuChoice );
 switch ( menu )
 case mApple:
 HandleAppleChoice( item );
 case mFile:
 HandleFileChoice( item );
 case mDevice:
 HandleDeviceChoice( item );
 HiliteMenu( 0 );

/****************** HandleAppleChoice ***********************/

void HandleAppleChoice( short item )
 MenuHandle appleMenu;
 Str255 accName;
 short  accNumber;
 switch ( item )
 case iAbout:
 NoteAlert( kAboutALRTid, kNULLFilterProc );
 appleMenu = GetMHandle( mApple );
 GetItem( appleMenu, item, accName );
 accNumber = OpenDeskAcc( accName );

/****************** HandleFileChoice ***********************/

void HandleFileChoice( short item )
 switch ( item )
 case iQuit :
 gDone = true;

/****************** HandleDeviceChoice **********************/

void HandleDeviceChoice( short item )
/* Try this: 
 Modify the program so that when a device is selected
 from the Device menu, the current window gets closed and a
 new window is opened on the selected device. Be careful when
 you translate the menu item back into an address. Debug your
 program thoroughly before you try to use the address as an
 address. You don't want to accidentally reformat your hard 
 drive, right?
 Also, don't forget to update the check mark!

/****************** HasColorQD *****************/

Boolean HasColorQD( void )
 unsigned char   version[ 4 ];
 OSErr  err;
 err = Gestalt( gestaltQuickdrawVersion, (long *)version );
 if ( err != noErr )
 SysBeep( 10 );  /*  Error calling Gestalt!!!  */
 if ( version[ 2 ] > 0 )
 return( true );
 return( false );

/****************** GetDeepestDevice *****************/

GDHandle GetDeepestDevice( void )
 GDHandle curDevice, maxDevice = NULL;
 short  curDepth, maxDepth = 0;
 curDevice = GetDeviceList();
 while ( curDevice != NULL )
 curDepth = GetDeviceDepth( curDevice );
 if ( curDepth > maxDepth )
 maxDepth = curDepth;
 maxDevice = curDevice;

 curDevice = GetNextDevice( curDevice );
 return( maxDevice );

/****************** GetDeviceDepth *****************/

short GetDeviceDepth( GDHandle device )
 PixMapHandle  screenPixMapH;
 screenPixMapH = (**device).gdPMap;
 return( (**screenPixMapH).pixelSize );

/****************** DrawRandomRect *****************/

void DrawRandomRect( void )
 Rect   randomRect;
 RGBColor color;
 RandomRect( &randomRect );
 RandomColor( &color );
 RGBForeColor( &color );
 PaintOval( &randomRect );

/****************** RandomColor *********************/

void RandomColor( RGBColor *colorPtr )
 colorPtr->red = Random() + 32767;
 colorPtr->blue = Random() + 32767;
 colorPtr->green = Random() + 32767;

/****************** RandomRect *********************/

void RandomRect( Rect *rectPtr )

 window = FrontWindow();
 rectPtr->left = Randomize( window->portRect.right
 - window->portRect.left );
 rectPtr->right = Randomize( window->portRect.right
 - window->portRect.left );
 rectPtr->top = Randomize( window->portRect.bottom
 - window-> );
 rectPtr->bottom = Randomize( window->portRect.bottom
 - window-> );

/****************** Randomize **********************/

short Randomize( short range )
 long   randomNumber;
 randomNumber = Random();
 if ( randomNumber < 0 )
 randomNumber *= -1;
 return( (randomNumber * range) / kRandomUpperLimit );

/***************** DoError ********************/

void DoError( Str255 errorString )
 ParamText( errorString, kEmptyString, 
 kEmptyString, kEmptyString );
 StopAlert( kErrorAlertID, kNULLFilterProc );

Running ColorMondrian

Save your changes, then select Run from the Project menu. If ColorQuickDraw is not available on your machine (unlikely), an error message will appear. Otherwise, a window, similar to the one shown in Figure 12, will appear on the monitor with the deepest pixel settings.

Figure 12. ColorMondrian in action.

Bring the Finder to the front by selecting Finder from the applications menu at the right end of the menu bar. Notice that ColorMondrian stops dead in its tracks. Go back to ColorMondrian and select Quit from the File menu. Back in THINK C, select Set Project Type... from the Project menu. Set the value in the SIZE Flags field to 5880 (you don’t have to fiddle with the popup menu - you can just type the number in the field).

You’ve just set ColorMondrian up to continue processing events even when it is running in the background. To prove this, select Run from the Project menu, then bring the Finder to the front again. This time, ColorMondrian will continue running, even in the background.

Next, click on the Devices menu. A hex address will appear for every monitor attached to your Macintosh. A check-mark will appear next to the address representing the monitor with the deepest settings. You’ll find out what the address or addresses are for in next month’s column. Figure 13 shows my Devices menu. As you can see, I’ve got two monitors attached to my Mac.

Figure 13. My devices menu.

If you’ve got more than one monitor on your machine, try using the Monitors control panel to set one monitor to 1-bit and the other to a deeper setting. Run ColorMondrian. The window should appear on the deeper monitor. Now switch the settings so that the second monitor has the deeper settings. Run ColorMondrian again. Now the window should appear on the other monitor.

Till Next Month...

Next, month we’ll get into all the theory behind ColorMondrian. Till then, take a look through the code, then read up on Color QuickDraw in the pages of Inside Macintosh or on your Mac, courtesy of THINK Reference.


Community Search:
MacTech Search:

Software Updates via MacUpdate

Black Hole Joyrider (Games)
Black Hole Joyrider 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: Guide your spacecraft through the gravity well of a powerful black hole using only your retro-thrusters and dwindling fuel... | Read more »
My Koi (Games)
My Koi 1.0 Device: iOS iPhone Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: My Koi is a beautiful and relaxing fish pond app. Customise and name each fish. Feed them daily. Watch them grow. Collect new fish.... | Read more »
Never Gone (Games)
Never Gone 1.0.2 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.2 (iTunes) Description: ###IMPPORTANT### Never Gone's HD art resources require devices with more than 1GB RAM, so please note that iPhone 4/4s, iPad 2/... | Read more »
INKS. (Games)
INKS. 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: From the makers of BAFTA-winning Lumino City comes INKS. INKS updates pinball for a new generation. It combines the joy of pinball with... | Read more »
How to maximise your profits in Bakery B...
Running a bakery can be an expensive venture. You’ll need to continuously upgrade your oven, your kitchen supplies, and even your ingredients to keep customers happy. Most of these renovations in Bakery Blitz cost a pretty penny, but we have a few... | Read more »
How to manage your time in Bakery Blitz
It can be tricky, especially when you risk burning your kitchen to the ground if you forget a cake in the oven, so make sure to use these time management tricks to keep your bakery running smoothly. Don’t collect the money right away [Read more] | Read more »
Model 15 (Music)
Model 15 1.0 Device: iOS iPhone Category: Music Price: $29.99, Version: 1.0 (iTunes) Description: The Moog Model 15 App is the first Moog modular synthesizer and synthesis educational tool created exclusively for iPad, iPhone and... | Read more »
How to deal with wind in Angry Birds Act...
Angry Birds Action! is a physics-based puzzler in which you're tasked with dragging and launching birds around an obstacle-littered field to achieve a set objective. It's simple enough at first, but when wind gets introduced things can get pretty... | Read more »
How to get three stars in every level of...
Angry Birds Action! is, essentially, a pinball-style take on the pull-and-fling action of the original games. When you first boot it up, you'll likely be wondering exactly what it is you have to do to get a good score. Well, never fear as 148Apps... | Read more »
The beginner's guide to Warbits
Warbits is a turn-based strategy that's clearly inspired by Nintendo's Advance Wars series. Since turn-based strategy games can be kind of tricky to dive into, see below for a few tips to help you in the beginning. Positioning is crucial [Read... | Read more »

Price Scanner via

12-inch 128GB iPad Pros on sale for up to $10...
B&H Photo has 12″ 128GB WiFi iPad Pros on sale for up to $100 off MSRP, each including free shipping. B&H charges sales tax in NY only: - 12″ Space Gray 128GB WiFi iPad Pro: $899 $50 off MSRP... Read more
Global Tablet Sales Slump Continues, iPad’s F...
Another miserable showing for the global slate tablet category in calendar Q1/16, with global tablet shipments falling another 1ten percent to 46.5 million units during the according to Strategy... Read more
Revel Systems to Showcase iPad POS Platform w...
Revel Systems, specialists in iPad Point of Sale management solution for brick-and-mortar retail, food businesses and more, today announced that it will showcase its innovative iPad Point of Sale... Read more
13-inch 2.5GHz MacBook Pro on sale for $999,...
B&H Photo has the 13″ 2.5GHz MacBook Pro on sale for $999 including free shipping plus NY sales tax only. Their price is $100 off MSRP. Read more
Apple refurbished 2015 iMacs available for up...
Apple now has a full line of Certified Refurbished 2015 21″ & 27″ iMacs available for up to $350 off MSRP. Apple’s one-year warranty is standard, and shipping is free. The following models are... Read more
Indian Smartphone Market Grows Annually by 12...
India’s smartphone market grew by 12 percent year-over-year, with 24.4 million units shipping in Q1 2016. The top five vendors stayed the same, with Samsung in the lead, followed by Micromax, Intex... Read more
Get Notifications When Your Friend’s Phone Ba...
Calgary, Canada based Stonelight Pictures has announced the release of Battery Share 1.0.1, its new utility for iOS 9 supported devices. The company notes that people are spending more time on their... Read more
11-inch 1.6GHz/128GB MacBook Air on sale for...
Amazon has the current-generation 11″ 1.6GHz/128GB MacBook Air (sku MJVM2LL/A) on sale for $749.99 for a limited time. Their price is $150 off MSRP, and it’s the lowest price available for this model... Read more
Price drops on clearance 2015 13-inch MacBook...
B&H Photo has dropped prices on clearance 2015 13″ MacBook Airs by up to $250. Shipping is free, and B&H charges NY sales tax only: - 13″ 1.6GHz/4GB/128GB MacBook Air (MJVE2LL/A): $799, $200... Read more
Mac minis on sale for up to $100 off MSRP
B&H Photo has Mac minis on sale for up to $100 off MSRP including free shipping plus NY sales tax only: - 1.4GHz Mac mini: $449 $50 off MSRP - 2.6GHz Mac mini: $649 $50 off MSRP - 2.8GHz Mac mini... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Restaurant Manager (Neighborhood Captain) - A...
…in every aspect of daily operation. WHY YOU'LL LIKE IT: You'll be the Big Apple . You'll solve problems. You'll get to show your ability to handle the stress and Read more
Automotive Sales Consultant - Apple Ford Linc...
…you. The best candidates are smart, technologically savvy and are customer focused. Apple Ford Lincoln Apple Valley is different, because: $30,000 annual salary Read more
Restaurant Manager (Neighborhood Captain) - A...
…in every aspect of daily operation. WHY YOU'LL LIKE IT: You'll be the Big Apple . You'll solve problems. You'll get to show your ability to handle the stress and Read more
Simply Mac *Apple* Specialist- Service Repa...
Simply Mac is the largest premier retailer of Apple products in the nation. In order to support our growing customer base, we are currently looking for a driven Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.