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

OmniGraffle 6.3 - Create diagrams, flow...
OmniGraffle 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 Graffle to... Read more
PDFKey Pro 4.3.2 - Edit and print passwo...
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
Ableton Live 9.2.2 - Record music using...
Ableton Live lets you create and record music on your Mac. Use digital instruments, pre-recorded sounds, and sampled loops to arrange, produce, and perform your music like never before. Ableton Live... 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
NetShade 6.3.1 - Browse privately using...
NetShade is an anonymous proxy and VPN app+service for Mac. Unblock your Internet through NetShade's high-speed proxy and VPN servers spanning seven countries. NetShade masks your IP address as you... Read more
Dragon Dictate 4.0.7 - Premium voice-rec...
With Dragon Dictate speech recognition software, you can use your voice to create and edit text or interact with your favorite Mac applications. Far more than just speech-to-text, Dragon Dictate lets... Read more
Persecond 1.0.2 - Timelapse video made e...
Persecond is the easy, fun way to create a beautiful timelapse video. Import an image sequence from any camera, trim the length of your video, adjust the speed and playback direction, and you’re done... Read more
GIMP 2.8.14p2 - Powerful, free image edi...
GIMP is a multi-platform photo manipulation tool. GIMP is an acronym for GNU Image Manipulation Program. The GIMP is suitable for a variety of image manipulation tasks, including photo retouching,... Read more
Sandvox 2.10.2 - Easily build eye-catchi...
Sandvox is for Mac users who want to create a professional looking website quickly and easily. With Sandvox, you don't need to be a Web genius to build a stylish, feature-rich, standards-compliant... Read more
LibreOffice - Free, open-source...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more

