Fabien Samuel is a mathematics teacher in Paris, as well as a convinced Macintosh adept and Programmer.

Getting Info

This article is meant to give a comprehensive overview about the various resources, structures and procedures involved in keyboard events, and especially about the relation between Keycodes and Ascii Codes. There has already been a couple of very good articles on that subject in MacTutor, and I must thank Joel West and Jörg Langowski for the help I found in these as a starting point. The present article tries to update and complete the information with respect to the new resources in System 4.0 or later.

As an example, I have included the KeyEdDemo application, which allows you to remap your keyboard according to specific needs and save that configuration both in RAM, for immediate access, and in your system file, so as to keep the changes after reboot. This is a very simplified version of my shareware application KeyEd 0.5, that features a fully functional file menu, multiple scrolling windows, extensive font and view options, and advanced error checking. The main purpose of this demo version is to show how the resources described below can be used.

The information presented here has been obtained by various means. Lacking documentation about the new resources introduced with system 4.0, the most valuable help was found in MacNosy. I had quite the feeling of being a detective, looking through the nosied code of INIT 0 and _KeyTrans to deduce the structure of KCHR resources.

When I finally got Inside Mac Vol V, I was able to confirm some of my discoveries and find some more information, although the information presented there is not always very reliable.

Transitions and Codes

The keyboard contains its own micro-processor, which returns to the Mac OS Transitions Codes, also known as Raw Key Codes, every time the user types a key. Those Raw Key Codes are then translated in Virtual Key Codes, involving the use of a translation table contained in KMAP resources. The details of this translation are beyond the scope of this article, and in everything that follows we will call Key Codes the virtual key codes that were so obtained.

Key Codes can take any value between 0 and 127, not all values being actually used (at least until they release a super-extended keyboard with 128 keys!). A 16 bytes long variable, found in the low-memory global KeyMap ($174), tells which keys are down at any given time: each set bit indicating that the corresponding key is down. At least 2 normal keys can be thus indicated, along with any combination of the modifiers keys (Shift, option, etc...).

Figure 1: Relation between KeyMap and Key Codes. KeyCaps from the Extended US ADB Keyboard have been shown along with the hex key codes , and the bit offset information .

The contents of this variable can also be obtained through the Pascal procedure GetKeys (TheKeys: KeyMap). A few important notes must be made here. First of all, although the standard interface for Type KeyMap is Packed Array [0..127] of Boolean, a limitation of the LightSpeed Pascal compiler redefines it as Array [0..3] of LongInt. The underlying structure remains the same, but it cannot be accessed in the same manner. Second, as shown in Figure 1, KeyCodes do not directly correspond to a bit offset in the KeyMap variable, the order of bits being reversed in each byte. This can be very convenient at the assembly language level, where you just need to shift the KeyCode by 3 bits to get the byte offset, the remainder being the bit offset within that byte that can be used along with instructions like BTST.

Things get more complicated in Pascal if one wants to use the bit-wise ToolBox utilities, as bits are computed in the reverse order (Higher to Lower bits, Lower to Higher Bytes) than they are in the corresponding assembly instructions. However the following code shows a way to access a KeyMap that will work with any compiler:

According to the countries and Mac models, the relation between physical keys and their key codes can vary greatly. This can be due to distinct physical mappings, for instance the return key or the cursor keys can be found at different locations from one keyboard to another. To make things even simpler, keys having the same function can have different key codes, or, better still, keys having the same keycodes can have different meanings! We will try to summarize these exceptions in a moment.

There currently are 6 different Apple keyboards, each one having its own keyboard type (Found in low-memory global KybdType = $21E - Byte value). However the keyboard types for the US classic and Euro classic keyboards are both equal to 3, despite their important differences: a way to distinguish between them is shown in the demo program (Function GetKbd) . A display map of these keyboards can be found in KCAP resources, contained in the system file Key Layout, that we will discuss later.

