TweetFollow Us on Twitter

Volume Number:7
Issue Number:9
Column Tag:Pascal Forum

Related Info: Quickdraw

Meter Windows

By Walt Davis, Raleigh, NC

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

[Walt is an electrical engineer who, until recently, worked for a NASA contractor based in the Washington, DC area. He developed Mac software for NASA that simulates the flow of high-speed data from space-based instruments and platforms through various space- and ground-based networks to users on the ground. He currently works for Alcatel Network Systems in Raleigh, North Carolina helping Alcatel develop fiber-optic telecommunications systems that will someday bring fiber into your home and to your Mac.]

Is the Meter Running?

No news is not necessarily good news. Especially when your application is performing a time consuming task (e.g. lengthy I/O or number crunching) and you’ve neglected to implement a mechanism to provide feedback on the task’s progress. As a conscientious programmer you’ve changed the arrow cursor to the watch cursor or maybe even harnessed the VBL interrupt to show a rotating watch cursor during these lengthy pauses, but still it’s not enough. The user really has no idea how far into the task the application has progressed or how much longer until the task is completed. Forcing the user to rely on the familiar sound of the disk-drive access or the sight of the disk-access light blinking during long pauses when such a rich graphical interface is available is either laziness, sloppiness, or rudeness on the part of the programmer. It is the programmer’s responsibility to see to it that the user always has a warm, fuzzy feeling about what the application is doing at any particular time. It is the programmer’s responsibility to create the illusion that the user is in control at all times.

Actually, I’ve evolved to this position over time due to my experiences as a user of my own software. I’ve written time consuming applications such as discrete-event simulations and fast Fourier transforms where a simple watch cursor just won’t cut it. And now that Apple has a full line of Macs with different processor and coprocessor configurations, applications that take a few seconds on one Mac platform may take several minutes on another Mac platform. With all this uncertainty, developers can be certain of one thing: your software will be used in ways and in environments that you’ve never considered (if you’re lucky!). You may not be able to test your software in all these environments, but you can add some simple features to your software that give it a consistent feel across these environments.

Meet the Meter

For these reasons, I’ve developed a set of procedures that support what I call the Meter Window (MW). The MW functions as a visual feedback mechanism for the progress of a task. The MW simply displays the title of the task and fills in a horizontal box as the task is completed. It is easy to expand on this idea of visual feedback and develop much more elaborate feedback graphics, but the primary goal of the MW is to provide as much feedback as possible with the minimum increase in the completion time of the task at hand. The MW is ideal for long repetitive loop processes but it can be adapted for any long process that can be decomposed into steps. The MW is also helpful during development and software testing to show how far into a task a problem occurs. In a multi-step task, refreshing the MW at each step results in a crude form of code profiler that shows the relative length of each step and helps identify which steps are good targets for code optimization.

Meter Nuts and Bolts

The enclosed code, written in Think Pascal version 2.0, is a unit used to initialize, display, update, and destroy the MW as well as code for a unit that creates a simple example application that demonstrates the MW operation. The self-contained MW unit provides full MW functionality for any Think Pascal project through five simple procedure calls: mWindowInit, mWindowDraw, mWindowTitle, mWindowUpdate, and mWindowKill. The mWindowInit procedure creates the MW data structures and draws the empty window in the center of the screen. It works with different size monitors because it uses the the QuickDraw global screenbits.bounds rectangle to determine the size of the screen. The mWindowDraw procedure draws the empty meter box with 5% graduations as well as the other meter box annotation (you can customize the graduation scale for your own application). The mWindowTitle procedure accepts a Str255 parameter, mStr, and draws the mStr parameter as the MW title. You can notify the user which part of the task or subtask is currently active through the MW title by repeatedly calling mWindowTitle procedure with a different mStr parameter. The mWindowUpdate procedure fills in the meter box from left to right based on the values of two integer parameters; curI and maxI. The curI parameter corresponds to the current step in a process with maxI steps. For example, mWindowUpdate(0,50) draws an empty meter box; mWindowUpdate(25,50) draws a half-filled meter box; and mWindowUpdate(50,50) draws a full meter box. mWindowKill destroys the MW and all associated data structures.

