1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-1.0 OR LicenseRef-Slint-commercial

use crate::dynamic_component::ErasedComponentBox;

use super::*;
use core::ptr::NonNull;
use i_slint_core::model::{Model, ModelNotify, SharedVectorModel};
use i_slint_core::slice::Slice;
use i_slint_core::window::WindowAdapter;
use std::ffi::c_void;
use vtable::VRef;

#[repr(C)]
#[cfg(target_pointer_width = "64")]
pub struct ValueOpaque([usize; 7]);
#[repr(C)]
#[cfg(target_pointer_width = "32")]
#[repr(align(8))]
pub struct ValueOpaque([usize; 9]);
/// Asserts that ValueOpaque is as large as Value and has the same alignment, to make transmute safe.
const _: [(); std::mem::size_of::<ValueOpaque>()] = [(); std::mem::size_of::<Value>()];
const _: [(); std::mem::align_of::<ValueOpaque>()] = [(); std::mem::align_of::<Value>()];

impl ValueOpaque {
    fn as_value(&self) -> &Value {
        // Safety: there should be no way to construct a ValueOpaque without it holding an actual Value
        unsafe { std::mem::transmute::<&ValueOpaque, &Value>(self) }
    }
}

/// Construct a new Value in the given memory location
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_value_new(val: *mut ValueOpaque) {
    std::ptr::write(val as *mut Value, Value::default())
}

/// Construct a new Value in the given memory location
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_value_clone(other: &ValueOpaque, val: *mut ValueOpaque) {
    std::ptr::write(val as *mut Value, other.as_value().clone())
}

/// Destruct the value in that memory location
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_value_destructor(val: *mut ValueOpaque) {
    drop(std::ptr::read(val as *mut Value))
}

#[no_mangle]
pub extern "C" fn slint_interpreter_value_eq(a: &ValueOpaque, b: &ValueOpaque) -> bool {
    a.as_value() == b.as_value()
}

/// Construct a new Value in the given memory location as string
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_value_new_string(
    str: &SharedString,
    val: *mut ValueOpaque,
) {
    std::ptr::write(val as *mut Value, Value::String(str.clone()))
}

/// Construct a new Value in the given memory location as double
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_value_new_double(double: f64, val: *mut ValueOpaque) {
    std::ptr::write(val as *mut Value, Value::Number(double))
}

/// Construct a new Value in the given memory location as bool
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_value_new_bool(b: bool, val: *mut ValueOpaque) {
    std::ptr::write(val as *mut Value, Value::Bool(b))
}

/// Construct a new Value in the given memory location as array model
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_value_new_array_model(
    a: &SharedVector<ValueOpaque>,
    val: *mut ValueOpaque,
) {
    // Safety: We assert that Value and ValueOpaque have the same size and alignment
    let vec = std::mem::transmute::<SharedVector<ValueOpaque>, SharedVector<Value>>(a.clone());
    std::ptr::write(
        val as *mut Value,
        Value::Model(ModelRc::new(SharedVectorModel::<Value>::from(vec))),
    )
}

/// Construct a new Value in the given memory location as Brush
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_value_new_brush(brush: &Brush, val: *mut ValueOpaque) {
    std::ptr::write(val as *mut Value, Value::Brush(brush.clone()))
}

/// Construct a new Value in the given memory location as Struct
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_value_new_struct(
    struc: &StructOpaque,
    val: *mut ValueOpaque,
) {
    std::ptr::write(val as *mut Value, Value::Struct(struc.as_struct().clone()))
}

/// Construct a new Value in the given memory location as image
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_value_new_image(img: &Image, val: *mut ValueOpaque) {
    std::ptr::write(val as *mut Value, Value::Image(img.clone()))
}

