TweetFollow Us on Twitter

FKeys, Events
Volume Number:3
Issue Number:9
Column Tag:Forth Forum

FKeys & Events

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

FKEYs and Events

The example we’ll deal with this time has some history. On a national bulletin board here in France, Calvacom, which has a large section of its activity devoted to the Mac, a proposal was made to write an FKEY that would paste one of a number of character strings into the application currently under use. Thus one would have an easy way to enter ‘boilerplate’ phrases or often used commands into text processors, terminal emulators etc.

I thought this would make a nice example for the Forth column, especially since we hadn’t had an FKEY dealt with yet. In the way of writing this, I discovered several things. First, the simple strategy that comes to mind - taking a string that was saved away somewhere and posting key down events for one character after the other - works only in certain cases, so one has to go a more complicated way (as you’ll see soon). Second, somebody had of course in the meantime written the FKEY under question - in some other language. Nevertheless, still a good Forth example.

Implementing an FKEY

Everyone of you has probably already used one or the other function key, that is, command-shift-number combination. Some might even have written one, its implementation being rather simple. The FKEY resource is a simple subroutine with its entry point at the beginning of its code. It is called from the routine that handles the keyboard. If that routine detects a command-shift-number combination, it will look for the FKEY resource corresponding to the number, and if such a resource is present, load and execute it.

No parameters are passed to the FKEY routine on the stack; we’ll simply set up a local Forth stack on entry to the routine, using LINK, save all registers away, then call the main body of the FKEY, and finally restore the registers and UNLINK A6. This is the standard glue routine for writing kernel-independent Mach2 code which you might already be familiar with. See listing 1.

[One remark with regard to the listing here. This program has been written in Mach2.12 which has a different Toolbox call mechanism than earlier versions. In particular, it expects D4 to point to a common stack low in memory which can be used for all toolbox calls. This stack, and D4, are set up in the Mach2 system. Therefore, to write kernel-independent code, one has to use the old CALL mechanism again. This word is available under a new name: (CALL). If you have an older Mach2 version, simply replace all occurrences of (CALL) with CALL, or redefine the word].

The main body of the FKEY will first look whether it has been called from a bona fide application or whether the topmost window is a dialog or desk accessory. In the latter two cases, the FKEY will do nothing but beep and return. Since the FKEY itself might display a dialog (for editing the text strings), it should not be allowed to redisplay its own dialog when it is already active. Checking whether any dialog is already in place is one way of achieving this; you might think up some more sophisticated ways and change the program accordingly.

If the routine has been called from within a good environment, it will wait for the next key pressed. If the key is a number key, the appropriate message will be posted (see later how this is done). If it is the ‘e’ key, a dialog will be displayed for editing the text strings. In all other cases the routine will simply beep and return.

Posting Events

The first problem that we encounter here is how to post key down events that correspond to the text string into the event queue. Very simple, you’ll say, do the following:

: post.char ( char -- ) 3 swap call post.event drop ;
 : post.string ( string -- )
 count 0 DO dup i + c@ post.char LOOP drop ;

where 3 is the event code for a key down event, and the event message simply contains the character code in the low byte, and no key code (=0). Leaving out the actual key code has so far caused no problem in any case that I tested.

Well, the simple example works. In a way. If the string that is posted is longer than 15 characters, Mach2 will simply beep because it cannot accept more keydown events before switching tasks. This doesn’t have anything to do with the actual length of the event queue or the maximum number of allowed events. It is the application that can’t deal with so many ‘keystrokes’ coming in rapid succession. In addition, of course, if we don’t check the event queue before posting an event, we take the risk of losing it if the maximum number of allowed events (20 by default) has been reached.

This last number can be changed by editing the boot blocks. However, one can think of a more elegant solution that makes the whole process completely independent of the maximum length of the event queue. We allow the posting of a character only if the GetNextEvent routine fetches a null event. In that case we can be sure that not too much activity is going on and the key down event will be handled correctly.

