Search code examples
rustkeyboardsfmltext-editorscancodes

Retrieving keyboard-layout-independent typed characters from scancodes in Rust


I would like to write a low level, fast text editor in Rust. For graphics/windowing, I was planning to use SFML for easy fast cross-compatibility between Windows, macOS, and Linux.

Now, the issue I've come across is when typing characters in a text editor that require the Shift key. SFML, and even other libraries which query native operating system syscalls like keyboard_query only give you scancodes like "SHIFT and 3 are pressed", now, on my keyboard (a British Macintosh keyboard) I would want that to produce a £ in the text editor, but an American would want it to produce #, and so on and so on for other keyboard layouts.

Is there a reliable cross-platform way to know which character somebody wants to type regardless of their keyboard layout?

Failing this, is there a way to do it just in macOS? Or will I have to type out a big mapping of what Shift+whatever key produces for every single keyboard layout I want to support?


Solution

  • If you're already using SFML, then you don't need to convert scancodes.

    Instead of watching for Event::KeyPressed, you could just watch for Event::TextEntered. That way you get a unicode: char, which you can insert directly into your string. The exception being, that you'd still need to watch for Event::KeyPressed, to be able to handle e.g. backspace.