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
Namedvariant - The
Unidentifiedvariant here, can still identify a key through it’sNativeKeyCode. - The
Deadvariant 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>
impl Key<SmolStr>
Sourcepub fn as_ref(&self) -> Key<&str>
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?
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
310 fn window_event(
311 &mut self,
312 event_loop: &ActiveEventLoop,
313 window_id: WindowId,
314 event: WindowEvent,
315 ) {
316 let window = match self.windows.get_mut(&window_id) {
317 Some(window) => window,
318 None => return,
319 };
320
321 match event {
322 WindowEvent::Resized(size) => {
323 window.resize(size);
324 },
325 WindowEvent::Focused(focused) => {
326 if focused {
327 info!("Window={window_id:?} focused");
328 } else {
329 info!("Window={window_id:?} unfocused");
330 }
331 },
332 WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
333 info!("Window={window_id:?} changed scale to {scale_factor}");
334 },
335 WindowEvent::ThemeChanged(theme) => {
336 info!("Theme changed to {theme:?}");
337 window.set_theme(theme);
338 },
339 WindowEvent::RedrawRequested => {
340 if let Err(err) = window.draw() {
341 error!("Error drawing window: {err}");
342 }
343 },
344 WindowEvent::Occluded(occluded) => {
345 window.set_occluded(occluded);
346 },
347 WindowEvent::CloseRequested => {
348 info!("Closing Window={window_id:?}");
349 self.windows.remove(&window_id);
350 },
351 WindowEvent::ModifiersChanged(modifiers) => {
352 window.modifiers = modifiers.state();
353 info!("Modifiers changed to {:?}", window.modifiers);
354 },
355 WindowEvent::MouseWheel { delta, .. } => match delta {
356 MouseScrollDelta::LineDelta(x, y) => {
357 info!("Mouse wheel Line Delta: ({x},{y})");
358 },
359 MouseScrollDelta::PixelDelta(px) => {
360 info!("Mouse wheel Pixel Delta: ({},{})", px.x, px.y);
361 },
362 },
363 WindowEvent::KeyboardInput { event, is_synthetic: false, .. } => {
364 let mods = window.modifiers;
365
366 // Dispatch actions only on press.
367 if event.state.is_pressed() {
368 let action = if let Key::Character(ch) = event.logical_key.as_ref() {
369 Self::process_key_binding(&ch.to_uppercase(), &mods)
370 } else {
371 None
372 };
373
374 if let Some(action) = action {
375 self.handle_action(event_loop, window_id, action);
376 }
377 }
378 },
379 WindowEvent::MouseInput { button, state, .. } => {
380 let mods = window.modifiers;
381 if let Some(action) =
382 state.is_pressed().then(|| Self::process_mouse_binding(button, &mods)).flatten()
383 {
384 self.handle_action(event_loop, window_id, action);
385 }
386 },
387 WindowEvent::CursorLeft { .. } => {
388 info!("Cursor left Window={window_id:?}");
389 window.cursor_left();
390 },
391 WindowEvent::CursorMoved { position, .. } => {
392 info!("Moved cursor to {position:?}");
393 window.cursor_moved(position);
394 },
395 WindowEvent::ActivationTokenDone { token: _token, .. } => {
396 #[cfg(any(x11_platform, wayland_platform))]
397 {
398 startup_notify::set_activation_token_env(_token);
399 if let Err(err) = self.create_window(event_loop, None) {
400 error!("Error creating new window: {err}");
401 }
402 }
403 },
404 WindowEvent::Ime(event) => match event {
405 Ime::Enabled => info!("IME enabled for Window={window_id:?}"),
406 Ime::Preedit(text, caret_pos) => {
407 info!("Preedit: {}, with caret at {:?}", text, caret_pos);
408 },
409 Ime::Commit(text) => {
410 info!("Committed: {}", text);
411 },
412 Ime::Disabled => info!("IME disabled for Window={window_id:?}"),
413 },
414 WindowEvent::PinchGesture { delta, .. } => {
415 window.zoom += delta;
416 let zoom = window.zoom;
417 if delta > 0.0 {
418 info!("Zoomed in {delta:.5} (now: {zoom:.5})");
419 } else {
420 info!("Zoomed out {delta:.5} (now: {zoom:.5})");
421 }
422 },
423 WindowEvent::RotationGesture { delta, .. } => {
424 window.rotated += delta;
425 let rotated = window.rotated;
426 if delta > 0.0 {
427 info!("Rotated counterclockwise {delta:.5} (now: {rotated:.5})");
428 } else {
429 info!("Rotated clockwise {delta:.5} (now: {rotated:.5})");
430 }
431 },
432 WindowEvent::PanGesture { delta, phase, .. } => {
433 window.panned.x += delta.x;
434 window.panned.y += delta.y;
435 info!("Panned ({delta:?})) (now: {:?}), {phase:?}", window.panned);
436 },
437 WindowEvent::DoubleTapGesture { .. } => {
438 info!("Smart zoom");
439 },
440 WindowEvent::TouchpadPressure { .. }
441 | WindowEvent::HoveredFileCancelled
442 | WindowEvent::KeyboardInput { .. }
443 | WindowEvent::CursorEntered { .. }
444 | WindowEvent::AxisMotion { .. }
445 | WindowEvent::DroppedFile(_)
446 | WindowEvent::HoveredFile(_)
447 | WindowEvent::Destroyed
448 | WindowEvent::Touch(_)
449 | WindowEvent::Moved(_) => (),
450 }
451 }Source§impl Key
impl Key
Sourcepub fn to_text(&self) -> Option<&str>
pub fn to_text(&self) -> Option<&str>
Convert a key to its approximate textual equivalent.
§Examples
use rio_winit_fork::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);