But how do we handle this process? We cannot do some sort of waiting loop within the FKEY, since GetNextEvent will only be called by the application after we have returned. Therefore the FKEY must install a short background routine that monitors the activity of GetNextEvent and posts key down events from the string to be transmitted each time a null event is received. Here the JGNEFilter system global, already used for several examples in MacTutor (V1#9, Bob Denny, and V2#6, JL), comes in very handy. To post a message into the event queue, the post.string word as defined in the listing saves the string and its length away into a defined place and then changes the JGNEFilter vector to point to a custom routine that will post the keystrokes.

The custom routine, GNE.glue, calls GNEIntfc through our standard glue code, which you really know by now. GNEIntfc looks at A1 (which points to the event record), and if a null event is about to be transmitted, it will take the next character from the saved message string and post a key down event under the following conditions:

1. A certain delay has expired since the last character was posted (2 ticks in my example) and

2. The number of pending events is less than a predefined number (here 10).

When the end of the string has been reached, the filter routine resets the JGNEFilter vector to its old value.

Using the method just described, one can transmit strings of arbitrary length to applications. Which is what we wanted.

Editing the text strings

If an ‘e’ is pressed after the FKEY, we’ll display the editing dialog. The Rmaker source for this dialog (ID=2000 for DLOG and DITL, you may want to change this) is in listing 2. It simply consists of 10 editable text items, one OK button and some static text.

The associated Forth word, edit.messages, does a number of things. It first tries to open a resource file named ‘FKEY.messages’ and creates a new one if it doesn’t succeed. By standard, this will be kept in the system folder; leave it there. You can prepare any number of files containing standard messages by renaming them.

The routine then gets the dialog with ID 2000 (it is a shame that FKEYs cannot ‘own’ resources like DRVRs etc. can). If the dialog can’t be found, it beeps and returns; otherwise, it displays the strings from the FKEY.messages file in the boxes for the editable text items. They are 10 individual string-format resources type ‘bplt” with ID=3 to 12 (corresponding to the dialog items 3 to 12). If the resources cannot be found (i.e. the file has just been created and is empty), they are created and initialized with whatever was in the EditText items of the dialog box. In my case, I used the texts ‘Message x’, but you might just leave the strings empty. If the bplt resources are there, they replace the EditText items.

A ModalDialog is then called, allowing the strings to be edited. The only enabled item is the OK button, which returns to the Forth routine. Then, the changed text strings are written back to the bplt resources in the FKEY.messages file, the resource file updated and the dialog disposed of.

Finally, post.message is the routine that is called when a number key is pushed after the FKEY. It gets the bplt resource corresponding to that number and calls post.string (described above) to transmit the string via the GetNextEvent filter routine.

make.fkey creates a file ‘fkey.text’ that contains the FKEY resource and has the correct type and creator to be opened from the FKEY installer (from Quick and Dirty Utilities, Dreams of the Phoenix, Inc., P.O.Box 10273, Jacksonville FL 32247, (904) 396-6952). This file is then packed together with the dialog resources into one file. The FKEY may be installed with the installer; the DLOG 2000 and DITL 2000 must be copied with ResEdit.

Some last notes

As you’ve seen, yet another Mach2 version has been released, v2.12, making v2.11 obsolete only two weeks after I received it. No BIG modifications, only minor ones.

I received some comments from a reader, James Merkel, who mentioned that it would be a good idea for Palo Alto Shipping to release the source for the multitasking kernel as well, now that we have the source of the I/O task. The second comment was to release bug fixes in MacTutor as well as on GEnie, for those not having access to the GEnie Roundtable (including myself). Very good suggestion. PAS, do you listen?

Last, the bulletin board that I mentioned, Calvacom, is now accessible via Tymnet from the US. If you’d like to see what’s going on over here or want to leave me some mail, connect yourself to a Tymnet line and type ‘CalvaCom’ at the login prompt, then ‘nouveau’ when it prompts you for your access code. You can subscribe with your credit card, as usual. Speaking some French helps, of course, but most anybody on the board will understand English. Connect charges (overseas rates included) are of the order of $25 per hour. I’d like to see your feedback in my mailbox!

Listing 1: Mach2 FKEY for text glossary
( *** Function Key example. JL June 1987 *** )

4ascii QD15 CONSTANT “qd15
4ascii bplt CONSTANT “bplt
4ascii DITL CONSTANT “ditl
4ascii DLOG CONSTANT “dlog

2 CONSTANT post.delay
 ( 2 ticks wait between posting of characters )
10 CONSTANT max.event  
 ( max # of pending events allowed during posting )
BINARY 0000000000001000 CONSTANT KeyEvent
 ( header code filled at end of definitions )
header start
 JMP start  ( to be filled later )
header temprect 8 allot
header itemrect 8 allot
header myEventRec 16 allot

: beep 5 (call) sysbeep ;

CODE cmove ( redefine since this is part of Kernel )
 MOVE.L (A6)+,D0
 MOVE.L (A6)+,A1
 MOVE.L (A6)+,A0
 TST.L  D0
 BLE.S  @2
@1 MOVE.B (A0)+,(A1)+
 SUBQ.L #1,D0
 BNE.S  @1
@2 RTS

: / w/ ;

: getFkeyDlg 
 2000 0 -1 (call) GetNewDialog 

: #events EvQHdr QTail + @ EvQHdr QHead + @ - 22 / ;

: post.char ( char -- ) 3 swap (call) postEvent drop

header SavedJGNEFilter 4 allot
header SavedString 256 allot
header bytesToTransfer 4 allot
header lastpost 4 allot

: GNEIntfc { | btt -- }
    getA1 w@ 0= IF
 [‘] bytesToTransfer @ -> btt
 btt IF  (call) tickcount [‘] lastpost @ - post.delay > 
 #events < AND 
 [‘] SavedString dup c@ btt - 1+
 + c@ post.char
 btt 1- [‘] bytesToTransfer !
 (call) tickcount [‘] lastpost !
 [‘] savedJGNEFilter @ JGNEFilter !
 LINK A6,#-256 ( 256 bytes of local Forth stack )
 MOVEM.L A0-A5/D0-D7,-(A7)( save registers )
 ( no need for loop return stack )
 ( no parameters are passed )
 JSR GNEintfc  ( call Forth routine )
 MOVEM.L (A7)+,A0-A5/D0-D7( restore registers )
 LEA  SavedJGNEFilter,A0
 MOVE.L (A0),A0  ( return address )
 JMP  (A0)

: post.string { string | length -- }
 string c@ -> length
 string [‘] SavedString length 1+ cmove
 length [‘] bytesToTransfer !
 (call) tickcount [‘] lastpost !
 JGNEFilter @ [‘] SavedJGNEFilter !
 [‘] GNE.glue JGNEFilter !

: post.message { msg# | dh dPtr tPtr -- }
 “ FKEY.messages” (call) OpenResFile (call) UseResFile
 “bplt msg# 3 + (call) getResource -> dh
 dh IF dh @ post.string

: edit.messages 
 { | dPtr itemType item box box1 itemHit thandle refnum -- }
 “ FKEY.messages” dup (call) OpenResFile
 (call) ResError 
 IF drop dup (call) CreateResFile
 (call) OpenResFile dup -> refNum 
 (call) UseResFile 
 ELSE dup -> refNum 
 (call) UseResFile drop 
 getFkeyDlg -> dPtr
 dPtr IF
 13 3 DO 
 dPtr i ^ itemType ^ item ^ box
 (call) GetDItem
 item (call) HLock drop
 “bplt i (call) GetResource -> thandle
 thandle IF 
 thandle (call) HLock drop
 item thandle @ (call) SetIText 
 thandle (call) HUnlock drop 
 256 (call) NewHandle drop
 “bplt i “ Message” (call) AddResource
 item (call) HUnlock drop
 LOOP ( all messages have been initialized )

 0 ^ itemHit (call) ModalDialog

 13 3 DO 
 dPtr i ^ itemType ^ item ^ box
 (call) GetDItem
 item (call) HLock drop
 “bplt i (call) GetResource -> thandle
 thandle IF 
 thandle (call) HLock drop
 item thandle @ (call) GetIText
 thandle (call) ChangedResource 
 thandle (call) HUnlock drop THEN
 item (call) HUnlock drop
 LOOP ( all messages have been updated )
 refNum (call) UpdateResFile
 dPtr (call) DisposDialog

: fkey { | keycode -- }
 (call) frontwindow windowkind + w@ l_ext dup
 2 = swap 0< OR 0= IF 
 KeyEvent [‘] myEventRec (call) GetNextEvent UNTIL

 [‘] myEventRec message + @ $FF and -> keycode
 keycode ascii e = 
 IF edit.messages 
 keycode ascii 0 < keycode ascii 9 > OR
 IF beep ELSE keycode 48 - post.message
 ELSE beep 

( *** our standard glue routine *** )

CODE fkey.glue
 LINK A6,#-2048  ( 2K 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  ( starting 256 bytes below locals )
 ( no parameters are passed to the FKEY )
 JSR fkey ( call Forth routine )

 MOVEM.L (A7)+,A0-A5/D0-D7( restore registers )
 MOVE.L (A7)+,A0 ( return address )
 JMP  (A0)

header end

( install initial jump vector )
‘ fkey.glue ‘ start 2+ - ‘ start 2+ w!

( *** installation *** )

: make.fkey { | refNum namePtr -- }
 “ fkey.text” dup $create-res
 abort” You have to delete the old ‘fkey.text’ file first.”
 $open-res dup -> refNum call UseResFile 
[‘] start [‘] end over - call PtrToHand drop ( result code )
 “fkey 5 “ Mach2 FKEY” call AddResource
 refNum $close-res drop ( result code )
 0 “ fkey.text” 
 getvol ioVRefNum + w@ l_ext
 getfileinfo drop
 “qd15 “fkey “ fkey.text” setfileinfo
Listing 2: Rmaker file for the FKEY
* File fkr.R
Mach2 Fkey

Include Fkey.Text

New Dialog
30 14 330 494
visible goAway

Type DITL   

256 32 278 91

256 136 286 463  
Text FKEY © 1987 J. Langowski/MacTutor Written in Mach2™ Forth

EditText Disabled
8 32 24 464
Message 0

EditText Disabled
32 32 48 464
Message 1

EditText Disabled
56 32 72 464
Message 2

EditText Disabled
80 32 96 464
Message 3

EditText Disabled
104 32 120 464
Message 4

EditText Disabled
128 32 144 464
Message 5

EditText Disabled
152 32 168 464
Message 6

EditText Disabled
176 32 192 464
Message 7

EditText Disabled
200 32 216 464
Message 8

EditText Disabled
224 32 240 464
Message 9
8 8 24 28

32 8 48 28

56 8 72 28

80 8 96 28

104 8 120 28

128 8 144 28

152 8 168 28

176 8 192 28

200 8 216 28

224 8 240 28

Community Search:
MacTech Search:

Software Updates via MacUpdate

Live Home 3D Pro 3.6.2 - $49.99
Live Home 3D Pro is powerful yet intuitive home design software that lets you build the house of your dreams right on your Mac, iPhone or iPad. It has every feature of Live Home 3D, plus some... Read more
RapidWeaver 8.2 - Create template-based...
RapidWeaver is a next-generation Web design application to help you easily create professional-looking Web sites in minutes. No knowledge of complex code is required, RapidWeaver will take care of... Read more
Opera 60.0.3255.109 - High-performance W...
Opera is a fast and secure browser trusted by millions of users. With the intuitive interface, Speed Dial and visual bookmarks for organizing favorite sites, news feature with fresh, relevant content... Read more
DEVONthink Pro 3.0beta2 - Knowledge base...
DEVONthink Pro is your essential assistant for today's world, where almost everything is digital. From shopping receipts to important research papers, your life often fills your hard drive in the... Read more
Tunnelblick 3.7.9 - GUI for OpenVPN.
Tunnelblick is a free, open source graphic user interface for OpenVPN on OS X. It provides easy control of OpenVPN client and/or server connections. It comes as a ready-to-use application with all... Read more
Carbon Copy Cloner 5.1.9 - Easy-to-use b...
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
Dropbox 73.4.118 - Cloud backup and sync...
Dropbox is an application that creates a special Finder folder that automatically syncs online and between your computers. It allows you to both backup files and keeps them up-to-date between systems... Read more
Postbox 6.1.18 - Powerful and flexible e...
Postbox is a new email application that helps you organize your work life and get stuff done. It has all the elegance and simplicity of Apple Mail, but with more power and flexibility to manage even... Read more
Wireshark 3.0.2 - Network protocol analy...
Wireshark is one of the world's foremost network protocol analyzers, and is the standard in many parts of the industry. It is the continuation of a project that started in 1998. Hundreds of... Read more
BetterTouchTool 2.856 - Customize multi-...
BetterTouchTool adds many new, fully customizable gestures to the Magic Mouse, Multi-Touch MacBook trackpad, and Magic Trackpad. These gestures are customizable: Magic Mouse: Pinch in / out (zoom... Read more

AFK Arena guide - Everything you need to...
Ok, so if you're like me, you've been playing (and sometimes waiting) your way through AFK Arena, only to learn there's a lot more to it than there appears on the surface. There's guilds, a PvP arena, and all sorts of other systems and game modes... | Read more »
Explore an epic fantasy world in MMORPG...
Webzen have just announced the official launch date for its stunning MMORPG ‘MU Origin 2’ which will arrive for iOS and Android on May 28th. It will be the second spinoff from the classic PC-based MU Online, and it looks to further refine the... | Read more »
Solar Explorer: New Dawn guide - Tips an...
Solar Explorer: New Dawn is a lunar lander game that really ratchets the intensity up to 11. With all of the asteroids flying around as you fly around at seemingly breakneck speeds, it can be easy to feel overwhelmed bythe whole thing. | Read more »
The Dalaran Heist - How Hearthstone...
I am someone who wrote Hearthstone off a while ago. It was hard not to try and stick with it. The game has incredible production values and a core of really great talent working on the game continuously to keep it feeling fresh and fun (full... | Read more »
Steam Link App - Everything You Need to...
Steam Link has finally released for iOS! That’s right, you can play your epic backlog of PC games on the go now. Well… sort of. While the Steam Link app was announced seemingly ages ago, it only got actual approval for release last night. Check out... | Read more »
Pre-register now for endless superhero r...
Talking Tom Hero Dash is set to take the ever-popular Talking Tom and Friends franchise in a brand new direction as it opens pre-registration to players worldwide. Not only does it promise to be a beautifully rendered, fast-paced, action-packed... | Read more »
AFK Arena - Guild Wars guide
Ok, so if you're like me, you've been playing (and sometimes waiting) your way through AFK Arena, only to learn there's a lot more to it than there appears on the surface. There's guilds, a PvP arena, and all sorts of other systems and game modes... | Read more »
Superhero-themed Talking Tom Hero Dash i...
One of the exciting releases that we’re looking forward to is Talking Tom Hero Dash, an upcoming superhero-themed runner created by Outfit7. This new game is an action-packed endless runner that takes you on an epic adventure to assemble the... | Read more »
Kingdom Rush Vengeance Update Guide 2 -...
Kingdom Rush: Vengeance just got updated once again to add more content to the game. This addition, called The Frozen Nightmare, adds three new levels, five new enemies, two new heroes, and some new achievements. | Read more »
Save the world with SCIENCE in the upcom...
Previous versions of space colonization game TerraGenesis encouraged you to explore the galaxy and settle its planets. The eagerly-awaited 5.0 update will try to smash them to bits. Yep, with a new "world killers" setting, you can unleash... | Read more »

Price Scanner via

12″ 1.2GHz MacBooks on sale for $999, $300 of...
Amazon has current-generation 12″ 1.2GHz Retina MacBooks on sale for $300 off Apple’s MSRP. Shipping is free: 12″ 1.2GHz Space Gray MacBook: $999.99 $300 off MSRP 12″ 1.2GHz Silver MacBook: $999.99 $... Read more
Here’s how to save $200 on Apple’s new 8-Core...
Apple has released details of their Education discount associated with the new 2019 15″ 6-Core and 8-Core MacBook Pros. Take $200 off the price of the new 8-Core model (now $2599) and $150 off the 15... Read more
Price drops! 2018 15″ 2.2GHz 6-Core MacBook P...
Amazon has dropped prices on clearance 2018 15″ 2.2GHz 6-Core Touch Bar MacBook Pros by $300 with models now available for $2099. These are the same models sold by Apple in their retail and online... Read more
Apple drops prices on 2018 13″ 2.3GHz Quad-Co...
Apple has dropped prices on Certified Refurbished 2018 13″ 2.3GHz 4-Core Touch Bar MacBook Pros with prices now starting at $1489. Apple’s one-year warranty is included, shipping is free, and each... Read more
Apple drops prices on 2018 Certified Refurbis...
Apple has dropped prices on clearance 2018 15″ 6-Core Touch Bar MacBook Pro, Certified Refurbished, with models available starting at only $1999. Each model features a new outer case, shipping is... Read more
Price drops! Clearance 2018 13″ Quad Core Mac...
Amazon has dropped prices on 2018 13″ Apple Quad-Core MacBook Pros with models now available for $250 off original MSRP. Shipping is free. Select Amazon as the seller, rather than a third-party, to... Read more
How Much Is ‘Solace’ Of Mind Worth When Buyin...
COMMENTARY: 05.22.19- Smartphone cases give us peace of mind by providing ample protection for such a fragile gadget and the sky’s the limit as far as choices go with a plethora of brands, styles,... Read more
Get a 13″ Touch Bar MacBook Pro for the lowes...
Apple has Certified Refurbished 2017 13″ 3.1GHz Dual-Core i5 Touch Bar MacBook Pros available starting at $1439, ranging up to $390 off original MSRP. Each MacBook features a new outer case, shipping... Read more
Apple adds new 15″ 8-Core MacBook Pro to line...
Apple has added a new 15″ MacBook Pro to its lineup featuring a 9th generation 2.3GHz 8-Core Intel i9 processor, 16GB of RAM, a 512GB SSD, and a Radeon Pro 560X with 4GB of GDDR5 memory for $2799.... Read more
21″ 2.3GHz iMac available for $999 at B&H...
B&H Photo has the 2018 21″ 2.3GHz Apple iMac on sale for $100 off MSRP. This is the same model offering by Apple in their retail and online stores. Shipping is free: – 21″ 2.3GHz iMac (MMQA2LL/A... Read more

Jobs Board

Best Buy *Apple* Computing Master - Best Bu...
**690427BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Sales **Location Number:** 000860-Charlottesville-Store **Job Description:** **What Read more
*Apple* Mobile Master - Best Buy (United Sta...
**696430BR** **Job Title:** Apple Mobile Master **Job Category:** Store Associates **Location Number:** 001012-Bismarck-Store **Job Description:** **What does a Best Read more
Manager - *Apple* Team - SHI International...
…opportunity available in the Hardware & Advanced Solutions Department as the Manager of the Apple Team The Manager must be familiar with all aspects of Apple Read more
Best Buy *Apple* Computing Master - Best Bu...
**696375BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Sales **Location Number:** 000203-North Austin-Store **Job Description:** **What does a Read more
Geek Squad *Apple* Master Consultation Agen...
**696286BR** **Job Title:** Geek Squad Apple Master Consultation Agent **Job Category:** Services/Installation/Repair **Location Number:** 000172-Rivergate-Store Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.