Skip to content

Latest commit

 

History

History
88 lines (73 loc) · 3.7 KB

producing_messages_by_mouse_events.md

File metadata and controls

88 lines (73 loc) · 3.7 KB

Producing Messages By Mouse Events

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, Status},
    mouse::Event::CursorMoved,
    touch::Event::FingerMoved,
    widget::text,
    Element, Event, Point, Subscription, Task,
};

fn main() -> iced::Result {
    iced::application(
        "producing messages by mouse events",
        MyApp::update,
        MyApp::view,
    )
    .subscription(MyApp::subscription)
    .run()
}

struct MyApp {
    mouse_point: Point,
}

impl Default for MyApp {
    fn default() -> Self {
        MyApp::new()
    }
}

#[derive(Debug, Clone)]
enum Message {
    PointUpdated(Point),
}

impl MyApp {
    fn new() -> Self {
        Self {
            mouse_point: Point::ORIGIN,
        }
    }

    fn update(&mut self, message: Message) -> Task<Message> {
        match message {
            Message::PointUpdated(p) => {
                self.mouse_point = p;
                return Task::none();
            }
        }
    }

    fn view(&self) -> Element<Message> {
        text(format!("{:?}", self.mouse_point)).into()
    }
  
    fn subscription(&self) -> Subscription<Message> {
        event::listen_with(|event, status, _window| {
            match (event, status) {
                // Using mouse
                (Event::Mouse(CursorMoved { position }), Status::Ignored)
                // Or using touchboard
                | (Event::Touch(FingerMoved {position, ..}), Status::Ignored) => {
                    Some(Message::PointUpdated(position))
                }
                _ => None
            }
        })
    }
}

Producing messages by mouse events

➡️ Next: Producing Messages By Keyboard Events

📘 Back: Table of contents