noesis_runtime 0.12.1

Rust bindings for the Noesis GUI Native SDK: load XAML UI, drive the view and renderer, and write custom controls in Rust. Renderer-agnostic; Bevy integration lives in noesis_bevy.
Documentation
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
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
//! `Style` from code + template assignment.
//!
//! The XAML you'd write as:
//!
//! ```xml
//! <Style TargetType="TextBlock">
//!   <Setter Property="FontSize" Value="24"/>
//! </Style>
//! ```
//!
//! built programmatically:
//!
//! ```no_run
//! # use noesis_runtime::styles::Style;
//! # use noesis_runtime::binding::box_f64;
//! let mut style = Style::new();
//! style.set_target_type("TextBlock");
//! style.add_setter("FontSize", &box_f64(24.0));
//! ```
//!
//! then assigned with
//! [`FrameworkElement::set_style`](crate::view::FrameworkElement::set_style).
//!
//! Templates ([`ControlTemplate`], [`DataTemplate`]) are authored by parsing a
//! `<ControlTemplate>` / `<DataTemplate>` from an in-memory XAML string and
//! assigning it: a `ControlTemplate` via
//! [`FrameworkElement::set_control_template`](crate::view::FrameworkElement::set_control_template),
//! a `DataTemplate` via the existing `set_component` path on `ContentTemplate` /
//! `ItemTemplate`.
//!
//! Style triggers are also built here: [`Trigger`], [`DataTrigger`],
//! [`MultiTrigger`] and [`EventTrigger`] construct from code, attach to a
//! [`Style`]'s `Triggers` collection ([`Style::add_trigger`]) and read back
//! ([`Style::get_trigger`]). A [`TemplateSelector`] wraps a
//! `Noesis::DataTemplateSelector` whose `SelectTemplate` dispatches into Rust.
//!
//! Noesis 3.2.13 has no `FrameworkElementFactory`, so the WPF-style code-built
//! template *factory tree* does not exist here; the XAML-parse + assign path is
//! the supported way to author a template's visual tree.

use core::ptr::NonNull;
use std::ffi::{CStr, CString, c_void};

use crate::animation::BeginStoryboard;
use crate::binding::{Binding, Boxed};
use crate::ffi::{
    TemplateSelectorVTable, noesis_base_component_release, noesis_control_template_parse,
    noesis_data_template_parse, noesis_framework_template_find_name, noesis_style_add_setter,
    noesis_style_create, noesis_style_destroy, noesis_style_set_based_on,
    noesis_style_set_target_type, noesis_templates_data_trigger_add_setter,
    noesis_templates_data_trigger_create, noesis_templates_data_trigger_get_binding,
    noesis_templates_data_trigger_get_value, noesis_templates_data_trigger_set_binding,
    noesis_templates_data_trigger_set_value, noesis_templates_data_trigger_setter_count,
    noesis_templates_event_trigger_action_count, noesis_templates_event_trigger_add_action,
    noesis_templates_event_trigger_create, noesis_templates_event_trigger_get_routed_event_name,
    noesis_templates_event_trigger_get_source_name,
    noesis_templates_event_trigger_set_routed_event,
    noesis_templates_event_trigger_set_source_name,
    noesis_templates_multi_data_trigger_add_condition,
    noesis_templates_multi_data_trigger_add_setter,
    noesis_templates_multi_data_trigger_condition_count,
    noesis_templates_multi_data_trigger_condition_has_binding,
    noesis_templates_multi_data_trigger_create,
    noesis_templates_multi_data_trigger_get_condition_value,
    noesis_templates_multi_data_trigger_setter_count, noesis_templates_multi_trigger_add_condition,
    noesis_templates_multi_trigger_add_setter, noesis_templates_multi_trigger_condition_count,
    noesis_templates_multi_trigger_create,
    noesis_templates_multi_trigger_get_condition_property_name,
    noesis_templates_multi_trigger_get_condition_value,
    noesis_templates_multi_trigger_setter_count, noesis_templates_selector_create,
    noesis_templates_selector_destroy, noesis_templates_selector_select,
    noesis_templates_style_add_trigger, noesis_templates_style_get_trigger,
    noesis_templates_style_trigger_count, noesis_templates_trigger_add_setter,
    noesis_templates_trigger_create, noesis_templates_trigger_get_property_name,
    noesis_templates_trigger_get_value, noesis_templates_trigger_set_property,
    noesis_templates_trigger_set_value, noesis_templates_trigger_setter_count, noesis_unbox_bool,
    noesis_unbox_int32, noesis_unbox_string,
};
use crate::view::FrameworkElement;

/// A code-built `Noesis::Style`: the programmatic equivalent of a XAML
/// `<Style>`. Owns a `+1` reference released on drop.
///
/// Assigning it to an element
/// ([`FrameworkElement::set_style`](crate::view::FrameworkElement::set_style))
/// or adding it to a [`ResourceDictionary`](crate::resources::ResourceDictionary)
/// makes Noesis take its own reference, so the handle may be dropped afterwards.
///
/// A `Style` is *sealed* the first time it's applied; mutate it (target type,
/// setters, based-on) **before** assigning it.
pub struct Style {
    ptr: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for Style {}

impl Default for Style {
    fn default() -> Self {
        Self::new()
    }
}

impl Style {
    /// Create an empty style (no target type, no setters).
    ///
    /// # Panics
    ///
    /// Panics if the Noesis allocation fails (returns null).
    #[must_use]
    pub fn new() -> Self {
        // SAFETY: no preconditions beyond a live Noesis runtime.
        let ptr = unsafe { noesis_style_create() };
        Self {
            ptr: NonNull::new(ptr).expect("noesis_style_create returned null"),
        }
    }

