Skip to content

A keyboard input model #753

Closed
Closed

Description

@pyfisch

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 KeyboardEvent well.

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.

  1. List of VirtualKeyCode is seen as incomplete (Enable Less and Greater Keys 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.
  2. While VirtualKeyCode should capture the meaning of the key there
    are different codes for e.g. "0": Key0 and Numpad0 or LControl and RControl.
  3. The ScanCode is platform dependent. Therefore apps wanting to use keys like
    WASD for navigation will assume an QWERTY layout instead of
    using the key locations.
  4. 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)
  5. A few useful modfiers like AltGraph and NumLock are missing.
  6. There is no relation between ReceivedCharacter and KeyboardInput
    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)
  7. 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) VirtualKeyCode is replaced with a Key. 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) ScanCode is complemented by Code. Codes describe
    physical key locations in a cross-platform way.
    Specification
  • (shortcoming 4) a repeat attribute 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 (like Fn, 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 by ReceivedCharacter.
    Either ReceivedCharacter is 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

  1. Osspial commented on Jan 7, 2019

    @Osspial
    Contributor

    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.

    VirtualKeyCode is replaced with a Key. 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.

    Being more general on this would be a good change. I don't like using a full String for this, though - it introduces various issues that I'm not particularly happy with:

    • A full String is more difficult to match on than an enum, str, or char.
    • Unicode characters have multiple cases, while keyboard keys only have one case. This could introduce some tricky bugs into people's applications.

    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.

    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.

    I like the idea of having a left/right enum to distinguish between sided keys. However, the Location enum should be exposed through variants in the Key enum (e.g. Ctrl(Location)), rather than on the main KeyboardEvent struct we expose.

    ScanCode is complemented by Code. Codes describe physical key locations in a cross-platform way. Specification

    Making scan codes platform-independent is certainly something we should do, although the W3C Code specification 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 remove ScanCode support 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 and Keys, for display purposes.

    (shortcoming 5) All known modifier keys are supported. Note: W3C decided to include some keys that are usually handled in hardware and don't emit keyboard events (like Fn, FnLock)

    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 ModifiersChanged event, but that needs discussion and I'm not entirely sure it's the right move.

    (shortcoming 4) a repeat attribute is added.
    (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.

    I'm down with all of these changes.

  2. pyfisch commented on Jan 7, 2019

    @pyfisch
    Author

    Hi, thanks for taking the time to review this!

    Being more general on this would be a good change. I don't like using a full String for this, though - it introduces various issues that I'm not particularly happy with:

    • A full String is more difficult to match on than an enum, str, or char.

    • Unicode characters have multiple cases, while keyboard keys only have one case. This could introduce some tricky bugs into people's applications.

    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 couldn't agree more and would have preferred to use char instead. Matching is easy and the Key enum can implement Copy. The reason to use a String is 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 &str is 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 ShortcutMatcher which 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)

    Unicode characters have multiple cases, while keyboard keys only have one case.

    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 current VirtualKeyCodes can be typed without modifiers on a US-ASCII keyboard (I think) some variants like LBracket can 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.

    I like the idea of having a left/right enum to distinguish between sided keys. However, the Location enum should be exposed through variants in the Key enum (e.g. Ctrl(Location)), rather than on the main KeyboardEvent struct we expose.

    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. Backspace on num pad) this would be a breaking change.

    Making scan codes platform-independent is certainly something we should do, although the W3C Code specification 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?

    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)

    I'd like to leave the hardware-handled keys out of our "officially supported" keys

    Yeah, there should be a list of supported modifiers for each platform in the docs.

    We may also want to create a separate ModifiersChanged event, but that needs discussion and I'm not entirely sure it's the right move.

    I am not sure when I would use ModifiersChanged event as modifier keys already send keydown and keyup events.

  3. Osspial commented on Jan 8, 2019

    @Osspial
    Contributor

    The problem with &str is 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.

    There's a solution for using &str, actually - we could convert unicode Strings 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:

    let string: String = "Hello".to_string();
    // Construct a 'static string at runtime.
    let x: &'static str = Box::leak(string.into_boxed_str());

    That would let us pass &strs through the unicode variant and let people use string matching.

    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 current VirtualKeyCodes can be typed without modifiers on a US-ASCII keyboard (I think) some variants like LBracket can 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.

    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.

    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. Backspace on num pad) this would be a breaking change.

    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:

    match (key, location) {
        (Key::A, _) => (),
        (Key::B, _) => (),
        (Key::C, _) => (),
        (Key::Alt, _) => (),
        (Key::Ctrl, Location::Left) => (),
        (Key::Ctrl, Location::Right) => (),
        _ => ()
    }

    With them combined into one type, it looks like this:

    match key {
        Key::A => (),
        Key::B => (),
        Key::C => (),
        Key::Alt(_) => (),
        Key::Ctrl(Location::Left) => (),
        Key::Ctrl(Location::Right) => (),
        _ => ()
    }

    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.

    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)

    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.

    I am not sure when I would use ModifiersChanged event as modifier keys already send keydown and keyup events.

    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 ModifiersChanged event was so that we wouldn't have to expose a modifiers variable 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 a KeyUp event for every KeyDown event or automatically sending KeyDown events for all pressed keys when a user focuses the window).

  4. Osspial commented on Jan 8, 2019

    @Osspial
    Contributor

    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.

  5. pyfisch commented on Jan 8, 2019

    @pyfisch
    Author

    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.

  6. pyfisch commented on Jan 8, 2019

    @pyfisch
    Author

    The purpose of having Key-codes is to let the program figure out which keys have been pressed irrespective of any modifier-key presses

    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.

    If you want to access the character that's outputted, taking into account modifier keys, you check the received character.

    What I propose is that the character that's outputted is the key. Received character is then redundant.

    To match with separate key and location you can do this:

    match event.key {
        Key::Home => ...
        Key::End => ...
        Key::Control if event.location == Left => ...
        Key::Control if event.location == Right => ...
        _ => ...
    }
    

    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.)

  7. Osspial commented on Jan 13, 2019

    @Osspial
    Contributor

    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.

    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.

    What I propose is that the character that's outputted is the key. Received character is then redundant.

    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:

    • Functional key-press API (handles unicode characters most of the time and layout-agnostic key-presses for layout-agnostic keys)
    • Physical key-press API (layout-agnostic keypresses)
    • Character composition API (handles unicode characters sometimes, but only when they aren't tied to a single keypress)

    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:

    • Physical key-press API (layout-agnostic keypresses)
    • Character input API (handles unicode characters and composition events)

    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.

    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).

    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).

  8. pyfisch commented on Jan 13, 2019

    @pyfisch
    Author

    I'd rather only have two keyboard input APIs:

    • Physical key-press API (layout-agnostic keypresses)
    • Character input API (handles unicode characters and composition events)

    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.

  9. Osspial commented on Jan 13, 2019

    @Osspial
    Contributor

    How do you handle keyboard shortcuts like Control+Z (for undo)?

    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:

    struct KeyboardInput {
        /// The pressed key, ignoring keyboard layout.
        ///
        /// Alphanumeric keys always correspond to their location on a QWERTY keyboard,
        /// regardless of whether or not the user is using an alternate keymap. For instance,
        /// pressing the Z key on a QWERTZ keyboard will result in `KeyCode::KeyY` getting
        /// sent. This also ignores any other remappings (e.g. even if the user has bound
        /// Control to Caps Lock, pressing the Caps Lock key will result in `KeyCode::CapsLock`.)
        ///
        /// This is useful for things like videogame keymaps, where the physical location of a
        /// key is more important than the actual key being pressed.
        physical_key: KeyCode,
        /// The pressed key, taking keyboard layout into account.
        ///
        /// If the user is using an alternate keyboard layout or have remapped any of their keys,
        /// their preferred mappings will be sent. Unlike `physical_key`, pressing Z on a QWERTZ
        /// keyboard will output `KeyCode::KeyZ`, and rebound keys as mentioned above will output
        /// the rebound key.
        ///
        /// This is useful for desktop application keymaps, where maintaining keybinding
        /// consistency with other applications is more important than the exact location of the
        /// key pressed.
        logical_key: KeyCode,
        /* other fields intentionally omitted */
    }

    EDIT: I have physical_key and logical_key using 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.

  10. pyfisch commented on Jan 13, 2019

    @pyfisch
    Author

    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.

  11. Osspial commented on Jan 13, 2019

    @Osspial
    Contributor

    There are two ways I can think of to do that:

    • Pass a location parameter alongside all keys that appear both on the numpad and elsewhere on the keyboard.
    • Always deliver the same keys regardless of whether or not numlock is pressed, and let the application handle translating them into special keys.

    My feeling is that we should take the first approach for logical_key and the second approach for physical_key. That sacrifices some consistency across the two input methods, but it also matches better with their respective stated goals.

  12. 147 remaining items

  13. ArturKovacs commented on Apr 23, 2021

    @ArturKovacs
    Contributor

    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-keyboard branch first, instead you can add my repo as a remote and you can checkout my new-keyboard branch and work on top of that. (Although I guess this means that we should merge PRs into winit's new-keyboard branch without squashing... But that shouldn't concern you @garasubo)

  14. maroider commented on Apr 23, 2021

    @maroider
    Member

    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).

  15. inodentry commented on May 5, 2021

    @inodentry

    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.

  16. modified the milestones: Keyboard Events Overhaul, on Jun 25, 2021
  17. mahkoh commented on Oct 21, 2021

    @mahkoh
    Contributor

    Afaict the API as discussed here does not support multiple seats which makes it cumbersome impossible to implement it on platforms that support multiple seats. E.g. consider the following sequence of events:

    • Seat 1: Press Alt
    • Seat 1: Press A
    • Seat 2: Press Shift
    • Seat 2: Press B
    • Seat 1: Press C

    I'm not sure which sequence of events this would generate with this API.

  18. dhardy commented on Oct 21, 2021

    @dhardy
    Contributor

    I'm pretty sure a winit app 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.

  19. mahkoh commented on Oct 21, 2021

    @mahkoh
    Contributor

    I'm pretty sure a winit app would be restricted to one seat and only report events from that.

    That seems like a significant restriction. Has this already been discussed elsewhere?

  20. mahkoh commented on Oct 23, 2021

    @mahkoh
    Contributor

    It's not like the apps on Seat 1 should know what is going on at Seat 2.

    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.

  21. veryjos commented on Nov 25, 2021

    @veryjos

    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.

  22. ArturKovacs commented on Nov 25, 2021

    @ArturKovacs
    Contributor

    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.

  23. kchibisov commented on May 28, 2023

    @kchibisov
    Member

    The #2662 was merged addressing most of this. For follow ups I'd suggest to open separate issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions