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

The best remote desktop apps for iOS
We've been sifting through the App Store to find the best ways to do computer tasks on a tablet. That gave us a thought - what if we could just do computer tasks from our tablets? Here's a list of the best remote desktop apps to help you use your... | Read more »
Warhammer 40,000: Freeblade guide - How...
Warhammer 40,000: Freebladejust launched in the App Store and it lets you live your childhood dream of blowing up and slashing a bunch of enemies as a massive, hulking Space Marine. It's not easy being a Space Marine though - and particularly if... | Read more »
Gopogo guide - How to bounce like the be...
Nitrome just launched a new game and, as to be expected, it's a lot of addictive fun. It's called Gopogo, and it challenges you to hoparound a bunch of platforms, avoiding enemies and picking up shiny stuff. It's not easy though - just like the... | Read more »
Sago Mini Superhero (Education)
Sago Mini Superhero 1.0 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0 (iTunes) Description: KAPOW! Jack the rabbit bursts into the sky as the Sago Mini Superhero! Fly with Jack as he lifts impossible weights,... | Read more »
Star Wars: Galaxy of Heroes guide - How...
Star Wars: Galaxy of Heroes is all about collecting heroes, powering them up, and using them together to defeat your foes. It's pretty straightforward stuff for the most part, but increasing your characters' stats can be a bit confusing because it... | Read more »
The best cooking apps (just in time for...
It’s that time of year again, where you’ll be gathering around the dinner table with your family and a huge feast in front of you. [Read more] | Read more »
Square Rave guide - How to grab those te...
Square Rave is an awesome little music-oriented puzzle game that smacks of games like Lumines, but with its own unique sense of gameplay. To help wrap your head around the game, keep the following tips and tricks in mind. [Read more] | Read more »
Snowboard Party 2 (Games)
Snowboard Party 2 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Crowned the best snowboarding game available on the market, Snowboard Party is back to fulfill all your adrenaline needs in... | Read more »
One Button Travel (Games)
One Button Travel 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: “To cut a long story short, If you like interactive fiction, just go buy this one.” - “Oozes the polish that... | Read more »
Light Apprentice Volume 1 (Games)
Light Apprentice Volume 1 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Light Apprentice Volume 1 includes Chapters 1 to 4, all gathered in a new exclusive game. When life in the world of... | Read more »

Price Scanner via

iMobie Releases its Ace iOS Cleaner PhoneClea...
iMobie Inc. has announced the new update of PhoneClean 4, its iOS cleaner designed to reclaim wasted space on iPhone/iPad for use and keep the device fast. Alongside, iMobie hosts a 3-day giveaway of... Read more
U.S. Cellular Offering iPad Pro
U.S. Cellular today announced that it is offering the new iPad Pro with Wi-Fi + Cellular, featuring a 12.9-inch Retina display with 5.6 million pixels — the most ever in an iOS device. U.S. Cellular... Read more
Newegg Canada Unveils Black Friday Deals for...
Newegg Canada is offering more than 1,000 deep discounts to Canadian customers this Black Friday, available now through Cyber Monday, with new deals posted throughout the week. “Black Friday is... Read more
Black Friday: Macs on sale for up to $500 off...
BLACK FRIDAY B&H Photo has all new Macs on sale for up to $500 off MSRP as part of their early Black Friday sale including free shipping plus NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $... Read more
Black Friday: Up to $125 off iPad Air 2s at B...
BLACK FRIDAY Walmart has the 16GB iPad Air 2 WiFi on sale for $100 off MSRP on their online store. Choose free shipping or free local store pickup (if available): - 16GB iPad Air 2 WiFi: $399, save $... Read more
Black Friday: iPad mini 4s on sale for $100 o...
BLACK FRIDAY Best Buy has iPad mini 4s on sale for $100 off MSRP on their online store for Black Friday. Choose free shipping or free local store pickup (if available): - 16GB iPad mini 4 WiFi: $299.... Read more
Black Friday: Apple Watch for up to $100 off...
BLACK FRIDAY Apple resellers are offering discounts and bundles with the purchase of an Apple Watch this Black Friday. Below is a roundup of the deals being offered by authorized Watch resellers:... Read more
Black Friday: Target offers 6th Generation iP...
BLACK FRIDAY Save $40 to $60 on a 6th generation iPod touch at Target with free shipping or free local store pickup (if available). Sale prices for online orders only, in-store prices may vary: -... Read more
Black Friday: Walmart and Target offer iPod n...
BLACK FRIDAY Walmart has the 16GB iPod nano (various colors) on sale for $119.20 on their online store for a limited time. That’s $30 off MSRP. Choose free shipping or free local store pickup (if... Read more
Black Friday deals on the Apple Watch and App...
Apple resellers are offering discounts and bundles with the purchase of an Apple Watch this Black Friday weekend. Below is a roundup of the deals being offered by authorized Watch resellers: Apple... Read more

Jobs Board

Storefront Operations Coordinator, *Apple* -...
# Storefront Operations Coordinator, Apple -Latin America Job Number: 43587750 Miami, Florida, United States Posted: Oct. 16, 2015 Weekly Hours: 40.00 **Job Summary** The Read more
*Apple* Enterprise / Government Professional...
# Apple Enterprise / Gove ment Professional Services Engineer Job Number: 42292976 Reston, Virginia, United States Posted: Aug. 18, 2015 Weekly Hours: 40.00 **Job Read more
iOS Wallet & *Apple* Pay Engineer - App...
# iOS Wallet & Apple Pay Engineer Job Number: 40586801 Santa Clara Valley, Califo ia, United States Posted: Nov. 16, 2015 Weekly Hours: 40.00 **Job Summary** The iOS Read more
Software Engineer, *Apple* Watch - Clock Fa...
# Software Engineer, Apple Watch - Clock Face Team Job Number: 44368761 Santa Clara Valley, Califo ia, United States Posted: Nov. 14, 2015 Weekly Hours: 40.00 **Job Read more
Administrative Assistant, *Apple* Online St...
# Administrative Assistant, Apple Online Store Job Number: 43992352 Santa Clara Valley, Califo ia, United States Posted: Nov. 9, 2015 Weekly Hours: 40.00 **Job Summary** Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.