    /// Wrap an already-owned (`+1`) `Noesis::Style*`, e.g. the `AddRef`'d result
    /// of `style`.
    ///
    /// # Safety
    ///
    /// `ptr` must be a live `Noesis::Style*` carrying a reference this wrapper
    /// takes ownership of (released on drop).
    #[must_use]
    pub(crate) unsafe fn from_owned(ptr: NonNull<c_void>) -> Self {
        Self { ptr }
    }

    /// Raw `Noesis::Style*` (a `BaseComponent*`). Borrowed for the lifetime of
    /// `self`.
    #[must_use]
    pub fn raw(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }

    /// Set the style's `TargetType` by registered type name (e.g. `"TextBlock"`,
    /// `"Button"`). The type is resolved through Noesis's reflection registry.
    /// It must already be registered, which the built-in controls do on first
    /// use (and any type referenced from loaded XAML does). Returns `false`
    /// (leaving the target type unset) if the name is unknown or contains an
    /// interior NUL byte. Setting the target type is a prerequisite for
    /// [`add_setter`](Self::add_setter), which resolves DPs on it.
    #[must_use = "a false return means the property was not set (unknown name / type mismatch / read-only)"]
    pub fn set_target_type(&mut self, type_name: &str) -> bool {
        let Ok(c) = CString::new(type_name) else {
            return false;
        };
        // SAFETY: self.ptr live; c lives for the call. The C side returns false
        // (no-op) on an unknown type name.
        unsafe { noesis_style_set_target_type(self.ptr.as_ptr(), c.as_ptr()) }
    }

    /// Append a `Setter` for the dependency property named `dp_name` (resolved
    /// on the style's `TargetType`) with the boxed `value`. The setter stores
    /// its own reference to `value`. Returns `false` if no target type is set,
    /// `dp_name` is not a DP on that type, or `dp_name` contains an interior NUL
    /// byte. Call [`set_target_type`](Self::set_target_type) first.
    pub fn add_setter(&mut self, dp_name: &str, value: &Boxed) -> bool {
        // SAFETY: value.raw() is a live BaseComponent* for the call.
        unsafe { self.add_setter_raw(dp_name, value.raw()) }
    }

    /// Append a `Setter` taking a raw `BaseComponent*` value (e.g. a brush, a
    /// nested object). See [`add_setter`](Self::add_setter) for the resolution
    /// rules and return contract.
    ///
    /// # Safety
    ///
    /// `value` must be a live `Noesis::BaseComponent*` that outlives the call;
    /// the setter takes its own reference.
    pub unsafe fn add_setter_raw(&mut self, dp_name: &str, value: *mut c_void) -> bool {
        let Ok(c) = CString::new(dp_name) else {
            return false;
        };
        // SAFETY: self.ptr live; c lives for the call; value per # Safety.
        unsafe { noesis_style_add_setter(self.ptr.as_ptr(), c.as_ptr(), value) }
    }

    /// Set the `BasedOn` style this style inherits setters/triggers from
    /// (`Style.BasedOn`). Noesis takes its own reference to `base`.
    pub fn set_based_on(&mut self, base: &Style) {
        // SAFETY: both pointers are live Style*; Noesis AddRefs `base`.
        unsafe { noesis_style_set_based_on(self.ptr.as_ptr(), base.raw()) }
    }

    /// Append `trigger` to this style's `Triggers` collection
    /// (`Style::GetTriggers`). The collection takes its own reference, so the
    /// trigger handle may be dropped afterwards. Like setters, triggers must be
    /// added **before** the style is sealed (first applied). Returns `false`
    /// only if the underlying handles are invalid.
    pub fn add_trigger<T: TriggerHandle>(&mut self, trigger: &T) -> bool {
        // SAFETY: both pointers are live; Noesis AddRefs the trigger.
        unsafe { noesis_templates_style_add_trigger(self.ptr.as_ptr(), trigger.trigger_ptr()) }
    }

    /// Number of triggers in this style's `Triggers` collection.
    #[must_use]
    pub fn trigger_count(&self) -> u32 {
        // SAFETY: self.ptr is a live Style*.
        let n = unsafe { noesis_templates_style_trigger_count(self.ptr.as_ptr()) };
        u32::try_from(n.max(0)).unwrap_or(0)
    }

    /// Take the trigger at `index` back out of the live `Triggers` collection as
    /// an owned [`TriggerReadback`] (`AddRef`'d). Its accessors re-read the
    /// property / value / setter surface from the live Noesis object. `None` if
    /// `index` is out of range.
    #[must_use]
    pub fn get_trigger(&self, index: u32) -> Option<TriggerReadback> {
        // SAFETY: self.ptr is a live Style*; the result is a +1-owned trigger.
        let p = unsafe { noesis_templates_style_get_trigger(self.ptr.as_ptr(), index) };
        NonNull::new(p).map(|ptr| TriggerReadback { ptr })
    }

