rsciter 0.0.11

Unofficial Rust bindings for Sciter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
use std::{
    ffi::CStr,
    num::NonZero,
    ops::{Deref, DerefMut},
    os::raw::{c_char, c_long, c_void},
    slice, str,
    sync::atomic::Ordering,
};

use crate::{api::sapi, bindings::*, Result, Value};

#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct Atom(NonZero<som_atom_t>);

impl Atom {
    pub fn new(name: impl AsRef<CStr>) -> Result<Self> {
        sapi()?
            .atom_value(name.as_ref())
            .map(|v| Self(unsafe { NonZero::new_unchecked(v) }))
    }

    pub fn name(&self) -> Result<String> {
        let mut target = String::new();
        let done =
            sapi()?.atom_name_cb(self.0.get(), Some(str_thunk), &mut target as *mut _ as _)?;
        if done {
            Ok(target)
        } else {
            Err(crate::Error::InvalidAtom(self.0.get()))
        }
    }
}

impl From<Atom> for som_atom_t {
    fn from(value: Atom) -> Self {
        value.0.get()
    }
}

unsafe extern "C" fn str_thunk(data: LPCSTR, len: UINT, target_ptr: LPVOID) {
    let data = slice::from_raw_parts(data as _, len as _);
    let data = str::from_utf8_unchecked(data);
    let target = target_ptr as *mut String;
    *target = data.to_string();
}

#[repr(transparent)]
struct RawAssetObj(som_asset_t);

#[allow(dead_code)]
impl RawAssetObj {
    pub(crate) fn new(class_data: som_asset_class_t) -> Self {
        let isa = Box::new(class_data);
        Self(som_asset_t {
            isa: Box::into_raw(isa),
        })
    }

    pub(crate) fn vtable(&self) -> &som_asset_class_t {
        unsafe { &*self.0.isa }
    }

    pub(crate) fn add_ref(&self) -> c_long {
        unsafe {
            let Some(f) = self.vtable().asset_add_ref else {
                return -1;
            };

            f(core::mem::transmute_copy(&self))
        }
    }

    pub(crate) fn release(&self) -> c_long {
        unsafe {
            let Some(f) = self.vtable().asset_release else {
                return -1;
            };

            f(core::mem::transmute_copy(&self))
        }
    }

    pub fn passport(&self) -> Option<&som_passport_t> {
        unsafe {
            self.vtable()
                .asset_get_passport
                .map(|f| &*f(core::mem::transmute_copy(&self)))
        }
    }
}

pub type Passport = crate::bindings::som_passport_t;
pub trait HasPassport {
    fn passport(&self) -> Result<&'static Passport>;
}

pub trait ItemGetter: HasPassport {
    fn get_item(&self, key: &Value) -> Result<Option<Value>>;
}
pub trait HasItemGetter {
    fn has_item_getter(&self) -> bool;
    fn do_get_item(&self, key: &Value) -> Result<Option<Value>>;
}

impl<T> HasItemGetter for &&T {
    #[inline(always)]
    fn has_item_getter(&self) -> bool {
        false
    }

    fn do_get_item(&self, _key: &Value) -> Result<Option<Value>> {
        Ok(None)
    }
}

impl<T: ItemGetter> HasItemGetter for &mut &&T {
    #[inline(always)]
    fn has_item_getter(&self) -> bool {
        true
    }

    fn do_get_item(&self, key: &Value) -> Result<Option<Value>> {
        self.get_item(key)
    }
}

pub trait ItemSetter: HasPassport {
    fn set_item(&self, key: &Value, value: &Value) -> Result<()>;
}

pub trait HasItemSetter {
    fn has_item_setter(&self) -> bool;
    fn do_set_item(&self, key: &Value, value: &Value) -> Result<()>;
}

impl<T> HasItemSetter for &&T {
    #[inline(always)]
    fn has_item_setter(&self) -> bool {
        false
    }

    fn do_set_item(&self, _key: &Value, _value: &Value) -> Result<()> {
        Ok(())
    }
}

impl<T: ItemSetter> HasItemSetter for &mut &&T {
    #[inline(always)]
    fn has_item_setter(&self) -> bool {
        true
    }

