To capture events of the window, we implement subscription method in Application.
This method returns Subscription struct, which allows us to specify how to handle events.
We can use listen_with function to construct a Subscription.
The listen_with function takes a function as its input.
The input function takes two parameters, Event and Status, and returns Option<MyAppMessage
>, which means this function is capable of transforming Event to MyAppMessage
.
We then receive the transformed MyAppMessage
in update method.
In the input function, we only care about ignored events (i.e., events that is not handled by widgets) by checking if Status is Status::Ignored.
In this tutorial, we capture Event::Mouse(...) and Event::Touch(...) and produce messages.
use iced::{
event::{self, Event, Status},
executor,
mouse::Event::CursorMoved,
touch::Event::FingerMoved,
widget::text,
Application, Point, Settings,
};
fn main() -> iced::Result {
MyApp::run(Settings::default())
}
#[derive(Debug, Clone)]
enum MyAppMessage {
PointUpdated(Point),
}
struct MyApp {
mouse_point: Point,
}
impl Application for MyApp {
type Executor = executor::Default;
type Message = MyAppMessage;
type Theme = iced::Theme;
type Flags = ();
fn new(_flags: Self::Flags) -> (Self, iced::Command<Self::Message>) {
(
Self {
mouse_point: Point::ORIGIN,
},
iced::Command::none(),
)
}
fn title(&self) -> String {
String::from("My App")
}
fn update(&mut self, message: Self::Message) -> iced::Command<Self::Message> {
match message {
MyAppMessage::PointUpdated(p) => self.mouse_point = p,
}
iced::Command::none()
}
fn view(&self) -> iced::Element<Self::Message> {
text(format!("{:?}", self.mouse_point)).into()
}
fn subscription(&self) -> iced::Subscription<Self::Message> {
event::listen_with(|event, status| match (event, status) {
(Event::Mouse(CursorMoved { position }), Status::Ignored)
| (Event::Touch(FingerMoved { position, .. }), Status::Ignored) => {
Some(MyAppMessage::PointUpdated(position))
}
_ => None,
})
}
}
➡️ Next: Producing Messages By Keyboard Events
📘 Back: Table of contents