    /// Start a [`StyleBuilder`] targeting `target_type` (e.g. `"TextBlock"`),
    /// resolved through Noesis's reflection registry like
    /// [`set_target_type`](Self::set_target_type). Chain
    /// [`setter`](StyleBuilder::setter) / [`based_on`](StyleBuilder::based_on) /
    /// [`trigger`](StyleBuilder::trigger), then [`build`](StyleBuilder::build).
    ///
    /// # Panics
    ///
    /// Panics if `target_type` is unknown to the reflection registry or contains
    /// an interior NUL byte — otherwise the resulting builder would be inert
    /// (every subsequent `setter` silently failing to resolve its DP). Use
    /// [`Style::new`] + [`set_target_type`](Self::set_target_type) for the
    /// fallible form.
    pub fn builder(target_type: &str) -> StyleBuilder {
        let mut style = Style::new();
        assert!(
            style.set_target_type(target_type),
            "Style::builder: unknown target type {target_type:?}"
        );
        StyleBuilder { style }
    }
}

/// Fluent builder for a [`Style`]: set its target type via
/// [`Style::builder`], append setters / triggers and an optional based-on style,
/// then [`build`](Self::build). The longhand
/// [`Style::new`] + [`set_target_type`](Style::set_target_type) +
/// [`add_setter`](Style::add_setter) form still works.
///
/// ```no_run
/// # use noesis_runtime::styles::Style;
/// # use noesis_runtime::binding::box_f64;
/// let style = Style::builder("TextBlock")
///     .setter("FontSize", &box_f64(24.0))
///     .build();
/// ```
#[must_use]
pub struct StyleBuilder {
    style: Style,
}

impl StyleBuilder {
    /// Append a `Setter` for the dependency property `dp_name` (resolved on the
    /// target type) with the boxed `value`. Like [`Style::add_setter`], a setter
    /// that fails to resolve is silently dropped.
    pub fn setter(mut self, dp_name: &str, value: &Boxed) -> Self {
        let _ = self.style.add_setter(dp_name, value);
        self
    }

    /// Set the `BasedOn` style this style inherits from.
    pub fn based_on(mut self, base: &Style) -> Self {
        self.style.set_based_on(base);
        self
    }

    /// Append a trigger to the style's `Triggers` collection.
    pub fn trigger<T: TriggerHandle>(mut self, trigger: &T) -> Self {
        let _ = self.style.add_trigger(trigger);
        self
    }

    /// Finish and return the built [`Style`].
    #[must_use]
    pub fn build(self) -> Style {
        self.style
    }
}

impl Drop for Style {
    fn drop(&mut self) {
        // SAFETY: produced with a +1 ref (create / from_owned).
        unsafe { noesis_style_destroy(self.ptr.as_ptr()) }
    }
}

/// A parsed `Noesis::ControlTemplate`. Owns a `+1` reference released on drop.
///
/// Assign it with
/// [`FrameworkElement::set_control_template`](crate::view::FrameworkElement::set_control_template)
/// (which targets `Control::SetTemplate`); Noesis takes its own reference, so
/// the handle may be dropped afterwards. After the templated control has been
/// laid out, name its parts with [`find_name`](Self::find_name) or via
/// [`FrameworkElement::template_child`](crate::view::FrameworkElement::template_child).
pub struct ControlTemplate {
    ptr: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for ControlTemplate {}

impl ControlTemplate {
    /// Parse a bare `<ControlTemplate>` from an in-memory XAML string. Returns
    /// `None` when the XAML is malformed or its root is not a `ControlTemplate`.
    ///
    /// # Panics
    ///
    /// Panics if `xaml` contains an interior NUL byte.
    #[must_use]
    pub fn parse(xaml: &str) -> Option<Self> {
        let c = CString::new(xaml).expect("xaml contained interior NUL");
        // SAFETY: c lives for the call; the result is a +1-owned ControlTemplate.
        let ptr = unsafe { noesis_control_template_parse(c.as_ptr()) };
        NonNull::new(ptr).map(|ptr| Self { ptr })
    }

    /// Wrap an already-owned (`+1`) `Noesis::ControlTemplate*`.
    ///
    /// # Safety
    ///
    /// `ptr` must be a live `Noesis::ControlTemplate*` carrying a reference this
    /// wrapper takes ownership of.
    #[must_use]
    pub(crate) unsafe fn from_owned(ptr: NonNull<c_void>) -> Self {
        Self { ptr }
    }

    /// Raw `Noesis::ControlTemplate*` (a `BaseComponent*`). Borrowed for the
    /// lifetime of `self`.
    #[must_use]
    pub fn raw(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }

    /// Find a named element inside this template as applied to
    /// `templated_parent` (`FrameworkTemplate::FindName`). Borrowed (no `+1`);
    /// valid only while the template stays applied to that parent. Returns
    /// `None` if the name isn't found (e.g. the template hasn't been applied /
    /// laid out yet).
    ///
    /// # Panics
    ///
    /// Panics if `name` contains an interior NUL byte.
    #[must_use]
    pub fn find_name(
        &self,
        name: &str,
        templated_parent: &FrameworkElement,
    ) -> Option<NonNull<c_void>> {
        let c = CString::new(name).expect("name contained interior NUL");
        // SAFETY: self.ptr live; c lives for the call; templated_parent.raw() is
        // a live FrameworkElement*. The returned pointer is borrowed.
        let p = unsafe {
            noesis_framework_template_find_name(
                self.ptr.as_ptr(),
                c.as_ptr(),
                templated_parent.raw(),
            )
        };
        NonNull::new(p)
    }
}

impl Drop for ControlTemplate {
    fn drop(&mut self) {
        // SAFETY: produced with a +1 ref (parse / from_owned).
        unsafe { noesis_base_component_release(self.ptr.as_ptr()) }
    }
}

/// A parsed `Noesis::DataTemplate`. Owns a `+1` reference released on drop.
///
/// Assign it through the existing component-DP path, e.g.
/// `element.set_component("ContentTemplate", template.raw())` on a
/// `ContentControl`, or `"ItemTemplate"` on an `ItemsControl`, which makes
/// Noesis take its own reference.
pub struct DataTemplate {
    ptr: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for DataTemplate {}

impl DataTemplate {
    /// Parse a bare `<DataTemplate>` from an in-memory XAML string. Returns
    /// `None` when the XAML is malformed or its root is not a `DataTemplate`.
    ///
    /// # Panics
    ///
    /// Panics if `xaml` contains an interior NUL byte.
    #[must_use]
    pub fn parse(xaml: &str) -> Option<Self> {
        let c = CString::new(xaml).expect("xaml contained interior NUL");
        // SAFETY: c lives for the call; the result is a +1-owned DataTemplate.
        let ptr = unsafe { noesis_data_template_parse(c.as_ptr()) };
        NonNull::new(ptr).map(|ptr| Self { ptr })
    }

