TweetFollow Us on Twitter

Sep 01 Programming

Volume Number: 17 (2001)
Issue Number: 09
Column Tag: Programming Techniques

The Under-used UserPane

by Spec Bowers

Presenting a Whole Slew of Nifty Controls

Introduction

Could you use a QuickTime control, an MLTE control, an HTML Renderer control, a StoneTable control, a WASTE control, a Color Picker control? They're all here - made out of a UserPane.

Of all the controls Apple has created in recent years, the most flexible is the UserPane. It is also the hardest to use. Most of us probably just write special–purpose code in our update handlers or mouse–down handlers rather than bother with the intricacies of a UserPane.

With a simple wrapper class, the UserPane is very easy to use - and it makes other packages easier to use. We have made UserPane controls for QuickTime, MLTE, HTML Rendering, the Color Picker, the StoneTable list manager replacement, and the WASTE text engine. These packages are easier to use thanks to the UserPane.


Figure 1. Four kinds of UserPane

Wrapping a UserPane control around QuickTime, MLTE, or other packages makes the code easy to reuse and greatly simplifies your event handling code. The QuickTime control is almost as simple as a standard pushbutton; the MLTE control is easier than TextEdit.

Your event loop already has code for HandleControlClick, HandleControlKey, SetKeyboardFocus, Activate/DeactivateControl, Hide/ShowControl, and IdleControls. When you wrap a UserPane control around a package like QuickTime, it automatically responds to your existing control handling code. You can put controls for QuickTime, MLTE, HTML Rendering, etc. in a window, a dialog, inside a tab panel - anywhere you put a standard control - and it just works.

This article:

  • describes the functions of a UserPane;
  • presents a C++ wrapper class that makes it easy to use a UserPane;
  • presents several examples of UserPanes;
  • shows how to handle a UserPane in a window or dialog

UserPane Functions

Apple defines several callback functions for a UserPane control:

  • A DrawProc draws the content of your control. It might be called to draw a part of the control but usually draws the entire control.
  • A HitTestProc returns the part code of the control where the mouse–down occurred. We usually just detect a mouse–down anywhere in the control and return a partcode which represents the entire control.
  • A TrackingProc tracks a control while the user holds down the mouse button.
  • An IdleProc performs idle processing.
  • A KeyDownProc handles keyboard events.
  • An ActivateProc handles activate and deactivate events.
  • A FocusProc handles keyboard focus - e.g. for Set/AdvanceKeyboardFocus.
  • A BackgroundProc sets the background color or pattern for embedded controls.

To install a callback you first create a UPP, then pass it to the control via SetControlData. Later, to prevent a memory leak, you should dispose the UPP. Alternatively, you can adopt a "create once and reuse" protocol. Whatever way you do it, installing a callback is a nuisance. The AMUserPane makes it very simple to install a callback.

The AMUserPane Class

The AMUserPane class provides functions for easily installing callbacks and for disposing of UPPs when the control is discarded, provides some standard callback functions, and provides some utility functions to simplify using a UserPane.

To install a DrawProc, just call "SetDrawProc ()":

//—————
void   AMUserPane::SetDrawProc ()
{
   mDrawUPP = NewControlUserPaneDrawUPP (StaticDrawProc);
   ::SetControlData (mControl,
                kControlNoPart,
                kControlUserPaneDrawProcTag,
                sizeof (mDrawUPP),
                (Ptr)&mDrawUPP);
}
There are similar functions for installing a TrackingProc, KeyDownProc, ActivateProc, etc.
AMUserPane declares data members for each callback function:
   ControlUserPaneDrawUPP            mDrawUPP;
   ControlUserPaneHitTestUPP         mHitTestUPP;
   ControlUserPaneTrackingUPP      mTrackingUPP;
   ControlUserPaneIdleUPP            mIdleUPP;
   ControlUserPaneKeyDownUPP         mKeyDownUPP;
   ControlUserPaneActivateUPP      mActivateUPP;
   ControlUserPaneFocusUPP            mFocusUPP;
   ControlUserPaneBackgroundUPP      mBackgroundUPP;
Its constructor initializes each UPP to nil, and its destructor disposes each (non–nil) UPP:
//—————
AMUserPane::AMUserPane ()
{
   mDrawUPP = nil;
   mHitTestUPP = nil;
   mTrackingUPP = nil;
   mIdleUPP = nil;
   mKeyDownUPP = nil;
   mActivateUPP = nil;
   mFocusUPP = nil;
   mBackgroundUPP = nil;
}

