Key to QWERTY

Recently on the Twitterwebs, Peter Hosey asked for a library that takes a character and returns the corresponding virtual key code (implicitly, in the U.S. keyboard layout). The intention was to use it to specify default key bindings when binding to physical keys rather than characters.

Now personally, I like to specify my defaults in plists, and if I was hard-coding them I’d use an enum. However, I thought of a mildly amusing implementation, so I wrote it (MIT/X11 license). It turned out to be less interestingly ugly than I expected, but did give me an opportunity to play with __builtin_constant_p(). This means that (if you’re using gcc) KEY_FROM_QWERTY_BODY(ex), where ex is a constant expression, will itself be a constant expression, and if ex is otherwise known at compile time to be constant (e.g. a locally-defined const int, which is not a constant expression in C) it will be constant-folded; in other cases, a function call will be generated.

Also included is code to generate the header, specifically the big ?:-based expression that does the work, using whatever keyboard layout happens to be active. Note, however, that the current implementation only includes keys that generate a single ASCII character, and skips dead keys. It includes capital letters as aliases for their lowercase equivalents, but not other shifted keys.

Conveniently, I’ve also written a library to get a display string for a virtual key code. That one does use the user’s current keyboard layout.

This entry was posted in Code. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *