[go: up one dir, main page]

Enum Key

Source
pub enum Key<Str = SmolStr> {
    Named(NamedKey),
    Character(Str),
    Unidentified(NativeKey),
    Dead(Option<char>),
}
Expand description

Key represents the meaning of a keypress.

This is a superset of the UI Events Specification’s KeyboardEvent.key with additions:

  • All simple variants are wrapped under the Named variant
  • The Unidentified variant here, can still identify a key through it’s NativeKeyCode.
  • The Dead variant here, can specify the character which is inserted when pressing the dead-key twice.

Variants§

§

Named(NamedKey)

A simple (unparameterised) action

§

Character(Str)

A key string that corresponds to the character typed by the user, taking into account the user’s current locale setting, and any system-level keyboard mapping overrides that are in effect.

§

Unidentified(NativeKey)

This variant is used when the key cannot be translated to any other variant.

The native key is provided (if available) in order to allow the user to specify keybindings for keys which are not defined by this API, mainly through some sort of UI.

§

Dead(Option<char>)

Contains the text representation of the dead-key when available.

§Platform-specific
  • Web: Always contains None

Implementations§

Source§

impl Key<SmolStr>

Source

pub fn as_ref(&self) -> Key<&str>

Convert Key::Character(SmolStr) to Key::Character(&str) so you can more easily match on Key. All other variants remain unchanged.

Examples found in repository?
examples/control_flow.rs (line 92)
77    fn window_event(
78        &mut self,
79        _event_loop: &ActiveEventLoop,
80        _window_id: WindowId,
81        event: WindowEvent,
82    ) {
83        info!("{event:?}");
84
85        match event {
86            WindowEvent::CloseRequested => {
87                self.close_requested = true;
88            },
89            WindowEvent::KeyboardInput {
90                event: KeyEvent { logical_key: key, state: ElementState::Pressed, .. },
91                ..
92            } => match key.as_ref() {
93                // WARNING: Consider using `key_without_modifiers()` if available on your platform.
94                // See the `key_binding` example
95                Key::Character("1") => {
96                    self.mode = Mode::Wait;
97                    warn!("mode: {:?}", self.mode);
98                },
99                Key::Character("2") => {
100                    self.mode = Mode::WaitUntil;
101                    warn!("mode: {:?}", self.mode);
102                },
103                Key::Character("3") => {
104                    self.mode = Mode::Poll;
105                    warn!("mode: {:?}", self.mode);
106                },
107                Key::Character("r") => {
108                    self.request_redraw = !self.request_redraw;
109                    warn!("request_redraw: {}", self.request_redraw);
110                },
111                Key::Named(NamedKey::Escape) => {
112                    self.close_requested = true;
113                },
114                _ => (),
115            },
116            WindowEvent::RedrawRequested => {
117                let window = self.window.as_ref().unwrap();
118                window.pre_present_notify();
119                fill::fill_window(window);
120            },
121            _ => (),
122        }
123    }
More examples
Hide additional examples
examples/window.rs (line 398)
340    fn window_event(
341        &mut self,
342        event_loop: &ActiveEventLoop,
343        window_id: WindowId,
344        event: WindowEvent,
345    ) {
346        let window = match self.windows.get_mut(&window_id) {
347            Some(window) => window,
348            None => return,
349        };
350
351        match event {
352            WindowEvent::Resized(size) => {
353                window.resize(size);
354            },
355            WindowEvent::Focused(focused) => {
356                if focused {
357                    info!("Window={window_id:?} focused");
358                } else {
359                    info!("Window={window_id:?} unfocused");
360                }
361            },
362            WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
363                info!("Window={window_id:?} changed scale to {scale_factor}");
364            },
365            WindowEvent::ThemeChanged(theme) => {
366                info!("Theme changed to {theme:?}");
367                window.set_draw_theme(theme);
368            },
369            WindowEvent::RedrawRequested => {
370                if let Err(err) = window.draw() {
371                    error!("Error drawing window: {err}");
372                }
373            },
374            WindowEvent::Occluded(occluded) => {
375                window.set_occluded(occluded);
376            },
377            WindowEvent::CloseRequested => {
378                info!("Closing Window={window_id:?}");
379                self.windows.remove(&window_id);
380            },
381            WindowEvent::ModifiersChanged(modifiers) => {
382                window.modifiers = modifiers.state();
383                info!("Modifiers changed to {:?}", window.modifiers);
384            },
385            WindowEvent::MouseWheel { delta, .. } => match delta {
386                MouseScrollDelta::LineDelta(x, y) => {
387                    info!("Mouse wheel Line Delta: ({x},{y})");
388                },
389                MouseScrollDelta::PixelDelta(px) => {
390                    info!("Mouse wheel Pixel Delta: ({},{})", px.x, px.y);
391                },
392            },
393            WindowEvent::KeyboardInput { event, is_synthetic: false, .. } => {
394                let mods = window.modifiers;
395
396                // Dispatch actions only on press.
397                if event.state.is_pressed() {
398                    let action = if let Key::Character(ch) = event.logical_key.as_ref() {
399                        Self::process_key_binding(&ch.to_uppercase(), &mods)
400                    } else {
401                        None
402                    };
403
404                    if let Some(action) = action {
405                        self.handle_action(event_loop, window_id, action);
406                    }
407                }
408            },
409            WindowEvent::MouseInput { button, state, .. } => {
410                let mods = window.modifiers;
411                if let Some(action) =
412                    state.is_pressed().then(|| Self::process_mouse_binding(button, &mods)).flatten()
413                {
414                    self.handle_action(event_loop, window_id, action);
415                }
416            },
417            WindowEvent::CursorLeft { .. } => {
418                info!("Cursor left Window={window_id:?}");
419                window.cursor_left();
420            },
421            WindowEvent::CursorMoved { position, .. } => {
422                info!("Moved cursor to {position:?}");
423                window.cursor_moved(position);
424            },
425            WindowEvent::ActivationTokenDone { token: _token, .. } => {
426                #[cfg(any(x11_platform, wayland_platform))]
427                {
428                    startup_notify::set_activation_token_env(_token);
429                    if let Err(err) = self.create_window(event_loop, None) {
430                        error!("Error creating new window: {err}");
431                    }
432                }
433            },
434            WindowEvent::Ime(event) => match event {
435                Ime::Enabled => info!("IME enabled for Window={window_id:?}"),
436                Ime::Preedit(text, caret_pos) => {
437                    info!("Preedit: {}, with caret at {:?}", text, caret_pos);
438                },
439                Ime::Commit(text) => {
440                    info!("Committed: {}", text);
441                },
442                Ime::Disabled => info!("IME disabled for Window={window_id:?}"),
443            },
444            WindowEvent::PinchGesture { delta, .. } => {
445                window.zoom += delta;
446                let zoom = window.zoom;
447                if delta > 0.0 {
448                    info!("Zoomed in {delta:.5} (now: {zoom:.5})");
449                } else {
450                    info!("Zoomed out {delta:.5} (now: {zoom:.5})");
451                }
452            },
453            WindowEvent::RotationGesture { delta, .. } => {
454                window.rotated += delta;
455                let rotated = window.rotated;
456                if delta > 0.0 {
457                    info!("Rotated counterclockwise {delta:.5} (now: {rotated:.5})");
458                } else {
459                    info!("Rotated clockwise {delta:.5} (now: {rotated:.5})");
460                }
461            },
462            WindowEvent::PanGesture { delta, phase, .. } => {
463                window.panned.x += delta.x;
464                window.panned.y += delta.y;
465                info!("Panned ({delta:?})) (now: {:?}), {phase:?}", window.panned);
466            },
467            WindowEvent::DoubleTapGesture { .. } => {
468                info!("Smart zoom");
469            },
470            WindowEvent::TouchpadPressure { .. }
471            | WindowEvent::HoveredFileCancelled
472            | WindowEvent::KeyboardInput { .. }
473            | WindowEvent::CursorEntered { .. }
474            | WindowEvent::AxisMotion { .. }
475            | WindowEvent::DroppedFile(_)
476            | WindowEvent::HoveredFile(_)
477            | WindowEvent::Destroyed
478            | WindowEvent::Touch(_)
479            | WindowEvent::Moved(_) => (),
480        }
481    }
Source§

