Skip to main content

fre_rs/types/
object.rs

1use super::*;
2
3
4/// An abstraction over objects of all types.
5/// 
6/// **In typical usage of this crate, this trait should not be implemented directly.**
7///
8/// This trait represents a common interface for types that are backed by an [`FREObject`].
9/// It is only intended to be implemented when defining a new object type.
10///
11/// # Safety
12///
13/// Implementing this trait requires strict guarantees about memory layout.
14/// The implementing type must be layout-compatible with [`FREObject`].
15/// In practice, this means it must be annotated with `#[repr(transparent)]`
16/// and wrap the underlying [`FREObject`] without altering its representation.
17///
18/// This requirement exists because the methods provided by this trait may
19/// perform reinterpretation of the underlying memory. Failure to uphold
20/// these guarantees will result in undefined behavior.
21/// 
22pub unsafe trait AsObject<'a>: Sized + Copy + Eq + Display + Into<FREObject> + Into<Object<'a>> {
23
24    /// The Type associated with the struct.
25    ///
26    /// This does not represent the actual runtime type of the object.
27    /// 
28    const TYPE: Type;
29
30    fn as_object (self) -> Object<'a> {
31        debug_assert_eq!(size_of_val(&self), size_of::<FREObject>());
32        unsafe {transmute_unchecked(self)}
33    }
34    fn as_ptr (self) -> FREObject {
35        unsafe {transmute(self.as_object())}
36    }
37    fn is_null(self) -> bool {self.as_ptr().is_null()}
38
39    /// Returns the runtime type of the object.
40    ///
41    /// The result depends on the underlying [`FREGetObjectType`] implementation.
42    /// Most unsupported types return [`Type::Object`].
43    /// 
44    fn get_type(self) -> Type {
45        let mut ty = FREObjectType(i32::default());
46        let r = unsafe {FREGetObjectType(self.as_ptr(), &mut ty)};
47        assert!(r.is_ok());
48        ty.into()
49    }
50
51    fn get_property (self, name: UCStr) -> Result<Object<'a>, ExternalError<'a>> {
52        let mut object = std::ptr::null_mut();
53        let mut thrown = std::ptr::null_mut();
54        let r = unsafe {FREGetObjectProperty(self.as_ptr(), name.as_ptr(), &mut object, &mut thrown)};
55        if let Ok(e) = ExternalError::try_from(r, Some(unsafe {transmute(thrown)})) {
56            Err(e)
57        }else{
58            Ok(unsafe {transmute(object)})
59        }
60    }
61    fn set_property <O: AsObject<'a>> (self, name: UCStr, value: O) -> Result<(), ExternalError<'a>> {
62        let mut thrown = std::ptr::null_mut();
63        let r = unsafe {FRESetObjectProperty(self.as_ptr(), name.as_ptr(), value.as_ptr(), &mut thrown)};
64        if let Ok(e) = ExternalError::try_from(r, Some(unsafe {transmute(thrown)})) {
65            Err(e)
66        }else{
67            Ok(())
68        }
69    }
70    fn call_method (self, name: UCStr, args: Option<&[Object]>) -> Result<Object<'a>, ExternalError<'a>> {
71        let args = args.unwrap_or_default();
72        debug_assert!(args.len() <= u32::MAX as usize);
73        let mut obj = std::ptr::null_mut();
74        let mut thrown = std::ptr::null_mut();
75        let r = unsafe {FRECallObjectMethod(self.as_ptr(), name.as_ptr(), args.len() as u32, transmute(args.as_ptr()), &mut obj, &mut thrown)};
76        if let Ok(e) = ExternalError::try_from(r, Some(unsafe {transmute(thrown)})) {
77            Err(e)
78        }else{
79            Ok(unsafe {transmute(obj)})
80        }
81    }
82    /// Return [`Err`] if this is `null` or `undefined`.
83    #[allow(non_snake_case)]
84    fn toString (self) -> Result<as3::String<'a>, ExternalError<'a>> {
85        const TO_STRING: UCStr = unsafe {UCStr::from_literal_unchecked(c"toString")};
86        self.call_method(TO_STRING, None).map(|r|{unsafe {transmute(r)}})
87    }
88}
89
90
91/// An abstraction for fallible casting between object types.
92///
93/// **In typical usage of this crate, this trait should not be implemented directly.**
94/// 
95/// Primarily used for object type casting, and should be implemented when defining a new type.
96/// 
97pub unsafe trait TryAs<'a, T>: AsObject<'a> + TryInto<T>
98where T: AsObject<'a> {
99    fn try_as (self) -> Result<T, Type> {
100        let ty = self.get_type();
101        if ty == T::TYPE {
102            debug_assert_eq!(size_of_val(&self), size_of::<T>());
103            Ok(unsafe {transmute_unchecked(self)})
104        }else{Err(ty)}
105    }
106}
107unsafe impl<'a, O> TryAs<'a, Object<'a>> for O
108where O: AsObject<'a> {
109    fn try_as (self) -> Result<Object<'a>, Type> {Ok(self.as_object())}
110}
111
112
113/// A wrapper around [`FREObject`].
114///
115/// This type assumes that the underlying handle is always valid.
116/// The runtime is responsible for ensuring the correctness and lifetime
117/// of the handle.
118///
119/// Note that the handle may still be [`as3::null`], depending on the API behavior.
120/// In such cases, [`as3::null`] is treated as a valid value at the ABI level,
121/// but may represent the absence of an object.
122/// 
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124#[repr(transparent)]
125pub struct Object <'a> (FREObject, PhantomData<&'a()>);
126impl<'a> Object<'a> {
127    pub fn new (_: &CurrentContext<'a>, class: UCStr, args: Option<&[Object<'a>]>) -> Result<Object<'a>, ExternalError<'a>> {
128        let args = args.unwrap_or_default();
129        debug_assert!(args.len() <= u32::MAX as usize);
130        let mut object = std::ptr::null_mut();
131        let mut thrown = std::ptr::null_mut();
132        let r = unsafe {FRENewObject(class.as_ptr(), args.len() as u32, transmute(args.as_ptr()), &mut object, &mut thrown)};
133        if let Ok(e) = ExternalError::try_from(r, Some(unsafe {transmute(thrown)})) {
134            Err(e)
135        }else{
136            assert!(!object.is_null());
137            Ok(unsafe {transmute(object)})
138        }
139    }
140
141    /// [`FRENativeWindow`] is only valid for the duration of this closure call.
142    /// 
143    /// Using [`as3::null`] inside the closure is meaningless and may lead to unintended FFI call ordering.
144    /// 
145    /// This is a minimal safety wrapper around the underlying FFI. Its current
146    /// placement, shape, and usage are not ideal, and it is expected to be
147    /// refactored if the ANE C API allows more precise determination of an
148    /// object's concrete type.
149    /// 
150    pub fn with_native_window <F, R> (self, f: F) -> Result<R, FfiError>
151    where F: FnOnce (FRENativeWindow) -> R + Sync
152    {
153        let mut handle = std::ptr::null_mut();
154        let result = unsafe {FREAcquireNativeWindowHandle(self.as_ptr(), &mut handle)};
155        if let Ok(e) = FfiError::try_from(result) {return Err(e)};
156        let r = f(handle);
157        let result = unsafe {FREReleaseNativeWindowHandle(self.as_ptr())};
158        assert!(result.is_ok());
159        Ok(r)
160    }
161
162    /// Using [`as3::null`] inside the closure is meaningless and may lead to unintended FFI call ordering.
163    /// 
164    /// This is a minimal safety wrapper around the underlying FFI. Its current
165    /// placement, shape, and usage are not ideal, and it is expected to be
166    /// refactored if the ANE C API allows more precise determination of an
167    /// object's concrete type.
168    /// 
169    pub fn with_native_window_3d <F, R> (self, f: F) -> Result<R, ExternalError<'a>>
170    where F: FnOnce (FRENativeWindow, &[Option<Context3D<'a>>]) -> R + Sync
171    {
172        const NAME_STAGE: UCStr = unsafe {UCStr::from_literal_unchecked(c"stage")};
173        const NAME_STAGE_3DS: UCStr = unsafe {UCStr::from_literal_unchecked(c"stage3Ds")};
174        const NAME_CONTEXT_3D: UCStr = unsafe {UCStr::from_literal_unchecked(c"context3D")};
175        let stage3ds: Vector = self.get_property(NAME_STAGE)?
176            .get_property(NAME_STAGE_3DS)?
177            .try_as()
178            .map_err(|_|ExternalError::C(FfiError::TypeMismatch))?;
179        let ctx3ds: Box<[Option<Context3D>]>  = stage3ds.iter()
180            .map(|stage3d|{
181                stage3d.get_property(NAME_CONTEXT_3D)
182                    .ok()
183            })
184            .map(|i|{
185                if let Some(ctx3d) = i {
186                    if ctx3d.is_null() {None} else {Some(unsafe {transmute(ctx3d)})}
187                } else {None}
188            })
189            .collect();
190        let mut handle = std::ptr::null_mut();
191        let result = unsafe {FREAcquireNativeWindowHandle(self.as_ptr(), &mut handle)};
192        if let Ok(e) = FfiError::try_from(result) {return Err(e.into())};
193        let r = f(handle, ctx3ds.as_ref());
194        let result = unsafe {FREReleaseNativeWindowHandle(self.as_ptr())};
195        debug_assert!(result.is_ok());
196        Ok(r)
197    }
198
199}
200impl TryFrom<Object<'_>> for i32 {
201    type Error = FfiError;
202    fn try_from(value: Object) -> Result<Self, Self::Error> {
203        let mut val = i32::default();
204        let r = unsafe {FREGetObjectAsInt32(value.0, &mut val)};
205        if let Ok(e) = r.try_into() {return Err(e);}
206        Ok(val)
207    }
208}
209impl TryFrom<Object<'_>> for u32 {
210    type Error = FfiError;
211    fn try_from(value: Object) -> Result<Self, Self::Error> {
212        let mut val = u32::default();
213        let r = unsafe {FREGetObjectAsUint32(value.0, &mut val)};
214        if let Ok(e) = r.try_into() {return Err(e);}
215        Ok(val)
216    }
217}
218impl TryFrom<Object<'_>> for f64 {
219    type Error = FfiError;
220    fn try_from(value: Object) -> Result<Self, Self::Error> {
221        let mut val = f64::default();
222        let r = unsafe {FREGetObjectAsDouble(value.0, &mut val)};
223        if let Ok(e) = r.try_into() {return Err(e);}
224        Ok(val)
225    }
226}
227impl TryFrom<Object<'_>> for bool {
228    type Error = FfiError;
229    fn try_from(value: Object) -> Result<Self, Self::Error> {
230        let mut val = u32::default();
231        let r = unsafe {FREGetObjectAsBool(value.0, &mut val)};
232        if let Ok(e) = r.try_into() {return Err(e);}
233        Ok(val != 0)
234    }
235}
236impl<'a> TryFrom<Object<'a>> for &'a str {
237    type Error = FfiError;
238    fn try_from(value: Object) -> Result<Self, Self::Error> {
239        let mut len = u32::default();
240        let mut ptr = std::ptr::null();
241        let r = unsafe {FREGetObjectAsUTF8(value.0, &mut len, &mut ptr)};
242        if let Ok(e) = r.try_into() {return Err(e);}
243        let bytes = unsafe {std::slice::from_raw_parts(ptr, len as usize)};
244        let s = unsafe {str::from_utf8_unchecked(bytes)};
245        Ok(s)
246    }
247}
248impl Display for Object<'_> {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        if self.is_null() {return write!(f, "null");}
251        match self.toString() {
252            Ok(s) => {Display::fmt(s.value(), f)},
253            Err(e) => {
254                match e {
255                    ExternalError::C(e) => Display::fmt(&e, f),
256                    ExternalError::ActionScript(e) => {
257                        if let Ok(s) = e.thrown().toString().map(|s|{s.value()}) {
258                            write!(f, "{e} {s}")
259                        } else {Display::fmt(&e, f)}
260                    },
261                }
262            },
263        }
264    }
265}
266impl Default for Object<'_> {
267    fn default() -> Self {as3::null}
268}
269unsafe impl<'a> AsObject<'a> for Object<'a> {const TYPE: Type = Type::Object;}
270impl From<()> for Object<'_> {fn from(_: ()) -> Self {as3::null}}
271impl<'a, O: AsObject<'a>> From<Option<O>> for Object<'a> {
272    fn from(value: Option<O>) -> Self {
273        if let Some(obj) = value {
274            obj.as_object()
275        } else {as3::null}
276    }
277}
278impl From<Object<'_>> for FREObject {fn from(value: Object) -> Self {value.as_ptr()}}