slint_interpreter/
ffi.rs

1// Copyright © SixtyFPS GmbH <[email protected]>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4use crate::dynamic_item_tree::ErasedItemTreeBox;
5
6use super::*;
7use core::ptr::NonNull;
8use i_slint_core::model::{Model, ModelNotify, SharedVectorModel};
9use i_slint_core::slice::Slice;
10use i_slint_core::window::WindowAdapter;
11use std::ffi::c_void;
12use vtable::VRef;
13
14/// Construct a new Value in the given memory location
15#[unsafe(no_mangle)]
16pub unsafe extern "C" fn slint_interpreter_value_new() -> Box<Value> {
17    Box::new(Value::default())
18}
19
20/// Construct a new Value in the given memory location
21#[unsafe(no_mangle)]
22pub unsafe extern "C" fn slint_interpreter_value_clone(other: &Value) -> Box<Value> {
23    Box::new(other.clone())
24}
25
26/// Destruct the value in that memory location
27#[unsafe(no_mangle)]
28pub unsafe extern "C" fn slint_interpreter_value_destructor(val: Box<Value>) {
29    drop(val);
30}
31
32#[unsafe(no_mangle)]
33pub extern "C" fn slint_interpreter_value_eq(a: &Value, b: &Value) -> bool {
34    a == b
35}
36
37/// Construct a new Value in the given memory location as string
38#[unsafe(no_mangle)]
39pub unsafe extern "C" fn slint_interpreter_value_new_string(str: &SharedString) -> Box<Value> {
40    Box::new(Value::String(str.clone()))
41}
42
43/// Construct a new Value in the given memory location as double
44#[unsafe(no_mangle)]
45pub unsafe extern "C" fn slint_interpreter_value_new_double(double: f64) -> Box<Value> {
46    Box::new(Value::Number(double))
47}
48
49/// Construct a new Value in the given memory location as bool
50#[unsafe(no_mangle)]
51pub unsafe extern "C" fn slint_interpreter_value_new_bool(b: bool) -> Box<Value> {
52    Box::new(Value::Bool(b))
53}
54
55/// Construct a new Value in the given memory location as array model
56#[unsafe(no_mangle)]
57pub unsafe extern "C" fn slint_interpreter_value_new_array_model(
58    a: &SharedVector<Box<Value>>,
59) -> Box<Value> {
60    let vec = a.iter().map(|vb| vb.as_ref().clone()).collect::<SharedVector<_>>();
61    Box::new(Value::Model(ModelRc::new(SharedVectorModel::from(vec))))
62}
63
64/// Construct a new Value in the given memory location as Brush
65#[unsafe(no_mangle)]
66pub unsafe extern "C" fn slint_interpreter_value_new_brush(brush: &Brush) -> Box<Value> {
67    Box::new(Value::Brush(brush.clone()))
68}
69
70/// Construct a new Value in the given memory location as Struct
71#[unsafe(no_mangle)]
72pub unsafe extern "C" fn slint_interpreter_value_new_struct(struc: &StructOpaque) -> Box<Value> {
73    Box::new(Value::Struct(struc.as_struct().clone()))
74}
75
76/// Construct a new Value in the given memory location as image
77#[unsafe(no_mangle)]
78pub unsafe extern "C" fn slint_interpreter_value_new_image(img: &Image) -> Box<Value> {
79    Box::new(Value::Image(img.clone()))
80}
81
82/// Construct a new Value containing a model in the given memory location
83#[unsafe(no_mangle)]
84pub unsafe extern "C" fn slint_interpreter_value_new_model(
85    model: NonNull<u8>,
86    vtable: &ModelAdaptorVTable,
87) -> Box<Value> {
88    Box::new(Value::Model(ModelRc::new(ModelAdaptorWrapper(vtable::VBox::from_raw(
89        NonNull::from(vtable),
90        model,
91    )))))
92}
93
94/// If the value contains a model set from [`slint_interpreter_value_new_model]` with the same vtable pointer,
95/// return the model that was set.
96/// Returns a null ptr otherwise
97#[unsafe(no_mangle)]
98pub extern "C" fn slint_interpreter_value_to_model(
99    val: &Value,
100    vtable: &ModelAdaptorVTable,
101) -> *const u8 {
102    if let Value::Model(m) = val {
103        if let Some(m) = m.as_any().downcast_ref::<ModelAdaptorWrapper>() {
104            if core::ptr::eq(m.0.get_vtable() as *const _, vtable as *const _) {
105                return m.0.as_ptr();
106            }
107        }
108    }
109    core::ptr::null()
110}
111
112#[unsafe(no_mangle)]
113pub unsafe extern "C" fn slint_interpreter_value_type(val: &Value) -> ValueType {
114    val.value_type()
115}
116
117#[unsafe(no_mangle)]
118pub extern "C" fn slint_interpreter_value_to_string(val: &Value) -> Option<&SharedString> {
119    match val {
120        Value::String(v) => Some(v),
121        _ => None,
122    }
123}
124
125#[unsafe(no_mangle)]
126pub extern "C" fn slint_interpreter_value_to_number(val: &Value) -> Option<&f64> {
127    match val {
128        Value::Number(v) => Some(v),
129        _ => None,
130    }
131}
132
133#[unsafe(no_mangle)]
134pub extern "C" fn slint_interpreter_value_to_bool(val: &Value) -> Option<&bool> {
135    match val {
136        Value::Bool(v) => Some(v),
137        _ => None,
138    }
139}
140
141/// Extracts a `SharedVector<ValueOpaque>` out of the given value `val`, writes that into the
142/// `out` parameter and returns true; returns false if the value does not hold an extractable
143/// array.
144#[unsafe(no_mangle)]
145pub extern "C" fn slint_interpreter_value_to_array(
146    val: &Box<Value>,
147    out: *mut SharedVector<Box<Value>>,
148) -> bool {
149    match val.as_ref() {
150        Value::Model(m) => {
151            let vec = m.iter().map(|vb| Box::new(vb)).collect::<SharedVector<_>>();
152            unsafe {
153                std::ptr::write(out, vec);
154            }
155
156            true
157        }
158        _ => false,
159    }
160}
161
162#[unsafe(no_mangle)]
163pub extern "C" fn slint_interpreter_value_to_brush(val: &Value) -> Option<&Brush> {
164    match val {
165        Value::Brush(b) => Some(b),
166        _ => None,
167    }
168}
169
170#[unsafe(no_mangle)]
171pub extern "C" fn slint_interpreter_value_to_struct(val: &Value) -> *const StructOpaque {
172    match val {
173        Value::Struct(s) => s as *const Struct as *const StructOpaque,
174        _ => std::ptr::null(),
175    }
176}
177
178#[unsafe(no_mangle)]
179pub extern "C" fn slint_interpreter_value_to_image(val: &Value) -> Option<&Image> {
180    match val {
181        Value::Image(img) => Some(img),
182        _ => None,
183    }
184}
185
186#[unsafe(no_mangle)]
187pub extern "C" fn slint_interpreter_value_enum_to_string(
188    val: &Value,
189    result: &mut SharedString,
190) -> bool {
191    match val {
192        Value::EnumerationValue(_, value) => {
193            *result = SharedString::from(value);
194            true
195        }
196        _ => false,
197    }
198}
199
200#[unsafe(no_mangle)]
201pub extern "C" fn slint_interpreter_value_new_enum(
202    name: Slice<u8>,
203    value: Slice<u8>,
204) -> Box<Value> {
205    Box::new(Value::EnumerationValue(
206        std::str::from_utf8(&name).unwrap().to_string(),
207        std::str::from_utf8(&value).unwrap().to_string(),
208    ))
209}
210
211#[repr(C)]
212#[cfg(target_pointer_width = "64")]
213pub struct StructOpaque([usize; 6]);
214#[repr(C)]
215#[cfg(target_pointer_width = "32")]
216pub struct StructOpaque([u64; 4]);
217const _: [(); std::mem::size_of::<StructOpaque>()] = [(); std::mem::size_of::<Struct>()];
218const _: [(); std::mem::align_of::<StructOpaque>()] = [(); std::mem::align_of::<Struct>()];
219
220impl StructOpaque {
221    fn as_struct(&self) -> &Struct {
222        // Safety: there should be no way to construct a StructOpaque without it holding an actual Struct
223        unsafe { std::mem::transmute::<&StructOpaque, &Struct>(self) }
224    }
225    fn as_struct_mut(&mut self) -> &mut Struct {
226        // Safety: there should be no way to construct a StructOpaque without it holding an actual Struct
227        unsafe { std::mem::transmute::<&mut StructOpaque, &mut Struct>(self) }
228    }
229}
230
231/// Construct a new Struct in the given memory location
232#[unsafe(no_mangle)]
233pub unsafe extern "C" fn slint_interpreter_struct_new(val: *mut StructOpaque) {
234    std::ptr::write(val as *mut Struct, Struct::default())
235}
236
237/// Construct a new Struct in the given memory location
238#[unsafe(no_mangle)]
239pub unsafe extern "C" fn slint_interpreter_struct_clone(
240    other: &StructOpaque,
241    val: *mut StructOpaque,
242) {
243    std::ptr::write(val as *mut Struct, other.as_struct().clone())
244}
245
246/// Destruct the struct in that memory location
247#[unsafe(no_mangle)]
248pub unsafe extern "C" fn slint_interpreter_struct_destructor(val: *mut StructOpaque) {
249    drop(std::ptr::read(val as *mut Struct))
250}
251
252#[unsafe(no_mangle)]
253pub extern "C" fn slint_interpreter_struct_get_field(
254    stru: &StructOpaque,
255    name: Slice<u8>,
256) -> *mut Value {
257    if let Some(value) = stru.as_struct().get_field(std::str::from_utf8(&name).unwrap()) {
258        Box::into_raw(Box::new(value.clone()))
259    } else {
260        std::ptr::null_mut()
261    }
262}
263
264#[unsafe(no_mangle)]
265pub extern "C" fn slint_interpreter_struct_set_field<'a>(
266    stru: &'a mut StructOpaque,
267    name: Slice<u8>,
268    value: &Value,
269) {
270    stru.as_struct_mut().set_field(std::str::from_utf8(&name).unwrap().into(), value.clone())
271}
272
273type StructIterator<'a> = std::collections::hash_map::Iter<'a, SmolStr, Value>;
274#[repr(C)]
275pub struct StructIteratorOpaque<'a>([usize; 5], std::marker::PhantomData<StructIterator<'a>>);
276const _: [(); std::mem::size_of::<StructIteratorOpaque>()] =
277    [(); std::mem::size_of::<StructIterator>()];
278const _: [(); std::mem::align_of::<StructIteratorOpaque>()] =
279    [(); std::mem::align_of::<StructIterator>()];
280
281#[unsafe(no_mangle)]
282pub unsafe extern "C" fn slint_interpreter_struct_iterator_destructor(
283    val: *mut StructIteratorOpaque,
284) {
285    drop(std::ptr::read(val as *mut StructIterator))
286}
287
288/// Advance the iterator and return the next value, or a null pointer
289#[unsafe(no_mangle)]
290pub unsafe extern "C" fn slint_interpreter_struct_iterator_next<'a>(
291    iter: &'a mut StructIteratorOpaque,
292    k: &mut Slice<'a, u8>,
293) -> *mut Value {
294    if let Some((str, val)) = (*(iter as *mut StructIteratorOpaque as *mut StructIterator)).next() {
295        *k = Slice::from_slice(str.as_bytes());
296        Box::into_raw(Box::new(val.clone()))
297    } else {
298        *k = Slice::default();
299        std::ptr::null_mut()
300    }
301}
302
303#[unsafe(no_mangle)]
304pub extern "C" fn slint_interpreter_struct_make_iter(
305    stru: &StructOpaque,
306) -> StructIteratorOpaque<'_> {
307    let ret_it: StructIterator = stru.as_struct().0.iter();
308    unsafe {
309        let mut r = std::mem::MaybeUninit::<StructIteratorOpaque>::uninit();
310        std::ptr::write(r.as_mut_ptr() as *mut StructIterator, ret_it);
311        r.assume_init()
312    }
313}
314
315/// Get a property. Returns a null pointer if the property does not exist.
316#[unsafe(no_mangle)]
317pub unsafe extern "C" fn slint_interpreter_component_instance_get_property(
318    inst: &ErasedItemTreeBox,
319    name: Slice<u8>,
320) -> *mut Value {
321    generativity::make_guard!(guard);
322    let comp = inst.unerase(guard);
323    match comp
324        .description()
325        .get_property(comp.borrow(), &normalize_identifier(std::str::from_utf8(&name).unwrap()))
326    {
327        Ok(val) => Box::into_raw(Box::new(val)),
328        Err(_) => std::ptr::null_mut(),
329    }
330}
331
332#[unsafe(no_mangle)]
333pub extern "C" fn slint_interpreter_component_instance_set_property(
334    inst: &ErasedItemTreeBox,
335    name: Slice<u8>,
336    val: &Value,
337) -> bool {
338    generativity::make_guard!(guard);
339    let comp = inst.unerase(guard);
340    comp.description()
341        .set_property(
342            comp.borrow(),
343            &normalize_identifier(std::str::from_utf8(&name).unwrap()),
344            val.clone(),
345        )
346        .is_ok()
347}
348
349/// Invoke a callback or function. Returns raw boxed value on success and null ptr on failure.
350#[unsafe(no_mangle)]
351pub unsafe extern "C" fn slint_interpreter_component_instance_invoke(
352    inst: &ErasedItemTreeBox,
353    name: Slice<u8>,
354    args: Slice<Box<Value>>,
355) -> *mut Value {
356    let args = args.iter().map(|vb| vb.as_ref().clone()).collect::<Vec<_>>();
357    generativity::make_guard!(guard);
358    let comp = inst.unerase(guard);
359    match comp.description().invoke(
360        comp.borrow(),
361        &normalize_identifier(std::str::from_utf8(&name).unwrap()),
362        args.as_slice(),
363    ) {
364        Ok(val) => Box::into_raw(Box::new(val)),
365        Err(_) => std::ptr::null_mut(),
366    }
367}
368
369/// Wrap the user_data provided by the native code and call the drop function on Drop.
370///
371/// Safety: user_data must be a pointer that can be destroyed by the drop_user_data function.
372/// callback must be a valid callback that initialize the `ret`
373pub struct CallbackUserData {
374    user_data: *mut c_void,
375    drop_user_data: Option<extern "C" fn(*mut c_void)>,
376    callback: extern "C" fn(user_data: *mut c_void, arg: Slice<Box<Value>>) -> Box<Value>,
377}
378
379impl Drop for CallbackUserData {
380    fn drop(&mut self) {
381        if let Some(x) = self.drop_user_data {
382            x(self.user_data)
383        }
384    }
385}
386
387impl CallbackUserData {
388    pub unsafe fn new(
389        user_data: *mut c_void,
390        drop_user_data: Option<extern "C" fn(*mut c_void)>,
391        callback: extern "C" fn(user_data: *mut c_void, arg: Slice<Box<Value>>) -> Box<Value>,
392    ) -> Self {
393        Self { user_data, drop_user_data, callback }
394    }
395
396    pub fn call(&self, args: &[Value]) -> Value {
397        let args = args.iter().map(|v| v.clone().into()).collect::<Vec<_>>();
398        (self.callback)(self.user_data, Slice::from_slice(args.as_ref())).as_ref().clone()
399    }
400}
401
402/// Set a handler for the callback.
403/// The `callback` function must initialize the `ret` (the `ret` passed to the callback is initialized and is assumed initialized after the function)
404#[unsafe(no_mangle)]
405pub unsafe extern "C" fn slint_interpreter_component_instance_set_callback(
406    inst: &ErasedItemTreeBox,
407    name: Slice<u8>,
408    callback: extern "C" fn(user_data: *mut c_void, arg: Slice<Box<Value>>) -> Box<Value>,
409    user_data: *mut c_void,
410    drop_user_data: Option<extern "C" fn(*mut c_void)>,
411) -> bool {
412    let ud = CallbackUserData::new(user_data, drop_user_data, callback);
413
414    generativity::make_guard!(guard);
415    let comp = inst.unerase(guard);
416    comp.description()
417        .set_callback_handler(
418            comp.borrow(),
419            &normalize_identifier(std::str::from_utf8(&name).unwrap()),
420            Box::new(move |args| ud.call(args)),
421        )
422        .is_ok()
423}
424
425/// Get a global property. Returns a raw boxed value on success; nullptr otherwise.
426#[unsafe(no_mangle)]
427pub unsafe extern "C" fn slint_interpreter_component_instance_get_global_property(
428    inst: &ErasedItemTreeBox,
429    global: Slice<u8>,
430    property_name: Slice<u8>,
431) -> *mut Value {
432    generativity::make_guard!(guard);
433    let comp = inst.unerase(guard);
434    match comp
435        .description()
436        .get_global(comp.borrow(), &normalize_identifier(std::str::from_utf8(&global).unwrap()))
437        .and_then(|g| {
438            g.as_ref()
439                .get_property(&normalize_identifier(std::str::from_utf8(&property_name).unwrap()))
440        }) {
441        Ok(val) => Box::into_raw(Box::new(val)),
442        Err(_) => std::ptr::null_mut(),
443    }
444}
445
446#[unsafe(no_mangle)]
447pub extern "C" fn slint_interpreter_component_instance_set_global_property(
448    inst: &ErasedItemTreeBox,
449    global: Slice<u8>,
450    property_name: Slice<u8>,
451    val: &Value,
452) -> bool {
453    generativity::make_guard!(guard);
454    let comp = inst.unerase(guard);
455    comp.description()
456        .get_global(comp.borrow(), &normalize_identifier(std::str::from_utf8(&global).unwrap()))
457        .and_then(|g| {
458            g.as_ref()
459                .set_property(
460                    &normalize_identifier(std::str::from_utf8(&property_name).unwrap()),
461                    val.clone(),
462                )
463                .map_err(|_| ())
464        })
465        .is_ok()
466}
467
468/// The `callback` function must initialize the `ret` (the `ret` passed to the callback is initialized and is assumed initialized after the function)
469#[unsafe(no_mangle)]
470pub unsafe extern "C" fn slint_interpreter_component_instance_set_global_callback(
471    inst: &ErasedItemTreeBox,
472    global: Slice<u8>,
473    name: Slice<u8>,
474    callback: extern "C" fn(user_data: *mut c_void, arg: Slice<Box<Value>>) -> Box<Value>,
475    user_data: *mut c_void,
476    drop_user_data: Option<extern "C" fn(*mut c_void)>,
477) -> bool {
478    let ud = CallbackUserData::new(user_data, drop_user_data, callback);
479
480    generativity::make_guard!(guard);
481    let comp = inst.unerase(guard);
482    comp.description()
483        .get_global(comp.borrow(), &normalize_identifier(std::str::from_utf8(&global).unwrap()))
484        .and_then(|g| {
485            g.as_ref().set_callback_handler(
486                &normalize_identifier(std::str::from_utf8(&name).unwrap()),
487                Box::new(move |args| ud.call(args)),
488            )
489        })
490        .is_ok()
491}
492
493/// Invoke a global callback or function. Returns raw boxed value on success; nullptr otherwise.
494#[unsafe(no_mangle)]
495pub unsafe extern "C" fn slint_interpreter_component_instance_invoke_global(
496    inst: &ErasedItemTreeBox,
497    global: Slice<u8>,
498    callable_name: Slice<u8>,
499    args: Slice<Box<Value>>,
500) -> *mut Value {
501    let args = args.iter().map(|vb| vb.as_ref().clone()).collect::<Vec<_>>();
502    generativity::make_guard!(guard);
503    let comp = inst.unerase(guard);
504    let callable_name = std::str::from_utf8(&callable_name).unwrap();
505    match comp
506        .description()
507        .get_global(comp.borrow(), &normalize_identifier(std::str::from_utf8(&global).unwrap()))
508        .and_then(|g| {
509            if matches!(
510                comp.description()
511                    .original
512                    .root_element
513                    .borrow()
514                    .lookup_property(callable_name)
515                    .property_type,
516                i_slint_compiler::langtype::Type::Function { .. }
517            ) {
518                g.as_ref().eval_function(
519                    &normalize_identifier(callable_name),
520                    args.as_slice().iter().cloned().collect(),
521                )
522            } else {
523                g.as_ref().invoke_callback(&normalize_identifier(callable_name), args.as_slice())
524            }
525        }) {
526        Ok(val) => Box::into_raw(Box::new(val)),
527        Err(_) => std::ptr::null_mut(),
528    }
529}
530
531/// Show or hide
532#[unsafe(no_mangle)]
533pub extern "C" fn slint_interpreter_component_instance_show(
534    inst: &ErasedItemTreeBox,
535    is_visible: bool,
536) {
537    generativity::make_guard!(guard);
538    let comp = inst.unerase(guard);
539    match is_visible {
540        true => comp.borrow_instance().window_adapter().window().show().unwrap(),
541        false => comp.borrow_instance().window_adapter().window().hide().unwrap(),
542    }
543}
544
545/// Return a window for the component
546///
547/// The out pointer must be uninitialized and must be destroyed with
548/// slint_windowrc_drop after usage
549#[unsafe(no_mangle)]
550pub unsafe extern "C" fn slint_interpreter_component_instance_window(
551    inst: &ErasedItemTreeBox,
552    out: *mut *const i_slint_core::window::ffi::WindowAdapterRcOpaque,
553) {
554    assert_eq!(
555        core::mem::size_of::<Rc<dyn WindowAdapter>>(),
556        core::mem::size_of::<i_slint_core::window::ffi::WindowAdapterRcOpaque>()
557    );
558    core::ptr::write(
559        out as *mut *const Rc<dyn WindowAdapter>,
560        inst.window_adapter_ref().unwrap() as *const _,
561    )
562}
563
564/// Instantiate an instance from a definition.
565///
566/// The `out` must be uninitialized and is going to be initialized after the call
567/// and need to be destroyed with slint_interpreter_component_instance_destructor
568#[unsafe(no_mangle)]
569pub unsafe extern "C" fn slint_interpreter_component_instance_create(
570    def: &ComponentDefinitionOpaque,
571    out: *mut ComponentInstance,
572) {
573    std::ptr::write(out, def.as_component_definition().create().unwrap())
574}
575
576#[unsafe(no_mangle)]
577pub unsafe extern "C" fn slint_interpreter_component_instance_component_definition(
578    inst: &ErasedItemTreeBox,
579    component_definition_ptr: *mut ComponentDefinitionOpaque,
580) {
581    generativity::make_guard!(guard);
582    let definition = ComponentDefinition { inner: inst.unerase(guard).description().into() };
583    std::ptr::write(component_definition_ptr as *mut ComponentDefinition, definition);
584}
585
586#[vtable::vtable]
587#[repr(C)]
588pub struct ModelAdaptorVTable {
589    pub row_count: extern "C" fn(VRef<ModelAdaptorVTable>) -> usize,
590    pub row_data: unsafe extern "C" fn(VRef<ModelAdaptorVTable>, row: usize) -> *mut Value,
591    pub set_row_data: extern "C" fn(VRef<ModelAdaptorVTable>, row: usize, value: Box<Value>),
592    pub get_notify: extern "C" fn(VRef<'_, ModelAdaptorVTable>) -> &ModelNotifyOpaque,
593    pub drop: extern "C" fn(VRefMut<ModelAdaptorVTable>),
594}
595
596struct ModelAdaptorWrapper(vtable::VBox<ModelAdaptorVTable>);
597impl Model for ModelAdaptorWrapper {
598    type Data = Value;
599
600    fn row_count(&self) -> usize {
601        self.0.row_count()
602    }
603
604    fn row_data(&self, row: usize) -> Option<Value> {
605        let val_ptr = unsafe { self.0.row_data(row) };
606        if val_ptr.is_null() {
607            None
608        } else {
609            Some(*unsafe { Box::from_raw(val_ptr) })
610        }
611    }
612
613    fn model_tracker(&self) -> &dyn i_slint_core::model::ModelTracker {
614        self.0.get_notify().as_model_notify()
615    }
616
617    fn set_row_data(&self, row: usize, data: Value) {
618        let val = Box::new(data);
619        self.0.set_row_data(row, val);
620    }
621
622    fn as_any(&self) -> &dyn core::any::Any {
623        self
624    }
625}
626
627#[repr(C)]
628#[cfg(target_pointer_width = "64")]
629pub struct ModelNotifyOpaque([usize; 8]);
630#[repr(C)]
631#[cfg(target_pointer_width = "32")]
632pub struct ModelNotifyOpaque([usize; 12]);
633/// Asserts that ModelNotifyOpaque is at least as large as ModelNotify, otherwise this would overflow
634const _: usize = std::mem::size_of::<ModelNotifyOpaque>() - std::mem::size_of::<ModelNotify>();
635const _: usize = std::mem::align_of::<ModelNotifyOpaque>() - std::mem::align_of::<ModelNotify>();
636
637impl ModelNotifyOpaque {
638    fn as_model_notify(&self) -> &ModelNotify {
639        // Safety: there should be no way to construct a ModelNotifyOpaque without it holding an actual ModelNotify
640        unsafe { std::mem::transmute::<&ModelNotifyOpaque, &ModelNotify>(self) }
641    }
642}
643
644/// Construct a new ModelNotifyNotify in the given memory region
645#[unsafe(no_mangle)]
646pub unsafe extern "C" fn slint_interpreter_model_notify_new(val: *mut ModelNotifyOpaque) {
647    std::ptr::write(val as *mut ModelNotify, ModelNotify::default());
648}
649
650/// Destruct the value in that memory location
651#[unsafe(no_mangle)]
652pub unsafe extern "C" fn slint_interpreter_model_notify_destructor(val: *mut ModelNotifyOpaque) {
653    drop(std::ptr::read(val as *mut ModelNotify))
654}
655
656#[unsafe(no_mangle)]
657pub unsafe extern "C" fn slint_interpreter_model_notify_row_changed(
658    notify: &ModelNotifyOpaque,
659    row: usize,
660) {
661    notify.as_model_notify().row_changed(row);
662}
663
664#[unsafe(no_mangle)]
665pub unsafe extern "C" fn slint_interpreter_model_notify_row_added(
666    notify: &ModelNotifyOpaque,
667    row: usize,
668    count: usize,
669) {
670    notify.as_model_notify().row_added(row, count);
671}
672
673#[unsafe(no_mangle)]
674pub unsafe extern "C" fn slint_interpreter_model_notify_reset(notify: &ModelNotifyOpaque) {
675    notify.as_model_notify().reset();
676}
677
678#[unsafe(no_mangle)]
679pub unsafe extern "C" fn slint_interpreter_model_notify_row_removed(
680    notify: &ModelNotifyOpaque,
681    row: usize,
682    count: usize,
683) {
684    notify.as_model_notify().row_removed(row, count);
685}
686
687// FIXME: Figure out how to re-export the one from compilerlib
688/// DiagnosticLevel describes the severity of a diagnostic.
689#[derive(Clone)]
690#[repr(u8)]
691pub enum DiagnosticLevel {
692    /// The diagnostic belongs to an error.
693    Error,
694    /// The diagnostic belongs to a warning.
695    Warning,
696}
697
698/// Diagnostic describes the aspects of either a warning or an error, along
699/// with its location and a description. Diagnostics are typically returned by
700/// slint::interpreter::ComponentCompiler::diagnostics() in a vector.
701#[derive(Clone)]
702#[repr(C)]
703pub struct Diagnostic {
704    /// The message describing the warning or error.
705    message: SharedString,
706    /// The path to the source file where the warning or error is located.
707    source_file: SharedString,
708    /// The line within the source file. Line numbers start at 1.
709    line: usize,
710    /// The column within the source file. Column numbers start at 1.
711    column: usize,
712    /// The level of the diagnostic, such as a warning or an error.
713    level: DiagnosticLevel,
714}
715
716#[repr(transparent)]
717pub struct ComponentCompilerOpaque(#[allow(deprecated)] NonNull<ComponentCompiler>);
718
719#[allow(deprecated)]
720impl ComponentCompilerOpaque {
721    fn as_component_compiler(&self) -> &ComponentCompiler {
722        // Safety: there should be no way to construct a ComponentCompilerOpaque without it holding an actual ComponentCompiler
723        unsafe { self.0.as_ref() }
724    }
725    fn as_component_compiler_mut(&mut self) -> &mut ComponentCompiler {
726        // Safety: there should be no way to construct a ComponentCompilerOpaque without it holding an actual ComponentCompiler
727        unsafe { self.0.as_mut() }
728    }
729}
730
731#[unsafe(no_mangle)]
732#[allow(deprecated)]
733pub unsafe extern "C" fn slint_interpreter_component_compiler_new(
734    compiler: *mut ComponentCompilerOpaque,
735) {
736    *compiler = ComponentCompilerOpaque(NonNull::new_unchecked(Box::into_raw(Box::new(
737        ComponentCompiler::default(),
738    ))));
739}
740
741#[unsafe(no_mangle)]
742pub unsafe extern "C" fn slint_interpreter_component_compiler_destructor(
743    compiler: *mut ComponentCompilerOpaque,
744) {
745    drop(Box::from_raw((*compiler).0.as_ptr()))
746}
747
748#[unsafe(no_mangle)]
749pub unsafe extern "C" fn slint_interpreter_component_compiler_set_include_paths(
750    compiler: &mut ComponentCompilerOpaque,
751    paths: &SharedVector<SharedString>,
752) {
753    compiler
754        .as_component_compiler_mut()
755        .set_include_paths(paths.iter().map(|path| path.as_str().into()).collect())
756}
757
758#[unsafe(no_mangle)]
759pub unsafe extern "C" fn slint_interpreter_component_compiler_set_style(
760    compiler: &mut ComponentCompilerOpaque,
761    style: Slice<u8>,
762) {
763    compiler.as_component_compiler_mut().set_style(std::str::from_utf8(&style).unwrap().to_string())
764}
765
766#[unsafe(no_mangle)]
767pub unsafe extern "C" fn slint_interpreter_component_compiler_set_translation_domain(
768    compiler: &mut ComponentCompilerOpaque,
769    translation_domain: Slice<u8>,
770) {
771    compiler
772        .as_component_compiler_mut()
773        .set_translation_domain(std::str::from_utf8(&translation_domain).unwrap().to_string())
774}
775
776#[unsafe(no_mangle)]
777pub unsafe extern "C" fn slint_interpreter_component_compiler_get_style(
778    compiler: &ComponentCompilerOpaque,
779    style_out: &mut SharedString,
780) {
781    *style_out =
782        compiler.as_component_compiler().style().map_or(SharedString::default(), |s| s.into());
783}
784
785#[unsafe(no_mangle)]
786pub unsafe extern "C" fn slint_interpreter_component_compiler_get_include_paths(
787    compiler: &ComponentCompilerOpaque,
788    paths: &mut SharedVector<SharedString>,
789) {
790    paths.extend(
791        compiler
792            .as_component_compiler()
793            .include_paths()
794            .iter()
795            .map(|path| path.to_str().map_or_else(Default::default, |str| str.into())),
796    );
797}
798
799#[unsafe(no_mangle)]
800pub unsafe extern "C" fn slint_interpreter_component_compiler_get_diagnostics(
801    compiler: &ComponentCompilerOpaque,
802    out_diags: &mut SharedVector<Diagnostic>,
803) {
804    #[allow(deprecated)]
805    out_diags.extend(compiler.as_component_compiler().diagnostics.iter().map(|diagnostic| {
806        let (line, column) = diagnostic.line_column();
807        Diagnostic {
808            message: diagnostic.message().into(),
809            source_file: diagnostic
810                .source_file()
811                .and_then(|path| path.to_str())
812                .map_or_else(Default::default, |str| str.into()),
813            line,
814            column,
815            level: match diagnostic.level() {
816                i_slint_compiler::diagnostics::DiagnosticLevel::Error => DiagnosticLevel::Error,
817                i_slint_compiler::diagnostics::DiagnosticLevel::Warning => DiagnosticLevel::Warning,
818                _ => DiagnosticLevel::Warning,
819            },
820        }
821    }));
822}
823
824#[unsafe(no_mangle)]
825pub unsafe extern "C" fn slint_interpreter_component_compiler_build_from_source(
826    compiler: &mut ComponentCompilerOpaque,
827    source_code: Slice<u8>,
828    path: Slice<u8>,
829    component_definition_ptr: *mut ComponentDefinitionOpaque,
830) -> bool {
831    match spin_on::spin_on(compiler.as_component_compiler_mut().build_from_source(
832        std::str::from_utf8(&source_code).unwrap().to_string(),
833        std::str::from_utf8(&path).unwrap().to_string().into(),
834    )) {
835        Some(definition) => {
836            std::ptr::write(component_definition_ptr as *mut ComponentDefinition, definition);
837            true
838        }
839        None => false,
840    }
841}
842
843#[unsafe(no_mangle)]
844pub unsafe extern "C" fn slint_interpreter_component_compiler_build_from_path(
845    compiler: &mut ComponentCompilerOpaque,
846    path: Slice<u8>,
847    component_definition_ptr: *mut ComponentDefinitionOpaque,
848) -> bool {
849    use std::str::FromStr;
850    match spin_on::spin_on(
851        compiler
852            .as_component_compiler_mut()
853            .build_from_path(PathBuf::from_str(std::str::from_utf8(&path).unwrap()).unwrap()),
854    ) {
855        Some(definition) => {
856            std::ptr::write(component_definition_ptr as *mut ComponentDefinition, definition);
857            true
858        }
859        None => false,
860    }
861}
862
863/// PropertyDescriptor is a simple structure that's used to describe a property declared in .slint
864/// code. It is returned from in a vector from
865/// slint::interpreter::ComponentDefinition::properties().
866#[derive(Clone)]
867#[repr(C)]
868pub struct PropertyDescriptor {
869    /// The name of the declared property.
870    property_name: SharedString,
871    /// The type of the property.
872    property_type: ValueType,
873}
874
875#[repr(C)]
876// Note: This needs to stay the size of 1 pointer to allow for the null pointer definition
877// in the C++ wrapper to allow for the null state.
878pub struct ComponentDefinitionOpaque([usize; 1]);
879/// Asserts that ComponentCompilerOpaque is as large as ComponentCompiler and has the same alignment, to make transmute safe.
880const _: [(); std::mem::size_of::<ComponentDefinitionOpaque>()] =
881    [(); std::mem::size_of::<ComponentDefinition>()];
882const _: [(); std::mem::align_of::<ComponentDefinitionOpaque>()] =
883    [(); std::mem::align_of::<ComponentDefinition>()];
884
885impl ComponentDefinitionOpaque {
886    fn as_component_definition(&self) -> &ComponentDefinition {
887        // Safety: there should be no way to construct a ComponentDefinitionOpaque without it holding an actual ComponentDefinition
888        unsafe { std::mem::transmute::<&ComponentDefinitionOpaque, &ComponentDefinition>(self) }
889    }
890}
891
892/// Construct a new Value in the given memory location
893#[unsafe(no_mangle)]
894pub unsafe extern "C" fn slint_interpreter_component_definition_clone(
895    other: &ComponentDefinitionOpaque,
896    def: *mut ComponentDefinitionOpaque,
897) {
898    std::ptr::write(def as *mut ComponentDefinition, other.as_component_definition().clone())
899}
900
901/// Destruct the component definition in that memory location
902#[unsafe(no_mangle)]
903pub unsafe extern "C" fn slint_interpreter_component_definition_destructor(
904    val: *mut ComponentDefinitionOpaque,
905) {
906    drop(std::ptr::read(val as *mut ComponentDefinition))
907}
908
909/// Returns the list of properties of the component the component definition describes
910#[unsafe(no_mangle)]
911pub unsafe extern "C" fn slint_interpreter_component_definition_properties(
912    def: &ComponentDefinitionOpaque,
913    props: &mut SharedVector<PropertyDescriptor>,
914) {
915    props.extend((&*def).as_component_definition().properties().map(
916        |(property_name, property_type)| PropertyDescriptor {
917            property_name: property_name.into(),
918            property_type,
919        },
920    ))
921}
922
923/// Returns the list of callback names of the component the component definition describes
924#[unsafe(no_mangle)]
925pub unsafe extern "C" fn slint_interpreter_component_definition_callbacks(
926    def: &ComponentDefinitionOpaque,
927    callbacks: &mut SharedVector<SharedString>,
928) {
929    callbacks.extend((&*def).as_component_definition().callbacks().map(|name| name.into()))
930}
931
932/// Returns the list of function names of the component the component definition describes
933#[unsafe(no_mangle)]
934pub unsafe extern "C" fn slint_interpreter_component_definition_functions(
935    def: &ComponentDefinitionOpaque,
936    functions: &mut SharedVector<SharedString>,
937) {
938    functions.extend((&*def).as_component_definition().functions().map(|name| name.into()))
939}
940
941/// Return the name of the component definition
942#[unsafe(no_mangle)]
943pub unsafe extern "C" fn slint_interpreter_component_definition_name(
944    def: &ComponentDefinitionOpaque,
945    name: &mut SharedString,
946) {
947    *name = (&*def).as_component_definition().name().into()
948}
949
950/// Returns a vector of strings with the names of all exported global singletons.
951#[unsafe(no_mangle)]
952pub unsafe extern "C" fn slint_interpreter_component_definition_globals(
953    def: &ComponentDefinitionOpaque,
954    names: &mut SharedVector<SharedString>,
955) {
956    names.extend((&*def).as_component_definition().globals().map(|name| name.into()))
957}
958
959/// Returns a vector of the property descriptors of the properties of the specified publicly exported global
960/// singleton. Returns true if a global exists under the specified name; false otherwise.
961#[unsafe(no_mangle)]
962pub unsafe extern "C" fn slint_interpreter_component_definition_global_properties(
963    def: &ComponentDefinitionOpaque,
964    global_name: Slice<u8>,
965    properties: &mut SharedVector<PropertyDescriptor>,
966) -> bool {
967    if let Some(property_it) = (&*def)
968        .as_component_definition()
969        .global_properties(std::str::from_utf8(&global_name).unwrap())
970    {
971        properties.extend(property_it.map(|(property_name, property_type)| PropertyDescriptor {
972            property_name: property_name.into(),
973            property_type,
974        }));
975        true
976    } else {
977        false
978    }
979}
980
981/// Returns a vector of the names of the callbacks of the specified publicly exported global
982/// singleton. Returns true if a global exists under the specified name; false otherwise.
983#[unsafe(no_mangle)]
984pub unsafe extern "C" fn slint_interpreter_component_definition_global_callbacks(
985    def: &ComponentDefinitionOpaque,
986    global_name: Slice<u8>,
987    names: &mut SharedVector<SharedString>,
988) -> bool {
989    if let Some(name_it) = (&*def)
990        .as_component_definition()
991        .global_callbacks(std::str::from_utf8(&global_name).unwrap())
992    {
993        names.extend(name_it.map(|name| name.into()));
994        true
995    } else {
996        false
997    }
998}
999
1000/// Returns a vector of the names of the functions of the specified publicly exported global
1001/// singleton. Returns true if a global exists under the specified name; false otherwise.
1002#[unsafe(no_mangle)]
1003pub unsafe extern "C" fn slint_interpreter_component_definition_global_functions(
1004    def: &ComponentDefinitionOpaque,
1005    global_name: Slice<u8>,
1006    names: &mut SharedVector<SharedString>,
1007) -> bool {
1008    if let Some(name_it) = (&*def)
1009        .as_component_definition()
1010        .global_functions(std::str::from_utf8(&global_name).unwrap())
1011    {
1012        names.extend(name_it.map(|name| name.into()));
1013        true
1014    } else {
1015        false
1016    }
1017}