1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use crate::context::AudioNodeId;
use crate::AudioRenderCapacityEvent;
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::{Arc, Mutex};
use crossbeam_channel::Receiver;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Event {
pub type_: &'static str,
}
#[derive(Hash, Eq, PartialEq)]
pub(crate) enum EventType {
Ended(AudioNodeId),
SinkChange,
RenderCapacity,
}
pub(crate) enum EventPayload {
None,
RenderCapacity(AudioRenderCapacityEvent),
}
pub(crate) struct EventDispatch {
type_: EventType,
payload: EventPayload,
}
impl EventDispatch {
pub fn ended(id: AudioNodeId) -> Self {
EventDispatch {
type_: EventType::Ended(id),
payload: EventPayload::None,
}
}
pub fn sink_change() -> Self {
EventDispatch {
type_: EventType::SinkChange,
payload: EventPayload::None,
}
}
pub fn render_capacity(value: AudioRenderCapacityEvent) -> Self {
EventDispatch {
type_: EventType::RenderCapacity,
payload: EventPayload::RenderCapacity(value),
}
}
}
pub(crate) enum EventHandler {
Once(Box<dyn FnOnce(EventPayload) + Send + 'static>),
Multiple(Box<dyn FnMut(EventPayload) + Send + 'static>),
}
#[derive(Clone, Default)]
pub(crate) struct EventLoop {
event_handlers: Arc<Mutex<HashMap<EventType, EventHandler>>>,
}
impl EventLoop {
pub fn new() -> Self {
Self::default()
}
pub fn run(&self, event_channel: Receiver<EventDispatch>) {
let self_clone = self.clone();
std::thread::spawn(move || loop {
for event in event_channel.iter() {
let mut handlers = self_clone.event_handlers.lock().unwrap();
if let Some(callback) = handlers.remove(&event.type_) {
match callback {
EventHandler::Once(f) => (f)(event.payload),
EventHandler::Multiple(mut f) => {
(f)(event.payload);
handlers.insert(event.type_, EventHandler::Multiple(f));
}
};
}
}
});
}
pub fn set_handler(&self, event: EventType, callback: EventHandler) {
self.event_handlers.lock().unwrap().insert(event, callback);
}
pub fn clear_handler(&self, event: EventType) {
self.event_handlers.lock().unwrap().remove(&event);
}
}