//—————
AMUserPane::~AMUserPane ()
{
   if (mDrawUPP != nil) {
      DisposeControlUserPaneDrawUPP (mDrawUPP);
   }
   if (mHitTestUPP != nil) {
      DisposeControlUserPaneHitTestUPP (mHitTestUPP);
   }
   if (mTrackingUPP != nil) {
      DisposeControlUserPaneTrackingUPP (mTrackingUPP);
   }
   if (mIdleUPP != nil) {
      DisposeControlUserPaneIdleUPP (mIdleUPP);
   }
   if (mKeyDownUPP != nil) {
      DisposeControlUserPaneKeyDownUPP (mKeyDownUPP);
   }
   if (mActivateUPP != nil) {
      DisposeControlUserPaneActivateUPP (mActivateUPP);
   }
   if (mFocusUPP != nil) {
      DisposeControlUserPaneFocusUPP (mFocusUPP);
   }
   if (mBackgroundUPP != nil) {
      DisposeControlUserPaneBackgroundUPP (mBackgroundUPP);
   }
}

Look back at SetDrawProc and you'll see that it installs a callback to a function named "StaticDrawProc". AMUserPane provides a member function, DoDraw, which is overridden in each subclass. The StaticDrawProc is a glue function which dispatches to the particular DoDraw of the subclass - the QuickTime DoDraw, or the MLTE DoDraw, for example. During initialization we store a pointer to a specific instance of AMUserPane in the control's RefCon. In each callback we retrieve the control's RefCon, cast it to an AMUserPane pointer, then call the member function.

//—————
void   AMUserPane::Initialize (
   ControlHandle      inControl)
{
   mControl = inControl;
   ::SetControlReference (mControl, (SInt32)this);
}

//—————
pascal void      AMUserPane::StaticDrawProc (
   ControlHandle   control,
   SInt16               part)
{
   AMUserPane*      pane = (AMUserPane*)::GetControlReference (control);

   pane->DoDraw (part);
}

//—————
void   AMUserPane::DoDraw (
   SInt16      part)
{
   // override in each subclass
}

AMUserPane is a base class; it provides common code for a wide variety of UserPane controls. We have made half a dozen subclasses. Let's take a look at some of them.

A ColorSwatch UserPane

Our simplest UserPane is a wrapper around the Color Picker. It paints the control's rectangle with a color. If the user clicks the UserPane, it invokes the Color Picker, then redraws the rectangle with the selected color. We overrode DoDraw and DoTracking. The Initialize function calls SetDrawProc and SetTrackingProc to install callbacks.

//—————
void   AMColorSwatch::DoDraw (
   SInt16         /* part */ )
{
   RGBColor      saveColor;
   Rect            rect;

   ::GetForeColor (&saveColor);
   ::RGBForeColor (&mSwatchColor);
   GetControlRect (&rect);
   ::PaintRect (&rect);
   ::RGBForeColor (&saveColor);
}

//—————
ControlPartCode      AMColorSwatch::DoTracking (
   Point            startPt,
   ControlActionUPP   actionProc)
{
   ControlPartCode      result = 0;
   Point            dialogPos = {0, 0};
   Str255            prompt = "\p";
   RGBColor         outColor;

   if (::GetColor (dialogPos, prompt, &mSwatchColor, &outColor)) {
      mSwatchColor = outColor;
      DoDraw (0);
      result = 99;   // any non-zero code
   }

   return result;
}

//—————
void   AMColorSwatch::Initialize (
   ControlHandle      inControl)
{
   AMUserPane::Initialize (inControl);

   SetDrawProc ();
   SetTrackingProc ();
}

An HTML Pane - Glitches and Solutions

The HTML pane is only slightly more complex but illustrates two glitches. The first time we put it inside a Tab control it worked pretty well. Clicking a tab results in HideControl/ShowControl of the panels. Each panel is a simple UserPane with embedded controls. When we hide or show a panel, the Control Manager hides or shows any embedded controls, including our custom UserPane controls. (This by the way is one of the advantages of turning QuickTime, MLTE, etc. into UserPane controls - HideControl, ShowControl and other Control Manager functions work the same as with standard controls.)

There was a glitch, though. When we deactivated the window, suddenly one of our hidden UserPane controls drew something. The Control Manager doesn't call the DrawProc of a hidden control but it may call the ActivateProc. We added a simple "IsVisible" call to test for visibility inside any of our callback functions that might draw anything.

