TweetFollow Us on Twitter

Try Pop-Up
Volume Number:1
Issue Number:13
Column Tag:C Workshop

Try Pop-Up Menus!

By Mike Schuster, Consulair Corp.

What's a Pop-Up Menu?

The Macintosh™ user interface provides a repertoire of graphic objects that perform functions when pressed with the mouse. Pressing a scroll bar's arrow moves the document under the window. Selecting a tool from a palette determines the type of object to be drawn. Pressing on a menu title presents a list of choosable actions and attributes. A feature missing from this repertoire is the ability to associate a menu with an arbitrary graphic object on the screen. A pop-up menu provides just this capability.

Here's how it works: When you press on a object with an associated pop-up menu (the little menu icon above), the menu instantly "pops-up" right on top of the object and under the pointer. While holding down the mouse button, you move the pointer down the menu. As pointer moves to each item, the item is highlighted. The item that's highlighted when you release the mouse button is choosen. As soon as the button is released, the command blinks briefly, the menu disappears, and the command is executed, just like a pull-down menu.

A pop-up menu shares many of the advantages of a pull-down menu: It's invisible until you want to see it, yet at the same time it's easy to see and choose items from. Until you choose an item, nothing happens, so you can look at a pop-up without making a commitment to do anything.

The advantage of a pop-up is that it directly associates actions and attributes with an object on the screen. Its biggest disadvantage is that there may be no indication that a given object has an associated menu, until you happen to press on it. This disadvantage could lead to less transparent and less consistent applications, especially if the application's standard menus were replaced with pop-ups. Don't do that! I find them most useful in dialog boxes and desk accessories.

One final issue. When the user presses on an object with a pop-up menu, it might be desirable to highlight the object and have the menu pop-up just below the object, in a manner similar to pull-down menus. I'd call such a scheme a "pop-down" menu, and leave its implementation as an exercise.

Designing a Pop-Up

To make pop-up menus easy to use, I wanted to minimize the number of additional routines an application or desk accessory must call. Also, I wanted to apply all of the existing resource editing and compiling tools to construction and modification of the resource file description of a pop-up. Finally, to minimize my programming effort, I wanted to use as much of the Menu Manager's built in machinery as possible. With these goals in mind, I decided to use the standard menu record and the standard menu definition procedure without modification.

My efforts resulted in the single routine PopUpSelect. Its interface is almost identical to the Menu Manager routine MenuSelect:

 typedef short int16;
 typedef long int32;
 int32 PopUpSelect(theMenu, hitPt)
 MenuHandle theMenu;
 Point * hitPt;

Here's how you use it: When your application receives a mouse-down event in an object that has an associated pop-up, your application should call the PopUpSelect, supplying it with a handle to the pop-up menu and the point where the mouse button was pressed. PopUpSelect will pop-up the menu, track the mouse and highlight menu items until the user releases the mouse button. PopUpSelect returns a 32 bit integer in a manner identical to MenuSelect. The high-order 16 bits contains the menu ID of the pop-up menu, the low-order 16 bits contains the menu item number of the item that was choosen. If no item was choosen, the value returned is 0. (I use int16 and int32 to avoid the ambiguity inherent in the sizes of C's short, int, and long types. Also, I pass points by address rather than by value, in deference to Inside Mac.)

Before PopUpSelect can be called, the pop-up menu itself must be set up. Since a pop-up has the same structure as a pull-down menu, you do this by reading the menu from a resource file using GetMenu, or allocate it with NewMenu and filling it with items using AppendMenu, AddResMenu or InsertResMenu. The only difference in usage between pull-down and pop-up menus is that pull-downs are added to the menu bar using InsertMenu, and pop-ups are passed to PopUpSelect whenever the appropriate mouse-down events occur.

One thing to note: Don't bother defining a command key equivalent to an item in a pop-up. Since the pop-up is not in the menu bar, the Menu Manager routine MenuKey won't be able to find it. You could add all of your pop-ups to the menu bar just before the MenuKey call, and remove them just after, but don't do this! There's no need for these items to have command equivalents.

Making It Work

PopUpSelect is built up from the following sequence of operations:

- determine where to draw the pop-up

- save the part of the screen under the pop-up

- draw the pop-up

- track the mouse until the mouse button is released

- blink the selected item, if any

- erase the pop-up and restore the screen

- return the appropriate result

The first task, that of determining where to draw the pop-up, is based on the size of the menu and the location where the mouse was pressed. The size of the menu is defined by the fields menuWidth and menuHeight in the menu record (whose definition is shown below), which specify the horizontal and vertical dimensions of the menu, in pixels. The Menu Manager determines these values when the menu is allocated and filled with items.

 typedef struct
 int16 menuID;
 int16 menuWidth;
 int16 menuHeight;
 Handle menuProc;
 int32 enableFlags;
 Str255 menuData;
 } MenuInfo, *MenuPtr, **MenuHandle;

The standard menu definition procedure draws the menu's items inside a rectangle of these dimensions. The black border and shadow of the standard pull-down menu appear immediately outside that rectangle.

I decided that the rectangle should be positioned so that the location where the mouse was pressed is just inside of the top-right corner of the menu. The pop-up hangs generally downward and to the left of the pointer. The only constraint on this positioning is that the menu must be completely visible in the desktop portion of the screen. Thus, the rectangle must be shifted in the appropriate direction if the mouse location is near the menu bar or an edge of the screen.

The technique I used to determine the coordinates of the menu rectangle can best be explained with the aid of a diagram. The point labeled S is the top-left corner of the screen. The point labeled M is the location where the mouse was pressed (defined by the hitPt argument). The rounded corner rectangle represents the screen. The thick bordered rectangle containing M represents the boundary of the pop-up.

Notice that top-left corner of the menu rectangle is displaced POINTERH pixels horizontally and POINTERV pixels vertically from M. These values incorporate my decision to have the menu appear generally to the left and downward from the pointer. They are constants in the implementation, and hence are easy to change.

The top of the menu rectangle is displaced 20 pixels downward from the local origin, labeled 0,0 in the diagram. By defining a local origin in this manner, the standard menu definition procedure is tricked into thinking that it is drawing the menu just below the menu bar. That is, the top coordinate of the menu rectangle in the local system is 20, the height of the standard menu bar. Given these values, you should be able to find that the horizontal coordinate of S is -(hitPt.h - POINTERH) and its vertical coordinate is -(hitPt.v - POINTERV - 20).

The final constraint on the local location of S is that the menu must be completely visible in the desktop portion of the screen. This constrains the horizontal coordinate of S to be less than or equal to 0 (otherwise the left side of the menu would be off-screen) and greater than or equal to the width of the menu minus the width of the screen (otherwise the right side would be off-screen). A similar situation holds vertically. All of these computations (plus an allowance for the menu's frame and shadow) are incorporated in the arguments of a Quickdraw SetOrigin call, which sets up the desired local origin.

One final item to note: SetOrigin translates the coordinates of the current port's portBits.bounds, portRect, and visRgn to the new coordinate system, but not its clipRgn. Hence, a call to ClipRect with the translated portRect as an argument is appropriate after the SetOrigin call.

PopUpSelect accomplishes the task of saving the part of the screen under the pop-up by copying that part to an off-screen bitmap using the Quickdraw routine CopyBits. The off-screen bitmap is allocated with a NewHandle call. The width of the menu rectangle (plus the width of the frame and shadow) determines the value of its rowBytes field (appropriate rounded up to a multiple of 2 bytes, since rowBytes must be even). The height of the menu rectangle (plus the height of the frame and shadow) determines the number of rows in the bitmap. These two values multiplied together, plus the size of a bitmap structure, determine the number of bytes to allocate. The bitmap structure itself is build in the first few bytes of the allocated area. The baseAddr field of the bitmap points to the byte immediately following the end of the bitmap structure.

The next task, that of drawing the menu, is performed by calling the standard menu definition procedure whose handle is contained in the menuProc field of the menu record. A menu definition procedure has the following interface:

 #define mDrawMsg 0
 #define mChooseMsg 1
 #define mSizeMsg 2

 MenuDefProc(message, theMenu, menuRect,
 hitPt, whichItem)
 int16 message;
 MenuHandle theMenu;
 Rect *menuRect;
 Point *hitPt;
 int16 *whichItem;

Passing the message mDrawMsg to the menu definition procedure causes it to draw the menu inside the rectangle menuRect. The Window Manager port should be the current port when this message is sent. I set the port's clipRgn equal to menuRect, just to be safe.

The task of tracking the mouse is accomplished by passing the message mChooseMsg to the menu definition procedure. When the procedure receives mChooseMsg, its hitPt parameter is the current mouse location, and its whichItem parameter is the item number of the last item that was choosen from the menu. If the location is in an enabled menu item, the procedure unhighlights whichItem and highlights the newly choosen item (unless the new item is the same as the whichItem), and returns the item number of the new item in whichItem. If the location isn't in an enabled item (or isn't inside menuRect), the procedure unhighlights whichItem and returns 0. The following fragment of code shows how this works:

 whichItem = 0;
 SetPt(hitPt, 0, 0);
 MenuDefProc(mChooseMsg, theMenu, 
 &menuRect, hitPt, &whichItem);
 while (WaitMouseUp());

