TweetFollow Us on Twitter

Icon Mania
Volume Number:8
Issue Number:6
Column Tag:Getting Started

Related Info: Window Manager Memory Manager Resource Manager

Icon Mania!

More on using WIND resources

By Dave Mark, MacTutor Regular Contributing Author

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

Our last program, PICTWindow, used a WIND resource to create a new window, and then loaded a PICT resource, drawing it in the window. This month, we’ll explore some new resources. We’ll start off in the usual way, using a WIND resource as the basis for a window.

In this month's program, instead of using the window title described in the WIND resource, we'll load the title from a resource designed specifically to hold a text string. Once we set the window's title, we'll load a color icon from the resource file, then plot it in random locations in the window.

This may sound kind of weird, but just be patient! Once you see this program in action, I think you'll like it.

Building the IconMania Resources

Create a new folder in your Development folder named IconMania. Next, launch ResEdit by double-clicking on its icon in the Finder. When you get enough of the clown-in-the-box, click the mouse button. When the “Open FIle” dialog appears, click the New button, navigate into your new IconMania folder and create a resource file named IconMania.Π.rsrc.

The first resource you’ll create is your WIND resource. Select Create New Resource from the Resource menu. When the scrolling list of resource types appears, type WIND (or select it from the scrolling list) and click the OK button. When the WIND editing window appears, change your WIND to reflect the specifications shown in Figure 1.

Figure 1: IconMania’s WIND resource.

Next, select Set 'WIND' Characteristics... from the WIND menu and delete any text in the Window title: field. We'll pull our window title from the resource we create next. Click the OK button, then close the WIND editing window and the WIND picker window, leaving yourself at the main window for the resource file.

Figure 2: The 'WIND' Characteristics dialog box with the window title deleted.

Once again, select Create New Resource from the Resource menu. This time, type the four characters 'STR ', then click the OK button. The fourth character in the resource name is a space. If you leave the space off, ResEdit will stick it in there for you, but don't forget that resource types are always four characters long.

The 'STR ' resource allows you to store a pascal string in the resource file. Remember, a pascal string is a length byte, followed by that many bytes of text. Pascal strings are associated with the Str255 data type. When the 'STR ' editing window appears, type some text in the field labeled "The String". This text will eventually become the title of the IconMania window.

Figure 3: The STR editing window.

Close the STR editing window and the STR picker window, leaving only the main resource window. One more resource to go! Once again, select Create New Resource from the Resource menu. This time, type cicn, then click the OK button. Each cicn resource represents a color icon.

Take a look at the cicn editing window shown in Figure 4. The cicn editor uses a series of MacPaint like tools (shown on the left side of the window) to let you create a pair of icons and an icon mask (see the right side of the window). The color icon is a full-blown color icon. When you click on the color icon on the right side, you'll have access to tools that let you select colors and patterns (The items in the Tools menu help determine the colors available for icon editing).

Figure 4: The cicn editing window.

Trying to edit a color icon on a black and white Mac doesn't make much sense (and it annoys the heck out of ResEdit). To get the most out of this exercise, borrow a friend's Mac if yours doesn't support color.

Spend some time creating just the right color icon. When you are done, click on the icon labeled B & W. Use the same techniques to create a black and white version of the same icon. As you'll see when we get to our source code, the toolbox routine that draws our icon will automatically plot the color icon in a color environment, and will draw the black and white icon when color is not available.

Next, click on the icon labeled Mask. This icon determines which of the pixels in the previous two icons will be plotted. In general, it's a good idea to set all the pixels in your mask to black. Once you're satisfied with your exquisite work of art, close the cicn editing window and the cicn picker window, leaving just the main resource window.

That's it! Your main resource window should show three resource types. Compare your window against the one shown in Figure 5. Once you are satisfied, save your changes, then quit ResEdit. Let's move on to the source code.

Figure 5: The main resource window, showing all three IconMania resource types.

Creating the IconMania Project

Launch THINK C. When you are prompted for a project to open, click the New button and create a project named IconMania.Π in your IconMania folder. Add MacTraps to your project. Next, select New from the File menu. When the new source code window appears, type in the following source code:

/* 1*/

#define kBaseResID 128
#define kMoveToFront (WindowPtr)-1
#define kRandomUpperLimit 32768

