Introduce Cursor type in canvas

This commit is contained in:
Héctor Ramón Jiménez 2020-04-29 04:25:49 +02:00
parent 5586034d66
commit dc51080328
6 changed files with 169 additions and 108 deletions

View File

@ -69,15 +69,13 @@ impl Sandbox for Example {
mod bezier { mod bezier {
use iced::{ use iced::{
canvas::{self, Canvas, Event, Frame, Geometry, Path, Stroke}, canvas::{self, Canvas, Cursor, Event, Frame, Geometry, Path, Stroke},
mouse, ButtonState, Element, Length, MouseCursor, Point, Rectangle, mouse, ButtonState, Element, Length, MouseCursor, Point, Rectangle,
Size,
}; };
#[derive(Default)] #[derive(Default)]
pub struct State { pub struct State {
pending: Option<Pending>, pending: Option<Pending>,
cursor_position: Point,
cache: canvas::Cache, cache: canvas::Cache,
} }
@ -106,31 +104,30 @@ mod bezier {
} }
impl<'a> canvas::Program<Curve> for Bezier<'a> { impl<'a> canvas::Program<Curve> for Bezier<'a> {
fn update(&mut self, event: Event, bounds: Size) -> Option<Curve> { fn update(
&mut self,
event: Event,
bounds: Rectangle,
cursor: Cursor,
) -> Option<Curve> {
let cursor_position = cursor.internal_position(&bounds)?;
match event { match event {
Event::Mouse(mouse_event) => match mouse_event { Event::Mouse(mouse_event) => match mouse_event {
mouse::Event::CursorMoved { x, y } => {
self.state.cursor_position = Point::new(x, y);
None
}
mouse::Event::Input { mouse::Event::Input {
button: mouse::Button::Left, button: mouse::Button::Left,
state: ButtonState::Pressed, state: ButtonState::Pressed,
} if Rectangle::with_size(bounds) } => match self.state.pending {
.contains(self.state.cursor_position) =>
{
match self.state.pending {
None => { None => {
self.state.pending = Some(Pending::One { self.state.pending = Some(Pending::One {
from: self.state.cursor_position, from: cursor_position,
}); });
None None
} }
Some(Pending::One { from }) => { Some(Pending::One { from }) => {
self.state.pending = Some(Pending::Two { self.state.pending = Some(Pending::Two {
from, from,
to: self.state.cursor_position, to: cursor_position,
}); });
None None
@ -141,18 +138,18 @@ mod bezier {
Some(Curve { Some(Curve {
from, from,
to, to,
control: self.state.cursor_position, control: cursor_position,
}) })
} }
} },
}
_ => None, _ => None,
}, },
} }
} }
fn draw(&self, bounds: Size) -> Vec<Geometry> { fn draw(&self, bounds: Rectangle, cursor: Cursor) -> Vec<Geometry> {
let content = self.state.cache.draw(bounds, |frame: &mut Frame| { let content =
self.state.cache.draw(bounds.size(), |frame: &mut Frame| {
Curve::draw_all(self.curves, frame); Curve::draw_all(self.curves, frame);
frame.stroke( frame.stroke(
@ -162,8 +159,7 @@ mod bezier {
}); });
if let Some(pending) = &self.state.pending { if let Some(pending) = &self.state.pending {
let pending_curve = let pending_curve = pending.draw(bounds, cursor);
pending.draw(bounds, self.state.cursor_position);
vec![content, pending_curve] vec![content, pending_curve]
} else { } else {
@ -171,9 +167,12 @@ mod bezier {
} }
} }
fn mouse_cursor(&self, bounds: Size) -> MouseCursor { fn mouse_cursor(
if Rectangle::with_size(bounds).contains(self.state.cursor_position) &self,
{ bounds: Rectangle,
cursor: Cursor,
) -> MouseCursor {
if cursor.is_over(&bounds) {
MouseCursor::Crosshair MouseCursor::Crosshair
} else { } else {
MouseCursor::default() MouseCursor::default()
@ -208,9 +207,10 @@ mod bezier {
} }
impl Pending { impl Pending {
fn draw(&self, bounds: Size, cursor_position: Point) -> Geometry { fn draw(&self, bounds: Rectangle, cursor: Cursor) -> Geometry {
let mut frame = Frame::new(bounds); let mut frame = Frame::new(bounds.size());
if let Some(cursor_position) = cursor.internal_position(&bounds) {
match *self { match *self {
Pending::One { from } => { Pending::One { from } => {
let line = Path::line(from, cursor_position); let line = Path::line(from, cursor_position);
@ -226,6 +226,7 @@ mod bezier {
Curve::draw_all(&[curve], &mut frame); Curve::draw_all(&[curve], &mut frame);
} }
}; };
}
frame.into_geometry() frame.into_geometry()
} }

View File

@ -1,7 +1,7 @@
use iced::{ use iced::{
canvas::{self, Cache, Canvas, Geometry, LineCap, Path, Stroke}, canvas::{self, Cache, Canvas, Cursor, Geometry, LineCap, Path, Stroke},
executor, Application, Color, Command, Container, Element, Length, Point, executor, Application, Color, Command, Container, Element, Length, Point,
Settings, Size, Subscription, Vector, Rectangle, Settings, Subscription, Vector,
}; };
pub fn main() { pub fn main() {
@ -75,10 +75,10 @@ impl Application for Clock {
} }
impl canvas::Program<Message> for Clock { impl canvas::Program<Message> for Clock {
fn draw(&self, bounds: Size) -> Vec<Geometry> { fn draw(&self, bounds: Rectangle, _cursor: Cursor) -> Vec<Geometry> {
use chrono::Timelike; use chrono::Timelike;
let clock = self.clock.draw(bounds, |frame| { let clock = self.clock.draw(bounds.size(), |frame| {
let center = frame.center(); let center = frame.center();
let radius = frame.width().min(frame.height()) / 2.0; let radius = frame.width().min(frame.height()) / 2.0;

View File

@ -7,8 +7,9 @@
//! //!
//! [1]: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations#An_animated_solar_system //! [1]: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations#An_animated_solar_system
use iced::{ use iced::{
canvas, executor, window, Application, Canvas, Color, Command, Element, canvas::{self, Cursor, Path, Stroke},
Length, Point, Settings, Size, Subscription, Vector, executor, window, Application, Canvas, Color, Command, Element, Length,
Point, Rectangle, Settings, Size, Subscription, Vector,
}; };
use std::time::Instant; use std::time::Instant;
@ -132,11 +133,14 @@ impl State {
} }
impl<Message> canvas::Program<Message> for State { impl<Message> canvas::Program<Message> for State {
fn draw(&self, bounds: Size) -> Vec<canvas::Geometry> { fn draw(
use canvas::{Path, Stroke}; &self,
bounds: Rectangle,
_cursor: Cursor,
) -> Vec<canvas::Geometry> {
use std::f32::consts::PI; use std::f32::consts::PI;
let background = self.space_cache.draw(bounds, |frame| { let background = self.space_cache.draw(bounds.size(), |frame| {
let space = Path::rectangle(Point::new(0.0, 0.0), frame.size()); let space = Path::rectangle(Point::new(0.0, 0.0), frame.size());
let stars = Path::new(|path| { let stars = Path::new(|path| {
@ -151,7 +155,7 @@ impl<Message> canvas::Program<Message> for State {
frame.fill(&stars, Color::WHITE); frame.fill(&stars, Color::WHITE);
}); });
let system = self.system_cache.draw(bounds, |frame| { let system = self.system_cache.draw(bounds.size(), |frame| {
let center = frame.center(); let center = frame.center();
let sun = Path::circle(center, Self::SUN_RADIUS); let sun = Path::circle(center, Self::SUN_RADIUS);

View File

@ -9,8 +9,8 @@
use crate::{Defaults, Primitive, Renderer}; use crate::{Defaults, Primitive, Renderer};
use iced_native::{ use iced_native::{
input::mouse, layout, Clipboard, Element, Hasher, Layout, Length, layout, Clipboard, Element, Hasher, Layout, Length, MouseCursor, Point,
MouseCursor, Point, Size, Vector, Widget, Size, Vector, Widget,
}; };
use std::hash::Hash; use std::hash::Hash;
use std::marker::PhantomData; use std::marker::PhantomData;
@ -18,6 +18,7 @@ use std::marker::PhantomData;
pub mod path; pub mod path;
mod cache; mod cache;
mod cursor;
mod event; mod event;
mod fill; mod fill;
mod frame; mod frame;
@ -27,6 +28,7 @@ mod stroke;
mod text; mod text;
pub use cache::Cache; pub use cache::Cache;
pub use cursor::Cursor;
pub use event::Event; pub use event::Event;
pub use fill::Fill; pub use fill::Fill;
pub use frame::Frame; pub use frame::Frame;
@ -59,10 +61,10 @@ pub use text::Text;
/// ```no_run /// ```no_run
/// # mod iced { /// # mod iced {
/// # pub use iced_wgpu::canvas; /// # pub use iced_wgpu::canvas;
/// # pub use iced_native::{Color, Size}; /// # pub use iced_native::{Color, Rectangle};
/// # } /// # }
/// use iced::canvas::{self, Cache, Canvas, Fill, Frame, Geometry, Path, Program}; /// use iced::canvas::{self, Canvas, Cursor, Fill, Frame, Geometry, Path, Program};
/// use iced::{Color, Size}; /// use iced::{Color, Rectangle};
/// ///
/// // First, we define the data we need for drawing /// // First, we define the data we need for drawing
/// #[derive(Debug)] /// #[derive(Debug)]
@ -72,9 +74,9 @@ pub use text::Text;
/// ///
/// // Then, we implement the `Program` trait /// // Then, we implement the `Program` trait
/// impl Program<()> for Circle { /// impl Program<()> for Circle {
/// fn draw(&self, bounds: Size) -> Vec<Geometry>{ /// fn draw(&self, bounds: Rectangle, _cursor: Cursor) -> Vec<Geometry>{
/// // We prepare a new `Frame` /// // We prepare a new `Frame`
/// let mut frame = Frame::new(bounds); /// let mut frame = Frame::new(bounds.size());
/// ///
/// // We create a `Path` representing a simple circle /// // We create a `Path` representing a simple circle
/// let circle = Path::circle(frame.center(), self.radius); /// let circle = Path::circle(frame.center(), self.radius);
@ -165,22 +167,16 @@ impl<Message, P: Program<Message>> Widget<Message, Renderer>
let canvas_event = match event { let canvas_event = match event {
iced_native::Event::Mouse(mouse_event) => { iced_native::Event::Mouse(mouse_event) => {
Some(Event::Mouse(match mouse_event { Some(Event::Mouse(mouse_event))
mouse::Event::CursorMoved { .. } => {
mouse::Event::CursorMoved {
x: cursor_position.x - bounds.x,
y: cursor_position.y - bounds.y,
}
}
_ => mouse_event,
}))
} }
_ => None, _ => None,
}; };
let cursor = Cursor::from_window_position(cursor_position);
if let Some(canvas_event) = canvas_event { if let Some(canvas_event) = canvas_event {
if let Some(message) = if let Some(message) =
self.program.update(canvas_event, bounds.size()) self.program.update(canvas_event, bounds, cursor)
{ {
messages.push(message); messages.push(message);
} }
@ -192,11 +188,11 @@ impl<Message, P: Program<Message>> Widget<Message, Renderer>
_renderer: &mut Renderer, _renderer: &mut Renderer,
_defaults: &Defaults, _defaults: &Defaults,
layout: Layout<'_>, layout: Layout<'_>,
_cursor_position: Point, cursor_position: Point,
) -> (Primitive, MouseCursor) { ) -> (Primitive, MouseCursor) {
let bounds = layout.bounds(); let bounds = layout.bounds();
let translation = Vector::new(bounds.x, bounds.y); let translation = Vector::new(bounds.x, bounds.y);
let size = Size::new(bounds.width, bounds.height); let cursor = Cursor::from_window_position(cursor_position);
( (
Primitive::Translate { Primitive::Translate {
@ -204,13 +200,13 @@ impl<Message, P: Program<Message>> Widget<Message, Renderer>
content: Box::new(Primitive::Group { content: Box::new(Primitive::Group {
primitives: self primitives: self
.program .program
.draw(size) .draw(bounds, cursor)
.into_iter() .into_iter()
.map(Geometry::into_primitive) .map(Geometry::into_primitive)
.collect(), .collect(),
}), }),
}, },
self.program.mouse_cursor(size), self.program.mouse_cursor(bounds, cursor),
) )
} }

View File

@ -0,0 +1,50 @@
use iced_native::{Point, Rectangle};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Cursor {
Available(Point),
Unavailable,
}
impl Cursor {
// TODO: Remove this once this type is used in `iced_native` to encode
// proper cursor availability
pub(crate) fn from_window_position(position: Point) -> Self {
if position.x < 0.0 || position.y < 0.0 {
Cursor::Unavailable
} else {
Cursor::Available(position)
}
}
pub fn position(&self) -> Option<Point> {
match self {
Cursor::Available(position) => Some(*position),
Cursor::Unavailable => None,
}
}
pub fn relative_position(&self, bounds: &Rectangle) -> Option<Point> {
match self {
Cursor::Available(position) => {
Some(Point::new(position.x - bounds.x, position.y - bounds.y))
}
_ => None,
}
}
pub fn internal_position(&self, bounds: &Rectangle) -> Option<Point> {
if self.is_over(bounds) {
self.relative_position(bounds)
} else {
None
}
}
pub fn is_over(&self, bounds: &Rectangle) -> bool {
match self {
Cursor::Available(position) => bounds.contains(*position),
Cursor::Unavailable => false,
}
}
}

View File

@ -1,14 +1,19 @@
use crate::canvas::{Event, Geometry, Size}; use crate::canvas::{Cursor, Event, Geometry};
use iced_native::MouseCursor; use iced_native::{MouseCursor, Rectangle};
pub trait Program<Message> { pub trait Program<Message> {
fn update(&mut self, _event: Event, _bounds: Size) -> Option<Message> { fn update(
&mut self,
_event: Event,
_bounds: Rectangle,
_cursor: Cursor,
) -> Option<Message> {
None None
} }
fn draw(&self, bounds: Size) -> Vec<Geometry>; fn draw(&self, bounds: Rectangle, cursor: Cursor) -> Vec<Geometry>;
fn mouse_cursor(&self, _bounds: Size) -> MouseCursor { fn mouse_cursor(&self, _bounds: Rectangle, _cursor: Cursor) -> MouseCursor {
MouseCursor::default() MouseCursor::default()
} }
} }
@ -17,15 +22,20 @@ impl<T, Message> Program<Message> for &mut T
where where
T: Program<Message>, T: Program<Message>,
{ {
fn update(&mut self, event: Event, bounds: Size) -> Option<Message> { fn update(
T::update(self, event, bounds) &mut self,
event: Event,
bounds: Rectangle,
cursor: Cursor,
) -> Option<Message> {
T::update(self, event, bounds, cursor)
} }
fn draw(&self, bounds: Size) -> Vec<Geometry> { fn draw(&self, bounds: Rectangle, cursor: Cursor) -> Vec<Geometry> {
T::draw(self, bounds) T::draw(self, bounds, cursor)
} }
fn mouse_cursor(&self, bounds: Size) -> MouseCursor { fn mouse_cursor(&self, bounds: Rectangle, cursor: Cursor) -> MouseCursor {
T::mouse_cursor(self, bounds) T::mouse_cursor(self, bounds, cursor)
} }
} }