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, 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>),
613    pub remove_row: extern "C" fn(VRef<ModelAdaptorVTable>, row: isize),
614    pub insert_row: extern "C" fn(VRef<ModelAdaptorVTable>, row: isize, value: Box<Value>),
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) {
642        let val = Box::new(data);
643        self.0.push_row(val);
644    }
645
646    fn remove_row(&self, row: isize) {
647        self.0.remove_row(row);
648    }
649
650    fn insert_row(&self, row: isize, data: Value) {
651        let val = Box::new(data);
652        self.0.insert_row(row, val);
653    }
654
655    fn as_any(&self) -> &dyn core::any::Any {
656        self
657    }
658}
659
660#[repr(C)]
661#[cfg(target_pointer_width = "64")]
662pub struct ModelNotifyOpaque([usize; 8]);
663#[repr(C)]
664#[cfg(target_pointer_width = "32")]
665pub struct ModelNotifyOpaque([usize; 12]);
666/// Asserts that ModelNotifyOpaque is at least as large as ModelNotify, otherwise this would overflow
667const _: usize = std::mem::size_of::<ModelNotifyOpaque>() - std::mem::size_of::<ModelNotify>();
668const _: usize = std::mem::align_of::<ModelNotifyOpaque>() - std::mem::align_of::<ModelNotify>();
669
670impl ModelNotifyOpaque {
671    fn as_model_notify(&self) -> &ModelNotify {
672        // Safety: there should be no way to construct a ModelNotifyOpaque without it holding an actual ModelNotify
673        unsafe { std::mem::transmute::<&ModelNotifyOpaque, &ModelNotify>(self) }
674    }
675}
676
677/// Construct a new ModelNotifyNotify in the given memory region
678#[unsafe(no_mangle)]
679pub unsafe extern "C" fn slint_interpreter_model_notify_new(val: *mut ModelNotifyOpaque) {
680    unsafe { std::ptr::write(val as *mut ModelNotify, ModelNotify::default()) };
681}
682
683/// Destruct the value in that memory location
684#[unsafe(no_mangle)]
685pub unsafe extern "C" fn slint_interpreter_model_notify_destructor(val: *mut ModelNotifyOpaque) {
686    drop(unsafe { std::ptr::read(val as *mut ModelNotify) })
687}
688
689#[unsafe(no_mangle)]
690pub unsafe extern "C" fn slint_interpreter_model_notify_row_changed(
691    notify: &ModelNotifyOpaque,
692    row: usize,
693) {
694    notify.as_model_notify().row_changed(row);
695}
696
697#[unsafe(no_mangle)]
698pub unsafe extern "C" fn slint_interpreter_model_notify_row_added(
699    notify: &ModelNotifyOpaque,
700    row: usize,
701    count: usize,
702) {
703    notify.as_model_notify().row_added(row, count);
704}
705
706#[unsafe(no_mangle)]
707pub unsafe extern "C" fn slint_interpreter_model_notify_reset(notify: &ModelNotifyOpaque) {
708    notify.as_model_notify().reset();
709}
710
711#[unsafe(no_mangle)]
712pub unsafe extern "C" fn slint_interpreter_model_notify_row_removed(
713    notify: &ModelNotifyOpaque,
714    row: usize,
715    count: usize,
716) {
717    notify.as_model_notify().row_removed(row, count);
718}
719
720// FIXME: Figure out how to re-export the one from compilerlib
721/// DiagnosticLevel describes the severity of a diagnostic.
722#[derive(Clone)]
723#[repr(u8)]
724pub enum DiagnosticLevel {
725    /// The diagnostic belongs to an error.
726    Error,
727    /// The diagnostic belongs to a warning.
728    Warning,
729    /// The diagnostic is a note
730    Note,
731}
732
733/// Diagnostic describes the aspects of either a warning or an error, along
734/// with its location and a description. Diagnostics are typically returned by
735/// slint::interpreter::ComponentCompiler::diagnostics() in a vector.
736#[derive(Clone)]
737#[repr(C)]
738pub struct Diagnostic {
739    /// The message describing the warning or error.
740    message: SharedString,
741    /// The path to the source file where the warning or error is located.
742    source_file: SharedString,
743    /// The line within the source file. Line numbers start at 1.
744    line: usize,
745    /// The column within the source file. Column numbers start at 1.
746    column: usize,
747    /// The level of the diagnostic, such as a warning or an error.
748    level: DiagnosticLevel,
749}
750
751#[repr(transparent)]
752pub struct ComponentCompilerOpaque(#[allow(deprecated)] NonNull<ComponentCompiler>);
753
754#[allow(deprecated)]
755impl ComponentCompilerOpaque {
756    fn as_component_compiler(&self) -> &ComponentCompiler {
757        // Safety: there should be no way to construct a ComponentCompilerOpaque without it holding an actual ComponentCompiler
758        unsafe { self.0.as_ref() }
759    }
760    fn as_component_compiler_mut(&mut self) -> &mut ComponentCompiler {
761        // Safety: there should be no way to construct a ComponentCompilerOpaque without it holding an actual ComponentCompiler
762        unsafe { self.0.as_mut() }
763    }
764}
765
766#[unsafe(no_mangle)]
767#[allow(deprecated)]
768pub unsafe extern "C" fn slint_interpreter_component_compiler_new(
769    compiler: *mut ComponentCompilerOpaque,
770) {
771    unsafe {
772        *compiler = ComponentCompilerOpaque(NonNull::new_unchecked(Box::into_raw(Box::new(
773            ComponentCompiler::default(),
774        ))));
775    }
776}
777
778#[unsafe(no_mangle)]
779pub unsafe extern "C" fn slint_interpreter_component_compiler_destructor(
780    compiler: *mut ComponentCompilerOpaque,
781) {
782    drop(unsafe { Box::from_raw((*compiler).0.as_ptr()) })
783}
784
785#[unsafe(no_mangle)]
786pub unsafe extern "C" fn slint_interpreter_component_compiler_set_include_paths(
787    compiler: &mut ComponentCompilerOpaque,
788    paths: &SharedVector<SharedString>,
789) {
790    compiler
791        .as_component_compiler_mut()
792        .set_include_paths(paths.iter().map(|path| path.as_str().into()).collect())
793}
794
795#[unsafe(no_mangle)]
796pub unsafe extern "C" fn slint_interpreter_component_compiler_set_style(
797    compiler: &mut ComponentCompilerOpaque,
798    style: Slice<u8>,
799) {
800    compiler.as_component_compiler_mut().set_style(std::str::from_utf8(&style).unwrap().to_string())
801}
802
803#[unsafe(no_mangle)]
804pub unsafe extern "C" fn slint_interpreter_component_compiler_set_translation_domain(
805    compiler: &mut ComponentCompilerOpaque,
806    translation_domain: Slice<u8>,
807) {
808    compiler
809        .as_component_compiler_mut()
810        .set_translation_domain(std::str::from_utf8(&translation_domain).unwrap().to_string())
811}
812
813#[unsafe(no_mangle)]
814pub unsafe extern "C" fn slint_interpreter_component_compiler_get_style(
815    compiler: &ComponentCompilerOpaque,
816    style_out: &mut SharedString,
817) {
818    *style_out =
819        compiler.as_component_compiler().style().map_or(SharedString::default(), |s| s.into());
820}
821
822#[unsafe(no_mangle)]
823pub unsafe extern "C" fn slint_interpreter_component_compiler_get_include_paths(
824    compiler: &ComponentCompilerOpaque,
825    paths: &mut SharedVector<SharedString>,
826) {
827    paths.extend(
828        compiler
829            .as_component_compiler()
830            .include_paths()
831            .iter()
832            .map(|path| path.to_str().map_or_else(Default::default, |str| str.into())),
833    );
834}
835
836#[unsafe(no_mangle)]
837pub unsafe extern "C" fn slint_interpreter_component_compiler_get_diagnostics(
838    compiler: &ComponentCompilerOpaque,
839    out_diags: &mut SharedVector<Diagnostic>,
840) {
841    #[allow(deprecated)]
842    out_diags.extend(compiler.as_component_compiler().diagnostics().iter().map(|diagnostic| {
843        let (line, column) = diagnostic.line_column();
844        Diagnostic {
845            message: diagnostic.message().into(),
846            source_file: diagnostic
847                .source_file()
848                .and_then(|path| path.to_str())
849                .map_or_else(Default::default, |str| str.into()),
850            line,
851            column,
852            level: match diagnostic.level() {
853                i_slint_compiler::diagnostics::DiagnosticLevel::Error => DiagnosticLevel::Error,
854                i_slint_compiler::diagnostics::DiagnosticLevel::Warning => DiagnosticLevel::Warning,
855                i_slint_compiler::diagnostics::DiagnosticLevel::Note => DiagnosticLevel::Note,
856                _ => DiagnosticLevel::Warning,
857            },
858        }
859    }));
860}
861
862#[unsafe(no_mangle)]
863pub unsafe extern "C" fn slint_interpreter_component_compiler_build_from_source(
864    compiler: &mut ComponentCompilerOpaque,
865    source_code: Slice<u8>,
866    path: Slice<u8>,
867    component_definition_ptr: *mut ComponentDefinitionOpaque,
868) -> bool {
869    match spin_on::spin_on(compiler.as_component_compiler_mut().build_from_source(
870        std::str::from_utf8(&source_code).unwrap().to_string(),
871        std::str::from_utf8(&path).unwrap().to_string().into(),
872    )) {
873        Some(definition) => {
874            unsafe {
875                std::ptr::write(component_definition_ptr as *mut ComponentDefinition, definition)
876            };
877            true
878        }
879        None => false,
880    }
881}
882
883#[unsafe(no_mangle)]
884pub unsafe extern "C" fn slint_interpreter_component_compiler_build_from_path(
885    compiler: &mut ComponentCompilerOpaque,
886    path: Slice<u8>,
887    component_definition_ptr: *mut ComponentDefinitionOpaque,
888) -> bool {
889    use std::str::FromStr;
890    match spin_on::spin_on(
891        compiler
892            .as_component_compiler_mut()
893            .build_from_path(PathBuf::from_str(std::str::from_utf8(&path).unwrap()).unwrap()),
894    ) {
895        Some(definition) => {
896            unsafe {
897                std::ptr::write(component_definition_ptr as *mut ComponentDefinition, definition)
898            };
899            true
900        }
901        None => false,
902    }
903}
904
905/// PropertyDescriptor is a simple structure that's used to describe a property declared in .slint
906/// code. It is returned from in a vector from
907/// slint::interpreter::ComponentDefinition::properties().
908#[derive(Clone)]
909#[repr(C)]
910pub struct PropertyDescriptor {
911    /// The name of the declared property.
912    property_name: SharedString,
913    /// The type of the property.
914    property_type: ValueType,
915}
916
917#[repr(C)]
918// Note: This needs to stay the size of 1 pointer to allow for the null pointer definition
919// in the C++ wrapper to allow for the null state.
920pub struct ComponentDefinitionOpaque([usize; 1]);
921/// Asserts that ComponentCompilerOpaque is as large as ComponentCompiler and has the same alignment, to make transmute safe.
922const _: [(); std::mem::size_of::<ComponentDefinitionOpaque>()] =
923    [(); std::mem::size_of::<ComponentDefinition>()];
924const _: [(); std::mem::align_of::<ComponentDefinitionOpaque>()] =
925    [(); std::mem::align_of::<ComponentDefinition>()];
926
927impl ComponentDefinitionOpaque {
928    fn as_component_definition(&self) -> &ComponentDefinition {
929        // Safety: there should be no way to construct a ComponentDefinitionOpaque without it holding an actual ComponentDefinition
930        unsafe { std::mem::transmute::<&ComponentDefinitionOpaque, &ComponentDefinition>(self) }
931    }
932}
933
934/// Construct a new Value in the given memory location
935#[unsafe(no_mangle)]
936pub unsafe extern "C" fn slint_interpreter_component_definition_clone(
937    other: &ComponentDefinitionOpaque,
938    def: *mut ComponentDefinitionOpaque,
939) {
940    unsafe {
941        std::ptr::write(def as *mut ComponentDefinition, other.as_component_definition().clone())
942    }
943}
944
945/// Destruct the component definition in that memory location
946#[unsafe(no_mangle)]
947pub unsafe extern "C" fn slint_interpreter_component_definition_destructor(
948    val: *mut ComponentDefinitionOpaque,
949) {
950    drop(unsafe { std::ptr::read(val as *mut ComponentDefinition) })
951}
952
953/// Returns the list of properties of the component the component definition describes
954#[unsafe(no_mangle)]
955pub unsafe extern "C" fn slint_interpreter_component_definition_properties(
956    def: &ComponentDefinitionOpaque,
957    props: &mut SharedVector<PropertyDescriptor>,
958) {
959    props.extend(def.as_component_definition().properties().map(
960        |(property_name, property_type)| PropertyDescriptor {
961            property_name: property_name.into(),
962            property_type,
963        },
964    ))
965}
966
967/// Returns the list of callback names of the component the component definition describes
968#[unsafe(no_mangle)]
969pub unsafe extern "C" fn slint_interpreter_component_definition_callbacks(
970    def: &ComponentDefinitionOpaque,
971    callbacks: &mut SharedVector<SharedString>,
972) {
973    callbacks.extend(def.as_component_definition().callbacks().map(|name| name.into()))
974}
975
976/// Returns the list of function names of the component the component definition describes
977#[unsafe(no_mangle)]
978pub unsafe extern "C" fn slint_interpreter_component_definition_functions(
979    def: &ComponentDefinitionOpaque,
980    functions: &mut SharedVector<SharedString>,
981) {
982    functions.extend(def.as_component_definition().functions().map(|name| name.into()))
983}
984
985/// Return the name of the component definition
986#[unsafe(no_mangle)]
987pub unsafe extern "C" fn slint_interpreter_component_definition_name(
988    def: &ComponentDefinitionOpaque,
989    name: &mut SharedString,
990) {
991    *name = def.as_component_definition().name().into()
992}
993
994/// Returns a vector of strings with the names of all exported global singletons.
995#[unsafe(no_mangle)]
996pub unsafe extern "C" fn slint_interpreter_component_definition_globals(
997    def: &ComponentDefinitionOpaque,
998    names: &mut SharedVector<SharedString>,
999) {
1000    names.extend(def.as_component_definition().globals().map(|name| name.into()))
1001}
1002
1003/// Returns a vector of the property descriptors of the properties of the specified publicly exported global
1004/// singleton. Returns true if a global exists under the specified name; false otherwise.
1005#[unsafe(no_mangle)]
1006pub unsafe extern "C" fn slint_interpreter_component_definition_global_properties(
1007    def: &ComponentDefinitionOpaque,
1008    global_name: Slice<u8>,
1009    properties: &mut SharedVector<PropertyDescriptor>,
1010) -> bool {
1011    if let Some(property_it) =
1012        def.as_component_definition().global_properties(std::str::from_utf8(&global_name).unwrap())
1013    {
1014        properties.extend(property_it.map(|(property_name, property_type)| PropertyDescriptor {
1015            property_name: property_name.into(),
1016            property_type,
1017        }));
1018        true
1019    } else {
1020        false
1021    }
1022}
1023
1024/// Returns a vector of the names of the callbacks of the specified publicly exported global
1025/// singleton. Returns true if a global exists under the specified name; false otherwise.
1026#[unsafe(no_mangle)]
1027pub unsafe extern "C" fn slint_interpreter_component_definition_global_callbacks(
1028    def: &ComponentDefinitionOpaque,
1029    global_name: Slice<u8>,
1030    names: &mut SharedVector<SharedString>,
1031) -> bool {
1032    if let Some(name_it) =
1033        def.as_component_definition().global_callbacks(std::str::from_utf8(&global_name).unwrap())
1034    {
1035        names.extend(name_it.map(|name| name.into()));
1036        true
1037    } else {
1038        false
1039    }
1040}
1041
1042/// Returns a vector of the names of the functions of the specified publicly exported global
1043/// singleton. Returns true if a global exists under the specified name; false otherwise.
1044#[unsafe(no_mangle)]
1045pub unsafe extern "C" fn slint_interpreter_component_definition_global_functions(
1046    def: &ComponentDefinitionOpaque,
1047    global_name: Slice<u8>,
1048    names: &mut SharedVector<SharedString>,
1049) -> bool {
1050    if let Some(name_it) =
1051        def.as_component_definition().global_functions(std::str::from_utf8(&global_name).unwrap())
1052    {
1053        names.extend(name_it.map(|name| name.into()));
1054        true
1055    } else {
1056        false
1057    }
1058}
1059
1060#[cfg(test)]
1061mod tests {
1062    #[test]
1063    fn no_strong_reference_leak_per_ffi_call() {
1064        i_slint_backend_testing::init_no_event_loop();
1065        let mut compiler = crate::Compiler::default();
1066        compiler.set_style("fluent".into());
1067        let result = spin_on::spin_on(compiler.build_from_source(
1068            "export component Test { out property <int> val: 42; }".into(),
1069            std::path::PathBuf::from("test.slint"),
1070        ));
1071        assert!(!result.has_errors(), "{:?}", result.diagnostics().collect::<Vec<_>>());
1072        let instance = result.component("Test").unwrap().create().unwrap();
1073        let vrc = &instance.inner.0;
1074        let before = vtable::VRc::strong_count(vrc);
1075        for _ in 0..3 {
1076            let val = super::slint_interpreter_component_instance_get_property(
1077                vrc,
1078                i_slint_core::slice::Slice::from_slice(b"val"),
1079            );
1080            assert!(!val.is_null());
1081            drop(unsafe { Box::from_raw(val) });
1082        }
1083        assert_eq!(vtable::VRc::strong_count(vrc), before);
1084    }
1085}