In chronological order, the Mac Classic (KybdType = 3) keyboards exist in US Version (KCAP ID = 3) and International Version (KCAP ID = 259). For archaeologists that might be interested, those are the keyboards that were released with the antiques 128 and 512 Macs. Then came the Mac Plus keyboard (KybdType = KCAP ID = 11), and the 3 ADB Keyboards released with the SE and Mac II: Standard (ID = 1), Extended (ID = 2) and ISO (ID = 4), this last one satisfying with the international ISO specifications, unlike the Standard ADB Keyboard.You can find representations of all those keyboards in Figures 2 to 7, along with the corresponding key codes.

Figure 2.

Figure 3

Figure 4.

Figure 5.

Figure 6.

Figure 7

We can now see better what are the main differences between keyboards:

1. Return and \: On the US Classic Keyboard the keycode for Return is $24, whereas on the Euro Classic it is $2A (which maps to the \ character on the US Classic). In all other keyboards, the keycode for Return is still $24, and in all cases the ascii code is and should be $0D.

2. Enter and Space: again the corresponding keycodes ($34 for Enter and $31 for Space on the MacClassic) have been inverted on the EuroClassic keyboard. On all subsequent keyboards, the Enter key has been moved to the numeric keypad, with keycode $4C, the Space key keeping its $31 keycode.

3. Cursor Keys: originally, those keys were only available on the optional numeric keypad, where they also served as operator keys when shifted. With the introduction of the Mac Plus built-in numeric keypad, the cursor keys were moved to the main keyboard, while the numeric operator keys stayed where they belonged on the keypad. The only problem is that they kept the same keycodes! To solve this conflict, when you type one of the numeric operator keys on the Plus, it acts as if you had held the shift key down (and likewise, holding down the shift key while typing one of the cursor keys will return the corresponding numeric operator). On subsequent models, this conflict was resolved by giving altogether different keycodes to both the numeric operator and cursor keys: this means 8 new key codes have been introduced for that purpose. The situation is summarized in Figure 8. Also note that the + and - keys on the keypad have been inverted between the ADB extended and standard keyboards.

The main conclusion of all this is that you should only rely on the ascii code of such control characters, which always keeps the same value whatever keyboard you use.

Figure 8.

Keyboard Events

For most purposes, dealing with keyboard input mainly involves polling KeyDown and AutoKey events. Information about such an event is given in the Message and Modifiers fields of the EventRecord returned by GetNextEvent. The Message field has the following 4 bytes long structure:

<Reserved, ADBAddress, keycode, ascii code>

ADBAddress is used with the Mac SE and II, and contains a reference number of the keyboard the typing came from, useful if various keyboards are simultaneously connected (see January 88 MacTutor for an example of this). Ascii code is obtained through the conversion routines that are discussed in the next paragraphs, taking into account both the key code and the state of modifiers keys.

The Modifiers field of the EventRecord is made up of 2 bytes, the high byte giving the state of the modifiers keys in the following bit-arrangement:

<x,y,z,control,option,caps lock,shift,command>

Flags x,y and z are normally zero. However, the extended ADB keyboard can be reconfigured so as to distinguish between the left and right Shift,Option and Control Keys. In that case, the right keys will generate new key codes, and flags x,y,z could be renamed: R.Control,R.Option,R.Shift. This possibility is supported in order to use the Mac with an operating system Inside Mac doesnt dare to mention, so neither will I! It can be implemented through the use of the ADB operators mechanism, which might be the subject of another article. Anyway, this capacity is strongly discouraged because it doesnt comply with the User Interface.

Finally, lets note that some keys do not immediately return an event: those are the keys that are used in conjunction with another key to produce exotic objects like accented characters. I will refer to them as Double Strike Keys, also the official terminology appears to be Dead Keys, but I just dont like the idea of my keys being dead!

Figure 9.

In the beginning, there was INIT 0 and 1...

On the first Macs, and until the Mac Plus with systems 3.x, all the information related to converting key codes to ascii codes was contained in system resources INIT 0 and 1. The Localizer was in charge of adapting these resources according to the various countries. Those resources contained both the conversion code and the associated translation tables.

