Skip to main content

slint_interpreter/
ffi.rs

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