/***************/
/*  Functions  */
/***************/

void  ToolBoxInit( void );
void  WindowInit( void );
void  MainLoop( void );
void  DrawRandomIcon( CIconHandle theIcon );
void  RandomPoint( Point *pointPtr );
short Randomize( short range );

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

void  main( void )
{
 ToolBoxInit();
 WindowInit();
 MainLoop();
}

/****************** ToolBoxInit *********************/

void  ToolBoxInit( void )
{
 InitGraf( &thePort );
 InitFonts();
 InitWindows();
 InitMenus();
 TEInit();
 InitDialogs( nil );
 InitCursor();
}

/****************** WindowInit ***********************/

void  WindowInit( void )
{
 WindowPtrwindow;
 StringHandle  windowTitleH;

 window = GetNewWindow( kBaseResID , nil,
 kMoveToFront );
 
 if ( window == nil )
 {
 SysBeep( 10 );  /*  Couldn't load the WIND resource!!!  */
 ExitToShell();
 }
 
 windowTitleH = GetString( kBaseResID );
 
 if ( windowTitleH == nil )
 {
 SysBeep( 10 );  /*  Couldn't load the STR resource!!!  */
 ExitToShell();
 }
 
 HLock( (Handle)windowTitleH );
 SetWTitle( window, *windowTitleH );
 HUnlock( (Handle)windowTitleH );
 
 ShowWindow( window );
 SetPort( window );
}

/****************** MainLoop ***********************/

void  MainLoop( void )
{
 CIconHandletheIcon;
 
 GetDateTime( (unsigned long *)(&randSeed) );
 
 theIcon = GetCIcon( kBaseResID );
 
 if ( theIcon == nil )
 {
 SysBeep( 10 );  /*  Couldn't load the cicn resource!!!  */
 ExitToShell();
 }

 while ( ! Button() )
 DrawRandomIcon( theIcon );
}

/****************** DrawRandomIcon *****************/

void  DrawRandomIcon( CIconHandle theIcon )
{
 Point  p;
 Rect   iconRect;
 
 RandomPoint( &p );
 
 SetRect( &iconRect, p.h, p.v, p.h+32, p.v+32 );
 PlotCIcon( &iconRect, theIcon );
}

/****************** RandomPoint *********************/

void  RandomPoint( Point  *pointPtr )
{
 WindowPtrwindow;

 window = FrontWindow();
 
 pointPtr->h = Randomize( window->portRect.right
 - window->portRect.left );
 pointPtr->v = Randomize( window->portRect.bottom
 - window->portRect.top );
}

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

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

Once your source code is typed in, select Save from the File menu. Save the file under the name “IconMania.c”. Next, add the source file to the project by select Add (not Add...) from the Source menu. Your project window should look like the one shown in Figure 6.

Figure 6: The IconMania project file.

Running the Program

Now you’re ready to run IconMania. Assuming you have a Mac that supports color, use the Monitors control panel to enable the full complement of colors. Next, run IconMania by selecting Run from the Project menu. If you encounter any errors, check your source code for typos and make sure your project window has the two files shown in Figure 6. Once your program runs, the IconMania window should appear, with its own psychedelic cicn show (See Figure 7). At this point, you might want to put on Houses of the Holy or Dark Side of the Moon and kick back for a while.

Important!!!

IconMania will not run on a Mac that doesn't support color (a Mac Plus, for example). If you absolutely can not get hold of a color Mac, modify IconMania by using an ICON resource instead of a cicn resource, and using GetIcon() and PlotIcon() instead of GetCIcon() and PlotCIcon(). Not as much fun, but it will work!!! Remember that GetCIcon() and PlotCIcon() take a different parameter than GetIcon() and PlotIcon(), so change the type of theIcon throughout the code.

Figure 7: It's IconMania!!!

Stepping Through the Source Code

The #defines kBaseResID and kMoveToFront should be familiar to you by now. kRandomUpperLimit is used by the random number generator in the routine Randomize().

/* 2 */

#define kBaseResID 128
#define kMoveToFront (WindowPtr)-1
#define kRandomUpperLimit 32768

As usual, every function (except main()) has an accompanying function prototype. Since C++ requires function prototypes, this is an especially important habit to develop.

