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