/// Construct a new Value containing a model in the given memory location
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_value_new_model(
    model: NonNull<u8>,
    vtable: &ModelAdaptorVTable,
    val: *mut ValueOpaque,
) {
    std::ptr::write(
        val as *mut Value,
        Value::Model(ModelRc::new(ModelAdaptorWrapper(vtable::VBox::from_raw(
            NonNull::from(vtable),
            model,
        )))),
    )
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_value_type(val: *const ValueOpaque) -> ValueType {
    (&*val).as_value().value_type()
}

#[no_mangle]
pub extern "C" fn slint_interpreter_value_to_string(val: &ValueOpaque) -> Option<&SharedString> {
    match val.as_value() {
        Value::String(v) => Some(v),
        _ => None,
    }
}

#[no_mangle]
pub extern "C" fn slint_interpreter_value_to_number(val: &ValueOpaque) -> Option<&f64> {
    match val.as_value() {
        Value::Number(v) => Some(v),
        _ => None,
    }
}

#[no_mangle]
pub extern "C" fn slint_interpreter_value_to_bool(val: &ValueOpaque) -> Option<&bool> {
    match val.as_value() {
        Value::Bool(v) => Some(v),
        _ => None,
    }
}

/// Extracts a `SharedVector<ValueOpaque>` out of the given value `val`, writes that into the
/// `out` parameter and returns true; returns false if the value does not hold an extractable
/// array.
#[no_mangle]
pub extern "C" fn slint_interpreter_value_to_array(
    val: &ValueOpaque,
    out: *mut SharedVector<ValueOpaque>,
) -> bool {
    match val.as_value() {
        Value::Model(m) => {
            let vec = if let Some(model) = m.as_any().downcast_ref::<SharedVectorModel<Value>>() {
                model.shared_vector()
            } else {
                m.iter().collect()
            };

            // Safety: We assert that Value and ValueOpaque have the same size and alignment
            unsafe {
                std::ptr::write(
                    out,
                    std::mem::transmute::<SharedVector<Value>, SharedVector<ValueOpaque>>(vec),
                );
            }

            true
        }
        _ => false,
    }
}

#[no_mangle]
pub extern "C" fn slint_interpreter_value_to_brush(val: &ValueOpaque) -> Option<&Brush> {
    match val.as_value() {
        Value::Brush(b) => Some(b),
        _ => None,
    }
}

#[no_mangle]
pub extern "C" fn slint_interpreter_value_to_struct(val: &ValueOpaque) -> *const StructOpaque {
    match val.as_value() {
        Value::Struct(s) => s as *const Struct as *const StructOpaque,
        _ => std::ptr::null(),
    }
}

#[no_mangle]
pub extern "C" fn slint_interpreter_value_to_image(val: &ValueOpaque) -> Option<&Image> {
    match val.as_value() {
        Value::Image(img) => Some(img),
        _ => None,
    }
}

#[repr(C)]
#[cfg(target_pointer_width = "64")]
pub struct StructOpaque([usize; 6]);
#[repr(C)]
#[cfg(target_pointer_width = "32")]
pub struct StructOpaque([u64; 4]);
const _: [(); std::mem::size_of::<StructOpaque>()] = [(); std::mem::size_of::<Struct>()];
const _: [(); std::mem::align_of::<StructOpaque>()] = [(); std::mem::align_of::<Struct>()];

impl StructOpaque {
    fn as_struct(&self) -> &Struct {
        // Safety: there should be no way to construct a StructOpaque without it holding an actual Struct
        unsafe { std::mem::transmute::<&StructOpaque, &Struct>(self) }
    }
    fn as_struct_mut(&mut self) -> &mut Struct {
        // Safety: there should be no way to construct a StructOpaque without it holding an actual Struct
        unsafe { std::mem::transmute::<&mut StructOpaque, &mut Struct>(self) }
    }
}

/// Construct a new Struct in the given memory location
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_struct_new(val: *mut StructOpaque) {
    std::ptr::write(val as *mut Struct, Struct::default())
}

/// Construct a new Struct in the given memory location
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_struct_clone(
    other: &StructOpaque,
    val: *mut StructOpaque,
) {
    std::ptr::write(val as *mut Struct, other.as_struct().clone())
}

/// Destruct the struct in that memory location
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_struct_destructor(val: *mut StructOpaque) {
    drop(std::ptr::read(val as *mut Struct))
}

#[no_mangle]
pub extern "C" fn slint_interpreter_struct_get_field<'a>(
    stru: &'a StructOpaque,
    name: Slice<u8>,
) -> Option<&'a ValueOpaque> {
    stru.as_struct()
        .get_field(std::str::from_utf8(&name).unwrap())
        .and_then(|v| unsafe { (v as *const Value as *const ValueOpaque).as_ref() })
}