Meter Madness

To use the MW, an application need only include the MW unit in the Think Pascal project and make the appropriate MW procedure calls. The application, through the MW unit interface, is responsible for initializing the MW module, determining when to draw the MW, displaying the proper MW title, updating the MW as the task progresses, and destroying the MW when the task is complete.

The code included with this article consists of two units; one (MeterWindow) contains the procedures necessary to implement the MW, the other (MWMain) contains a small event shell and a procedure that illustrates the MW unit interface and demonstrates the MW functionality. Figure 1 shows the Think Pascal project (MWDemoProject) necessary to build the MW demo.

Figure 1: MW Demo Project

The event shell first creates the menu and the Meter menu and then handles the menu item selections in a small event loop. This event loop supports Desk Accessory items in the menu and the ‘Run Dumb’, ‘Run Smart’, and ‘Quit’ items in the Meter menu.

The ‘Run Dumb’ item performs the same loop processing task as the ‘Run Smart’ item but with the MW operation disabled. The MW is disabled to illustrate the effect of the long loop processing without the MW feedback. Except for the watch cursor, the user is clueless as to which process is currently active and how long until the process is finished. Run the demo and compare the execution times between the ‘Run Dumb’ and ‘Run Smart’ items to see how little it costs in execution time to implement the MW.

Selecting the ‘Run Smart’ item runs the same loop processing task with the MW enabled. The DoMeterWindowDemo procedure handles the MW unit interface for the demo. The first thing the DoMeterWindowDemo procedure does is test to see which processor is active. The SysEnvirons toolbox call returns information about the current hardware and software platform in the dWorld parameter. This information includes, besides the processor type, whether Color QuickDraw is present, whether a math-coprocessor is present, and which version of the System software is running. The SysEnvirons call is a convenient way for the software to determine the current operating environment and, if necessary, adjust accordingly. In this demo the loop lengths are adjusted based on the processor type. This is needed because the MW demo loop on a 68000 based Mac will only be a blur on the screen of a 68020 or 68030 based Mac.

Demo Details

The DoMeterWindowDemo procedure uses two local variables (meterHit, m) and a constant (meterGrade) to control the MW display. The meterGrade constant corresponds to the graduations on the MW meter box; i.e. 5% equals 20 graduations. The meterHit variable contains the number of loops that correspond to one graduation (5%) of the loop processing and is computed by dividing the total number of loop iterations, loopsize, by the meterGrade value. The m variable is used as a step counter in the loop and is compared with the meterHit variable every loop to determine when another 5% is complete.

This demo consists of three nested loops; an n loop, an i loop, and a j loop. The outer most loop, n, loops 5 times, each time redrawing the MW with a new title. The middle loop, i, loops loopsize (say that 5 times fast) times for each of the n loops and is used to fill the meter box in 5% graduations. The inner most loop, j, is a dummy loop and used only as a delay to update the meter box. The number of j loops, innerloop, is adjusted based on the current processor type.

The mWindowInit procedure is called prior to entering the first n loop. In each of the 5 n loops the MW is redrawn (mWindowDraw) and the MW title is updated (mWindowTitle(iStr)). The step counter variable, m, is initialized prior to entering the i loop and, for each iteration of the i loop, is compared with the meterHit variable to determine if another 5% of the loop has been completed. If it has, another portion of the meter box is filled in (mWindowUpdate(i,loopsize)) and the step counter reset to 1. Following the completion of all loops, the mWindowKill procedure is called to destroy any MW data structures.

Happy Metering

In conclusion, the MW is a simple example of a graphic feedback mechanism that adds a professional touch to software that seems to “go away” during long internal processes. It allows you to show the user that you’re not hiding anything, even if you are.

Listing:  MeterWindow

{MeterWindow Unit.                            }
{This unit contains all the functions and       }
{procedures needed to support the   initializing, }
{displaying, updating, and destroying of the    }
{Meter Window.                                  }

