iced_futures/
subscription.rs

1//! Listen to external events in your application.
2mod tracker;
3
4pub use tracker::Tracker;
5
6use crate::core::event;
7use crate::core::theme;
8use crate::core::window;
9use crate::futures::Stream;
10use crate::{BoxStream, MaybeSend};
11
12use std::any::TypeId;
13use std::hash::Hash;
14
15/// A subscription event.
16#[derive(Debug, Clone, PartialEq)]
17pub enum Event {
18    /// A user interacted with a user interface in a window.
19    Interaction {
20        /// The window holding the interface of the interaction.
21        window: window::Id,
22        /// The [`Event`] describing the interaction.
23        ///
24        /// [`Event`]: event::Event
25        event: event::Event,
26
27        /// The [`event::Status`] of the interaction.
28        status: event::Status,
29    },
30
31    /// The system theme has changed.
32    SystemThemeChanged(theme::Mode),
33
34    /// A platform specific event.
35    PlatformSpecific(PlatformSpecific),
36}
37
38/// A platform specific event
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum PlatformSpecific {
41    /// A MacOS specific event
42    MacOS(MacOS),
43}
44
45/// Describes an event specific to MacOS
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum MacOS {
48    /// Triggered when the app receives an URL from the system
49    ///
50    /// _**Note:** For this event to be triggered, the executable needs to be properly [bundled]!_
51    ///
52    /// [bundled]: https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/BundleTypes/BundleTypes.html#//apple_ref/doc/uid/10000123i-CH101-SW19
53    ReceivedUrl(String),
54}
55
56/// A stream of runtime events.
57///
58/// It is the input of a [`Subscription`].
59pub type EventStream = BoxStream<Event>;
60
61/// The hasher used for identifying subscriptions.
62pub type Hasher = rustc_hash::FxHasher;
63
64/// A request to listen to external events.
65///
66/// Besides performing async actions on demand with `Task`, most
67/// applications also need to listen to external events passively.
68///
69/// A [`Subscription`] is normally provided to some runtime, like a `Task`,
70/// and it will generate events as long as the user keeps requesting it.
71///
72/// For instance, you can use a [`Subscription`] to listen to a `WebSocket`
73/// connection, keyboard presses, mouse events, time ticks, etc.
74///
75/// # The Lifetime of a [`Subscription`]
76/// Much like a [`Future`] or a [`Stream`], a [`Subscription`] does not produce any effects
77/// on its own. For a [`Subscription`] to run, it must be returned to the iced runtime—normally
78/// in the `subscription` function of an `application` or a `daemon`.
79///
80/// When a [`Subscription`] is provided to the runtime for the first time, the runtime will
81/// start running it asynchronously. Running a [`Subscription`] consists in building its underlying
82/// [`Stream`] and executing it in an async runtime.
83///
84/// Therefore, you can think of a [`Subscription`] as a "stream builder". It simply represents a way
85/// to build a certain [`Stream`] together with some way to _identify_ it.
86///
87/// Identification is important because when a specific [`Subscription`] stops being returned to the
88/// iced runtime, the runtime will kill its associated [`Stream`]. The runtime uses the identity of a
89/// [`Subscription`] to keep track of it.
90///
91/// This way, iced allows you to declaratively __subscribe__ to particular streams of data temporarily
92/// and whenever necessary.
93///
94/// ```
95/// # mod iced {
96/// #     pub mod time {
97/// #         pub use iced_futures::backend::default::time::every;
98/// #         pub use std::time::{Duration, Instant};
99/// #     }
100/// #
101/// #     pub use iced_futures::Subscription;
102/// # }
103/// use iced::time::{self, Duration, Instant};
104/// use iced::Subscription;
105///
106/// struct State {
107///     timer_enabled: bool,
108/// }
109///
110/// fn subscription(state: &State) -> Subscription<Instant> {
111///     if state.timer_enabled {
112///         time::every(Duration::from_secs(1))
113///     } else {
114///         Subscription::none()
115///     }
116/// }
117/// ```
118///
119/// [`Future`]: std::future::Future
120#[must_use = "`Subscription` must be returned to the runtime to take effect; normally in your `subscription` function."]
121pub struct Subscription<T> {
122    recipes: Vec<Box<dyn Recipe<Output = T>>>,
123}
124
125impl<T> Subscription<T> {
126    /// Returns an empty [`Subscription`] that will not produce any output.
127    pub fn none() -> Self {
128        Self {
129            recipes: Vec::new(),
130        }
131    }
132
133    /// Returns a [`Subscription`] that will call the given function to create and
134    /// asynchronously run the given [`Stream`].
135    ///
136    /// # Creating an asynchronous worker with bidirectional communication
137    /// You can leverage this helper to create a [`Subscription`] that spawns
138    /// an asynchronous worker in the background and establish a channel of
139    /// communication with an `iced` application.
140    ///
141    /// You can achieve this by creating an `mpsc` channel inside the closure
142    /// and returning the `Sender` as a `Message` for the `Application`:
143    ///
144    /// ```
145    /// # mod iced {
146    /// #     pub use iced_futures::Subscription;   
147    /// #     pub use iced_futures::futures;
148    /// #     pub use iced_futures::stream;
149    /// # }
150    /// use iced::futures::channel::mpsc;
151    /// use iced::futures::sink::SinkExt;
152    /// use iced::futures::Stream;
153    /// use iced::stream;
154    /// use iced::Subscription;
155    ///
156    /// pub enum Event {
157    ///     Ready(mpsc::Sender<Input>),
158    ///     WorkFinished,
159    ///     // ...
160    /// }
161    ///
162    /// enum Input {
163    ///     DoSomeWork,
164    ///     // ...
165    /// }
166    ///
167    /// fn some_worker() -> impl Stream<Item = Event> {
168    ///     stream::channel(100, async |mut output| {
169    ///         // Create channel
170    ///         let (sender, mut receiver) = mpsc::channel(100);
171    ///
172    ///         // Send the sender back to the application
173    ///         output.send(Event::Ready(sender)).await;
174    ///
175    ///         loop {
176    ///             use iced_futures::futures::StreamExt;
177    ///
178    ///             // Read next input sent from `Application`
179    ///             let input = receiver.select_next_some().await;
180    ///
181    ///             match input {
182    ///                 Input::DoSomeWork => {
183    ///                     // Do some async work...
184    ///
185    ///                     // Finally, we can optionally produce a message to tell the
186    ///                     // `Application` the work is done
187    ///                     output.send(Event::WorkFinished).await;
188    ///                 }
189    ///             }
190    ///         }
191    ///     })
192    /// }
193    ///
194    /// fn subscription() -> Subscription<Event> {
195    ///     Subscription::run(some_worker)
196    /// }
197    /// ```
198    ///
199    /// Check out the [`websocket`] example, which showcases this pattern to maintain a `WebSocket`
200    /// connection open.
201    ///
202    /// [`websocket`]: https://github.com/iced-rs/iced/tree/0.13/examples/websocket
203    pub fn run<S>(builder: fn() -> S) -> Self
204    where
205        S: Stream<Item = T> + MaybeSend + 'static,
206        T: 'static,
207    {
208        from_recipe(Runner {
209            data: builder,
210            spawn: |builder, _| builder(),
211        })
212    }
213
214    /// Returns a [`Subscription`] that will create and asynchronously run the
215    /// given [`Stream`].
216    ///
217    /// Both the `data` and the function pointer will be used to uniquely identify
218    /// the [`Subscription`].
219    pub fn run_with<D, S>(data: D, builder: fn(&D) -> S) -> Self
220    where
221        D: Hash + 'static,
222        S: Stream<Item = T> + MaybeSend + 'static,
223        T: 'static,
224    {
225        from_recipe(Runner {
226            data: (data, builder),
227            spawn: |(data, builder), _| builder(data),
228        })
229    }
230
231    /// Batches all the provided subscriptions and returns the resulting
232    /// [`Subscription`].
233    pub fn batch(
234        subscriptions: impl IntoIterator<Item = Subscription<T>>,
235    ) -> Self {
236        Self {
237            recipes: subscriptions
238                .into_iter()
239                .flat_map(|subscription| subscription.recipes)
240                .collect(),
241        }
242    }
243
244    /// Adds a value to the [`Subscription`] context.
245    ///
246    /// The value will be part of the identity of a [`Subscription`].
247    pub fn with<A>(mut self, value: A) -> Subscription<(A, T)>
248    where
249        T: 'static,
250        A: std::hash::Hash + Clone + Send + Sync + 'static,
251    {
252        Subscription {
253            recipes: self
254                .recipes
255                .drain(..)
256                .map(|recipe| {
257                    Box::new(With::new(recipe, value.clone()))
258                        as Box<dyn Recipe<Output = (A, T)>>
259                })
260                .collect(),
261        }
262    }
263
264    /// Transforms the [`Subscription`] output with the given function.
265    ///
266    /// # Panics
267    /// The closure provided must be a non-capturing closure. The method
268    /// will panic in debug mode otherwise.
269    pub fn map<F, A>(mut self, f: F) -> Subscription<A>
270    where
271        T: 'static,
272        F: Fn(T) -> A + MaybeSend + Clone + 'static,
273        A: 'static,
274    {
275        debug_assert!(
276            std::mem::size_of::<F>() == 0,
277            "the closure {} provided in `Subscription::map` is capturing",
278            std::any::type_name::<F>(),
279        );
280
281        Subscription {
282            recipes: self
283                .recipes
284                .drain(..)
285                .map(move |recipe| {
286                    Box::new(Map::new(recipe, f.clone()))
287                        as Box<dyn Recipe<Output = A>>
288                })
289                .collect(),
290        }
291    }
292
293    /// Returns the amount of recipe units in this [`Subscription`].
294    pub fn units(&self) -> usize {
295        self.recipes.len()
296    }
297}
298
299/// Creates a [`Subscription`] from a [`Recipe`] describing it.
300pub fn from_recipe<T>(
301    recipe: impl Recipe<Output = T> + 'static,
302) -> Subscription<T> {
303    Subscription {
304        recipes: vec![Box::new(recipe)],
305    }
306}
307
308/// Returns the different recipes of the [`Subscription`].
309pub fn into_recipes<T>(
310    subscription: Subscription<T>,
311) -> Vec<Box<dyn Recipe<Output = T>>> {
312    subscription.recipes
313}
314
315impl<T> std::fmt::Debug for Subscription<T> {
316    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317        f.debug_struct("Subscription").finish()
318    }
319}
320
321/// The description of a [`Subscription`].
322///
323/// A [`Recipe`] is the internal definition of a [`Subscription`]. It is used
324/// by runtimes to run and identify subscriptions. You can use it to create your
325/// own!
326///
327/// # Examples
328/// The repository has a couple of [examples] that use a custom [`Recipe`]:
329///
330/// - [`download_progress`], a basic application that asynchronously downloads
331///   a dummy file of 100 MB and tracks the download progress.
332/// - [`stopwatch`], a watch with start/stop and reset buttons showcasing how
333///   to listen to time.
334///
335/// [examples]: https://github.com/iced-rs/iced/tree/0.13/examples
336/// [`download_progress`]: https://github.com/iced-rs/iced/tree/0.13/examples/download_progress
337/// [`stopwatch`]: https://github.com/iced-rs/iced/tree/0.13/examples/stopwatch
338pub trait Recipe {
339    /// The events that will be produced by a [`Subscription`] with this
340    /// [`Recipe`].
341    type Output;
342
343    /// Hashes the [`Recipe`].
344    ///
345    /// This is used by runtimes to uniquely identify a [`Subscription`].
346    fn hash(&self, state: &mut Hasher);
347
348    /// Executes the [`Recipe`] and produces the stream of events of its
349    /// [`Subscription`].
350    fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output>;
351}
352
353struct Map<A, B, F>
354where
355    F: Fn(A) -> B + 'static,
356{
357    recipe: Box<dyn Recipe<Output = A>>,
358    mapper: F,
359}
360
361impl<A, B, F> Map<A, B, F>
362where
363    F: Fn(A) -> B + 'static,
364{
365    fn new(recipe: Box<dyn Recipe<Output = A>>, mapper: F) -> Self {
366        Map { recipe, mapper }
367    }
368}
369
370impl<A, B, F> Recipe for Map<A, B, F>
371where
372    A: 'static,
373    B: 'static,
374    F: Fn(A) -> B + 'static + MaybeSend,
375{
376    type Output = B;
377
378    fn hash(&self, state: &mut Hasher) {
379        TypeId::of::<F>().hash(state);
380        self.recipe.hash(state);
381    }
382
383    fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output> {
384        use futures::StreamExt;
385
386        let mapper = self.mapper;
387
388        Box::pin(self.recipe.stream(input).map(mapper))
389    }
390}
391
392struct With<A, B> {
393    recipe: Box<dyn Recipe<Output = A>>,
394    value: B,
395}
396
397impl<A, B> With<A, B> {
398    fn new(recipe: Box<dyn Recipe<Output = A>>, value: B) -> Self {
399        With { recipe, value }
400    }
401}
402
403impl<A, B> Recipe for With<A, B>
404where
405    A: 'static,
406    B: 'static + std::hash::Hash + Clone + Send + Sync,
407{
408    type Output = (B, A);
409
410    fn hash(&self, state: &mut Hasher) {
411        std::any::TypeId::of::<B>().hash(state);
412        self.value.hash(state);
413        self.recipe.hash(state);
414    }
415
416    fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output> {
417        use futures::StreamExt;
418
419        let value = self.value;
420
421        Box::pin(
422            self.recipe
423                .stream(input)
424                .map(move |element| (value.clone(), element)),
425        )
426    }
427}
428
429/// Creates a [`Subscription`] from a hashable id and a filter function.
430pub fn filter_map<I, F, T>(id: I, f: F) -> Subscription<T>
431where
432    I: Hash + 'static,
433    F: Fn(Event) -> Option<T> + MaybeSend + 'static,
434    T: 'static + MaybeSend,
435{
436    from_recipe(Runner {
437        data: id,
438        spawn: |_, events| {
439            use futures::future;
440            use futures::stream::StreamExt;
441
442            events.filter_map(move |event| future::ready(f(event)))
443        },
444    })
445}
446
447struct Runner<I, F, S, T>
448where
449    F: FnOnce(&I, EventStream) -> S,
450    S: Stream<Item = T>,
451{
452    data: I,
453    spawn: F,
454}
455
456impl<I, F, S, T> Recipe for Runner<I, F, S, T>
457where
458    I: Hash + 'static,
459    F: FnOnce(&I, EventStream) -> S,
460    S: Stream<Item = T> + MaybeSend + 'static,
461{
462    type Output = T;
463
464    fn hash(&self, state: &mut Hasher) {
465        std::any::TypeId::of::<I>().hash(state);
466        self.data.hash(state);
467    }
468
469    fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output> {
470        crate::boxed_stream((self.spawn)(&self.data, input))
471    }
472}