#[no_mangle]
pub extern "C" fn slint_interpreter_struct_set_field<'a>(
    stru: &'a mut StructOpaque,
    name: Slice<u8>,
    value: &ValueOpaque,
) {
    stru.as_struct_mut()
        .set_field(std::str::from_utf8(&name).unwrap().into(), value.as_value().clone())
}

type StructIterator<'a> = std::collections::hash_map::Iter<'a, String, Value>;
#[repr(C)]
pub struct StructIteratorOpaque<'a>([usize; 5], std::marker::PhantomData<StructIterator<'a>>);
const _: [(); std::mem::size_of::<StructIteratorOpaque>()] =
    [(); std::mem::size_of::<StructIterator>()];
const _: [(); std::mem::align_of::<StructIteratorOpaque>()] =
    [(); std::mem::align_of::<StructIterator>()];

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_struct_iterator_destructor(
    val: *mut StructIteratorOpaque,
) {
    drop(std::ptr::read(val as *mut StructIterator))
}

/// The result of the slint_interpreter_struct_iterator_next function
/// If the iterator was at the end, the key will be empty, and the value will be None
#[repr(C)]
pub struct StructIteratorResult<'a> {
    k: Slice<'a, u8>,
    v: Option<&'a Value>,
}

/// Advance the iterator and return the next value, or an
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_struct_iterator_next<'a>(
    iter: &'a mut StructIteratorOpaque,
) -> StructIteratorResult<'a> {
    if let Some((str, val)) = (*(iter as *mut StructIteratorOpaque as *mut StructIterator)).next() {
        StructIteratorResult { k: Slice::from_slice(str.as_bytes()), v: Some(val) }
    } else {
        StructIteratorResult { k: Slice::default(), v: None }
    }
}

#[no_mangle]
pub extern "C" fn slint_interpreter_struct_make_iter(stru: &StructOpaque) -> StructIteratorOpaque {
    let ret_it: StructIterator = stru.as_struct().0.iter();
    unsafe {
        let mut r = std::mem::MaybeUninit::<StructIteratorOpaque>::uninit();
        std::ptr::write(r.as_mut_ptr() as *mut StructIterator, ret_it);
        r.assume_init()
    }
}

/// Get a property.
/// The `out` parameter must be uninitialized. If this function returns true, the out will be initialized
/// to the resulting value. If this function returns false, out is unchanged
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_instance_get_property(
    inst: &ErasedComponentBox,
    name: Slice<u8>,
    out: *mut ValueOpaque,
) -> bool {
    generativity::make_guard!(guard);
    let comp = inst.unerase(guard);
    match comp
        .description()
        .get_property(comp.borrow(), &normalize_identifier(std::str::from_utf8(&name).unwrap()))
    {
        Ok(val) => {
            std::ptr::write(out as *mut Value, val);
            true
        }
        Err(_) => false,
    }
}

#[no_mangle]
pub extern "C" fn slint_interpreter_component_instance_set_property(
    inst: &ErasedComponentBox,
    name: Slice<u8>,
    val: &ValueOpaque,
) -> bool {
    generativity::make_guard!(guard);
    let comp = inst.unerase(guard);
    comp.description()
        .set_property(
            comp.borrow(),
            &normalize_identifier(std::str::from_utf8(&name).unwrap()),
            val.as_value().clone(),
        )
        .is_ok()
}

/// Invoke a callback or function
/// The `out` parameter must be uninitialized. If this function returns true, the out will be initialized
/// to the resulting value. If this function returns false, out is unchanged
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_instance_invoke(
    inst: &ErasedComponentBox,
    name: Slice<u8>,
    args: Slice<ValueOpaque>,
    out: *mut ValueOpaque,
) -> bool {
    let args = std::mem::transmute::<Slice<ValueOpaque>, Slice<Value>>(args);
    generativity::make_guard!(guard);
    let comp = inst.unerase(guard);
    match comp.description().invoke(
        comp.borrow(),
        &normalize_identifier(std::str::from_utf8(&name).unwrap()),
        args.as_slice(),
    ) {
        Ok(val) => {
            std::ptr::write(out as *mut Value, val);
            true
        }
        Err(_) => false,
    }
}