    /// Raw `Noesis::DataTemplate*` (a `BaseComponent*`), for handing to
    /// [`FrameworkElement::set_component`](crate::view::FrameworkElement::set_component)
    /// on a template DP (`ContentTemplate` / `ItemTemplate`). Borrowed for the
    /// lifetime of `self`.
    #[must_use]
    pub fn raw(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }

    /// Find a named element inside this template as applied to
    /// `templated_parent` (`FrameworkTemplate::FindName`). Borrowed (no `+1`).
    /// Returns `None` if not found.
    ///
    /// # Panics
    ///
    /// Panics if `name` contains an interior NUL byte.
    #[must_use]
    pub fn find_name(
        &self,
        name: &str,
        templated_parent: &FrameworkElement,
    ) -> Option<NonNull<c_void>> {
        let c = CString::new(name).expect("name contained interior NUL");
        // SAFETY: self.ptr live; c lives for the call; templated_parent.raw() is
        // a live FrameworkElement*. The returned pointer is borrowed.
        let p = unsafe {
            noesis_framework_template_find_name(
                self.ptr.as_ptr(),
                c.as_ptr(),
                templated_parent.raw(),
            )
        };
        NonNull::new(p)
    }
}

impl Drop for DataTemplate {
    fn drop(&mut self) {
        // SAFETY: produced with a +1 ref (parse).
        unsafe { noesis_base_component_release(self.ptr.as_ptr()) }
    }
}

/// An owned (`+1`) boxed value handed back from a trigger / condition getter.
/// Released on drop. The `as_*` accessors unbox the common primitive payloads
/// (`bool`, `i32`, `String`).
pub struct OwnedValue {
    ptr: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for OwnedValue {}

impl OwnedValue {
    /// Raw `Noesis::BaseComponent*`. Borrowed for the lifetime of `self`.
    #[must_use]
    pub fn raw(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }

    /// Unbox a `bool` payload, or `None` if the value is not a boxed `bool`.
    #[must_use]
    pub fn as_bool(&self) -> Option<bool> {
        let mut out = false;
        // SAFETY: self.ptr is a live boxed BaseComponent*.
        let ok = unsafe { noesis_unbox_bool(self.ptr.as_ptr(), &mut out) };
        ok.then_some(out)
    }

    /// Unbox an `i32` payload, or `None` if the value is not a boxed `i32`.
    #[must_use]
    pub fn as_i32(&self) -> Option<i32> {
        let mut out = 0;
        // SAFETY: self.ptr is a live boxed BaseComponent*.
        let ok = unsafe { noesis_unbox_int32(self.ptr.as_ptr(), &mut out) };
        ok.then_some(out)
    }

