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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
// Custom XAML class registration FFI.
//
// Architecture mirrors what Noesis's C# / Unity binding does for managed
// code: we cannot conjure C++ types from C-FFI, but we *can* synthesize
// a `TypeClassBuilder` per consumer-named class and register a Factory
// creator that returns a fresh instance of a per-base trampoline subclass
// whose `GetClassType()` reports the synthetic class.
//
// Components:
//   * RustContentControl / RustControl / RustFrameworkElement /
//     RustUserControl / RustPanel / RustDecorator: trampoline subclasses,
//     one per supported base type. Each derives from its Noesis base AND the
//     plain `RustClassInstance` interface; holds a back-pointer to its owning
//     ClassData; overrides GetClassType() / OnPropertyChanged() (report the
//     synthetic TypeClass + forward DP changes) and MeasureOverride /
//     ArrangeOverride (forward to the Rust layout vtable when one is
//     installed, else fall back to the base layout). All six are generated by
//     the `RUST_TRAMPOLINE` macro so adding a base is a one-line change.
//   * RustClassInstance: non-BaseComponent interface mixed into every
//     trampoline so the FFI boundary can recover ClassData / the
//     DependencyObject / the privileged read-only setter from a canonical
//     BaseComponent* WITHOUT a `static_cast` to a single concrete type (which
//     would be wrong now that several bases exist). A canonical-pointer ->
//     interface map (`g_instance_map`) bridges the multiple-inheritance
//     pointer adjustment.
//   * ClassData. Per-registered-class state: synthetic TypeClassBuilder,
//     UIElementData metadata, dense list of registered DPs (with their FFI
//     value-type tags + read-only flag), the property-change callback, an
//     optional coerce callback, and an optional layout vtable.
//   * g_class_registry: Symbol → ClassData* lookup so the Factory creator
//     (which only receives a Symbol) can recover the right ClassData.

#include "noesis_shim.h"

#include <NsCore/Noesis.h>
#include <NsCore/Boxing.h>
#include <NsCore/DynamicCast.h>
#include <NsCore/Factory.h>
#include <NsCore/HashMap.h>
#include <NsCore/Ptr.h>
#include <NsCore/Reflection.h>
#include <NsCore/ReflectionImplement.h>
#include <NsCore/String.h>
#include <NsCore/Symbol.h>
#include <NsCore/TypeClass.h>
#include <NsCore/TypeClassBuilder.h>
#include <NsCore/TypeEnum.h>
#include <NsCore/TypeOf.h>
#include <NsDrawing/Color.h>
#include <NsDrawing/Point.h>
#include <NsDrawing/Rect.h>
#include <NsDrawing/Size.h>
#include <NsDrawing/Thickness.h>
#include <NsMath/Vector.h>
#include <NsGui/ContentControl.h>
#include <NsGui/Control.h>
#include <NsGui/Decorator.h>
#include <NsGui/DependencyData.h>
#include <NsGui/DependencyObject.h>
#include <NsGui/DrawingContext.h>
#include <NsGui/DependencyProperty.h>
#include <NsGui/Freezable.h>
#include <NsGui/FrameworkElement.h>
#include <NsGui/FrameworkPropertyMetadata.h>
#include <NsGui/ImageSource.h>
#include <NsGui/Panel.h>
#include <NsGui/PropertyMetadata.h>
#include <NsGui/UIElement.h>
#include <NsGui/UIElementData.h>
#include <NsGui/UserControl.h>

#include <array>
#include <atomic>
#include <cstring>
#include <mutex>
#include <unordered_map>
#include <utility>
#include <vector>

namespace {

struct PropEntry {
    const Noesis::DependencyProperty* dp;
    noesis_prop_type type;
    bool read_only;
};

// Intrusively refcounted per-registered-class state.
//
// Lifetime model:
//
//   * `ref_count` starts at 1. That's the Rust caller's reference, held by
//     the `ClassRegistration` Rust struct.
//   * Each live instance (constructed by the Noesis Factory via
//     `class_creator` below) bumps the count via `RustClassInstance::
//     BindClassData`; the instance's destructor releases its share.
//   * `noesis_class_unregister` calls `Release()` on the Rust caller's
//     ref. When the count hits 0, every donated Rust box (property handler,
//     coerce handler, layout handler) is freed immediately via its free
//     trampoline; `ClassData` itself, `typeClass`, and `uiData` persist until
//     process exit. (The destructor chain from a still-live-during-Release
//     instance walks `typeClass` after `Release` returns; tearing it down
//     mid-chain UAFs in libNoesis. See `Release` and
//     `noesis_classes_force_free_at_shutdown`.)
//
// This guarantees that any property-change / coerce / layout callback fired
// during instance destruction sees live `userdata`.
struct ClassData {
    Noesis::String                      name;
    Noesis::Symbol                      sym;
    noesis_class_base                base;
    // TypeClassBuilder isn't a BaseComponent. It inherits TypeMeta and is
    // owned by Noesis's Reflection registry (Reflection::RegisterType +
    // Reflection::Unregister handle the lifecycle).
    Noesis::TypeClassBuilder*           typeClass;
    // DP metadata container attached to `typeClass`. For UIElement bases this is
    // a UIElementData (which IS-A DependencyData and also carries routed events);
    // for the Freezable base it is a plain DependencyData. DP registration only
    // needs DependencyData::InsertProperty, so we store the base type.
    Noesis::Ptr<Noesis::DependencyData>  uiData;
    std::vector<PropEntry>              properties;
    noesis_prop_changed_fn           cb;
    void*                               userdata;
    noesis_class_free_fn             free_handler;
    // Optional class-level coerce callback (opted-in per DP at register time).
    noesis_coerce_fn                 coerce_cb;
    void*                               coerce_userdata;
    noesis_class_free_fn             coerce_free;
    // Optional layout vtable (MeasureOverride / ArrangeOverride trampoline).
    bool                                has_layout;
    noesis_layout_vtable             layout;
    void*                               layout_userdata;
    noesis_layout_free_fn            layout_free;
    // Optional render callback (OnRender trampoline).
    noesis_render_fn                 render_cb;
    void*                               render_userdata;
    noesis_render_free_fn            render_free;
    std::atomic<int>                    ref_count;

    ClassData()
        : base(NOESIS_BASE_CONTENT_CONTROL)
        , typeClass(nullptr)
        , cb(nullptr)
        , userdata(nullptr)
        , free_handler(nullptr)
        , coerce_cb(nullptr)
        , coerce_userdata(nullptr)
        , coerce_free(nullptr)
        , has_layout(false)
        , layout{}
        , layout_userdata(nullptr)
        , layout_free(nullptr)
        , render_cb(nullptr)
        , render_userdata(nullptr)
        , render_free(nullptr)
        , ref_count(1) {}

    void AddRef() noexcept {
        ref_count.fetch_add(1, std::memory_order_relaxed);
    }

    // Free every donated Rust box exactly once. CAS each pointer to null so a
    // (currently-impossible but future-defensive) double free-at-zero can't
    // double-free a box.
    void FreeDonated() {
        void* ud = userdata;
        userdata = nullptr;
        if (free_handler && ud) free_handler(ud);

        void* cu = coerce_userdata;
        coerce_userdata = nullptr;
        if (coerce_free && cu) coerce_free(cu);

        void* lu = layout_userdata;
        layout_userdata = nullptr;
        if (layout_free && lu) layout_free(lu);

        void* ru = render_userdata;
        render_userdata = nullptr;
        if (render_free && ru) render_free(ru);
    }

    void Release() {
        // acq_rel on the decrement so the final store synchronizes with any
        // prior writes from other threads holding the last refs.
        if (ref_count.fetch_sub(1, std::memory_order_acq_rel) == 1) {
            std::atomic_thread_fence(std::memory_order_acquire);
            // Run the Rust handler-box drops ONLY. Do NOT delete typeClass,
            // uiData, or `this`. `~RustClassInstance` runs Release from inside
            // the C++ destructor chain, and the parent destructors that run
            // AFTER our body still walk `typeClass`. The Noesis-side state is
            // freed at process shutdown by
            // `noesis_classes_force_free_at_shutdown`. Bounded leak: one
            // ClassData per registered class.
            FreeDonated();
        }
    }
};

// Symbol-keyed registry. Symbols are 32-bit interned IDs so we can use a
// plain unordered_map keyed by their underlying integer.
std::mutex                                       g_registry_mutex;
std::unordered_map<uint32_t, ClassData*>         g_class_registry;

// Every successfully-registered ClassData, ever. `Release` doesn't erase
// from this list when refcount hits zero. Instead, the shutdown sweep
// walks the whole list and free's any box that's still set.
std::mutex                                       g_all_class_data_mutex;
std::vector<ClassData*>                          g_all_class_data;

void track_class_data(ClassData* cd) {
    std::lock_guard<std::mutex> lock(g_all_class_data_mutex);
    g_all_class_data.push_back(cd);
}

ClassData* registry_find(Noesis::Symbol sym) {
    std::lock_guard<std::mutex> lock(g_registry_mutex);
    auto it = g_class_registry.find((uint32_t)sym);
    return it == g_class_registry.end() ? nullptr : it->second;
}

bool registry_insert(Noesis::Symbol sym, ClassData* cd) {
    std::lock_guard<std::mutex> lock(g_registry_mutex);
    return g_class_registry.emplace((uint32_t)sym, cd).second;
}

void registry_erase(Noesis::Symbol sym) {
    std::lock_guard<std::mutex> lock(g_registry_mutex);
    g_class_registry.erase((uint32_t)sym);
}

// ── Instance map ────────────────────────────────────────────────────────────
//
// Maps a trampoline's canonical `BaseComponent*` (the address handed across
// the FFI, equal to the most-derived object address because the Noesis base
// is the FIRST base of every trampoline) to its `RustClassInstance*` interface
// subobject (which lives at a non-zero offset under multiple inheritance).
// This lets the FFI boundary recover ClassData / the DependencyObject / the
// read-only setter without knowing the concrete trampoline type.

struct RustClassInstance;

std::mutex                                       g_instance_mutex;
std::unordered_map<void*, RustClassInstance*>    g_instance_map;

void instance_map_insert(void* canonical, RustClassInstance* iface) {
    std::lock_guard<std::mutex> lock(g_instance_mutex);
    g_instance_map[canonical] = iface;
}

void instance_map_erase(void* canonical) {
    std::lock_guard<std::mutex> lock(g_instance_mutex);
    g_instance_map.erase(canonical);
}

RustClassInstance* instance_lookup(void* canonical) {
    std::lock_guard<std::mutex> lock(g_instance_mutex);
    auto it = g_instance_map.find(canonical);
    return it == g_instance_map.end() ? nullptr : it->second;
}

// ── RustClassInstance interface ─────────────────────────────────────────────
//
// Mixed into every trampoline as a SECOND base (after the Noesis base). Holds
// the ClassData back-pointer + the canonical / DependencyObject pointers so
// destruction and the FFI boundary never need the concrete type. The only
// per-base virtual is `RustSetReadOnly` (must run in concrete-class context to
// reach the protected `DependencyObject::SetReadOnlyProperty`).
struct RustClassInstance {
    virtual ~RustClassInstance() {
        if (mCanonical) {
            instance_map_erase(mCanonical);
            mCanonical = nullptr;
        }
        if (mClassData) {
            mClassData->Release();
            mClassData = nullptr;
        }
    }