/// Wrap the user_data provided by the native code and call the drop function on Drop.
///
/// Safety: user_data must be a pointer that can be destroyed by the drop_user_data function.
/// callback must be a valid callback that initialize the `ret`
struct CallbackUserData {
    user_data: *mut c_void,
    drop_user_data: Option<extern "C" fn(*mut c_void)>,
    callback: extern "C" fn(user_data: *mut c_void, arg: Slice<ValueOpaque>, ret: *mut ValueOpaque),
}

impl Drop for CallbackUserData {
    fn drop(&mut self) {
        if let Some(x) = self.drop_user_data {
            x(self.user_data)
        }
    }
}

impl CallbackUserData {
    fn call(&self, args: &[Value]) -> Value {
        unsafe {
            let args = std::mem::transmute::<&[Value], &[ValueOpaque]>(args);
            let mut ret = std::mem::MaybeUninit::<Value>::uninit();
            (self.callback)(
                self.user_data,
                Slice::from_slice(args),
                ret.as_mut_ptr() as *mut ValueOpaque,
            );
            ret.assume_init()
        }
    }
}

/// Set a handler for the callback.
/// The `callback` function must initialize the `ret` (the `ret` passed to the callback is initialized and is assumed initialized after the function)
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_instance_set_callback(
    inst: &ErasedComponentBox,
    name: Slice<u8>,
    callback: extern "C" fn(user_data: *mut c_void, arg: Slice<ValueOpaque>, ret: *mut ValueOpaque),
    user_data: *mut c_void,
    drop_user_data: Option<extern "C" fn(*mut c_void)>,
) -> bool {
    let ud = CallbackUserData { user_data, drop_user_data, callback };

    generativity::make_guard!(guard);
    let comp = inst.unerase(guard);
    comp.description()
        .set_callback_handler(
            comp.borrow(),
            &normalize_identifier(std::str::from_utf8(&name).unwrap()),
            Box::new(move |args| ud.call(args)),
        )
        .is_ok()
}

/// Get a global property.
/// The `out` parameter must be uninitialized. If this function returns true, the out will be initialized
/// to the resulting value. If this function returns false, out is unchanged
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_instance_get_global_property(
    inst: &ErasedComponentBox,
    global: Slice<u8>,
    property_name: Slice<u8>,
    out: *mut ValueOpaque,
) -> bool {
    generativity::make_guard!(guard);
    let comp = inst.unerase(guard);
    match comp
        .description()
        .get_global(comp.borrow(), &normalize_identifier(std::str::from_utf8(&global).unwrap()))
        .and_then(|g| {
            g.as_ref()
                .get_property(&normalize_identifier(std::str::from_utf8(&property_name).unwrap()))
        }) {
        Ok(val) => {
            std::ptr::write(out as *mut Value, val);
            true
        }
        Err(_) => false,
    }
}

#[no_mangle]
pub extern "C" fn slint_interpreter_component_instance_set_global_property(
    inst: &ErasedComponentBox,
    global: Slice<u8>,
    property_name: Slice<u8>,
    val: &ValueOpaque,
) -> bool {
    generativity::make_guard!(guard);
    let comp = inst.unerase(guard);
    comp.description()
        .get_global(comp.borrow(), &normalize_identifier(std::str::from_utf8(&global).unwrap()))
        .and_then(|g| {
            g.as_ref()
                .set_property(
                    &normalize_identifier(std::str::from_utf8(&property_name).unwrap()),
                    val.as_value().clone(),
                )
                .map_err(|_| ())
        })
        .is_ok()
}

