ass_editor/events/
channel.rs1use super::{EventChannelConfig, EventFilter, EventHandler, EventStats};
8use crate::core::Result;
9
10#[cfg(feature = "async")]
11use super::DocumentEvent;
12
13#[cfg(not(feature = "std"))]
14use alloc::{boxed::Box, vec::Vec};
15
16#[cfg(feature = "multi-thread")]
17use std::sync::{Arc, RwLock};
18
19#[cfg(not(feature = "multi-thread"))]
20use core::cell::RefCell;
21
22#[cfg(all(not(feature = "multi-thread"), not(feature = "std")))]
23use alloc::rc::Rc;
24
25#[cfg(all(not(feature = "multi-thread"), feature = "std"))]
26use std::rc::Rc;
27
28#[cfg(feature = "async")]
29use futures::channel::mpsc;
30
31#[derive(Debug)]
33pub struct EventChannel {
34 pub(super) config: EventChannelConfig,
36
37 #[cfg(feature = "multi-thread")]
39 pub(super) handlers: Arc<RwLock<Vec<HandlerInfo>>>,
40
41 #[cfg(not(feature = "multi-thread"))]
42 pub(super) handlers: Rc<RefCell<Vec<HandlerInfo>>>,
43
44 pub(super) stats: EventStats,
46
47 #[cfg(feature = "async")]
49 pub(super) async_sender: Option<mpsc::UnboundedSender<DocumentEvent>>,
50
51 pub(super) next_handler_id: usize,
53}
54
55pub(super) struct HandlerInfo {
57 pub(super) id: usize,
59 pub(super) handler: Box<dyn EventHandler>,
61 pub(super) filter: EventFilter,
63 pub(super) priority: i32,
65 pub(super) events_processed: usize,
67}
68
69impl core::fmt::Debug for HandlerInfo {
70 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
71 f.debug_struct("HandlerInfo")
72 .field("id", &self.id)
73 .field("filter", &self.filter)
74 .field("priority", &self.priority)
75 .field("events_processed", &self.events_processed)
76 .field("handler", &"<EventHandler>")
77 .finish()
78 }
79}
80
81impl EventChannel {
82 pub fn new() -> Self {
84 Self::with_config(EventChannelConfig::default())
85 }
86
87 pub fn with_config(config: EventChannelConfig) -> Self {
89 Self {
90 config,
91 #[cfg(feature = "multi-thread")]
92 handlers: Arc::new(RwLock::new(Vec::new())),
93 #[cfg(not(feature = "multi-thread"))]
94 handlers: Rc::new(RefCell::new(Vec::new())),
95 stats: EventStats {
96 events_dispatched: 0,
97 handlers_count: 0,
98 events_filtered: 0,
99 async_events_queued: 0,
100 avg_processing_time_us: 0,
101 },
102 #[cfg(feature = "async")]
103 async_sender: None,
104 next_handler_id: 0,
105 }
106 }
107
108 pub fn stats(&self) -> &EventStats {
110 &self.stats
111 }
112
113 pub fn clear_handlers(&mut self) -> Result<()> {
115 #[cfg(feature = "multi-thread")]
116 {
117 let mut handlers =
118 self.handlers
119 .write()
120 .map_err(|_| crate::core::EditorError::ThreadSafetyError {
121 message: "Failed to acquire write lock for handlers".to_string(),
122 })?;
123 handlers.clear();
124 }
125
126 #[cfg(not(feature = "multi-thread"))]
127 {
128 let mut handlers = self.handlers.borrow_mut();
129 handlers.clear();
130 }
131
132 self.stats.handlers_count = 0;
133 Ok(())
134 }
135}
136
137impl Default for EventChannel {
138 fn default() -> Self {
139 Self::new()
140 }
141}