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#[derive(Debug, Clone, Copy)]
17pub struct EventDispatcher (pub(crate) crate::context::ContextHandle);
18impl EventDispatcher {
19    pub fn dispatch (&self, event: Event) {
20        let r = unsafe {FREDispatchStatusEventAsync(self.0.as_ptr(), event.code.as_ptr(), event.level.as_ptr())};
21        debug_assert!(r.is_ok());
22    }
23    pub fn debug (&self, message: impl AsRef<str>) {
24        let s = message.as_ref();
25        let code = match UCStr::try_from(s) {
26            Ok(s) => s,
27            Err(e) => format!(
28                "String contains an unexpected NUL byte at index {} (length: {})\n{}",
29                e.nul_position(),
30                s.len(),
31                std::backtrace::Backtrace::capture(),
32            ).try_into().unwrap(),
33        };
34        let evt = Event { level: EventLevel::Debug, code };
35        self.dispatch(evt);
36    }
37}
38unsafe impl Send for EventDispatcher {}
39
40
41#[derive(Debug, Clone)]
42pub struct Event {
43    pub code: UCStr,
44    pub level: EventLevel,
45}
46impl Event {
47    pub fn new (code: UCStr, level: Option<EventLevel>) -> Self {
48        let level = level.unwrap_or_default();
49        Self { code, level }
50    }
51}
52
53
54#[derive(Debug, Clone)]
55pub enum EventLevel {
56    Status,
57    Warning,
58    Error,
59    Debug,
60    Custom(UCStr)
61}
62impl EventLevel {
63    pub fn as_ptr (&self) -> FREStr {
64        const STATUS: FREStr = c"status".as_ptr() as FREStr;
65        const WARNING: FREStr = c"warning".as_ptr() as FREStr;
66        const ERROR: FREStr = c"error".as_ptr() as FREStr;
67        const DEBUG: FREStr = c"debug".as_ptr() as FREStr;
68        match self {
69            Self::Status => STATUS,
70            Self::Warning => WARNING,
71            Self::Error => ERROR,
72            Self::Debug => DEBUG,
73            Self::Custom(s) => s.as_ptr(),
74        }
75    }
76}
77impl Default for EventLevel {
78    fn default() -> Self {Self::Status}
79}