iced_core/mouse/
cursor.rs

1use crate::{Point, Rectangle, Vector};
2
3/// The mouse cursor state.
4#[derive(Debug, Clone, Copy, PartialEq, Default)]
5pub enum Cursor {
6    /// The cursor has a defined position.
7    Available(Point),
8
9    /// The cursor is currently unavailable (i.e. out of bounds or busy).
10    #[default]
11    Unavailable,
12}
13
14impl Cursor {
15    /// Returns the absolute position of the [`Cursor`], if available.
16    pub fn position(self) -> Option<Point> {
17        match self {
18            Cursor::Available(position) => Some(position),
19            Cursor::Unavailable => None,
20        }
21    }
22
23    /// Returns the absolute position of the [`Cursor`], if available and inside
24    /// the given bounds.
25    ///
26    /// If the [`Cursor`] is not over the provided bounds, this method will
27    /// return `None`.
28    pub fn position_over(self, bounds: Rectangle) -> Option<Point> {
29        self.position().filter(|p| bounds.contains(*p))
30    }
31
32    /// Returns the relative position of the [`Cursor`] inside the given bounds,
33    /// if available.
34    ///
35    /// If the [`Cursor`] is not over the provided bounds, this method will
36    /// return `None`.
37    pub fn position_in(self, bounds: Rectangle) -> Option<Point> {
38        self.position_over(bounds)
39            .map(|p| p - Vector::new(bounds.x, bounds.y))
40    }
41
42    /// Returns the relative position of the [`Cursor`] from the given origin,
43    /// if available.
44    pub fn position_from(self, origin: Point) -> Option<Point> {
45        self.position().map(|p| p - Vector::new(origin.x, origin.y))
46    }
47
48    /// Returns true if the [`Cursor`] is over the given `bounds`.
49    pub fn is_over(self, bounds: Rectangle) -> bool {
50        self.position_over(bounds).is_some()
51    }
52}