    fn do_set_item(&self, key: &Value, value: &Value) -> Result<()> {
        self.set_item(key, value)
    }
}

#[macro_export]
macro_rules! impl_item_getter {
    ($type:ty) => {
        impl_item_getter!($type, item_getter)
    };
    ($type:ty, $name:ident) => {
        unsafe extern "C" fn $name(
            thing: *mut ::rsciter::bindings::som_asset_t,
            p_key: *const ::rsciter::bindings::SCITER_VALUE,
            p_value: *mut ::rsciter::bindings::SCITER_VALUE,
        ) -> ::rsciter::bindings::SBOOL {
            use rsciter::AsValueRef;
            let key = p_key.as_value_ref();
            let asset_ref = ::rsciter::som::AssetRef::<$type>::new(thing);
            let Ok(Some(res)) = (&mut &asset_ref.data()).do_get_item(key) else {
                return 0;
            };

            *p_value = res.take();
            return 1;
        }
    };
}

#[macro_export]
macro_rules! impl_item_setter {
    ($type:ty) => {
        impl_item_setter!($type, item_setter)
    };
    ($type:ty, $name:ident) => {
        unsafe extern "C" fn $name(
            thing: *mut ::rsciter::bindings::som_asset_t,
            p_key: *const ::rsciter::bindings::SCITER_VALUE,
            p_value: *const ::rsciter::bindings::SCITER_VALUE,
        ) -> ::rsciter::bindings::SBOOL {
            use rsciter::AsValueRef;
            let key = p_key.as_value_ref();
            let value = p_value.as_value_ref();
            let asset_ref = ::rsciter::som::AssetRef::<$type>::new(thing);
            let Ok(_) = (&mut &asset_ref.data()).do_set_item(key, value) else {
                return 0;
            };

            return 1;
        }
    };
}

pub use impl_item_getter;
pub use impl_item_setter;

pub type PropertyDef = crate::bindings::som_property_def_t;
pub type PropertyAccessorDef = crate::bindings::som_property_def_t__bindgen_ty_1;
pub type PropertyAccessors = crate::bindings::som_property_def_t__bindgen_ty_1__bindgen_ty_1;
unsafe impl Sync for PropertyDef {}
unsafe impl Send for PropertyDef {}

#[macro_export]
macro_rules! impl_prop {
    ($type:ident :: $name:ident) => {
        impl_prop!($type :: $name : true true)
    };
    ($type:ident :: $name:ident get) => {
        impl_prop!($type :: $name : true false)
    };
    ($type:ident :: $name:ident set) => {
        impl_prop!($type :: $name : false true)
    };
    ($type:ident :: $name:ident get set) => {
        impl_prop!($type :: $name : true true)
    };
    ($type:ident :: $name:ident set get) => {
        impl_prop!($type :: $name : true true)
    };

    ($type:ident :: $name:ident : $has_getter:literal $has_setter:literal) => {{
        use ::rsciter::*;

        unsafe extern "C" fn getter(
            thing: *mut bindings::som_asset_t,
            p_value: *mut bindings::SCITER_VALUE,
        ) -> bindings::SBOOL {
            let asset_ref = som::AssetRef::<$type>::new(thing);
            let Ok(value) = conv::ToValue::to_value(&asset_ref.$name) else {
                return 0;
            };

            *p_value = value.take();

            1
        }

        unsafe extern "C" fn setter(
            thing: *mut bindings::som_asset_t,
            p_value: *mut bindings::SCITER_VALUE,
        ) -> bindings::SBOOL {
            let mut asset_mut = som::AssetRefMut::<$type>::new(thing);
            let value = p_value.as_value_ref();
            let Ok(_) = ::rsciter::conv::FromValue::from_value(value)
                .map(|v| asset_mut.$name = v)
            else {
                return 0;
            };

            1
        }

        som::Atom::new(::rsciter::cstr!($name)).map(|name| som::PropertyDef {
            type_: bindings::SOM_PROP_TYPE::SOM_PROP_ACCSESSOR.0 as _,
            name: name.into(),
            u: som::PropertyAccessorDef {
                accs: som::PropertyAccessors {
                    getter: if $has_getter { Some(getter) } else { None },
                    setter: if $has_setter { Some(setter) } else { None },
                },
            },
        })


    }};
}
pub use impl_prop;

