Friday, October 31, 2014

Chemistry Keyboard - an iOS Keyboard Extension for Chemists


To learn a computer language, you have to write something in that language, just reading the book doesn't help much. So when Swift was introduced at WWDC, I had to assign myself a project to learn the language. As Apple also announced keyboard extensions, and I've long been kicking around the idea of a keyboard specifically made for Chemists—my degree field is Analytical Science, a branch of Chemistry—it seemed like a small enough project to get done in my limited free time.




Not that it was always smooth trekking. I could most certainly have written it faster in Objective-C, the Swift tools took a while to settle down; for a while I was killing the background syntax checking process every few minutes. But,  in many ways, Swift makes life easier; I'm particularly enamored with Swift enumerations, which turned out to be a powerful way to model my keyboard, and make my code extensible to writing different keyboards with just a few changes.

As for writing a Chemistry keyboard, I imagined what it would be like to write inorganic formulae such as:
2•Fe²⁺+2•H₂O→2Fe³⁺+H₂+2•OH⁻
So the first thing was figuring out what characters would be needed. Subscripts and superscripts of the numbers, +, -, (, ), and some arrows. And since I wouldn't want the user to waste time switching between keyboards, the common elements. Since Carbon is so common, along with Oxygen and Hydrogen, they'd get their own keys, but the other elements would have to be packed together in related groups or in one big grid.

So the Halogens, the common ones, would share a key:
Just tap the key and slide right to choose one, or don't slide and get Chlorine.

And as for superscripts and subscripts,
This is a tap and either a drag down for a subscript, or a drag up for a superscript. Very fast. You'll notice that the characters themselves are on a long tab, so as to not be hidden by the tapping finger. The appearance of the keyboard mimics the standard iOS keyboard, supports both regular and dark appearances, and even makes use of the 51 separate keyboard localizations for the word 'space' and the various name for the return key. Everything from 3 different flavors of Portuguese to Cherokee. 

One thing about gestures is that to select a character there does not have to be a one-to-one correspondence between movement and location. You don't have to drag your finger all the way across the screen to get to the last character in a flyout. The fact is that dragging is more accurate than tapping, given the right amount of feedback a drag can be half as long as the distance your selection covers. The user will quickly figure it out. 

Unlike many keyboard extensions, it doesn't need a network connection and switching out is a simple tap, not some complicated unlocking. I'm sure that it will take some more refining, but it actually came out pretty well.