/// The `callback` function must initialize the `ret` (the `ret` passed to the callback is initialized and is assumed initialized after the function)
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_instance_set_global_callback(
    inst: &ErasedComponentBox,
    global: Slice<u8>,
    name: Slice<u8>,
    callback: extern "C" fn(user_data: *mut c_void, arg: Slice<ValueOpaque>, ret: *mut ValueOpaque),
    user_data: *mut c_void,
    drop_user_data: Option<extern "C" fn(*mut c_void)>,
) -> bool {
    let ud = CallbackUserData { user_data, drop_user_data, callback };

    generativity::make_guard!(guard);
    let comp = inst.unerase(guard);
    comp.description()
        .get_global(comp.borrow(), &normalize_identifier(std::str::from_utf8(&global).unwrap()))
        .and_then(|g| {
            g.as_ref().set_callback_handler(
                &normalize_identifier(std::str::from_utf8(&name).unwrap()),
                Box::new(move |args| ud.call(args)),
            )
        })
        .is_ok()
}

/// Invoke a global callback or function.
/// The `out` parameter must be uninitialized. If this function returns true, the out will be initialized
/// to the resulting value. If this function returns false, out is unchanged
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_instance_invoke_global(
    inst: &ErasedComponentBox,
    global: Slice<u8>,
    callable_name: Slice<u8>,
    args: Slice<ValueOpaque>,
    out: *mut ValueOpaque,
) -> bool {
    let args = std::mem::transmute::<Slice<ValueOpaque>, Slice<Value>>(args);
    generativity::make_guard!(guard);
    let comp = inst.unerase(guard);
    let callable_name = std::str::from_utf8(&callable_name).unwrap();
    match comp
        .description()
        .get_global(comp.borrow(), &normalize_identifier(std::str::from_utf8(&global).unwrap()))
        .and_then(|g| {
            if matches!(
                comp.description()
                    .original
                    .root_element
                    .borrow()
                    .lookup_property(callable_name)
                    .property_type,
                i_slint_compiler::langtype::Type::Function { .. }
            ) {
                g.as_ref().eval_function(
                    &normalize_identifier(callable_name),
                    args.as_slice().iter().cloned().collect(),
                )
            } else {
                g.as_ref().invoke_callback(&normalize_identifier(callable_name), args.as_slice())
            }
        }) {
        Ok(val) => {
            std::ptr::write(out as *mut Value, val);
            true
        }
        Err(_) => false,
    }
}

/// Show or hide
#[no_mangle]
pub extern "C" fn slint_interpreter_component_instance_show(
    inst: &ErasedComponentBox,
    is_visible: bool,
) {
    generativity::make_guard!(guard);
    let comp = inst.unerase(guard);
    if let Some(w) = comp.borrow_instance().window_adapter().internal(i_slint_core::InternalToken) {
        if is_visible {
            w.show().unwrap();
        } else {
            w.hide().unwrap();
        }
    }
}

/// Return a window for the component
///
/// The out pointer must be uninitialized and must be destroyed with
/// slint_windowrc_drop after usage
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_instance_window(
    inst: &ErasedComponentBox,
    out: *mut *const i_slint_core::window::ffi::WindowAdapterRcOpaque,
) {
    assert_eq!(
        core::mem::size_of::<Rc<dyn WindowAdapter>>(),
        core::mem::size_of::<i_slint_core::window::ffi::WindowAdapterRcOpaque>()
    );
    core::ptr::write(
        out as *mut *const Rc<dyn WindowAdapter>,
        inst.window_adapter().unwrap() as *const _,
    )
}

/// Instantiate an instance from a definition.
///
/// The `out` must be uninitialized and is going to be initialized after the call
/// and need to be destroyed with slint_interpreter_component_instance_destructor
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_instance_create(
    def: &ComponentDefinitionOpaque,
    out: *mut ComponentInstance,
) {
    std::ptr::write(out, def.as_component_definition().create().unwrap())
}

#[vtable::vtable]
#[repr(C)]
pub struct ModelAdaptorVTable {
    pub row_count: extern "C" fn(VRef<ModelAdaptorVTable>) -> usize,
    pub row_data:
        unsafe extern "C" fn(VRef<ModelAdaptorVTable>, row: usize, out: *mut ValueOpaque) -> bool,
    pub set_row_data: extern "C" fn(VRef<ModelAdaptorVTable>, row: usize, value: &ValueOpaque),
    pub get_notify: extern "C" fn(VRef<ModelAdaptorVTable>) -> &ModelNotifyOpaque,
    pub drop: extern "C" fn(VRefMut<ModelAdaptorVTable>),
}