WhichItem and hitPt are both initialized to 0 since the local coordinate system has changed, invalidating the original value of hitPt. This initialization is consistent since the local origin is outside menuRect. GetMouse returns the mouse location in the local coordinate system of the current port, which is just what we want. Finally, WaitMouseUp is called rather than StillDown so that the pending mouse-up event is removed, to avoid confusing the application (MenuSelect does this too).

If the final value of whichItem is not zero, then PopUpSelect interrogates the menu blink value in the system parameter ram area and sends the menu definition procedure the mChooseMsg message an appropriate number of times to blink the selected item. The hitPt argument is alternately modified so that the item blinks.

The task of restoring the screen after the mouse-up occurs is easily accomplished with CopyBits. The off-screen bitmap is deallocated after CopyBits completes. The original coordinate system is also restored with a second SetOrigin call.

Finally, PopUpSelect returns the appropriate result based on the menu's menuID field and the final value of whichItem.

An Implementation

The remainder of the article contains the implementation of PopUpSelect and a sample program showing how to use it. The sample draws the caution alert icon on the screen and pops-up a short menu whenever the icon is pressed. The sources are set up to use the Consulair C compiler and header files, version 4.01. [Note that a complete Megamax version is supplied along with this Consulair version on the source code disk, courtesy of the author. -Ed.]

 * Pop-Up Menu Selection
 * by Mike Schuster
 * function PopUpSelect(theMenu: MenuHandle, hitPt: Point): Longint
 * with hitPt equal to the point (in global coordinates) where the mouse
 * button was pressed, PopUpSelect will pop up theMenu and retain control
 * by tracking the mouse and highlighting menu items until the mouse 
 * is released.  PopUpSelect returns a 32-bit integer in a manner identical
 * to the Menu Manager routine MenuSelect.
 * October 16, 1985: Version 1.0

#include "memory.h"
#include "resource.h"
#include "quickdraw.h"
#include "menu.h"
#include "osmisc.h"

#define GETSYSPPTR ((SysPPtr) 0x1F8)

typedef short int16;
typedef long int32;

#define mDrawMsg 0
#define mChooseMsg 1
#define mSizeMsg 2

#define POINTERH (*theMenu)->menuWidth - 4   /* width offset from hitPt 
#define POINTERV 8 /* height offset from hitPt */

#define MENUV 20 /* height of menu bar */

#define FRAMEH 2 /* width of menu frame */
#define FRAMEV 2 /* height of menu frame */

#define DELAY 2L /* blink delay */

/* pin integer i between lower and upper bounds l and u */
static pin(i, l, u)
 int16 i;
 int16 l;
 int16 u;
 if (i < l)
 return l;
 else if (i > u)
 return u;
 return i;

