web_audio_api/
message_port.rs

1use std::any::Any;
2
3use crate::context::AudioContextRegistration;
4use crate::node::AudioNode;
5
6use crate::events::{EventHandler, EventPayload, EventType};
7
8/// One of the two ports of a message channel
9///
10/// Allowing messages to be sent from one port and listening out for them arriving at the other.
11pub struct MessagePort<'a>(&'a AudioContextRegistration);
12
13impl std::fmt::Debug for MessagePort<'_> {
14    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15        f.debug_struct("MessagePort").finish_non_exhaustive()
16    }
17}
18
19impl<'a> MessagePort<'a> {
20    pub(crate) fn from_node(node: &'a dyn AudioNode) -> Self {
21        Self(node.registration())
22    }
23
24    /// Send a message from the port.
25    pub fn post_message<M: Any + Send + 'static>(&self, msg: M) {
26        self.0.post_message(msg);
27    }
28
29    /// Register callback to run when a message arrives on the channel.
30    ///
31    /// Only a single event handler is active at any time. Calling this method multiple times will
32    /// override the previous event handler.
33    pub fn set_onmessage<F: FnMut(Box<dyn Any + Send + 'static>) + Send + 'static>(
34        &self,
35        mut callback: F,
36    ) {
37        let callback = move |v| match v {
38            EventPayload::Message(v) => callback(v),
39            _ => unreachable!(),
40        };
41
42        self.0.context().set_event_handler(
43            EventType::Message(self.0.id()),
44            EventHandler::Multiple(Box::new(callback)),
45        );
46    }
47
48    /// Unset the callback to run when a message arrives on the channel.
49    pub fn clear_onmessage(&self) {
50        self.0
51            .context()
52            .clear_event_handler(EventType::Message(self.0.id()));
53    }
54}