pixel_canvas/
input.rs

1//! Pre-built canvas input event handlers.
2//!
3//! These are used with the [`state`] and [`input`] methods on the Canvas.
4//!
5//! [`state`]: ../canvas/struct.Canvas.html#method.state
6//! [`input`]: ../canvas/struct.Canvas.html#method.input
7
8// @Todo: Write docs on how write your own input handler.
9
10use crate::canvas::CanvasInfo;
11/// Re-export the glutin module for writing your own event handlers.
12pub use glium::glutin;
13/// Re-export some common event types that are useful when writing your own
14/// event handlers.
15pub use glium::glutin::event::{Event, WindowEvent};
16
17/// An input handler that tracks the position of the mouse.
18///
19/// It provides physical and virtual coordinates.
20/// - Virtual coordinates (`virtual_x` and `virtual_y`) are as reported by the
21///   OS, which means that they originate from the upper left corner and
22///   account for DPI. You don't want this very often, but if you want to match
23///   the OS coordinates for some reason, this is it.
24/// - Physical coordinates (`x` and `y`) match the pixels in the image. This is
25///   usually what you want.
26pub struct MouseState {
27    /// The x position from the lower-left corner, measured in physical pixels.
28    /// This should always correspond to the column of the pixel in the image.
29    pub x: i32,
30    /// The y position from the lower-left corner, measured in physical pixels.
31    /// This should always correspond to the row of the pixel in the image.
32    pub y: i32,
33    /// The x position from the upper-left corner as reported by the OS,
34    /// measured in virtual pixels.
35    pub virtual_x: i32,
36    /// The y position from the upper-left corner as reported by the OS,
37    /// measured in virtual pixels.
38    pub virtual_y: i32,
39}
40
41impl MouseState {
42    /// Create a MouseState. For use with the `state` method.
43    pub fn new() -> Self {
44        Self {
45            x: 0,
46            y: 0,
47            virtual_x: 0,
48            virtual_y: 0,
49        }
50    }
51
52    /// Handle input for the mouse. For use with the `input` method.
53    pub fn handle_input(info: &CanvasInfo, mouse: &mut MouseState, event: &Event<()>) -> bool {
54        match event {
55            Event::WindowEvent {
56                event: WindowEvent::CursorMoved { position, .. },
57                ..
58            } => {
59                let (x, y): (i32, i32) = (*position).into();
60                mouse.virtual_x = x;
61                mouse.virtual_y = y;
62                mouse.x = (x as f64 * info.dpi) as i32;
63                mouse.y = ((info.height as i32 - y) as f64 * info.dpi) as i32;
64                true
65            }
66            _ => false,
67        }
68    }
69}