Fix keyboard handling

This commit also does some refactoring related to the fix.
Merge pull request #3 from crumblingstatue/master

Fix keyboard handling