1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
//! The `Event` enum and assorted supporting types. //! //! These are sent to the closure given to [`EventLoop::run(...)`][event_loop_run], where they get //! processed and used to modify the program state. For more details, see the root-level documentation. //! //! Some of these events represent different "parts" of a traditional event-handling loop. You could //! approximate the basic ordering loop of [`EventLoop::run(...)`][event_loop_run] like this: //! //! ```rust,ignore //! let mut control_flow = ControlFlow::Poll; //! let mut start_cause = StartCause::Init; //! //! while control_flow != ControlFlow::Exit { //! event_handler(NewEvents(start_cause), ..., &mut control_flow); //! //! for e in (window events, user events, device events) { //! event_handler(e, ..., &mut control_flow); //! } //! event_handler(MainEventsCleared, ..., &mut control_flow); //! //! for w in (redraw windows) { //! event_handler(RedrawRequested(w), ..., &mut control_flow); //! } //! event_handler(RedrawEventsCleared, ..., &mut control_flow); //! //! start_cause = wait_if_necessary(control_flow); //! } //! //! event_handler(LoopDestroyed, ..., &mut control_flow); //! ``` //! //! This leaves out timing details like `ControlFlow::WaitUntil` but hopefully //! describes what happens in what order. //! //! [event_loop_run]: crate::event_loop::EventLoop::run use instant::Instant; use std::path::PathBuf; use crate::{ dpi::{PhysicalPosition, PhysicalSize}, platform_impl, window::{Theme, WindowId}, }; /// Describes a generic event. /// /// See the module-level docs for more information on the event loop manages each event. #[derive(Debug, PartialEq)] pub enum Event<'a, T: 'static> { /// Emitted when new events arrive from the OS to be processed. /// /// This event type is useful as a place to put code that should be done before you start /// processing events, such as updating frame timing information for benchmarking or checking /// the [`StartCause`][crate::event::StartCause] to see if a timer set by /// [`ControlFlow::WaitUntil`](crate::event_loop::ControlFlow::WaitUntil) has elapsed. NewEvents(StartCause), /// Emitted when the OS sends an event to a winit window. WindowEvent { window_id: WindowId, event: WindowEvent<'a>, }, /// Emitted when the OS sends an event to a device. DeviceEvent { device_id: DeviceId, event: DeviceEvent, }, /// Emitted when an event is sent from [`EventLoopProxy::send_event`](crate::event_loop::EventLoopProxy::send_event) UserEvent(T), /// Emitted when the application has been suspended. Suspended, /// Emitted when the application has been resumed. Resumed, /// Emitted when all of the event loop's input events have been processed and redraw processing /// is about to begin. /// /// This event is useful as a place to put your code that should be run after all /// state-changing events have been handled and you want to do stuff (updating state, performing /// calculations, etc) that happens as the "main body" of your event loop. If your program only draws /// graphics when something changes, it's usually better to do it in response to /// [`Event::RedrawRequested`](crate::event::Event::RedrawRequested), which gets emitted /// immediately after this event. Programs that draw graphics continuously, like most games, /// can render here unconditionally for simplicity. MainEventsCleared, /// Emitted after `MainEventsCleared` when a window should be redrawn. /// /// This gets triggered in two scenarios: /// - The OS has performed an operation that's invalidated the window's contents (such as /// resizing the window). /// - The application has explicitly requested a redraw via /// [`Window::request_redraw`](crate::window::Window::request_redraw). /// /// During each iteration of the event loop, Winit will aggregate duplicate redraw requests /// into a single event, to help avoid duplicating rendering work. /// /// Mainly of interest to applications with mostly-static graphics that avoid redrawing unless /// something changes, like most non-game GUIs. RedrawRequested(WindowId), /// Emitted after all `RedrawRequested` events have been processed and control flow is about to /// be taken away from the program. If there are no `RedrawRequested` events, it is emitted /// immediately after `MainEventsCleared`. /// /// This event is useful for doing any cleanup or bookkeeping work after all the rendering /// tasks have been completed. RedrawEventsCleared, /// Emitted when the event loop is being shut down. /// /// This is irreversable - if this event is emitted, it is guaranteed to be the last event that /// gets emitted. You generally want to treat this as an "do on quit" event. LoopDestroyed, } impl<T: Clone> Clone for Event<'static, T> { fn clone(&self) -> Self { use self::Event::*; match self { WindowEvent { window_id, event } => WindowEvent { window_id: *window_id, event: event.clone(), }, UserEvent(event) => UserEvent(event.clone()), DeviceEvent { device_id, event } => DeviceEvent { device_id: *device_id, event: event.clone(), }, NewEvents(cause) => NewEvents(cause.clone()), MainEventsCleared => MainEventsCleared, RedrawRequested(wid) => RedrawRequested(*wid), RedrawEventsCleared => RedrawEventsCleared, LoopDestroyed => LoopDestroyed, Suspended => Suspended, Resumed => Resumed, } } } impl<'a, T> Event<'a, T> { pub fn map_nonuser_event<U>(self) -> Result<Event<'a, U>, Event<'a, T>> { use self::Event::*; match self { UserEvent(_) => Err(self), WindowEvent { window_id, event } => Ok(WindowEvent { window_id, event }), DeviceEvent { device_id, event } => Ok(DeviceEvent { device_id, event }), NewEvents(cause) => Ok(NewEvents(cause)), MainEventsCleared => Ok(MainEventsCleared), RedrawRequested(wid) => Ok(RedrawRequested(wid)), RedrawEventsCleared => Ok(RedrawEventsCleared), LoopDestroyed => Ok(LoopDestroyed), Suspended => Ok(Suspended), Resumed => Ok(Resumed), } } /// If the event doesn't contain a reference, turn it into an event with a `'static` lifetime. /// Otherwise, return `None`. pub fn to_static(self) -> Option<Event<'static, T>> { use self::Event::*; match self { WindowEvent { window_id, event } => event .to_static() .map(|event| WindowEvent { window_id, event }), UserEvent(event) => Some(UserEvent(event)), DeviceEvent { device_id, event } => Some(DeviceEvent { device_id, event }), NewEvents(cause) => Some(NewEvents(cause)), MainEventsCleared => Some(MainEventsCleared), RedrawRequested(wid) => Some(RedrawRequested(wid)), RedrawEventsCleared => Some(RedrawEventsCleared), LoopDestroyed => Some(LoopDestroyed), Suspended => Some(Suspended), Resumed => Some(Resumed), } } } /// Describes the reason the event loop is resuming. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StartCause { /// Sent if the time specified by `ControlFlow::WaitUntil` has been reached. Contains the /// moment the timeout was requested and the requested resume time. The actual resume time is /// guaranteed to be equal to or after the requested resume time. ResumeTimeReached { start: Instant, requested_resume: Instant, }, /// Sent if the OS has new events to send to the window, after a wait was requested. Contains /// the moment the wait was requested and the resume time, if requested. WaitCancelled { start: Instant, requested_resume: Option<Instant>, }, /// Sent if the event loop is being resumed after the loop's control flow was set to /// `ControlFlow::Poll`. Poll, /// Sent once, immediately after `run` is called. Indicates that the loop was just initialized. Init, } /// Describes an event from a `Window`. #[derive(Debug, PartialEq)] pub enum WindowEvent<'a> { /// The size of the window has changed. Contains the client area's new dimensions. Resized(PhysicalSize<u32>), /// The position of the window has changed. Contains the window's new position. Moved(PhysicalPosition<i32>), /// The window has been requested to close. CloseRequested, /// The window has been destroyed. Destroyed, /// A file has been dropped into the window. /// /// When the user drops multiple files at once, this event will be emitted for each file /// separately. DroppedFile(PathBuf), /// A file is being hovered over the window. /// /// When the user hovers multiple files at once, this event will be emitted for each file /// separately. HoveredFile(PathBuf), /// A file was hovered, but has exited the window. /// /// There will be a single `HoveredFileCancelled` event triggered even if multiple files were /// hovered. HoveredFileCancelled, /// The window received a unicode character. ReceivedCharacter(char), /// The window gained or lost focus. /// /// The parameter is true if the window has gained focus, and false if it has lost focus. Focused(bool), /// An event from the keyboard has been received. KeyboardInput { device_id: DeviceId, input: KeyboardInput, /// If `true`, the event was generated synthetically by winit /// in one of the following circumstances: /// /// * Synthetic key press events are generated for all keys pressed /// when a window gains focus. Likewise, synthetic key release events /// are generated for all keys pressed when a window goes out of focus. /// ***Currently, this is only functional on X11 and Windows*** /// /// Otherwise, this value is always `false`. is_synthetic: bool, }, /// The keyboard modifiers have changed. /// /// Platform-specific behavior: /// - **Web**: This API is currently unimplemented on the web. This isn't by design - it's an /// issue, and it should get fixed - but it's the current state of the API. ModifiersChanged(ModifiersState), /// The cursor has moved on the window. CursorMoved { device_id: DeviceId, /// (x,y) coords in pixels relative to the top-left corner of the window. Because the range of this data is /// limited by the display area and it may have been transformed by the OS to implement effects such as cursor /// acceleration, it should not be used to implement non-cursor-like interactions such as 3D camera control. position: PhysicalPosition<f64>, #[deprecated = "Deprecated in favor of WindowEvent::ModifiersChanged"] modifiers: ModifiersState, }, /// The cursor has entered the window. CursorEntered { device_id: DeviceId }, /// The cursor has left the window. CursorLeft { device_id: DeviceId }, /// A mouse wheel movement or touchpad scroll occurred. MouseWheel { device_id: DeviceId, delta: MouseScrollDelta, phase: TouchPhase, #[deprecated = "Deprecated in favor of WindowEvent::ModifiersChanged"] modifiers: ModifiersState, }, /// An mouse button press has been received. MouseInput { device_id: DeviceId, state: ElementState, button: MouseButton, #[deprecated = "Deprecated in favor of WindowEvent::ModifiersChanged"] modifiers: ModifiersState, }, /// Touchpad pressure event. /// /// At the moment, only supported on Apple forcetouch-capable macbooks. /// The parameters are: pressure level (value between 0 and 1 representing how hard the touchpad /// is being pressed) and stage (integer representing the click level). TouchpadPressure { device_id: DeviceId, pressure: f32, stage: i64, }, /// Motion on some analog axis. May report data redundant to other, more specific events. AxisMotion { device_id: DeviceId, axis: AxisId, value: f64, }, /// Touch event has been received Touch(Touch), /// The window's scale factor has changed. /// /// The following user actions can cause DPI changes: /// /// * Changing the display's resolution. /// * Changing the display's scale factor (e.g. in Control Panel on Windows). /// * Moving the window to a display with a different scale factor. /// /// After this event callback has been processed, the window will be resized to whatever value /// is pointed to by the `new_inner_size` reference. By default, this will contain the size suggested /// by the OS, but it can be changed to any value. /// /// For more information about DPI in general, see the [`dpi`](crate::dpi) module. ScaleFactorChanged { scale_factor: f64, new_inner_size: &'a mut PhysicalSize<u32>, }, /// The system window theme has changed. /// /// Applications might wish to react to this to change the theme of the content of the window /// when the system changes the window theme. /// /// At the moment this is only supported on Windows. ThemeChanged(Theme), } impl Clone for WindowEvent<'static> { fn clone(&self) -> Self { use self::WindowEvent::*; return match self { Resized(size) => Resized(size.clone()), Moved(pos) => Moved(pos.clone()), CloseRequested => CloseRequested, Destroyed => Destroyed, DroppedFile(file) => DroppedFile(file.clone()), HoveredFile(file) => HoveredFile(file.clone()), HoveredFileCancelled => HoveredFileCancelled, ReceivedCharacter(c) => ReceivedCharacter(*c), Focused(f) => Focused(*f), KeyboardInput { device_id, input, is_synthetic, } => KeyboardInput { device_id: *device_id, input: *input, is_synthetic: *is_synthetic, }, ModifiersChanged(modifiers) => ModifiersChanged(modifiers.clone()), #[allow(deprecated)] CursorMoved { device_id, position, modifiers, } => CursorMoved { device_id: *device_id, position: *position, modifiers: *modifiers, }, CursorEntered { device_id } => CursorEntered { device_id: *device_id, }, CursorLeft { device_id } => CursorLeft { device_id: *device_id, }, #[allow(deprecated)] MouseWheel { device_id, delta, phase, modifiers, } => MouseWheel { device_id: *device_id, delta: *delta, phase: *phase, modifiers: *modifiers, }, #[allow(deprecated)] MouseInput { device_id, state, button, modifiers, } => MouseInput { device_id: *device_id, state: *state, button: *button, modifiers: *modifiers, }, TouchpadPressure { device_id, pressure, stage, } => TouchpadPressure { device_id: *device_id, pressure: *pressure, stage: *stage, }, AxisMotion { device_id, axis, value, } => AxisMotion { device_id: *device_id, axis: *axis, value: *value, }, Touch(touch) => Touch(*touch), ThemeChanged(theme) => ThemeChanged(theme.clone()), ScaleFactorChanged { .. } => { unreachable!("Static event can't be about scale factor changing") } }; } } impl<'a> WindowEvent<'a> { pub fn to_static(self) -> Option<WindowEvent<'static>> { use self::WindowEvent::*; match self { Resized(size) => Some(Resized(size)), Moved(position) => Some(Moved(position)), CloseRequested => Some(CloseRequested), Destroyed => Some(Destroyed), DroppedFile(file) => Some(DroppedFile(file)), HoveredFile(file) => Some(HoveredFile(file)), HoveredFileCancelled => Some(HoveredFileCancelled), ReceivedCharacter(c) => Some(ReceivedCharacter(c)), Focused(focused) => Some(Focused(focused)), KeyboardInput { device_id, input, is_synthetic, } => Some(KeyboardInput { device_id, input, is_synthetic, }), ModifiersChanged(modifiers) => Some(ModifiersChanged(modifiers)), #[allow(deprecated)] CursorMoved { device_id, position, modifiers, } => Some(CursorMoved { device_id, position, modifiers, }), CursorEntered { device_id } => Some(CursorEntered { device_id }), CursorLeft { device_id } => Some(CursorLeft { device_id }), #[allow(deprecated)] MouseWheel { device_id, delta, phase, modifiers, } => Some(MouseWheel { device_id, delta, phase, modifiers, }), #[allow(deprecated)] MouseInput { device_id, state, button, modifiers, } => Some(MouseInput { device_id, state, button, modifiers, }), TouchpadPressure { device_id, pressure, stage, } => Some(TouchpadPressure { device_id, pressure, stage, }), AxisMotion { device_id, axis, value, } => Some(AxisMotion { device_id, axis, value, }), Touch(touch) => Some(Touch(touch)), ThemeChanged(theme) => Some(ThemeChanged(theme)), ScaleFactorChanged { .. } => None, } } } /// Identifier of an input device. /// /// Whenever you receive an event arising from a particular input device, this event contains a `DeviceId` which /// identifies its origin. Note that devices may be virtual (representing an on-screen cursor and keyboard focus) or /// physical. Virtual devices typically aggregate inputs from multiple physical devices. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct DeviceId(pub(crate) platform_impl::DeviceId); impl DeviceId { /// Returns a dummy `DeviceId`, useful for unit testing. The only guarantee made about the return /// value of this function is that it will always be equal to itself and to future values returned /// by this function. No other guarantees are made. This may be equal to a real `DeviceId`. /// /// **Passing this into a winit function will result in undefined behavior.** pub unsafe fn dummy() -> Self { DeviceId(platform_impl::DeviceId::dummy()) } } /// Represents raw hardware events that are not associated with any particular window. /// /// Useful for interactions that diverge significantly from a conventional 2D GUI, such as 3D camera or first-person /// game controls. Many physical actions, such as mouse movement, can produce both device and window events. Because /// window events typically arise from virtual devices (corresponding to GUI cursors and keyboard focus) the device IDs /// may not match. /// /// Note that these events are delivered regardless of input focus. #[derive(Clone, Debug, PartialEq)] pub enum DeviceEvent { Added, Removed, /// Change in physical position of a pointing device. /// /// This represents raw, unfiltered physical motion. Not to be confused with `WindowEvent::CursorMoved`. MouseMotion { /// (x, y) change in position in unspecified units. /// /// Different devices may use different units. delta: (f64, f64), }, /// Physical scroll event MouseWheel { delta: MouseScrollDelta, }, /// Motion on some analog axis. This event will be reported for all arbitrary input devices /// that winit supports on this platform, including mouse devices. If the device is a mouse /// device then this will be reported alongside the MouseMotion event. Motion { axis: AxisId, value: f64, }, Button { button: ButtonId, state: ElementState, }, Key(KeyboardInput), Text { codepoint: char, }, } /// Describes a keyboard input event. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct KeyboardInput { /// Identifies the physical key pressed /// /// This should not change if the user adjusts the host's keyboard map. Use when the physical location of the /// key is more important than the key's host GUI semantics, such as for movement controls in a first-person /// game. pub scancode: ScanCode, pub state: ElementState, /// Identifies the semantic meaning of the key /// /// Use when the semantics of the key are more important than the physical location of the key, such as when /// implementing appropriate behavior for "page up." pub virtual_keycode: Option<VirtualKeyCode>, /// Modifier keys active at the time of this input. /// /// This is tracked internally to avoid tracking errors arising from modifier key state changes when events from /// this device are not being delivered to the application, e.g. due to keyboard focus being elsewhere. #[deprecated = "Deprecated in favor of WindowEvent::ModifiersChanged"] pub modifiers: ModifiersState, } /// Describes touch-screen input state. #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum TouchPhase { Started, Moved, Ended, Cancelled, } /// Represents a touch event /// /// Every time the user touches the screen, a new `Start` event with an unique /// identifier for the finger is generated. When the finger is lifted, an `End` /// event is generated with the same finger id. /// /// After a `Start` event has been emitted, there may be zero or more `Move` /// events when the finger is moved or the touch pressure changes. /// /// The finger id may be reused by the system after an `End` event. The user /// should assume that a new `Start` event received with the same id has nothing /// to do with the old finger and is a new finger. /// /// A `Cancelled` event is emitted when the system has canceled tracking this /// touch, such as when the window loses focus, or on iOS if the user moves the /// device against their face. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Touch { pub device_id: DeviceId, pub phase: TouchPhase, pub location: PhysicalPosition<f64>, /// Describes how hard the screen was pressed. May be `None` if the platform /// does not support pressure sensitivity. /// /// ## Platform-specific /// /// - Only available on **iOS** 9.0+ and **Windows** 8+. pub force: Option<Force>, /// Unique identifier of a finger. pub id: u64, } /// Describes the force of a touch event #[derive(Debug, Clone, Copy, PartialEq)] pub enum Force { /// On iOS, the force is calibrated so that the same number corresponds to /// roughly the same amount of pressure on the screen regardless of the /// device. Calibrated { /// The force of the touch, where a value of 1.0 represents the force of /// an average touch (predetermined by the system, not user-specific). /// /// The force reported by Apple Pencil is measured along the axis of the /// pencil. If you want a force perpendicular to the device, you need to /// calculate this value using the `altitude_angle` value. force: f64, /// The maximum possible force for a touch. /// /// The value of this field is sufficiently high to provide a wide /// dynamic range for values of the `force` field. max_possible_force: f64, /// The altitude (in radians) of the stylus. /// /// A value of 0 radians indicates that the stylus is parallel to the /// surface. The value of this property is Pi/2 when the stylus is /// perpendicular to the surface. altitude_angle: Option<f64>, }, /// If the platform reports the force as normalized, we have no way of /// knowing how much pressure 1.0 corresponds to – we know it's the maximum /// amount of force, but as to how much force, you might either have to /// press really really hard, or not hard at all, depending on the device. Normalized(f64), } impl Force { /// Returns the force normalized to the range between 0.0 and 1.0 inclusive. /// Instead of normalizing the force, you should prefer to handle /// `Force::Calibrated` so that the amount of force the user has to apply is /// consistent across devices. pub fn normalized(&self) -> f64 { match self { Force::Calibrated { force, max_possible_force, altitude_angle, } => { let force = match altitude_angle { Some(altitude_angle) => force / altitude_angle.sin(), None => *force, }; force / max_possible_force } Force::Normalized(force) => *force, } } } /// Hardware-dependent keyboard scan code. pub type ScanCode = u32; /// Identifier for a specific analog axis on some device. pub type AxisId = u32; /// Identifier for a specific button on some device. pub type ButtonId = u32; /// Describes the input state of a key. #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum ElementState { Pressed, Released, } /// Describes a button of a mouse controller. #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum MouseButton { Left, Right, Middle, Other(u8), } /// Describes a difference in the mouse scroll wheel state. #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum MouseScrollDelta { /// Amount in lines or rows to scroll in the horizontal /// and vertical directions. /// /// Positive values indicate movement forward /// (away from the user) or rightwards. LineDelta(f32, f32), /// Amount in pixels to scroll in the horizontal and /// vertical direction. /// /// Scroll events are expressed as a PixelDelta if /// supported by the device (eg. a touchpad) and /// platform. PixelDelta(PhysicalPosition<f64>), } /// Symbolic name for a keyboard key. #[derive(Debug, Hash, Ord, PartialOrd, PartialEq, Eq, Clone, Copy)] #[repr(u32)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum VirtualKeyCode { /// The '1' key over the letters. Key1, /// The '2' key over the letters. Key2, /// The '3' key over the letters. Key3, /// The '4' key over the letters. Key4, /// The '5' key over the letters. Key5, /// The '6' key over the letters. Key6, /// The '7' key over the letters. Key7, /// The '8' key over the letters. Key8, /// The '9' key over the letters. Key9, /// The '0' key over the 'O' and 'P' keys. Key0, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, /// The Escape key, next to F1. Escape, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, /// Print Screen/SysRq. Snapshot, /// Scroll Lock. Scroll, /// Pause/Break key, next to Scroll lock. Pause, /// `Insert`, next to Backspace. Insert, Home, Delete, End, PageDown, PageUp, Left, Up, Right, Down, /// The Backspace key, right over Enter. // TODO: rename Back, /// The Enter key. Return, /// The space bar. Space, /// The "Compose" key on Linux. Compose, Caret, Numlock, Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9, NumpadAdd, NumpadDivide, NumpadDecimal, NumpadComma, NumpadEnter, NumpadEquals, NumpadMultiply, NumpadSubtract, AbntC1, AbntC2, Apostrophe, Apps, Asterisk, At, Ax, Backslash, Calculator, Capital, Colon, Comma, Convert, Equals, Grave, Kana, Kanji, LAlt, LBracket, LControl, LShift, LWin, Mail, MediaSelect, MediaStop, Minus, Mute, MyComputer, // also called "Next" NavigateForward, // also called "Prior" NavigateBackward, NextTrack, NoConvert, OEM102, Period, PlayPause, Plus, Power, PrevTrack, RAlt, RBracket, RControl, RShift, RWin, Semicolon, Slash, Sleep, Stop, Sysrq, Tab, Underline, Unlabeled, VolumeDown, VolumeUp, Wake, WebBack, WebFavorites, WebForward, WebHome, WebRefresh, WebSearch, WebStop, Yen, Copy, Paste, Cut, } impl ModifiersState { /// Returns `true` if the shift key is pressed. pub fn shift(&self) -> bool { self.intersects(Self::SHIFT) } /// Returns `true` if the control key is pressed. pub fn ctrl(&self) -> bool { self.intersects(Self::CTRL) } /// Returns `true` if the alt key is pressed. pub fn alt(&self) -> bool { self.intersects(Self::ALT) } /// Returns `true` if the logo key is pressed. pub fn logo(&self) -> bool { self.intersects(Self::LOGO) } } bitflags! { /// Represents the current state of the keyboard modifiers /// /// Each flag represents a modifier and is set if this modifier is active. #[derive(Default)] pub struct ModifiersState: u32 { // left and right modifiers are currently commented out, but we should be able to support // them in a future release /// The "shift" key. const SHIFT = 0b100 << 0; // const LSHIFT = 0b010 << 0; // const RSHIFT = 0b001 << 0; /// The "control" key. const CTRL = 0b100 << 3; // const LCTRL = 0b010 << 3; // const RCTRL = 0b001 << 3; /// The "alt" key. const ALT = 0b100 << 6; // const LALT = 0b010 << 6; // const RALT = 0b001 << 6; /// This is the "windows" key on PC and "command" key on Mac. const LOGO = 0b100 << 9; // const LLOGO = 0b010 << 9; // const RLOGO = 0b001 << 9; } } #[cfg(feature = "serde")] mod modifiers_serde { use super::ModifiersState; use serde::{Deserialize, Deserializer, Serialize, Serializer}; #[derive(Default, Serialize, Deserialize)] #[serde(default)] #[serde(rename = "ModifiersState")] pub struct ModifiersStateSerialize { pub shift: bool, pub ctrl: bool, pub alt: bool, pub logo: bool, } impl Serialize for ModifiersState { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let s = ModifiersStateSerialize { shift: self.shift(), ctrl: self.ctrl(), alt: self.alt(), logo: self.logo(), }; s.serialize(serializer) } } impl<'de> Deserialize<'de> for ModifiersState { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let ModifiersStateSerialize { shift, ctrl, alt, logo, } = ModifiersStateSerialize::deserialize(deserializer)?; let mut m = ModifiersState::empty(); m.set(ModifiersState::SHIFT, shift); m.set(ModifiersState::CTRL, ctrl); m.set(ModifiersState::ALT, alt); m.set(ModifiersState::LOGO, logo); Ok(m) } } }