unit MeterWindow;
 procedure mWindowInit;
 procedure mWindowDraw;
 procedure mWindowTitle (mStr: Str255);
 procedure mWindowUpdate (curI, maxI: longint);
 procedure mWindowKill;

{Constants to control the size and placement of }
{the Meter Window title and meter box.          }
  mRx = 13;
  mRy = 24;
  mRw = 250;
  mRh = 16;

  tRx = 13;
  tRy = 1;
  tRw = 253;
  tRh = 16;

  mWPtr: WindowPtr;

{mWindowInit procedure                        }
{This procedure initializes the meter window and}
{draw it in the middle of the screen.           }

 procedure mWindowInit;

{The constants for the height and width of the  }
{Meter Window.                                  }
   mWwidth = 280;
   mWheight = 60;

   savePort: GrafPtr;
   iRect: Rect;
   mwXOffset, mwYOffset: integer;

  SetRect(iRect, 0, 0, mWwidth, mWheight);

{Create the Meter Window with a window          }
{definition ID equal to 1.                      }
  mWPtr := NewWindow(nil, iRect, ‘’, false, 1, Pointer(-1), false, longint(0));

{Figure out the x and y offsets in pixels to put}
{the Meter Window in the center of this screen. }
{After that move the window there and display   }
{the empty window.                              }
  iRect := screenBits.bounds;
  mwXOffset := integer(round(((iRect.right - iRect.left) - (mWptr^.portRect.right 
- mWptr^.portRect.left)) / 2));
  mwYOffset := integer(round(((iRect.bottom - - (mWptr^.portRect.bottom 
- mWptr^ / 2));
  MoveWindow(mWPtr, mwXOffset, mwYOffset, false);

{mWindowDraw procedure                        }
{This procedure draws the meter box with its    }
{graduations and the corresponding annotation.  }

 procedure mWindowDraw;

{These constatns control the placement of the 5%}
{and 10% graduations in the meter box based on a}
{meter box that is 250 pixels wide.             }
   fiveSize = 1;
   fiveStep = 12;
   tenSize = 3;
   tenStep = 25;

   i: integer;
   mRect: Rect;
   savePort: GrafPtr;


{Erase the Meter Window in case something is    }
{already drawn there.                           }

{Set up the meter box in the mRect rectangle.}
  SetRect(mRect, mRx, mRy, mRx + mRw, mRy + mRh);
  PenSize(1, 1);

{Draw the frame around the meter box rectangle.}
  InsetRect(mRect, -1, -1);
  InsetRect(mRect, 1, 1);

{Draw the first 5% graduation then let the      }
{following loop do the rest.                    }
  MoveTo(mRect.left + fiveStep, - 1);
  Line(0, fiveSize);
  MoveTo(mRect.left + fiveStep, mRect.bottom);
  Line(0, -fiveSize);
  for i := 1 to 9 do
    MoveTo(mRect.left + (i * tenStep) - 1, - 1);
    Line(0, tenSize);
    MoveTo(mRect.left + (i * tenStep) - 1, mRect.bottom);
    Line(0, -tenSize);
    MoveTo(mRect.left + (i * tenStep) + fiveStep, - 1);
    Line(0, fiveSize);
    MoveTo(mRect.left + (i * tenStep) + fiveStep, mRect.bottom);
    Line(0, -fiveSize);

{Now draw the appropriate meter box annotation.}
  MoveTo(mRect.left + 65, mRect.bottom + mRh);
  DrawString(‘Percent Complete’);
  MoveTo(mRect.left - 5, mRect.bottom + mRh);
  MoveTo(mRect.right - 20, mRect.bottom + mRh);

{mWindowTitle procedure                       }
{This procedure draws the title of the meter    }
{window in the tRect rectangle.                 }

 procedure mWindowTitle;

   savePort: GrafPtr;
   tRect: Rect;


{Set up the title rectangle in the tRect        }
{structure, erase the rectangle, then draw the  }
{title string in the rectangle.                 }
  SetRect(tRect, tRx, tRy, tRx + tRw, tRy + tRh);
  MoveTo(tRect.left, tRect.bottom);

{mWindowUpdate procedure                      }
{This procedure fills in the meter box based on }
{the curI and maxI parameters.  CurI is the     }
{current step in the process with maxI steps.   }

 procedure mWindowUpdate;

   pDone: integer;
   mRect: Rect;
   savePort: GrafPtr;


{Determine which percent of the process is done }
{and load it in pDone.                          }
  if maxI = 0 then
   pDone := 0
   pDone := integer(round(curI / maxI * 100));

{Just in case the percent done is greater than 100%.}
  if pDone > 100 then
   pDone := 100;
  SetRect(mRect, mRx, mRy, mRx + mRw, mRy + mRh);

{Since the meter box is 250 pixels wide, each   }
{percent corresponds to 2.5 pixels.             }
  mRect.right := mRect.left + integer(round((pDone * 2.5)));
  FillRect(mRect, black);

{mWindowKill procedure                        }
{This procedure disposes of the Meter Window    } 
{data structure.                                }

 procedure mWindowKill;


{MWMain Unit.                                 }
{This unit contains the event loop and the loop }
{procedure for the MacTutor demo.               }
Listing:  MWMain

program MWMain;


{DoMeterWindowDemo procedure                  }
{This procedure demonstrates the Meter Window   }
{interface.  It uses three nested loops to      } 
{create a dummy task that is slow enough to show}
{the Meter Window functionality.  This procedure}
{accepts one parameter, runSmart.  When runSmart}
{is true, the Meter Window is displayed during  }
{the loop execution; if runSmart is false the   }
{then loop is executed but without creating the }
{Meter Window.                                  }

 procedure DoMeterWindowDemo (runSmart: boolean);

   outLoop = 5;
   loopsize = 500;
   meterGrade = 20;

   i, j, m, n: integer;
   myCursor: CursHandle;
   meterhit, k, innerloop: longint;
   dWorld: SysEnvRec;
   rnum: OSErr;
   vReq: integer;
   iStr: Str255;

{First determine which processor is in this Mac }
{and then adjust the innerloop parameter        }
{accordingly.  This is done so that the loop    }
{will not execute too quickly on high-powered Macs. }
  vReq := 1;
  rnum := SysEnvirons(vReq, dWorld);
  if rnum = 0 then
    if dWorld.processor = env68000 then
     innerloop := loopsize
    else if dWorld.processor = env68010 then
     innerloop := loopsize
    else if dWorld.processor = env68020 then
     innerloop := 20 * loopsize
     innerloop := 20 * loopsize;
   innerloop := loopsize;

{Figure out how many loops equal 5% of the total loop.}
  meterHit := longint(round(loopsize / meterGrade));

  myCursor := GetCursor(WatchCursor);

{This is always the first call to the           }
{MeterWindow unit.  It initializes and displays }
{the Window Meter.                              }
  if runSmart then

  for n := 1 to outLoop do
{For each of the n loops, create a new Meter Window title. }
    NumToString(n, iStr);
    iStr := concat(‘MacTutor Demo - Loop ‘, iStr);
    iStr := concat(iStr, ‘ of 5.’);

{Now eraes the Meter Window and redraw it with a}
{new title.                                     }
    if runSmart then
    m := 1;
    for i := 1 to loopsize do
{When m = meterHit the another 5% of the total  }
{loop has been completed and it is time to      }
{update the meter box in the Meter Window.      }
     if m = meterHit then
        m := 1;
        if runSmart then
        mWindowUpdate(i, loopsize);
        m := m + 1;
     k := 0;

{This is the dummy innerloop that is adjusted   }
{based on the current processor.                }
     for j := 1 to innerloop do
        k := k + 1;

{All done!  Now destroy the Meter Window.}
  if runSmart then

{This is the main procedure for this demo.  It  }
{sets up the Apple and Meter menus and handles  }
{the selection of items from these menus.       }

  AppleID = 1;
  MeterID = 2;
  AboutItem = 1;
  RunDItem = 1;
  RunSItem = 2;
  QuitItem = 3;

  appleMenu, meterMenu: MenuHandle;
  myTitle: string[1];
  daName: Str255;
  dEvent: EventRecord;
  TimeToQuit: boolean;
  dPart, dItem, dMenu, daNum: integer;
  dWindow: WindowPtr;
  dChoice: longint;


{Set up the menus.}
 myTitle := ‘ ‘;
 myTitle[1] := CHR(appleMark);
 appleMenu := NewMenu(AppleID, myTitle);
 AddResMenu(appleMenu, ‘DRVR’);
 InsertMenu(appleMenu, 0);
 meterMenu := NewMenu(MeterID, ‘Meter’);
 AppendMenu(meterMenu, ‘Run Dumb’);
 AppendMenu(meterMenu, ‘Run Smart’);
 AppendMenu(meterMenu, ‘Quit’);
 InsertMenu(meterMenu, 0);

 TimeToQuit := false;
{The TimeToQuit variable is set to true when the}
{Quit item is selected from the Meter menu.     }
 while not TimeToQuit do
   if GetNextEvent(everyEvent, dEvent) then

{Only handle mousedown events in this simple demo.}
     case dEvent.what of
        dPart := FindWindow(dEvent.where, dWindow);
        case dPart of

{The SysWindow mousedown is for DA’s            } 
        SystemClick(dEvent, dWindow);

{Figure out which menu item was selected.}
        dChoice := MenuSelect(dEvent.where);
        dItem := LoWord(dChoice);
        dMenu := HiWord(dChoice);
        case dMenu of

{If an Apple menu item was selected, then do the item.}
        GetItem(appleMenu, dItem, daName);
        daNum := OpenDeskAcc(daName);
        case dItem of

{The Run Dumb item was selected.  Do the loop   }
{processing without displaying the Meter Window.}

{Do the loop processing and display the Meter Window. }

{Quit and go home.}
        TimeToQuit := true;

Community Search:
MacTech Search:

Software Updates via MacUpdate

Rodeo Stampede guide to running a better...
In Rodeo Stampede, honing your skills so you can jump from animal to animal and outrun the herd as long as possible is only half the fun. Once you've tamed a few animals, you can bring them home with you. [Read more] | Read more »
VoxSyn (Music)
VoxSyn 1.0 Device: iOS Universal Category: Music Price: $6.99, Version: 1.0 (iTunes) Description: VoxSyn turns your voice into the most flexible vocal sound generator ever. Instantly following even subtle modulations of pitch and... | Read more »
Catch Battleplans on Google Play from Ju...
Real-time strategy title Battleplans is due for release on Google Play on June 30th, following its release for iOS systems last month. With its simple interface and pretty graphics, the crowd-pleaser brings a formerly overlooked genre out for the... | Read more »
iDoyle: The interactive Adventures of Sh...
iDoyle: The interactive Adventures of Sherlock Holmes - A Scandal in Bohemia 1.0 Device: iOS Universal Category: Books Price: $1.99, Version: 1.0 (iTunes) Description: Special Release Price $1.99 (Normally $3.99) | Read more »
Five popular free apps to help you slim...
Thanks to retail and advertising, we're used to thinking one season ahead. Here we are just a week into the summer and we're conditioned to start thinking about the fall. [Read more] | Read more »
How to ride longer and tame more animals...
It's hard to accurately describe Rodeo Stampede to people who haven't seen it yet. It's like if someone took Crossy Roadand Disco Zoo and put them in a blender, yet with a unique game mechanic that's still simple and fun for anyone. [Read more] | Read more »
Teeny Titans - A Teen Titans Go! Figure...
Teeny Titans - A Teen Titans Go! Figure Battling Game 1.0.0 Device: iOS Universal Category: Games Price: $3.99, Version: 1.0.0 (iTunes) Description: Teeny Titans, GO! Join Robin for a figure battling RPG of epic proportions! TEENY... | Read more »
NinjAwesome: Tips and tricks to be a mor...
Sorry about that headline, but I'm going to go ahead and assume that GameResort would not have named its game NinjAwesome without expecting some of that. It is, in fact, pretty awesome the way it combines an endless runner and old school arcade... | Read more »
Into Mirror (Games)
Into Mirror 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: "Is all that we see or seem, but a dream within a dream?"- Edgar Allan Poe New game by Lemon Jam Studio, the team behind Pursuit... | Read more »
Perchang (Games)
Perchang 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Welcome to Perchang! A test of skill and puzzle solving across 60 stunning levels. | Read more »

Price Scanner via

15-inch Retina MacBook Pros on sale for $200-...
B&H Photo has 15″ Retina MacBook Pros on sale for up to $210 off MSRP. Shipping is free, and B&H charges NY tax only: - 15″ 2.2GHz Retina MacBook Pro: $1799.99 $200 off MSRP - 15″ 2.5GHz... Read more
Mac minis on sale for up to $100 off MSRP
B&H Photo has Mac minis on sale for up to $100 off MSRP including free shipping plus NY sales tax only: - 1.4GHz Mac mini: $449 $50 off MSRP - 2.6GHz Mac mini: $649 $50 off MSRP - 2.8GHz Mac mini... Read more
Clearance 2015 13-inch MacBook Airs available...
B&H Photo has clearance 2015 13″ MacBook Airs available for $300 off original MSRP. Shipping is free, and B&H charges NY sales tax only: - 13″ 1.6GHz/4GB/128GB MacBook Air (MJVE2LL/A): $799.... Read more
Apple refurbished Mac minis available for up...
Apple has Certified Refurbished Mac minis available starting at $419. Apple’s one-year warranty is included with each mini, and shipping is free: - 1.4GHz Mac mini: $419 $80 off MSRP - 2.6GHz Mac... Read more
ABBYY TextGrabber: 1,000,000 Installs in 5 Da...
ABBYY, an international OCR technologies provider, has announced that their image-to-text application TextGrabber, got installed 1,000,000 times in just five days while being featured by the App... Read more
New SkinIt Waterproof Case For iPhone 6
With its impact and waterproof design, the Skinit Waterproof case provides security and protection to guarantee your phone will get you through even the most demanding outdoor conditions. The impact-... Read more
iMacs on sale for up to $150 off MSRP
B&H Photo has 21″ and 27″ iMacs on sale for up to $150 off MSRP including free shipping plus NY sales tax only: - 27″ 3.3GHz iMac 5K: $2181.11 $118 off MSRP - 27″ 3.2GHz/1TB Fusion iMac 5K: $1949... Read more
12-inch 1.1GHz Retina MacBooks on sale for $5...
B&H Photo has 2016 12″ 1.1GHz/256GB Retina MacBooks on sale for up to $50 off MSRP. Shipping is free, and B&H charges NY tax only: - 12″ 1.1GHz Space Gray Retina MacBook: $1249 $50 off MSRP... Read more
WWDC Announcements Revisited Still Underwhelm...
I was disappointed that no new MacBook hardware was announced at this year’s all-software World Wide Developer’s Conference. Not even a hint about what’s in the development pipeline. Of course, we... Read more
Twelve South Compass 2 iPad Stand Now Availab...
Twelve South has updated its most popular iPad stand, Compass 2, with the introduction of two new colors — Gold and Rose Gold. These new color options n perfectly complement the new Rose Gold iPad... Read more

Jobs Board

*Apple* New Products Testers Needed - Apple...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
*Apple* Solutions Consultant - APPLE (United...
Job Summary As an Apple Solutions Consultant, you'll be the link between our future customers and our products. You'll showcase your entrepreneurial spirit as you Read more
*Apple* Retail - Multiple Positions - Apple,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Retail - Multiple Positions, Towson...
Job Description:SalesSpecialist - Retail Customer Service and SalesTransform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Professional Learning Specialist - A...
Job Summary The Apple Professional Learning Specialist is a full-time position for one year with Apple in the Phoenix, AZ area. This position requires a high Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.