ReBoard: Revolutionary Keyboard (Utilit...
ReBoard: Revolutionary Keyboard 1.0 Device: iOS Universal Category: Utilities Price: $1.99, Version: 1.0 (iTunes) Description: Do everything within the keyboard without switching apps! If you are in WhatsApp, how do you schedule a... | Read more »
Tiny Empire (Games)
Tiny Empire 1.1.3 Device: iOS Universal Category: Games Price: $2.99, Version: 1.1.3 (iTunes) Description: Launch cannonballs and blow tiny orcs into thousands of pieces in this intuitive fantasy-themed puzzle shooter! Embark on an... | Read more »
Astropad Mini (Productivity)
Astropad Mini 1.0 Device: iOS iPhone Category: Productivity Price: $4.99, Version: 1.0 (iTunes) Description: *** 50% off introductory price! ​*** Get the high-end experience of a Wacom tablet at a fraction of the price with Astropad... | Read more »
Emo Chorus (Music)
Emo Chorus 1.0.0 Device: iOS Universal Category: Music Price: $1.99, Version: 1.0.0 (iTunes) Description: Realistic Choir simulator ranging from simple Chorus emulation to full ensemble Choir with 128 members. ### introductory offer... | Read more »
Forest Spirit (Games)
Forest Spirit 1.0.5 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.5 (iTunes) Description: | Read more »
Ski Safari 2 (Games)
Ski Safari 2 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: The world's most fantastical, fun, family-friendly skiing game is back and better than ever! Play as Sven's sister Evana, share... | Read more »
Lara Croft GO (Games)
Lara Croft GO 1.0.47768 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.47768 (iTunes) Description: Lara Croft GO is a turn based puzzle-adventure set in a long-forgotten world. Explore the ruins of an ancient... | Read more »
Whispering Willows (Games)
Whispering Willows 1.23 Device: iOS Universal Category: Games Price: $4.99, Version: 1.23 (iTunes) Description: **LAUNCH SALE 50% OFF** - Whispering Willows is on sale for 50% off ($4.99) until September 9th. | Read more »
Calvino Noir (Games)
Calvino Noir 1.1 Device: iOS iPhone Category: Games Price: $3.99, Version: 1.1 (iTunes) Description: The film noir stealth game. Calvino Noir is the exploratory, sneaking adventure through the 1930s European criminal underworld.... | Read more »
Angel Sword (Games)
Angel Sword 1.0 Device: iOS Universal Category: Games Price: $6.99, Version: 1.0 (iTunes) Description: Prepare to adventure in the most epic full scale multiplayer 3D RPG for mobile! Experience amazing detailed graphics in full HD.... | Read more »

Price Scanner via

Apple offering refurbished 2015 13-inch Retin...
The Apple Store is offering Apple Certified Refurbished 2015 13″ Retina MacBook Pros for up to $270 (15%) off the cost of new models. An Apple one-year warranty is included with each model, and... Read more
Apple refurbished 2015 MacBook Airs available...
The Apple Store has Apple Certified Refurbished 2015 11″ and 13″ MacBook Airs (the latest models), available for up to $180 off the cost of new models. An Apple one-year warranty is included with... Read more
21-inch iMacs on sale for up to $120 off MSRP
B&H Photo has 21″ iMacs on sale for up to $120 off MSRP including free shipping plus NY sales tax only: - 21″ 1.4GHz iMac: $999.99 $100 off - 21″ 2.7GHz iMac: $1199.99 $100 off - 21″ 2.9GHz iMac... Read more
5K iMacs on sale for up to $150 off MSRP, fre...
B&H Photo has the 27″ 3.3GHz 5K iMac on sale for $1899.99 including free shipping plus NY tax only. Their price is $100 off MSRP. They have the 27″ 3.5GHz 5K iMac on sale for $2149.99 $2199.99, $... Read more
1.4GHz Mac mini, refurbished, available for $...
The Apple Store has Apple Certified Refurbished 1.4GHz Mac minis available for $419. Apple’s one-year warranty is included, and shipping is free. Their price is $80 off MSRP, and it’s the lowest... Read more
iPad Air 2 on sale for up to $100 off MSRP
Best Buy has iPad Air 2s on sale for up to $100 off MSRP on their online store for a limited time. Choose free shipping or free local store pickup (if available). Sale prices available for online... Read more
MacBook Airs on sale for $100 off MSRP
Best Buy has MacBook Airs on sale for $100 off MSRP on their online store. Choose free shipping or free local store pickup (if available). Sale prices for online orders only, in-store prices may vary... Read more
Big Grips Lift Handle For iPad Air and iPad A...
KEM Ventures, Inc. which pioneered the extra-large, super-protective iPad case market with the introduction of Big Grips Frame and Stand in 2011, is launching Big Grips Lift featuring a new super-... Read more
Samsung Launches Galaxy Tab S2, Its Most Powe...
Samsung Electronics America, Inc. has announced the U.S. release of the Galaxy Tab S2, its thinnest, lightest, ultra-fast tablet. Blending form and function, elegant design and multitasking power,... Read more
Tablet Screen Sizes Expanding as iPad Pro App...
Larger screen sizes are gaining favor as the tablet transforms into a productivity device, with shipments growing 185 percent year-over-year in 2015. According to a new Strategy Analytics’ Tablet... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Desktop Analyst - KDS Staffing (Unit...
…field and consistent professional recruiting achievement. Job Description: Title: Apple Desktop AnalystPosition Type: Full-time PermanentLocation: White Plains, NYHot Read more
*Apple* Systems Engineer (Mclean, VA and NYC...
Title: Apple Systems Engineer (Mclean, VA and NYC) Location: United States-New York-New York-200 Park Ave (22005) Other Locations: United States-Virginia-Vienna-Towers Read more
*Apple* Systems Engineer (Mclean, VA and NYC...
…Assist in providing strategic direction and technical leadership within the Apple portfolio, including desktops, laptops, and printing environment. This person will Read more
*Apple* Subject Matter Expert - Experis (Uni...
We are seeking an Apple Subject Matter Expert to assist in developing the architecture, support and services for integration of Apple devices into the company's Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.