raui_core/signals.rs
1//! Widget signals
2//!
3//! Signals are a way for widgets to send [messages][crate::messenger] to the RAUI
4//! [`Application`][crate::application::Application]. This can be used to create custom integrations
5//! with the RAUI host or rendering backend.
6//!
7//! Signals may be sent using the [`SignalSender`] in the widget [change context][change_context] or
8//! [unmount context][unmount_context].
9//!
10//! [change_context]: crate::widget::context::WidgetMountOrChangeContext
11//!
12//! [unmount_context]: crate::widget::context::WidgetUnmountContext
13
14use crate::{
15 messenger::{Message, MessageData},
16 widget::WidgetId,
17};
18use std::sync::mpsc::Sender;
19
20/// A signal is a [message][crate::messenger] sent by a widget that can be read by the
21/// [`Application`][crate::application::Application]
22pub type Signal = (WidgetId, Box<dyn MessageData>);
23
24/// Used to send [`Signal`]s from a component [change context][change_context]
25///
26/// [change_context]: crate::widget::context::WidgetMountOrChangeContext
27#[derive(Clone)]
28pub struct SignalSender {
29 id: WidgetId,
30 sender: Sender<Signal>,
31}
32
33impl SignalSender {
34 /// Create a new [`SignalSender`]
35 pub(crate) fn new(id: WidgetId, sender: Sender<Signal>) -> Self {
36 Self { id, sender }
37 }
38
39 /// Send a message
40 ///
41 /// Returns `false` if the message could not successfully be sent
42 pub fn write<T>(&self, message: T) -> bool
43 where
44 T: 'static + MessageData,
45 {
46 self.sender
47 .send((self.id.clone(), Box::new(message)))
48 .is_ok()
49 }
50
51 /// Send a raw [`Message`]
52 ///
53 /// Returns `false` if the message could not be successfully sent
54 pub fn write_raw(&self, message: Message) -> bool {
55 self.sender.send((self.id.clone(), message)).is_ok()
56 }
57
58 /// Sends a set of raw [`Message`]s from an iterator
59 pub fn write_raw_all<I>(&self, messages: I)
60 where
61 I: IntoIterator<Item = Message>,
62 {
63 for data in messages {
64 let _ = self.sender.send((self.id.clone(), data));
65 }
66 }
67}