    /// Copy a boxed `String` payload out as an owned `String`, or `None` if the
    /// value is not a boxed string.
    #[must_use]
    pub fn as_string(&self) -> Option<String> {
        // SAFETY: self.ptr is a live boxed BaseComponent*; the returned pointer
        // (if non-null) is valid while self is alive.
        let p = unsafe { noesis_unbox_string(self.ptr.as_ptr()) };
        if p.is_null() {
            return None;
        }
        // SAFETY: p is a NUL-terminated C string owned by the boxed value.
        Some(unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned())
    }
}

impl Drop for OwnedValue {
    fn drop(&mut self) {
        // SAFETY: produced with a +1 ref by a *_get_value getter.
        unsafe { noesis_base_component_release(self.ptr.as_ptr()) }
    }
}

/// Sealed marker for the four trigger wrappers, so [`Style::add_trigger`] can
/// take any of them by reference.
pub trait TriggerHandle: private::Sealed {
    /// Raw `Noesis::BaseTrigger*`. Borrowed for the lifetime of `self`.
    fn trigger_ptr(&self) -> *mut c_void;
}

mod private {
    pub trait Sealed {}
}

macro_rules! owned_trigger {
    ($name:ident, $create:ident, $doc:literal) => {
        #[doc = $doc]
        ///
        /// Owns a `+1` reference released on drop. Add it to a [`Style`] with
        /// [`Style::add_trigger`] (the `Triggers` collection takes its own
        /// reference) before the style is sealed.
        pub struct $name {
            ptr: NonNull<c_void>,
        }

        // SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
        unsafe impl Send for $name {}

        impl Default for $name {
            fn default() -> Self {
                Self::new()
            }
        }

        impl $name {
            /// Construct an empty trigger.
            ///
            /// # Panics
            ///
            /// Panics if the Noesis allocation fails (returns null).
            #[must_use]
            pub fn new() -> Self {
                // SAFETY: no preconditions beyond a live Noesis runtime.
                let ptr = unsafe { $create() };
                Self {
                    ptr: NonNull::new(ptr).expect(concat!(stringify!($create), " returned null")),
                }
            }

            /// Raw `Noesis::BaseTrigger*`. Borrowed for the lifetime of `self`.
            #[must_use]
            pub fn raw(&self) -> *mut c_void {
                self.ptr.as_ptr()
            }
        }

        impl Drop for $name {
            fn drop(&mut self) {
                // SAFETY: produced with a +1 ref (create).
                unsafe { noesis_base_component_release(self.ptr.as_ptr()) }
            }
        }

        impl private::Sealed for $name {}
        impl TriggerHandle for $name {
            fn trigger_ptr(&self) -> *mut c_void {
                self.ptr.as_ptr()
            }
        }
    };
}

owned_trigger!(
    Trigger,
    noesis_templates_trigger_create,
    "A property `Trigger`: applies its setters while a dependency property on the\ntargeted element equals the trigger `Value` (`Noesis::Trigger`)."
);
owned_trigger!(
    DataTrigger,
    noesis_templates_data_trigger_create,
    "A `DataTrigger`: applies its setters while a bound value equals the trigger\n`Value` (`Noesis::DataTrigger`)."
);
owned_trigger!(
    MultiTrigger,
    noesis_templates_multi_trigger_create,
    "A `MultiTrigger`: applies its setters while **all** of its property\nconditions are met (`Noesis::MultiTrigger`)."
);
owned_trigger!(
    MultiDataTrigger,
    noesis_templates_multi_data_trigger_create,
    "A `MultiDataTrigger`: applies its setters while **all** of its\nbinding-value conditions are met (`Noesis::MultiDataTrigger`). The\nbinding-condition sibling of [`MultiTrigger`]."
);
owned_trigger!(
    EventTrigger,
    noesis_templates_event_trigger_create,
    "An `EventTrigger`: runs its actions in response to a routed event\n(`Noesis::EventTrigger`)."
);

impl Trigger {
    /// Set the `Property` this trigger watches, resolved by `dp_name` on the
    /// reflection-registered `type_name` (e.g. `("ToggleButton", "IsChecked")`).
    /// Returns `false` if the type or DP name is unknown, or either string has
    /// an interior NUL.
    #[must_use = "a false return means the property was not set (unknown name / type mismatch / read-only)"]
    pub fn set_property(&mut self, type_name: &str, dp_name: &str) -> bool {
        let (Ok(t), Ok(d)) = (CString::new(type_name), CString::new(dp_name)) else {
            return false;
        };
        // SAFETY: self.ptr live; the CStrings live for the call.
        unsafe { noesis_templates_trigger_set_property(self.ptr.as_ptr(), t.as_ptr(), d.as_ptr()) }
    }

    /// Name of the trigger's `Property`, read back from the live object, or
    /// `None` if unset.
    #[must_use]
    pub fn property_name(&self) -> Option<String> {
        read_name(unsafe { noesis_templates_trigger_get_property_name(self.ptr.as_ptr()) })
    }

    /// Set the `Value` the property is compared against (Noesis stores its own
    /// reference to the boxed value).
    #[must_use = "a false return means the property was not set (unknown name / type mismatch / read-only)"]
    pub fn set_value(&mut self, value: &Boxed) -> bool {
        // SAFETY: self.ptr live; value.raw() is a live boxed BaseComponent*.
        unsafe { noesis_templates_trigger_set_value(self.ptr.as_ptr(), value.raw()) }
    }

    /// The trigger's `Value`, `AddRef`'d back out of the live object.
    #[must_use]
    pub fn value(&self) -> Option<OwnedValue> {
        owned_value(unsafe { noesis_templates_trigger_get_value(self.ptr.as_ptr()) })
    }

    /// Append a setter (`dp_name` resolved on `type_name`) applied while the
    /// trigger is active. Returns `false` on an unresolvable DP or null value.
    pub fn add_setter(&mut self, type_name: &str, dp_name: &str, value: &Boxed) -> bool {
        let (Ok(t), Ok(d)) = (CString::new(type_name), CString::new(dp_name)) else {
            return false;
        };
        // SAFETY: self.ptr live; CStrings + value live for the call.
        unsafe {
            noesis_templates_trigger_add_setter(
                self.ptr.as_ptr(),
                t.as_ptr(),
                d.as_ptr(),
                value.raw(),
            )
        }
    }

    /// Number of setters attached to this trigger.
    #[must_use]
    pub fn setter_count(&self) -> u32 {
        count(unsafe { noesis_templates_trigger_setter_count(self.ptr.as_ptr()) })
    }
}

impl DataTrigger {
    /// Set the `Binding` whose produced value is compared against the trigger
    /// `Value`. Noesis stores its own reference. Returns `false` only on invalid
    /// handles.
    #[must_use = "a false return means the property was not set (unknown name / type mismatch / read-only)"]
    pub fn set_binding(&mut self, binding: &Binding) -> bool {
        // SAFETY: self.ptr live; binding.raw() is a live BaseBinding*.
        unsafe { noesis_templates_data_trigger_set_binding(self.ptr.as_ptr(), binding.raw()) }
    }

    /// Whether a `Binding` is set, observed by reading it back from the live
    /// object (`AddRef`'d and immediately released).
    #[must_use]
    pub fn has_binding(&self) -> bool {
        // SAFETY: self.ptr live; the +1 result is released here if present.
        let p = unsafe { noesis_templates_data_trigger_get_binding(self.ptr.as_ptr()) };
        if p.is_null() {
            false
        } else {
            // SAFETY: p is a +1-owned handout we own and must release.
            unsafe { noesis_base_component_release(p) };
            true
        }
    }

