To capture events of the window, we implement subscription by instantiating an application with the iced::application function.
We need to pass to this function a function that returns a Subscription. This function receives as parameter the application state itself.
We can use listen_with function to construct a Subscription.
The listen_with function takes a function as its input.
The input function takes three parameters, Event, Status, and the Id of the window. It returns an Option<Message>, which means this function is capable of transforming Event to Message.
We then receive the transformed Message in the update method of our application.
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::{
Point, Task,
event::{self, Event, Status},
mouse::Event::CursorMoved,
touch::Event::FingerMoved,
widget::text,
};
fn main() -> iced::Result {
iced::application("My App", MyApp::update, MyApp::view)
.subscription(MyApp::subscription)
.run_with(MyApp::new)
}
#[derive(Debug, Clone)]
enum Message {
PointUpdated(Point),
}
#[derive(Default)]
struct MyApp {
mouse_point: Point,
}
impl MyApp {
fn new() -> (Self, Task<Message>) {
(
Self {
mouse_point: Point::ORIGIN,
},
Task::none(),
)
}
fn update(&mut self, message: Message) -> Task<Message> {
match message {
Message::PointUpdated(p) => self.mouse_point = p,
}
Task::none()
}
fn view(&self) -> iced::Element<Message> {
text(format!("{:?}", self.mouse_point)).into()
}
fn subscription(&self) -> iced::Subscription<Message> {
event::listen_with(|event, status, _| match (event, status) {
(Event::Mouse(CursorMoved { position }), Status::Ignored)
| (Event::Touch(FingerMoved { position, .. }), Status::Ignored) => {
Some(Message::PointUpdated(position))
}
_ => None,
})
}
}➡️ Next: Producing Messages By Keyboard Events
📘 Back: Table of contents
