TweetFollow Us on Twitter

Custom Menu
Volume Number:3
Issue Number:7
Column Tag:Forth Forum

Custom Menu Definition

By Jörg Langowski, MacTutor Editorial Board, Grenoble, France

"Pascal calling and menu definition routines"

Once again, this month's excursion will take us into a field that is unusual for threaded code languages on the Macintosh: we will define a custom menu routine entirely in Mach 2 Forth and create the necessary glue code that is needed to call this routine as a Pascal procedure, the way the Toolbox expects it.

The subject as such had already been addressed by Darryl Lovato (V2#8), where he redefined the standard menu definition procedure in TML Pascal. Besides giving you one more example of 'kernel-independent' Forth code, I chose this topic to illustrate the concept of Pascal parameter passing in Forth (discovering on the way one potentially awful bug in the desk accessory glue code that I wrote recently. Read on.).

We'll also have some Forth bits recently sent to me by Juri Munkki (the creator of the TED editor task), and some news on further Mach2 developments. But first, to our main theme.

Menu Defintion Routines

The format of a menu is record is given below.

As you might know, the routine that is used by the Menu Manager to draw a menu is kept in a MDEF resource. Since each menu contains information on the ID of its corresponding MDEF resource, the menu definition routine may be changed easily by changing the routine ID in the MENU resource. (Fig. 1). The standard Macintosh MDEF (contained in the Mac+ ROMS) has an ID of 0. If the menu resource contains a different ID, that MDEF will be loaded and a handle to it put into the menuProc field of the menu record. Alternatively, one may install the menu with its old ID, and substitute the handle afterwards.

In order to write our custom menu definition routine in Forth, we need to know some details about the parameters that are passed to it and how they are located on the stack. The menu definition routine is a Pascal procedure defined in the following way (IM):

procedure MyMenu (message: INTEGER; theMenu: MenuHandle; VAR menuRect: 
Rect; hitPt: Point; VAR whichItem: INTEGER);

with the parameters

message: 0, 1, or 2. 0 is mDrawMsg, telling the menu routine to draw the menu within the bounds given by menuRect. 1 is mChooseMsg, which tells the routine that the menu item corresponding to the mouse location in hitPt should be highlighted and its number returned in whichItem. 2, mSizeMsg, indicates that the menu's dimensions should be calculated and stored in the menuWidth and menuHeight fields of the menu record.

theMenu a handle to the menu record from which the routine was initiated.

menuRect: the rectangle, in global coordinates, in which the menu is located.

hitPt the mouse location, in global coordinates, when the routine was called.

whichItem on entry contains the item number of the last item selected and on exit the number of the new item selected.

The menu manager expects the entry point to the routine to be at the beginning of the MDEF resource. Since the entry point to the highest-level Forth word is usually somewhere near the end of the code, this will require some hacking with vectors.

Fig. 2 shows how the stack looks like on entry to the routine. As usual, the top of stack (lowest in memory) contains the return address, followed by the parameters. What our glue code has to do is to save the return address somewhere, move all parameters from the A7 to the Forth stack (A6), save the contents of all registers, and call the Forth routine. On exit, the registers should be restored, before returning through an RTS. Fig. 3 shows a possible stack arrangement just before entering (or after exiting) the Forth routine.

This simple method, however, has some drawbacks. In order to put the parameters on the Forth stack, we have to define an A6 stack space first (thereby changing A6), so the registers will have to be saved before the parameters are transferred. That by itself is not a big problem, in fact it is the standard method for Pascal procedure calling. The other problem is with setting up the A6 stack. In earlier columns I included routines for stack setup in the glue code, defining stack space within the code space. Although this will do the job, it completely precludes re-entrancy and can be space-consuming if different routines cannot share the same stack space. Therefore, this time I'll describe an improvement that is also much closer to the Pascal calling conventions.

In Pascal routines, the first instruction usually is a

 LINK A6, -nnn

where nnn is the number of bytes to reserve on the stack for local variables. The LINK instruction will push the current value of A6 on the stack, copy A7 to A6 (thereby making A6 point to the top of stack), and reserve nnn bytes on the stack, changing A7 accordingly. Before we exit the routine, we'll have an


which reverses the action of LINK: it replaces A7 with the current value of A6 and pops the top of stack into A6, thereby restoring A6 and A7 to the values they had on routine entry.

To get rid of the parameters on the stack, we then put the return address into A0

 MOVE.L (A7)+,A0

pop the parameters (m bytes) off the stack

 ADD.L  #m,A7

and leave the routine through the return address

 JMP    (A0) .

The glue code at the end of listing 1 implements this calling procedure. Its advantage is that after the LINK instruction we may peacefully save the registers on the stack, preserving A6 as a pointer to our parameters (they start at 8(A6)). Also, we have automatically created a local variable space (512 bytes in our example) which serves as a Forth stack with A6 already aligned in the proper way. Since the Forth stack is located within a stack frame in the A7 stack, re-entry is no problem (remember, though, that some applications don't provide too much A7 stack space, so be careful).

Half the local stack space is devoted to the A3 stack, which is the loop return stack in Mach2. A3, too, is set up by the glue code. And here comes the potential bug in my DA routines that I had already mentioned: those glue routines do not contain support for an A3 stack. Since I did not use DO...LOOPs in the examples, there were no problems, but should you use that code to develop other desk accessories that use loops, be careful to add the extra A3 setup.

Messages to the MDEF routine

Now that we have passed all the parameters to the menu definition routine in the right way, what are we going to do with them? We have to write a routine that handles the three possible message, mDrawMsg, mChooseMsg and mSizeMsg.

Our custom menu will look like the one in Fig. 4.

Fig. 4: Output from the custom MDEF routine

A simple four-by-four palette arrangement of fixed size (100 by 100 pixels in the example). The item number returned will be from 1 to 16, and we do not take into account whether a menu item is disabled or not.

The three possible messages are handled in a CASE statement which forms the main body of the MDEF routine. Refer to Listing 1 to see how they work. First, the menu width and height are recalled from the menu record, and the sizes of the palette rectangles calculated (wd and ht). The top and left coordinates of the menu rectangle are obtained from menuRect. The CASE statement follows, where the Draw message simply draws sixteen little boxes into the menu rectangle, filling them with some patterns. These patterns are part of the Quickdraw global variables, to which the words white, etc. provide access.

The Size message stores the menu's dimensions in the menu record.

The Choose message is the most complicated one: whichItem on entry contains the number of the item selected last (zero if none). The item rectangles are scanned, one after the other, to see whether hitPt is in one of them. If so, the new item number is calculated and compared to the old one. If they are the same, nothing is done; if they are not, both the new and the old item rectangles are inverted and the new item number returned in whichItem. If the new mouse location does not correspond to any item, we just invert the old item and return zero in whichItem.

At the end of the listing, code is provided to install the new MDEF routine in the header of an existing menu for testing (and to remove it, of course). To get the IDs of the menus installed in the Mach2 system (or any other Forth you might transport this code to), the word list.menus is defined near the beginning of the listing. Finally, at the very end I added some code to write a MDEF 1 resource to a new resource file so that you may install this custom menu with ResEdit.

Feedback dept.

I recently received some more mail from Juri Munkki, who already had an article in this magazine. It deals with implementing animation under Mach2 and you'll read about it very soon; for now just a clever trick that I found in the code. ANEW <word>, used at the beginning of a file to forget the previous definition, is very useful and does not exist in Mach2. A redefinition using FORGET was possible in Mach2.0, but no more in 2.1, since FORGET is not a global definition anymore. Listing 2 shows Juri's hack to circumvent that problem: he takes the definition of DUMP, which is defined (global) just before FORGET in the dictionary, and uses it as a pointer to access the FORGET code. Try out for yourself. There is also a word that will return heap space for a variable that contains a handle.

The new Mach2 update, containing the editor, is on its way (as of beginning of May). In addition to the editor (still only single-window, sorry to say), the debugger has the bus, address, etc. error handlers fixed: they return back directly into the Forth system. Also, a switch is included by which you can select to enter TMON (or any other debugger) or the Forth debugger upon pressing the interrupt switch. For customizing, the source code of the I/O task is included, and the SANE handling has improved (like error traps etc.). I might tell you more about it next time when I've received my copy.

For this time, happy threading.

Listing 1: Menu definition routine
( © J. Langowski/MacTutor   )

( *** menu definition procedures. J.L. April 1987 *** )


4D444546 CONSTANT "mdef
1 CONSTANT mChooseMsg

CODE white
 MOVE.L (A5),-(A6)
 SUBQ.L #8,(A6)

CODE black
 MOVE.L (A5),-(A6)
 SUBI.L #16,(A6)

CODE gray
 MOVE.L (A5),-(A6)
 SUBI.L #24,(A6)

CODE ltgray
 MOVE.L (A5),-(A6)
 SUBI.L #32,(A6)

CODE dkgray
 MOVE.L (A5),-(A6)
 SUBI.L #40,(A6)

 MOVE.L (A6)+,D1
 MOVE.L (A6)+,D0
 MOVE.L D0,-(A6)

 MOVE.L (A6)+,D1
 MOVE.L (A6)+,D0
 EXT.L  D0
 MOVE.L D0,-(A6)
CODE w/mod
 MOVE.L (A6)+,D1
 MOVE.L (A6)+,D0
 EXT.L  D1
 EXT.L  D0
 MOVE.L D1,-(A6)
 MOVE.L D0,-(A6)
( *** menu record data structure *** )
 0 CONSTANT menuID ( integer )
 2 CONSTANT menuWidth( integer )
 4 CONSTANT menuHeight  ( integer )
 6 CONSTANT menuProc ( handle )
10 CONSTANT enableFlags   ( longint )
14 CONSTANT menuData ( Str255 and other data ) 
 ( *** menu Data format *** )
 ( counted string: menu title )
 ( followed by 1 to 31 times: )
 ( counted string: menu item  )
 ( byte: item icon # )
 ( byte: equivalent character )
 ( byte: check mark character )
 ( byte: text attributes )
 ( .... )
 ( end: zero byte. )

: list.menus 
 32767 0 do 
 i call getMhandle
 ?dup IF ." Menu # " i . ." , handle " dup . cr 
 ." MenuData:" cr
 @ menuData + dup count type cr 
 ( type menu title )
 dup c@ + 1+ ( start of first item string )
 dup count dup
 WHILE type cr 
 dup c@ + 5 +
 REPEAT drop 
 PAUSE loop

( *** code moved to custom menu routine space starts here *** )

header start
 JMP start  ( to be filled later )
header temprect 8 allot
header itemrect 8 allot

( redefine multiplication and division words )
( so they remain local to our code, not relative )
( to application globals )
: * w* ;
: / w/ ;
: /mod w/mod ;

: mdef { message theMenu menuRect hitPt whichItem | 
 width height wd ht top left item# wi# -- }
 theMenu @ dup menuwidth  + w@ -> width
 width 4 / -> wd 
   menuheight + w@ -> height  
      height 4 / -> ht
 menuRect    w@ -> top
 menuRect 2+ w@ -> left

 message CASE
 mDrawMsg OF ( draw menu )
 height 0 DO
 4 0 DO 
 ['] temprect 
 left i wd * + top j + over wd + over ht +
 call setrect   
 ['] tempRect 4 4 
 i  CASE  0 OF white ENDOF
 1 OF ltgray  ENDOF
 2 OF gray  ENDOF
 3 OF dkgray  ENDOF
   black ( shouldn't occur )
   ENDCASE CALL FillRoundRect 
 ['] tempRect 4 4 CALL FrameRoundRect
 ht +LOOP

 mChooseMsg OF ( choose item )
 whichItem w@ -> wi#
 ['] ItemRect 
 wi# 1- 4 /mod ht * top + swap wd * left + swap
 over wd + over ht +  call setrect
 hitPt menuRect call PtInrect
   4 0 DO
 4 0 DO 
 i j 4 * + 1+ -> item#
 ['] temprect 
 left i wd * + top j ht * + 
 over wd + over ht +  call setrect   
 hitPt ['] tempRect call PtInRect 
 IF item# wi# <>
  IF ['] ItemRect 4 4 call InvertRoundRect
     ['] tempRect 4 4 call InvertRoundRect
   item# whichItem w!
  wi# IF ['] ItemRect 4 4 call InvertRoundRect THEN
   0 whichItem w!

 mSizeMsg OF ( our sizes are constant ) 
 100 theMenu @ menuWidth  + w!
 100 theMenu @ menuHeight + w!

( *** glue routine *** )

    LINKA6,#-512 ( 512 bytes of local Forth stack )
 MOVEM.L A0-A5/D0-D7,-(A7)( save registers )
 MOVE.L A6,A3    ( setup local loop return stack )
 SUBA.L #256,A3  ( in the low 256 local stack bytes )
 MOVE.L 8(A6),D0 ( VAR whichItem: INTEGER )
 MOVE.L 12(A6),D1  ( hitPt: Point )
 MOVE.L 16(A6),A0( VAR menuRect: Rect )
 MOVE.L 20(A6),A1  ( theMenu: MenuHandle )
 MOVEQ.L #0,D2
 MOVE.W 24(A6),D2  ( message: INTEGER )
 MOVE.L D2,-(A6)
 MOVE.L A1,-(A6)
 MOVE.L A0,-(A6)
 MOVE.L D1,-(A6)
 MOVE.L D0,-(A6)

 JSR mdef ( call Forth routine )

 MOVEM.L (A7)+,A0-A5/D0-D7( restore registers )
 MOVE.L (A7)+,A0 ( return address )
 ADD.W  #18,A7   ( pop off 18 bytes of parameters )
 JMP    (A0)

header end

' ' start 2+ - ' start 2+ w!

( *** installation *** )
variable Hregular

: install.custom { menu# | mh procH -- }
 menu# call getMHandle -> mh
 mh 0= abort" Non-existing menu ID given."
 ['] start ['] end over - call PtrToHand 
 abort" Can't get enough memory to install."
 -> procH 
 mh call HLock
 mh @ menuProc + @ Hregular !
 procH mh @ menuProc + !
 mh call HUnLock
 . . cr

: remove.custom { menu# | mh procH -- }
 menu# call getMHandle -> mh
 mh 0= abort" Non-existing menu ID given."
 mh call HLock
 mh @ menuProc + @ call DisposHandle
 Hregular @ mh @ menuProc + !
 mh call HUnLock
 . . . cr

( *** making a resource *** )
: $create-res call CreateResFile call ResError L_ext ;

: $open-res { addr | refNum -- result }
 addr call openresfile -> refNum
 call ResError L_ext
 dup not IF drop refNum THEN 

: $close-res call CloseResFile call ResError L_ext ;

: make-mdef { | refNum -- }
 " mdef.res" dup $create-res
 abort" You have to delete the old 'mdef.res' file first."
 $open-res dup -> refNum call UseResFile 
 ['] start ['] end over - call PtrToHand drop ( result code )
 "mdef 1 " Mach2 MDEF" call AddResource
 refNum $close-res drop ( result code )
Listing 2: some Mach2 tricks from Finland
( Juri Munkki, April 1987 )

: ANEW { | LEN }
   IF .s LEN >IN +! 
      ['] DUMP ( dump is defined just before FORGET )
 LEN >IN +!

( Heapvar:
  Used in the form: HEAPVAR VARIABLE_NAME. 
  If VARIABLE_NAME exists, it returns the handle 
  from VARIABLE_NAME to the heap. It should be used
  before ANEW to free space from the heap. )
  32 WORD
     @ DUP 

Community Search:
MacTech Search:

Software Updates via MacUpdate

WhiteCap 6.6 - Visual plug-in for iTunes...
WhiteCap is a sleek and sophisticated music visualizer and screensaver that features futuristic, wireframe mesh visuals with dynamic backgrounds and colors. WhiteCap contains thousands of visual... Read more
VueScan 9.5.65 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
Carbon Copy Cloner 4.1.13 - Easy-to-use...
Carbon Copy Cloner backups are better than ordinary backups. Suppose the unthinkable happens while you're under deadline to finish a project: your Mac is unresponsive and all you hear is an ominous,... Read more
TrailRunner 3.8.831 - Route planning for...
TrailRunner is the perfect companion for runners, bikers, hikers, and all people wandering under the sky. Plan routes on a geographical map. Import GPS or workout recordings and journalize your... Read more
Quicken 4.4.2 - Complete personal financ...
Quicken makes managing your money easier than ever. Whether paying bills, upgrading from Windows, enjoying more reliable downloads, or getting expert product help, Quicken's new and improved features... Read more
Adobe Illustrator CC 2017 21.0.2 - Profe...
Illustrator CC 2017 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous Illustrator customer). Adobe Illustrator CC 2017 is the industry... Read more
Paparazzi! 1.0b2 - Make user-defined siz...
Paparazzi! is a small utility for OS X that makes screenshots of webpages. This very simple tool takes screenshots of websites which do not fit on one screen. You specify the desired width, minimal... Read more
Monodraw 1.2.1 - Powerful ASCII art edit...
Monodraw allows you to easily create text-based art (like diagrams, layouts, flow charts) and visually represent algorithms, data structures, binary formats and more. Because it's all just text, it... Read more
Monodraw 1.2.1 - Powerful ASCII art edit...
Monodraw allows you to easily create text-based art (like diagrams, layouts, flow charts) and visually represent algorithms, data structures, binary formats and more. Because it's all just text, it... Read more
Iridient Developer 3.1.3 - Powerful imag...
Iridient Developer (was RAW Developer) is a powerful image conversion application designed specifically for OS X. Iridient Developer gives advanced photographers total control over every aspect of... Read more

ROME: Total War - Barbarian Invasion set...
To the delight of mobile strategy fans, Feral Interactive released ROME: Total War just a few months ago. Now the game's expansion, Barbarian Invasion is marching onto iPads as a standalone release. [Read more] | Read more »
Yuri (Games)
Yuri 1.0 Device: iOS iPhone Category: Games Price: $3.99, Version: 1.0 (iTunes) Description: It's night. Yuri opens his eyes. He wakes up in a strange forest.The small, courageous explorer rides on his bed on casters in this... | Read more »
Space schmup Xenoraid launches on the Ap...
10Tons Xenoraid is out today on the App Store, bringing some high-speed space action to your mobile gadgets just in time for the weekend. The company's last premium title, another sci-fi game titled Neon Chrome, did quite well for itself, so... | Read more »
Star Wars: Force Arena Beginner's G...
Star Wars: Force Arena joined the populous ranks of Star Wars games on mobile today. It's a two-lane MOBA starring many familiar faces from George Lucas's famed sci-fi franchise. As with most games of this nature, Force Arena can be a little obtuse... | Read more »
Mysterium: The Board Game (Games)
Mysterium: The Board Game 1.0 Device: iOS Universal Category: Games Price: $6.99, Version: 1.0 (iTunes) Description: The official adaptation of the famous board game Mysterium! | Read more »
Sonny (Games)
Sonny 1.0.4 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.4 (iTunes) Description: Reimagined for iOS, cult-hit RPG Sonny brings challenging turn-based combat that requires strategy and mastery of each new skill to... | Read more »
Towaga (Games)
Towaga 1.0 Device: iOS iPhone Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: "It has been foretold that a masked being would stand atop the legendary Towaga Temple, dwelling among shadows to fulfil The Black Moon... | Read more »
Bubble Witch 3 Saga Guide: How to get th...
King's bringing its fairytale bubble-popping puzzler back for its 3rd outing in Bubble Witch 3 Saga. If you're familiar with the series, not much has changed here on the surface level, though you'll likely be pleased with the improvements. If you'... | Read more »
Sunless Sea sails onto iPad this spring
Failbetter Games, the folks who brought you Fallen London, are celebrating their 7th birthday today. To commemorate the event, the team revealed that Sunless Sea is coming to iPad this spring. | Read more »
The Binding of Isaac: Rebirth (Games)
The Binding of Isaac: Rebirth 1.1 Device: iOS Universal Category: Games Price: $14.99, Version: 1.1 (iTunes) Description: Gameplay | Read more »

Price Scanner via

13-inch 1.6GHz/128GB MacBook Air on sale for... has the 1.6GHz/128GB 13″ MacBook Air on sale for $130 off MSRP including free shipping: - 13″ 1.6GHz/128GB MacBook Air (MMGF2LL/A): $869.99 $130 off MSRP Their price is the lowest... Read more
12-inch 32GB Space Gray iPad Pro on sale for...
B&H Photo has 12″ Space Gray 32GB WiFi Apple iPad Pros on sale for $55 off MSRP including free shipping. B&H charges sales tax in NY only: - 12″ Space Gray 32GB WiFi iPad Pro: $744.44 $55 off... Read more
9-inch 32GB Space Gray iPad Pro on sale for $...
B&H Photo has the 9.7″ 32GB Space Gray Apple iPad Pro on sale for $549 for a limited time. Shipping is free, and B&H charges NY sales tax only. Read more
Apple iMacs on sale for up to $120 off MSRP,...
B&H Photo has 21″ and 27″ Apple iMacs on sale for up to $120 off MSRP, each including free shipping plus NY sales tax only: - 27″ 3.3GHz iMac 5K: $2199 $100 off MSRP - 27″ 3.2GHz/1TB Fusion iMac... Read more
Apple refurbished Apple TVs available for up...
Apple has Certified Refurbished 32GB and 64GB Apple TVs available for up to $30 off the cost of new models. Apple’s standard one-year warranty is included with each model, and shipping is free: -... Read more
1.4GHz Mac mini, refurbished, available for $...
The Apple Store has Apple Certified Refurbished 1.4GHz Mac minis available for $419. Apple’s one-year warranty is included, and shipping is free. Their price is $80 off MSRP, and it’s the lowest... Read more
16GB iPad Air 2, Apple refurbished, available...
Apple has Certified Refurbished 16GB iPad Air 2s available for $319 including free shipping. A standard Apple one-year is included. Their price is $60 off original MSRP for this model. Read more
Mac Pros on sale for $200 off MSRP, refurbish...
B&H Photo has Mac Pros on sale for $200 off MSRP. Shipping is free, and B&H charges sales tax in NY only: - 3.7GHz 4-core Mac Pro: $2799, $200 off MSRP - 3.5GHz 6-core Mac Pro: $3799, $200... Read more
Save with Apple refurbished iPad Pros, models...
Apple has Certified Refurbished 9″ and 12″ Apple iPad Pros available for up to $160 off the cost of new iPads. An Apple one-year warranty is included with each model, and shipping is free: - 32GB 9″... Read more
Amazon drops 12-inch Retina MacBook prices to...
Amazon has 2016 12″ Apple Retina MacBooks on sale for $300 off MSRP for a limited time. Shipping is free. The following configurations are available: - 12″ 1.1GHz Silver Retina MacBook: $999.99 $300... Read more

Jobs Board

*Apple* & PC Desktop Support Technician...
Apple & PC Desktop Support Technician job in Los Angeles, CA Introduction: We have immediate job openings for several Desktop Support Technicians with one of our Read more
*Apple* Retail - Multiple Positions - Apple,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Premier Retailer - PT Service Specia...
DescriptionSimply Mac is the largest premier retailer for Apple products and solutions. At Simply Mac we are all Apple , all the time. Same products. Same prices. Read more
*Apple* Premier Retailer - Service Manager -...
DescriptionSimply Mac is the largest premier retailer for Apple products and solutions. At Simply Mac we are all Apple , all the time. Same products. Same prices. Read more
*Apple* Solutions Consultant - Apple (United...
# Apple Solutions Consultant Job Number: 54267729 Altamonte Springs, Florida, United States Posted: Jan. 6, 2017 Weekly Hours: 40.00 **Job Summary** As an Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.