TweetFollow Us on Twitter

Separate Data, Code
Volume 8
Number4
Column Title:Getting Started

Related Info: Resource Manager Window Manager Picture Utilities

Separating Data from Code

Using those little pockets of data called resources

By Dave Mark, MacTutor Regular Contributing Author

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

Last month’s column focused on QuickDraw, the Macintosh drawing environment. The TextBoxer program showed you how to use QuickDraw in combination with the Window Manager to draw text and graphics in a window. This month we’ll learn about resources, the Mac’s mechanism for separating data from code.

Resources

Resources are little pockets of data, designed to pull descriptive data out of your program’s source code. For example, a WIND resource describes the size, location, and characteristics of a Macintosh window. In last month’s column, we used the Window Manager call NewWindow() to create a new window:

/* 1 */

WindowPtr window;
Rect    windowRect;
 
SetRect( &windowRect, 20, 40, 260, 74 );

window = NewWindow( nil, &windowRect, "\pBox o’ Text",
 kVisible, documentProc, kMoveToFront,
 kNoGoAway, kNilRefCon );

The parameters passed to NewWindow() completely describe the window. The trouble is, the description is inexorably bound into the source code. To change the size or position of the window, you’ve got to recompile your program. The WIND resource gives you an alternative to this strategy. Here’s how it works...

Basic Resource Strategy

At the heart of any resource strategy is a resource editor. Though there are others, for my money [especially since it is free - Ed.] ResEdit can’t be beat. ResEdit allows you to edit resources using a graphic resource editor designed for that resource type. For example, Figure 1 shows ResEdit’s WIND editing window.

This window gives you all the tools you’ll need to completely describe a window. At the top is a row of icons that let you select the type of window you’d like to create. At bottom-left is a series of fields you can use to describe the size and location of the window. In the center is a miniature version of your screen, showing how your window will look once it’s created.

Figure 1. ResEdit’s WIND editing window.

Once you design your resources, you load them into your program using a set of Toolbox routines designed to work with resources. As an example, the routine GetNewWindow() loads a WIND resource and creates the same kind of WindowRecord as the Window Manager routine NewWindow():

/* 2 */

window = GetNewWindow( kBaseResID, nil, kMoveToFront );

If you use NewWindow() to create a window, the data that describes the window is embedded in the source code in the form of NewWindow() parameters. If you use GetNewWindow(), the data that describes the window resides outside of your program’s code, in the WIND resource. The WIND resource acts as a template for creating a window.

As you spend more time programming the Macintosh, you’ll learn more and more about the enormous potential of resources. For now, we’ll start slowly, introducing a few basic resources in this column, and adding to our list each month.

Resource Management Specifics

Resources are identified by a resource type and a resource ID. The resource type is a four-byte value, typically made up of readable ASCII characters. The resource type defines the data described by the resource. For example, a WIND resource always follows the same format and always describes a Macintosh window. There are lots of different resource types.

A program can contain more than one resource of a given type. The resource ID serves to differentiate one resource of a given type from another. Typically, resource IDs start at 128 and move upwards from there. If your program used three WIND resources, you’d number them 128, 129, and 130.

This month’s sample program, PICTWindow, makes use of two resources, a PICT and a WIND. The PICT resource contains a Macintosh picture. PICTWindow uses the WIND resource to create a new window, loads the PICT resource into memory, then draws the PICT in the window.

Let’s get to work...

Creating the PICTWindow Resources

If you don’t already have a copy of ResEdit, go out and get one. You can download ResEdit from most of the big bulletin boards, and you can purchase ResEdit from APDA.

In my latest APDA catalog, there were three entries for ResEdit version 2.1.1. $29.95 gets you the manual and disk, $14.95 is the manual only, and $15.00 for the disk only. You can reach APDA by phone at (800) 282-2732 in the United States, (800) 637-0029 in Canada, and (408) 562-3910 internationally.

You might also consider ordering the book ResEdit Complete, a fine book written by Peter Alley and Carolyn Strange ($29.95 from APDA).

Once you’ve copied your copy of ResEdit to your hard drive, create a folder for all the PICTWindow files inside your development folder. I called my folder (logically enough) PICTWindow.

Next, use your favorite graphics package to create a pleasing picture. Copy the picture, then paste it into the Scrapbook. Feel free to use color, text, and whatever else pleases your eye in your picture. PICTWindow can handle anything you can paste into the Scrapbook.

Now you’re ready to create some resources. Double-click on the ResEdit icon to start-up ResEdit. When the bouncing Jack-in-the-box appears, click the mouse button. You’ll be prompted for a file to open (if your version of ResEdit doesn’t prompt you, it’s OK, just ignore the rest of this paragraph). Click the Cancel button.