With systems 4.x and later, The INITs now mainly contain code, the translation tables being now separate and contained in the KCHR 0 system resource. At boot time, the INITs are loaded into the system heap and jumped to. They are mainly in charge of installing pointers to the conversions routines in low-memory globals Key1Trans and Key2Trans.

The reason for there being two separate routines is due to the fact that originally, the numeric keypad was optional. Key1Trans will thus deal with keycodes from 0 to 63, while Key2Trans treats keycodes from 64 to 127, that used to be found exclusively on the numeric keypad. This distinction now appears completely artificial (if not intelligent...) since the Mac Plus was introduced. It seems that those routines have only stayed for compatibility reasons, as their codes are now almost the same, and both refer to the new _KeyTrans ToolBox trap, which does most of the work.

The Inner Workings

To start with, I will describe the main steps involved in INIT 0, INIT 1 having a similar functionality. As any INIT resource, it gets executed at boot time after being loaded as a locked relocatable block, accessed through a handle. Its made up of two essential routines that Ill call SetUp and Key1TransMain. SetUp is the part that gets jumped to at boot time and does the following :

1. Load KCHR 0 into the system heap, if its not already there.

2. Create a non-relocatable copy of KCHR 0 in system heap and store a pointer to it at offset 14 in a parameter block that is accessed through the pointer maintained in BasicGlob (= $2B6) low-memory global. Actually, this copy is expanded by at least 512 bytes, probably in order to allow its modification by another program.

3. Copy Byte 6 from the itlc 0 in a Data zone internal to INIT 0. This is an international utilities resource, and the value of this byte will be used to distinguish between the US Classic and Euro Classic keyboards, as illustrated in the GetKbd function of the demo program. This actually must mean that running with an Euro Classic keyboard and a US system would make believe the keyboard was US [This is true, recalling all the mixups we had using different systems - JL]: there doesnt seem to be a hardware method to distinguish between the two keyboards.

4. Put the entry point to Key1TransMain in low-memory global Key1Trans.

5. Cut down the size of its own handle before returning, the SetUp routine being now useless (this is accomplished by putting those last instructions at the beginning of the block, unless one wants to call this the Auto-Destroy routine!).

Key1Trans

Key1transMain is the part currently used every time a keydown or keyup event is detected by the Event Manager. This is a register-based routine, and calling it from an high level language involves assembler glue-code (see the Demo Program). It takes on entry:

D2 contains the keycode (less than 64, or nothing will happen: in that case one must call Key2Trans)

D1 contains the state of the modifiers keys (as it appears in the third word of the KeyMap structure: this differs from the EventRecord Modifiers field).

D3 should be 0 for most purposes: bit 7 can be set to indicate that the event should be treated as a key-up event rather than a key-down event.

On exit, D0 contains the resulting ascii code.

This routine works as follows:

1. Make up a word that has the following structure:

- the high byte contains the modifier flags as they would appear in the EventRecord modifiers field:

<x,y,z,ctl,opt,caps,shift,cmd>

Note that the command key state is read directly on the keyboard when the routine is executed, and so doesnt depend on the one you pass in D1.

where KeyCode is the word obtained in step 1, TransData a pointer to the copy of KCHR 0 accessed through BasicGlob as described above, and State an offset used for double strike keys that is maintained at offset 10 in the parameter block pointed to by BasicGlob. We will see how this works in just a moment .

The function result contains in its Low Word the ascii code of the current key, taking into account its possible combination with a previous double strike key. The High Word returns the ascii code for an eventually waiting double strike if it couldnt be combined with the current key.

3. In case the High Word is non-zero, Key1Trans will post an event for it, thus causing the default ascii value of the previous double strike to be reported before that of the current key.

4. In any case, the ascii code for the current key and modifiers is returned in D0.

KeyTrans and KCHR 0

What finally remains to complete this overview is to understand how the KeyTrans function is working. In order to do that, we first need to know the structure of the KCHR 0 resource, which will incidentally give us the means to modify it.