impl Key

Source

pub fn to_text(&self) -> Option<&str>

Convert a key to its approximate textual equivalent.

§Examples
use winit::keyboard::{Key, NamedKey};

assert_eq!(Key::Character("a".into()).to_text(), Some("a"));
assert_eq!(Key::Named(NamedKey::Enter).to_text(), Some("\r"));
assert_eq!(Key::Named(NamedKey::F20).to_text(), None);

Trait Implementations§

Source§

impl<Str: Clone> Clone for Key<Str>

Source§

fn clone(&self) -> Key<Str>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<Str: Debug> Debug for Key<Str>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de, Str> Deserialize<'de> for Key<Str>
where Str: Deserialize<'de>,

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<NamedKey> for Key

Source§

fn from(action: NamedKey) -> Self

Converts to this type from the input type.
Source§

impl From<NativeKey> for Key

Source§

fn from(code: NativeKey) -> Self

Converts to this type from the input type.
Source§

impl<Str: Hash> Hash for Key<Str>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<Str: Ord> Ord for Key<Str>

Source§

fn cmp(&self, other: &Key<Str>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<Str: PartialEq<str>> PartialEq<&str> for Key<Str>

Source§

fn eq(&self, rhs: &&str) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<Str> PartialEq<Key<Str>> for NativeKey

Source§

fn eq(&self, rhs: &Key<Str>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<Str> PartialEq<NamedKey> for Key<Str>

Source§

fn eq(&self, rhs: &NamedKey) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<Str> PartialEq<NativeKey> for Key<Str>

Source§

fn eq(&self, rhs: &NativeKey) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<Str: PartialEq<str>> PartialEq<str> for Key<Str>

Source§

fn eq(&self, rhs: &str) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<Str: PartialEq> PartialEq for Key<Str>

Source§

fn eq(&self, other: &Key<Str>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<Str: PartialOrd> PartialOrd for Key<Str>

Source§

fn partial_cmp(&self, other: &Key<Str>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<Str> Serialize for Key<Str>
where Str: Serialize,

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<Str: Eq> Eq for Key<Str>

Source§

impl<Str> StructuralPartialEq for Key<Str>

Auto Trait Implementations§

§

impl<Str> Freeze for Key<Str>
where Str: Freeze,

§

impl<Str> RefUnwindSafe for Key<Str>
where Str: RefUnwindSafe,

§

impl<Str> Send for Key<Str>
where Str: Send,

§

impl<Str> Sync for Key<Str>
where Str: Sync,

§

impl<Str> Unpin for Key<Str>
where Str: Unpin,

§

impl<Str> UnwindSafe for Key<Str>
where Str: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,