//—————
void   AMHTMLPane::DoActivate (
   Boolean      activating)
{
   Rect         cntlRect;

   if (IsVisible ()) {
      if (activating) {
         HRActivate (mHTMLRec);
      } else {
         HRDeactivate (mHTMLRec);
      }
   }
}

This didn't completely solve the problem, however. We saw the HTMLPane's scrollbars even when the pane was hidden. This was because the scrollbars were not properly embedded within the HTML UserPane. The HTML Rendering Lib creates scrollbars on the fly as needed. Those scrollbars end up embedded in the root control. Because they are not embedded in the HTML UserPane they are not hidden/shown along with the pane. Our solution is to look for newly created controls in the root control and embed them in our UserPane control.

Before we call any function that might create other controls we call CountRootControls. Afterwards, we call EmbedNewControls. If there are more controls afterwards than before, those new controls should be embedded in our UserPane, not in the root control.

//—————
UInt16      AMUserPane::CountRootControls ()
{
   UInt16            numControls = 0;
   WindowRef      theWindow;
   ControlRef      root;

   theWindow = GetOwnerWindow ();
   ::GetRootControl (theWindow, &root);
   ::CountSubControls (root, &numControls);

   return numControls;
}

//—————
void   AMUserPane::EmbedNewControls (
   UInt16         inBeforeNum)
{
   WindowRef      theWindow;
   ControlRef      root;
   UInt16            afterNum;
   UInt16            i;
   ControlRef      child;

   theWindow = GetOwnerWindow ();
   ::GetRootControl (theWindow, &root);
   ::CountSubControls (root, &afterNum);
   for (i = afterNum; i > inBeforeNum; i—) {
      ::GetIndexedSubControl (root, i, &child);
      ::EmbedControl (child, mControl);
   }
}

In most of our UserPanes' Initialize functions we call CountNewControls and EmbedNewControls just in case subcontrols are created. The HTMLPane's Initialize is typical. We get a "before" count of root controls, create a new HRReference, then set its bounds to the UserPane control's bounds. We install a DrawProc, TrackingProc, and ActivateProc. Finally, we embed the newly created controls (scrollbars) in the UserPane.

//—————
void   AMHTMLPane::Initialize (
   ControlHandle      inControl)
{
   AMUserPane::Initialize (inControl);

   OSErr         err = noErr;
   UInt16         beforeNum;
   Rect            cntlRect;
   GrafPtr      ownerPort;

   beforeNum = CountRootControls ();

   GetControlRect (&cntlRect);

   ownerPort = (GrafPtr) GetWindowPort (GetOwnerWindow ());
   err = HRNewReference (&mHTMLRec, kHRRendererHTML32Type, ownerPort);

   if (err == noErr) {
      HRSetRenderingRect (mHTMLRec, &cntlRect);
      HRSetDrawBorder (mHTMLRec, true);

      SetDrawProc ();
      SetTrackingProc ();
      SetActivateProc ();
   }

   EmbedNewControls (beforeNum);
}

The HTMLPane was now working well - until we viewed an HTML file that had a frameset. Suddenly, there were two new scrollbars and they were not embedded properly. So we added CountRootControls and EmbedNewControls to the DoDraw function. Other than that, the DoDraw is very simple.

//—————
void   AMHTMLPane::DoDraw (
   SInt16         part)
{
   UInt16         beforeNum;
   Rect            cntlRect;

   beforeNum = CountRootControls ();

   GetControlRect (&cntlRect);
   HRSetRenderingRect (mHTMLRec, &cntlRect);

   RectRgn (mHTMLRgn, &cntlRect),
   HRDraw (mHTMLRec, mHTMLRgn);

   EmbedNewControls (beforeNum);
      // in case last click created new scroll bars
}

The DoTracking function is very simple. About all it does is ask the HTML Rendering library to handle the event. We could have synthesized a mouse–down event from the Start Point but instead we call an external function to get the current event record from our main event–handling code.

//—————
ControlPartCode      AMHTMLPane::DoTracking (
   Point            startPt,
   ControlActionUPP   actionProc)
{
   WindowRef      owner = GetOwnerWindow ();

   ::SetPortWindowPort (owner);
   ::HRIsHREvent (GetCurrentEventRecord ());

   return 99;   // any non-zero code
}

Using a UserPane

Okay, so we have written a UserPane class. How do we use it? That's the easy part. First, create a UserPane control resource. For a window or a dialog, create a CNTL with procID 256 and initial value 318. This value turns on feature bits for SupportsEmbedding, SupportsFocus, WantsIdle, WantsActivate, HandlesTracking, and GetsFocusOnClick. For a dialog, in its DITL resource create an item of type Control and set its ID to the resource ID of the CNTL resource.

