TweetFollow Us on Twitter

Utility In Utilities

Volume Number: 15 (1999)
Issue Number: 6
Column Tag: PowerPlant Workshop

Utility in Utilities

by John C. Daub, Austin, Texas USA

Exploring the PowerPlant Utility Classes

In The Details

When you first learn PowerPlant, you must concern yourself with the larger notions of The Framework - the event handler, the view hierarchy, the Commander chain, Broadcasters and Listeners. These are core, foundational aspects of PowerPlant that you must know and understand to begin writing applications in PowerPlant. After you have the core down and have hacked out your first PowerPlant app, you start to explore new areas of The Framework: perhaps the Networking Classes, Internet Classes, Threads, AppleScript-ability. Those areas are certainly all good, however I'd like to suggest one group of classes and code that you might not have thought to take a further look at. All the little classes that exist in both cohesive groups and scattered one-shots throughout The Framework - Utility Classes.

Utility Classes are an important part of any framework. They help you accomplish the work you need to do by perhaps simplifying an API, or providing means to manage other objects and states, or maybe just consolidate a lot of (perhaps commonly used) code into a single function call. Utilities won't solve all of your programming problems, but they certainly should prove to find a useful place in your toolbox as they alleviate a lot of the headaches you encounter on a daily basis. Working the use of such utilities into your coding habits can help you write more robust and less-error-prone code from the onset.

General Framework Utilities

Most of the Utility Classes in PowerPlant can be classified into a couple groups, with a few left over. We'll take a brief look at them all. By the way, you can follow along in source code by opening your Utility Classes folder and reading each source file as we get to it.

Core

There are some Utility Classes that implement the internal support structure for portions of The Framework's functionality. UReanimator and URegistrar are two such core classes, as they are central to the PPob mechanism. These classes implement the ability to instantiate your PPob at runtime. UReanimator reads the 'PPob' DataStream and calls the proper object constructor/creation-routine - found by a table lookup to URegistrar - to reanimate your PPob (Window, Dialog, etc.). UDebugging and UException are another file combination, implementing the core debugging and exception handling infrastructure for PowerPlant. UCursor implements basic cursor handling. UEnvironment collects, maintains, and provides a query mechanism on particular environmental information (EnvironmentFeature), such as if a certain technology is present (Drag and Drop, Thread Manager, Appearance Manager, etc.). These core classes are used throughout PowerPlant by the framework itself, and of course you are free to use them. In fact, you should use these facilities provided by The Framework because if you write to PowerPlant's API, you can many-times be shielded from the pains of OS conversions (especially useful as we move towards Carbon) as well as pick up any advances/fixes from PowerPlant for free.

An important piece of, as well as a recent addition to, the core utilities is UAppearance. UAppearance is a strange but useful class for working with the Appearance Manager, especially Appearance Manager v1.1. In Appearance Manager 1.1 (released as a part of Mac OS 8.5), Apple introduced Themes. Themes were a way to modify the overall cosmetic look and feel of your Mac (akin to the shareware Kaleidoscope). For whatever reason, Themes didn't come to pass in OS 8.5, but nevertheless PowerPlant worked to try to be as Theme-savvy as possible. One problem faced was how to support the various versions of the Appearance Manager (v1.0, v1.0.x, v1.1) from a unified API. Furthermore, OS 8.5 was PowerPC-only, which meant Appearance Manager 1.1 was PPC-only as well. As PowerPlant must work on both 68K and PPC from the same codebase, what to do to allow ones code to work properly with Themes, all Appearance Manager versions, and possible runtime architectures? Whew! Enter UAppearance, consolidating the various means for determining Appearance-related information into a single-API. If you need to get the text color, call UAppearance::GetThemeTextColor() and it will Do The Right Thing® based upon compile and runtime options. Read the source (that includes reading the header, too!) to get the low-down. UAppearance doesn't bridge all such needs that might exist in the Toolbox, just what PowerPlant itself needs. Of course, if you need to obtain this information in any of your code, do use the UAppearance bottlenecks as they should always Do The Right Thing.