    /// Set the `Value` the bound value is compared against.
    #[must_use = "a false return means the property was not set (unknown name / type mismatch / read-only)"]
    pub fn set_value(&mut self, value: &Boxed) -> bool {
        // SAFETY: self.ptr live; value.raw() is a live boxed BaseComponent*.
        unsafe { noesis_templates_data_trigger_set_value(self.ptr.as_ptr(), value.raw()) }
    }

    /// The trigger's `Value`, `AddRef`'d back out of the live object.
    #[must_use]
    pub fn value(&self) -> Option<OwnedValue> {
        owned_value(unsafe { noesis_templates_data_trigger_get_value(self.ptr.as_ptr()) })
    }

    /// Append a setter (`dp_name` resolved on `type_name`).
    pub fn add_setter(&mut self, type_name: &str, dp_name: &str, value: &Boxed) -> bool {
        let (Ok(t), Ok(d)) = (CString::new(type_name), CString::new(dp_name)) else {
            return false;
        };
        // SAFETY: self.ptr live; CStrings + value live for the call.
        unsafe {
            noesis_templates_data_trigger_add_setter(
                self.ptr.as_ptr(),
                t.as_ptr(),
                d.as_ptr(),
                value.raw(),
            )
        }
    }

    /// Number of setters attached to this trigger.
    #[must_use]
    pub fn setter_count(&self) -> u32 {
        count(unsafe { noesis_templates_data_trigger_setter_count(self.ptr.as_ptr()) })
    }
}

impl MultiTrigger {
    /// Append a `Condition{ Property=dp_name@type_name, Value }`. The trigger
    /// activates only when every condition is met. Returns `false` on an
    /// unresolvable DP or null value.
    pub fn add_condition(&mut self, type_name: &str, dp_name: &str, value: &Boxed) -> bool {
        let (Ok(t), Ok(d)) = (CString::new(type_name), CString::new(dp_name)) else {
            return false;
        };
        // SAFETY: self.ptr live; CStrings + value live for the call.
        unsafe {
            noesis_templates_multi_trigger_add_condition(
                self.ptr.as_ptr(),
                t.as_ptr(),
                d.as_ptr(),
                value.raw(),
            )
        }
    }

    /// Number of conditions.
    #[must_use]
    pub fn condition_count(&self) -> u32 {
        count(unsafe { noesis_templates_multi_trigger_condition_count(self.ptr.as_ptr()) })
    }

    /// Property name of the condition at `index`, read back from the live
    /// object.
    #[must_use]
    pub fn condition_property_name(&self, index: u32) -> Option<String> {
        read_name(unsafe {
            noesis_templates_multi_trigger_get_condition_property_name(self.ptr.as_ptr(), index)
        })
    }

    /// `Value` of the condition at `index`, `AddRef`'d back out of the live
    /// object.
    #[must_use]
    pub fn condition_value(&self, index: u32) -> Option<OwnedValue> {
        owned_value(unsafe {
            noesis_templates_multi_trigger_get_condition_value(self.ptr.as_ptr(), index)
        })
    }

    /// Append a setter (`dp_name` resolved on `type_name`).
    pub fn add_setter(&mut self, type_name: &str, dp_name: &str, value: &Boxed) -> bool {
        let (Ok(t), Ok(d)) = (CString::new(type_name), CString::new(dp_name)) else {
            return false;
        };
        // SAFETY: self.ptr live; CStrings + value live for the call.
        unsafe {
            noesis_templates_multi_trigger_add_setter(
                self.ptr.as_ptr(),
                t.as_ptr(),
                d.as_ptr(),
                value.raw(),
            )
        }
    }

    /// Number of setters.
    #[must_use]
    pub fn setter_count(&self) -> u32 {
        count(unsafe { noesis_templates_multi_trigger_setter_count(self.ptr.as_ptr()) })
    }
}

impl MultiDataTrigger {
    /// Append a `Condition{ Binding, Value }`. Each condition matches the value
    /// produced by `binding` (against bound data, e.g. the `DataContext`)
    /// against `value`; the trigger activates only when **every** condition is
    /// met. Noesis stores its own references to the binding and value. Returns
    /// `false` only on invalid handles.
    pub fn add_condition(&mut self, binding: &Binding, value: &Boxed) -> bool {
        // SAFETY: self.ptr live; binding.raw() is a live BaseBinding*; value.raw()
        // a live boxed BaseComponent*, both for the call.
        unsafe {
            noesis_templates_multi_data_trigger_add_condition(
                self.ptr.as_ptr(),
                binding.raw(),
                value.raw(),
            )
        }
    }

    /// Number of conditions.
    #[must_use]
    pub fn condition_count(&self) -> u32 {
        count(unsafe { noesis_templates_multi_data_trigger_condition_count(self.ptr.as_ptr()) })
    }

    /// Whether the condition at `index` has a `Binding` set, observed by reading
    /// it back from the live object. `false` if `index` is out of range or no
    /// binding is set.
    #[must_use]
    pub fn condition_has_binding(&self, index: u32) -> bool {
        // SAFETY: self.ptr live; returns -1 / 0 / 1.
        let has = unsafe {
            noesis_templates_multi_data_trigger_condition_has_binding(self.ptr.as_ptr(), index)
        };
        has == 1
    }

    /// `Value` of the condition at `index`, `AddRef`'d back out of the live
    /// object.
    #[must_use]
    pub fn condition_value(&self, index: u32) -> Option<OwnedValue> {
        owned_value(unsafe {
            noesis_templates_multi_data_trigger_get_condition_value(self.ptr.as_ptr(), index)
        })
    }