/// There may be two property sources:
///
/// 1) Struct fields (handled via the [Fields] trait):
/// ```rust,ignore
/// #[rsciter::asset]
/// struct Asset {
///     name: String,
///     id: u32,
/// }
/// ```
///
/// 2) Virtual properties in `impl` blocks (handled via the [VirtualProperties] trait):
/// ```rust,ignore
/// #[rsciter::asset]
/// impl Asset {
///     #[get]
///     pub fn year(&self) -> String { ... }
///     #[set]
///     pub fn set_year(&self) -> String { ... }
/// }
/// ```
/// `property_name` and `set_property_name` patterns are handled automatically and bound to the same `property_name`.
/// Note: All public methods without `get` or `set` attributes are exported as functions.
///
/// Alternative syntax with explicit `year` name:
/// ```rust,ignore
/// #[rsciter::asset]
/// impl Asset {
///     #[get(year)]
///     fn any_get_year_name(&self) -> String { ... }
///
///     #[set(year)]
///     fn any_set_year_name(&self) -> String { ... }
/// }
/// ```
///
/// Note: The `get` and `set` attributes ignore visibility!
pub trait Fields: HasPassport {
    fn fields() -> &'static [Result<PropertyDef>];
}

/// See [Fields]. The traits are splitted only for codegen reasons.
pub trait VirtualProperties: HasPassport {
    fn properties() -> &'static [Result<PropertyDef>];
}

pub trait HasFields {
    fn enum_fields(&self) -> &'static [Result<PropertyDef>];
}

impl<T> HasFields for &&T {
    fn enum_fields(&self) -> &'static [Result<PropertyDef>] {
        &[]
    }
}

impl<T: Fields> HasFields for &mut &&T {
    fn enum_fields(&self) -> &'static [Result<PropertyDef>] {
        T::fields()
    }
}

pub trait HasVirtualProperties {
    fn enum_properties(&self) -> &'static [Result<PropertyDef>];
}

impl<T> HasVirtualProperties for &&T {
    fn enum_properties(&self) -> &'static [Result<PropertyDef>] {
        &[]
    }
}

impl<T: VirtualProperties> HasVirtualProperties for &mut &&T {
    fn enum_properties(&self) -> &'static [Result<PropertyDef>] {
        T::properties()
    }
}

pub type MethodDef = som_method_def_t;
unsafe impl Send for MethodDef {}
unsafe impl Sync for MethodDef {}
pub trait Methods: HasPassport {
    fn methods() -> &'static [Result<MethodDef>];
}

pub trait HasMethods {
    fn enum_methods(&self) -> &'static [Result<MethodDef>];
}

impl<T> HasMethods for &&T {
    fn enum_methods(&self) -> &'static [Result<MethodDef>] {
        &[]
    }
}

impl<T: Methods> HasMethods for &mut &&T {
    fn enum_methods(&self) -> &'static [Result<MethodDef>] {
        T::methods()
    }
}

trait IAsset {
    fn class() -> som_asset_class_t
    where
        Self: Sized;
}

pub struct GlobalAsset<T: HasPassport> {
    ptr: *mut AssetData<T>,
}

impl<T: HasPassport> IAsset for GlobalAsset<T> {
    fn class() -> som_asset_class_t {
        // global assets are not ref-counted.
        unsafe extern "C" fn ref_count_stub(_thing: *mut som_asset_t) -> c_long {
            return 1;
        }

        unsafe extern "C" fn asset_get_interface(
            _thing: *mut som_asset_t,
            _name: *const c_char,
            _out: *mut *mut c_void,
        ) -> c_long {
            // TODO: query interface (any usage?)
            return 0;
        }

        unsafe extern "C" fn asset_get_passport<T: HasPassport>(
            thing: *mut som_asset_t,
        ) -> *mut som_passport_t {
            let asset_ref = AssetRef::<T>::new(thing);
            let Ok(passport) = asset_ref.passport() else {
                return std::ptr::null_mut();
            };
            passport as *const _ as *mut _
        }

        som_asset_class_t {
            asset_add_ref: Some(ref_count_stub),
            asset_release: Some(ref_count_stub),
            asset_get_interface: Some(asset_get_interface),
            asset_get_passport: Some(asset_get_passport::<T>),
        }
    }
}