/* 3 */

/***************/
/*  Functions  */
/***************/

void  ToolBoxInit( void );
void  WindowInit( void );
void  MainLoop( void );
void  DrawRandomIcon( CIconHandle theIcon );
void  RandomPoint( Point *pointPtr );
short Randomize( short range );

main() initializes the Toolbox, creates the IconMania window, then enters the main icon drawing loop.

/* 4 */

/****************** main ***************************/
void  main( void )
{
 ToolBoxInit();
 WindowInit();
 MainLoop();
}

ToolBoxInit() is the same as it ever was.

/* 5 */

/****************** ToolBoxInit *********************/
void  ToolBoxInit( void )
{
 InitGraf( &thePort );
 InitFonts();
 InitWindows();
 InitMenus();
 TEInit();
 InitDialogs( nil );
 InitCursor();
}

As we did in PICTWindow, we call GetNewWindow() to load a WIND resource. If the WIND resource wasn't loaded successfully, beep once, then exit.

/* 6 */

/****************** WindowInit ***********************/

void  WindowInit( void )
{
 WindowPtrwindow;
 StringHandle  windowTitleH;

 window = GetNewWindow( kBaseResID , nil,
 kMoveToFront );
 
 if ( window == nil )
 {
 SysBeep( 10 );  /*  Couldn't load the WIND resource!!!  */
 ExitToShell();
 }

Next, call GetString() to load the 'STR ' resource with the specified resource ID. GetString() reads in the string and returns a handle to the first byte of the string. A handle is essentially a pointer to a pointer. By convention, we end all handle variables with a capital H, as in windowTitleH.

/* 7 */

 windowTitleH = GetString( kBaseResID );

A handle is actually a pointer to a master pointer. When the Mac's memory manager creates a handle to a block of memory, it places the pointer to the block in its list of master pointers and returns a pointer to the master pointer to you.

The reason for handles becomes clearer when the memory manager moves that block of memory. When the block moves (to make way for a larger block, perhaps), the memory manager updates the value in the master pointer, making sure it points to the block's new location. Since your handle points to the master pointer, and the master pointer hasn't moved, the value in your handle doesn't change. Therefore, your handle still references the same block of memory, even though the block changed location.

If handles seem a little abstract, don't panic. As time goes on, handles will become clearer to you. There's really not that much to them, but they can be confusing.

If the 'STR ' resource wasn't loaded, beep once, then exit.

/* 8 */

 if ( windowTitleH == nil )
 {
 SysBeep( 10 );  /*  Couldn't load the STR resource!!!  */
 ExitToShell();
 }

Next, we need to lock the handle, telling the memory manager not to move the block of memory containing the text string. In general, you always lock a handle when you directly reference the master pointer (the pointer the handle poists to). In this case, we'll be passing the master pointer as a parameter to the routine SetWTitle(). That's because the master pointer contains the address of the first byte of the string (just like any Str255 variable).

/* 9 */

 HLock( (Handle)windowTitleH );

Next, the string is passed on to SetWTitle(), which will change the title of the referenced window to the string in the 'STR ' resource.

/* 10 */

 SetWTitle( window, *windowTitleH );

Now that we are done referencing the master pointer, we can unlock the handle again.

/* 11 */

 HUnlock( (Handle)windowTitleH );

Finally, make the window visible and the current port.

/* 12 */

 ShowWindow( window );
 SetPort( window );
}

MainLoop() starts by loading the current date and time into the global variable randSeed. This serves to initialize the Mac's random number generator.

/* 13 */

/****************** MainLoop ***********************/

void  MainLoop( void )
{
 CIconHandletheIcon;
 
 GetDateTime( (unsigned long *)(&randSeed) );

Next, we call GetCIcon() to load the cicn resource from the resource file.

/* 14 */

 theIcon = GetCIcon( kBaseResID );

If the cicn resource wasn't found, beep once then exit.

/* 15 */

 if ( theIcon == nil )
 {
 SysBeep( 10 );  /*  Couldn't load the cicn resource!!!  */
 ExitToShell();
 }

Next, draw random icons until the mouse button is pressed.

/* 16 */

 while ( ! Button() )
 DrawRandomIcon( theIcon );
}