We’re going to create a new resource file. Select New... from the File menu. The dialog box shown in Figure 2 will appear, asking you to name the new resource file. Using the standard techniques, navigate over and in to the PICTWindow folder you created earlier. In the text field at the bottom of the dialog box, type the file name PICTWindow.Π.rsrc exactly as it appears in Figure 2. To type the Π character, hold down the option key and press the p key. Be sure to type the name exactly as shown. Don’t add anything. Don’t leave anything out. You’ll see why later in the column.

Figure 2. Naming your new resource file.

Once the name is typed in, click on the New button. ResEdit will create the new resource file and display a window showing the resources in this file. So far, there are none. We’ll fix that right now.

Select Create New Resource from the Resource menu. A scrolling list of resource types will appear (Figure 3). Scroll to the bottom of the list and select WIND (if you prefer, you can type WIND in the text field). Once WIND is selected (or typed) click the OK button. A WIND icon will be added to the PICTWindow.Π.rsrc main window, showing you that a WIND resource exists. A WIND picker window will appear, listing all the WIND resources in this file. Finally, on top of the other two, a WIND editing window will appear, allowing you to edit your new WIND.

Figure 3. Creating a new WIND resource.

By default, your new WIND resource is given the resource ID 128. That’s convenient, since that’s the number we wanted it to have. Use the settings shown in Figure 4 to modify your WIND resource. Click the second icon from the left (at the top of the window) and type in the four numbers shown in the lower left corner.

Figure 4. The WIND editing window from WIND 128.

Next, select Set 'WIND' Characteristics... from the WIND menu that appeared along with the WIND editor. Type in an appropriate window title (don’t change any of the other fields) and click the OK button. Congratulations! You’ve just created your first Macintosh resource. Close the WIND editing window and the WIND picker window, leaving the main window for the resource file. A WIND icon should appear in this window.

Let’s add the second resource needed by our program, the PICT resource. Go to the Scrapbook and Copy the picture you pasted in there earlier (if you prefer, Copy one of the pictures that come with the Scrapbook - Don’t copy plain text. Plain text won’t do what we want).

Once your picture is copied, bring the PICTWindow.Π.rsrc window back to the front and select Paste from ResEdit’s Edit menu. A new resource will be created and a PICT icon will appear in the main window verifying this fact. The PICT resource will automatically be given the resource ID 128. Now would be an excellent time to select Save from the File menu. You are done creating resources.

Quit ResEdit by selecting Quit from the File menu.

Creating the PICTWindow Project

Startup THINK C and create a new project in the PICTWindow folder. Name the new project PICTWindow.Π (be sure to spell it exactly this way). When you run a project, THINK C automatically tacks on the five characters “.rsrc” to the end of the project name and looks for a resource file with that name. If a resource file with that name is found, the resources in that file are automatically made available to your program. PICTWindow.Π is the name of your project file and PICTWindow.Π.rsrc is the name of your resource file.

Once the project is created, go into the Mac Libraries folder and add MacTraps to the project. Next, select New from the File menu to create a new source code file. Type in this source code:

/* 3 */

#define kBaseResID 128
#define kMoveToFront (WindowPtr)-1L


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

void  ToolBoxInit( void );
void  WindowInit( void );
void  DrawMyPicture( void );


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

void  main( void )
{
 ToolBoxInit();
 WindowInit();
 
 DrawMyPicture();
 
 while ( !Button() ) ;
}


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

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


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

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


/****************** DrawMyPicture ********************/

void  DrawMyPicture( void )
{
 Rect   pictureRect;
 PicHandlepicture;
 
 picture = GetPicture( kBaseResID );
 
 if ( picture == nil )
 {
 SysBeep( 10 );  /*  Couldn't load the PICT resource!!!  */
 ExitToShell();
 }
 
 pictureRect = (**picture).picFrame;
 
 OffsetRect( &pictureRect, - pictureRect.left,
 - pictureRect.top );
 
 DrawPicture( picture, &pictureRect );
 
 FrameRect( &pictureRect );
}

Once your source code is typed in, select Save from the File menu. Save the file under the name “PICTWindow.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 5.

Figure 5. The project window for PICTWindow.Π.

Running the Program

Now you’re ready to run your program. Select 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 5. Once your program runs, you should see a window similar to the one shown in Figure 6.

Notice that the picture is drawn in the upper left corner of the window. The upper left corner of the picture is at (0,0) in the window’s local coordinate system.

Figure 6. The PICTWindow window!

Key Lines of Code

Most of the program should make sense to you if you read through last month’s TextBoxer example. Rather than repeat last weeks explanations, I’d like to point out three key segments of code. The first is the code that loads the WIND resource and creates a new window:

/* 4 */

 window = GetNewWindow( kBaseResID, nil, kMoveToFront );

