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...

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Chromium 119.0.6044.0 - Fast and stable...
Chromium is an open-source browser project that aims to build a safer, faster, and more stable way for all Internet users to experience the web. List of changes available here. Version for Apple... Read more
Spotify 1.2.21.1104 - Stream music, crea...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
Tor Browser 12.5.5 - Anonymize Web brows...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Malwarebytes 4.21.9.5141 - Adware remova...
Malwarebytes (was AdwareMedic) helps you get your Mac experience back. Malwarebytes scans for and removes code that degrades system performance or attacks your system. Making your Mac once again your... Read more
TinkerTool 9.5 - 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
Paragon NTFS 15.11.839 - Provides full r...
Paragon NTFS breaks down the barriers between Windows and macOS. Paragon NTFS effectively solves the communication problems between the Mac system and NTFS. Write, edit, copy, move, delete files on... Read more
Apple Safari 17 - Apple's Web brows...
Apple Safari is Apple's web browser that comes bundled with the most recent macOS. Safari is faster and more energy efficient than other browsers, so sites are more responsive and your notebook... Read more
Firefox 118.0 - Fast, safe Web browser.
Firefox offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals and casual... Read more
ClamXAV 3.6.1 - Virus checker based on C...
ClamXAV is a popular virus checker for OS X. Time to take control ClamXAV keeps threats at bay and puts you firmly in charge of your Mac’s security. Scan a specific file or your entire hard drive.... Read more
SuperDuper! 3.8 - Advanced disk cloning/...
SuperDuper! is an advanced, yet easy to use disk copying program. It can, of course, make a straight copy, or "clone" - useful when you want to move all your data from one machine to another, or do a... Read more

Latest Forum Discussions

See All

‘Monster Hunter Now’ October Events Incl...
Niantic and Capcom have just announced this month’s plans for the real world hunting action RPG Monster Hunter Now (Free) for iOS and Android. If you’ve not played it yet, read my launch week review of it here. | Read more »
Listener Emails and the iPhone 15! – The...
In this week’s episode of The TouchArcade Show we finally get to a backlog of emails that have been hanging out in our inbox for, oh, about a month or so. We love getting emails as they always lead to interesting discussion about a variety of topics... | Read more »
TouchArcade Game of the Week: ‘Cypher 00...
This doesn’t happen too often, but occasionally there will be an Apple Arcade game that I adore so much I just have to pick it as the Game of the Week. Well, here we are, and Cypher 007 is one of those games. The big key point here is that Cypher... | Read more »
SwitchArcade Round-Up: ‘EA Sports FC 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 29th, 2023. In today’s article, we’ve got a ton of news to go over. Just a lot going on today, I suppose. After that, there are quite a few new releases to look at... | Read more »
‘Storyteller’ Mobile Review – Perfect fo...
I first played Daniel Benmergui’s Storyteller (Free) through its Nintendo Switch and Steam releases. Read my original review of it here. Since then, a lot of friends who played the game enjoyed it, but thought it was overpriced given the short... | Read more »
An Interview with the Legendary Yu Suzuk...
One of the cool things about my job is that every once in a while, I get to talk to the people behind the games. It’s always a pleasure. Well, today we have a really special one for you, dear friends. Mr. Yu Suzuki of Ys Net, the force behind such... | Read more »
New ‘Marvel Snap’ Update Has Balance Adj...
As we wait for the information on the new season to drop, we shall have to content ourselves with looking at the latest update to Marvel Snap (Free). It’s just a balance update, but it makes some very big changes that combined with the arrival of... | Read more »
‘Honkai Star Rail’ Version 1.4 Update Re...
At Sony’s recently-aired presentation, HoYoverse announced the Honkai Star Rail (Free) PS5 release date. Most people speculated that the next major update would arrive alongside the PS5 release. | Read more »
‘Omniheroes’ Major Update “Tide’s Cadenc...
What secrets do the depths of the sea hold? Omniheroes is revealing the mysteries of the deep with its latest “Tide’s Cadence" update, where you can look forward to scoring a free Valkyrie and limited skin among other login rewards like the 2nd... | Read more »
Recruit yourself some run-and-gun royalt...
It is always nice to see the return of a series that has lost a bit of its global staying power, and thanks to Lilith Games' latest collaboration, Warpath will be playing host the the run-and-gun legend that is Metal Slug 3. [Read more] | Read more »

Price Scanner via MacPrices.net

Clearance M1 Max Mac Studio available today a...
Apple has clearance M1 Max Mac Studios available in their Certified Refurbished store for $270 off original MSRP. Each Mac Studio comes with Apple’s one-year warranty, and shipping is free: – Mac... Read more
Apple continues to offer 24-inch iMacs for up...
Apple has a full range of 24-inch M1 iMacs available today in their Certified Refurbished store. Models are available starting at only $1099 and range up to $260 off original MSRP. Each iMac is in... Read more
Final weekend for Apple’s 2023 Back to School...
This is the final weekend for Apple’s Back to School Promotion 2023. It remains active until Monday, October 2nd. Education customers receive a free $150 Apple Gift Card with the purchase of a new... Read more
Apple drops prices on refurbished 13-inch M2...
Apple has dropped prices on standard-configuration 13″ M2 MacBook Pros, Certified Refurbished, to as low as $1099 and ranging up to $230 off MSRP. These are the cheapest 13″ M2 MacBook Pros for sale... Read more
14-inch M2 Max MacBook Pro on sale for $300 o...
B&H Photo has the Space Gray 14″ 30-Core GPU M2 Max MacBook Pro in stock and on sale today for $2799 including free 1-2 day shipping. Their price is $300 off Apple’s MSRP, and it’s the lowest... Read more
Apple is now selling Certified Refurbished M2...
Apple has added a full line of standard-configuration M2 Max and M2 Ultra Mac Studios available in their Certified Refurbished section starting at only $1699 and ranging up to $600 off MSRP. Each Mac... Read more
New sale: 13-inch M2 MacBook Airs starting at...
B&H Photo has 13″ MacBook Airs with M2 CPUs in stock today and on sale for $200 off Apple’s MSRP with prices available starting at only $899. Free 1-2 day delivery is available to most US... Read more
Apple has all 15-inch M2 MacBook Airs in stoc...
Apple has Certified Refurbished 15″ M2 MacBook Airs in stock today starting at only $1099 and ranging up to $230 off MSRP. These are the cheapest M2-powered 15″ MacBook Airs for sale today at Apple.... Read more
In stock: Clearance M1 Ultra Mac Studios for...
Apple has clearance M1 Ultra Mac Studios available in their Certified Refurbished store for $540 off original MSRP. Each Mac Studio comes with Apple’s one-year warranty, and shipping is free: – Mac... Read more
Back on sale: Apple’s M2 Mac minis for $100 o...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $100 –... Read more

Jobs Board

Licensed Dental Hygienist - *Apple* River -...
Park Dental Apple River in Somerset, WI is seeking a compassionate, professional Dental Hygienist to join our team-oriented practice. COMPETITIVE PAY AND SIGN-ON Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Sep 30, 2023 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
*Apple* / Mac Administrator - JAMF - Amentum...
Amentum is seeking an ** Apple / Mac Administrator - JAMF** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Child Care Teacher - Glenda Drive/ *Apple* V...
Child Care Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter 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.