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