As I said, KCHR 0 is the fundamental resource that allows to translate a keycode, along with the associated modifiers, to a standard ascii code.

1. The first word of a KCHR resource presently contains zero, and doesnt seem to be currently used.

2. The next 256 bytes serve as a kind of offset table, each one containing a block number used as follows: the high byte of the Event Record modifiers field can theoretically take any value between 0 and 255, assuming the right modifiers keys are activated. This value serves as an offset into the table to get the corresponding block number. Each block is 128 bytes long, and contains the mapping for every key code when typed along with the above modifiers.

3. The following word contains the actual number of blocks that are used (currently 8, numbered from 0 to 7). This means different modifiers combinations can lead to the same block.

4. Then come the block themselves, each of its 128 bytes giving the ascii code for the corresponding key code, which serves as an offset into the block. If the ascii code is zero, it means its either a double strike key, a modifier key, or no key at all.

5. Finally, we find a variable length part that deals with double strikes.

a) The first word contains the total number of double strike keys.

b) For each one of them, we find a structure organized as follows:

b1) 2 bytes, giving the block number and key code of that double strike.

b2) Word giving the total number of associated variants.

b3) List of all those variants in the form: Current Ascii Code / Resulting Ascii Code

b4) Word giving the default ascii value of that double strike, in case the current ascii code wouldnt combine with it to produce a resulting ascii code.

Lets give an example to try and make things a bit clearer: on the US keyboard, Option E followed by E results in the accented Character é, but if followed by P it will result in the two consecutive characters ´p. The keycode for E is $E, while the option key gives a value of 8 to the modifiers flags high byte. Counting from zero, byte number 8 in the block numbers table has a value of 3, which leads us to block number 3. Looking at byte number $E in that block, we see that its value is zero! This confirms us in thinking that Option E is a double strike. Now, lets look at the list of double strike keys: the first of them is precisely the one we want: Block Number = 3, KeyCode = $E. The next word tells us 7 variants are associated with it, and among them we find the variant $65,$8F: ascii code $65 (Character e) thus combines with our double strike to produce ascii code $8F (Character é). On the other hand, no variant is associated with ascii code $70 (Character p), and it will thus be the default value $60 (´ accent) that will be returned, followed by the character p.

We finally can explain how the KeyTrans function does its trick. The Modifiers byte is used as an offset into the block numbers table, while the keycode byte serves as an offset into the designated block. If the ascii code it finds at the designated position is non-zero, KeyTrans just returns with it. If it is zero, KeyTrans looks into the double-strike table and tries to match the BlockNumber/Keycode combination with one in the list. If it succeeds, the State variable is loaded with the byte offset between the start of the first block and the location of the number of variants entry associated with that double strike. In all other cases, State will be cleared. When KeyTrans is called again, and State is non-zero, it assumes theres a pending double strike and, after getting the current ascii code, it will look right away at the designated offset to find a match between the current ascii code and an eventual resulting ascii code. If it finds one, it returns with the resulting ascii code. Otherwise it returns with the current ascii code in its low word, and the default ascii code of the pending double strike in its high word. In the last case, and if it has been called by Key1Trans, Key1Trans will post the appropriate event as described above. We can thus see how important it is to maintain the value of State between calls to KeyTrans if we want to get double strikes responses.

As a final point, note that KeyTrans actually does some pre-processing related to the Script Manager.

The Demo Program

The following LightSpeed Pascal program tries to give a simple example of how all this stuff can be put to use. It needs system 4.0 or later to run. It only allows editing of normal keys, and I left out all memory and resources error checking in order to keep it as short as possible. Note that the Shareware version KeyEd 0.5 does implement advanced error-checking features. Ill leave it as an exercise to the reader to check for Nil Handles and call MemError or ResError when appropriate. However, I couldnt resist showing how the KCAPs resources mentioned above can be used in giving a graphical interface to keyboard editing, and that accounts for a large part of the program code. So I first have to say a word about their structure (obtained once again by nosying the KeyCaps DA):

1. Window Rectangle

2. KeyCaps DA TextEdit view rectangle

