TweetFollow Us on Twitter

Resource Jargon

Volume Number: 13 (1997)
Issue Number: 2
Column Tag: Toolbox Techniques

The Language of Resources

By Chris Stasny

A common sense introduction to the Resource Manager

Say Again?

I discovered a new version of English when I worked the oil fields of Trinidad years ago. Part of this dialect's uniqueness was due to the influence of multiple cultures on the island - notable for its heavy and complex accent. Eventually, I learned how to respond to things like, "And me anudder spanner. Dees one's too slight." (He wanted a larger wrench.)

Some years later I discovered that the Macintosh contained its own rendition of English, where common terms were linked in new ways to form powerful commands. This is clearly demonstrated in Resource Manager calls. Terms like USERESFILE and SETRESATTRS turn out to be everything expected and more. This article will focus on some common resource handling operations. While our syntax will be that of FutureBASIC II, the toolbox calls are so easily recognizable that programmers of all linguistic persuasions should be able to follow along without difficulty.

Resource Files

We all know that our application's resource fork is open and available. Some of us understand that the System's resource file is also open and available. In real life, there are usually between twenty and a hundred resource files open at any given moment, on any given Mac. Remember all of those font files and sound files that you dumped into the System Folder?

The layers of resources are guided strictly by the order they were opened via commands like OPENRESFILE or OPENRFPERM. If you think of your Mac as an oil drum, the System file is thrown into the barrel first and always resides at the bottom. It is followed by a plethora of extensions and additions that come online during startup. We cannot change this order. When we open a resource file, it is always thrown on top. [There are some exceptions. Most notably, CTB tools are loaded below the System resources. -ed.]

Application Heaps

When an application is double-clicked into life, a divider is used to segment the barrel in such a way that the application's resources are isolated from those of other programs. This divider does not extend all the way to the bottom of the drum, where system resources remain pooled and available for all to use. This means that resource files opened by that application can look down upon both application and system resources without ever being aware of items (owned by other applications) on the other side of the divider. This segment of the barrel is known as the application heap.

The search pattern here is important. If we ask the Resource Manager for a chunk of bits, it will respond by searching the top levels of information in our application's quadrant of the barrel. Each failure forces it to submerge deeper into the drum until it eventually finds itself scanning the System resources at the bottom. It is not possible to change this order. At best, we can tell the Resource Manager to start at a deeper level and ignore some of the sludge that has floated to the top. We do this with CALL USERESFILE(resRef).

After USERESFILE, we have effectively chopped off the top portion of the barrel, and items opened after the target file become invisible to the system. This procedure, when improperly used, often sends a program into a death spiral. Our first mistake is to assume that the call somehow changes the order of resource files. This is impossible. Our second mistake is to assume that we can put things right by calling USERESFILE with the application's resource reference number. This is also a fantasy. Here is the only safe way to switch forks in mid stream:

origRes = FN CURRESFILE
CALL USERESFILE(resRef)

‘ Handle your file-specific resource operations here.

CALL USERESFILE(origRes)

Rules to Load By

Let's backtrack for a moment to re-examine the operations involved in opening a resource file. During this operation, the Resource Manager loads a map into memory that lists all of the blocks behind the doors of the newly opened file. If, during creation of that map, the Manager sees something that the programmer marked as "Pre-load," the information is actually moved from the disk into RAM. (The resource can be marked this way either by checking the appropriate box in ResEdit or Resourcerer, or by using SETRESATTRS.)

When we look for a resource with a statement like FN GETRESOURCE, we don't actually dig through RAM searching for our unique block. The Resource Manager scans the maps that are held in memory to see if an entry matches our needs. This entry must be the same resource type with the proper ID or name. Our Manager, clever fellow that he is, does not blindly load a resource when he locates the entry. He first checks to see if the resource has been previously loaded and, if so, returns a handle to the existing item.

Toolbox calls that obtain resource handles are governed by very specific rules. Normally, the resource is moved from disk to memory, but you can circumvent this in cases where you may wish to do something like record and list available resources. The following example records the names of all sound resources without actually loading them into memory.

DIM sndName$(100)

‘ Don't load - just look
CALL SETRESLOAD(_false)

‘ Get res count, but don't let it extend past
‘ the arbitrary limits of the string array.
theCount = FN COUNTRESOURCES(_"snd ")
if theCount > 100 then theCount = 100

‘ Get each resource handle and request 
‘ info on it.
FOR i = 1 TO theCount
 rHndl& = FN GETINDRESOURCE(_"snd ",i)
 CALL GETRESINFO(rHndl&,rID,rType&,rName$)
 sndName$(i) = rName$
NEXT

‘ Restore normal resource loading
CALL SETRESLOAD(_zTrue)

