Fix keyboard handling

This commit also does some refactoring related to the fix.