    /// Append a setter (`dp_name` resolved on `type_name`) applied while all
    /// conditions are met.
    pub fn add_setter(&mut self, type_name: &str, dp_name: &str, value: &Boxed) -> bool {
        let (Ok(t), Ok(d)) = (CString::new(type_name), CString::new(dp_name)) else {
            return false;
        };
        // SAFETY: self.ptr live; CStrings + value live for the call.
        unsafe {
            noesis_templates_multi_data_trigger_add_setter(
                self.ptr.as_ptr(),
                t.as_ptr(),
                d.as_ptr(),
                value.raw(),
            )
        }
    }

    /// Number of setters.
    #[must_use]
    pub fn setter_count(&self) -> u32 {
        count(unsafe { noesis_templates_multi_data_trigger_setter_count(self.ptr.as_ptr()) })
    }
}

impl EventTrigger {
    /// Set the `RoutedEvent` that fires this trigger, resolved by `event_name`
    /// registered on `owner_type` (e.g. `("Button", "Click")`). Returns `false`
    /// if the type or event name is unknown.
    #[must_use = "a false return means the property was not set (unknown name / type mismatch / read-only)"]
    pub fn set_routed_event(&mut self, owner_type: &str, event_name: &str) -> bool {
        let (Ok(o), Ok(e)) = (CString::new(owner_type), CString::new(event_name)) else {
            return false;
        };
        // SAFETY: self.ptr live; CStrings live for the call.
        unsafe {
            noesis_templates_event_trigger_set_routed_event(
                self.ptr.as_ptr(),
                o.as_ptr(),
                e.as_ptr(),
            )
        }
    }

    /// Name of the trigger's `RoutedEvent`, read back from the live object.
    #[must_use]
    pub fn routed_event_name(&self) -> Option<String> {
        read_name(unsafe {
            noesis_templates_event_trigger_get_routed_event_name(self.ptr.as_ptr())
        })
    }

    /// Set the `SourceName` (the named element whose event activates this
    /// trigger).
    #[must_use = "a false return means the property was not set (unknown name / type mismatch / read-only)"]
    pub fn set_source_name(&mut self, name: &str) -> bool {
        let Ok(n) = CString::new(name) else {
            return false;
        };
        // SAFETY: self.ptr live; n lives for the call.
        unsafe { noesis_templates_event_trigger_set_source_name(self.ptr.as_ptr(), n.as_ptr()) }
    }

    /// The trigger's `SourceName`, read back from the live object, or `None` if
    /// unset (an empty name reads back as `None`).
    #[must_use]
    pub fn source_name(&self) -> Option<String> {
        read_name(unsafe { noesis_templates_event_trigger_get_source_name(self.ptr.as_ptr()) })
            .filter(|s| !s.is_empty())
    }

    /// Number of `TriggerAction` objects in the trigger's `Actions` collection.
    #[must_use]
    pub fn action_count(&self) -> u32 {
        count(unsafe { noesis_templates_event_trigger_action_count(self.ptr.as_ptr()) })
    }

    /// Append a [`BeginStoryboard`] action to this trigger's `Actions`
    /// collection (the collection takes its own reference, so the action handle
    /// may be dropped afterwards). When the trigger's `RoutedEvent` fires, each
    /// action is invoked: a `BeginStoryboard` starts its [`Storyboard`]. Read
    /// the count back with [`action_count`](Self::action_count). Returns `false`
    /// only on invalid handles.
    ///
    /// [`Storyboard`]: crate::animation::Storyboard
    pub fn add_action(&mut self, action: &BeginStoryboard) -> bool {
        // SAFETY: self.ptr live; action.raw() is a live TriggerAction*
        // (BeginStoryboard*); Noesis AddRefs it into the Actions collection.
        unsafe { noesis_templates_event_trigger_add_action(self.ptr.as_ptr(), action.raw()) }
    }
}

/// A trigger `AddRef`'d back out of a [`Style`]'s `Triggers` collection by
/// [`Style::get_trigger`]. Its accessors re-read the *live* Noesis object. Each
/// accessor targets one concrete trigger kind (via a `DynamicCast` on the C
/// side) and returns `None` / `0` if this handle is a different kind.
pub struct TriggerReadback {
    ptr: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for TriggerReadback {}

impl TriggerReadback {
    /// Raw `Noesis::BaseTrigger*`. Borrowed for the lifetime of `self`.
    #[must_use]
    pub fn raw(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }

    /// Property name (`Trigger` only).
    #[must_use]
    pub fn property_name(&self) -> Option<String> {
        read_name(unsafe { noesis_templates_trigger_get_property_name(self.ptr.as_ptr()) })
    }

    /// Compared `Value` (`Trigger` only).
    #[must_use]
    pub fn value(&self) -> Option<OwnedValue> {
        owned_value(unsafe { noesis_templates_trigger_get_value(self.ptr.as_ptr()) })
    }

    /// Setter count (`Trigger` only; use the kind-specific reads for others).
    #[must_use]
    pub fn setter_count(&self) -> u32 {
        count(unsafe { noesis_templates_trigger_setter_count(self.ptr.as_ptr()) })
    }

    /// Routed-event name (`EventTrigger` only).
    #[must_use]
    pub fn routed_event_name(&self) -> Option<String> {
        read_name(unsafe {
            noesis_templates_event_trigger_get_routed_event_name(self.ptr.as_ptr())
        })
    }

