iced_futures/
event.rs

1//! Listen to runtime events.
2use crate::core::event::{self, Event};
3use crate::core::window;
4use crate::subscription::{self, Subscription};
5use crate::MaybeSend;
6
7/// Returns a [`Subscription`] to all the ignored runtime events.
8///
9/// This subscription will notify your application of any [`Event`] that was
10/// not captured by any widget.
11pub fn listen() -> Subscription<Event> {
12    listen_with(|event, status, _window| match status {
13        event::Status::Ignored => Some(event),
14        event::Status::Captured => None,
15    })
16}
17
18/// Creates a [`Subscription`] that listens and filters all the runtime events
19/// with the provided function, producing messages accordingly.
20///
21/// This subscription will call the provided function for every [`Event`]
22/// handled by the runtime. If the function:
23///
24/// - Returns `None`, the [`Event`] will be discarded.
25/// - Returns `Some` message, the `Message` will be produced.
26pub fn listen_with<Message>(
27    f: fn(Event, event::Status, window::Id) -> Option<Message>,
28) -> Subscription<Message>
29where
30    Message: 'static + MaybeSend,
31{
32    #[derive(Hash)]
33    struct EventsWith;
34
35    subscription::filter_map((EventsWith, f), move |event| match event {
36        subscription::Event::Interaction {
37            event: Event::Window(window::Event::RedrawRequested(_)),
38            ..
39        } => None,
40        subscription::Event::Interaction {
41            window,
42            event,
43            status,
44        } => f(event, status, window),
45    })
46}
47
48/// Creates a [`Subscription`] that produces a message for every runtime event,
49/// including the redraw request events.
50///
51/// **Warning:** This [`Subscription`], if unfiltered, may produce messages in
52/// an infinite loop.
53pub fn listen_raw<Message>(
54    f: fn(Event, event::Status, window::Id) -> Option<Message>,
55) -> Subscription<Message>
56where
57    Message: 'static + MaybeSend,
58{
59    #[derive(Hash)]
60    struct RawEvents;
61
62    subscription::filter_map((RawEvents, f), move |event| match event {
63        subscription::Event::Interaction {
64            window,
65            event,
66            status,
67        } => f(event, status, window),
68    })
69}