iced_futures/
event.rs

1//! Listen to runtime events.
2use crate::MaybeSend;
3use crate::core::event::{self, Event};
4use crate::core::window;
5use crate::subscription::{self, Subscription};
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        }
40        | subscription::Event::SystemThemeChanged(_) => None,
41        subscription::Event::Interaction {
42            window,
43            event,
44            status,
45        } => f(event, status, window),
46    })
47}
48
49/// Creates a [`Subscription`] that produces a message for every runtime event,
50/// including the redraw request events.
51///
52/// **Warning:** This [`Subscription`], if unfiltered, may produce messages in
53/// an infinite loop.
54pub fn listen_raw<Message>(
55    f: fn(Event, event::Status, window::Id) -> Option<Message>,
56) -> Subscription<Message>
57where
58    Message: 'static + MaybeSend,
59{
60    #[derive(Hash)]
61    struct RawEvents;
62
63    subscription::filter_map((RawEvents, f), move |event| match event {
64        subscription::Event::Interaction {
65            window,
66            event,
67            status,
68        } => f(event, status, window),
69        subscription::Event::SystemThemeChanged(_) => None,
70    })
71}