    virtual void RustSetReadOnly(const Noesis::DependencyProperty* dp,
        noesis_prop_type type, const void* value_ptr) = 0;

    // Called exactly once per instance (from `make_trampoline`) before the
    // visual tree sees the object. `canonical` is the BaseComponent subobject
    // pointer; `dobj` the DependencyObject subobject pointer. The +1 ref taken
    // here is paired with the dtor's Release.
    void BindClassData(ClassData* cd, Noesis::BaseComponent* canonical,
                       Noesis::DependencyObject* dobj) {
        mClassData = cd;
        mCanonical = canonical;
        mDO = dobj;
        if (cd) cd->AddRef();
        if (canonical) instance_map_insert(canonical, this);
    }

    ClassData* GetClassData() const { return mClassData; }
    Noesis::DependencyObject* GetDO() const { return mDO; }
    void* GetCanonical() const { return mCanonical; }

protected:
    ClassData* mClassData = nullptr;
    Noesis::BaseComponent* mCanonical = nullptr;
    Noesis::DependencyObject* mDO = nullptr;
};

// ── Marshaling helpers ─────────────────────────────────────────────────────

void invoke_cb(ClassData* cd, void* instance, uint32_t idx,
               noesis_prop_type ty, const void* raw) {
    if (!cd->cb) return;

    switch (ty) {
        case NOESIS_PROP_INT32:
        case NOESIS_PROP_UINT32:
        case NOESIS_PROP_UINT64:
        case NOESIS_PROP_FLOAT:
        case NOESIS_PROP_DOUBLE:
        case NOESIS_PROP_BOOL:
        case NOESIS_PROP_THICKNESS:
        case NOESIS_PROP_COLOR:
        case NOESIS_PROP_RECT:
        case NOESIS_PROP_POINT:
        case NOESIS_PROP_SIZE:
        case NOESIS_PROP_VECTOR:
        case NOESIS_PROP_ENUM:
            // Pass through directly. `raw` already points to the typed value
            // (POINT/SIZE/VECTOR: float[2]; ENUM: int32; UINT64: uint64).
            cd->cb(cd->userdata, instance, idx, raw);
            return;

        case NOESIS_PROP_STRING: {
            // Noesis stores String values as Noesis::String (FixedString<24>);
            // expose as `const char*` to Rust via a borrowed pointer.
            const auto* s = static_cast<const Noesis::String*>(raw);
            const char* c = s ? s->Str() : nullptr;
            cd->cb(cd->userdata, instance, idx, &c);
            return;
        }

        case NOESIS_PROP_IMAGE_SOURCE:
        case NOESIS_PROP_BASE_COMPONENT: {
            // Noesis stores object values as Ptr<T>. The raw pointer is to a
            // Ptr<BaseComponent>. Unbox to a borrowed BaseComponent*.
            const auto* p = static_cast<const Noesis::Ptr<Noesis::BaseComponent>*>(raw);
            Noesis::BaseComponent* b = p ? p->GetPtr() : nullptr;
            cd->cb(cd->userdata, instance, idx, &b);
            return;
        }
    }
}

// Privileged read-only setter, dispatched per FFI tag. Runs in concrete-class
// context (templated on the trampoline type) so the protected
// `DependencyObject::SetReadOnlyProperty` (re-exposed as public via a `using`
// declaration in each trampoline) is reachable. Object / ImageSource tags are
// intentionally not supported (no boxed SetReadOnly form); they no-op.
template<class Obj>
void apply_set_readonly(Obj* obj, const Noesis::DependencyProperty* dp,
                        noesis_prop_type type, const void* value_ptr) {
    using namespace Noesis;
    switch (type) {
        case NOESIS_PROP_INT32:
            obj->template SetReadOnlyProperty<int32_t>(
                dp, value_ptr ? *static_cast<const int32_t*>(value_ptr) : 0);
            return;
        case NOESIS_PROP_UINT32:
            obj->template SetReadOnlyProperty<uint32_t>(
                dp, value_ptr ? *static_cast<const uint32_t*>(value_ptr) : 0);
            return;
        case NOESIS_PROP_UINT64:
            obj->template SetReadOnlyProperty<uint64_t>(
                dp, value_ptr ? *static_cast<const uint64_t*>(value_ptr) : 0);
            return;
        case NOESIS_PROP_FLOAT:
            obj->template SetReadOnlyProperty<float>(
                dp, value_ptr ? *static_cast<const float*>(value_ptr) : 0.0f);
            return;
        case NOESIS_PROP_DOUBLE:
            obj->template SetReadOnlyProperty<double>(
                dp, value_ptr ? *static_cast<const double*>(value_ptr) : 0.0);
            return;
        case NOESIS_PROP_BOOL:
            obj->template SetReadOnlyProperty<bool>(
                dp, value_ptr ? *static_cast<const bool*>(value_ptr) : false);
            return;
        case NOESIS_PROP_STRING: {
            const char* s = value_ptr ? *static_cast<const char* const*>(value_ptr) : nullptr;
            obj->template SetReadOnlyProperty<String>(dp, s ? s : "");
            return;
        }
        case NOESIS_PROP_THICKNESS: {
            Thickness t;
            if (value_ptr) {
                const auto* f = static_cast<const float*>(value_ptr);
                t = Thickness(f[0], f[1], f[2], f[3]);
            }
            obj->template SetReadOnlyProperty<Thickness>(dp, t);
            return;
        }
        case NOESIS_PROP_COLOR: {
            Color c;
            if (value_ptr) {
                const auto* f = static_cast<const float*>(value_ptr);
                c = Color(f[0], f[1], f[2], f[3]);
            }
            obj->template SetReadOnlyProperty<Color>(dp, c);
            return;
        }
        case NOESIS_PROP_RECT: {
            Rect r;
            if (value_ptr) {
                const auto* f = static_cast<const float*>(value_ptr);
                r = Rect(f[0], f[1], f[0] + f[2], f[1] + f[3]);
            }
            obj->template SetReadOnlyProperty<Rect>(dp, r);
            return;
        }
        case NOESIS_PROP_POINT: {
            Point p;
            if (value_ptr) {
                const auto* f = static_cast<const float*>(value_ptr);
                p = Point(f[0], f[1]);
            }
            obj->template SetReadOnlyProperty<Point>(dp, p);
            return;
        }
        case NOESIS_PROP_SIZE: {
            Size s;
            if (value_ptr) {
                const auto* f = static_cast<const float*>(value_ptr);
                s = Size(f[0], f[1]);
            }
            obj->template SetReadOnlyProperty<Size>(dp, s);
            return;
        }
        case NOESIS_PROP_VECTOR: {
            Vector2 v;
            if (value_ptr) {
                const auto* f = static_cast<const float*>(value_ptr);
                v = Vector2(f[0], f[1]);
            }
            obj->template SetReadOnlyProperty<Vector2>(dp, v);
            return;
        }
        case NOESIS_PROP_ENUM:
            // Enum storage is int32. The DP's reflected Type is the runtime enum.
            obj->template SetReadOnlyProperty<int32_t>(
                dp, value_ptr ? *static_cast<const int32_t*>(value_ptr) : 0);
            return;
        case NOESIS_PROP_IMAGE_SOURCE:
        case NOESIS_PROP_BASE_COMPONENT:
            // No boxed SetReadOnly form; unsupported.
            return;
    }
}

// Forward a DP change to the Rust callback. Shared by every trampoline.
void rust_forward_change(RustClassInstance* self,
                         const Noesis::DependencyPropertyChangedEventArgs& args) {
    ClassData* cd = self->GetClassData();
    if (!cd) return;
    for (uint32_t i = 0; i < cd->properties.size(); ++i) {
        const auto& pe = cd->properties[i];
        if (pe.dp == args.prop) {
            invoke_cb(cd, self->GetCanonical(), i, pe.type, args.newValue);
            return;
        }
    }
}

// Run the Rust measure / arrange handler when installed. Returns false (so the
// trampoline falls back to the base layout) when no handler is set.
bool rust_run_measure(RustClassInstance* self, const Noesis::Size& avail, Noesis::Size* out) {
    ClassData* cd = self->GetClassData();
    if (!cd || !cd->has_layout || !cd->layout.measure) return false;
    float w = 0.0f, h = 0.0f;
    cd->layout.measure(cd->layout_userdata, self->GetCanonical(),
                       avail.width, avail.height, &w, &h);
    *out = Noesis::Size(w, h);
    return true;
}

bool rust_run_arrange(RustClassInstance* self, const Noesis::Size& final_, Noesis::Size* out) {
    ClassData* cd = self->GetClassData();
    if (!cd || !cd->has_layout || !cd->layout.arrange) return false;
    float w = 0.0f, h = 0.0f;
    cd->layout.arrange(cd->layout_userdata, self->GetCanonical(),
                       final_.width, final_.height, &w, &h);
    *out = Noesis::Size(w, h);
    return true;
}

// Forward an OnRender to the Rust render callback when installed. The
// DrawingContext is handed out as an opaque borrowed BaseComponent*; the Rust
// side reaches DrawingContext methods through the noesis_drawing_* FFI.
void rust_run_render(RustClassInstance* self, Noesis::DrawingContext* dc) {
    ClassData* cd = self->GetClassData();
    if (!cd || !cd->render_cb) return;
    cd->render_cb(cd->render_userdata, self->GetCanonical(),
                  static_cast<Noesis::BaseComponent*>(dc));
}

// ── Trampoline subclasses ───────────────────────────────────────────────────
//
// Hand-rolled reflection: we cannot use NS_DECLARE_REFLECTION /
// NS_IMPLEMENT_REFLECTION because they generate a `GetClassType()` that always
// returns the static class type. We need a custom override so that instances
// created via the synthetic Factory creator report their per-name TypeClass
// instead. That's what makes XAML `Style TargetType="my:Foo"` / bindings
// work. The hand-rolled version reuses Noesis's own `TypeClassCreator::Create`
// / `Fill` template machinery so `TypeOf<>`, `RegisterType`, and
// `IsAssignableFrom` all behave normally.
//
// Every base derives (transitively) from FrameworkElement, so MeasureOverride
// / ArrangeOverride exist on all of them.

#define RUST_TRAMPOLINE(ClassName, NsBase, ReflName)                                       \
class ClassName final : public NsBase, public RustClassInstance {                              \
public:                                                                                        \
    ClassName() = default;                                                                     \
    /* Re-expose the protected read-only setter so apply_set_readonly reaches it. */           \
    using Noesis::DependencyObject::SetReadOnlyProperty;                                       \
    void RustSetReadOnly(const Noesis::DependencyProperty* dp,                                 \
        noesis_prop_type type, const void* value_ptr) override {                            \
        apply_set_readonly(this, dp, type, value_ptr);                                         \
    }                                                                                          \
    static const Noesis::TypeClass* StaticGetClassType(Noesis::TypeTag<ClassName>*);           \
    const Noesis::TypeClass* GetClassType() const override {                                   \
        if (mClassData && mClassData->typeClass)                                               \
            return static_cast<const Noesis::TypeClass*>(mClassData->typeClass);               \
        return StaticGetClassType((Noesis::TypeTag<ClassName>*)nullptr);                       \
    }                                                                                          \
protected:                                                                                     \
    bool OnPropertyChanged(const Noesis::DependencyPropertyChangedEventArgs& args) override {  \
        bool processed = NsBase::OnPropertyChanged(args);                                      \
        rust_forward_change(this, args);                                                       \
        return processed;                                                                      \
    }                                                                                          \
    Noesis::Size MeasureOverride(const Noesis::Size& availableSize) override {                 \
        Noesis::Size out;                                                                      \
        if (rust_run_measure(this, availableSize, &out)) return out;                           \
        return NsBase::MeasureOverride(availableSize);                                         \
    }                                                                                          \
    Noesis::Size ArrangeOverride(const Noesis::Size& finalSize) override {                     \
        Noesis::Size out;                                                                      \
        if (rust_run_arrange(this, finalSize, &out)) return out;                               \
        return NsBase::ArrangeOverride(finalSize);                                             \
    }                                                                                          \
    void OnRender(Noesis::DrawingContext* drawingContext) override {                            \
        NsBase::OnRender(drawingContext);                                                      \
        rust_run_render(this, drawingContext);                                                \
    }                                                                                          \
private:                                                                                       \
    typedef ClassName SelfClass;                                                               \
    typedef NsBase ParentClass;                                                                \
    friend class Noesis::TypeClassCreator;                                                     \
    static void StaticFillClassType(Noesis::TypeClassCreator&) {}                              \
};                                                                                             \
const Noesis::TypeClass* ClassName::StaticGetClassType(Noesis::TypeTag<ClassName>*) {           \
    static const Noesis::TypeClass* type;                                                      \
    if (NS_UNLIKELY(type == 0)) {                                                              \
        type = static_cast<const Noesis::TypeClass*>(Noesis::Reflection::RegisterType(         \
            ReflName, Noesis::TypeClassCreator::Create<ClassName>,                             \
            Noesis::TypeClassCreator::Fill<ClassName, NsBase>));                               \
    }                                                                                          \
    return type;                                                                               \
}

RUST_TRAMPOLINE(RustContentControl, Noesis::ContentControl, "DmNoesis.RustContentControl")
RUST_TRAMPOLINE(RustControl, Noesis::Control, "DmNoesis.RustControl")
RUST_TRAMPOLINE(RustFrameworkElement, Noesis::FrameworkElement, "DmNoesis.RustFrameworkElement")
RUST_TRAMPOLINE(RustUserControl, Noesis::UserControl, "DmNoesis.RustUserControl")
RUST_TRAMPOLINE(RustPanel, Noesis::Panel, "DmNoesis.RustPanel")
RUST_TRAMPOLINE(RustDecorator, Noesis::Decorator, "DmNoesis.RustDecorator")

#undef RUST_TRAMPOLINE

// Forward decl: the Freezable trampoline's CreateInstanceCore clones via the
// same factory path used for fresh instances.
Noesis::BaseComponent* make_trampoline(ClassData* cd);

// Freezable trampoline. A Freezable is NOT a UIElement, so there is no
// Measure/Arrange/Render/routed-event surface: only DP change forwarding plus
// the one pure virtual a Freezable subclass must supply (CreateInstanceCore).
// This proves the synthetic-TypeClass reflection machinery extends to the
// DependencyObject side of the hierarchy beyond UIElement. The other Animatable
// subtrees (Brush/Geometry/Transform/Effect) add IRenderProxyCreator's three
// pure render-tree virtuals and are NOT subclassable this way (see LIMITATIONS.md).
class RustFreezable final : public Noesis::Freezable, public RustClassInstance {
public:
    RustFreezable() = default;
    using Noesis::DependencyObject::SetReadOnlyProperty;
    void RustSetReadOnly(const Noesis::DependencyProperty* dp,
        noesis_prop_type type, const void* value_ptr) override {
        apply_set_readonly(this, dp, type, value_ptr);
    }
    static const Noesis::TypeClass* StaticGetClassType(Noesis::TypeTag<RustFreezable>*);
    const Noesis::TypeClass* GetClassType() const override {
        if (mClassData && mClassData->typeClass)
            return static_cast<const Noesis::TypeClass*>(mClassData->typeClass);
        return StaticGetClassType((Noesis::TypeTag<RustFreezable>*)nullptr);
    }

protected:
    bool OnPropertyChanged(const Noesis::DependencyPropertyChangedEventArgs& args) override {
        bool processed = Freezable::OnPropertyChanged(args);
        rust_forward_change(this, args);
        return processed;
    }
    // Required pure virtual: produce a fresh instance of the same dynamic type,
    // bound to the same ClassData (used by Clone / GetAsFrozen).
    Noesis::Ptr<Noesis::Freezable> CreateInstanceCore() const override {
        if (mClassData) {
            Noesis::BaseComponent* bc = make_trampoline(mClassData);
            auto* fz = Noesis::DynamicCast<Noesis::Freezable*>(bc);
            // make_trampoline hands back a +1 (new starts at refcount 1); adopt
            // it rather than taking a second reference.
            if (fz) return Noesis::Ptr<Noesis::Freezable>(*fz);
        }
        return Noesis::Ptr<Noesis::Freezable>(*new RustFreezable());
    }

private:
    typedef RustFreezable SelfClass;
    typedef Noesis::Freezable ParentClass;
    friend class Noesis::TypeClassCreator;
    static void StaticFillClassType(Noesis::TypeClassCreator&) {}
};
const Noesis::TypeClass* RustFreezable::StaticGetClassType(Noesis::TypeTag<RustFreezable>*) {
    static const Noesis::TypeClass* type;
    if (NS_UNLIKELY(type == 0)) {
        type = static_cast<const Noesis::TypeClass*>(Noesis::Reflection::RegisterType(
            "DmNoesis.RustFreezable", Noesis::TypeClassCreator::Create<RustFreezable>,
            Noesis::TypeClassCreator::Fill<RustFreezable, Noesis::Freezable>));
    }
    return type;
}

// The reflected static base type for a given base enum (used as the synthetic
// TypeClass's parent so XAML / reflection resolve the hierarchy).
const Noesis::TypeClass* base_static_type(noesis_class_base base) {
    using namespace Noesis;
    switch (base) {
        case NOESIS_BASE_CONTENT_CONTROL:
            return RustContentControl::StaticGetClassType((TypeTag<RustContentControl>*)nullptr);
        case NOESIS_BASE_CONTROL:
            return RustControl::StaticGetClassType((TypeTag<RustControl>*)nullptr);
        case NOESIS_BASE_FRAMEWORK_ELEMENT:
            return RustFrameworkElement::StaticGetClassType((TypeTag<RustFrameworkElement>*)nullptr);
        case NOESIS_BASE_USER_CONTROL:
            return RustUserControl::StaticGetClassType((TypeTag<RustUserControl>*)nullptr);
        case NOESIS_BASE_PANEL:
            return RustPanel::StaticGetClassType((TypeTag<RustPanel>*)nullptr);
        case NOESIS_BASE_DECORATOR:
            return RustDecorator::StaticGetClassType((TypeTag<RustDecorator>*)nullptr);
        case NOESIS_BASE_FREEZABLE:
            return RustFreezable::StaticGetClassType((TypeTag<RustFreezable>*)nullptr);
    }
    return nullptr;
}

bool base_supported(noesis_class_base base) {
    switch (base) {
        case NOESIS_BASE_CONTENT_CONTROL:
        case NOESIS_BASE_CONTROL:
        case NOESIS_BASE_FRAMEWORK_ELEMENT:
        case NOESIS_BASE_USER_CONTROL:
        case NOESIS_BASE_PANEL:
        case NOESIS_BASE_DECORATOR:
        case NOESIS_BASE_FREEZABLE:
            return true;
    }
    return false;
}

// Whether `base` is a UIElement-derived base (gets UIElementData metadata +
// routed events) vs the non-UIElement Freezable base (plain DependencyData).
bool base_is_uielement(noesis_class_base base) {
    return base != NOESIS_BASE_FREEZABLE;
}

// Construct a trampoline for `cd`'s base, bind ClassData, and return the
// canonical BaseComponent*. `new` starts the BaseComponent at refcount 1, so
// the returned pointer already carries a +1 the caller owns (adopt it; do not
// AddRef again).
Noesis::BaseComponent* make_trampoline(ClassData* cd) {
    Noesis::BaseComponent* canonical = nullptr;
    Noesis::DependencyObject* dobj = nullptr;
    RustClassInstance* iface = nullptr;

    switch (cd->base) {
        case NOESIS_BASE_CONTENT_CONTROL: {
            auto* o = new RustContentControl(); canonical = o; dobj = o; iface = o; break;
        }
        case NOESIS_BASE_CONTROL: {
            auto* o = new RustControl(); canonical = o; dobj = o; iface = o; break;
        }
        case NOESIS_BASE_FRAMEWORK_ELEMENT: {
            auto* o = new RustFrameworkElement(); canonical = o; dobj = o; iface = o; break;
        }
        case NOESIS_BASE_USER_CONTROL: {
            auto* o = new RustUserControl(); canonical = o; dobj = o; iface = o; break;
        }
        case NOESIS_BASE_PANEL: {
            auto* o = new RustPanel(); canonical = o; dobj = o; iface = o; break;
        }
        case NOESIS_BASE_DECORATOR: {
            auto* o = new RustDecorator(); canonical = o; dobj = o; iface = o; break;
        }
        case NOESIS_BASE_FREEZABLE: {
            auto* o = new RustFreezable(); canonical = o; dobj = o; iface = o; break;
        }
        default:
            return nullptr;
    }

    iface->BindClassData(cd, canonical, dobj);
    return canonical;
}

// ── Factory creator ────────────────────────────────────────────────────────

Noesis::BaseComponent* class_creator(Noesis::Symbol name) {
    ClassData* cd = registry_find(name);
    if (!cd) return nullptr;
    return make_trampoline(cd);
}

// ── Coerce thunk pool ───────────────────────────────────────────────────────
//
// Noesis's CoerceValueCallback receives (d, baseValue, coercedValue) but no DP
// pointer, so a single free function can't tell which DP fired. We resolve
// this with a fixed pool of templated thunks, each hard-coding its property
// slot, assigned to the matching DP at register time. The slot equals the
// dense property index, capping coerced DPs at the first kCoerceSlots props.

constexpr uint32_t kCoerceSlots = 32;

size_t coercible_size(noesis_prop_type t) {
    switch (t) {
        case NOESIS_PROP_INT32:
        case NOESIS_PROP_UINT32:
        case NOESIS_PROP_FLOAT:
        case NOESIS_PROP_ENUM:
            return 4;
        case NOESIS_PROP_DOUBLE:
            return 8;
        case NOESIS_PROP_BOOL:
            return sizeof(bool);
        case NOESIS_PROP_POINT:
        case NOESIS_PROP_SIZE:
        case NOESIS_PROP_VECTOR:
            return sizeof(float) * 2;
        case NOESIS_PROP_THICKNESS:
        case NOESIS_PROP_COLOR:
        case NOESIS_PROP_RECT:
            return sizeof(float) * 4;
        default:
            return 0;  // string / object tags are not coercible
    }
}

bool rust_coerce_dispatch(const Noesis::DependencyObject* d, uint32_t slot,
                          const void* baseValue, void* coercedValue) {
    // Noesis hands us an *uninitialized* stack POD in `coercedValue` and, when
    // we return true, treats it as the effective value. Every path here must
    // therefore leave it written. Resolve the property's POD size from the slot
    // machinery and mirror `baseValue` into `coercedValue` up front so a
    // pass-through (unknown slot, no installed handler, or a no-op Rust coerce)
    // yields the unchanged value instead of stack garbage. A zero size means a
    // non-coercible tag (string / object), which Noesis default-constructs
    // rather than leaving uninitialized, so leaving it untouched is safe.
    RustClassInstance* iface =
        instance_lookup((void*)static_cast<const Noesis::BaseComponent*>(d));
    ClassData* cd = iface ? iface->GetClassData() : nullptr;
    size_t sz = (cd && slot < cd->properties.size())
                    ? coercible_size(cd->properties[slot].type)
                    : 0;

    if (sz != 0 && baseValue && coercedValue) {
        std::memcpy(coercedValue, baseValue, sz);
        if (cd->coerce_cb) {
            cd->coerce_cb(cd->coerce_userdata,
                          (void*)static_cast<const Noesis::BaseComponent*>(d),
                          slot, baseValue, coercedValue);
        }
    }
    return true;
}

template<uint32_t Slot>
bool coerce_thunk(const Noesis::DependencyObject* d, const void* baseValue, void* coercedValue) {
    return rust_coerce_dispatch(d, Slot, baseValue, coercedValue);
}

template<uint32_t... I>
std::array<Noesis::CoerceValueCallback, sizeof...(I)>
make_coerce_table(std::integer_sequence<uint32_t, I...>) {
    return { Noesis::CoerceValueCallback(&coerce_thunk<I>)... };
}

Noesis::CoerceValueCallback coerce_callback_for(uint32_t slot) {
    static const std::array<Noesis::CoerceValueCallback, kCoerceSlots> table =
        make_coerce_table(std::make_integer_sequence<uint32_t, kCoerceSlots>{});
    if (slot >= kCoerceSlots) return Noesis::CoerceValueCallback();
    return table[slot];
}

// ── DP metadata + creation ──────────────────────────────────────────────────

template<class T>
Noesis::Ptr<Noesis::PropertyMetadata> make_md(
    const T& def, uint32_t options, const Noesis::CoerceValueCallback& coerce) {
    using namespace Noesis;
    if (options != 0) {
        if (coerce) return FrameworkPropertyMetadata::Create<T>(def, options, coerce);
        return FrameworkPropertyMetadata::Create<T>(def, options);
    }
    if (coerce) return PropertyMetadata::Create<T>(def, coerce);
    return PropertyMetadata::Create<T>(def);
}

template<class T>
Noesis::Ptr<Noesis::PropertyMetadata> make_md_obj(const T& def, uint32_t options) {
    using namespace Noesis;
    if (options != 0) return FrameworkPropertyMetadata::Create<T>(def, options);
    return PropertyMetadata::Create<T>(def);
}

// Create a DependencyProperty for `type` with the requested metadata options,
// coerce callback, and access. `coerce` is only honored for coercible tags.
Noesis::Ptr<Noesis::DependencyProperty> create_dp_ex(
    const char* name,
    const Noesis::TypeClass* owner,
    noesis_prop_type type,
    const void* default_ptr,
    uint32_t options,
    const Noesis::CoerceValueCallback& coerce,
    bool read_only) {
    using namespace Noesis;
    PropertyAccess access = read_only ? PropertyAccess_ReadOnly : PropertyAccess_ReadWrite;
    switch (type) {
        case NOESIS_PROP_INT32: {
            int32_t def = default_ptr ? *static_cast<const int32_t*>(default_ptr) : 0;
            return DependencyProperty::Create<int32_t>(
                name, owner, make_md<int32_t>(def, options, coerce).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_UINT32: {
            uint32_t def = default_ptr ? *static_cast<const uint32_t*>(default_ptr) : 0;
            return DependencyProperty::Create<uint32_t>(
                name, owner, make_md<uint32_t>(def, options, coerce).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_UINT64: {
            uint64_t def = default_ptr ? *static_cast<const uint64_t*>(default_ptr) : 0;
            return DependencyProperty::Create<uint64_t>(
                name, owner, make_md<uint64_t>(def, options, coerce).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_FLOAT: {
            float def = default_ptr ? *static_cast<const float*>(default_ptr) : 0.0f;
            return DependencyProperty::Create<float>(
                name, owner, make_md<float>(def, options, coerce).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_DOUBLE: {
            double def = default_ptr ? *static_cast<const double*>(default_ptr) : 0.0;
            return DependencyProperty::Create<double>(
                name, owner, make_md<double>(def, options, coerce).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_BOOL: {
            bool def = default_ptr ? *static_cast<const bool*>(default_ptr) : false;
            return DependencyProperty::Create<bool>(
                name, owner, make_md<bool>(def, options, coerce).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_STRING: {
            const char* def = default_ptr ? *static_cast<const char* const*>(default_ptr) : nullptr;
            String s = def ? String(def) : String();
            return DependencyProperty::Create<String>(
                name, owner, make_md<String>(s, options, coerce).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_THICKNESS: {
            Thickness def;
            if (default_ptr) {
                const auto* f = static_cast<const float*>(default_ptr);
                def = Thickness(f[0], f[1], f[2], f[3]);
            }
            return DependencyProperty::Create<Thickness>(
                name, owner, make_md<Thickness>(def, options, coerce).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_COLOR: {
            Color def;
            if (default_ptr) {
                const auto* f = static_cast<const float*>(default_ptr);
                def = Color(f[0], f[1], f[2], f[3]);
            }
            return DependencyProperty::Create<Color>(
                name, owner, make_md<Color>(def, options, coerce).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_RECT: {
            Rect def;
            if (default_ptr) {
                const auto* f = static_cast<const float*>(default_ptr);
                def = Rect(f[0], f[1], f[0] + f[2], f[1] + f[3]);
            }
            return DependencyProperty::Create<Rect>(
                name, owner, make_md<Rect>(def, options, coerce).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_POINT: {
            Point def;
            if (default_ptr) {
                const auto* f = static_cast<const float*>(default_ptr);
                def = Point(f[0], f[1]);
            }
            return DependencyProperty::Create<Point>(
                name, owner, make_md<Point>(def, options, coerce).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_SIZE: {
            Size def;
            if (default_ptr) {
                const auto* f = static_cast<const float*>(default_ptr);
                def = Size(f[0], f[1]);
            }
            return DependencyProperty::Create<Size>(
                name, owner, make_md<Size>(def, options, coerce).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_VECTOR: {
            Vector2 def;
            if (default_ptr) {
                const auto* f = static_cast<const float*>(default_ptr);
                def = Vector2(f[0], f[1]);
            }
            return DependencyProperty::Create<Vector2>(
                name, owner, make_md<Vector2>(def, options, coerce).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_ENUM:
            // Enum DPs are created through noesis_class_register_enum_property
            // (they need the runtime TypeEnum*), not this value-only path.
            return nullptr;
        case NOESIS_PROP_IMAGE_SOURCE: {
            // Seed an explicit null Ptr<BaseComponent> default: a missing Box
            // source crashes the typed Init path during a real visual-tree
            // walk. Coercion is not supported for object tags.
            Ptr<BaseComponent> null_default;
            return DependencyProperty::Create<Ptr<BaseComponent>>(
                name, TypeOf<ImageSource>(), owner,
                make_md_obj<Ptr<BaseComponent>>(null_default, options).GetPtr(), nullptr, access);
        }
        case NOESIS_PROP_BASE_COMPONENT: {
            Ptr<BaseComponent> null_default;
            return DependencyProperty::Create<Ptr<BaseComponent>>(
                name, TypeOf<BaseComponent>(), owner,
                make_md_obj<Ptr<BaseComponent>>(null_default, options).GetPtr(), nullptr, access);
        }
    }
    return nullptr;
}

// Create an enum-typed DP: int32 storage, but the reflected Type is the runtime
// TypeEnum resolved from `enum_type_name`. Mirrors create_dp_ex's int32 path
// except for the explicit type argument. Returns null if the enum name does not
// resolve to a registered TypeEnum.
Noesis::Ptr<Noesis::DependencyProperty> create_enum_dp(
    const char* name,
    const Noesis::TypeClass* owner,
    const char* enum_type_name,
    int32_t default_value,
    uint32_t options,
    bool read_only) {
    using namespace Noesis;
    if (!enum_type_name) return nullptr;
    Symbol sym(enum_type_name, Symbol::NullIfNotFound());
    if (sym.IsNull()) return nullptr;
    const auto* enumType = DynamicCast<const TypeEnum*>(Reflection::GetType(sym));
    if (!enumType) return nullptr;

    PropertyAccess access = read_only ? PropertyAccess_ReadOnly : PropertyAccess_ReadWrite;
    auto md = make_md<int32_t>(default_value, options, CoerceValueCallback());
    return DependencyProperty::Create<int32_t>(
        name, enumType, owner, md.GetPtr(), nullptr, access);
}

}  // namespace

// ── C ABI surface ──────────────────────────────────────────────────────────

extern "C" void* noesis_class_register(
    const char* name,
    noesis_class_base base,
    noesis_prop_changed_fn cb,
    void* userdata,
    noesis_class_free_fn free_handler) {
    if (!name) return nullptr;
    if (!base_supported(base)) return nullptr;

    Noesis::Symbol sym = Noesis::Symbol(name);

    // Reject duplicate names so callers see the failure rather than silently
    // shadowing an earlier registration with a stale ClassData* dangling
    // inside the Factory creator path.
    if (Noesis::Reflection::IsTypeRegistered(sym)) {
        return nullptr;
    }

    auto* cd = new ClassData();
    cd->name = name;
    cd->sym = sym;
    cd->base = base;
    cd->cb = cb;
    cd->userdata = userdata;
    cd->free_handler = free_handler;

    // Build the synthetic TypeClass. Reflection::RegisterType assumes
    // ownership and deletes it on Unregister / Shutdown.
    cd->typeClass = new Noesis::TypeClassBuilder(sym, /*isInterface*/ false);
    cd->typeClass->AddBase(base_static_type(base));

    // UIElement bases get UIElementData (DP storage + routed events); the
    // Freezable base gets a plain DependencyData (DP storage only).
    if (base_is_uielement(base)) {
        cd->uiData = Noesis::MakePtr<Noesis::UIElementData>(cd->typeClass);
    } else {
        cd->uiData = Noesis::MakePtr<Noesis::DependencyData>(cd->typeClass);
    }
    cd->typeClass->AddMeta(cd->uiData.GetPtr());

    Noesis::Reflection::RegisterType(cd->typeClass);
    Noesis::Factory::RegisterComponent(sym, Noesis::Symbol(""), class_creator);

    if (!registry_insert(sym, cd)) {
        // Symbol collision after the IsTypeRegistered check. Extremely
        // unlikely, but unwind. No instances exist yet, so a full free
        // (including donated boxes + ClassData itself) is safe.
        Noesis::Factory::UnregisterComponent(sym);
        Noesis::Reflection::Unregister(cd->typeClass);
        cd->FreeDonated();
        delete cd;
        return nullptr;
    }

    track_class_data(cd);
    return cd;
}

// Instantiate a registered class directly from Rust (no XAML reference needed).
// Returns a BaseComponent* with +1 ref for the caller, released via
// noesis_base_component_release. NULL on null/invalid token.
extern "C" void* noesis_class_create_instance(void* class_token) {
    if (!class_token) return nullptr;
    auto* cd = static_cast<ClassData*>(class_token);
    Noesis::BaseComponent* instance = make_trampoline(cd);
    if (!instance) return nullptr;
    // `new` (inside make_trampoline) started the BaseComponent at refcount 1.
    // That IS the caller's +1, paired with base_component_release.
    return instance;
}

extern "C" uint32_t noesis_class_register_property_ex(
    void* class_token,
    const char* prop_name,
    noesis_prop_type prop_type,
    const void* default_ptr,
    uint32_t fpm_options,
    bool read_only,
    bool coerce) {
    if (!class_token || !prop_name) return UINT32_MAX;
    auto* cd = static_cast<ClassData*>(class_token);

    uint32_t index = static_cast<uint32_t>(cd->properties.size());

    bool coerce_eff = coerce && coercible_size(prop_type) != 0;
    if (coerce_eff && index >= kCoerceSlots) return UINT32_MAX;
    Noesis::CoerceValueCallback cc =
        coerce_eff ? coerce_callback_for(index) : Noesis::CoerceValueCallback();

    auto dp = create_dp_ex(prop_name, cd->typeClass, prop_type, default_ptr,
                           fpm_options, cc, read_only);
    if (!dp) return UINT32_MAX;

    const Noesis::DependencyProperty* installed = cd->uiData->InsertProperty(dp.GetPtr());
    if (!installed) return UINT32_MAX;

    cd->properties.push_back({installed, prop_type, read_only});
    return index;
}

extern "C" uint32_t noesis_class_register_property(
    void* class_token,
    const char* prop_name,
    noesis_prop_type prop_type,
    const void* default_ptr) {
    return noesis_class_register_property_ex(
        class_token, prop_name, prop_type, default_ptr, /*options*/ 0,
        /*read_only*/ false, /*coerce*/ false);
}

extern "C" uint32_t noesis_class_register_enum_property(
    void* class_token,
    const char* prop_name,
    const char* enum_type_name,
    int32_t default_value,
    uint32_t fpm_options,
    bool read_only) {
    if (!class_token || !prop_name) return UINT32_MAX;
    auto* cd = static_cast<ClassData*>(class_token);

    uint32_t index = static_cast<uint32_t>(cd->properties.size());

    auto dp = create_enum_dp(prop_name, cd->typeClass, enum_type_name, default_value,
                             fpm_options, read_only);
    if (!dp) return UINT32_MAX;

    const Noesis::DependencyProperty* installed = cd->uiData->InsertProperty(dp.GetPtr());
    if (!installed) return UINT32_MAX;

    // Tag as ENUM so the marshaling switches treat its storage as int32.
    cd->properties.push_back({installed, NOESIS_PROP_ENUM, read_only});
    return index;
}

extern "C" void noesis_class_set_coerce(
    void* class_token,
    noesis_coerce_fn cb,
    void* userdata,
    noesis_class_free_fn free_handler) {
    if (!class_token) {
        if (free_handler && userdata) free_handler(userdata);
        return;
    }
    auto* cd = static_cast<ClassData*>(class_token);
    // Drop any previously-installed coerce box.
    if (cd->coerce_free && cd->coerce_userdata) cd->coerce_free(cd->coerce_userdata);
    cd->coerce_cb = cb;
    cd->coerce_userdata = userdata;
    cd->coerce_free = free_handler;
    if (!cb && free_handler && userdata) {
        // Detaching but a box was donated: free it now to avoid a leak.
        free_handler(userdata);
        cd->coerce_userdata = nullptr;
        cd->coerce_free = nullptr;
    }
}

extern "C" void noesis_class_set_layout(
    void* class_token,
    const noesis_layout_vtable* vtable,
    void* userdata,
    noesis_layout_free_fn free_handler) {
    if (!class_token) {
        if (free_handler && userdata) free_handler(userdata);
        return;
    }
    auto* cd = static_cast<ClassData*>(class_token);
    if (cd->layout_free && cd->layout_userdata) cd->layout_free(cd->layout_userdata);
    cd->layout_userdata = nullptr;
    cd->layout_free = nullptr;
    cd->has_layout = false;
    if (vtable) {
        cd->layout = *vtable;
        cd->layout_userdata = userdata;
        cd->layout_free = free_handler;
        cd->has_layout = true;
    } else if (free_handler && userdata) {
        free_handler(userdata);
    }
}

extern "C" void noesis_class_set_render(
    void* class_token,
    noesis_render_fn cb,
    void* userdata,
    noesis_render_free_fn free_handler) {
    if (!class_token) {
        if (free_handler && userdata) free_handler(userdata);
        return;
    }
    auto* cd = static_cast<ClassData*>(class_token);
    // Drop any previously-installed render box.
    if (cd->render_free && cd->render_userdata) cd->render_free(cd->render_userdata);
    cd->render_cb = cb;
    cd->render_userdata = userdata;
    cd->render_free = free_handler;
    if (!cb && free_handler && userdata) {
        // Detaching but a box was donated: free it now to avoid a leak.
        free_handler(userdata);
        cd->render_userdata = nullptr;
        cd->render_free = nullptr;
    }
}

extern "C" void noesis_class_unregister(void* class_token) {
    if (!class_token) return;
    auto* cd = static_cast<ClassData*>(class_token);

    // Stop new instances from being created. Existing instances keep their
    // ClassData reference; the typeClass / uiData / ClassData allocations stay
    // alive because the parent destructor chain still walks the type metadata
    // after `~RustClassInstance`.
    Noesis::Factory::UnregisterComponent(cd->sym);
    registry_erase(cd->sym);

    // Release the Rust caller's ref. If no instances are alive, every donated
    // box is freed here; otherwise the freeing is deferred to the last
    // instance dying.
    cd->Release();
}

// Called from `noesis_shutdown` AFTER `Noesis::Shutdown` has destroyed
// every live DependencyObject. Defensively frees any donated boxes whose
// owning instances never fired the refcount-driven cleanup. Does NOT delete
// ClassData / typeClass / uiData (their lifetime is entangled with Noesis's
// Reflection registry; one ClassData per class is a bounded leak).
extern "C" void noesis_classes_force_free_at_shutdown(void) {
    std::vector<ClassData*> all;
    {
        std::lock_guard<std::mutex> lock(g_all_class_data_mutex);
        all = std::move(g_all_class_data);
    }
    for (ClassData* cd : all) {
        cd->FreeDonated();
    }
}

namespace {

// Locate the prop entry + the owning DependencyObject for an FFI instance
// pointer (a canonical BaseComponent*). Returns null on any mismatch.
const PropEntry* instance_prop(void* instance, uint32_t prop_index,
                               ClassData** out_cd, Noesis::DependencyObject** out_do) {
    RustClassInstance* iface = instance_lookup(instance);
    if (!iface) return nullptr;
    ClassData* cd = iface->GetClassData();
    if (!cd || prop_index >= cd->properties.size()) return nullptr;
    if (out_cd) *out_cd = cd;
    if (out_do) *out_do = iface->GetDO();
    return &cd->properties[prop_index];
}

// Which setter the per-tag write switch dispatches to.
enum class SetMode { Local, Current };

// Which getter the per-tag read switch dispatches to.
enum class GetMode { Effective, Base };

// Shared per-`noesis_prop_type` boxing switch for writes.
void apply_set(
    Noesis::DependencyObject* obj,
    const Noesis::DependencyProperty* dp,
    noesis_prop_type type,
    const void* value_ptr,
    SetMode mode = SetMode::Local) {
    using namespace Noesis;
    switch (type) {
        case NOESIS_PROP_INT32: {
            int32_t v = value_ptr ? *static_cast<const int32_t*>(value_ptr) : 0;
            if (mode == SetMode::Current) obj->SetCurrentValue<int32_t>(dp, v);
            else obj->SetValue<int32_t>(dp, v);
            return;
        }
        case NOESIS_PROP_UINT32: {
            uint32_t v = value_ptr ? *static_cast<const uint32_t*>(value_ptr) : 0;
            if (mode == SetMode::Current) obj->SetCurrentValue<uint32_t>(dp, v);
            else obj->SetValue<uint32_t>(dp, v);
            return;
        }
        case NOESIS_PROP_UINT64: {
            uint64_t v = value_ptr ? *static_cast<const uint64_t*>(value_ptr) : 0;
            if (mode == SetMode::Current) obj->SetCurrentValue<uint64_t>(dp, v);
            else obj->SetValue<uint64_t>(dp, v);
            return;
        }
        case NOESIS_PROP_FLOAT: {
            float v = value_ptr ? *static_cast<const float*>(value_ptr) : 0.0f;
            if (mode == SetMode::Current) obj->SetCurrentValue<float>(dp, v);
            else obj->SetValue<float>(dp, v);
            return;
        }
        case NOESIS_PROP_DOUBLE: {
            double v = value_ptr ? *static_cast<const double*>(value_ptr) : 0.0;
            if (mode == SetMode::Current) obj->SetCurrentValue<double>(dp, v);
            else obj->SetValue<double>(dp, v);
            return;
        }
        case NOESIS_PROP_BOOL: {
            bool v = value_ptr ? *static_cast<const bool*>(value_ptr) : false;
            if (mode == SetMode::Current) obj->SetCurrentValue<bool>(dp, v);
            else obj->SetValue<bool>(dp, v);
            return;
        }
        case NOESIS_PROP_STRING: {
            const char* s = value_ptr ? *static_cast<const char* const*>(value_ptr) : nullptr;
            const char* safe = s ? s : "";
            if (mode == SetMode::Current) obj->SetCurrentValue<String>(dp, safe);
            else obj->SetValue<String>(dp, safe);
            return;
        }
        case NOESIS_PROP_THICKNESS: {
            Thickness t;
            if (value_ptr) {
                const auto* f = static_cast<const float*>(value_ptr);
                t = Thickness(f[0], f[1], f[2], f[3]);
            }
            if (mode == SetMode::Current) obj->SetCurrentValue<Thickness>(dp, t);
            else obj->SetValue<Thickness>(dp, t);
            return;
        }
        case NOESIS_PROP_COLOR: {
            Color c;
            if (value_ptr) {
                const auto* f = static_cast<const float*>(value_ptr);
                c = Color(f[0], f[1], f[2], f[3]);
            }
            if (mode == SetMode::Current) obj->SetCurrentValue<Color>(dp, c);
            else obj->SetValue<Color>(dp, c);
            return;
        }
        case NOESIS_PROP_RECT: {
            Rect r;
            if (value_ptr) {
                const auto* f = static_cast<const float*>(value_ptr);
                r = Rect(f[0], f[1], f[0] + f[2], f[1] + f[3]);
            }
            if (mode == SetMode::Current) obj->SetCurrentValue<Rect>(dp, r);
            else obj->SetValue<Rect>(dp, r);
            return;
        }
        case NOESIS_PROP_POINT: {
            Point p;
            if (value_ptr) {
                const auto* f = static_cast<const float*>(value_ptr);
                p = Point(f[0], f[1]);
            }
            if (mode == SetMode::Current) obj->SetCurrentValue<Point>(dp, p);
            else obj->SetValue<Point>(dp, p);
            return;
        }
        case NOESIS_PROP_SIZE: {
            Size s;
            if (value_ptr) {
                const auto* f = static_cast<const float*>(value_ptr);
                s = Size(f[0], f[1]);
            }
            if (mode == SetMode::Current) obj->SetCurrentValue<Size>(dp, s);
            else obj->SetValue<Size>(dp, s);
            return;
        }
        case NOESIS_PROP_VECTOR: {
            Vector2 v;
            if (value_ptr) {
                const auto* f = static_cast<const float*>(value_ptr);
                v = Vector2(f[0], f[1]);
            }
            if (mode == SetMode::Current) obj->SetCurrentValue<Vector2>(dp, v);
            else obj->SetValue<Vector2>(dp, v);
            return;
        }
        case NOESIS_PROP_ENUM: {
            int32_t v = value_ptr ? *static_cast<const int32_t*>(value_ptr) : 0;
            if (mode == SetMode::Current) obj->SetCurrentValue<int32_t>(dp, v);
            else obj->SetValue<int32_t>(dp, v);
            return;
        }
        case NOESIS_PROP_IMAGE_SOURCE:
        case NOESIS_PROP_BASE_COMPONENT: {
            BaseComponent* b = value_ptr ? *static_cast<BaseComponent* const*>(value_ptr) : nullptr;
            if (mode == SetMode::Current) obj->SetCurrentValueObject(dp, b);
            else obj->SetValueObject(dp, b);
            return;
        }
    }
}

// Shared per-`noesis_prop_type` unboxing switch for reads.
bool apply_get(
    Noesis::DependencyObject* obj,
    const Noesis::DependencyProperty* dp,
    noesis_prop_type type,
    void* out_value,
    GetMode mode = GetMode::Effective) {
    using namespace Noesis;
    const bool base = mode == GetMode::Base;
    switch (type) {
        case NOESIS_PROP_INT32:
            *static_cast<int32_t*>(out_value) =
                base ? obj->GetBaseValue<int32_t>(dp) : obj->GetValue<int32_t>(dp);
            return true;
        case NOESIS_PROP_UINT32:
            *static_cast<uint32_t*>(out_value) =
                base ? obj->GetBaseValue<uint32_t>(dp) : obj->GetValue<uint32_t>(dp);
            return true;
        case NOESIS_PROP_UINT64:
            *static_cast<uint64_t*>(out_value) =
                base ? obj->GetBaseValue<uint64_t>(dp) : obj->GetValue<uint64_t>(dp);
            return true;
        case NOESIS_PROP_FLOAT:
            *static_cast<float*>(out_value) =
                base ? obj->GetBaseValue<float>(dp) : obj->GetValue<float>(dp);
            return true;
        case NOESIS_PROP_DOUBLE:
            *static_cast<double*>(out_value) =
                base ? obj->GetBaseValue<double>(dp) : obj->GetValue<double>(dp);
            return true;
        case NOESIS_PROP_BOOL:
            *static_cast<bool*>(out_value) =
                base ? obj->GetBaseValue<bool>(dp) : obj->GetValue<bool>(dp);
            return true;
        case NOESIS_PROP_STRING: {
            const String& s = base ? obj->GetBaseValue<String>(dp) : obj->GetValue<String>(dp);
            *static_cast<const char**>(out_value) = s.Str();
            return true;
        }
        case NOESIS_PROP_THICKNESS: {
            const Thickness& t =
                base ? obj->GetBaseValue<Thickness>(dp) : obj->GetValue<Thickness>(dp);
            auto* f = static_cast<float*>(out_value);
            f[0] = t.left; f[1] = t.top; f[2] = t.right; f[3] = t.bottom;
            return true;
        }
        case NOESIS_PROP_COLOR: {
            const Color& c = base ? obj->GetBaseValue<Color>(dp) : obj->GetValue<Color>(dp);
            auto* f = static_cast<float*>(out_value);
            f[0] = c.r; f[1] = c.g; f[2] = c.b; f[3] = c.a;
            return true;
        }
        case NOESIS_PROP_RECT: {
            const Rect& r = base ? obj->GetBaseValue<Rect>(dp) : obj->GetValue<Rect>(dp);
            auto* f = static_cast<float*>(out_value);
            f[0] = r.x; f[1] = r.y; f[2] = r.width; f[3] = r.height;
            return true;
        }
        case NOESIS_PROP_POINT: {
            const Point& p = base ? obj->GetBaseValue<Point>(dp) : obj->GetValue<Point>(dp);
            auto* f = static_cast<float*>(out_value);
            f[0] = p.x; f[1] = p.y;
            return true;
        }
        case NOESIS_PROP_SIZE: {
            const Size& s = base ? obj->GetBaseValue<Size>(dp) : obj->GetValue<Size>(dp);
            auto* f = static_cast<float*>(out_value);
            f[0] = s.width; f[1] = s.height;
            return true;
        }
        case NOESIS_PROP_VECTOR: {
            const Vector2& v = base ? obj->GetBaseValue<Vector2>(dp) : obj->GetValue<Vector2>(dp);
            auto* f = static_cast<float*>(out_value);
            f[0] = v.x; f[1] = v.y;
            return true;
        }
        case NOESIS_PROP_ENUM:
            *static_cast<int32_t*>(out_value) =
                base ? obj->GetBaseValue<int32_t>(dp) : obj->GetValue<int32_t>(dp);
            return true;
        case NOESIS_PROP_IMAGE_SOURCE:
        case NOESIS_PROP_BASE_COMPONENT: {
            if (base) return false;
            Ptr<BaseComponent> v = obj->GetValueObject(dp);
            *static_cast<BaseComponent**>(out_value) = v.GetPtr();
            return true;
        }
    }
    return false;
}

// Validate that a caller-supplied tag matches a resolved DP's real Type*.
bool prop_type_matches(const Noesis::Type* t, noesis_prop_type tag) {
    using namespace Noesis;
    if (!t) return false;
    switch (tag) {
        case NOESIS_PROP_INT32:     return t == TypeOf<int32_t>();
        case NOESIS_PROP_UINT32:    return t == TypeOf<uint32_t>();
        case NOESIS_PROP_UINT64:    return t == TypeOf<uint64_t>();
        case NOESIS_PROP_FLOAT:     return t == TypeOf<float>();
        case NOESIS_PROP_DOUBLE:    return t == TypeOf<double>();
        case NOESIS_PROP_BOOL:      return t == TypeOf<bool>();
        case NOESIS_PROP_STRING:    return t == TypeOf<String>();
        case NOESIS_PROP_THICKNESS: return t == TypeOf<Thickness>();
        case NOESIS_PROP_COLOR:     return t == TypeOf<Color>();
        case NOESIS_PROP_RECT:      return t == TypeOf<Rect>();
        case NOESIS_PROP_POINT:     return t == TypeOf<Point>();
        case NOESIS_PROP_SIZE:      return t == TypeOf<Size>();
        case NOESIS_PROP_VECTOR:    return t == TypeOf<Vector2>();
        case NOESIS_PROP_ENUM:      return DynamicCast<const TypeEnum*>(t) != nullptr;
        case NOESIS_PROP_IMAGE_SOURCE:
            return TypeOf<ImageSource>()->IsAssignableFrom(t);
        case NOESIS_PROP_BASE_COMPONENT:
            return TypeOf<BaseComponent>()->IsAssignableFrom(t);
    }
    return false;
}

// Inverse of `prop_type_matches`.
int32_t prop_type_to_tag(const Noesis::Type* t) {
    using namespace Noesis;
    if (!t) return -1;
    if (t == TypeOf<int32_t>())   return NOESIS_PROP_INT32;
    if (t == TypeOf<uint32_t>())  return NOESIS_PROP_UINT32;
    if (t == TypeOf<uint64_t>())  return NOESIS_PROP_UINT64;
    if (t == TypeOf<float>())     return NOESIS_PROP_FLOAT;
    if (t == TypeOf<double>())    return NOESIS_PROP_DOUBLE;
    if (t == TypeOf<bool>())      return NOESIS_PROP_BOOL;
    if (t == TypeOf<String>())    return NOESIS_PROP_STRING;
    if (t == TypeOf<Thickness>()) return NOESIS_PROP_THICKNESS;
    if (t == TypeOf<Color>())     return NOESIS_PROP_COLOR;
    if (t == TypeOf<Rect>())      return NOESIS_PROP_RECT;
    if (t == TypeOf<Point>())     return NOESIS_PROP_POINT;
    if (t == TypeOf<Size>())      return NOESIS_PROP_SIZE;
    if (t == TypeOf<Vector2>())   return NOESIS_PROP_VECTOR;
    if (Noesis::DynamicCast<const Noesis::TypeEnum*>(t)) return NOESIS_PROP_ENUM;
    if (TypeOf<ImageSource>()->IsAssignableFrom(t)) return NOESIS_PROP_IMAGE_SOURCE;
    if (TypeOf<BaseComponent>()->IsAssignableFrom(t)) return NOESIS_PROP_BASE_COMPONENT;
    return -1;
}

// Resolve `obj` to a DependencyObject and `name` to one of its DPs.
const Noesis::DependencyProperty* resolve_dp(
    void* obj, const char* name, Noesis::DependencyObject** out_d) {
    if (!obj || !name) return nullptr;
    auto* d = Noesis::DynamicCast<Noesis::DependencyObject*>(
        static_cast<Noesis::BaseComponent*>(obj));
    if (out_d) *out_d = d;
    if (!d) return nullptr;
    return Noesis::FindDependencyProperty(d->GetClassType(), Noesis::Symbol(name));
}

}  // namespace

extern "C" void noesis_instance_set_property(
    void* instance,
    uint32_t prop_index,
    const void* value_ptr) {
    Noesis::DependencyObject* obj = nullptr;
    const PropEntry* pe = instance_prop(instance, prop_index, nullptr, &obj);
    if (!pe || !obj) return;
    // The ordinary setter path refuses read-only DPs (the privileged
    // noesis_instance_set_readonly_property is the only legal writer).
    if (pe->read_only) return;
    apply_set(obj, pe->dp, pe->type, value_ptr);
}

extern "C" bool noesis_instance_set_readonly_property(
    void* instance,
    uint32_t prop_index,
    const void* value_ptr) {
    RustClassInstance* iface = instance_lookup(instance);
    if (!iface) return false;
    ClassData* cd = iface->GetClassData();
    if (!cd || prop_index >= cd->properties.size()) return false;
    const PropEntry& pe = cd->properties[prop_index];
    iface->RustSetReadOnly(pe.dp, pe.type, value_ptr);
    return true;
}

extern "C" bool noesis_freezable_freeze(void* freezable) {
    if (!freezable) return false;
    auto* fz = Noesis::DynamicCast<Noesis::Freezable*>(
        static_cast<Noesis::BaseComponent*>(freezable));
    if (!fz || !fz->CanFreeze()) return false;
    fz->Freeze();
    return true;
}

extern "C" bool noesis_freezable_is_frozen(void* freezable) {
    if (!freezable) return false;
    auto* fz = Noesis::DynamicCast<Noesis::Freezable*>(
        static_cast<Noesis::BaseComponent*>(freezable));
    return fz && fz->IsFrozen();
}

extern "C" bool noesis_freezable_can_freeze(void* freezable) {
    if (!freezable) return false;
    auto* fz = Noesis::DynamicCast<Noesis::Freezable*>(
        static_cast<Noesis::BaseComponent*>(freezable));
    return fz && fz->CanFreeze();
}

extern "C" bool noesis_image_source_get_size(
    void* image_source,
    float* out_width,
    float* out_height) {
    if (!image_source || !out_width || !out_height) return false;
    auto* obj = static_cast<Noesis::BaseComponent*>(image_source);
    auto* img = Noesis::DynamicCast<Noesis::ImageSource*>(obj);
    if (!img) return false;
    *out_width = img->GetWidth();
    *out_height = img->GetHeight();
    return true;
}

extern "C" bool noesis_instance_get_property(
    void* instance,
    uint32_t prop_index,
    void* out_value) {
    Noesis::DependencyObject* obj = nullptr;
    const PropEntry* pe = instance_prop(instance, prop_index, nullptr, &obj);
    if (!pe || !obj || !out_value) return false;
    return apply_get(obj, pe->dp, pe->type, out_value);
}

// ── UIElement layout primitives ─────────────────────────────────────────────

extern "C" bool noesis_uielement_measure(void* element, float avail_w, float avail_h) {
    if (!element) return false;
    auto* e = Noesis::DynamicCast<Noesis::UIElement*>(static_cast<Noesis::BaseComponent*>(element));
    if (!e) return false;
    e->Measure(Noesis::Size(avail_w, avail_h));
    return true;
}

extern "C" bool noesis_uielement_arrange(void* element, float x, float y, float w, float h) {
    if (!element) return false;
    auto* e = Noesis::DynamicCast<Noesis::UIElement*>(static_cast<Noesis::BaseComponent*>(element));
    if (!e) return false;
    // Noesis::Rect's 4-arg constructor is (left, top, right, bottom).
    e->Arrange(Noesis::Rect(x, y, x + w, y + h));
    return true;
}

extern "C" bool noesis_uielement_desired_size(void* element, float* out_w, float* out_h) {
    if (!element || !out_w || !out_h) return false;
    auto* e = Noesis::DynamicCast<Noesis::UIElement*>(static_cast<Noesis::BaseComponent*>(element));
    if (!e) return false;
    const Noesis::Size& d = e->GetDesiredSize();
    *out_w = d.width;
    *out_h = d.height;
    return true;
}

// ── Generic name-keyed DependencyProperty access ───────────────────────────
//
// Resolve a DependencyProperty by *name* on an arbitrary DependencyObject,
// then marshal through the same per-type switch. The caller-supplied tag is
// validated against the property's reflected type before casting.
//
// No VerifyAccess(): these must never throw across the C ABI.

extern "C" bool noesis_dependency_object_set_property(
    void* obj,
    const char* name,
    uint32_t prop_type,
    const void* value_ptr) {
    if (!obj || !name) return false;
    auto* base = static_cast<Noesis::BaseComponent*>(obj);
    auto* d = Noesis::DynamicCast<Noesis::DependencyObject*>(base);
    if (!d) return false;

    const Noesis::DependencyProperty* dp =
        Noesis::FindDependencyProperty(d->GetClassType(), Noesis::Symbol(name));
    if (!dp) return false;

    auto type = static_cast<noesis_prop_type>(prop_type);
    if (!prop_type_matches(dp->GetType(), type)) return false;
    if (dp->IsReadOnly()) return false;

    apply_set(d, dp, type, value_ptr);
    return true;
}

extern "C" bool noesis_dependency_object_get_property(
    void* obj,
    const char* name,
    uint32_t prop_type,
    void* out_value) {
    if (!obj || !name || !out_value) return false;
    auto* base = static_cast<Noesis::BaseComponent*>(obj);
    auto* d = Noesis::DynamicCast<Noesis::DependencyObject*>(base);
    if (!d) return false;

    const Noesis::DependencyProperty* dp =
        Noesis::FindDependencyProperty(d->GetClassType(), Noesis::Symbol(name));
    if (!dp) return false;

    auto type = static_cast<noesis_prop_type>(prop_type);
    if (!prop_type_matches(dp->GetType(), type)) return false;

    return apply_get(d, dp, type, out_value);
}

// ── Attached properties ─────────────────────────────────────────────────────
//
// Resolve a DependencyProperty registered on `owner_type` (e.g. owner="Grid",
// prop="Row"), then set / get it on `obj`. The owner type is resolved through
// Reflection by name. Works for the built-in Noesis types AND for Rust-backed
// owner classes registered via noesis_class_register (the registration side
// of attached properties: register the DP on the owner class, then any
// DependencyObject can carry it).

extern "C" bool noesis_dependency_object_set_attached(
    void* obj,
    const char* owner_type,
    const char* prop_name,
    uint32_t prop_type,
    const void* value_ptr) {
    if (!obj || !owner_type || !prop_name) return false;
    auto* d = Noesis::DynamicCast<Noesis::DependencyObject*>(
        static_cast<Noesis::BaseComponent*>(obj));
    if (!d) return false;

    const Noesis::Type* t = Noesis::Reflection::GetType(Noesis::Symbol(owner_type));
    const auto* owner = Noesis::DynamicCast<const Noesis::TypeClass*>(t);
    if (!owner) return false;

    const Noesis::DependencyProperty* dp =
        Noesis::FindDependencyProperty(owner, Noesis::Symbol(prop_name));
    if (!dp) return false;

    auto type = static_cast<noesis_prop_type>(prop_type);
    if (!prop_type_matches(dp->GetType(), type)) return false;
    if (dp->IsReadOnly()) return false;

    apply_set(d, dp, type, value_ptr);
    return true;
}

extern "C" bool noesis_dependency_object_get_attached(
    void* obj,
    const char* owner_type,
    const char* prop_name,
    uint32_t prop_type,
    void* out_value) {
    if (!obj || !owner_type || !prop_name || !out_value) return false;
    auto* d = Noesis::DynamicCast<Noesis::DependencyObject*>(
        static_cast<Noesis::BaseComponent*>(obj));
    if (!d) return false;

    const Noesis::Type* t = Noesis::Reflection::GetType(Noesis::Symbol(owner_type));
    const auto* owner = Noesis::DynamicCast<const Noesis::TypeClass*>(t);
    if (!owner) return false;

    const Noesis::DependencyProperty* dp =
        Noesis::FindDependencyProperty(owner, Noesis::Symbol(prop_name));
    if (!dp) return false;

    auto type = static_cast<noesis_prop_type>(prop_type);
    if (!prop_type_matches(dp->GetType(), type)) return false;

    return apply_get(d, dp, type, out_value);
}

// ── ClearValue / SetCurrentValue / GetBaseValue ─────────────────────────────

extern "C" bool noesis_dependency_object_clear_value(void* obj, const char* name) {
    Noesis::DependencyObject* d = nullptr;
    const Noesis::DependencyProperty* dp = resolve_dp(obj, name, &d);
    if (!dp) return false;
    if (dp->IsReadOnly()) return false;
    d->ClearLocalValue(dp);
    return true;
}

extern "C" bool noesis_dependency_object_set_current_value(
    void* obj,
    const char* name,
    uint32_t prop_type,
    const void* value_ptr) {
    Noesis::DependencyObject* d = nullptr;
    const Noesis::DependencyProperty* dp = resolve_dp(obj, name, &d);
    if (!dp) return false;

    auto type = static_cast<noesis_prop_type>(prop_type);
    if (!prop_type_matches(dp->GetType(), type)) return false;
    if (dp->IsReadOnly()) return false;

    apply_set(d, dp, type, value_ptr, SetMode::Current);
    return true;
}

extern "C" bool noesis_dependency_object_get_base_value(
    void* obj,
    const char* name,
    uint32_t prop_type,
    void* out_value) {
    if (!out_value) return false;
    Noesis::DependencyObject* d = nullptr;
    const Noesis::DependencyProperty* dp = resolve_dp(obj, name, &d);
    if (!dp) return false;

    auto type = static_cast<noesis_prop_type>(prop_type);
    if (!prop_type_matches(dp->GetType(), type)) return false;

    // Object tags have no boxed base-value accessor: apply_get returns false.
    return apply_get(d, dp, type, out_value, GetMode::Base);
}

extern "C" int32_t noesis_dependency_object_property_tag(void* obj, const char* name) {
    const Noesis::DependencyProperty* dp = resolve_dp(obj, name, nullptr);
    if (!dp) return -1;
    return prop_type_to_tag(dp->GetType());
}