/* invoke the standard menu definition procedure */
static MenuDefProc(message, theMenu, menuRect, hitPt, whichItem)
 int16 message;
 MenuHandle theMenu;
 Rect *menuRect;
 Point *hitPt;
 int16 *whichItem;
 move.w message,-(A7); push first parameter
 move.l theMenu,-(A7)
 move.l menuRect,-(A7)
 move.l hitPt,A0
 move.l (A0),-(A7)
 move.l whichItem,-(A7)   ; push last parameter
 move.l theMenu,A0 ; get menu handle
 move.l (A0),A0  ; get menu pointer
 move.l 6(A0),A0 ; get menu proc handle
 move.l (A0),A0  ; get menu proc pointer
 jsr    (A0); dive in

/* popup menu selection routine */
int32 PopUpSelect (theMenu, hitPt)
 MenuHandle theMenu;
 Point *hitPt;
 GrafPtr port;   /* current graf port */
 GrafPtr wMgrPort; /* window manager port */
 BitMap **theMenuBits;    /* handle to BitMap to save screen in */
 BitMap *menuBits; /* pointer to "" */
 int16 rowBytes; /* rowBytes of "" */
 int16 rows;/* rows of "" */
 Rect menuRect;  /* menu rectangle, in local coordinates*/

 int16 whichItem;/* selected item */
 int16 blink;    /* blink count */
 int32 nilPt;    /* nil point for blink */

 /* return if mouse is not down */
 if (!WaitMouseUp())
 return 0L;

 /* determine the menu rectangle, in local coordinates */
 0, MENUV, (*theMenu)->menuWidth, MENUV + (*theMenu)->menuHeight);

 /* inset the menu rectangle to include the frame and shadow */
 InsetRect(&menuRect, -FRAMEH, -FRAMEV);

 /* allocate the bitmap to save screen in */
 rowBytes = ((menuRect.right - menuRect.left + 15) >> 4) << 1;
 rows = menuRect.bottom -;
 theMenuBits = (BitMap **) 
 NewHandle(rowBytes * rows + (int32) sizeof(BitMap));

 /* return if no space */
 if (!theMenuBits)
 return 0L;

 /* lock down the bitmap */
 menuBits = *theMenuBits;

 /* initialize the BitMap */
 menuBits->baseAddr = (char *) (menuBits + 1);
 menuBits->rowBytes = rowBytes;
 menuBits->bounds = menuRect;

 /* save the current graf port, use the window manager port */

 /* set origin so that menu definition procedure draws menu under hitPt 
 /* pin so that whole menu is visible */
 (pin(POINTERH - hitPt->h, 
 (*theMenu)->menuWidth - wMgrPort->portRect.right + 
  pin(MENUV + POINTERV - hitPt->v, 
   MENUV + (*theMenu)->menuHeight - wMgrPort->portRect.bottom + 

 /* clip to save the screen */

 /* save the screen */
 CopyBits(&wMgrPort->portBits, menuBits, 
 &menuBits->bounds, &menuBits->bounds, 0, 0L);

 /* erase and frame the menu rectangle */
 InsetRect(&menuRect, FRAMEH, FRAMEV);
 InsetRect(&menuRect, -1, -1);
 InsetRect(&menuRect, 1, 1);

 /* add shadow */
 MoveTo(menuRect.left + 1, menuRect.bottom + 1);
 Line((*theMenu)->menuWidth, 0);
 Line(0, - (*theMenu)->menuHeight);

 /* clip for the standard menu definition procedure */

 /* prepare to call the standard menu definition procedure */

 /* draw the menu */
 whichItem = 0;
 SetPt(hitPt, 0, 0);
 MenuDefProc(mDrawMsg, theMenu, &menuRect, hitPt, &whichItem);

 /* track the mouse until the button is released */
 MenuDefProc(mChooseMsg, theMenu, &menuRect, hitPt, &whichItem);
 while (WaitMouseUp());

 /* blink the item */
 if (whichItem)
 for (blink = GETSYSPPTR->Misc >> 2 & 0x3; blink; blink--)
 nilPt = 0L;
 MenuDefProc(mChooseMsg, theMenu, &menuRect, &nilPt,&whichItem);
 nilPt = Delay(DELAY);    /* Inside Mac and Consulair C differ here */
 menudefproc(mChooseMsg, theMenu, &menuRect, hitPt, &whichItem);
 nilPt = Delay(DELAY);    /* Inside Mac and Consulair C differ here */

 /* done calling the standard menu definition procedure */

 /* clip to restore screen */

 /* restore the screen and clean up */
 CopyBits(menuBits, &wMgrPort->portBits, 
 &menuBits->bounds, &menuBits->bounds, 0, 0L);

 /* restore the window manager port origin and the current graf port 
 SetOrigin(0, 0);

 /* return the standard result */
 return whichItem ? ((int32) (*theMenu)->menuID << 16) + whichItem : 

 * Pop-up Menu Example

#include "quickdraw.h"
#include "menu.h"
#include "events.h"

extern long PopUpSelect();

 MenuHandle menu;
 EventRecord event;
 GrafPtr port;
 Rect box;

 /* initialize the managers */
 /* InitGraf(&thePort); *//* Consulair does this for us */
 /* InitFonts(); */
 /* InitWindows(); */

 /* draw the icon */
 SetRect(&box, 32, 32, 64, 64);
 PlotIcon(&box, GetIcon(0));

 /* initialize the popup menu */
 menu = NewMenu(1, "");
 AppendMenu(menu, "\pBeep;(-;Quit"); /* \p for pascal string */

 /* handle mouse down events */
 while (1)
 GetNextEvent(everyEvent, &event);
 if (event.what == mouseDown)
 if (PtInRect(&event.where, &box))
 switch (LoWord(PopUpSelect(menu, &event.where)))
 case 1:
 case 3:


Community Search:
MacTech Search:

Software Updates via MacUpdate

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 »
The best games like Animal Crossing on m...
Animal Crossing amiibo Festival is out right now for the Wii U, reminding us of just how much fun that world can be. Or at least to go back and check in on our villages once in a while. [Read more] | Read more »
Between 2 Taps - Tap for Tap interview M...
Hello, and welcome back to Between 2 Taps, Tap for Tap’s Indie Dev interview series. [Read more] | 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
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
Early Black Friday sale at B&H Photo, up...
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: $1699 $300 off... Read more
NewerTech/OWC/MacSales Black Friday Deals 201... • Free Shipping available on nearly EVERYTHING on orders $35.00 & up within USA + • International Delivery Specials from $2.99+ Special Purolator... Read more
Walmart Black Friday deals: $100 off select i...
Walmart has released their Black Friday deals for 2015, now available online. Choose free shipping or free local store pickup (if available): - 16GB iPad Air 2: $399, $100 off MSRP - 16GB iPad Air: $... Read more
Photo Cleaner 1.0 Reclaims iPhone Storage Spa...
Seoul, Korea based mix1009 has announced the release and immediate availability of Photo Cleaner 1.0, their handy iPhone app that deletes the video portion of Live Photos, in order to reclaim space... Read more
Black Friday and Holiday sales on our price t...
Scan our Mac Price Trackers for the latest Black Friday and Holiday season information on sales, bundles, and availability on systems from Apple’s authorized internet/catalog resellers. We update the... Read more
Best Buy Black Friday deals: Up to $200 off M...
Best Buy has posted their Black Friday sale prices for 2015. Save on MacBook Pros, MacBooks, MacBook Airs, iMacs, iPads, and Apple Watches. Choose free shipping or free local store pickup (if... Read more
Save $30-$40 on new Apple TVs after rebate
Adorama has new Apple TVs on sale for up to $40 off MSRP after mail-in rebate, good through December 15th. Shipping is free, and Adorama charges NY & NJ sales tax only: - 32GB Apple TV: $119.99... Read more
13-Inch Haswell MacBook Air At Two Years – Th...
The 13-inch mid-2013 “Haswell” MacBook Air I ordered in Apple’s November 2013 Black Friday sale was my first new Mac in four and a half years — the longest interval I’ve gone between system upgrades... 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.