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