struct ModelAdaptorWrapper(vtable::VBox<ModelAdaptorVTable>);
impl Model for ModelAdaptorWrapper {
    type Data = Value;

    fn row_count(&self) -> usize {
        self.0.row_count()
    }

    fn row_data(&self, row: usize) -> Option<Value> {
        unsafe {
            let mut v = std::mem::MaybeUninit::<Value>::uninit();
            if self.0.row_data(row, v.as_mut_ptr() as *mut ValueOpaque) {
                Some(v.assume_init())
            } else {
                None
            }
        }
    }

    fn model_tracker(&self) -> &dyn i_slint_core::model::ModelTracker {
        self.0.get_notify().as_model_notify()
    }

    fn set_row_data(&self, row: usize, data: Value) {
        let val: &ValueOpaque = unsafe { std::mem::transmute::<&Value, &ValueOpaque>(&data) };
        self.0.set_row_data(row, val);
    }
}

#[repr(C)]
#[cfg(target_pointer_width = "64")]
pub struct ModelNotifyOpaque([usize; 8]);
#[repr(C)]
#[cfg(target_pointer_width = "32")]
pub struct ModelNotifyOpaque([usize; 12]);
/// Asserts that ModelNotifyOpaque is at least as large as ModelNotify, otherwise this would overflow
const _: usize = std::mem::size_of::<ModelNotifyOpaque>() - std::mem::size_of::<ModelNotify>();
const _: usize = std::mem::align_of::<ModelNotifyOpaque>() - std::mem::align_of::<ModelNotify>();

impl ModelNotifyOpaque {
    fn as_model_notify(&self) -> &ModelNotify {
        // Safety: there should be no way to construct a ModelNotifyOpaque without it holding an actual ModelNotify
        unsafe { std::mem::transmute::<&ModelNotifyOpaque, &ModelNotify>(self) }
    }
}

/// Construct a new ModelNotifyNotify in the given memory region
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_model_notify_new(val: *mut ModelNotifyOpaque) {
    std::ptr::write(val as *mut ModelNotify, ModelNotify::default());
}

