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

Top 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... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

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