Wherever you declare the variables (data members) for your window or dialog, declare an instance of the UserPane class. We find it convenient also to declare a ControlHandle. You'll also have to #include the UserPane class's header.

#include "AMColorSwatch.h"
   ControlHandle   mSwatchHandle;
   AMColorSwatch   mSwatchPane;

When you create a window, get a ControlHandle to the UserPane control, then initialize the instance of the UserPane class.

   mSwatchHandle = ::GetNewControl (CNTL_Swatch, window);
   mSwatchPane.Initialize (mSwatchHandle);

In your window's event handling code for a mouse–down, call the usual FindControl. If the click is in the UserPane control, call the usual TrackControl or HandleControlClick.

   if (whichControl == mSwatchHandle) {
      if (HandleControlClick (mSwatchHandle, where, curEvent.modifiers, nil) != 0) {
      }
   } else if (mSwatchPane.ClickSubControl (whichControl, where)) {
      // ClickedSwatch ();
   }

What is "ClickSubControl"? If the UserPane has any subcontrols, e.g. scrollbars, then FindControl may find that the click was in the scrollbar. ClickSubControl checks to see if the click was in one of the UserPane's subcontrols. If it was, then ClickSubControl passes the click along to the UserPane class's DoTracking method and returns true. If the click was not in a subcontrol, then ClickSubControl returns false.

//—————
Boolean      AMUserPane::ClickSubControl (
   ControlRef      inControl,
   Point            inWhere)
{
   UInt16            numSubs;
   UInt16            i;
   ControlRef      sub;

   ::CountSubControls (mControl, &numSubs);
   for (i = 1; i <= numSubs; i++) {
      ::GetIndexedSubControl (mControl, i, &sub);
      if (inControl == sub) {
         DoTracking (inWhere, nil);
            // treat it as a click in the userPane
         return true;
      }
   }
   return false;
}

The example application doesn't have any UserPanes in a dialog but it's easy to do. After creating the dialog, call GetDialogItemAsControl to get a ControlHandle to the UserPane. Then Initialize the UserPane instance with the control handle. The Control Manager and Dialog Manager will take care of almost everything. You just add a case to your dialog's switch statement.

There is one other piece of code you will have to add if your UserPane has subcontrols. You'll have to add a Filter function because the Dialog Manager doesn't know anything about the subcontrols. The Filter function will have code like this:

      if (mQuickTimePane.FilterSubControls (ioEvent)) {
         *outItemHit = kQuickTimePane;
         return true;
      }

FilterSubControls checks to see if the event is a mouse–down. If it is, then FilterSubControls calls FindWindow and FindControl, then calls ClickSubControl, which we saw earlier.

//—————
// if the event is for one of our subcontrols
// then process it as if it were for us;
// pass back true to tell Dialog Manager
// that event has been processed
//
Boolean      AMUserPane::FilterSubControls (
   EventRecord      *ioEvent)
{
   Boolean         filtered = false;
   UInt16         numControls = 0;
   WindowPtr      whichWindow;
   ControlHandle   whichControl;
   Point         localWhere;
   short         partCode;
   UInt16         i;
   ControlRef      sub;

   ::CountSubControls (mControl, &numControls);
   if (numControls > 0) {
      if ((ioEvent->what == mouseDown)
      && (FindWindow (ioEvent->where, &whichWindow) == inContent)) {
         SetPortWindowPort (whichWindow);
         localWhere = ioEvent->where;
         GlobalToLocal (&localWhere);
         FindControl (localWhere, whichWindow, &whichControl);
         if (ClickSubControl (whichControl, localWhere)) {
            return true;
               // => click was for this userPane
         }
      }
   }
   return filtered;
}

Summary

We've described two of our UserPanes - the Color Picker and the HTML Renderer. The other four UserPanes - for QuickTime, MLTE, StoneTable, and WASTE - are similar. The AMUserPane class, all six UserPane classes, and the example application are available as source code. The controls are useful and easy to use. If you use any of them we would be interested in hearing from you.

A Plug

These UserPane classes are part of the AppMaker library. The example was created using AppMaker, which generated both the resources and the source code. Whether you use AppMaker or you do it by hand, I think you will find that these UserPanes are very useful widgets to have in your toolbox.


Spec Bowers is the founder, cook, and chief bottle washer at Bowers Development. He has been developing programming tools for most of his career. You can contact him at bowersdev@aol.com or see the web page at http://members.aol.com/bowersdev.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom 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.