The example used COUNTRESOURCES and GETINDRESOURCE. These calls start at the top of the barrel and continue until they encounter the aging rusty steel at the bottom. (Don't forget, if USERESFILE was invoked, the top of the barrel may have been cut off, and our point of origin for the search may have started lower in the drum than expected.) We could have easily examined the resources that existed in one file to the exclusion of all others by switching to calls that contain "1" in their names. FN COUNT1RESOURCES would return the number of sound resources in the most recently designated file. FN GET1INDRESOURCE would retrieve the indexed resource only in that file.

Let's bring this all together in a routine that searches for sound resources in the System file.

DIM sndName$(100)
origRes = FN CURRESFILE

‘ Ignore anything above the System file.
CALL USERESFILE(0)
CALL SETRESLOAD(_false)

‘ We only want resources in the current file.
theCount = FN COUNT1RESOURCES(_"snd ")
if theCount > 100 then theCount = 100
FOR i = 1 TO theCount

‘ Get indexed resources only from the top file.
 rHndl& = FN GET1INDRESOURCE(_"snd ",i)
 CALL GETRESINFO(rHndl&,rID,rType&,rName$)
 sndName$(i) = rName$
NEXT
CALL SETRESLOAD(_zTrue)

‘ Put things back like we found them.
CALL USERESFILE(origRes)

We have now clearly established the limits of a resource operation. USERESFILE tells us where to start searching, and a "1" in the toolbox name tells us that we should stop after searching a single file. Absence of the "1" forces our search to extend to the deepest recesses of the drum.

Shared Responsibilities

In most cases resources are loaded into memory and used, rather than just being inventoried and listed. The conditions under which these items enter RAM is another perplexing methodology that begs for explanation. The complexity centers around the fact that the management of a resource becomes the shared responsibility of the Resource and Memory Managers.

The Resource Manager begins by examining a resource's attributes to see if it should be purgeable or locked, and allocates the correct memory through FN NEWHANDLE. It can even be loaded into the system heap instead of the application heap, so that it may be shared with other applications that can look downward from their side of the dividers and see it. You may recognize these attributes as check boxes in ResEdit dialogs that are labeled Purgeable, Lock, and System Heap.

Armed with attribute information, the Resource Manager asks the Memory Manager (politely, of course) for a block of memory that is purgeable (or not), locked (or not), or in the system or application heap. Information is moved into that block. This is (practically) the only time resource attributes are examined - when the resource is loaded. From this point forward, the Memory Manager is in charge of the block. Memory Manager calls like HLOCK and HNOPURGE are used to handle the item as it floats around in the heap.

There is one very important exception to this rule. Never use CALL DISPOSEHANDLE on a resource handle. The Memory Manager would carry out its assignment by throwing away the information contained in the handle, but the Resource Manager (who was diligently tracking the block on his own personal tiny clipboard) would be left with a firm grip on an indeterminate chunk of RAM. It's not a pretty sight.

Lock and Purge

To lock or not to lock. That is the question. Most of the time, when I am called upon to debug a particular resource operation, I see abuses that would be too embarrassing to discuss on a daytime talk show. We have a tendency to ignore the attributes set up by the programmer who created the resource in the first place. As with SETRESLOAD and USERESFILE, we need to remain conscious of the creator's intent as we manipulate these items.

Assume that your application has a large preference resource that is loaded at startup. If we lock this piece of information in place, we have locked up a big, otherwise usable piece of binary real estate. Making it non-purgeable would have a similar effect. It may be our intent to move the entire resource into a global record or to examine individual pieces and branch to other operations. Either way, this resource would be marked as purgeable by its creator, but must temporarily be held in memory. We do it like this:

rHndl& = FN GETRESOURCE(_"PREF",_myPrefID)
LONG IF rHndl&

 ‘ Record the status of the handle.
 hState = FN HGETSTATE(rHndl&)

 ‘ Make sure it stays in memory.
 OSErr = FN HNOPURGE(rHndl&)

 ‘ Handle resource operations here,
 ‘ then restore the handle to its original state.
 OSErr = FN HSETSTATE(rHndl&,hState)
END IF

Some toolbox routines handle purging without a programmer's assistance. Picture resources are among the most abused in all of Mac-dom. Take the following (really bad) example.

‘ Bad example! Don't try this at home.

DIM t,l,b,r

rHndl& = FN GETPICTURE(_myPictureID)
OSErr = FN HLOCK(rHndl&)
t;8 = [rHndl&]+_picFrame
CALL OFFSETRECT(t,-l, -t)
CALL DRAWPICTURE(rHndl&,t)
CALL DISPOSEHANDLE(rHndl&)

This example was so wretched that it was painful to type, but it represents the type of resource handling that is common in most programs. The first error was to lock the picture handle. If this picture was to be used often during the course of an application (as might be the case with a tool palette picture), its creator would have marked it as non-purgeable. In most cases, even the purgeable attribute would be turned off so that the picture could be expunged if required. Locking is generally a bad thing and would normally be done only on a temporary basis. (Remember HGETSTATE and HSETSTATE?) In our case, the HLOCK was unnecessary, since QuickDraw manages this particular resource during its operation, and undesirable since low-level picture operations may actually move or resize the picture resource.

Our next major mistake was to assume that the picture was loaded into memory. We immediately went to work on a resource handle without checking it for validity. Then, we disposed of the handle, which was being jointly tracked by the Resource Manager and the Memory Manager. Since DISPOSEHANDLE is a Memory Manager call, the Resource Manager was left out of the operation and is likely to cause serious damage when it next reaches for that resource.

Here's how we should have handled the operation.

  DIM t,l,b,r
 
  rHndl& = FN GETPICTURE(_myPictureID)
  LONG IF rHndl&
   t;8 = [rHndl&]+_picFrame
   CALL OFFSETRECT(t,-l, -t)
   CALL DRAWPICTURE(rHndl&,t)
  END IF

If this was a startup picture, it would probably never be needed again. The moment that the memory it occupied was required for some other operation, the picture would be purged from RAM. On the other hand, if the application's partition was large and the user's requirements small, it might remain in place for the duration.

Later, when the user decided to view the application's "About" box, we would use exactly the same routine to display the picture a second time. If plenty of space was available and the picture had managed to remain in memory, it would not be reloaded. A handle to the existing data would be returned from FN GETPICTURE. If constraints had forced the resource out of memory, it would be reloaded as a result of the call. This debugged example was more memory-efficient, and took fewer lines of code.

Handle Hand-off

While the ownership of resource handles seems to be preordained, we may still exercise control over who will ultimately own the handle. A call to DETACHRESOURCE does this. It pulls the resource's entry from a file's resource map. It does not remove the handle from memory or change the attributes of that handle. After this call, the Memory Manager controls the block, and the Resource Manager ceases to acknowledge its existence. If you wish to dispose of it, you'll have to use DISPOSEHANDLE.

While there is no call that completely releases a Memory Manager handle to the control of the Resource Manager, there is a procedure that turns a handle into a resource: ADDRESOURCE. This call takes a great deal of setup and is best documented in FN pGreplaceRes in the Runtime.INCL file of a Program Generator project. But there are some important rules that deserve attention. When a resource is added, it is added to the current resource file. Use CURRESFILE and USERESFILE to change this during such operations. Adding a resource is a blind operation that allows duplication. If you add a preference resource to your application three times, you'll end up with three copies of the resource in your file.

Slow Execution

Because most folks have a hard time understanding resources, there is a tendency to write out a resource every time it is modified. Apple engineers are no exception. Most of us remember the early days of the Macintosh 840AV. An uninformed ROM rat patched the toolbox call CHANGEDRESOURCE to make it call UPDATERESFILE each time it was called. This was a bad thing. Let me explain why.

When your program calls UPDATERESFILE or WRITERESOURCE, the entire file may be written to disk. Remember that resources are not really magical. They occupy space on a disk, and are ordered according to strict internal guidelines. If you replace a picture that is 50K with one that is 100K, there is no sorcerer's potion that compresses the new resource into the same space used by the old one. The file is simply rewritten, starting at the beginning of the old 50K resource.

When the AV's were first released, folks complained that resource handlers like ResEdit and Program Generator slowed to a crawl. This is because a simple operation (CHANGEDRESOURCE), which was supposed to set a single bit in a single flag, ended up rewriting the file. The reality is that it is almost never necessary to update the file or write its resources. This happens automatically when the file is closed.

There is one additional feature of CHANGEDRESOURCE that deserves attention: You should never call CHANGEDRESOURCE on a purgeable block. When the file is closed, the Resource Manager scans its list to see what has been modified. Then it rewrites the file with these new items in place. If, in the interim, the Memory Manager has purged the block, you will see random data written to the disk. If you have ever seen a file explode from a few hundred K to several megabytes, this is the likely reason. Mark resources in the following manner to prevent this problem.

OSErr = FN HNOPURGE(rHndl&)
CALL CHANGEDRESOURCE(rHndl&)

Conclusion

Our list of rules to live by grows ever more complex. In the olden days, we were just supposed to remember not to tug on Superman's cape or spit into the wind. Now we must watch resource attributes and referee a tenuous cease-fire between two headstrong Macintosh Managers. My friends from Trinidad might beg for simplicity. "And me anudder monager. Dees ones too complex."

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.