Skip to main content

ass_editor/events/
channel.rs

1//! Core [`EventChannel`] state and lifecycle.
2//!
3//! Holds the channel struct, the internal handler record, construction helpers,
4//! statistics access, and handler clearing. Registration and dispatch live in
5//! the sibling `registry` and `dispatch` modules.
6
7use 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/// Event channel for distributing document events to handlers
32#[derive(Debug)]
33pub struct EventChannel {
34    /// Configuration for this channel
35    pub(super) config: EventChannelConfig,
36
37    /// Registered event handlers
38    #[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    /// Event statistics
45    pub(super) stats: EventStats,
46
47    /// Async event sender (if async feature is enabled)
48    #[cfg(feature = "async")]
49    pub(super) async_sender: Option<mpsc::UnboundedSender<DocumentEvent>>,
50
51    /// Next handler ID for unique identification
52    pub(super) next_handler_id: usize,
53}
54
55/// Information about a registered handler
56pub(super) struct HandlerInfo {
57    /// Unique handler ID
58    pub(super) id: usize,
59    /// Handler implementation
60    pub(super) handler: Box<dyn EventHandler>,
61    /// Event filter for this handler
62    pub(super) filter: EventFilter,
63    /// Handler priority
64    pub(super) priority: i32,
65    /// Number of events processed by this handler
66    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    /// Create a new event channel with default configuration
83    pub fn new() -> Self {
84        Self::with_config(EventChannelConfig::default())
85    }
86
87    /// Create a new event channel with custom configuration
88    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    /// Get event statistics
109    pub fn stats(&self) -> &EventStats {
110        &self.stats
111    }
112
113    /// Clear all event handlers
114    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}