Repository navigation
Description
TLDR: I think that Winit needs more expressive keyboards events and to follow a written specification to keep platform inconsistencies to a minimum. I propose to adapt the JS KeyboardEvent for winit and to follow the UI Events specification for keyboard input.
Winit is used for many applications that need
to handle different kinds of keyboard input.
- Games: Physical location of keys like
WASD for movement and actions.
Text inpput for names and chat. - GUI applications: Text input and keyboard shortcuts.
- the Servo Browser: Wants to support JS
KeyboardEventwell.
Currently there are two events for text input in Winit:
KeyboardInput and ReceivedCharacter.
pub struct KeyboardInput {
pub scancode: ScanCode,
pub state: ElementState,
pub virtual_keycode: Option<VirtualKeyCode>,
pub modifiers: ModifiersState,
}The KeyboardInput event carries information about keys pressed and released.
scancode is a platform-dependent code identifying the physical key.
virtual_keycode optionally describes the meaning of the key.
It indicates ASCII letters, some punctuation and some function keys.
modifiers tells if the Shift, Control, Alt and Logo keys are currently pressed.
The ReceivedCharacter event sends a single Unicode codepoint. The character can
be pushed to the end of a string and if this is done for all events the user
will see the text they intended to enter.
Shortcomings
This is my personal list in no particular order.
- List of
VirtualKeyCodeis seen as incomplete (EnableLessandGreaterKeys on X11 #71, Support keypress events with non-ascii chars #59).
Without a given list it is hard to decide which keys to include
and when the list is complete.
Also it is necessary to define each virtual key code so multiple platforms will
map keys to the same virtual key codes.
While it probably uncontroversial that ASCII keys should be included
for non-ASCII single keys found on many keyboards like é, µ, or ü
it is more difficult to decide and to create an exhaustive list. - While
VirtualKeyCodeshould capture the meaning of the key there
are different codes for e.g. "0":Key0andNumpad0orLControlandRControl. - The
ScanCodeis platform dependent. Therefore apps wanting to use keys like
WASD for navigation will assume an QWERTY layout instead of
using the key locations. - It is unclear if a key is repeated or not. Some applications only want to
act on the first keypress and ignore all following repeated keys. Right
now these applications need to do extra tracking and are probably not
correct if the keyboard focus changes while a key is held down. ( A way to disable key repeats #310) - A few useful modfiers like AltGraph and NumLock are missing.
- There is no relation between
ReceivedCharacterandKeyboardInput
events. While this is not necessary for every application some
(like browsers) need it and have to use ugly (and incorrect) work-arounds. (Associate received characters with key inputs #34) - Dead-key handling is unspecified and IMEs (Input Method Editors) are not supported.
In general there are many issues that are platform-dependant and where it is
unclear what the correct behavior is or it is not documented.
Both alacritty and Servo just to name two applications have multiple
issues where people mention that keyboard input does not work as expeced.
Proposed Solution
Winit is not the first software that needs to deal with keyboard input on
a variety of platforms. In particular the web platform has a complete
specification how keyboard events should behave which is implemented on
all platforms that Winit aims to support.
While the specification talks about JS objects it can be easily ported
to Rust. Some information is duplicated in KeyboardEvent for
backwards compatibility but this can be omitted in Rust so Winit stays simpler.
See the keyboard-types for how keyboard events can look like in Rust.
- (shortcoming 1)
VirtualKeyCodeis replaced with aKey. This is an enum
with all the values for functional keys and a variant for Unicode values
that stores printable characters both from the whole Unicode range.
Specification - (shortcoming 2) is also adressed by this. There is just one value for keys
like "Control" but if necessary one can distinguish left/right or
keyboard/numpad keys by their location attribute. - (shortcoming 3)
ScanCodeis complemented byCode. Codes describe
physical key locations in a cross-platform way.
Specification - (shortcoming 4) a
repeatattribute is added. - (shortcoming 5) All known modifier keys are supported.
**Specification
Note: W3C decided to include some keys that are usually handled
in hardware and don't emit keyboard events (likeFn,FnLock) - (shortcoming 6) received characters and keyboard events are now one
(exceptions see below) - (shortcoming 7) to handle dead keys and IMEs a composition event
is introduced. It describes the text that should be added at
the current cursor position. Specification
Note: The introduction composition events makes it a bit harder to
get "just the text" which is currently emitted byReceivedCharacter.
EitherReceivedCharacteris kept around for easier use or a utility
function is provided that takes keyboard and composition events and
emits the printable text.
Implementation
This is obviously a breaking change so there needs to be a new release of winit and release notes.
While the proposed events are very expressive it is possible to convert Winit to the new
events first and then improve each backend to emit the additional information about key-codes,
locations, repeating keys etc.
Thank you for writing and maintaining Winit! I hope this helps to get a discussion about keyboard input handling started and maybe some ideas or even the whole proposal is implemented in Winit.
Activity
Osspial commentedon Jan 7, 2019
Hi, and thanks for taking the time to put this together! Overall, I like the direction this is going, but there are some specific feedback points that come up for this.
Being more general on this would be a good change. I don't like using a full
Stringfor this, though - it introduces various issues that I'm not particularly happy with:Stringis more difficult tomatchon than anenum,str, orchar.Unfortunately I can't think of a good replacement that's as flexible as a string while accounting for both of those issues, but it's something that rubs me the wrong way.
I like the idea of having a left/right enum to distinguish between sided keys. However, the
Locationenum should be exposed through variants in theKeyenum (e.g.Ctrl(Location)), rather than on the mainKeyboardEventstruct we expose.Making scan codes platform-independent is certainly something we should do, although the W3C
Codespecification relies a bit too much on the layout of the US keyboard for my liking. Perhaps we should use some sort of numeric index for this? I feel we should also removeScanCodesupport entirely, since it doesn't seem to provide any real use for cross-platform application programming. I'd be open to a counter-example, though.Whatever mechanism we decide on, there should be some method for translating between
Codes andKeys, for display purposes.I'd like to leave the hardware-handled keys out of our "officially supported" keys, but this would be a good change. We may also want to create a separate
ModifiersChangedevent, but that needs discussion and I'm not entirely sure it's the right move.I'm down with all of these changes.
pyfisch commentedon Jan 7, 2019
Hi, thanks for taking the time to review this!
I couldn't agree more and would have preferred to use
charinstead. Matching is easy and theKeyenum can implementCopy. The reason to use aStringis that a key string has a base character and 0 or more combining characters because certain languages have keys that can't be represented with a single code point. (The problem with&stris that someone needs to own it and an enum is problematic because someone needs to decide which characters exist ahead of time and extend it for each new Unicode version.)Because matching strings is so painful I wrote the
ShortcutMatcherwhich is used by Servo. It is a quite convenient way to match keys and shortcuts. (Btw it ignores ASCII case and handles some other quirks)One way to think about keyboard keys is that they have multiple levels. For example the "M" key on my keyboard has four levels that are accessed with different modifier keys: "m", "M", "µ", "º". These values should be a different
Key. On the other hand, while the currentVirtualKeyCodes can be typed without modifiers on a US-ASCII keyboard (I think) some variants likeLBracketcan only be accessed with modifier keys (in my case AltGr+8) on other keyboards. For these reasons I think it is preferable to have different Unicode cases in key values.Is there a specific reason to do it this way?
If there is ever a need to add a location to a key that previously did not have one (e.g.
Backspaceon num pad) this would be a breaking change.One upside of using names referring to the US keyboard layout is that this layout is already familiar to a lot of people and there are plenty of diagrams and photos of the layout for quick reference. Classic scancodes are too short (8-bit) and vary between keyboards from different manufacturers. One language independent index used by X11 can be seen below. (search for X11 keycode names)
Yeah, there should be a list of supported modifiers for each platform in the docs.
I am not sure when I would use
ModifiersChangedevent as modifier keys already send keydown and keyup events.Osspial commentedon Jan 8, 2019
There's a solution for using
&str, actually - we could convert unicodeStrings that are constructed at runtime into&'static strs as follows, then we can internally store a cache of keypress strings so that we don't consume additional memory for every keypress:That would let us pass
&strs through the unicode variant and let people use string matching.The purpose of having
Key-codes is to let the program figure out which keys have been pressed irrespective of any modifier-key presses - we'd want all of those characters to always be exposed under one key, since they're mapped to the same key. If you want to access the character that's outputted, taking into account modifier keys, you check the received character.Mainly, to make matching more ergonomic. If you wanted to match on both location and key with the types being separate, you'd have to do this:
With them combined into one type, it looks like this:
The second version is nicer to read, and it also lets the reader know when a key's specific location is being ignored, versus when a key only has one possible location. The first version doesn't communicate that information.
Regarding adding a location to an existing key being a breaking change - there shouldn't be any reason we ever have to do that! Keyboard layouts are fairly static, and only a limited subset of keys are going to have multiple locations on the keyboard. We should be able to keep track of which ones have multiple locations and structure the enum as necessary.
My main issue with using the QWERTY keys to specify a layout-independent keymap feels against the spirit of providing such an API. Something in the vein of that X11 index seems like a decent solution, though.
If users could always keep track of which modifier keys have been pressed with keydown and keyup events, we wouldn't need to expose a modifiers parameter at all. The reason we expose them is because if someone presses a modifier key outside of the window then focuses the window, or presses the modifier key inside the window and unfocuses the window, the key-down/key-up events won't be properly delivered.
The reason I was floating a separate
ModifiersChangedevent was so that we wouldn't have to expose amodifiersvariable alongside pretty much every window event, as we do now. However, I realize now that it would be simpler from a user's standpoint to provide stronger guarantees about keypress events so that they can reliably keep track of which keys have been pressed without running into the pitfalls described above (such as, guaranteeing to deliver aKeyUpevent for everyKeyDownevent or automatically sendingKeyDownevents for all pressed keys when a user focuses the window).Osspial commentedon Jan 8, 2019
Actually, regarding device-dependent virtual key-codes - what real purpose do they provide that isn't provided by exposing the received character and the device-independent key code? I can't think of a reason for using the virtual key-codes that isn't better-served by one of the other two methods; keyboard mappings should generally be done with the device-independent keys, and character input is best done with received character events.
pyfisch commentedon Jan 8, 2019
The UI Event Specification explains how keyboards work. It discusses why each part of the event is useful and how they relate to each other.
pyfisch commentedon Jan 8, 2019
Looks like we are talking about different things then. You seem to associate the visual markings on the key cap with key codes.
While the UI Events specification and I refer to the functional mapping of the key.
What I propose is that the character that's outputted is the key. Received character is then redundant.
To match with separate
keyandlocationyou can do this:If a user does not care about key locations they don't have to
know they exist at all. On the other hand if key and location are one type
every user needs to know (or be told by the compiler)
which keys have multiple locations to write
Key::Control(_i_dont_care).(I expect this to be the common case.)
Osspial commentedon Jan 13, 2019
Not quite - if the user has switched their keyboard layout away from what's printed on their keyboard (say, to Dvorak) the key code would correspond to the remapped keybindings. Otherwise that seems fairly accurate.
So, following the UI Events specification would have us mix character input and other keypresses (ctrl, alt, arrow keys, etc.) into a single API, right? I really don't like the idea of doing that. Having that API in addition to the physical key-press and character composition APIs leads to a situation where there's a lot of overlap for what each API does:
The functional key-press API doesn't have its own specific purpose: sometimes it does things the physical keypress API does, and because it handles the majority of unicode input it make the character composition API easy to ignore.
I'd rather only have two keyboard input APIs:
Under this design, the purpose of each API is much more clear: the physical keypress API handles mapping each key to a function, and the character input API handles... well, all character input. Skimming through the UI Events spec it seems like it would be possible to map this API onto that, as well.
That's the point of merging those two events - to force users to decide whether they care or not. Whether you like that is up to personal preference, I guess; I like it because it improves the readability of the code (you know when someone's opting out of considering location vs. when there's no location to consider) and the documentation (we don't have to manually specify which keys have locations - if a key has a location, it's inherent to the declaration of the variant).
pyfisch commentedon Jan 13, 2019
Fine. How do you handle keyboard shortcuts like Control+Z (for undo)? Keep in mind that the placement of the Z key varies across common layouts and reasonable people may move the functionality of the Control key to another physical key.
Osspial commentedon Jan 13, 2019
I... hmm.
That's something that crossed my mind briefly when I was first writing that comment, and I'll admit that that design doesn't handle this case well. Ideally, we'd be able to keep the same physical keymap across layouts (which is what you want for things like videogame keymaps), but that also leads to problems when other software developers haven't done that, causing our applications to violate those UX standards!
Something we could do is use the UIEvents-Code keycodes (or an equivalent), and structure keyboard events like this:
EDIT: I have
physical_keyandlogical_keyusing the same type to make it clear that they both have the same underlying variants. We may want to split them into separate types with the same internal layout, as we've done with DPI types, but that decision isn't important for establishing whether or not this general API is a good idea.pyfisch commentedon Jan 13, 2019
Well this design is a lot better.
What happens if I want to detect the "Page Up" key on my numpad? If "Num Lock" is on I want to receive the character "9" instead.
Osspial commentedon Jan 13, 2019
There are two ways I can think of to do that:
My feeling is that we should take the first approach for
logical_keyand the second approach forphysical_key. That sacrifices some consistency across the two input methods, but it also matches better with their respective stated goals.147 remaining items
ArturKovacs commentedon Apr 23, 2021
That sounds awesome @garasubo! I know that @maroider did work on the X11 implementation but I'm not sure how far he's gotten with it. Maybe the two of you could cooperate or race :D I would really want to see this completed as soon as possible.
#1788 is currently waiting to get approved by @msiglreith. But you don't need to wait for that to get merged into the
new-keyboardbranch first, instead you can add my repo as a remote and you can checkout mynew-keyboardbranch and work on top of that. (Although I guess this means that we should merge PRs into winit'snew-keyboardbranch without squashing... But that shouldn't concern you @garasubo)maroider commentedon Apr 23, 2021
As mentioned, I'm working on the Wayland and X11 implementations simultaneously, as I want them to share logic where possible.
My efforts on the X11 implementation have admittedly ground to a halt due to issues with initializing
libxkbcommon, and I intend to take another stab at getting it working today.I would of course be grateful for any help I can get, be it code or advice. If you'd like, @garasubo, we can chat more about this on Matrix or Discord (where you'll find me as
maroider#8969).inodentry commentedon May 5, 2021
Feel free to ping me if you need any testing on Wayland and XWayland. 🙂 I am a multilingual user with keyboard layouts (incl. custom ones) for different scripts.
mahkoh commentedon Oct 21, 2021
Afaict the API as discussed here does not support multiple seats which makes it
cumbersomeimpossible to implement it on platforms that support multiple seats. E.g. consider the following sequence of events:I'm not sure which sequence of events this would generate with this API.
dhardy commentedon Oct 21, 2021
I'm pretty sure a
winitapp would be restricted to one seat and only report events from that. It's not like the apps on Seat 1 should know what is going on at Seat 2.mahkoh commentedon Oct 21, 2021
That seems like a significant restriction. Has this already been discussed elsewhere?
mahkoh commentedon Oct 23, 2021
I missed this when I read your comment the first time. I think there is a misunderstanding what a seat is. A seat is simply a mouse and/or keyboard set. If you have multiple independent sets, then you have multiple seats. Each seat is represented on the screen by its own cursor.
Iirc on wayland it is standard that each tablet connected to the PC is its own seat. This means that you have to support multiple seats to fully support tablet input on wayland.
Another example of multiple seats are VNC applications that represent the remote mouse/keyboard as a separate seat so that the remote user doesn't have to fight with the local user over control of the cursor.
veryjos commentedon Nov 25, 2021
This issue is huge and a few years old, I'm having trouble tracking..
Is the key repeat solution proposed in the original issue available yet? I can't find anything in the source.
ArturKovacs commentedon Nov 25, 2021
I think this will be very helpful to you: #1806
To answer your question, nothing is merged into master yet but the implementations are mostly done actually. See the tracking issue I referenced above.
kchibisov commentedon May 28, 2023
The #2662 was merged addressing most of this. For follow ups I'd suggest to open separate issues.