3. Number of different key shapes

4. For each shape:

a) Number of points used to define it, minus 1.

b) List of those points.

c) Number of associated keys, minus 1.

d) List of those keys in the form:

<KeyCode,Vertical Offset, Horizontal Offset>.

The points define a region made up of rectangles, that will then be offset to the adequate position for each consecutive key. Note that the keycode field actually contains additional information, so I take it modulo 128. The procedure MainCaps that runs through this structure shows you type-casting in Pascal can do wonders, but would evidently be more elegant in assembly! The only thing I wasnt able to do with type-casting was to access a byte at a time in memory, so I wrote the short assembly routines Peek and Poke for that purpose, the names being a tribute to Basic programmers.

The program also shows an example of using procedural parameters, a most convenient feature of the LSP compiler. This way the region obtained in MainCaps can be used either for drawing the key or for dealing with a click inside it, or for any other purpose you might want. However, if you want to port that program to another compiler, youll need to implement a Case statement within MainCaps to achieve the same result.

Finally, the program also shows the use of a modeless dialog with an User Item. The user procedure UserDraw is attached to that item with the SetUserProc procedure. The Dialog Manager will call it automatically on each update event for the dialog window, and it is in charge of drawing the keyboard. Likewise, if there was a click in that User Item rectangle, we call MainCaps to find if it was in a key, and handle the event accordingly in the ActiveClick procedure. Note that although the Dialog Manager deals with mouse-down events when the Dialog Window is active, you still have to explicitly activate it by calling Select Window when the Event Manager reports a click in the contents region. You also have to pre-process keydown events, to filter out command key equivalents and any other typing you dont want passed to the edit field. One important warning if you use LightsBug while running this program is that if you inadvertently click in your switched-out Dialog Window, LSP 1.11 will bomb after displaying the usual You can only drag your programs windows while it is halted message. This could be due to the fact that LSP gets notified of the event only after the Dialog Manager has tried to run your User Proc, which will rely on globals that have become invalid since your program is switched out. Anyway, I nearly got my hard-disk trashed while trying to figure out the problem!

Note that the RMaker source file for the program doesnt include definitions for the KCAP resources used by the program. So after compiling this file with RMaker, you should use ResEdit to copy these resources from the Key Layout file in your system folder and paste them into your resource file. While youre at it, you could also install BNDL or SIZE resources to make the program look more fancy. It should run at ease under a 50K partition. There are many more possible improvements, but Ill leave them to your imagination.

Software Updates via MacUpdate

EtreCheck 3.1.5 - For troubleshooting yo...

EtreCheck is an app that displays the important details of your system configuration and allow you to copy that information to the Clipboard. It is meant to be used with Apple Support Communities to... Read more

WALTR 2 2.0.8 - $39.95

WALTR 2 helps you wirelessly drag-and-drop any music, ringtones, videos, PDF, and ePub files onto your iPhone, iPad, or iPod without iTunes. It is the second major version of Softorino's critically-... Read more

Carbon Copy Cloner 4.1.12 - 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

Dropbox 16.3.27 - Cloud backup and synch...

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 keep them up-to-date between systems... Read more

Microsoft OneNote 15.29 - Free digital n...

OneNote is your very own digital notebook. With OneNote, you can capture that flash of genius, that moment of inspiration, or that list of errands that's too important to forget. Whether you're at... Read more

Spotify 1.0.44.100. - Stream music, crea...

Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more

SpamSieve 2.9.27 - Robust spam filter fo...

SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering.
SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more

VueScan 9.5.62 - 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

Fantastical 2.3.2 - Create calendar even...

Fantastical 2 is the Mac calendar you'll actually enjoy using. Creating an event with Fantastical is quick, easy, and fun:
Open Fantastical with a single click or keystroke
Type in your event... Read more

PCalc 4.4.4 - Full-featured scientific c...

PCalc is a full-featured, scriptable scientific calculator with support for hexadecimal, octal, and binary calculations, as well as an RPN mode, programmable functions, and an extensive set of unit... Read more