    /// Condition count (`MultiTrigger` only).
    #[must_use]
    pub fn condition_count(&self) -> u32 {
        count(unsafe { noesis_templates_multi_trigger_condition_count(self.ptr.as_ptr()) })
    }
}

impl Drop for TriggerReadback {
    fn drop(&mut self) {
        // SAFETY: produced with a +1 ref by get_trigger.
        unsafe { noesis_base_component_release(self.ptr.as_ptr()) }
    }
}

fn read_name(p: *const std::os::raw::c_char) -> Option<String> {
    if p.is_null() {
        return None;
    }
    // SAFETY: p is a NUL-terminated C string owned by Noesis, valid for the call.
    Some(unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned())
}

fn owned_value(p: *mut c_void) -> Option<OwnedValue> {
    NonNull::new(p).map(|ptr| OwnedValue { ptr })
}

fn count(n: i32) -> u32 {
    u32::try_from(n.max(0)).unwrap_or(0)
}

/// User logic for a [`TemplateSelector`]: choose a [`DataTemplate`] for a data
/// item. Return `None` to select no template.
pub trait SelectTemplate: Send + 'static {
    /// `item` is the borrowed boxed data object (`BaseComponent*`, may be null);
    /// `container` is the borrowed item container (`DependencyObject*`, may be
    /// null). Return the chosen template (its reference is **borrowed**; the
    /// selector keeps its candidate templates alive).
    ///
    /// Takes `&self` (re-entrant: selecting a template for an item that itself
    /// hosts items routed through the same selector re-enters this box; use
    /// interior mutability for handler state).
    fn select(&self, item: *mut c_void, container: *mut c_void) -> Option<*mut c_void>;
}

impl<F: Fn(*mut c_void, *mut c_void) -> Option<*mut c_void> + Send + 'static> SelectTemplate for F {
    fn select(&self, item: *mut c_void, container: *mut c_void) -> Option<*mut c_void> {
        self(item, container)
    }
}

/// A `Noesis::DataTemplateSelector` whose `SelectTemplate` dispatches into Rust.
/// Owns a `+1` reference released on drop; assign its [`raw`](Self::raw) pointer
/// to an `ItemsControl::ItemTemplateSelector` / `ContentControl` selector DP via
/// the component path, or drive it directly with [`select`](Self::select).
pub struct TemplateSelector {
    ptr: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for TemplateSelector {}

impl TemplateSelector {
    /// Build a selector backed by `handler`. The handler box is owned by the
    /// native object and dropped when its last reference is released.
    ///
    /// # Panics
    ///
    /// Panics if the Noesis allocation fails (returns null).
    #[must_use]
    pub fn new<H: SelectTemplate>(handler: H) -> Self {
        let boxed: Box<Box<dyn SelectTemplate>> = Box::new(Box::new(handler));
        let userdata = Box::into_raw(boxed).cast::<c_void>();
        const VTABLE: TemplateSelectorVTable = TemplateSelectorVTable {
            select: selector_select_trampoline,
        };
        // SAFETY: VTABLE is 'static; userdata is the leaked handler box, freed by
        // selector_free_trampoline when the native object is destroyed.
        let ptr = unsafe {
            noesis_templates_selector_create(&VTABLE, userdata, selector_free_trampoline)
        };
        match NonNull::new(ptr) {
            Some(ptr) => Self { ptr },
            None => {
                // Reclaim the leaked box so a (single) failed create doesn't leak.
                // SAFETY: userdata is the box we just leaked and ownership wasn't taken.
                drop(unsafe { Box::from_raw(userdata.cast::<Box<dyn SelectTemplate>>()) });
                panic!("noesis_templates_selector_create returned null");
            }
        }
    }

    /// Raw `Noesis::DataTemplateSelector*` (a `BaseComponent*`). Borrowed for the
    /// lifetime of `self`.
    #[must_use]
    pub fn raw(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }

    /// Drive `SelectTemplate(item, container)` through the C++ virtual, returning
    /// the borrowed `DataTemplate*` the handler chose (or `None`).
    ///
    /// # Safety
    ///
    /// `item` and `container` are passed straight to Noesis: each must be either
    /// null or a live `BaseComponent*` / `DependencyObject*` that outlives the
    /// call.
    #[must_use]
    pub unsafe fn select(
        &self,
        item: *mut c_void,
        container: *mut c_void,
    ) -> Option<NonNull<c_void>> {
        // SAFETY: self.ptr is a live selector; item/container per # Safety.
        let p = unsafe { noesis_templates_selector_select(self.ptr.as_ptr(), item, container) };
        NonNull::new(p)
    }
}

impl Drop for TemplateSelector {
    fn drop(&mut self) {
        // SAFETY: produced with a +1 ref (create); destroy releases it and, on
        // the final release, runs selector_free_trampoline to drop the handler.
        unsafe { noesis_templates_selector_destroy(self.ptr.as_ptr()) }
    }
}

unsafe extern "C" fn selector_select_trampoline(
    userdata: *mut c_void,
    item: *mut c_void,
    container: *mut c_void,
) -> *mut c_void {
    crate::panic_guard::guard_or(core::ptr::null_mut(), || {
        if userdata.is_null() {
            return core::ptr::null_mut();
        }
        // SAFETY: userdata is the Box<Box<dyn SelectTemplate>> leaked in `new`, alive
        // until selector_free_trampoline runs. Shared `&`: re-entrant handler box
        // (see `SelectTemplate::select`).
        let handler = unsafe { &*userdata.cast::<Box<dyn SelectTemplate>>() };
        handler
            .select(item, container)
            .unwrap_or(core::ptr::null_mut())
    })
}

unsafe extern "C" fn selector_free_trampoline(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        if userdata.is_null() {
            return;
        }
        // SAFETY: called exactly once when the native object is destroyed; reclaims
        // the leaked handler box.
        drop(unsafe { Box::from_raw(userdata.cast::<Box<dyn SelectTemplate>>()) });
    })
}