Encapsulated Functionality

Some Utility Classes work to consolidate common behaviors into groups and easy-to-call functions. UTextTraits provides the complete functionality needed by The Framework to work with TextTraits Resources ('Txtr'). UWindows provides implementations of some common window manipulation routines, like getting the content and structure Rects. UScreenPort creates a GrafPort the size of the GrayRgn (see UFloatingDesktop for use). UPrintingMgr provides wrappers for some common printing needs. UKeyFilters provides the functionality to implement KeyFilters (as used by classes like LEditField and LEditText).

UDrawingState and UDrawingUtils are two of the more commonly used portions of this group. If you look in those source files, you'll see there's a lot of good stuff. UDrawingState is mainly a collection of small stack-based classes for saving/restoring drawing states: GrafPort, color, pen, text style, clipping region, port origin. I'll speak about stack-based classes in greater depth later in this article. UDrawingState also contains stack-based classes for manipulating the visRgn and the CQDProcs. UDrawingUtils is a general collection of routines for drawing behaviors. UTextDrawing performs various text renderings, akin to TETextBox only better. LMarchingAnts and UMarchingAnts can help you implement a marquee selection (see also LMarqueeTask in the Constructor Additions). UDrawingUtils and StColorDrawLoop help to work with drawing devices so PowerPlant can Draw() in a device-friendly manner (e.g. proper rendering of widgets when they straddle multiple monitors each set at a different bit-depth).

Other

Finally, some classes don't fit into any nice grouping. UAttachments contains many simple, pre-made Attachment classes. UProfiler contains a simple stack-based class to aid working with the Metrowerks Profiler. UQDOperators.h implements some global operators for easily comparison of some QuickDraw data types. Most of the routines in the Utility Classes are small and quick, simple to understand and use. Many are stack-based classes, and those hold a special bit of functionality within the Utility classes.

Exception Safety and Resource Management

One powerful feature of C++ is its error handling mechanism - exceptions. One joy of exceptions is they can interrupt the flow of execution when something goes wrong. But, this same joy can bring problems in that the normal flow of execution normally ended with a cleaning up of resources, for example:

   {
      Handle      theHandle   = ::NewHandle(kSize);
      ThrowIfMemFail_(theHandle);

      DoSomething(theHandle);      // Could throw an exception.

      ::DisposeHandle(theHandle);
   }

If DoSomething() causes an exception to be thrown, the stack will unwind and ::DisposeHandle() will never be called causing theHandle to be leaked with no possible means of cleaning it up. Not a desirable situation. You could handle this problem with a try/catch block:

   {
      Handle      theHandle = ::NewHandle(kSize);
      ThrowIfMemFail_(theHandle);

      try {
         DoSomething(theHandle);    // Could throw an exception.
      } catch(...) {
         
            // Perform cleanup
         ::DisposeHandle(theHandle);

            // Rethrow the exception
         throw;
      }

      ::DisposeHandle(theHandle);
   }

