Skip to main content

fre_rs/
event.rs

1//! 
2//! Asynchronous event dispatching utilities for cross-thread scenarios,
3//! providing a safe interface for interacting with the Flash Runtime.
4//! 
5
6
7use super::*;
8
9
10/// A handle for dispatching events that may become invalid under the same
11/// conditions as [`Context`].
12///
13/// In asynchronous scenarios, its validity is difficult to predict.
14/// Therefore, all APIs on this type are safe to call, but their execution
15/// results cannot be guaranteed or reliably observed.
16/// 
17#[derive(Debug, Clone, Copy)]
18pub struct EventDispatcher (pub(crate) crate::context::ContextHandle);
19impl EventDispatcher {
20
21    /// Attempts to dispatch a event to the associated `ExtensionContext`.
22    ///
23    /// If the underlying context has already been disposed, this call has no effect.
24    /// 
25    pub fn dispatch (self, event: Event) {
26        let r = unsafe {FREDispatchStatusEventAsync(self.0.as_ptr(), event.code.as_ptr(), event.level.as_ptr())};
27        debug_assert!(r.is_ok());
28    }
29
30    /// Sends a debug message as a event through the associated `ExtensionContext`.
31    /// 
32    /// If the underlying context has already been disposed, this call has no effect.
33    /// 
34    pub fn debug (self, message: impl AsRef<str>) {
35        let s = message.as_ref();
36        let code = match UCStr::try_from(s) {
37            Ok(s) => s,
38            Err(e) => format!(
39                "String contains an unexpected NUL byte at index {} (length: {})\n{}",
40                e.nul_position(),
41                s.len(),
42                std::backtrace::Backtrace::capture(),
43            ).try_into().unwrap(),
44        };
45        let evt = Event { level: EventLevel::Debug, code };
46        self.dispatch(evt);
47    }
48}
49unsafe impl Send for EventDispatcher {}
50
51
52/// `flash.events.StatusEvent`
53/// 
54#[derive(Debug, Clone)]
55pub struct Event {
56    pub code: UCStr,
57    pub level: EventLevel,
58}
59impl Event {
60    pub fn new (code: UCStr, level: Option<EventLevel>) -> Self {
61        let level = level.unwrap_or_default();
62        Self { code, level }
63    }
64}
65
66
67#[derive(Debug, Clone)]
68pub enum EventLevel {
69    Status,
70    Warning,
71    Error,
72    Debug,
73    Custom(UCStr)
74}
75impl EventLevel {
76    pub fn as_ptr (&self) -> FREStr {
77        const STATUS: FREStr = c"status".as_ptr() as FREStr;
78        const WARNING: FREStr = c"warning".as_ptr() as FREStr;
79        const ERROR: FREStr = c"error".as_ptr() as FREStr;
80        const DEBUG: FREStr = c"debug".as_ptr() as FREStr;
81        match self {
82            Self::Status => STATUS,
83            Self::Warning => WARNING,
84            Self::Error => ERROR,
85            Self::Debug => DEBUG,
86            Self::Custom(s) => s.as_ptr(),
87        }
88    }
89}
90impl Default for EventLevel {
91    fn default() -> Self {Self::Status}
92}