As mentioned earlier, this line of code accomplishes the same thing as NewWindow(), except that GetNewWindow() gets its information from the WIND resource, instead of its parameter list. GetNewWindow() is described in Volume I of Inside Macintosh, on page 283.

The second key line of code is the line that loads the PICT resource:

/* 5 */

 picture = GetPicture( kBaseResID );

This line of code loads the PICT resource with an ID matching kBaseResID. Match this line of code up with the following:

/* 6 */

 DrawPicture( picture, &pictureRect );

and you can really see the power of resources. Two lines of code and you’ve drawn a complex graphic in a window!!! By the way, GetPicture() is on page 475 of Volume I of Inside Macintosh and DrawPicture() is on page 190 of Volume I.

Till Next Month

Take some time to play around with ResEdit. Use ResEdit to modify your WIND resource, changing the type of window (click on the icons on the top row of the WIND editor) and the window’s location. Notice that the picture is drawn in the upper left of the window, no matter where the window is drawn on the screen. Look up OffsetRect() in Inside Macintosh and try to figure out why the picture is drawn where it is.

Finally, try to write a routine that centers the picture in the window. For a little help with this last exercise, you can check out the ShowPICT program in Volume I of the Mac Primer.

Sorry to cut this column short, but the next time I speak with you all, I should be a proud new poppa! Stay tuned...

 
AAPL
$97.89
Apple Inc.
+0.22
MSFT
$44.03
Microsoft Corpora
-0.47
GOOG
$585.34
Google Inc.
-3.68

MacTech Search:
Community Search:

Software Updates via MacUpdate

Bartender 1.2.20 - Organize your menu ba...
Bartender lets you organize your menu bar apps. Features: Lets you tidy your menu bar apps how you want. See your menu bar apps when you want. Hide the apps you need to run, but do not need to... Read more
TotalFinder 1.6.2 - Adds tabs, hotkeys,...
TotalFinder is a universally acclaimed navigational companion for your Mac. Enhance your Mac's Finder with features so smart and convenient, you won't believe you ever lived without them. Tab-based... Read more
Vienna 3.0.0 RC 2 :be5265e: - RSS and At...
Vienna is a freeware and Open-Source RSS/Atom newsreader with article storage and management via a SQLite database, written in Objective-C and Cocoa, for the OS X operating system. It provides... Read more
VLC Media Player 2.1.5 - Popular multime...
VLC Media Player is a highly portable multimedia player for various audio and video formats (MPEG-1, MPEG-2, MPEG-4, DivX, MP3, OGG, ...) as well as DVDs, VCDs, and various streaming protocols. It... Read more
Default Folder X 4.6.7 - Enhances Open a...
Default Folder X attaches a toolbar to the right side of the Open and Save dialogs in any OS X-native application. The toolbar gives you fast access to various folders and commands. You just click... Read more
TinkerTool 5.3 - Expanded preference set...
TinkerTool is an application that gives you access to additional preference settings Apple has built into Mac OS X. This allows to activate hidden features in the operating system and in some of the... Read more
Audio Hijack Pro 2.11.0 - Record and enh...
Audio Hijack Pro drastically changes the way you use audio on your computer, giving you the freedom to listen to audio when you want and how you want. Record and enhance any audio with Audio Hijack... Read more
Intermission 1.1.1 - Pause and rewind li...
Intermission allows you to pause and rewind live audio from any application on your Mac. Intermission will buffer up to 3 hours of audio, allowing users to skip through any assortment of audio... Read more
Autopano Giga 3.6 - Stitch multiple imag...
Autopano Giga allows you to stitch 2, 20, or 2,000 images. Version 3.0 integrates impressive new features that will definitely make you adopt Autopano Pro or Autopano Giga: Choose between 9... Read more
Airfoil 4.8.7 - Send audio from any app...
Airfoil allows you to send any audio to AirPort Express units, Apple TVs, and even other Macs and PCs, all in sync! It's your audio - everywhere. With Airfoil you can take audio from any... Read more

Latest Forum Discussions

See All

