rio_window/
keyboard.rs

1//! Types related to the keyboard.
2
3// This file contains a substantial portion of the UI Events Specification by the W3C. In
4// particular, the variant names within `Key` and `KeyCode` and their documentation are modified
5// versions of contents of the aforementioned specification.
6//
7// The original documents are:
8//
9// ### For `Key`
10// UI Events KeyboardEvent key Values
11// https://www.w3.org/TR/2017/CR-uievents-key-20170601/
12// Copyright © 2017 W3C® (MIT, ERCIM, Keio, Beihang).
13//
14// ### For `KeyCode`
15// UI Events KeyboardEvent code Values
16// https://www.w3.org/TR/2017/CR-uievents-code-20170601/
17// Copyright © 2017 W3C® (MIT, ERCIM, Keio, Beihang).
18//
19// These documents were used under the terms of the following license. This W3C license as well as
20// the W3C short notice apply to the `Key` and `KeyCode` enums and their variants and the
21// documentation attached to their variants.
22
23// --------- BEGINNING OF W3C LICENSE --------------------------------------------------------------
24//
25// License
26//
27// By obtaining and/or copying this work, you (the licensee) agree that you have read, understood,
28// and will comply with the following terms and conditions.
29//
30// Permission to copy, modify, and distribute this work, with or without modification, for any
31// purpose and without fee or royalty is hereby granted, provided that you include the following on
32// ALL copies of the work or portions thereof, including modifications:
33//
34// - The full text of this NOTICE in a location viewable to users of the redistributed or derivative
35//   work.
36// - Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none
37//   exist, the W3C Software and Document Short Notice should be included.
38// - Notice of any changes or modifications, through a copyright statement on the new code or
39//   document such as "This software or document includes material copied from or derived from
40//   [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)."
41//
42// Disclaimers
43//
44// THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES,
45// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR
46// ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD
47// PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
48//
49// COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES
50// ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT.
51//
52// The name and trademarks of copyright holders may NOT be used in advertising or publicity
53// pertaining to the work without specific, written prior permission. Title to copyright in this
54// work will at all times remain with copyright holders.
55//
56// --------- END OF W3C LICENSE --------------------------------------------------------------------
57
58// --------- BEGINNING OF W3C SHORT NOTICE ---------------------------------------------------------
59//
60// winit: https://github.com/rust-windowing/winit
61//
62// Copyright © 2021 World Wide Web Consortium, (Massachusetts Institute of Technology, European
63// Research Consortium for Informatics and Mathematics, Keio University, Beihang). All Rights
64// Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will
65// be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
66// FITNESS FOR A PARTICULAR PURPOSE.
67//
68// [1] http://www.w3.org/Consortium/Legal/copyright-software
69//
70// --------- END OF W3C SHORT NOTICE ---------------------------------------------------------------
71
72use bitflags::bitflags;
73pub use smol_str::SmolStr;
74
75/// Contains the platform-native physical key identifier
76///
77/// The exact values vary from platform to platform (which is part of why this is a per-platform
78/// enum), but the values are primarily tied to the key's physical location on the keyboard.
79///
80/// This enum is primarily used to store raw keycodes when Winit doesn't map a given native
81/// physical key identifier to a meaningful [`KeyCode`] variant. In the presence of identifiers we
82/// haven't mapped for you yet, this lets you use use [`KeyCode`] to:
83///
84/// - Correctly match key press and release events.
85/// - On non-web platforms, support assigning keybinds to virtually any key through a UI.
86#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
87pub enum NativeKeyCode {
88    Unidentified,
89    /// An Android "scancode".
90    Android(u32),
91    /// A macOS "scancode".
92    MacOS(u16),
93    /// A Windows "scancode".
94    Windows(u16),
95    /// An XKB "keycode".
96    Xkb(u32),
97}
98
99impl std::fmt::Debug for NativeKeyCode {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        use NativeKeyCode::{Android, MacOS, Unidentified, Windows, Xkb};
102        let mut debug_tuple;
103        match self {
104            Unidentified => {
105                debug_tuple = f.debug_tuple("Unidentified");
106            }
107            Android(code) => {
108                debug_tuple = f.debug_tuple("Android");
109                debug_tuple.field(&format_args!("0x{code:04X}"));
110            }
111            MacOS(code) => {
112                debug_tuple = f.debug_tuple("MacOS");
113                debug_tuple.field(&format_args!("0x{code:04X}"));
114            }
115            Windows(code) => {
116                debug_tuple = f.debug_tuple("Windows");
117                debug_tuple.field(&format_args!("0x{code:04X}"));
118            }
119            Xkb(code) => {
120                debug_tuple = f.debug_tuple("Xkb");
121                debug_tuple.field(&format_args!("0x{code:04X}"));
122            }
123        }
124        debug_tuple.finish()
125    }
126}
127
128/// Contains the platform-native logical key identifier
129///
130/// Exactly what that means differs from platform to platform, but the values are to some degree
131/// tied to the currently active keyboard layout. The same key on the same keyboard may also report
132/// different values on different platforms, which is one of the reasons this is a per-platform
133/// enum.
134///
135/// This enum is primarily used to store raw keysym when Winit doesn't map a given native logical
136/// key identifier to a meaningful [`Key`] variant. This lets you use [`Key`], and let the user
137/// define keybinds which work in the presence of identifiers we haven't mapped for you yet.
138#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
139pub enum NativeKey {
140    Unidentified,
141    /// An Android "keycode", which is similar to a "virtual-key code" on Windows.
142    Android(u32),
143    /// A macOS "scancode". There does not appear to be any direct analogue to either keysyms or
144    /// "virtual-key" codes in macOS, so we report the scancode instead.
145    MacOS(u16),
146    /// A Windows "virtual-key code".
147    Windows(u16),
148    /// An XKB "keysym".
149    Xkb(u32),
150    /// A "key value string".
151    Web(SmolStr),
152}
153
154impl std::fmt::Debug for NativeKey {
155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156        use NativeKey::{Android, MacOS, Unidentified, Web, Windows, Xkb};
157        let mut debug_tuple;
158        match self {
159            Unidentified => {
160                debug_tuple = f.debug_tuple("Unidentified");
161            }
162            Android(code) => {
163                debug_tuple = f.debug_tuple("Android");
164                debug_tuple.field(&format_args!("0x{code:04X}"));
165            }
166            MacOS(code) => {
167                debug_tuple = f.debug_tuple("MacOS");
168                debug_tuple.field(&format_args!("0x{code:04X}"));
169            }
170            Windows(code) => {
171                debug_tuple = f.debug_tuple("Windows");
172                debug_tuple.field(&format_args!("0x{code:04X}"));
173            }
174            Xkb(code) => {
175                debug_tuple = f.debug_tuple("Xkb");
176                debug_tuple.field(&format_args!("0x{code:04X}"));
177            }
178            Web(code) => {
179                debug_tuple = f.debug_tuple("Web");
180                debug_tuple.field(code);
181            }
182        }
183        debug_tuple.finish()
184    }
185}
186
187impl From<NativeKeyCode> for NativeKey {
188    #[inline]
189    fn from(code: NativeKeyCode) -> Self {
190        match code {
191            NativeKeyCode::Unidentified => NativeKey::Unidentified,
192            NativeKeyCode::Android(x) => NativeKey::Android(x),
193            NativeKeyCode::MacOS(x) => NativeKey::MacOS(x),
194            NativeKeyCode::Windows(x) => NativeKey::Windows(x),
195            NativeKeyCode::Xkb(x) => NativeKey::Xkb(x),
196        }
197    }
198}
199
200impl PartialEq<NativeKey> for NativeKeyCode {
201    #[allow(clippy::cmp_owned)] // uses less code than direct match; target is stack allocated
202    #[inline]
203    fn eq(&self, rhs: &NativeKey) -> bool {
204        NativeKey::from(*self) == *rhs
205    }
206}
207
208impl PartialEq<NativeKeyCode> for NativeKey {
209    #[inline]
210    fn eq(&self, rhs: &NativeKeyCode) -> bool {
211        rhs == self
212    }
213}
214
215/// Represents the location of a physical key.
216///
217/// This type is a superset of [`KeyCode`], including an [`Unidentified`][Self::Unidentified]
218/// variant.
219#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
220pub enum PhysicalKey {
221    /// A known key code
222    Code(KeyCode),
223    /// This variant is used when the key cannot be translated to a [`KeyCode`]
224    ///
225    /// The native keycode is provided (if available) so you're able to more reliably match
226    /// key-press and key-release events by hashing the [`PhysicalKey`]. It is also possible to use
227    /// this for keybinds for non-standard keys, but such keybinds are tied to a given platform.
228    Unidentified(NativeKeyCode),
229}
230
231impl From<KeyCode> for PhysicalKey {
232    #[inline]
233    fn from(code: KeyCode) -> Self {
234        PhysicalKey::Code(code)
235    }
236}
237
238impl From<NativeKeyCode> for PhysicalKey {
239    #[inline]
240    fn from(code: NativeKeyCode) -> Self {
241        PhysicalKey::Unidentified(code)
242    }
243}
244
245impl PartialEq<KeyCode> for PhysicalKey {
246    #[inline]
247    fn eq(&self, rhs: &KeyCode) -> bool {
248        match self {
249            PhysicalKey::Code(ref code) => code == rhs,
250            _ => false,
251        }
252    }
253}
254
255impl PartialEq<PhysicalKey> for KeyCode {
256    #[inline]
257    fn eq(&self, rhs: &PhysicalKey) -> bool {
258        rhs == self
259    }
260}
261
262impl PartialEq<NativeKeyCode> for PhysicalKey {
263    #[inline]
264    fn eq(&self, rhs: &NativeKeyCode) -> bool {
265        match self {
266            PhysicalKey::Unidentified(ref code) => code == rhs,
267            _ => false,
268        }
269    }
270}
271
272impl PartialEq<PhysicalKey> for NativeKeyCode {
273    #[inline]
274    fn eq(&self, rhs: &PhysicalKey) -> bool {
275        rhs == self
276    }
277}
278
279/// Code representing the location of a physical key
280///
281/// This mostly conforms to the UI Events Specification's [`KeyboardEvent.code`] with a few
282/// exceptions:
283/// - The keys that the specification calls "MetaLeft" and "MetaRight" are named "SuperLeft" and
284///   "SuperRight" here.
285/// - The key that the specification calls "Super" is reported as `Unidentified` here.
286///
287/// [`KeyboardEvent.code`]: https://w3c.github.io/uievents-code/#code-value-tables
288#[non_exhaustive]
289#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
290pub enum KeyCode {
291    /// <kbd>`</kbd> on a US keyboard. This is also called a backtick or grave.
292    /// This is the <kbd>半角</kbd>/<kbd>全角</kbd>/<kbd>漢字</kbd>
293    /// (hankaku/zenkaku/kanji) key on Japanese keyboards
294    Backquote,
295    /// Used for both the US <kbd>\\</kbd> (on the 101-key layout) and also for the key
296    /// located between the <kbd>"</kbd> and <kbd>Enter</kbd> keys on row C of the 102-,
297    /// 104- and 106-key layouts.
298    /// Labeled <kbd>#</kbd> on a UK (102) keyboard.
299    Backslash,
300    /// <kbd>[</kbd> on a US keyboard.
301    BracketLeft,
302    /// <kbd>]</kbd> on a US keyboard.
303    BracketRight,
304    /// <kbd>,</kbd> on a US keyboard.
305    Comma,
306    /// <kbd>0</kbd> on a US keyboard.
307    Digit0,
308    /// <kbd>1</kbd> on a US keyboard.
309    Digit1,
310    /// <kbd>2</kbd> on a US keyboard.
311    Digit2,
312    /// <kbd>3</kbd> on a US keyboard.
313    Digit3,
314    /// <kbd>4</kbd> on a US keyboard.
315    Digit4,
316    /// <kbd>5</kbd> on a US keyboard.
317    Digit5,
318    /// <kbd>6</kbd> on a US keyboard.
319    Digit6,
320    /// <kbd>7</kbd> on a US keyboard.
321    Digit7,
322    /// <kbd>8</kbd> on a US keyboard.
323    Digit8,
324    /// <kbd>9</kbd> on a US keyboard.
325    Digit9,
326    /// <kbd>=</kbd> on a US keyboard.
327    Equal,
328    /// Located between the left <kbd>Shift</kbd> and <kbd>Z</kbd> keys.
329    /// Labeled <kbd>\\</kbd> on a UK keyboard.
330    IntlBackslash,
331    /// Located between the <kbd>/</kbd> and right <kbd>Shift</kbd> keys.
332    /// Labeled <kbd>\\</kbd> (ro) on a Japanese keyboard.
333    IntlRo,
334    /// Located between the <kbd>=</kbd> and <kbd>Backspace</kbd> keys.
335    /// Labeled <kbd>¥</kbd> (yen) on a Japanese keyboard. <kbd>\\</kbd> on a
336    /// Russian keyboard.
337    IntlYen,
338    /// <kbd>a</kbd> on a US keyboard.
339    /// Labeled <kbd>q</kbd> on an AZERTY (e.g., French) keyboard.
340    KeyA,
341    /// <kbd>b</kbd> on a US keyboard.
342    KeyB,
343    /// <kbd>c</kbd> on a US keyboard.
344    KeyC,
345    /// <kbd>d</kbd> on a US keyboard.
346    KeyD,
347    /// <kbd>e</kbd> on a US keyboard.
348    KeyE,
349    /// <kbd>f</kbd> on a US keyboard.
350    KeyF,
351    /// <kbd>g</kbd> on a US keyboard.
352    KeyG,
353    /// <kbd>h</kbd> on a US keyboard.
354    KeyH,
355    /// <kbd>i</kbd> on a US keyboard.
356    KeyI,
357    /// <kbd>j</kbd> on a US keyboard.
358    KeyJ,
359    /// <kbd>k</kbd> on a US keyboard.
360    KeyK,
361    /// <kbd>l</kbd> on a US keyboard.
362    KeyL,
363    /// <kbd>m</kbd> on a US keyboard.
364    KeyM,
365    /// <kbd>n</kbd> on a US keyboard.
366    KeyN,
367    /// <kbd>o</kbd> on a US keyboard.
368    KeyO,
369    /// <kbd>p</kbd> on a US keyboard.
370    KeyP,
371    /// <kbd>q</kbd> on a US keyboard.
372    /// Labeled <kbd>a</kbd> on an AZERTY (e.g., French) keyboard.
373    KeyQ,
374    /// <kbd>r</kbd> on a US keyboard.
375    KeyR,
376    /// <kbd>s</kbd> on a US keyboard.
377    KeyS,
378    /// <kbd>t</kbd> on a US keyboard.
379    KeyT,
380    /// <kbd>u</kbd> on a US keyboard.
381    KeyU,
382    /// <kbd>v</kbd> on a US keyboard.
383    KeyV,
384    /// <kbd>w</kbd> on a US keyboard.
385    /// Labeled <kbd>z</kbd> on an AZERTY (e.g., French) keyboard.
386    KeyW,
387    /// <kbd>x</kbd> on a US keyboard.
388    KeyX,
389    /// <kbd>y</kbd> on a US keyboard.
390    /// Labeled <kbd>z</kbd> on a QWERTZ (e.g., German) keyboard.
391    KeyY,
392    /// <kbd>z</kbd> on a US keyboard.
393    /// Labeled <kbd>w</kbd> on an AZERTY (e.g., French) keyboard, and <kbd>y</kbd> on a
394    /// QWERTZ (e.g., German) keyboard.
395    KeyZ,
396    /// <kbd>-</kbd> on a US keyboard.
397    Minus,
398    /// <kbd>.</kbd> on a US keyboard.
399    Period,
400    /// <kbd>'</kbd> on a US keyboard.
401    Quote,
402    /// <kbd>;</kbd> on a US keyboard.
403    Semicolon,
404    /// <kbd>/</kbd> on a US keyboard.
405    Slash,
406    /// <kbd>Alt</kbd>, <kbd>Option</kbd>, or <kbd>⌥</kbd>.
407    AltLeft,
408    /// <kbd>Alt</kbd>, <kbd>Option</kbd>, or <kbd>⌥</kbd>.
409    /// This is labeled <kbd>AltGr</kbd> on many keyboard layouts.
410    AltRight,
411    /// <kbd>Backspace</kbd> or <kbd>⌫</kbd>.
412    /// Labeled <kbd>Delete</kbd> on Apple keyboards.
413    Backspace,
414    /// <kbd>CapsLock</kbd> or <kbd>⇪</kbd>
415    CapsLock,
416    /// The application context menu key, which is typically found between the right
417    /// <kbd>Super</kbd> key and the right <kbd>Control</kbd> key.
418    ContextMenu,
419    /// <kbd>Control</kbd> or <kbd>⌃</kbd>
420    ControlLeft,
421    /// <kbd>Control</kbd> or <kbd>⌃</kbd>
422    ControlRight,
423    /// <kbd>Enter</kbd> or <kbd>↵</kbd>. Labeled <kbd>Return</kbd> on Apple keyboards.
424    Enter,
425    /// The Windows, <kbd>⌘</kbd>, <kbd>Command</kbd>, or other OS symbol key.
426    SuperLeft,
427    /// The Windows, <kbd>⌘</kbd>, <kbd>Command</kbd>, or other OS symbol key.
428    SuperRight,
429    /// <kbd>Shift</kbd> or <kbd>⇧</kbd>
430    ShiftLeft,
431    /// <kbd>Shift</kbd> or <kbd>⇧</kbd>
432    ShiftRight,
433    /// <kbd> </kbd> (space)
434    Space,
435    /// <kbd>Tab</kbd> or <kbd>⇥</kbd>
436    Tab,
437    /// Japanese: <kbd>変</kbd> (henkan)
438    Convert,
439    /// Japanese: <kbd>カタカナ</kbd>/<kbd>ひらがな</kbd>/<kbd>ローマ字</kbd>
440    /// (katakana/hiragana/romaji)
441    KanaMode,
442    /// Korean: HangulMode <kbd>한/영</kbd> (han/yeong)
443    ///
444    /// Japanese (Mac keyboard): <kbd>か</kbd> (kana)
445    Lang1,
446    /// Korean: Hanja <kbd>한</kbd> (hanja)
447    ///
448    /// Japanese (Mac keyboard): <kbd>英</kbd> (eisu)
449    Lang2,
450    /// Japanese (word-processing keyboard): Katakana
451    Lang3,
452    /// Japanese (word-processing keyboard): Hiragana
453    Lang4,
454    /// Japanese (word-processing keyboard): Zenkaku/Hankaku
455    Lang5,
456    /// Japanese: <kbd>無変換</kbd> (muhenkan)
457    NonConvert,
458    /// <kbd>⌦</kbd>. The forward delete key.
459    /// Note that on Apple keyboards, the key labelled <kbd>Delete</kbd> on the main part of
460    /// the keyboard is encoded as [`Backspace`].
461    ///
462    /// [`Backspace`]: Self::Backspace
463    Delete,
464    /// <kbd>Page Down</kbd>, <kbd>End</kbd>, or <kbd>↘</kbd>
465    End,
466    /// <kbd>Help</kbd>. Not present on standard PC keyboards.
467    Help,
468    /// <kbd>Home</kbd> or <kbd>↖</kbd>
469    Home,
470    /// <kbd>Insert</kbd> or <kbd>Ins</kbd>. Not present on Apple keyboards.
471    Insert,
472    /// <kbd>Page Down</kbd>, <kbd>PgDn</kbd>, or <kbd>⇟</kbd>
473    PageDown,
474    /// <kbd>Page Up</kbd>, <kbd>PgUp</kbd>, or <kbd>⇞</kbd>
475    PageUp,
476    /// <kbd>↓</kbd>
477    ArrowDown,
478    /// <kbd>←</kbd>
479    ArrowLeft,
480    /// <kbd>→</kbd>
481    ArrowRight,
482    /// <kbd>↑</kbd>
483    ArrowUp,
484    /// On the Mac, this is used for the numpad <kbd>Clear</kbd> key.
485    NumLock,
486    /// <kbd>0 Ins</kbd> on a keyboard. <kbd>0</kbd> on a phone or remote control
487    Numpad0,
488    /// <kbd>1 End</kbd> on a keyboard. <kbd>1</kbd> or <kbd>1 QZ</kbd> on a phone or remote
489    /// control
490    Numpad1,
491    /// <kbd>2 ↓</kbd> on a keyboard. <kbd>2 ABC</kbd> on a phone or remote control
492    Numpad2,
493    /// <kbd>3 PgDn</kbd> on a keyboard. <kbd>3 DEF</kbd> on a phone or remote control
494    Numpad3,
495    /// <kbd>4 ←</kbd> on a keyboard. <kbd>4 GHI</kbd> on a phone or remote control
496    Numpad4,
497    /// <kbd>5</kbd> on a keyboard. <kbd>5 JKL</kbd> on a phone or remote control
498    Numpad5,
499    /// <kbd>6 →</kbd> on a keyboard. <kbd>6 MNO</kbd> on a phone or remote control
500    Numpad6,
501    /// <kbd>7 Home</kbd> on a keyboard. <kbd>7 PQRS</kbd> or <kbd>7 PRS</kbd> on a phone
502    /// or remote control
503    Numpad7,
504    /// <kbd>8 ↑</kbd> on a keyboard. <kbd>8 TUV</kbd> on a phone or remote control
505    Numpad8,
506    /// <kbd>9 PgUp</kbd> on a keyboard. <kbd>9 WXYZ</kbd> or <kbd>9 WXY</kbd> on a phone
507    /// or remote control
508    Numpad9,
509    /// <kbd>+</kbd>
510    NumpadAdd,
511    /// Found on the Microsoft Natural Keyboard.
512    NumpadBackspace,
513    /// <kbd>C</kbd> or <kbd>A</kbd> (All Clear). Also for use with numpads that have a
514    /// <kbd>Clear</kbd> key that is separate from the <kbd>NumLock</kbd> key. On the Mac, the
515    /// numpad <kbd>Clear</kbd> key is encoded as [`NumLock`].
516    ///
517    /// [`NumLock`]: Self::NumLock
518    NumpadClear,
519    /// <kbd>C</kbd> (Clear Entry)
520    NumpadClearEntry,
521    /// <kbd>,</kbd> (thousands separator). For locales where the thousands separator
522    /// is a "." (e.g., Brazil), this key may generate a <kbd>.</kbd>.
523    NumpadComma,
524    /// <kbd>. Del</kbd>. For locales where the decimal separator is "," (e.g.,
525    /// Brazil), this key may generate a <kbd>,</kbd>.
526    NumpadDecimal,
527    /// <kbd>/</kbd>
528    NumpadDivide,
529    NumpadEnter,
530    /// <kbd>=</kbd>
531    NumpadEqual,
532    /// <kbd>#</kbd> on a phone or remote control device. This key is typically found
533    /// below the <kbd>9</kbd> key and to the right of the <kbd>0</kbd> key.
534    NumpadHash,
535    /// <kbd>M</kbd> Add current entry to the value stored in memory.
536    NumpadMemoryAdd,
537    /// <kbd>M</kbd> Clear the value stored in memory.
538    NumpadMemoryClear,
539    /// <kbd>M</kbd> Replace the current entry with the value stored in memory.
540    NumpadMemoryRecall,
541    /// <kbd>M</kbd> Replace the value stored in memory with the current entry.
542    NumpadMemoryStore,
543    /// <kbd>M</kbd> Subtract current entry from the value stored in memory.
544    NumpadMemorySubtract,
545    /// <kbd>*</kbd> on a keyboard. For use with numpads that provide mathematical
546    /// operations (<kbd>+</kbd>, <kbd>-</kbd> <kbd>*</kbd> and <kbd>/</kbd>).
547    ///
548    /// Use `NumpadStar` for the <kbd>*</kbd> key on phones and remote controls.
549    NumpadMultiply,
550    /// <kbd>(</kbd> Found on the Microsoft Natural Keyboard.
551    NumpadParenLeft,
552    /// <kbd>)</kbd> Found on the Microsoft Natural Keyboard.
553    NumpadParenRight,
554    /// <kbd>*</kbd> on a phone or remote control device.
555    ///
556    /// This key is typically found below the <kbd>7</kbd> key and to the left of
557    /// the <kbd>0</kbd> key.
558    ///
559    /// Use <kbd>"NumpadMultiply"</kbd> for the <kbd>*</kbd> key on
560    /// numeric keypads.
561    NumpadStar,
562    /// <kbd>-</kbd>
563    NumpadSubtract,
564    /// <kbd>Esc</kbd> or <kbd>⎋</kbd>
565    Escape,
566    /// <kbd>Fn</kbd> This is typically a hardware key that does not generate a separate code.
567    Fn,
568    /// <kbd>FLock</kbd> or <kbd>FnLock</kbd>. Function Lock key. Found on the Microsoft
569    /// Natural Keyboard.
570    FnLock,
571    /// <kbd>PrtScr SysRq</kbd> or <kbd>Print Screen</kbd>
572    PrintScreen,
573    /// <kbd>Scroll Lock</kbd>
574    ScrollLock,
575    /// <kbd>Pause Break</kbd>
576    Pause,
577    /// Some laptops place this key to the left of the <kbd>↑</kbd> key.
578    ///
579    /// This also the "back" button (triangle) on Android.
580    BrowserBack,
581    BrowserFavorites,
582    /// Some laptops place this key to the right of the <kbd>↑</kbd> key.
583    BrowserForward,
584    /// The "home" button on Android.
585    BrowserHome,
586    BrowserRefresh,
587    BrowserSearch,
588    BrowserStop,
589    /// <kbd>Eject</kbd> or <kbd>⏏</kbd>. This key is placed in the function section on some Apple
590    /// keyboards.
591    Eject,
592    /// Sometimes labelled <kbd>My Computer</kbd> on the keyboard
593    LaunchApp1,
594    /// Sometimes labelled <kbd>Calculator</kbd> on the keyboard
595    LaunchApp2,
596    LaunchMail,
597    MediaPlayPause,
598    MediaSelect,
599    MediaStop,
600    MediaTrackNext,
601    MediaTrackPrevious,
602    /// This key is placed in the function section on some Apple keyboards, replacing the
603    /// <kbd>Eject</kbd> key.
604    Power,
605    Sleep,
606    AudioVolumeDown,
607    AudioVolumeMute,
608    AudioVolumeUp,
609    WakeUp,
610    // Legacy modifier key. Also called "Super" in certain places.
611    Meta,
612    // Legacy modifier key.
613    Hyper,
614    Turbo,
615    Abort,
616    Resume,
617    Suspend,
618    /// Found on Sun’s USB keyboard.
619    Again,
620    /// Found on Sun’s USB keyboard.
621    Copy,
622    /// Found on Sun’s USB keyboard.
623    Cut,
624    /// Found on Sun’s USB keyboard.
625    Find,
626    /// Found on Sun’s USB keyboard.
627    Open,
628    /// Found on Sun’s USB keyboard.
629    Paste,
630    /// Found on Sun’s USB keyboard.
631    Props,
632    /// Found on Sun’s USB keyboard.
633    Select,
634    /// Found on Sun’s USB keyboard.
635    Undo,
636    /// Use for dedicated <kbd>ひらがな</kbd> key found on some Japanese word processing keyboards.
637    Hiragana,
638    /// Use for dedicated <kbd>カタカナ</kbd> key found on some Japanese word processing keyboards.
639    Katakana,
640    /// General-purpose function key.
641    /// Usually found at the top of the keyboard.
642    F1,
643    /// General-purpose function key.
644    /// Usually found at the top of the keyboard.
645    F2,
646    /// General-purpose function key.
647    /// Usually found at the top of the keyboard.
648    F3,
649    /// General-purpose function key.
650    /// Usually found at the top of the keyboard.
651    F4,
652    /// General-purpose function key.
653    /// Usually found at the top of the keyboard.
654    F5,
655    /// General-purpose function key.
656    /// Usually found at the top of the keyboard.
657    F6,
658    /// General-purpose function key.
659    /// Usually found at the top of the keyboard.
660    F7,
661    /// General-purpose function key.
662    /// Usually found at the top of the keyboard.
663    F8,
664    /// General-purpose function key.
665    /// Usually found at the top of the keyboard.
666    F9,
667    /// General-purpose function key.
668    /// Usually found at the top of the keyboard.
669    F10,
670    /// General-purpose function key.
671    /// Usually found at the top of the keyboard.
672    F11,
673    /// General-purpose function key.
674    /// Usually found at the top of the keyboard.
675    F12,
676    /// General-purpose function key.
677    /// Usually found at the top of the keyboard.
678    F13,
679    /// General-purpose function key.
680    /// Usually found at the top of the keyboard.
681    F14,
682    /// General-purpose function key.
683    /// Usually found at the top of the keyboard.
684    F15,
685    /// General-purpose function key.
686    /// Usually found at the top of the keyboard.
687    F16,
688    /// General-purpose function key.
689    /// Usually found at the top of the keyboard.
690    F17,
691    /// General-purpose function key.
692    /// Usually found at the top of the keyboard.
693    F18,
694    /// General-purpose function key.
695    /// Usually found at the top of the keyboard.
696    F19,
697    /// General-purpose function key.
698    /// Usually found at the top of the keyboard.
699    F20,
700    /// General-purpose function key.
701    /// Usually found at the top of the keyboard.
702    F21,
703    /// General-purpose function key.
704    /// Usually found at the top of the keyboard.
705    F22,
706    /// General-purpose function key.
707    /// Usually found at the top of the keyboard.
708    F23,
709    /// General-purpose function key.
710    /// Usually found at the top of the keyboard.
711    F24,
712    /// General-purpose function key.
713    F25,
714    /// General-purpose function key.
715    F26,
716    /// General-purpose function key.
717    F27,
718    /// General-purpose function key.
719    F28,
720    /// General-purpose function key.
721    F29,
722    /// General-purpose function key.
723    F30,
724    /// General-purpose function key.
725    F31,
726    /// General-purpose function key.
727    F32,
728    /// General-purpose function key.
729    F33,
730    /// General-purpose function key.
731    F34,
732    /// General-purpose function key.
733    F35,
734}
735
736/// A [`Key::Named`] value
737///
738/// This mostly conforms to the UI Events Specification's [`KeyboardEvent.key`] with a few
739/// exceptions:
740/// - The `Super` variant here, is named `Meta` in the aforementioned specification. (There's
741///   another key which the specification calls `Super`. That does not exist here.)
742/// - The `Space` variant here, can be identified by the character it generates in the
743///   specification.
744///
745/// [`KeyboardEvent.key`]: https://w3c.github.io/uievents-key/
746#[non_exhaustive]
747#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
748pub enum NamedKey {
749    /// The `Alt` (Alternative) key.
750    ///
751    /// This key enables the alternate modifier function for interpreting concurrent or subsequent
752    /// keyboard input. This key value is also used for the Apple <kbd>Option</kbd> key.
753    Alt,
754    /// The Alternate Graphics (<kbd>AltGr</kbd> or <kbd>AltGraph</kbd>) key.
755    ///
756    /// This key is used enable the ISO Level 3 shift modifier (the standard `Shift` key is the
757    /// level 2 modifier).
758    AltGraph,
759    /// The `Caps Lock` (Capital) key.
760    ///
761    /// Toggle capital character lock function for interpreting subsequent keyboard input event.
762    CapsLock,
763    /// The `Control` or `Ctrl` key.
764    ///
765    /// Used to enable control modifier function for interpreting concurrent or subsequent keyboard
766    /// input.
767    Control,
768    /// The Function switch `Fn` key. Activating this key simultaneously with another key changes
769    /// that key’s value to an alternate character or function. This key is often handled directly
770    /// in the keyboard hardware and does not usually generate key events.
771    Fn,
772    /// The Function-Lock (`FnLock` or `F-Lock`) key. Activating this key switches the mode of the
773    /// keyboard to changes some keys' values to an alternate character or function. This key is
774    /// often handled directly in the keyboard hardware and does not usually generate key events.
775    FnLock,
776    /// The `NumLock` or Number Lock key. Used to toggle numpad mode function for interpreting
777    /// subsequent keyboard input.
778    NumLock,
779    /// Toggle between scrolling and cursor movement modes.
780    ScrollLock,
781    /// Used to enable shift modifier function for interpreting concurrent or subsequent keyboard
782    /// input.
783    Shift,
784    /// The Symbol modifier key (used on some virtual keyboards).
785    Symbol,
786    SymbolLock,
787    // Legacy modifier key. Also called "Super" in certain places.
788    Meta,
789    // Legacy modifier key.
790    Hyper,
791    /// Used to enable "super" modifier function for interpreting concurrent or subsequent keyboard
792    /// input. This key value is used for the "Windows Logo" key and the Apple `Command` or `⌘`
793    /// key.
794    ///
795    /// Note: In some contexts (e.g. the Web) this is referred to as the "Meta" key.
796    Super,
797    /// The `Enter` or `↵` key. Used to activate current selection or accept current input. This
798    /// key value is also used for the `Return` (Macintosh numpad) key. This key value is also
799    /// used for the Android `KEYCODE_DPAD_CENTER`.
800    Enter,
801    /// The Horizontal Tabulation `Tab` key.
802    Tab,
803    /// Used in text to insert a space between words. Usually located below the character keys.
804    Space,
805    /// Navigate or traverse downward. (`KEYCODE_DPAD_DOWN`)
806    ArrowDown,
807    /// Navigate or traverse leftward. (`KEYCODE_DPAD_LEFT`)
808    ArrowLeft,
809    /// Navigate or traverse rightward. (`KEYCODE_DPAD_RIGHT`)
810    ArrowRight,
811    /// Navigate or traverse upward. (`KEYCODE_DPAD_UP`)
812    ArrowUp,
813    /// The End key, used with keyboard entry to go to the end of content (`KEYCODE_MOVE_END`).
814    End,
815    /// The Home key, used with keyboard entry, to go to start of content (`KEYCODE_MOVE_HOME`).
816    /// For the mobile phone `Home` key (which goes to the phone’s main screen), use [`GoHome`].
817    ///
818    /// [`GoHome`]: Self::GoHome
819    Home,
820    /// Scroll down or display next page of content.
821    PageDown,
822    /// Scroll up or display previous page of content.
823    PageUp,
824    /// Used to remove the character to the left of the cursor. This key value is also used for
825    /// the key labeled `Delete` on MacOS keyboards.
826    Backspace,
827    /// Remove the currently selected input.
828    Clear,
829    /// Copy the current selection. (`APPCOMMAND_COPY`)
830    Copy,
831    /// The Cursor Select key.
832    CrSel,
833    /// Cut the current selection. (`APPCOMMAND_CUT`)
834    Cut,
835    /// Used to delete the character to the right of the cursor. This key value is also used for
836    /// the key labeled `Delete` on MacOS keyboards when `Fn` is active.
837    Delete,
838    /// The Erase to End of Field key. This key deletes all characters from the current cursor
839    /// position to the end of the current field.
840    EraseEof,
841    /// The Extend Selection (Exsel) key.
842    ExSel,
843    /// Toggle between text modes for insertion or overtyping.
844    /// (`KEYCODE_INSERT`)
845    Insert,
846    /// The Paste key. (`APPCOMMAND_PASTE`)
847    Paste,
848    /// Redo the last action. (`APPCOMMAND_REDO`)
849    Redo,
850    /// Undo the last action. (`APPCOMMAND_UNDO`)
851    Undo,
852    /// The Accept (Commit, OK) key. Accept current option or input method sequence conversion.
853    Accept,
854    /// Redo or repeat an action.
855    Again,
856    /// The Attention (Attn) key.
857    Attn,
858    Cancel,
859    /// Show the application’s context menu.
860    /// This key is commonly found between the right `Super` key and the right `Control` key.
861    ContextMenu,
862    /// The `Esc` key. This key was originally used to initiate an escape sequence, but is
863    /// now more generally used to exit or "escape" the current context, such as closing a dialog
864    /// or exiting full screen mode.
865    Escape,
866    Execute,
867    /// Open the Find dialog. (`APPCOMMAND_FIND`)
868    Find,
869    /// Open a help dialog or toggle display of help information. (`APPCOMMAND_HELP`,
870    /// `KEYCODE_HELP`)
871    Help,
872    /// Pause the current state or application (as appropriate).
873    ///
874    /// Note: Do not use this value for the `Pause` button on media controllers. Use `"MediaPause"`
875    /// instead.
876    Pause,
877    /// Play or resume the current state or application (as appropriate).
878    ///
879    /// Note: Do not use this value for the `Play` button on media controllers. Use `"MediaPlay"`
880    /// instead.
881    Play,
882    /// The properties (Props) key.
883    Props,
884    Select,
885    /// The ZoomIn key. (`KEYCODE_ZOOM_IN`)
886    ZoomIn,
887    /// The ZoomOut key. (`KEYCODE_ZOOM_OUT`)
888    ZoomOut,
889    /// The Brightness Down key. Typically controls the display brightness.
890    /// (`KEYCODE_BRIGHTNESS_DOWN`)
891    BrightnessDown,
892    /// The Brightness Up key. Typically controls the display brightness. (`KEYCODE_BRIGHTNESS_UP`)
893    BrightnessUp,
894    /// Toggle removable media to eject (open) and insert (close) state. (`KEYCODE_MEDIA_EJECT`)
895    Eject,
896    LogOff,
897    /// Toggle power state. (`KEYCODE_POWER`)
898    /// Note: Note: Some devices might not expose this key to the operating environment.
899    Power,
900    /// The `PowerOff` key. Sometime called `PowerDown`.
901    PowerOff,
902    /// Initiate print-screen function.
903    PrintScreen,
904    /// The Hibernate key. This key saves the current state of the computer to disk so that it can
905    /// be restored. The computer will then shutdown.
906    Hibernate,
907    /// The Standby key. This key turns off the display and places the computer into a low-power
908    /// mode without completely shutting down. It is sometimes labelled `Suspend` or `Sleep` key.
909    /// (`KEYCODE_SLEEP`)
910    Standby,
911    /// The WakeUp key. (`KEYCODE_WAKEUP`)
912    WakeUp,
913    /// Initiate the multi-candidate mode.
914    AllCandidates,
915    Alphanumeric,
916    /// Initiate the Code Input mode to allow characters to be entered by
917    /// their code points.
918    CodeInput,
919    /// The Compose key, also known as "Multi_key" on the X Window System. This key acts in a
920    /// manner similar to a dead key, triggering a mode where subsequent key presses are combined
921    /// to produce a different character.
922    Compose,
923    /// Convert the current input method sequence.
924    Convert,
925    /// The Final Mode `Final` key used on some Asian keyboards, to enable the final mode for IMEs.
926    FinalMode,
927    /// Switch to the first character group. (ISO/IEC 9995)
928    GroupFirst,
929    /// Switch to the last character group. (ISO/IEC 9995)
930    GroupLast,
931    /// Switch to the next character group. (ISO/IEC 9995)
932    GroupNext,
933    /// Switch to the previous character group. (ISO/IEC 9995)
934    GroupPrevious,
935    /// Toggle between or cycle through input modes of IMEs.
936    ModeChange,
937    NextCandidate,
938    /// Accept current input method sequence without
939    /// conversion in IMEs.
940    NonConvert,
941    PreviousCandidate,
942    Process,
943    SingleCandidate,
944    /// Toggle between Hangul and English modes.
945    HangulMode,
946    HanjaMode,
947    JunjaMode,
948    /// The Eisu key. This key may close the IME, but its purpose is defined by the current IME.
949    /// (`KEYCODE_EISU`)
950    Eisu,
951    /// The (Half-Width) Characters key.
952    Hankaku,
953    /// The Hiragana (Japanese Kana characters) key.
954    Hiragana,
955    /// The Hiragana/Katakana toggle key. (`KEYCODE_KATAKANA_HIRAGANA`)
956    HiraganaKatakana,
957    /// The Kana Mode (Kana Lock) key. This key is used to enter hiragana mode (typically from
958    /// romaji mode).
959    KanaMode,
960    /// The Kanji (Japanese name for ideographic characters of Chinese origin) Mode key. This key
961    /// is typically used to switch to a hiragana keyboard for the purpose of converting input
962    /// into kanji. (`KEYCODE_KANA`)
963    KanjiMode,
964    /// The Katakana (Japanese Kana characters) key.
965    Katakana,
966    /// The Roman characters function key.
967    Romaji,
968    /// The Zenkaku (Full-Width) Characters key.
969    Zenkaku,
970    /// The Zenkaku/Hankaku (full-width/half-width) toggle key. (`KEYCODE_ZENKAKU_HANKAKU`)
971    ZenkakuHankaku,
972    /// General purpose virtual function key, as index 1.
973    Soft1,
974    /// General purpose virtual function key, as index 2.
975    Soft2,
976    /// General purpose virtual function key, as index 3.
977    Soft3,
978    /// General purpose virtual function key, as index 4.
979    Soft4,
980    /// Select next (numerically or logically) lower channel. (`APPCOMMAND_MEDIA_CHANNEL_DOWN`,
981    /// `KEYCODE_CHANNEL_DOWN`)
982    ChannelDown,
983    /// Select next (numerically or logically) higher channel. (`APPCOMMAND_MEDIA_CHANNEL_UP`,
984    /// `KEYCODE_CHANNEL_UP`)
985    ChannelUp,
986    /// Close the current document or message (Note: This doesn’t close the application).
987    /// (`APPCOMMAND_CLOSE`)
988    Close,
989    /// Open an editor to forward the current message. (`APPCOMMAND_FORWARD_MAIL`)
990    MailForward,
991    /// Open an editor to reply to the current message. (`APPCOMMAND_REPLY_TO_MAIL`)
992    MailReply,
993    /// Send the current message. (`APPCOMMAND_SEND_MAIL`)
994    MailSend,
995    /// Close the current media, for example to close a CD or DVD tray. (`KEYCODE_MEDIA_CLOSE`)
996    MediaClose,
997    /// Initiate or continue forward playback at faster than normal speed, or increase speed if
998    /// already fast forwarding. (`APPCOMMAND_MEDIA_FAST_FORWARD`, `KEYCODE_MEDIA_FAST_FORWARD`)
999    MediaFastForward,
1000    /// Pause the currently playing media. (`APPCOMMAND_MEDIA_PAUSE`, `KEYCODE_MEDIA_PAUSE`)
1001    ///
1002    /// Note: Media controller devices should use this value rather than `"Pause"` for their pause
1003    /// keys.
1004    MediaPause,
1005    /// Initiate or continue media playback at normal speed, if not currently playing at normal
1006    /// speed. (`APPCOMMAND_MEDIA_PLAY`, `KEYCODE_MEDIA_PLAY`)
1007    MediaPlay,
1008    /// Toggle media between play and pause states. (`APPCOMMAND_MEDIA_PLAY_PAUSE`,
1009    /// `KEYCODE_MEDIA_PLAY_PAUSE`)
1010    MediaPlayPause,
1011    /// Initiate or resume recording of currently selected media. (`APPCOMMAND_MEDIA_RECORD`,
1012    /// `KEYCODE_MEDIA_RECORD`)
1013    MediaRecord,
1014    /// Initiate or continue reverse playback at faster than normal speed, or increase speed if
1015    /// already rewinding. (`APPCOMMAND_MEDIA_REWIND`, `KEYCODE_MEDIA_REWIND`)
1016    MediaRewind,
1017    /// Stop media playing, pausing, forwarding, rewinding, or recording, if not already stopped.
1018    /// (`APPCOMMAND_MEDIA_STOP`, `KEYCODE_MEDIA_STOP`)
1019    MediaStop,
1020    /// Seek to next media or program track. (`APPCOMMAND_MEDIA_NEXTTRACK`, `KEYCODE_MEDIA_NEXT`)
1021    MediaTrackNext,
1022    /// Seek to previous media or program track. (`APPCOMMAND_MEDIA_PREVIOUSTRACK`,
1023    /// `KEYCODE_MEDIA_PREVIOUS`)
1024    MediaTrackPrevious,
1025    /// Open a new document or message. (`APPCOMMAND_NEW`)
1026    New,
1027    /// Open an existing document or message. (`APPCOMMAND_OPEN`)
1028    Open,
1029    /// Print the current document or message. (`APPCOMMAND_PRINT`)
1030    Print,
1031    /// Save the current document or message. (`APPCOMMAND_SAVE`)
1032    Save,
1033    /// Spellcheck the current document or selection. (`APPCOMMAND_SPELL_CHECK`)
1034    SpellCheck,
1035    /// The `11` key found on media numpads that
1036    /// have buttons from `1` ... `12`.
1037    Key11,
1038    /// The `12` key found on media numpads that
1039    /// have buttons from `1` ... `12`.
1040    Key12,
1041    /// Adjust audio balance leftward. (`VK_AUDIO_BALANCE_LEFT`)
1042    AudioBalanceLeft,
1043    /// Adjust audio balance rightward. (`VK_AUDIO_BALANCE_RIGHT`)
1044    AudioBalanceRight,
1045    /// Decrease audio bass boost or cycle down through bass boost states. (`APPCOMMAND_BASS_DOWN`,
1046    /// `VK_BASS_BOOST_DOWN`)
1047    AudioBassBoostDown,
1048    /// Toggle bass boost on/off. (`APPCOMMAND_BASS_BOOST`)
1049    AudioBassBoostToggle,
1050    /// Increase audio bass boost or cycle up through bass boost states. (`APPCOMMAND_BASS_UP`,
1051    /// `VK_BASS_BOOST_UP`)
1052    AudioBassBoostUp,
1053    /// Adjust audio fader towards front. (`VK_FADER_FRONT`)
1054    AudioFaderFront,
1055    /// Adjust audio fader towards rear. (`VK_FADER_REAR`)
1056    AudioFaderRear,
1057    /// Advance surround audio mode to next available mode. (`VK_SURROUND_MODE_NEXT`)
1058    AudioSurroundModeNext,
1059    /// Decrease treble. (`APPCOMMAND_TREBLE_DOWN`)
1060    AudioTrebleDown,
1061    /// Increase treble. (`APPCOMMAND_TREBLE_UP`)
1062    AudioTrebleUp,
1063    /// Decrease audio volume. (`APPCOMMAND_VOLUME_DOWN`, `KEYCODE_VOLUME_DOWN`)
1064    AudioVolumeDown,
1065    /// Increase audio volume. (`APPCOMMAND_VOLUME_UP`, `KEYCODE_VOLUME_UP`)
1066    AudioVolumeUp,
1067    /// Toggle between muted state and prior volume level. (`APPCOMMAND_VOLUME_MUTE`,
1068    /// `KEYCODE_VOLUME_MUTE`)
1069    AudioVolumeMute,
1070    /// Toggle the microphone on/off. (`APPCOMMAND_MIC_ON_OFF_TOGGLE`)
1071    MicrophoneToggle,
1072    /// Decrease microphone volume. (`APPCOMMAND_MICROPHONE_VOLUME_DOWN`)
1073    MicrophoneVolumeDown,
1074    /// Increase microphone volume. (`APPCOMMAND_MICROPHONE_VOLUME_UP`)
1075    MicrophoneVolumeUp,
1076    /// Mute the microphone. (`APPCOMMAND_MICROPHONE_VOLUME_MUTE`, `KEYCODE_MUTE`)
1077    MicrophoneVolumeMute,
1078    /// Show correction list when a word is incorrectly identified. (`APPCOMMAND_CORRECTION_LIST`)
1079    SpeechCorrectionList,
1080    /// Toggle between dictation mode and command/control mode.
1081    /// (`APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE`)
1082    SpeechInputToggle,
1083    /// The first generic "LaunchApplication" key. This is commonly associated with launching "My
1084    /// Computer", and may have a computer symbol on the key. (`APPCOMMAND_LAUNCH_APP1`)
1085    LaunchApplication1,
1086    /// The second generic "LaunchApplication" key. This is commonly associated with launching
1087    /// "Calculator", and may have a calculator symbol on the key. (`APPCOMMAND_LAUNCH_APP2`,
1088    /// `KEYCODE_CALCULATOR`)
1089    LaunchApplication2,
1090    /// The "Calendar" key. (`KEYCODE_CALENDAR`)
1091    LaunchCalendar,
1092    /// The "Contacts" key. (`KEYCODE_CONTACTS`)
1093    LaunchContacts,
1094    /// The "Mail" key. (`APPCOMMAND_LAUNCH_MAIL`)
1095    LaunchMail,
1096    /// The "Media Player" key. (`APPCOMMAND_LAUNCH_MEDIA_SELECT`)
1097    LaunchMediaPlayer,
1098    LaunchMusicPlayer,
1099    LaunchPhone,
1100    LaunchScreenSaver,
1101    LaunchSpreadsheet,
1102    LaunchWebBrowser,
1103    LaunchWebCam,
1104    LaunchWordProcessor,
1105    /// Navigate to previous content or page in current history. (`APPCOMMAND_BROWSER_BACKWARD`)
1106    BrowserBack,
1107    /// Open the list of browser favorites. (`APPCOMMAND_BROWSER_FAVORITES`)
1108    BrowserFavorites,
1109    /// Navigate to next content or page in current history. (`APPCOMMAND_BROWSER_FORWARD`)
1110    BrowserForward,
1111    /// Go to the user’s preferred home page. (`APPCOMMAND_BROWSER_HOME`)
1112    BrowserHome,
1113    /// Refresh the current page or content. (`APPCOMMAND_BROWSER_REFRESH`)
1114    BrowserRefresh,
1115    /// Call up the user’s preferred search page. (`APPCOMMAND_BROWSER_SEARCH`)
1116    BrowserSearch,
1117    /// Stop loading the current page or content. (`APPCOMMAND_BROWSER_STOP`)
1118    BrowserStop,
1119    /// The Application switch key, which provides a list of recent apps to switch between.
1120    /// (`KEYCODE_APP_SWITCH`)
1121    AppSwitch,
1122    /// The Call key. (`KEYCODE_CALL`)
1123    Call,
1124    /// The Camera key. (`KEYCODE_CAMERA`)
1125    Camera,
1126    /// The Camera focus key. (`KEYCODE_FOCUS`)
1127    CameraFocus,
1128    /// The End Call key. (`KEYCODE_ENDCALL`)
1129    EndCall,
1130    /// The Back key. (`KEYCODE_BACK`)
1131    GoBack,
1132    /// The Home key, which goes to the phone’s main screen. (`KEYCODE_HOME`)
1133    GoHome,
1134    /// The Headset Hook key. (`KEYCODE_HEADSETHOOK`)
1135    HeadsetHook,
1136    LastNumberRedial,
1137    /// The Notification key. (`KEYCODE_NOTIFICATION`)
1138    Notification,
1139    /// Toggle between manner mode state: silent, vibrate, ring, ... (`KEYCODE_MANNER_MODE`)
1140    MannerMode,
1141    VoiceDial,
1142    /// Switch to viewing TV. (`KEYCODE_TV`)
1143    TV,
1144    /// TV 3D Mode. (`KEYCODE_3D_MODE`)
1145    TV3DMode,
1146    /// Toggle between antenna and cable input. (`KEYCODE_TV_ANTENNA_CABLE`)
1147    TVAntennaCable,
1148    /// Audio description. (`KEYCODE_TV_AUDIO_DESCRIPTION`)
1149    TVAudioDescription,
1150    /// Audio description mixing volume down. (`KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN`)
1151    TVAudioDescriptionMixDown,
1152    /// Audio description mixing volume up. (`KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP`)
1153    TVAudioDescriptionMixUp,
1154    /// Contents menu. (`KEYCODE_TV_CONTENTS_MENU`)
1155    TVContentsMenu,
1156    /// Contents menu. (`KEYCODE_TV_DATA_SERVICE`)
1157    TVDataService,
1158    /// Switch the input mode on an external TV. (`KEYCODE_TV_INPUT`)
1159    TVInput,
1160    /// Switch to component input #1. (`KEYCODE_TV_INPUT_COMPONENT_1`)
1161    TVInputComponent1,
1162    /// Switch to component input #2. (`KEYCODE_TV_INPUT_COMPONENT_2`)
1163    TVInputComponent2,
1164    /// Switch to composite input #1. (`KEYCODE_TV_INPUT_COMPOSITE_1`)
1165    TVInputComposite1,
1166    /// Switch to composite input #2. (`KEYCODE_TV_INPUT_COMPOSITE_2`)
1167    TVInputComposite2,
1168    /// Switch to HDMI input #1. (`KEYCODE_TV_INPUT_HDMI_1`)
1169    TVInputHDMI1,
1170    /// Switch to HDMI input #2. (`KEYCODE_TV_INPUT_HDMI_2`)
1171    TVInputHDMI2,
1172    /// Switch to HDMI input #3. (`KEYCODE_TV_INPUT_HDMI_3`)
1173    TVInputHDMI3,
1174    /// Switch to HDMI input #4. (`KEYCODE_TV_INPUT_HDMI_4`)
1175    TVInputHDMI4,
1176    /// Switch to VGA input #1. (`KEYCODE_TV_INPUT_VGA_1`)
1177    TVInputVGA1,
1178    /// Media context menu. (`KEYCODE_TV_MEDIA_CONTEXT_MENU`)
1179    TVMediaContext,
1180    /// Toggle network. (`KEYCODE_TV_NETWORK`)
1181    TVNetwork,
1182    /// Number entry. (`KEYCODE_TV_NUMBER_ENTRY`)
1183    TVNumberEntry,
1184    /// Toggle the power on an external TV. (`KEYCODE_TV_POWER`)
1185    TVPower,
1186    /// Radio. (`KEYCODE_TV_RADIO_SERVICE`)
1187    TVRadioService,
1188    /// Satellite. (`KEYCODE_TV_SATELLITE`)
1189    TVSatellite,
1190    /// Broadcast Satellite. (`KEYCODE_TV_SATELLITE_BS`)
1191    TVSatelliteBS,
1192    /// Communication Satellite. (`KEYCODE_TV_SATELLITE_CS`)
1193    TVSatelliteCS,
1194    /// Toggle between available satellites. (`KEYCODE_TV_SATELLITE_SERVICE`)
1195    TVSatelliteToggle,
1196    /// Analog Terrestrial. (`KEYCODE_TV_TERRESTRIAL_ANALOG`)
1197    TVTerrestrialAnalog,
1198    /// Digital Terrestrial. (`KEYCODE_TV_TERRESTRIAL_DIGITAL`)
1199    TVTerrestrialDigital,
1200    /// Timer programming. (`KEYCODE_TV_TIMER_PROGRAMMING`)
1201    TVTimer,
1202    /// Switch the input mode on an external AVR (audio/video receiver). (`KEYCODE_AVR_INPUT`)
1203    AVRInput,
1204    /// Toggle the power on an external AVR (audio/video receiver). (`KEYCODE_AVR_POWER`)
1205    AVRPower,
1206    /// General purpose color-coded media function key, as index 0 (red). (`VK_COLORED_KEY_0`,
1207    /// `KEYCODE_PROG_RED`)
1208    ColorF0Red,
1209    /// General purpose color-coded media function key, as index 1 (green). (`VK_COLORED_KEY_1`,
1210    /// `KEYCODE_PROG_GREEN`)
1211    ColorF1Green,
1212    /// General purpose color-coded media function key, as index 2 (yellow). (`VK_COLORED_KEY_2`,
1213    /// `KEYCODE_PROG_YELLOW`)
1214    ColorF2Yellow,
1215    /// General purpose color-coded media function key, as index 3 (blue). (`VK_COLORED_KEY_3`,
1216    /// `KEYCODE_PROG_BLUE`)
1217    ColorF3Blue,
1218    /// General purpose color-coded media function key, as index 4 (grey). (`VK_COLORED_KEY_4`)
1219    ColorF4Grey,
1220    /// General purpose color-coded media function key, as index 5 (brown). (`VK_COLORED_KEY_5`)
1221    ColorF5Brown,
1222    /// Toggle the display of Closed Captions. (`VK_CC`, `KEYCODE_CAPTIONS`)
1223    ClosedCaptionToggle,
1224    /// Adjust brightness of device, by toggling between or cycling through states. (`VK_DIMMER`)
1225    Dimmer,
1226    /// Swap video sources. (`VK_DISPLAY_SWAP`)
1227    DisplaySwap,
1228    /// Select Digital Video Rrecorder. (`KEYCODE_DVR`)
1229    DVR,
1230    /// Exit the current application. (`VK_EXIT`)
1231    Exit,
1232    /// Clear program or content stored as favorite 0. (`VK_CLEAR_FAVORITE_0`)
1233    FavoriteClear0,
1234    /// Clear program or content stored as favorite 1. (`VK_CLEAR_FAVORITE_1`)
1235    FavoriteClear1,
1236    /// Clear program or content stored as favorite 2. (`VK_CLEAR_FAVORITE_2`)
1237    FavoriteClear2,
1238    /// Clear program or content stored as favorite 3. (`VK_CLEAR_FAVORITE_3`)
1239    FavoriteClear3,
1240    /// Select (recall) program or content stored as favorite 0. (`VK_RECALL_FAVORITE_0`)
1241    FavoriteRecall0,
1242    /// Select (recall) program or content stored as favorite 1. (`VK_RECALL_FAVORITE_1`)
1243    FavoriteRecall1,
1244    /// Select (recall) program or content stored as favorite 2. (`VK_RECALL_FAVORITE_2`)
1245    FavoriteRecall2,
1246    /// Select (recall) program or content stored as favorite 3. (`VK_RECALL_FAVORITE_3`)
1247    FavoriteRecall3,
1248    /// Store current program or content as favorite 0. (`VK_STORE_FAVORITE_0`)
1249    FavoriteStore0,
1250    /// Store current program or content as favorite 1. (`VK_STORE_FAVORITE_1`)
1251    FavoriteStore1,
1252    /// Store current program or content as favorite 2. (`VK_STORE_FAVORITE_2`)
1253    FavoriteStore2,
1254    /// Store current program or content as favorite 3. (`VK_STORE_FAVORITE_3`)
1255    FavoriteStore3,
1256    /// Toggle display of program or content guide. (`VK_GUIDE`, `KEYCODE_GUIDE`)
1257    Guide,
1258    /// If guide is active and displayed, then display next day’s content. (`VK_NEXT_DAY`)
1259    GuideNextDay,
1260    /// If guide is active and displayed, then display previous day’s content. (`VK_PREV_DAY`)
1261    GuidePreviousDay,
1262    /// Toggle display of information about currently selected context or media. (`VK_INFO`,
1263    /// `KEYCODE_INFO`)
1264    Info,
1265    /// Toggle instant replay. (`VK_INSTANT_REPLAY`)
1266    InstantReplay,
1267    /// Launch linked content, if available and appropriate. (`VK_LINK`)
1268    Link,
1269    /// List the current program. (`VK_LIST`)
1270    ListProgram,
1271    /// Toggle display listing of currently available live content or programs. (`VK_LIVE`)
1272    LiveContent,
1273    /// Lock or unlock current content or program. (`VK_LOCK`)
1274    Lock,
1275    /// Show a list of media applications: audio/video players and image viewers. (`VK_APPS`)
1276    ///
1277    /// Note: Do not confuse this key value with the Windows' `VK_APPS` / `VK_CONTEXT_MENU` key,
1278    /// which is encoded as `"ContextMenu"`.
1279    MediaApps,
1280    /// Audio track key. (`KEYCODE_MEDIA_AUDIO_TRACK`)
1281    MediaAudioTrack,
1282    /// Select previously selected channel or media. (`VK_LAST`, `KEYCODE_LAST_CHANNEL`)
1283    MediaLast,
1284    /// Skip backward to next content or program. (`KEYCODE_MEDIA_SKIP_BACKWARD`)
1285    MediaSkipBackward,
1286    /// Skip forward to next content or program. (`VK_SKIP`, `KEYCODE_MEDIA_SKIP_FORWARD`)
1287    MediaSkipForward,
1288    /// Step backward to next content or program. (`KEYCODE_MEDIA_STEP_BACKWARD`)
1289    MediaStepBackward,
1290    /// Step forward to next content or program. (`KEYCODE_MEDIA_STEP_FORWARD`)
1291    MediaStepForward,
1292    /// Media top menu. (`KEYCODE_MEDIA_TOP_MENU`)
1293    MediaTopMenu,
1294    /// Navigate in. (`KEYCODE_NAVIGATE_IN`)
1295    NavigateIn,
1296    /// Navigate to next key. (`KEYCODE_NAVIGATE_NEXT`)
1297    NavigateNext,
1298    /// Navigate out. (`KEYCODE_NAVIGATE_OUT`)
1299    NavigateOut,
1300    /// Navigate to previous key. (`KEYCODE_NAVIGATE_PREVIOUS`)
1301    NavigatePrevious,
1302    /// Cycle to next favorite channel (in favorites list). (`VK_NEXT_FAVORITE_CHANNEL`)
1303    NextFavoriteChannel,
1304    /// Cycle to next user profile (if there are multiple user profiles). (`VK_USER`)
1305    NextUserProfile,
1306    /// Access on-demand content or programs. (`VK_ON_DEMAND`)
1307    OnDemand,
1308    /// Pairing key to pair devices. (`KEYCODE_PAIRING`)
1309    Pairing,
1310    /// Move picture-in-picture window down. (`VK_PINP_DOWN`)
1311    PinPDown,
1312    /// Move picture-in-picture window. (`VK_PINP_MOVE`)
1313    PinPMove,
1314    /// Toggle display of picture-in-picture window. (`VK_PINP_TOGGLE`)
1315    PinPToggle,
1316    /// Move picture-in-picture window up. (`VK_PINP_UP`)
1317    PinPUp,
1318    /// Decrease media playback speed. (`VK_PLAY_SPEED_DOWN`)
1319    PlaySpeedDown,
1320    /// Reset playback to normal speed. (`VK_PLAY_SPEED_RESET`)
1321    PlaySpeedReset,
1322    /// Increase media playback speed. (`VK_PLAY_SPEED_UP`)
1323    PlaySpeedUp,
1324    /// Toggle random media or content shuffle mode. (`VK_RANDOM_TOGGLE`)
1325    RandomToggle,
1326    /// Not a physical key, but this key code is sent when the remote control battery is low.
1327    /// (`VK_RC_LOW_BATTERY`)
1328    RcLowBattery,
1329    /// Toggle or cycle between media recording speeds. (`VK_RECORD_SPEED_NEXT`)
1330    RecordSpeedNext,
1331    /// Toggle RF (radio frequency) input bypass mode (pass RF input directly to the RF output).
1332    /// (`VK_RF_BYPASS`)
1333    RfBypass,
1334    /// Toggle scan channels mode. (`VK_SCAN_CHANNELS_TOGGLE`)
1335    ScanChannelsToggle,
1336    /// Advance display screen mode to next available mode. (`VK_SCREEN_MODE_NEXT`)
1337    ScreenModeNext,
1338    /// Toggle display of device settings screen. (`VK_SETTINGS`, `KEYCODE_SETTINGS`)
1339    Settings,
1340    /// Toggle split screen mode. (`VK_SPLIT_SCREEN_TOGGLE`)
1341    SplitScreenToggle,
1342    /// Switch the input mode on an external STB (set top box). (`KEYCODE_STB_INPUT`)
1343    STBInput,
1344    /// Toggle the power on an external STB (set top box). (`KEYCODE_STB_POWER`)
1345    STBPower,
1346    /// Toggle display of subtitles, if available. (`VK_SUBTITLE`)
1347    Subtitle,
1348    /// Toggle display of teletext, if available (`VK_TELETEXT`, `KEYCODE_TV_TELETEXT`).
1349    Teletext,
1350    /// Advance video mode to next available mode. (`VK_VIDEO_MODE_NEXT`)
1351    VideoModeNext,
1352    /// Cause device to identify itself in some manner, e.g., audibly or visibly. (`VK_WINK`)
1353    Wink,
1354    /// Toggle between full-screen and scaled content, or alter magnification level. (`VK_ZOOM`,
1355    /// `KEYCODE_TV_ZOOM_MODE`)
1356    ZoomToggle,
1357    /// General-purpose function key.
1358    /// Usually found at the top of the keyboard.
1359    F1,
1360    /// General-purpose function key.
1361    /// Usually found at the top of the keyboard.
1362    F2,
1363    /// General-purpose function key.
1364    /// Usually found at the top of the keyboard.
1365    F3,
1366    /// General-purpose function key.
1367    /// Usually found at the top of the keyboard.
1368    F4,
1369    /// General-purpose function key.
1370    /// Usually found at the top of the keyboard.
1371    F5,
1372    /// General-purpose function key.
1373    /// Usually found at the top of the keyboard.
1374    F6,
1375    /// General-purpose function key.
1376    /// Usually found at the top of the keyboard.
1377    F7,
1378    /// General-purpose function key.
1379    /// Usually found at the top of the keyboard.
1380    F8,
1381    /// General-purpose function key.
1382    /// Usually found at the top of the keyboard.
1383    F9,
1384    /// General-purpose function key.
1385    /// Usually found at the top of the keyboard.
1386    F10,
1387    /// General-purpose function key.
1388    /// Usually found at the top of the keyboard.
1389    F11,
1390    /// General-purpose function key.
1391    /// Usually found at the top of the keyboard.
1392    F12,
1393    /// General-purpose function key.
1394    /// Usually found at the top of the keyboard.
1395    F13,
1396    /// General-purpose function key.
1397    /// Usually found at the top of the keyboard.
1398    F14,
1399    /// General-purpose function key.
1400    /// Usually found at the top of the keyboard.
1401    F15,
1402    /// General-purpose function key.
1403    /// Usually found at the top of the keyboard.
1404    F16,
1405    /// General-purpose function key.
1406    /// Usually found at the top of the keyboard.
1407    F17,
1408    /// General-purpose function key.
1409    /// Usually found at the top of the keyboard.
1410    F18,
1411    /// General-purpose function key.
1412    /// Usually found at the top of the keyboard.
1413    F19,
1414    /// General-purpose function key.
1415    /// Usually found at the top of the keyboard.
1416    F20,
1417    /// General-purpose function key.
1418    /// Usually found at the top of the keyboard.
1419    F21,
1420    /// General-purpose function key.
1421    /// Usually found at the top of the keyboard.
1422    F22,
1423    /// General-purpose function key.
1424    /// Usually found at the top of the keyboard.
1425    F23,
1426    /// General-purpose function key.
1427    /// Usually found at the top of the keyboard.
1428    F24,
1429    /// General-purpose function key.
1430    F25,
1431    /// General-purpose function key.
1432    F26,
1433    /// General-purpose function key.
1434    F27,
1435    /// General-purpose function key.
1436    F28,
1437    /// General-purpose function key.
1438    F29,
1439    /// General-purpose function key.
1440    F30,
1441    /// General-purpose function key.
1442    F31,
1443    /// General-purpose function key.
1444    F32,
1445    /// General-purpose function key.
1446    F33,
1447    /// General-purpose function key.
1448    F34,
1449    /// General-purpose function key.
1450    F35,
1451}
1452
1453/// Key represents the meaning of a keypress.
1454///
1455/// This is a superset of the UI Events Specification's [`KeyboardEvent.key`] with
1456/// additions:
1457/// - All simple variants are wrapped under the `Named` variant
1458/// - The `Unidentified` variant here, can still identify a key through it's `NativeKeyCode`.
1459/// - The `Dead` variant here, can specify the character which is inserted when pressing the
1460///   dead-key twice.
1461///
1462/// [`KeyboardEvent.key`]: https://w3c.github.io/uievents-key/
1463#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
1464pub enum Key<Str = SmolStr> {
1465    /// A simple (unparameterised) action
1466    Named(NamedKey),
1467
1468    /// A key string that corresponds to the character typed by the user, taking into account the
1469    /// user’s current locale setting, and any system-level keyboard mapping overrides that are in
1470    /// effect.
1471    Character(Str),
1472
1473    /// This variant is used when the key cannot be translated to any other variant.
1474    ///
1475    /// The native key is provided (if available) in order to allow the user to specify keybindings
1476    /// for keys which are not defined by this API, mainly through some sort of UI.
1477    Unidentified(NativeKey),
1478
1479    /// Contains the text representation of the dead-key when available.
1480    ///
1481    /// ## Platform-specific
1482    /// - **Web:** Always contains `None`
1483    Dead(Option<char>),
1484}
1485
1486impl From<NamedKey> for Key {
1487    #[inline]
1488    fn from(action: NamedKey) -> Self {
1489        Key::Named(action)
1490    }
1491}
1492
1493impl From<NativeKey> for Key {
1494    #[inline]
1495    fn from(code: NativeKey) -> Self {
1496        Key::Unidentified(code)
1497    }
1498}
1499
1500impl<Str> PartialEq<NamedKey> for Key<Str> {
1501    #[inline]
1502    fn eq(&self, rhs: &NamedKey) -> bool {
1503        match self {
1504            Key::Named(ref a) => a == rhs,
1505            _ => false,
1506        }
1507    }
1508}
1509
1510impl<Str: PartialEq<str>> PartialEq<str> for Key<Str> {
1511    #[inline]
1512    fn eq(&self, rhs: &str) -> bool {
1513        match self {
1514            Key::Character(ref s) => s == rhs,
1515            _ => false,
1516        }
1517    }
1518}
1519
1520impl<Str: PartialEq<str>> PartialEq<&str> for Key<Str> {
1521    #[inline]
1522    fn eq(&self, rhs: &&str) -> bool {
1523        self == *rhs
1524    }
1525}
1526
1527impl<Str> PartialEq<NativeKey> for Key<Str> {
1528    #[inline]
1529    fn eq(&self, rhs: &NativeKey) -> bool {
1530        match self {
1531            Key::Unidentified(ref code) => code == rhs,
1532            _ => false,
1533        }
1534    }
1535}
1536
1537impl<Str> PartialEq<Key<Str>> for NativeKey {
1538    #[inline]
1539    fn eq(&self, rhs: &Key<Str>) -> bool {
1540        rhs == self
1541    }
1542}
1543
1544impl Key<SmolStr> {
1545    /// Convert `Key::Character(SmolStr)` to `Key::Character(&str)` so you can more easily match on
1546    /// `Key`. All other variants remain unchanged.
1547    pub fn as_ref(&self) -> Key<&str> {
1548        match self {
1549            Key::Named(a) => Key::Named(*a),
1550            Key::Character(ch) => Key::Character(ch.as_str()),
1551            Key::Dead(d) => Key::Dead(*d),
1552            Key::Unidentified(u) => Key::Unidentified(u.clone()),
1553        }
1554    }
1555}
1556
1557impl NamedKey {
1558    /// Convert an action to its approximate textual equivalent.
1559    ///
1560    /// # Examples
1561    ///
1562    /// ```
1563    /// use rio_window::keyboard::NamedKey;
1564    ///
1565    /// assert_eq!(NamedKey::Enter.to_text(), Some("\r"));
1566    /// assert_eq!(NamedKey::F20.to_text(), None);
1567    /// ```
1568    pub fn to_text(&self) -> Option<&str> {
1569        match self {
1570            NamedKey::Enter => Some("\r"),
1571            NamedKey::Backspace => Some("\x08"),
1572            NamedKey::Tab => Some("\t"),
1573            NamedKey::Space => Some(" "),
1574            NamedKey::Escape => Some("\x1b"),
1575            _ => None,
1576        }
1577    }
1578}
1579
1580impl Key {
1581    /// Convert a key to its approximate textual equivalent.
1582    ///
1583    /// # Examples
1584    ///
1585    /// ```
1586    /// use rio_window::keyboard::{Key, NamedKey};
1587    ///
1588    /// assert_eq!(Key::Character("a".into()).to_text(), Some("a"));
1589    /// assert_eq!(Key::Named(NamedKey::Enter).to_text(), Some("\r"));
1590    /// assert_eq!(Key::Named(NamedKey::F20).to_text(), None);
1591    /// ```
1592    pub fn to_text(&self) -> Option<&str> {
1593        match self {
1594            Key::Named(action) => action.to_text(),
1595            Key::Character(ch) => Some(ch.as_str()),
1596            _ => None,
1597        }
1598    }
1599}
1600
1601/// The location of the key on the keyboard.
1602///
1603/// Certain physical keys on the keyboard can have the same value, but are in different locations.
1604/// For instance, the Shift key can be on the left or right side of the keyboard, or the number
1605/// keys can be above the letters or on the numpad. This enum allows the user to differentiate
1606/// them.
1607///
1608/// See the documentation for the [`location`] field on the [`KeyEvent`] struct for more
1609/// information.
1610///
1611/// [`location`]: ../event/struct.KeyEvent.html#structfield.location
1612/// [`KeyEvent`]: crate::event::KeyEvent
1613#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1614pub enum KeyLocation {
1615    /// The key is in its "normal" location on the keyboard.
1616    ///
1617    /// For instance, the "1" key above the "Q" key on a QWERTY keyboard will use this location.
1618    /// This invariant is also returned when the location of the key cannot be identified.
1619    ///
1620    /// ![Standard 1 key](https://raw.githubusercontent.com/rust-windowing/winit/master/docs/res/keyboard_standard_1_key.svg)
1621    ///
1622    /// <sub>
1623    ///   For image attribution, see the
1624    ///   <a href="https://github.com/rust-windowing/winit/blob/master/docs/res/ATTRIBUTION.md">
1625    ///     ATTRIBUTION.md
1626    ///   </a>
1627    ///   file.
1628    /// </sub>
1629    Standard,
1630
1631    /// The key is on the left side of the keyboard.
1632    ///
1633    /// For instance, the left Shift key below the Caps Lock key on a QWERTY keyboard will use this
1634    /// location.
1635    ///
1636    /// ![Left Shift key](https://raw.githubusercontent.com/rust-windowing/winit/master/docs/res/keyboard_left_shift_key.svg)
1637    ///
1638    /// <sub>
1639    ///   For image attribution, see the
1640    ///   <a href="https://github.com/rust-windowing/winit/blob/master/docs/res/ATTRIBUTION.md">
1641    ///     ATTRIBUTION.md
1642    ///   </a>
1643    ///   file.
1644    /// </sub>
1645    Left,
1646
1647    /// The key is on the right side of the keyboard.
1648    ///
1649    /// For instance, the right Shift key below the Enter key on a QWERTY keyboard will use this
1650    /// location.
1651    ///
1652    /// ![Right Shift key](https://raw.githubusercontent.com/rust-windowing/winit/master/docs/res/keyboard_right_shift_key.svg)
1653    ///
1654    /// <sub>
1655    ///   For image attribution, see the
1656    ///   <a href="https://github.com/rust-windowing/winit/blob/master/docs/res/ATTRIBUTION.md">
1657    ///     ATTRIBUTION.md
1658    ///   </a>
1659    ///   file.
1660    /// </sub>
1661    Right,
1662
1663    /// The key is on the numpad.
1664    ///
1665    /// For instance, the "1" key on the numpad will use this location.
1666    ///
1667    /// ![Numpad 1 key](https://raw.githubusercontent.com/rust-windowing/winit/master/docs/res/keyboard_numpad_1_key.svg)
1668    ///
1669    /// <sub>
1670    ///   For image attribution, see the
1671    ///   <a href="https://github.com/rust-windowing/winit/blob/master/docs/res/ATTRIBUTION.md">
1672    ///     ATTRIBUTION.md
1673    ///   </a>
1674    ///   file.
1675    /// </sub>
1676    Numpad,
1677}
1678
1679bitflags! {
1680    /// Represents the current state of the keyboard modifiers
1681    ///
1682    /// Each flag represents a modifier and is set if this modifier is active.
1683    #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1684    pub struct ModifiersState: u32 {
1685        /// The "shift" key.
1686        const SHIFT = 0b100;
1687        /// The "control" key.
1688        const CONTROL = 0b100 << 3;
1689        /// The "alt" key.
1690        const ALT = 0b100 << 6;
1691        /// This is the "windows" key on PC and "command" key on Mac.
1692        const SUPER = 0b100 << 9;
1693    }
1694}
1695
1696impl ModifiersState {
1697    /// Returns `true` if the shift key is pressed.
1698    pub fn shift_key(&self) -> bool {
1699        self.intersects(Self::SHIFT)
1700    }
1701
1702    /// Returns `true` if the control key is pressed.
1703    pub fn control_key(&self) -> bool {
1704        self.intersects(Self::CONTROL)
1705    }
1706
1707    /// Returns `true` if the alt key is pressed.
1708    pub fn alt_key(&self) -> bool {
1709        self.intersects(Self::ALT)
1710    }
1711
1712    /// Returns `true` if the super key is pressed.
1713    pub fn super_key(&self) -> bool {
1714        self.intersects(Self::SUPER)
1715    }
1716}
1717
1718/// The state of the particular modifiers key.
1719#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
1720pub enum ModifiersKeyState {
1721    /// The particular key is pressed.
1722    Pressed,
1723    /// The state of the key is unknown.
1724    #[default]
1725    Unknown,
1726}
1727
1728// NOTE: the exact modifier key is not used to represent modifiers state in the
1729// first place due to a fact that modifiers state could be changed without any
1730// key being pressed and on some platforms like Wayland/X11 which key resulted
1731// in modifiers change is hidden, also, not that it really matters.
1732//
1733// The reason this API is even exposed is mostly to provide a way for users
1734// to treat modifiers differently based on their position, which is required
1735// on macOS due to their AltGr/Option situation.
1736bitflags! {
1737    #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
1738    pub(crate) struct ModifiersKeys: u8 {
1739        const LSHIFT   = 0b0000_0001;
1740        const RSHIFT   = 0b0000_0010;
1741        const LCONTROL = 0b0000_0100;
1742        const RCONTROL = 0b0000_1000;
1743        const LALT     = 0b0001_0000;
1744        const RALT     = 0b0010_0000;
1745        const LSUPER   = 0b0100_0000;
1746        const RSUPER   = 0b1000_0000;
1747    }
1748}