impl<T: HasPassport> Drop for GlobalAsset<T> {
    fn drop(&mut self) {
        let ptr: *mut som_asset_t = self.ptr.cast();
        let _res = sapi().and_then(|api| api.release_global_asset(ptr));
        debug_assert!(_res.is_ok());
    }
}

impl<T: HasPassport> GlobalAsset<T> {
    pub fn new(data: T) -> Result<Self> {
        let obj = RawAssetObj::new(Self::class());
        let res = AssetData::new(obj, data);
        let boxed = Box::new(res);
        let ptr = Box::into_raw(boxed);

        // SciterSetGlobalAsset overrides assets, so it might return false only if there is no asset_get_passport callback,
        // as we always provide one, it's safe to ignore the result
        let _res = sapi()?.set_global_asset(ptr as _)?;
        debug_assert!(_res);

        Ok(Self { ptr })
    }

    pub fn as_ref(&self) -> AssetRef<T> {
        unsafe { AssetRef::new(self.ptr.cast()) }
    }
}

#[macro_export]
macro_rules! impl_passport {
    ($self:ident, $type:ident) => {{
        static PASSPORT: std::sync::OnceLock<::rsciter::Result<::rsciter::bindings::som_passport_t>> =
            std::sync::OnceLock::new();

        let res = PASSPORT.get_or_init(|| {
            let mut passport =
                ::rsciter::bindings::som_passport_t::new(::rsciter::cstr!($type))?;
            use ::rsciter::som::{
                self, HasFields, HasItemGetter, HasItemSetter, HasMethods, HasVirtualProperties
            };

            let autoref_trick = &mut &$self;

            if autoref_trick.has_item_getter() {
                som::impl_item_getter!($type);
                passport.item_getter = Some(item_getter);
            }

            if autoref_trick.has_item_setter() {
                som::impl_item_setter!($type);
                passport.item_setter = Some(item_setter);
            }

            let mut properties = Vec::new();
            for f in autoref_trick.enum_fields() {
                match f {
                    Ok(v) => properties.push(v.clone()),
                    Err(e) => return Err(e.clone()),
                }
            }
            for p in autoref_trick.enum_properties() {
                match p {
                    Ok(v) => properties.push(v.clone()),
                    Err(e) => return Err(e.clone()),
                }
            }

            let mut methods = Vec::new();
            for m in autoref_trick.enum_methods() {
                match m {
                    Ok(v) => methods.push(v.clone()),
                    Err(e) => return Err(e.clone()),
                }
            }

            let boxed_props = properties.into_boxed_slice();
            passport.n_properties = boxed_props.len();
            if passport.n_properties > 0 {
                passport.properties = Box::into_raw(boxed_props) as *const _; // leak is acceptable here!
            }

            let boxed_methods = methods.into_boxed_slice();
            passport.n_methods = boxed_methods.len();
            if passport.n_methods > 0 {
                passport.methods = Box::into_raw(boxed_methods) as *const _; // leak is acceptable here!
            }

            Ok(passport)
        });

        match res {
            Ok(p) => Ok(p),
            Err(e) => Err(e.clone()),
        }
    }};
}
pub use impl_passport;

#[repr(C)]
struct AssetData<T> {
    obj: RawAssetObj,
    pub data: T,
}

impl<T> AssetData<T> {
    fn new(obj: RawAssetObj, data: T) -> Self {
        Self { obj, data }
    }
}

// TODO: refactor to support AsRef and Borrow
/// AssetRef does not use add_ref\release machinery,
/// Instead, it utilizes a lifetime and is guaranteed to be a valid reference to an asset.
pub struct AssetRef<'a, T> {
    this: &'a AssetData<T>,
}

impl<'a, T> AssetRef<'a, T> {
    pub unsafe fn new(thing: *const som_asset_t) -> Self {
        let this = thing as *const AssetData<T>;
        let this = unsafe { &*this };
        Self { this }
    }

    pub fn data(&self) -> &T {
        &self.this.data
    }
}

impl<T> Deref for AssetRef<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.data()
    }
}

pub struct AssetRefMut<'a, T> {
    this: &'a mut AssetData<T>,
}

impl<'a, T> AssetRefMut<'a, T> {
    pub unsafe fn new(thing: *mut som_asset_t) -> Self {
        let this = thing as *mut AssetData<T>;
        let this = unsafe { &mut *this };
        Self { this }
    }

    pub fn data(&self) -> &T {
        &self.this.data
    }

    pub fn data_mut(&mut self) -> &mut T {
        &mut self.this.data
    }
}

impl<T> Deref for AssetRefMut<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.data()
    }
}

impl<T> DerefMut for AssetRefMut<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.data_mut()
    }
}

pub struct Asset<T: HasPassport> {
    boxed: Box<AssetDataWithCounter<T>>,
}

#[repr(C)]
struct AssetDataWithCounter<T> {
    data: AssetData<T>,
    counter: std::sync::atomic::AtomicI32,
}

impl<T> AssetDataWithCounter<T> {
    unsafe fn get_mut_ref<'c>(thing: *mut som_asset_t) -> &'c mut Self {
        let this = thing as *mut AssetDataWithCounter<T>;
        &mut *this
    }
}

impl<T: HasPassport> IAsset for Asset<T> {
    fn class() -> som_asset_class_t {
        unsafe extern "C" fn asset_add_ref<TT>(thing: *mut som_asset_t) -> c_long {
            let this = AssetDataWithCounter::<TT>::get_mut_ref(thing);
            let refc = this.counter.fetch_add(1, Ordering::SeqCst) + 1;
            return refc;
        }

        unsafe extern "C" fn asset_release<TT>(thing: *mut som_asset_t) -> c_long {
            let this = AssetDataWithCounter::<TT>::get_mut_ref(thing);
            let refc = this.counter.fetch_sub(1, Ordering::SeqCst) - 1;
            if refc == 0 {
                // TODO: should not panic, reason: for each asset we got unexpected asset_release call with bad ptr
                let _ = std::panic::catch_unwind(|| {
                    let _asset_to_drop = Box::from_raw(thing as *mut AssetDataWithCounter<TT>);
                });
            }
            return refc;
        }

        unsafe extern "C" fn asset_get_interface(
            _thing: *mut som_asset_t,
            _name: *const c_char,
            _out: *mut *mut c_void,
        ) -> c_long {
            // TODO: query interface (any usage?)
            return 0;
        }

        unsafe extern "C" fn asset_get_passport<TT: HasPassport>(
            thing: *mut som_asset_t,
        ) -> *mut som_passport_t {
            let asset_ref = AssetRef::<TT>::new(thing);
            let Ok(passport) = asset_ref.passport() else {
                return std::ptr::null_mut();
            };
            passport as *const _ as *mut _
        }

        som_asset_class_t {
            asset_add_ref: Some(asset_add_ref::<T>),
            asset_release: Some(asset_release::<T>),
            asset_get_interface: Some(asset_get_interface),
            asset_get_passport: Some(asset_get_passport::<T>),
        }
    }
}

impl<T: HasPassport> Asset<T> {
    pub fn new(data: T) -> Self {
        let obj = RawAssetObj::new(Self::class());
        Self {
            boxed: Box::new(AssetDataWithCounter {
                data: AssetData::new(obj, data),
                counter: Default::default(),
            }),
        }
    }

    pub(crate) fn to_raw_ptr(self) -> *const som_asset_t {
        let ptr = Box::into_raw(self.boxed);
        ptr.cast()
    }

    pub fn as_ref(&self) -> AssetRef<T> {
        let ptr = &self.boxed.as_ref().data as *const AssetData<T>;
        unsafe { AssetRef::new(ptr.cast()) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_atom() {
        let atom = Atom::new(c"name").unwrap();
        let name = atom.name().unwrap();
        assert_eq!(name, "name");
    }
}