Exploration Focused Puzzle Game Beatbudd...
Exploration Focused Puzzle Game Beatbuddy Set to Make Transition from PC to iOS this September Posted by Jennifer Allen on July 28th, 2014 [ permalink ] | Read more »
PlanetHD
PlanetHD By Nadia Oxford on July 28th, 2014 Our Rating: :: SPACE MADNESSUniversal App - Designed for iPhone and iPad PlanetHD will keep players busy for a while, though its unpredictable physics are a handful to deal with.   | Read more »
This Week at 148Apps: July 21-25, 2014
Another Week of Expert App Reviews   At 148Apps, we help you sort through the great ocean of apps to find the ones we think you’ll like and the ones you’ll need. Our top picks become Editor’s Choice, our stamp of approval for apps with that little... | Read more »
Reddme for iPhone - The Reddit Client (...
Reddme for iPhone - The Reddit Client 1.0 Device: iOS iPhone Category: News Price: $.99, Version: 1.0 (iTunes) Description: Reddme for iPhone is an iOS 7-optimized Reddit client that offers a refreshing new way to experience Reddit... | Read more »
Jacob Jones and the Bigfoot Mystery : Ep...
Jacob Jones and the Bigfoot Mystery : Episode 2 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Jacob Jones is back in Episode 2 of one of Apples 'Best of 2013' games and an App Store... | Read more »
New Trailer For Outcast Odyssey, A New K...
New Trailer For Outcast Odyssey, A New Kind of Card Battler Posted by Jennifer Allen on July 25th, 2014 [ permalink ] Out this Fall is a new kind of card battle game: Outcast Odyssey. | Read more »
Hay Day – Tip, Tricks, Strategies, and C...
Recently got into Supercell’s other huge hit, Hay Day and could do with some advice on what to do? We’ve got you covered with some helpful trips and tricks to bear in mind! Ticking Along One of the key things to keep in mind while building up that... | Read more »
Monster Head Review
Monster Head Review By Nadia Oxford on July 25th, 2014 Our Rating: :: FEEDING TIMEUniversal App - Designed for iPhone and iPad Racking up a high score with Monster Head is trickier than it first appears. The appeal wears out fairly... | Read more »
Garfield: Survival of the Fattest Coming...
Garfield: Survival of the Fattest Coming to iOS this Fall Posted by Jennifer Allen on July 25th, 2014 [ permalink ] Who loves lasagna? Me. Also everyone’s favorite grumpy fat cat, Garfield. | Read more »
Happy Flock Review
Happy Flock Review By Andrew Fisher on July 25th, 2014 Our Rating: :: HERD IT ALL BEFOREUniversal App - Designed for iPhone and iPad Underneath the gloss of Happy Flock’s visuals is a game of very little substance. It’s cute, but... | Read more »

Price Scanner via MacPrices.net

13-inch 2.5GHz MacBook Pro on sale for $1099,...
Best Buy has the 13″ 2.5GHz MacBook Pro available for $1099.99 on their online store. Choose free shipping or free instant local store pickup (if available). Their price is $100 off MSRP. Price is... Read more
Roundup of Apple refurbished MacBook Pros, th...
The Apple Store has Apple Certified Refurbished 13″ and 15″ MacBook Pros available for up to $400 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free. Their prices... Read more
Record Mac Shipments In Q2/14 Confound Analys...
A Seeking Alpha Trefis commentary notes that Apple’s fiscal Q3 2014 results released July 22, beat market predictions on earnings, although revenues were slightly lower than anticipated. Apple’s Mac’... Read more
Intel To Launch Core M Silicon For Use In Not...
Digitimes’ Monica Chen and Joseph Tsai, report that Intel will launch 14nm-based Core M series processors specifically for use in fanless notebook/tablet 2-in-1 models in Q4 2014, with many models to... Read more
Apple’s 2014 Back to School promotion: $100 g...
 Apple’s 2014 Back to School promotion includes a free $100 App Store Gift Card with the purchase of any new Mac (Mac mini excluded), or a $50 Gift Card with the purchase of an iPad or iPhone,... Read more
iMacs on sale for $150 off MSRP, $250 off for...
Best Buy has iMacs on sale for up to $160 off MSRP for a limited time. Choose free home shipping or free instant local store pickup (if available). Prices are valid for online orders only, in-store... Read more
Mac minis on sale for $100 off MSRP, starting...
Best Buy has Mac minis on sale for $100 off MSRP. Choose free shipping or free instant local store pickup. Prices are for online orders only, in-store prices may vary: 2.5GHz Mac mini: $499.99 2.3GHz... Read more
Global Tablet Market Grows 11% in Q2/14 Notwi...
Worldwide tablet sales grew 11.0 percent year over year in the second quarter of 2014, with shipments reaching 49.3 million units according to preliminary data from the International Data Corporation... Read more
New iPhone 6 Models to Have Staggered Release...
Digitimes’ Cage Chao and Steve Shen report that according to unnamed sources in Apple’s upstream iPhone supply chain, the new 5.5-inch iPhone will be released several months later than the new 4.7-... Read more
New iOS App Helps People Feel Good About thei...
Mobile shoppers looking for big savings at their favorite stores can turn to the Goodshop app, a new iOS app with the latest coupons and deals at more than 5,000 online stores. In addition to being a... Read more

Jobs Board

*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
WW Sales Program Manager, *Apple* Online St...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
Lead Software Engineer, *Apple* Online Stor...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
Manager, *Apple* Fullfillment Operation (AF...
…cross-functional teams to drive the highest level of program management quality for Apple . You will help plan launch strategy and demand generation programs with Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.