The above certainly works and handles the situation, but it feels overkill for such a simple situation. Furthermore, in more complex situations than this trivial example, littering your code with too many try/catch blocks can get to be cumbersome. Instead, consider exploiting a power hook of the C++ language: the destructor. Whenever a C++ object is destroyed (by calling delete on a heap-based object, or going out of scope on a stack-based object), it is guaranteed that the destructor will be called. You can exploit this hook to aid in the management of resources (which aren't necessarily Mac OS Resources, but certainly can be); this is what stack-based classes are all about. Let's look at how this works in greater detail by examining probably the most frequently-utilized group of stack-based classes in PowerPlant: UMemoryMgr, and specifically StHandleBlock.

The basic premise behind a stack-based class is the constructor does something and the destructor undoes it. Push-Pop. Hence, stack-based. A common paradigm in programming is to temporarily change the state of something by saving off its current state, changing it to the new state, doing whatever work you needed to do, then restoring the original state. Such situations are prime for stack-based classes, and the classes of UDrawingState are perfect examples of this lot (StColorPenState). Other stack-based classes still function on the same push-pop paradigm (say that five times fast!), but provide greater functionality to the user; StHandleBlock is a good example of this sort of class.

StHandleBlock is a stack-based class that manages a Mac OS Handle. (I'm sure by now you've noticed the PowerPlant convention of naming (most) stack-based classes with an St prefix). The StHandleBlock constructors either take ownership of an existing Handle or allocate a new one (::NewHandle()). There are routines to manipulate the Handle, so you can treat an StHandleBlock object as a Handle in your code. And most importantly the StHandleBlock destructor disposes of the Handle. One benefit of the class is that the Dispose() method is smart and checks first to see if the Handle is a Memory or Resource Handle, calling ::DisposeHandle() or ::ReleaseResource() as appropriate (no more need for the DisposeResource INIT). StHandleBlock is fairly straightforward, and most of your use of the class in code will be fairly boring and uneventful. The joy the class brings comes in terms of cleanup.

Again, StHandleBlock is a stack-based class - whenever the object leaves scope (since you do tend to create stack-based classes on the stack...), the destructor for the object will be called. Think about the ways that you can leave scope. You could leave them normally, like reaching the bottom of the function. You could leave abnormally, perhaps as a goto or as a result of an error or exception. But no matter how you leave, the (StHandleBlock ) object leaves scope and its destructor is called thereby undoing whatever you did (::DisposeHandle())and leaving the world in the state that you found it. So we can rewrite our above code snippet like this:

   {
      StHandleBlock   theHandle(kSize);
      DoSomething(theHandle);
   }

Yea, that's all the code becomes, and therein is part of the joy. The StHandleBlock constructor will try to allocate a Handle of the requested kSize, failure resulting in an exception being thrown (due to the constructor that we used, see the source for more details). Once that returns, theHandle is now a valid StHandleBlock object with a Handle of size kSize, just like before. Through the magic of an implicit type conversion operator, theHandle can be passed directly to DoSomething() as argument. If DoSomething() should throw an exception, theHandle will go out of scope and ::DisposeHandle(mHandle). If DoSomething() does not throw and the routine exits normally, theHandle still goes out of scope and ::DisposeHandle(mHandle). By use of StHandleBlock, no functionality has been lost, and the gains of resource management and exception safety have been won. You just write it and forget it. Your code is now more robust, less chance for error, and Spotlight should hopefully find your code more agreeable (and then so should your customers!).

Certainly the use of the stack-based class isn't without cost (Meyers discusses costs of C++ in More Effective C++). There is the overhead of the object itself, the storage requirements (in addition to the storing of the normal data, be it a Handle or Ptr or Str255 or what have you), the time involved to create/dispose the object. In most situations these are worthwhile tradeoffs. If exception safety is needed, if delegating the responsibility of cleanup to the object itself is desired, then by all means use the classes. But there are occasions where it's more wasteful to use them, e.g.:

   {
      Handle      theHandle   = ::NewHandle(kSize);
      ::BlockMoveData(dataPtr, *theHandle, 
                           ::GetPtrSize(dataPtr));
      ::DisposeHandle(theHandle);
   }

In the above code, theHandle was allocated, used, and disposed of with no chance for the flow of execution to change unexpectedly. Using StHandleBlock here is certainly legal and fine to do, but is not as efficient as is direct Toolbox access. Base your approach upon the context.

If you like StHandleBlock, check out StTempHandle and StClearHandleBlock which are subclasses of StHandleBlock that allocate a Handle in temporary memory and allocate a cleared Handle, respectively. Related to StHandleBlock is StPointerBlock (and StClearPointerBlock); these classes behave similar to their Handle counterparts, but maintain a Mac OS Ptr rather than a Handle. UMemoryMgr also contains a PowerPlant version of std::auto_ptr<T> called PP_PowerPlant::StDeleter<T>; StDeleter is functionally equivalent to auto_ptr, but exists to minimize dependencies upon the C++ standard library. StHandleLocker merely locks a Handle and ensures a proper restoration of the Handle state, which allows StHandleLocker objects to be nested safely. Furthermore, StHandleLocker implements Handle locking in a scheme consistent with Apple TechNote 1122, which discusses the proper way to lock a Handle.

Related to UMemoryMgr is URegions. URegions is comprised of two classes: StRegion and StRegionBuilder, providing similar functionality as StHandleBlock, but specifically tuned towards working with Mac OS Regions. Not only is the creation/destruction of the RgnHandle accounted for, but all manner of operator overloads and methods are provided to facilitate working with Regions - never has working with Regions been so simple! StRegionBuilder works in conjunction with StRegion to facilitate the on-the-fly creation of Regions. As you use these classes in your own code, you start to see how through their use throughout your code, the tighter the web they weave to keep code clean and properly coping with unexpected problems when they crop up.

UMemoryMgr is a prime example of how stack-based classes can help you better manage your resources, eliminate memory leaks, eliminate stale state information, be exception-safe, and write more robust code. These sorts of utility classes should find their way into your toolbox as need for them arises. Explore. If you'd like to learn more about the concepts these classes are based upon, check out C++ FAQs by Cline and Lomow, and Scott Meyers' excellent books Effective C++ and More Effective C++.

More Than Utility Classes

There are a good many "utility" classes throughout PowerPlant; it's not isolated to only those files and classes located with the Utility Classes folder. Many of the other folders contain "utility" type classes, and many files have little utility classes and/or methods to ease working with other classes within the same file.

The Support Classes folder is a prime example of another set of "utility" classes. With classes for working with the Clipboard (LClipboard), GrowZones (LGrowZone), tracking the mouse (LMouseTracker), manipulating windows (UDesktop and UFloatingDesktop), and of course we can't forget LString. The In Progress folder also houses a number of utility classes (at least at the time of this writing, looking at PowerPlant 2.0). There are utilities for working with graphics (LGAIconMixin, LGATitleMixin, UGAColorRamp, UGraphicUtils), menus, StuffIt archives, contextual menus. AppleEvent Classes folder has UAppleEventsMgr and UExtractFromAEDesc.

Contained within many source files are utilities for the particular main class. In LModelObject.h, you'll find the StLazyLock and StTempTellTarget classes that facilitate working with LModelObject. TSharablePtr is a smart-pointer class for working with LSharable objects (reference counting). And the lists can go on.

Fin

Utility Classes are an essential part of any framework. They are tidbits of code that help make our life a little bit easier by letting us write one line instead of ten, automate some process, facilitate another process. They help our code be more robust through exception-safety and resource management. They help us out in the long run because we can write more trouble-free code from the start, which means less time wasted debugging and more time spent refining the features of your killer app.

I hope this brief tour of the Utility Classes in PowerPlant has shown you something new, perhaps some unexplored area of PowerPlant. Stack-based classes are a great part of the Utility classes and are probably a good place for you to start to get familiar with these classes. But don't stop there! Read the source code and see what else PowerPlant has to offer. There are lots of nooks and crannies in PowerPlant that hold some really neat stuff. The more you know, the more you can do.

Happy programming!

Bibliography

  • Dow, Greg. Chief PowerPlant Architect.
  • Hinnant, Howard. Metrowerks C++ Library Wizard.

URLs


John C. Daub loves his new WallStreet/DVD - it's what he's using to type this article. John is transitioning to a new position with Pervasive Software working on the Mac Editor portion of Tango. At the time of this writing, John has been with the company three weeks and is having fun! As always, you can reach John via email at <hsoi@pobox.com>, or feel free to drop him a line at <John.Daub@pervasive.com> (IS won't let him have "hsoi" ;-)

 
AAPL
$119.00
Apple Inc.
+1.40
MSFT
$47.75
Microsoft Corpora
+0.28
GOOG
$540.37
Google Inc.
-0.71

MacTech Search:
Community Search:

Software Updates via MacUpdate

RapidWeaver 6.0.3 - Create template-base...
RapidWeaver is a next-generation Web design application to help you easily create professional-looking Web sites in minutes. No knowledge of complex code is required, RapidWeaver will take care of... Read more
iPhoto Library Manager 4.1.10 - Manage m...
iPhoto Library Manager lets you organize your photos into multiple iPhoto libraries. Separate your high school and college photos from your latest summer vacation pictures. Or keep some photo... Read more
iExplorer 3.5.1.9 - View and transfer al...
iExplorer is an iPhone browser for Mac lets you view the files on your iOS device. By using a drag and drop interface, you can quickly copy files and folders between your Mac and your iPhone or... Read more
MacUpdate Desktop 6.0.3 - Discover and i...
MacUpdate Desktop 6 brings seamless 1-click installs and version updates to your Mac. With a free MacUpdate account and MacUpdate Desktop 6, Mac users can now install almost any Mac app on macupdate.... Read more
SteerMouse 4.2.2 - Powerful third-party...
SteerMouse is an advanced driver for USB and Bluetooth mice. It also supports Apple Mighty Mouse very well. SteerMouse can assign various functions to buttons that Apple's software does not allow,... Read more
iMazing 1.1 - Complete iOS device manage...
iMazing (was DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can: Copy music to and from... Read more
PopChar X 7.0 - Floating window shows av...
PopChar X helps you get the most out of your font collection. With its crystal-clear interface, PopChar X provides a frustration-free way to access any font's special characters. Expanded... Read more
Carbon Copy Cloner 4.0.3 - Easy-to-use b...
Carbon Copy Cloner backups are better than ordinary backups. Suppose the unthinkable happens while you're under deadline to finish a project: your Mac is unresponsive and all you hear is an ominous,... Read more
ForeverSave 2.1.3 - Universal auto-save...
ForeverSave auto-saves all documents you're working on while simultaneously doing backup versioning in the background. Lost data can be quickly restored at any time. Losing data, caused by... Read more
Voila 3.8.1 - Capture, annotate, organiz...
Voila is a screen-capture, recording, and annotation tool that is a full-featured replacement for Mac's screen-capture and screen-recording capabilities. It has a large and robust set of editing,... Read more

Latest Forum Discussions

See All

Make Way for Fat Chicken, from the Maker...
Make Way for Fat Chicken, from the Makers of Scrap Squad Posted by Jessica Fisher on November 26th, 2014 [ permalink ] Relevant Games has announced they will be releasing their reverse tower defense game, | Read more »
Tripnary Review
Tripnary Review By Jennifer Allen on November 26th, 2014 Our Rating: :: TRAVEL BUCKET LISTiPhone App - Designed for the iPhone, compatible with the iPad Want to create a travel bucket list? Tripnary is a fun way to do exactly that... | Read more »
Ossian Studios’ RPG, The Shadow Sun, is...
Ossian Studios’ RPG, The Shadow Sun, is Now Available for $4.99 Posted by Jessica Fisher on November 26th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Mmmm, Tasty – Having the Angry Birds for...
The very first Angry Birds debuted on iOS back in 2009. When you sit back and tally up the number of Angry Birds games out there and the impact they’ve had on pop culture as a whole, you just need to ask yourself: “How would the birds taste... | Read more »
Rescue Quest Review
Rescue Quest Review By Jennifer Allen on November 26th, 2014 Our Rating: :: PATH BASED MATCH-3Universal App - Designed for iPhone and iPad Guide a wizard to safety by matching gems. Rescue Quest might not be an entirely original... | Read more »
You Can Play the Final Chapter of Lone W...
You Can Play the Final Chapter of Lone Wolf: Dawn Over V’taag Right Now Posted by Jessica Fisher on November 26th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Swords of Anima (Games)
Swords of Anima 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: A new tactical turn-based RPG experience. Command the Savior Rex Squad in an epic journey of courage and deception. Can you... | Read more »
Audio Defence: Zombie Arena
Audio Defence: Zombie Arena By Lee Hamlet on November 26th, 2014 Our Rating: :: DRAGS ITS FEETUniversal App - Designed for iPhone and iPad From the makers of Papa Sangre comes a defense game that forces players to listen carefully... | Read more »
Tales from the Borderland​s Will be Comi...
Tales from the Borderland​s Will be Coming to iOS by the End of the Year Posted by Jessica Fisher on November 26th, 2014 [ permalink ] Telltale Games has announced | Read more »
Sunburn! Review
Sunburn! Review By Campbell Bird on November 26th, 2014 Our Rating: :: DON'T DIE ALONEUniversal App - Designed for iPhone and iPad Platform through the depths of space to make sure your entire crew dies together in this satisfying... | Read more »

Price Scanner via MacPrices.net

Early Black Friday MacBook Air sale prices, $...
 MacMall has posted early Black Friday MacBook Air sale prices. Save $101 on all models for a limited time: - 11″ 1.4GHz/128GB MacBook Air: $798 - 11″ 1.4GHz/256GB MacBook Air: $998 - 13″ 1.4GHz/... Read more
Why iPhone 6 Tablet/Laptop Cannibalization Is...
247wallst.com blogger Douglas A. McIntyre noted last week that according to research posted on the Applovin blog site the iPhone 6 is outselling the iPhone 6 Plus by a wide margin . Hardly a surprise... Read more
Worldwide Tablet Growth Expected to Slow to 7...
The global tablet market is expected to record massive deceleration in 2014 with year-over-year growth slowing to 7.2%, down from 52.5% in 2013, according to a new forecast from International Data... Read more
Touchscreen Glove Company Announces New Produ...
Surrey, United Kingdom based TouchAbility specializes in design and manufacture of a wide variety of products compatible with touchscreen devices including smartphones, tablets and computers. Their... Read more
OtterBox Alpha Glass Screen Protectors for iP...
To complement the bigger, sharper displays on the latest Apple devices, OtterBox has introduced Alpha Glass screen protectors to the iPhone 6 and iPhone 6 Plus. The fortified glass screen protectors... Read more
Early Black Friday Mac Pro sale, 6-Core 3.5GH...
 B&H Photo has the 6-Core 3.5GHz Mac Pro on sale today for $3499 including free shipping plus NY sales tax. Their price is $500 off MSRP, and it’s the lowest price available for this model from... Read more
Early Black Friday sale price: 15-inch 2.2GHz...
 B&H Photo has the 2014 15″ 2.2GHz Retina MacBook Pro on sale today for $1699.99. Shipping is free, and B&H charges NY sales tax only. Their price is $300 off MSRP, equalling Best Buy’s price... Read more
13-inch 2.5GHz MacBook Pro (refurbished) avai...
The Apple Store has Apple Certified Refurbished 13″ 2.5GHz MacBook Pros available for $170 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free: - 13″ 2.5GHz... Read more
Early Black Friday iPad mini 3 sale: $75 off...
 Best Buy has iPad mini 3s on sale for $75 off MSRP on their online store for a limited time. Choose free shipping or free local store pickup (if available). Sale prices available for online orders... Read more
Early Black Friday MacBook Pro sale: 15-inch...
 Best Buy has posted early Black Friday prices on 15″ Retina MacBook Pros, with models on sale for $300 off MSRP on their online store for a limited time. Choose free local store pickup (if available... 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
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.