/// Destruct the value in that memory location
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_model_notify_destructor(val: *mut ModelNotifyOpaque) {
    drop(std::ptr::read(val as *mut ModelNotify))
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_model_notify_row_changed(
    notify: &ModelNotifyOpaque,
    row: usize,
) {
    notify.as_model_notify().row_changed(row);
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_model_notify_row_added(
    notify: &ModelNotifyOpaque,
    row: usize,
    count: usize,
) {
    notify.as_model_notify().row_added(row, count);
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_model_notify_reset(notify: &ModelNotifyOpaque) {
    notify.as_model_notify().reset();
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_model_notify_row_removed(
    notify: &ModelNotifyOpaque,
    row: usize,
    count: usize,
) {
    notify.as_model_notify().row_removed(row, count);
}

// FIXME: Figure out how to re-export the one from compilerlib
/// DiagnosticLevel describes the severity of a diagnostic.
#[derive(Clone)]
#[repr(C)]
pub enum DiagnosticLevel {
    /// The diagnostic belongs to an error.
    Error,
    /// The diagnostic belongs to a warning.
    Warning,
}

/// Diagnostic describes the aspects of either a warning or an error, along
/// with its location and a description. Diagnostics are typically returned by
/// slint::interpreter::ComponentCompiler::diagnostics() in a vector.
#[derive(Clone)]
#[repr(C)]
pub struct Diagnostic {
    /// The message describing the warning or error.
    message: SharedString,
    /// The path to the source file where the warning or error is located.
    source_file: SharedString,
    /// The line within the source file. Line numbers start at 1.
    line: usize,
    /// The column within the source file. Column numbers start at 1.
    column: usize,
    /// The level of the diagnostic, such as a warning or an error.
    level: DiagnosticLevel,
}

#[repr(transparent)]
pub struct ComponentCompilerOpaque(NonNull<ComponentCompiler>);

impl ComponentCompilerOpaque {
    fn as_component_compiler(&self) -> &ComponentCompiler {
        // Safety: there should be no way to construct a ComponentCompilerOpaque without it holding an actual ComponentCompiler
        unsafe { self.0.as_ref() }
    }
    fn as_component_compiler_mut(&mut self) -> &mut ComponentCompiler {
        // Safety: there should be no way to construct a ComponentCompilerOpaque without it holding an actual ComponentCompiler
        unsafe { self.0.as_mut() }
    }
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_compiler_new(
    compiler: *mut ComponentCompilerOpaque,
) {
    *compiler = ComponentCompilerOpaque(NonNull::new_unchecked(Box::into_raw(Box::new(
        ComponentCompiler::default(),
    ))));
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_compiler_destructor(
    compiler: *mut ComponentCompilerOpaque,
) {
    drop(Box::from_raw((*compiler).0.as_ptr()))
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_compiler_set_include_paths(
    compiler: &mut ComponentCompilerOpaque,
    paths: &SharedVector<SharedString>,
) {
    compiler
        .as_component_compiler_mut()
        .set_include_paths(paths.iter().map(|path| path.as_str().into()).collect())
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_compiler_set_style(
    compiler: &mut ComponentCompilerOpaque,
    style: Slice<u8>,
) {
    compiler.as_component_compiler_mut().set_style(std::str::from_utf8(&style).unwrap().to_string())
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_compiler_get_style(
    compiler: &ComponentCompilerOpaque,
    style_out: &mut SharedString,
) {
    *style_out =
        compiler.as_component_compiler().style().map_or(SharedString::default(), |s| s.into());
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_compiler_get_include_paths(
    compiler: &ComponentCompilerOpaque,
    paths: &mut SharedVector<SharedString>,
) {
    paths.extend(
        compiler
            .as_component_compiler()
            .include_paths()
            .iter()
            .map(|path| path.to_str().map_or_else(Default::default, |str| str.into())),
    );
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_compiler_get_diagnostics(
    compiler: &ComponentCompilerOpaque,
    out_diags: &mut SharedVector<Diagnostic>,
) {
    out_diags.extend(compiler.as_component_compiler().diagnostics.iter().map(|diagnostic| {
        let (line, column) = diagnostic.line_column();
        Diagnostic {
            message: diagnostic.message().into(),
            source_file: diagnostic
                .source_file()
                .and_then(|path| path.to_str())
                .map_or_else(Default::default, |str| str.into()),
            line,
            column,
            level: match diagnostic.level() {
                i_slint_compiler::diagnostics::DiagnosticLevel::Error => DiagnosticLevel::Error,
                i_slint_compiler::diagnostics::DiagnosticLevel::Warning => DiagnosticLevel::Warning,
                _ => DiagnosticLevel::Warning,
            },
        }
    }));
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_compiler_build_from_source(
    compiler: &mut ComponentCompilerOpaque,
    source_code: Slice<u8>,
    path: Slice<u8>,
    component_definition_ptr: *mut ComponentDefinitionOpaque,
) -> bool {
    match spin_on::spin_on(compiler.as_component_compiler_mut().build_from_source(
        std::str::from_utf8(&source_code).unwrap().to_string(),
        std::str::from_utf8(&path).unwrap().to_string().into(),
    )) {
        Some(definition) => {
            std::ptr::write(component_definition_ptr as *mut ComponentDefinition, definition);
            true
        }
        None => false,
    }
}

#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_compiler_build_from_path(
    compiler: &mut ComponentCompilerOpaque,
    path: Slice<u8>,
    component_definition_ptr: *mut ComponentDefinitionOpaque,
) -> bool {
    use std::str::FromStr;
    match spin_on::spin_on(
        compiler
            .as_component_compiler_mut()
            .build_from_path(PathBuf::from_str(std::str::from_utf8(&path).unwrap()).unwrap()),
    ) {
        Some(definition) => {
            std::ptr::write(component_definition_ptr as *mut ComponentDefinition, definition);
            true
        }
        None => false,
    }
}

/// PropertyDescriptor is a simple structure that's used to describe a property declared in .slint
/// code. It is returned from in a vector from
/// slint::interpreter::ComponentDefinition::properties().
#[derive(Clone)]
#[repr(C)]
pub struct PropertyDescriptor {
    /// The name of the declared property.
    property_name: SharedString,
    /// The type of the property.
    property_type: ValueType,
}

#[repr(C)]
// Note: This needs to stay the size of 1 pointer to allow for the null pointer definition
// in the C++ wrapper to allow for the null state.
pub struct ComponentDefinitionOpaque([usize; 1]);
/// Asserts that ComponentCompilerOpaque is as large as ComponentCompiler and has the same alignment, to make transmute safe.
const _: [(); std::mem::size_of::<ComponentDefinitionOpaque>()] =
    [(); std::mem::size_of::<ComponentDefinition>()];
const _: [(); std::mem::align_of::<ComponentDefinitionOpaque>()] =
    [(); std::mem::align_of::<ComponentDefinition>()];

impl ComponentDefinitionOpaque {
    fn as_component_definition(&self) -> &ComponentDefinition {
        // Safety: there should be no way to construct a ComponentDefinitionOpaque without it holding an actual ComponentDefinition
        unsafe { std::mem::transmute::<&ComponentDefinitionOpaque, &ComponentDefinition>(self) }
    }
}

/// Construct a new Value in the given memory location
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_definition_clone(
    other: &ComponentDefinitionOpaque,
    def: *mut ComponentDefinitionOpaque,
) {
    std::ptr::write(def as *mut ComponentDefinition, other.as_component_definition().clone())
}

/// Destruct the component definition in that memory location
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_definition_destructor(
    val: *mut ComponentDefinitionOpaque,
) {
    drop(std::ptr::read(val as *mut ComponentDefinition))
}

/// Returns the list of properties of the component the component definition describes
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_definition_properties(
    def: &ComponentDefinitionOpaque,
    props: &mut SharedVector<PropertyDescriptor>,
) {
    props.extend((&*def).as_component_definition().properties().map(
        |(property_name, property_type)| PropertyDescriptor {
            property_name: property_name.into(),
            property_type,
        },
    ))
}

/// Returns the list of callback names of the component the component definition describes
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_definition_callbacks(
    def: &ComponentDefinitionOpaque,
    callbacks: &mut SharedVector<SharedString>,
) {
    callbacks.extend((&*def).as_component_definition().callbacks().map(|name| name.into()))
}

/// Return the name of the component definition
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_definition_name(
    def: &ComponentDefinitionOpaque,
    name: &mut SharedString,
) {
    *name = (&*def).as_component_definition().name().into()
}

/// Returns a vector of strings with the names of all exported global singletons.
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_definition_globals(
    def: &ComponentDefinitionOpaque,
    names: &mut SharedVector<SharedString>,
) {
    names.extend((&*def).as_component_definition().globals().map(|name| name.into()))
}

/// Returns a vector of the property descriptors of the properties of the specified publicly exported global
/// singleton. Returns true if a global exists under the specified name; false otherwise.
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_definition_global_properties(
    def: &ComponentDefinitionOpaque,
    global_name: Slice<u8>,
    properties: &mut SharedVector<PropertyDescriptor>,
) -> bool {
    if let Some(property_it) = (&*def)
        .as_component_definition()
        .global_properties(std::str::from_utf8(&global_name).unwrap())
    {
        properties.extend(property_it.map(|(property_name, property_type)| PropertyDescriptor {
            property_name: property_name.into(),
            property_type,
        }));
        true
    } else {
        false
    }
}

/// Returns a vector of the names of the callbacks of the specified publicly exported global
/// singleton. Returns true if a global exists under the specified name; false otherwise.
#[no_mangle]
pub unsafe extern "C" fn slint_interpreter_component_definition_global_callbacks(
    def: &ComponentDefinitionOpaque,
    global_name: Slice<u8>,
    names: &mut SharedVector<SharedString>,
) -> bool {
    if let Some(name_it) = (&*def)
        .as_component_definition()
        .global_callbacks(std::str::from_utf8(&global_name).unwrap())
    {
        names.extend(name_it.map(|name| name.into()));
        true
    } else {
        false
    }
}