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);
 do
 {
 MenuDefProc(mChooseMsg, theMenu, 
 &menuRect, hitPt, &whichItem);
 GetMouse(hitPt);
 }
 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 
button
 * 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;
 else
 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;
 {
 #asm
 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
 #endasm
 }

/* 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 */
 SetRect(&menuRect, 
 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 - menuRect.top;
 theMenuBits = (BitMap **) 
 NewHandle(rowBytes * rows + (int32) sizeof(BitMap));

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

 /* lock down the bitmap */
 HLock(theMenuBits);
 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 */
 GetPort(&port);
 GetWMgrPort(&wMgrPort);
 SetPort(wMgrPort);

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

 /* clip to save the screen */
 ClipRect(&wMgrPort->portRect);

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

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

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

 /* clip for the standard menu definition procedure */
 ClipRect(&menuRect);

 /* prepare to call the standard menu definition procedure */
 LoadResource((*theMenu)->menuProc);
 HLock((*theMenu)->menuProc);

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

 /* track the mouse until the button is released */
 do
 {
 MenuDefProc(mChooseMsg, theMenu, &menuRect, hitPt, &whichItem);
 GetMouse(hitPt);
 }
 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 */
 HUnlock((*theMenu)->menuProc);

 /* clip to restore screen */
 ClipRect(&wMgrPort->portRect);

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

 /* restore the window manager port origin and the current graf port 
*/
 SetOrigin(0, 0);
 ClipRect(&wMgrPort->portRect);
 SetPort(port);

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

/*
 * Pop-up Menu Example
 */

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

extern long PopUpSelect();

main()
 {
 MenuHandle menu;
 EventRecord event;
 GrafPtr port;
 Rect box;

 /* initialize the managers */
 /* InitGraf(&thePort); *//* Consulair does this for us */
 /* InitFonts(); */
 /* InitWindows(); */
 InitMenus();
 TEInit();
 InitDialogs(0L);
 InitCursor();

 /* draw the icon */
 GetWMgrPort(&port);
 SetPort(port);
 ClipRect(&port->portRect);
 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:
 SysBeep(4);
 break;
 case 3:
 ExitToShell();
 break;
 }
 }
 }

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Six fantastic ways to spend National Vid...
As if anyone needed an excuse to play games today, I am about to give you one: it is National Video Games Day. A day for us to play games, like we no doubt do every day. Let’s not look a gift horse in the mouth. Instead, feast your eyes on this... | Read more »
Old School RuneScape players turn out in...
The sheer leap in technological advancements in our lifetime has been mind-blowing. We went from Commodore 64s to VR glasses in what feels like a heartbeat, but more importantly, the internet. It can be a dark mess, but it also brought hundreds of... | Read more »
Today's Best Mobile Game Discounts...
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Nintendo and The Pokémon Company's...
Unless you have been living under a rock, you know that Nintendo has been locked in an epic battle with Pocketpair, creator of the obvious Pokémon rip-off Palworld. Nintendo often resorts to legal retaliation at the drop of a hat, but it seems this... | Read more »
Apple exclusive mobile games don’t make...
If you are a gamer on phones, no doubt you have been as distressed as I am on one huge sticking point: exclusivity. For years, Xbox and PlayStation have done battle, and before this was the Sega Genesis and the Nintendo NES. On console, it makes... | Read more »
Regionally exclusive events make no sens...
Last week, over on our sister site AppSpy, I babbled excitedly about the Pokémon GO Safari Days event. You can get nine Eevees with an explorer hat per day. Or, can you? Specifically, you, reader. Do you have the time or funds to possibly fly for... | Read more »
As Jon Bellamy defends his choice to can...
Back in March, Jagex announced the appointment of a new CEO, Jon Bellamy. Mr Bellamy then decided to almost immediately paint a huge target on his back by cancelling the Runescapes Pride event. This led to widespread condemnation about his perceived... | Read more »
Marvel Contest of Champions adds two mor...
When I saw the latest two Marvel Contest of Champions characters, I scoffed. Mr Knight and Silver Samurai, thought I, they are running out of good choices. Then I realised no, I was being far too cynical. This is one of the things that games do best... | Read more »
Grass is green, and water is wet: Pokémo...
It must be a day that ends in Y, because Pokémon Trading Card Game Pocket has kicked off its Zoroark Drop Event. Here you can get a promo version of another card, and look forward to the next Wonder Pick Event and the next Mass Outbreak that will be... | Read more »
Enter the Gungeon review
It took me a minute to get around to reviewing this game for a couple of very good reasons. The first is that Enter the Gungeon's style of roguelike bullet-hell action is teetering on the edge of being straight-up malicious, which made getting... | Read more »

Price Scanner via MacPrices.net

Take $150 off every Apple 11-inch M3 iPad Air
Amazon is offering a $150 discount on 11-inch M3 WiFi iPad Airs right now. Shipping is free: – 11″ 128GB M3 WiFi iPad Air: $449, $150 off – 11″ 256GB M3 WiFi iPad Air: $549, $150 off – 11″ 512GB M3... Read more
Apple iPad minis back on sale for $100 off MS...
Amazon is offering $100 discounts (up to 20% off) on Apple’s newest 2024 WiFi iPad minis, each with free shipping. These are the lowest prices available for new minis among the Apple retailers we... Read more
Apple’s 16-inch M4 Max MacBook Pros are on sa...
Amazon has 16-inch M4 Max MacBook Pros (Silver and Black colors) on sale for up to $410 off Apple’s MSRP right now. Shipping is free. Be sure to select Amazon as the seller, rather than a third-party... Read more
Red Pocket Mobile is offering a $150 rebate o...
Red Pocket Mobile has new Apple iPhone 17’s on sale for $150 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Switch to Verizon, and get any iPhone 16 for...
With yesterday’s introduction of the new iPhone 17 models, Verizon responded by running “on us” promos across much of the iPhone 16 lineup: iPhone 16 and 16 Plus show as $0/mo for 36 months with bill... Read more
Here is a summary of the new features in Appl...
Apple’s September 2025 event introduced major updates across its most popular product lines, focusing on health, performance, and design breakthroughs. The AirPods Pro 3 now feature best-in-class... Read more
Apple’s Smartphone Lineup Could Use A Touch o...
COMMENTARY – Whatever happened to the old adage, “less is more”? Apple’s smartphone lineup. — which is due for its annual refresh either this month or next (possibly at an Apple Event on September 9... Read more
Take $50 off every 11th-generation A16 WiFi i...
Amazon has Apple’s 11th-generation A16 WiFi iPads in stock on sale for $50 off MSRP right now. Shipping is free: – 11″ 11th-generation 128GB WiFi iPads: $299 $50 off MSRP – 11″ 11th-generation 256GB... Read more
Sunday Sale: 14-inch M4 MacBook Pros for up t...
Don’t pay full price! Amazon has Apple’s 14-inch M4 MacBook Pros (Silver and Black colors) on sale for up to $220 off MSRP right now. Shipping is free. Be sure to select Amazon as the seller, rather... Read more
Mac mini with M4 Pro CPU back on sale for $12...
B&H Photo has Apple’s Mac mini with the M4 Pro CPU back on sale for $1259, $140 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – Mac mini M4 Pro CPU (24GB/512GB): $1259, $... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.