DrawRandomIcon() draws the specified color icon at a random point in the frontmost window.

/* 17 */

/****************** DrawRandomIcon *****************/

void  DrawRandomIcon( CIconHandle theIcon )
{
 Point  p;
 Rect   iconRect;

First, call RandomPoint() to pick a random location in the window.

/* 18 */

 RandomPoint( &p );

Next, use that point as the upper left corner to create a Rect that is 32 pixels by 32 pixels, the size of a color icon.

/* 19 */

 SetRect( &iconRect, p.h, p.v, p.h+32, p.v+32 );

Finally, call PlotCIcon() to draw the icon in the specified Rect. If you like, try changing the 32's in the previous line to 16's or to 64's, to get a feel for plotting an icon in a different size rectangle.

/* 20 */

 PlotCIcon( &iconRect, theIcon );
}

PlotCIcon() is pretty smart. If color is turned off (or simply not available) PlotCIcon() will plot its black and white icon instead. To prove this, try running IconMania with color turned off (see Figure 8).

Figure 8: IconMania in black and white.

RandomPoint() uses the function Randomize() to generate a point somewhere inside the frontmost window.

/* 21 */

/****************** RandomPoint *********************/

void  RandomPoint( Point  *pointPtr )
{
 WindowPtrwindow;

 window = FrontWindow();
 
 pointPtr->h = Randomize( window->portRect.right
 - window->portRect.left );
 pointPtr->v = Randomize( window->portRect.bottom
 - window->portRect.top );
}

Randomize() uses an algorithm from the Mondrian program in the Macintosh Programming Primer, Volume I.

/* 22 */

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

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

...and for you Pascal Folks

Here's the IconMania source code for you THINK Pascal folks. Type in the code, then work your way through the C commentary. Use this as an opportunity to come up to speed on C.

Remember to select Run Options... from the Run menu and add the resource file to the project.

program IconMania;
 const
  kBaseResID = 128;
  kRandomUpperLimit = 32768;

{--------------------------------> Randomize <---}

 function Randomize (range: INTEGER): INTEGER;
  var
   randomNumber: LONGINT;
 begin
  randomNumber := Random;
  randomNumber := abs(randomNumber);

  Randomize := (randomNumber * range) div kRandomUpperLimit;
 end;

{--------------------------------> RandomPoint     <---}

 procedure RandomPoint (var thePoint: Point);
  var
   window: WindowPtr;
 begin
  window := FrontWindow;

  thePoint.h := Randomize(window^.portRect.right -             
 window^.portRect.left);
  thePoint.v := Randomize(window^.portRect.bottom - 
 window^.portRect.top);
 end;

{--------------------------------> DrawRandomIcon  <---}

 procedure DrawRandomIcon (theIcon: CIconHandle);
  var
   p: Point;
   iconRect: Rect;
 begin
  RandomPoint(p);

  SetRect(iconRect, p.h, p.v, p.h + 32, p.v + 32);
  PlotCIcon(iconRect, theIcon);
 end;

{--------------------------------> MainLoop  <---}

 procedure MainLoop;
  var
   theIcon: CIconHandle;
 begin
  GetDateTime(randSeed);

  theIcon := GetCIcon(kBaseResID);

  if theIcon = nil then
  begin
   SysBeep(10);
   ExitToShell;
  end;

  while (not Button) do
   DrawRandomIcon(theIcon);
 end;

{--------------------------------> WindowInit      <---}

 procedure WindowInit;
  var
   window: WindowPtr;
   windowTitleH: StringHandle;
 begin
  window := GetNewWindow(kBaseResID, nil, WindowPtr(-1));

  if window = nil then
  begin
   SysBeep(10);
   ExitToShell;
  end;

  windowTitleH := GetString(kBaseResID);

  if windowTitleH = nil then
  begin
   SysBeep(10);
   ExitToShell;
  end;

  HLock(Handle(windowTitleH));
  SetWTitle(window, windowTitleH^^);
  HUnlock(Handle(windowTitleH));

  ShowWindow(window);
  SetPort(window);
 end;

{--------------------------------> Mondrian  <---}

begin
 WindowInit;
 MainLoop;
end.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
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
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and 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
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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.