Latest Forum Discussions

Galaxy on Fire 3 - Manticore brings the series back for another round of daring space battles. It's familiar territory for folks who are familiar with the franchise. If you've beaten the game and are looking to broaden your horizons, might we... | Read more »

The best apps for your holiday gift exch...

What's that, you say? You still haven't started your holiday shopping? Don't beat yourself up over it -- a lot of people have been putting it off, too. It's become easier and easier to procrastinate gift shopping thanks to a number of apps that... | Read more »

MyTona, based in the chilly Siberian city of Yakutsk, has brought a little festive fun to its hidden object game Seekers Notes: Hidden Mystery. The Christmas update introduces some new inhabitants to players, and with them a chance to win plenty of... | Read more »

PINE GROVE 1.0
Device: iOS Universal
Category: Games
Price: $1.99, Version: 1.0 (iTunes)
Description:
A pine grove where there are no footsteps of people due to continuous missing cases. The case is still unsolved and nothing has... | Read more »

Niantic teases new Pokémon announcement...

After rumors started swirling yesterday, it turns out there is an official Pokémon GO update on its way. We’ll find out what’s in store for us and our growing Pokémon collections tomorrow during the Starbucks event, but Niantic will be revealing... | Read more »

3 reasons why Nicki Minaj: The Empire is...

Nicki Minaj is as business-savvy as she is musically talented and she’s proved that by launching her own game. Designed by Glu, purveyors of other fine celebrity games like cult favorite Kim Kardashian: Hollywood, Nicki Minaj: The Empire launched... | Read more »

Clash of Clans is getting its own animat...

Riding on its unending wave of fame and success, Clash of Clans is getting an animated web series based on its Clash-A-Rama animated shorts.As opposed to the current shorts' 60 second run time, the new and improved Clash-A-Rama will be comprised of... | Read more »

Leaks hint at Pokémon GO and Starbucks C...

Leaked images from a hub for Starbucks employees suggests that a big Pokémon GO event with the coffee giant could begin this very week. The images appeared on Reddit and hint at some exciting new things to come for Niantic's smash hit game.
| Read more »

Price Scanner via MacPrices.net

Never Settle for Low Performing Wifi With iOS...

AppYogi Software has announced the release of WiFi Signal Strength Status App 1.0, the company’s new utility developed exclusively for macOS. WiFi Signal Strength Status App features a unique, single... Read more

DietSensor, Inc., a developer of smart food and nutrition applications designed to fight diabetes and obesity and help improve overall fitness, has announced the launch of its DietSensor app for... Read more

Best Buy has dropped their price on the 64GB Apple TV to $159.99 including free shipping. That’s $40 off MSRP.
32GB Apple TVs are on sale right now for $98 on Sams Club’s online store. That’s $51 off... Read more

12-inch Retina MacBooks, Apple refurbished, n...

Apple has restocked a full line of Certified Refurbished 2016 12″ Retina MacBooks, now available for $200-$260 off MSRP. Refurbished 2015 models are available starting at $929. Apple will include a... Read more

Apple has Certified Refurbished 13″ MacBook Airs available starting at $849. An Apple one-year warranty is included with each MacBook, and shipping is free:
- 13″ 1.6GHz/8GB/128GB MacBook Air: $849 $... Read more

Apple refurbished iMacs available for up to $...

Apple has Certified Refurbished 2015 21″ & 27″ iMacs available for up to $350 off MSRP. Apple’s one-year warranty is standard, and shipping is free. The following models are available:
- 21″ 3.... Read more

MacTech is a registered trademark of Xplain Corporation. Xplain, "The journal of Apple technology", Apple Expo, Explain It, MacDev, MacDev-1, THINK Reference, NetProfessional, Apple Expo, MacTech Central, MacTech Domains, MacNews, MacForge, and the MacTutorMan are trademarks or service marks of Xplain Corporation. Sprocket is a registered trademark of eSprocket Corporation. Other trademarks and copyrights appearing in this printing or software remain the property of their respective holders. Not responsible for typographical errors.

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