truce-gui 0.49.11

Built-in GUI for truce plugins
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
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
//! Built-in editor using the CPU render backend.
//!
//! Renders parameter widgets via `RenderBackend`. Uses tiny-skia for
//! software rasterization and baseview + wgpu for window management
//! and blitting. For GPU-accelerated rendering see the `truce-gpu`
//! crate which provides `GpuEditor` wrapping this editor.

#[cfg(feature = "cpu")]
use std::ptr;
use std::sync::Arc;
#[cfg(feature = "cpu")]
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};

use truce_core::Float;
#[cfg(feature = "cpu")]
use truce_core::editor::Editor;
#[cfg(feature = "cpu")]
use truce_core::editor::RawWindowHandle;
use truce_core::editor::{PluginContext, PluginContextReadF32};
use truce_params::Params;

#[cfg(feature = "cpu")]
use crate::backend_cpu::CpuBackend;
use crate::interaction::{self, InputEvent, InteractionState, ParamEdit};
use crate::layout::{GridLayout, Layout, PluginLayout};
#[cfg(feature = "cpu")]
use crate::platform::EditorScale;
use crate::render::RenderBackend;
use crate::render_core::{
    EditorSnapshotClosures, build_snapshot_closures as build_snapshot_closures_impl,
    render_widgets as render_widgets_impl,
};
use crate::theme::Theme;
use crate::widgets;

/// Built-in editor that renders parameter widgets to a pixel buffer.
///
/// Uses the CPU backend (tiny-skia) for software rasterization. When
/// `open()` is called, creates a baseview window and blits pixels via wgpu.
pub struct BuiltinEditor<P: Params> {
    params: Arc<P>,
    layout: Layout,
    theme: Theme,
    /// CPU pixmap rendering target. Only present when the `cpu`
    /// feature is on; in `gpu`-only mode `BuiltinEditor` is wrapped
    /// by `GpuEditor`, which renders through `WgpuBackend` directly
    /// via [`Self::render_to`] without touching this field.
    #[cfg(feature = "cpu")]
    backend: Option<CpuBackend>,
    interaction: InteractionState,
    context: Option<PluginContext>,
    /// Active baseview window handle for the cpu-path `Editor`
    /// impl. Only meaningful when `cpu` is on.
    #[cfg(feature = "cpu")]
    window: Option<baseview::WindowHandle>,
    /// Weak-ish handle to the blit backend the window-handler
    /// materializes. The editor keeps the canonical `Arc` and the
    /// handler gets a clone. On close we take the `Option` out of
    /// the inner mutex - dropping the wgpu Surface synchronously -
    /// before asking baseview to tear the `NSView` down.
    #[cfg(feature = "cpu")]
    blit_backend: Option<SharedBackend>,
    /// Set whenever something visible changes (param edited via the
    /// UI, host-driven state reload, explicit `request_repaint` by
    /// plugin code). `on_frame` clears it and only does the
    /// rasterize + blit pass when it was true.
    ///
    /// Shared so `PluginContext::set_param` and `state_changed`
    /// closures can flip it without touching editor internals.
    needs_repaint: Arc<AtomicBool>,
    /// Normalized values captured at the last render pass, in the
    /// same order as `interaction.knob_regions`. Used to detect
    /// host-driven param changes (automation, preset recall) - if any
    /// live value drifts from the last-painted one, we force a
    /// repaint even if the UI never received a direct edit. Only
    /// the cpu path's incremental render uses this signal.
    #[cfg(feature = "cpu")]
    last_painted_values: Vec<f32>,
    /// Live content-scale factor (a [`crate::platform::EditorScale`]).
    /// `set_scale_factor` (host) writes the cell; the baseview
    /// handler holds a clone, compares against `last_applied_scale`
    /// each frame, and rebuilds the CPU pixmap + reconfigures the
    /// wgpu surface when the value diverges. Only consumed by the
    /// cpu path; in gpu-only mode `GpuEditor` has its own
    /// `EditorScale` and this field is unused.
    #[cfg(feature = "cpu")]
    scale: EditorScale,
    /// Meter IDs referenced by the layout, collected once at
    /// construction. Meters are display-only values written from the
    /// audio thread (`PluginContext::get_meter`); they never move
    /// through the param system, so the CPU repaint gate needs to poll
    /// them explicitly to know when to redraw. Empty for layouts with
    /// no meters - the poll then short-circuits.
    #[cfg(feature = "cpu")]
    meter_ids: Vec<u32>,
    /// Meter values captured at the last repaint, parallel to
    /// `meter_ids`. `detect_meter_changes` compares the live values
    /// against these to flip the dirty bit only when a meter actually
    /// moved (the gpu path repaints unconditionally and ignores this).
    #[cfg(feature = "cpu")]
    last_meter_values: Vec<f32>,
}

// SAFETY: `baseview::WindowHandle` holds a raw native window pointer
// (HWND / NSView / X11 Window) and is not auto-`Send`. Hosts call
// `Editor::open` / `idle` / `close` from a single dedicated GUI thread
// - never concurrently and never from the audio thread - so the
// handle is only ever touched on the thread that created it. The
// `Editor` trait requires `Send` so the editor can live behind a
// trait object; this impl asserts that the type doesn't escape its
// thread in practice. All other fields (`Arc<P>`, `Layout`, `Theme`,
// `Option<CpuBackend>`, etc.) are themselves `Send`.
unsafe impl<P: Params> Send for BuiltinEditor<P> {}

/// Gather every meter ID referenced by a layout, in layout order. The
/// CPU editor polls these each frame to decide when a meter moved and
/// the surface needs a repaint.
#[cfg(feature = "cpu")]
fn collect_meter_ids(layout: &Layout) -> Vec<u32> {
    let mut ids = Vec::new();
    match layout {
        Layout::Rows(pl) => {
            for row in &pl.rows {
                for knob in &row.knobs {
                    if let Some(m) = &knob.meter_ids {
                        ids.extend_from_slice(m);
                    }
                }
            }
        }
        Layout::Grid(gl) => {
            for widget in &gl.widgets {
                if let Some(m) = &widget.meter_ids {
                    ids.extend_from_slice(m);
                }
            }
        }
    }
    ids
}

impl<P: Params + 'static> BuiltinEditor<P> {
    /// Request a repaint on the next idle tick. Call this if plugin
    /// code mutates display state outside the normal param or
    /// `state_changed` pathways (uncommon). User interaction and
    /// host automation already flag themselves dirty automatically.
    pub fn request_repaint(&self) {
        self.needs_repaint.store(true, Ordering::Release);
    }

    /// Only consumed by the cpu Editor impl's render gate.
    #[cfg(feature = "cpu")]
    fn take_needs_repaint(&self) -> bool {
        self.needs_repaint.swap(false, Ordering::AcqRel)
    }

    /// Compare the values just read by `update_interaction` (live from
    /// the host / params Arc) against those captured at the last
    /// render. A mismatch means an automation lane wrote a new value,
    /// a preset was recalled, or some other off-UI state change
    /// happened - force a repaint so the widget tracks it.
    ///
    /// Only used by the cpu blit path's incremental render gate;
    /// the gpu path repaints every frame and skips this check.
    #[cfg(feature = "cpu")]
    fn detect_host_param_changes(&mut self) {
        let regions = &self.interaction.knob_regions;
        if regions.len() != self.last_painted_values.len() {
            // Region set changed (e.g. after a layout rebuild). Force
            // a repaint and re-sync on the next paint.
            self.request_repaint();
            return;
        }
        for (i, region) in regions.iter().enumerate() {
            if (region.normalized_value - self.last_painted_values[i]).abs() > f32::EPSILON {
                self.request_repaint();
                return;
            }
        }
    }

    /// Snapshot the regions' normalized values for the next frame's
    /// automation detection. Called after each render. Only used by
    /// the cpu blit path.
    #[cfg(feature = "cpu")]
    fn stash_painted_values(&mut self) {
        let regions = &self.interaction.knob_regions;
        // Resize-then-overwrite reuses the existing allocation
        // unchanged when the region count is steady (the common
        // case - knob layouts only change on
        // `interaction.build_regions`). The previous
        // clear-then-extend form pumped through the iterator path
        // every frame even when the length didn't change.
        self.last_painted_values.resize(regions.len(), 0.0);
        for (slot, region) in self.last_painted_values.iter_mut().zip(regions.iter()) {
            *slot = region.normalized_value;
        }
    }

    /// Poll the layout's meters and flag a repaint when any value
    /// moved since the last frame. Meters are display-only values the
    /// audio thread reports through `PluginContext::get_meter`; they
    /// don't flow through `detect_host_param_changes` (which only
    /// inspects knob param regions), so without this the CPU gate would
    /// freeze the meter until an unrelated repaint trigger (a knob drag,
    /// host param churn) happened to fire. The gpu path repaints every
    /// frame and skips this entirely.
    #[cfg(feature = "cpu")]
    #[allow(clippy::float_cmp)]
    fn detect_meter_changes(&mut self) {
        if self.meter_ids.is_empty() {
            return;
        }
        let Some(ctx) = self.context.as_ref() else {
            return;
        };
        let current: Vec<f32> = self.meter_ids.iter().map(|&id| ctx.get_meter(id)).collect();
        if current != self.last_meter_values {
            self.last_meter_values = current;
            self.request_repaint();
        }
    }

    pub fn new(params: Arc<P>, layout: PluginLayout) -> Self {
        Self::with_layout_inner(params, Layout::Rows(layout))
    }

    pub fn new_with_layout(params: Arc<P>, layout: Layout) -> Self {
        Self::with_layout_inner(params, layout)
    }

    pub fn new_grid(params: Arc<P>, layout: GridLayout) -> Self {
        Self::with_layout_inner(params, Layout::Grid(layout))
    }

    fn with_layout_inner(params: Arc<P>, layout: Layout) -> Self {
        #[cfg(feature = "cpu")]
        let meter_ids = collect_meter_ids(&layout);
        Self {
            params,
            layout,
            theme: Theme::dark(),
            #[cfg(feature = "cpu")]
            backend: None,
            interaction: InteractionState::default(),
            context: None,
            #[cfg(feature = "cpu")]
            window: None,
            #[cfg(feature = "cpu")]
            blit_backend: None,
            needs_repaint: Arc::new(AtomicBool::new(false)),
            #[cfg(feature = "cpu")]
            last_painted_values: Vec::new(),
            #[cfg(feature = "cpu")]
            scale: EditorScale::new(crate::backing_scale()),
            #[cfg(feature = "cpu")]
            meter_ids,
            #[cfg(feature = "cpu")]
            last_meter_values: Vec::new(),
        }
    }

    #[must_use]
    pub fn with_theme(mut self, theme: Theme) -> Self {
        self.theme = theme;
        self
    }

    /// Render the full UI to the internal CPU pixel buffer.
    ///
    /// Only available when the `cpu` feature is on. In `gpu`-only
    /// mode, render through [`Self::render_to`] with a
    /// `truce_gpu::WgpuBackend` instead.
    ///
    /// # Panics
    ///
    /// Panics if the lazy `CpuBackend::new` allocation fails (out of
    /// memory or zero dimensions). The backend is allocated on first
    /// render - subsequent calls reuse it.
    #[cfg(feature = "cpu")]
    pub fn render(&mut self) {
        let (w, h) = (self.layout.width(), self.layout.height());
        let scale = self.scale.get_f32();
        let owned = self.build_snapshot_closures();
        let snapshot = owned.as_snapshot();
        let backend = self
            .backend
            .get_or_insert_with(|| CpuBackend::new(w, h, scale).expect("Failed to create backend"));
        render_widgets_impl(
            &self.layout,
            &self.theme,
            &mut self.interaction,
            &snapshot,
            backend,
        );
    }

    /// Build owned boxed closures from `self.context` / `self.params` that
    /// back a `ParamSnapshot`. Each closure clones the `Arc<P>` or the
    /// `PluginContext`, so `EditorSnapshotClosures` is `'static` and safe
    /// to hold across a borrow of `&mut self.interaction`. Delegates to
    /// the shared `render_core` impl so the iOS editor doesn't have to
    /// duplicate the (~100-line) closure scaffolding.
    fn build_snapshot_closures(&self) -> EditorSnapshotClosures {
        build_snapshot_closures_impl(&self.params, self.context.as_ref())
    }

    /// Apply a single `ParamEdit` returned by `interaction::dispatch`.
    fn apply_edit(&self, edit: ParamEdit) {
        match edit {
            ParamEdit::Begin { id } => {
                if let Some(ref ctx) = self.context {
                    ctx.begin_edit(id);
                }
            }
            ParamEdit::Set { id, normalized } => {
                self.params.set_normalized(id, f64::from(normalized));
                if let Some(ref ctx) = self.context {
                    ctx.set_param(id, f64::from(normalized));
                }
                self.request_repaint();
            }
            ParamEdit::End { id } => {
                if let Some(ref ctx) = self.context {
                    ctx.end_edit(id);
                }
            }
        }
    }

    /// Feed a batch of input events through `interaction::dispatch` and
    /// apply the resulting param edits. Flags a repaint when hover,
    /// dropdown-open state, or any param moved.
    ///
    /// Typically callers build the events by running each baseview
    /// event through [`interaction::BaseviewTranslator`] and batching
    /// the non-`None` results.
    pub fn dispatch_events(&mut self, events: &[InputEvent]) {
        let hover_before = self.interaction.hover_idx;
        let dd_before = self.interaction.dropdown_is_open();
        let owned = self.build_snapshot_closures();
        let snapshot = owned.as_snapshot();
        let edits = interaction::dispatch(events, &self.layout, &snapshot, &mut self.interaction);
        let had_edits = !edits.is_empty();
        for e in edits {
            self.apply_edit(e);
        }
        // Anything that changes a pixel on screen flips the dirty
        // bit: param edits (already covered by `apply_edit`), hover
        // highlights moving between widgets, dropdown open/close
        // transitions, and any event that explicitly requested a
        // repaint (e.g. MouseLeave clearing hover state).
        let explicit = self.interaction.take_repaint_request();
        if had_edits
            || explicit
            || self.interaction.hover_idx != hover_before
            || self.interaction.dropdown_is_open() != dd_before
        {
            self.request_repaint();
        }
    }

    /// Get the raw pixel data after rendering (RGBA premultiplied).
    /// Only available when the `cpu` feature is on.
    #[cfg(feature = "cpu")]
    #[must_use]
    pub fn pixel_data(&self) -> Option<&[u8]> {
        self.backend
            .as_ref()
            .map(super::backend_cpu::CpuBackend::data)
    }

    // --- Public API for external backends (truce-gpu) ---

    /// Whether the editor has an active context.
    #[must_use]
    pub fn has_context(&self) -> bool {
        self.context.is_some()
    }

    /// Take the editor context, leaving `None` in its place.
    /// Used by hot-reload to preserve the context when swapping editors.
    pub fn take_context(&mut self) -> Option<PluginContext> {
        self.context.take()
    }

    /// Set the editor context (host callbacks) without opening the CPU view.
    pub fn set_context(&mut self, context: PluginContext) {
        self.context = Some(context);
        match &self.layout {
            Layout::Rows(pl) => self.interaction.build_regions(pl),
            Layout::Grid(gl) => self.interaction.build_regions_grid(gl),
        }
    }

    /// Editor logical size (width, height in points). Inherent
    /// method so it stays callable when the `Editor` trait impl is
    /// cfg'd out in gpu-only builds.
    #[must_use]
    pub fn size(&self) -> (u32, u32) {
        (self.layout.width(), self.layout.height())
    }

    /// Notify the widget tree that plugin state was restored
    /// (preset recall, undo, session load). Inherent for the same
    /// reason as [`Self::size`] above.
    pub fn state_changed(&mut self) {
        self.request_repaint();
    }

    /// Render all widgets to an external `RenderBackend`.
    ///
    /// Used by `truce-gpu` to draw through the GPU backend instead of
    /// the internal CPU backend.
    pub fn render_to(&mut self, backend: &mut dyn RenderBackend) {
        update_interaction(self);
        let owned = self.build_snapshot_closures();
        let snapshot = owned.as_snapshot();
        render_widgets_impl(
            &self.layout,
            &self.theme,
            &mut self.interaction,
            &snapshot,
            backend,
        );
    }
}

/// Test-only ergonomic wrappers. Production callers go through
/// `dispatch_events` (usually with events synthesized by
/// [`crate::interaction::BaseviewTranslator`]).
#[cfg(test)]
impl<P: Params + 'static> BuiltinEditor<P> {
    fn on_mouse_down(&mut self, x: f32, y: f32) {
        self.dispatch_events(&[InputEvent::MouseDown {
            pointer_id: truce_gui_types::interaction::SINGLE_POINTER,
            x,
            y,
            button: crate::interaction::MouseButton::Left,
        }]);
    }

    fn on_mouse_up(&mut self, x: f32, y: f32) {
        self.dispatch_events(&[InputEvent::MouseUp {
            pointer_id: truce_gui_types::interaction::SINGLE_POINTER,
            x,
            y,
            button: crate::interaction::MouseButton::Left,
        }]);
    }

    fn on_mouse_moved(&mut self, x: f32, y: f32) {
        self.dispatch_events(&[InputEvent::MouseMove {
            pointer_id: truce_gui_types::interaction::SINGLE_POINTER,
            x,
            y,
        }]);
    }
}

// ---------------------------------------------------------------------------
// C callbacks - thin wrappers that cast the context pointer back to &mut Self
// ---------------------------------------------------------------------------

/// Update interaction regions and live param values.
///
/// Takes `&mut BuiltinEditor<P>` so the borrow checker enforces
/// non-aliasing - the function only touches Rust references and is
/// fully safe.
pub fn update_interaction<P: Params + 'static>(editor: &mut BuiltinEditor<P>) {
    match &editor.layout {
        Layout::Rows(pl) => {
            editor.interaction.build_regions(pl);
            let mut flat_idx = 0usize;
            for row in &pl.rows {
                for knob_def in &row.knobs {
                    if let Some(region) = editor.interaction.knob_regions.get_mut(flat_idx) {
                        region.widget_type = resolve_widget_type(
                            knob_def.widget,
                            knob_def.param_id,
                            &*editor.params,
                        );
                    }
                    flat_idx += 1;
                }
            }
        }
        Layout::Grid(gl) => {
            editor.interaction.build_regions_grid(gl);
            for (idx, gw) in gl.widgets.iter().enumerate() {
                if let Some(region) = editor.interaction.knob_regions.get_mut(idx) {
                    region.widget_type =
                        resolve_widget_type(gw.widget, gw.param_id, &*editor.params);
                }
            }
        }
    }
    for region in &mut editor.interaction.knob_regions {
        if let Some(ref ctx) = editor.context {
            // Resolves through `PluginContextReadF32` - bridge's `f64` narrows inside.
            region.normalized_value = ctx.get_param(region.param_id);
        } else {
            region.normalized_value =
                f32::from_f64(editor.params.get_normalized(region.param_id).unwrap_or(0.0));
        }
    }
}

// ---------------------------------------------------------------------------
// Baseview WindowHandler - drives the CPU render loop
// ---------------------------------------------------------------------------
//
// On macOS + AAX: blits via CoreGraphics (CGImage → CALayer) to avoid Metal
// autorelease crashes with multiple editor windows.
// Otherwise: blits via wgpu fullscreen triangle.
//
// The whole section (window handler + Editor trait impl below) is
// gated behind the `cpu` feature. In `gpu`-only mode the editor is
// provided by `GpuEditor` (which wraps `BuiltinEditor::render_to`
// through `truce_gpu::WgpuBackend`) and these wgpu-blit details
// drop out of the compile.

#[cfg(feature = "cpu")]
fn create_wgpu_backend(window: &mut baseview::Window, phys_w: u32, phys_h: u32) -> BlitBackend {
    let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
    desc.backends = wgpu::Backends::PRIMARY;
    let instance = wgpu::Instance::new(desc);

    let surface = unsafe { crate::platform::create_wgpu_surface(&instance, window) }
        .expect("failed to create wgpu surface");

    let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
        power_preference: wgpu::PowerPreference::HighPerformance,
        compatible_surface: Some(&surface),
        force_fallback_adapter: false,
    }))
    .expect("no suitable GPU adapter");

    let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
        label: Some("truce-gui"),
        required_features: wgpu::Features::empty(),
        required_limits: wgpu::Limits::downlevel_defaults(),
        experimental_features: wgpu::ExperimentalFeatures::default(),
        memory_hints: wgpu::MemoryHints::Performance,
        trace: wgpu::Trace::Off,
    }))
    .expect("failed to create wgpu device");

    let caps = surface.get_capabilities(&adapter);
    let format = caps
        .formats
        .iter()
        .find(|f| f.is_srgb())
        .copied()
        .unwrap_or(caps.formats[0]);

    let surface_config = wgpu::SurfaceConfiguration {
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
        format,
        width: phys_w,
        height: phys_h,
        present_mode: wgpu::PresentMode::AutoVsync,
        desired_maximum_frame_latency: 2,
        alpha_mode: wgpu::CompositeAlphaMode::Auto,
        view_formats: vec![],
    };
    surface.configure(&device, &surface_config);

    // Blit texture matches the CPU pixmap, which is now sized at
    // physical pixels (see CpuBackend's scale handling). With texture
    // and surface at the same physical size, the full-screen-triangle
    // blit samples 1:1 - no stretch, no Retina blur.
    let blit = crate::blit::BlitPipeline::new(&device, format, phys_w, phys_h);

    BlitBackend {
        blit,
        surface_config,
        surface,
        queue,
        device,
    }
}

// Field-declaration order doubles as the implicit drop order Rust uses
// when this struct is dropped through the `Option<BlitBackend>` cell
// directly (e.g. when the host drops the editor without calling
// `close`). Children before parent: per-pipeline GPU resources, then
// the surface (releases swap chain / CAMetalLayer), then queue, then
// device. `BuiltinEditor::close` does the same thing explicitly via
// destructure - this declaration order keeps the implicit path safe
// too.
#[cfg(feature = "cpu")]
struct BlitBackend {
    blit: crate::blit::BlitPipeline,
    surface_config: wgpu::SurfaceConfiguration,
    surface: wgpu::Surface<'static>,
    queue: wgpu::Queue,
    device: wgpu::Device,
}

#[cfg(feature = "cpu")]
impl BlitBackend {
    /// Reconfigure the wgpu surface and blit texture for a new physical
    /// size. Used when `Editor::set_scale_factor` reports a host-driven
    /// DPI change - the logical editor size doesn't change, but the
    /// physical pixmap and surface need to grow / shrink to match.
    fn resize(&mut self, phys_w: u32, phys_h: u32) {
        self.surface_config.width = phys_w.max(1);
        self.surface_config.height = phys_h.max(1);
        self.surface.configure(&self.device, &self.surface_config);
        self.blit.resize(&self.device, phys_w, phys_h);
    }
}

/// Shared ownership of the blit backend between `BuiltinEditor` and the
/// `BuiltinWindowHandler` baseview hands us. Sharing lets the editor
/// drop the wgpu surface *before* it asks baseview to close the
/// `NSView`. Important on AAX where interleaving Metal teardown with
/// baseview's close sequence inside Pro Tools' outer autorelease pool
/// leaves stale refs in DFW container views.
#[cfg(feature = "cpu")]
type SharedBackend = Arc<Mutex<Option<BlitBackend>>>;

#[cfg(feature = "cpu")]
struct BuiltinWindowHandler<P: Params> {
    /// Raw pointer to the `BuiltinEditor` owned by the host. Valid only
    /// while `backend.lock()` returns `Some(_)`. `BuiltinEditor::close`
    /// takes the inner `Option<BlitBackend>` (atomically through this
    /// mutex) before returning, and the host can only drop the editor
    /// after `close()` returns - so any frame that holds the lock and
    /// finds the inner option `Some` is guaranteed the editor is still
    /// alive. The lock acquire is the synchronization point that keeps
    /// an in-flight `on_frame` from dereferencing this pointer after
    /// the host dropped the editor while baseview's render thread still
    /// had a callback queued. Only accessed from the GUI thread.
    editor: *mut BuiltinEditor<P>,
    backend: SharedBackend,
    /// Canonical baseview → `InputEvent` translator. Handles cursor
    /// tracking, double-click synthesis, and line→pixel scroll
    /// conversion once for everyone.
    translator: crate::interaction::BaseviewTranslator,
    /// Last scale we built the CPU pixmap + wgpu surface against.
    /// `on_frame` reads `editor.scale.get()` (via the raw ptr deref
    /// it already does) and compares; on divergence it rebuilds the
    /// pixmap and reconfigures the surface. Unlike egui / iced /
    /// slint we don't need a separate `EditorScale` clone on the
    /// handler - the editor is reachable through the same ptr that
    /// guards the lifecycle, so reading `editor.scale` is the
    /// canonical access path.
    last_applied_scale: f32,
}

// SAFETY: The raw pointer is only accessed from the GUI thread.
// baseview requires Send for WindowHandler.
#[cfg(feature = "cpu")]
unsafe impl<P: Params> Send for BuiltinWindowHandler<P> {}

#[cfg(feature = "cpu")]
impl<P: Params + 'static> baseview::WindowHandler for BuiltinWindowHandler<P> {
    fn on_frame(&mut self, _window: &mut baseview::Window) {
        // Lock the shared backend cell *before* deref'ing `self.editor`.
        // `BuiltinEditor::close` calls `drop(guard.take())` on the same
        // mutex before returning; the host then drops the editor. So
        // either we observe `Some(_)` here (close hasn't taken it yet,
        // editor still alive) or we observe `None` and return without
        // touching `self.editor`. Either way the deref below is sound.
        let Ok(mut guard) = self.backend.lock() else {
            return;
        };
        if guard.is_none() {
            // Editor already dropped the backend in its close path.
            // Nothing to do - baseview will tear us down next.
            return;
        }

        let editor = unsafe { &mut *self.editor };

        // Pick up scale changes that landed in the shared cell since
        // the last frame - either from a host callback (CLAP
        // `set_scale`, VST3 `IPlugViewContentScaleSupport`) or from
        // the OS-driven `Resized` path writing through `info.scale()`.
        // Logical w×h is fixed (resize is disallowed per
        // `Editor::can_resize`'s `false` default); only the
        // logical→physical ratio moves through here.
        if let Some(cur_scale) = editor.scale.take_change(&mut self.last_applied_scale) {
            let (lw, lh) = editor.size();
            let phys_w = crate::platform::to_physical_px(lw, f64::from(cur_scale));
            let phys_h = crate::platform::to_physical_px(lh, f64::from(cur_scale));
            editor.backend = CpuBackend::new(lw, lh, cur_scale);
            if let Some(backend) = guard.as_mut() {
                backend.resize(phys_w, phys_h);
            }
            editor.request_repaint();
        }

        update_interaction(editor);
        // Pick up host automation / preset recall that changed params
        // without going through the UI: flips the dirty bit so the
        // normal gate below still has the chance to short-circuit when
        // truly nothing moved.
        editor.detect_host_param_changes();
        editor.detect_meter_changes();
        if !editor.take_needs_repaint() {
            return;
        }
        editor.render();
        editor.stash_painted_values();

        if let Some(pixels) = editor.pixel_data() {
            let backend = guard
                .as_mut()
                .expect("guard was checked Some above and the lock is still held");
            let BlitBackend {
                device,
                queue,
                surface,
                blit,
                ..
            } = backend;
            blit.update(queue, pixels);
            let (wgpu::CurrentSurfaceTexture::Success(frame)
            | wgpu::CurrentSurfaceTexture::Suboptimal(frame)) = surface.get_current_texture()
            else {
                return;
            };
            let view = frame
                .texture
                .create_view(&wgpu::TextureViewDescriptor::default());
            let mut encoder =
                device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
            blit.render(&mut encoder, &view);
            queue.submit(std::iter::once(encoder.finish()));
            frame.present();
        }
    }

    fn on_event(
        &mut self,
        window: &mut baseview::Window,
        event: baseview::Event,
    ) -> baseview::EventStatus {
        // `window` is only read on Windows (focus-on-click below);
        // discard explicitly on other platforms so the lint stays quiet.
        #[cfg(not(target_os = "windows"))]
        let _ = &window;

        if let baseview::Event::Mouse(baseview::MouseEvent::ButtonPressed {
            button: baseview::MouseButton::Left,
            ..
        }) = &event
        {
            // WS_CHILD plugin windows don't receive WM_KEYDOWN
            // until focused; baseview doesn't SetFocus on click,
            // so we do it here. Without this, text-edit widgets
            // never see keystrokes (the DAW keeps eating them for
            // transport shortcuts).
            #[cfg(target_os = "windows")]
            {
                if !window.has_focus() {
                    window.focus();
                }
            }
        }

        // Lock-then-check-then-deref pattern, same as `on_frame` -
        // the backend cell is the synchronization point with
        // `BuiltinEditor::close`. If the cell is `None`, the editor
        // pointer is no longer guaranteed valid and we must not deref.
        let Ok(guard) = self.backend.lock() else {
            return baseview::EventStatus::Ignored;
        };
        if guard.is_none() {
            return baseview::EventStatus::Ignored;
        }

        match event {
            baseview::Event::Mouse(_) => {
                let Some(input) = self.translator.translate(&event) else {
                    return baseview::EventStatus::Ignored;
                };
                let editor = unsafe { &mut *self.editor };
                editor.dispatch_events(&[input]);
                baseview::EventStatus::Captured
            }
            baseview::Event::Window(baseview::WindowEvent::Resized(info)) => {
                // Logical resize is disallowed (`Editor::can_resize` is
                // `false`), but the OS-reported *scale* is authoritative:
                // on Windows the parent HWND queried at `open()` time
                // can report a different DPI than the child surface
                // baseview actually creates, and on every platform
                // dragging across a monitor boundary needs to land on
                // the new DPI. Write through to the shared cell so
                // `on_frame`'s `take_change` path rebuilds the CPU
                // pixmap and reconfigures the wgpu surface at the new
                // scale; logical w×h stays put. Matches the iced /
                // egui / slint backends' Resized handlers.
                let editor = unsafe { &mut *self.editor };
                editor.scale.set(info.scale());
                crate::platform::note_linux_scale_factor(info.scale());
                baseview::EventStatus::Ignored
            }
            _ => baseview::EventStatus::Ignored,
        }
    }
}

// ---------------------------------------------------------------------------
// Editor trait implementation
// ---------------------------------------------------------------------------

/// Resolve widget type: explicit override > auto-detect from param range.
fn resolve_widget_type<P: Params>(
    widget: Option<crate::layout::WidgetKind>,
    param_id: u32,
    params: &P,
) -> widgets::WidgetType {
    match widget {
        Some(crate::layout::WidgetKind::Knob) => widgets::WidgetType::Knob,
        Some(crate::layout::WidgetKind::Slider) => widgets::WidgetType::Slider,
        Some(crate::layout::WidgetKind::Toggle) => widgets::WidgetType::Toggle,
        Some(crate::layout::WidgetKind::Selector) => widgets::WidgetType::Selector,
        Some(crate::layout::WidgetKind::Dropdown) => widgets::WidgetType::Dropdown,
        Some(crate::layout::WidgetKind::Meter) => widgets::WidgetType::Meter,
        Some(crate::layout::WidgetKind::XYPad) => widgets::WidgetType::XYPad,
        None => {
            let param_info = params
                .param_infos()
                .iter()
                .find(|i| i.id == param_id)
                .copied();
            match param_info.as_ref().map(|i| &i.range) {
                Some(truce_params::ParamRange::Discrete { min: 0, max: 1 }) => {
                    widgets::WidgetType::Toggle
                }
                Some(truce_params::ParamRange::Enum { .. }) => widgets::WidgetType::Dropdown,
                _ => widgets::WidgetType::Knob,
            }
        }
    }
}

#[cfg(feature = "cpu")]
impl<P: Params + 'static> Editor for BuiltinEditor<P> {
    fn size(&self) -> (u32, u32) {
        (self.layout.width(), self.layout.height())
    }

    fn state_changed(&mut self) {
        // Preset recall / undo / session load: params moved without
        // going through the UI, so force the next idle tick to repaint.
        self.request_repaint();
    }

    fn open(&mut self, parent: RawWindowHandle, context: PluginContext) {
        let (w, h) = self.size();
        // Refresh the shared scale from the parent window - on macOS
        // this is the live `[NSWindow backingScaleFactor]`, on
        // Windows the per-monitor DPI from the parent HWND. Any
        // `set_scale_factor` the host issues after open will overwrite
        // through the same shared cell.
        self.scale
            .set(crate::platform::query_backing_scale(&parent));
        let scale = self.scale.get();
        let scale_f32 = self.scale.get_f32();
        self.backend = CpuBackend::new(w, h, scale_f32);
        self.context = Some(context);

        // Build interaction regions
        match &self.layout {
            Layout::Rows(pl) => self.interaction.build_regions(pl),
            Layout::Grid(gl) => self.interaction.build_regions_grid(gl),
        }

        // Render initial frame and flag dirty so the first `on_frame`
        // blit also runs (the construction default is `false` because a
        // not-yet-opened editor has nothing to paint to).
        self.render();
        self.request_repaint();

        let (lw, lh) = (f64::from(w), f64::from(h));
        let phys_w = crate::platform::to_physical_px(w, scale);
        let phys_h = crate::platform::to_physical_px(h, scale);

        let options = baseview::WindowOpenOptions {
            title: String::from("truce"),
            size: baseview::Size::new(lw, lh),
            scale: baseview::WindowScalePolicy::SystemScaleFactor,
        };

        let parent_wrapper = crate::platform::ParentWindow(parent);
        let editor_addr = ptr::from_mut::<BuiltinEditor<P>>(self) as usize;

        // Shared backend cell: the editor keeps one Arc and baseview's
        // window handler gets the other. At close time the editor
        // takes the inner Option and drops it *before* asking baseview
        // to tear down the NSView.
        let shared_backend: SharedBackend = Arc::new(Mutex::new(None));
        self.blit_backend = Some(shared_backend.clone());
        let shared_for_handler = shared_backend;

        let window = baseview::Window::open_parented(
            &parent_wrapper,
            options,
            move |window: &mut baseview::Window| {
                let mut backend = create_wgpu_backend(window, phys_w, phys_h);

                // Render + present an initial frame synchronously, before
                // baseview shows the window. Without this, the window briefly
                // displays whatever garbage is in the surface buffer until the
                // first `on_frame` tick - especially noticeable on VST2
                // (Windows), where `effEditOpen` creates and shows the window
                // in one call.
                let editor = unsafe { &mut *(editor_addr as *mut BuiltinEditor<P>) };
                editor.render();
                if let Some(pixels) = editor.pixel_data() {
                    let BlitBackend {
                        device,
                        queue,
                        surface,
                        blit,
                        ..
                    } = &mut backend;
                    blit.update(queue, pixels);
                    if let wgpu::CurrentSurfaceTexture::Success(frame)
                    | wgpu::CurrentSurfaceTexture::Suboptimal(frame) =
                        surface.get_current_texture()
                    {
                        let view = frame
                            .texture
                            .create_view(&wgpu::TextureViewDescriptor::default());
                        let mut encoder =
                            device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                                label: None,
                            });
                        blit.render(&mut encoder, &view);
                        queue.submit(std::iter::once(encoder.finish()));
                        frame.present();
                    }
                }

                // Publish the backend into the shared cell. If the
                // editor has already been asked to close (very
                // unlikely race - only if close fires before baseview
                // calls our build closure), the None-check on the
                // mutex side will simply replace Some(None) → Some
                // and everything drops at the usual time.
                if let Ok(mut guard) = shared_for_handler.lock() {
                    *guard = Some(backend);
                }

                BuiltinWindowHandler {
                    editor: editor_addr as *mut BuiltinEditor<P>,
                    backend: shared_for_handler.clone(),
                    translator: crate::interaction::BaseviewTranslator::default(),
                    last_applied_scale: scale_f32,
                }
            },
        );

        self.window = Some(window);
    }

    fn set_scale_factor(&mut self, factor: f64) {
        // Write to the shared cell; the baseview handler picks up the
        // change on its next frame and rebuilds the CPU pixmap +
        // reconfigures the wgpu surface. The trait's default no-op
        // would silently swallow host scale changes here.
        self.scale.set(factor);
    }

    fn close(&mut self) {
        // On macOS, wrap the teardown in an autoreleasepool so
        // anything baseview / wgpu / AppKit autoreleases during the
        // view's cleanup drains here rather than escaping into the
        // host's outer pool. AAX / Pro Tools is the canonical host
        // that walks back through residual responders before the
        // pool drains, surfacing use-after-free crashes.
        #[cfg(target_os = "macos")]
        let pool = unsafe {
            unsafe extern "C" {
                fn objc_autoreleasePoolPush() -> *mut std::ffi::c_void;
            }
            objc_autoreleasePoolPush()
        };

        // Drop the wgpu surface (CAMetalLayer, MTLDevice, command
        // queue, etc.) before asking baseview to release the NSView.
        // Keeps the Metal teardown order deterministic. The destructure
        // makes the drop order explicit rather than depending on
        // `BlitPipeline`'s field-declaration order. Order: per-pipeline
        // GPU resources first (textures, bind groups, sampler), then
        // the surface (releases the swap chain / CAMetalLayer), then
        // queue, then device last - children before parent.
        if let Some(shared) = self.blit_backend.take()
            && let Ok(mut guard) = shared.lock()
            && let Some(backend) = guard.take()
        {
            let BlitBackend {
                blit,
                surface,
                surface_config,
                queue,
                device,
            } = backend;
            drop(surface_config);
            drop(blit);
            drop(surface);
            drop(queue);
            drop(device);
        }

        if let Some(mut window) = self.window.take() {
            window.close();
        }
        self.context = None;
        self.backend = None;

        #[cfg(target_os = "macos")]
        unsafe {
            unsafe extern "C" {
                fn objc_autoreleasePoolPop(pool: *mut std::ffi::c_void);
            }
            objc_autoreleasePoolPop(pool);
        }
    }

    fn idle(&mut self) {
        // baseview drives `on_frame` via its internal timer; idle is
        // only meaningful for the headless/standalone case where the
        // caller wants a render cycle to pull pixel data out.
        if self.window.is_none() {
            self.render();
        }
    }

    fn screenshot(
        &mut self,
        _params: Arc<dyn truce_params::Params>,
    ) -> Option<(Vec<u8>, u32, u32)> {
        // Headless render of the widget tree into a fresh
        // `CpuBackend` at the live content scale. Mirrors
        // `GpuEditor::screenshot`'s shape: same `render_to` call
        // path, same physical-size rounding so reference PNGs baked
        // on either backend match dimensions exactly. Used by
        // `truce_test::assert_screenshot::<P>()`.
        let (lw, lh) = self.size();
        let scale = self.scale.get_f32();
        let mut backend = CpuBackend::new(lw, lh, scale)?;
        self.render_to(&mut backend);
        let pixels = backend.data().to_vec();
        let (phys_w, phys_h) = (backend.width(), backend.height());
        Some((pixels, phys_w, phys_h))
    }
}

#[cfg(feature = "cpu")]
impl<P: Params + 'static> Drop for BuiltinEditor<P> {
    fn drop(&mut self) {
        // The baseview `WindowHandle` does not cancel the macOS frame
        // timer when it drops, and the NSView keeps its own strong
        // `Rc<WindowState>`, so the timer keeps firing `on_frame`
        // against the handler's raw `*mut BuiltinEditor`. If the host
        // drops us without calling `Editor::close` first, that pointer
        // dangles the moment our fields (`scale`, the shared backend)
        // are freed - the next tick deref'd freed memory and crashes in
        // `EditorScale::take_change`. Run the same teardown here so the
        // timer is always cancelled before our fields go away; it is
        // idempotent via the `Option::take`s, so a prior `close` makes
        // this a no-op.
        Editor::close(self);
    }
}

#[cfg(test)]
mod tests {
    // Layout-coordinate assertions compare stored anchor values for
    // bit-exact equality (no arithmetic between them).
    #![allow(clippy::float_cmp, clippy::cast_precision_loss)]

    use super::*;
    use crate::layout::{GridLayout, GridWidget, Layout, section, widgets};
    use crate::widgets::WidgetType;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU64, Ordering};
    use truce_params::{ParamFlags, ParamInfo, ParamRange, ParamUnit, ParamValueKind, Params};

    // -- Mock Params with one enum param (4 options) and one float --

    struct TestParams {
        values: [AtomicU64; 2],
    }

    impl TestParams {
        fn new() -> Self {
            Self {
                values: [
                    AtomicU64::new(0.0f64.to_bits()),
                    AtomicU64::new(0.0f64.to_bits()),
                ],
            }
        }
    }

    impl truce_params::__private::Sealed for TestParams {}
    impl Params for TestParams {
        fn param_infos(&self) -> Vec<ParamInfo> {
            vec![
                ParamInfo {
                    id: 0,
                    name: "Mode",
                    short_name: "Mode",
                    group: "",
                    range: ParamRange::Enum { count: 4 },
                    default_plain: 0.0,
                    flags: ParamFlags::AUTOMATABLE,
                    unit: ParamUnit::None,
                    kind: ParamValueKind::Enum,
                },
                ParamInfo {
                    id: 1,
                    name: "Gain",
                    short_name: "Gain",
                    group: "",
                    range: ParamRange::Linear { min: 0.0, max: 1.0 },
                    default_plain: 0.5,
                    flags: ParamFlags::AUTOMATABLE,
                    unit: ParamUnit::None,
                    kind: ParamValueKind::Float,
                },
            ]
        }

        fn count(&self) -> usize {
            2
        }

        fn get_normalized(&self, id: u32) -> Option<f64> {
            self.values
                .get(id as usize)
                .map(|v| f64::from_bits(v.load(Ordering::Relaxed)))
        }

        fn set_normalized(&self, id: u32, value: f64) {
            if let Some(v) = self.values.get(id as usize) {
                v.store(value.to_bits(), Ordering::Relaxed);
            }
        }

        fn get_plain(&self, id: u32) -> Option<f64> {
            let norm = self.get_normalized(id)?;
            let info = self.param_infos().iter().find(|i| i.id == id).copied()?;
            Some(info.range.denormalize(norm))
        }

        fn set_plain(&self, id: u32, value: f64) {
            if let Some(info) = self.param_infos().iter().find(|i| i.id == id).copied() {
                self.set_normalized(id, info.range.normalize(value));
            }
        }

        fn format_value(&self, _id: u32, value: f64) -> Option<String> {
            Some(format!("{value:.0}"))
        }

        fn parse_value(&self, _id: u32, _text: &str) -> Option<f64> {
            None
        }
        fn snap_smoothers(&self) {}
        fn set_sample_rate(&self, _: f64) {}

        fn collect_values(&self) -> (Vec<u32>, Vec<f64>) {
            let ids = vec![0, 1];
            let vals: Vec<f64> = ids
                .iter()
                .map(|&id| self.get_plain(id).unwrap_or(0.0))
                .collect();
            (ids, vals)
        }

        fn restore_values(&self, values: &[(u32, f64)]) {
            for &(id, val) in values {
                self.set_plain(id, val);
            }
        }
    }

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

    // -- Helpers --

    /// Build a `BuiltinEditor` with a dropdown at position 0 and a knob at position 1.
    fn make_editor() -> BuiltinEditor<TestParams> {
        let params = Arc::new(TestParams::new());
        let layout = GridLayout::build(vec![widgets(vec![
            GridWidget::dropdown(0u32, "Mode"),
            GridWidget::knob(1u32, "Gain"),
        ])]);
        let mut editor = BuiltinEditor::new_grid(params, layout);
        // Build interaction regions (normally done in open/render)
        if let Layout::Grid(ref gl) = editor.layout {
            editor.interaction.build_regions_grid(gl);
            for (idx, gw) in gl.widgets.iter().enumerate() {
                if let Some(region) = editor.interaction.knob_regions.get_mut(idx) {
                    region.widget_type =
                        resolve_widget_type(gw.widget, gw.param_id, &*editor.params);
                }
            }
        }
        // Render once to populate dropdown_anchor_y
        editor.render();
        editor
    }

    /// Build an editor with section breaks to test anchor stability.
    fn make_editor_with_sections() -> BuiltinEditor<TestParams> {
        let params = Arc::new(TestParams::new());
        let layout = GridLayout::build(vec![
            section(
                "SECTION A",
                vec![
                    GridWidget::knob(1u32, "Gain"),
                    GridWidget::knob(1u32, "Gain 2"),
                ],
            ),
            section(
                "SECTION B",
                vec![
                    GridWidget::dropdown(0u32, "Mode"),
                    GridWidget::knob(1u32, "Gain 3"),
                ],
            ),
        ]);
        let mut editor = BuiltinEditor::new_grid(params, layout);
        if let Layout::Grid(ref gl) = editor.layout {
            editor.interaction.build_regions_grid(gl);
            for (idx, gw) in gl.widgets.iter().enumerate() {
                if let Some(region) = editor.interaction.knob_regions.get_mut(idx) {
                    region.widget_type =
                        resolve_widget_type(gw.widget, gw.param_id, &*editor.params);
                }
            }
        }
        editor.render();
        editor
    }

    /// Find the center of the first dropdown widget's region.
    fn dropdown_center(editor: &BuiltinEditor<TestParams>) -> (f32, f32) {
        let region = editor
            .interaction
            .knob_regions
            .iter()
            .find(|r| r.widget_type == WidgetType::Dropdown)
            .expect("no dropdown in layout");
        (region.x + region.w / 2.0, region.y + region.h / 2.0)
    }

    // -- Tests: dropdown close-on-reclick --

    #[test]
    fn dropdown_click_opens() {
        let mut editor = make_editor();
        let (dx, dy) = dropdown_center(&editor);

        editor.on_mouse_down(dx, dy);
        assert!(editor.interaction.dropdown_is_open());
    }

    #[test]
    fn dropdown_click_toggles_closed() {
        let mut editor = make_editor();
        let (dx, dy) = dropdown_center(&editor);

        // Open
        editor.on_mouse_down(dx, dy);
        editor.on_mouse_up(dx, dy);
        assert!(editor.interaction.dropdown_is_open());

        // Click same button again - should close, not reopen
        editor.on_mouse_down(dx, dy);
        assert!(!editor.interaction.dropdown_is_open());
    }

    #[test]
    fn dropdown_click_outside_closes() {
        let mut editor = make_editor();
        let (dx, dy) = dropdown_center(&editor);

        editor.on_mouse_down(dx, dy);
        editor.on_mouse_up(dx, dy);
        assert!(editor.interaction.dropdown_is_open());

        // Click far away
        editor.on_mouse_down(0.0, 0.0);
        assert!(!editor.interaction.dropdown_is_open());
    }

    #[test]
    fn dropdown_click_option_selects_and_closes() {
        let mut editor = make_editor();
        let (dx, dy) = dropdown_center(&editor);

        editor.on_mouse_down(dx, dy);
        editor.on_mouse_up(dx, dy);
        assert!(editor.interaction.dropdown_is_open());

        // Click the second option (index 1) inside the popup
        let dd = editor.interaction.dropdown.as_ref().unwrap();
        let (px, py, _, _) = dd.popup_rect;
        let item_h = 18.0f32;
        let padding = 4.0f32;
        let option_y = py + padding + item_h + item_h / 2.0; // middle of second item

        // Touch model: down then up at the same point commits the
        // option under the release point. (Down alone starts a
        // popup-drag - the up handler decides commit-vs-scroll.)
        editor.on_mouse_down(px + 10.0, option_y);
        editor.on_mouse_up(px + 10.0, option_y);

        assert!(!editor.interaction.dropdown_is_open());
        // Enum{count:4} → step_count=3 → 4 options. Index 1 → norm = 1/3
        let norm = editor.params.get_normalized(0).unwrap();
        let expected = 1.0 / 3.0;
        assert!(
            (norm - expected).abs() < 0.01,
            "expected {expected:.4}, got {norm}"
        );
    }

    // -- Tests: dropdown anchor positioning --

    #[test]
    fn dropdown_anchor_set_after_render() {
        let editor = make_editor();
        let region = editor
            .interaction
            .knob_regions
            .iter()
            .find(|r| r.widget_type == WidgetType::Dropdown)
            .unwrap();

        // Anchor should be within the widget region (below y, above y+h)
        assert!(
            region.dropdown_anchor_y > region.y,
            "anchor {} should be below region.y {}",
            region.dropdown_anchor_y,
            region.y
        );
        assert!(
            region.dropdown_anchor_y < region.y + region.h,
            "anchor {} should be above region bottom {}",
            region.dropdown_anchor_y,
            region.y + region.h
        );
    }

    #[test]
    fn dropdown_popup_uses_anchor() {
        let mut editor = make_editor();
        let (dx, dy) = dropdown_center(&editor);

        editor.on_mouse_down(dx, dy);
        editor.on_mouse_up(dx, dy);

        let dd = editor.interaction.dropdown.as_ref().unwrap();
        let region = &editor.interaction.knob_regions[dd.region_idx];

        // popup_y must equal the stored anchor - popup always
        // anchors directly below the button (scrolls on tight
        // editors rather than relocating).
        assert_eq!(dd.popup_rect.1, region.dropdown_anchor_y);
    }

    #[test]
    fn dropdown_anchor_gap_stable_with_sections() {
        let editor_plain = make_editor();
        let editor_sections = make_editor_with_sections();

        let r_plain = editor_plain
            .interaction
            .knob_regions
            .iter()
            .find(|r| r.widget_type == WidgetType::Dropdown)
            .unwrap();
        let r_sections = editor_sections
            .interaction
            .knob_regions
            .iter()
            .find(|r| r.widget_type == WidgetType::Dropdown)
            .unwrap();

        // The gap from widget vertical center to anchor should be identical
        // regardless of section offsets shifting the absolute Y position.
        let gap_plain = r_plain.dropdown_anchor_y - (r_plain.y + r_plain.h / 2.0);
        let gap_sections = r_sections.dropdown_anchor_y - (r_sections.y + r_sections.h / 2.0);
        assert!(
            (gap_plain - gap_sections).abs() < 0.1,
            "gap_plain={gap_plain}, gap_sections={gap_sections}"
        );
    }

    // -- Mock Params with a large enum (20 options) for overflow/scroll tests --

    struct ManyOptionParams {
        values: [AtomicU64; 2],
    }

    impl ManyOptionParams {
        fn new() -> Self {
            Self {
                values: [
                    AtomicU64::new(0.0f64.to_bits()),
                    AtomicU64::new(0.0f64.to_bits()),
                ],
            }
        }
    }

    impl truce_params::__private::Sealed for ManyOptionParams {}
    impl Params for ManyOptionParams {
        fn param_infos(&self) -> Vec<ParamInfo> {
            vec![
                ParamInfo {
                    id: 0,
                    name: "Note",
                    short_name: "Note",
                    group: "",
                    range: ParamRange::Enum { count: 20 },
                    default_plain: 0.0,
                    flags: ParamFlags::AUTOMATABLE,
                    unit: ParamUnit::None,
                    kind: ParamValueKind::Enum,
                },
                ParamInfo {
                    id: 1,
                    name: "Gain",
                    short_name: "Gain",
                    group: "",
                    range: ParamRange::Linear { min: 0.0, max: 1.0 },
                    default_plain: 0.5,
                    flags: ParamFlags::AUTOMATABLE,
                    unit: ParamUnit::None,
                    kind: ParamValueKind::Float,
                },
            ]
        }

        fn count(&self) -> usize {
            2
        }

        fn get_normalized(&self, id: u32) -> Option<f64> {
            self.values
                .get(id as usize)
                .map(|v| f64::from_bits(v.load(Ordering::Relaxed)))
        }

        fn set_normalized(&self, id: u32, value: f64) {
            if let Some(v) = self.values.get(id as usize) {
                v.store(value.to_bits(), Ordering::Relaxed);
            }
        }

        fn get_plain(&self, id: u32) -> Option<f64> {
            let norm = self.get_normalized(id)?;
            let info = self.param_infos().iter().find(|i| i.id == id).copied()?;
            Some(info.range.denormalize(norm))
        }

        fn set_plain(&self, id: u32, value: f64) {
            if let Some(info) = self.param_infos().iter().find(|i| i.id == id).copied() {
                self.set_normalized(id, info.range.normalize(value));
            }
        }

        fn format_value(&self, _id: u32, value: f64) -> Option<String> {
            Some(format!("{value:.0}"))
        }

        fn parse_value(&self, _id: u32, _text: &str) -> Option<f64> {
            None
        }
        fn snap_smoothers(&self) {}
        fn set_sample_rate(&self, _: f64) {}

        fn collect_values(&self) -> (Vec<u32>, Vec<f64>) {
            let ids = vec![0, 1];
            let vals: Vec<f64> = ids
                .iter()
                .map(|&id| self.get_plain(id).unwrap_or(0.0))
                .collect();
            (ids, vals)
        }

        fn restore_values(&self, values: &[(u32, f64)]) {
            for &(id, val) in values {
                self.set_plain(id, val);
            }
        }
    }

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

    // -- Additional helpers --

    /// Build an editor with a dropdown in the last row (near the window bottom).
    fn make_editor_bottom_dropdown() -> BuiltinEditor<TestParams> {
        let params = Arc::new(TestParams::new());
        // 3 rows of 2, dropdown in the last row (row 2)
        let layout = GridLayout::build(vec![widgets(vec![
            GridWidget::knob(1u32, "K1"),
            GridWidget::knob(1u32, "K2"),
            GridWidget::knob(1u32, "K3"),
            GridWidget::knob(1u32, "K4"),
            GridWidget::dropdown(0u32, "Mode"),
            GridWidget::knob(1u32, "K5"),
        ])])
        .with_cols(2);
        let mut editor = BuiltinEditor::new_grid(params, layout);
        if let Layout::Grid(ref gl) = editor.layout {
            editor.interaction.build_regions_grid(gl);
            for (idx, gw) in gl.widgets.iter().enumerate() {
                if let Some(region) = editor.interaction.knob_regions.get_mut(idx) {
                    region.widget_type =
                        resolve_widget_type(gw.widget, gw.param_id, &*editor.params);
                }
            }
        }
        editor.render();
        editor
    }

    /// Build an editor with two dropdowns side by side.
    fn make_editor_two_dropdowns() -> BuiltinEditor<TestParams> {
        let params = Arc::new(TestParams::new());
        let layout = GridLayout::build(vec![widgets(vec![
            GridWidget::dropdown(0u32, "Mode A"),
            GridWidget::dropdown(0u32, "Mode B"),
        ])]);
        let mut editor = BuiltinEditor::new_grid(params, layout);
        if let Layout::Grid(ref gl) = editor.layout {
            editor.interaction.build_regions_grid(gl);
            for (idx, gw) in gl.widgets.iter().enumerate() {
                if let Some(region) = editor.interaction.knob_regions.get_mut(idx) {
                    region.widget_type =
                        resolve_widget_type(gw.widget, gw.param_id, &*editor.params);
                }
            }
        }
        editor.render();
        editor
    }

    /// Build an editor with a 20-option dropdown for scroll testing.
    fn make_editor_many_options() -> BuiltinEditor<ManyOptionParams> {
        let params = Arc::new(ManyOptionParams::new());
        let layout = GridLayout::build(vec![widgets(vec![
            GridWidget::dropdown(0u32, "Note"),
            GridWidget::knob(1u32, "Gain"),
        ])]);
        let mut editor = BuiltinEditor::new_grid(params, layout);
        if let Layout::Grid(ref gl) = editor.layout {
            editor.interaction.build_regions_grid(gl);
            for (idx, gw) in gl.widgets.iter().enumerate() {
                if let Some(region) = editor.interaction.knob_regions.get_mut(idx) {
                    region.widget_type =
                        resolve_widget_type(gw.widget, gw.param_id, &*editor.params);
                }
            }
        }
        editor.render();
        editor
    }

    fn dropdown_center_many(editor: &BuiltinEditor<ManyOptionParams>) -> (f32, f32) {
        let region = editor
            .interaction
            .knob_regions
            .iter()
            .find(|r| r.widget_type == WidgetType::Dropdown)
            .expect("no dropdown in layout");
        (region.x + region.w / 2.0, region.y + region.h / 2.0)
    }

    // -- Tests: dropdown overflow/clipping --

    #[test]
    fn dropdown_anchors_below_button_scrolls_when_tight() {
        let mut editor = make_editor_bottom_dropdown();
        let (dx, dy) = {
            let region = editor
                .interaction
                .knob_regions
                .iter()
                .find(|r| r.widget_type == WidgetType::Dropdown)
                .unwrap();
            (region.x + region.w / 2.0, region.y + region.h / 2.0)
        };

        editor.on_mouse_down(dx, dy);
        editor.on_mouse_up(dx, dy);
        assert!(editor.interaction.dropdown_is_open());

        let dd = editor.interaction.dropdown.as_ref().unwrap();
        let region = &editor.interaction.knob_regions[dd.region_idx];
        let (_, popup_y, _, popup_h) = dd.popup_rect;
        let window_h = editor.layout.height() as f32;

        // Popup anchors at the button's bottom - never shifts up
        // and never flips above. If the full option list doesn't
        // fit between the anchor and the window bottom, the popup
        // scrolls instead of relocating away from the tap target.
        assert_eq!(
            popup_y, region.dropdown_anchor_y,
            "popup must anchor at dropdown_anchor_y, got popup_y={popup_y}"
        );
        // Popup never extends past the window bottom.
        assert!(
            popup_y + popup_h <= window_h + 1.0,
            "popup bottom {} exceeds window height {window_h}",
            popup_y + popup_h
        );
    }

    #[test]
    fn dropdown_clamps_horizontal_near_right_edge() {
        let mut editor = make_editor_two_dropdowns();
        // The second dropdown is in column 1 (right side)
        let region = &editor.interaction.knob_regions[1];
        assert_eq!(region.widget_type, WidgetType::Dropdown);
        let dx = region.x + region.w / 2.0;
        let dy = region.y + region.h / 2.0;

        editor.on_mouse_down(dx, dy);
        editor.on_mouse_up(dx, dy);
        assert!(editor.interaction.dropdown_is_open());

        let dd = editor.interaction.dropdown.as_ref().unwrap();
        let (popup_x, _, popup_w, _) = dd.popup_rect;
        let window_w = editor.layout.width() as f32;

        assert!(
            popup_x + popup_w <= window_w + 1.0,
            "popup right edge {} exceeds window width {window_w}",
            popup_x + popup_w
        );
        assert!(popup_x >= 0.0, "popup_x={popup_x} is negative");
    }

    #[test]
    fn dropdown_scroll_long_list() {
        let mut editor = make_editor_many_options();
        let (dx, dy) = dropdown_center_many(&editor);

        editor.on_mouse_down(dx, dy);
        editor.on_mouse_up(dx, dy);
        assert!(editor.interaction.dropdown_is_open());

        let dd = editor.interaction.dropdown.as_ref().unwrap();
        // 20-option enum → step_count = 19 → 19 options
        assert!(
            dd.options.len() > dd.visible_count,
            "expected scroll: {} options, {} visible",
            dd.options.len(),
            dd.visible_count
        );
        assert_eq!(dd.scroll_offset, 0);
    }

    #[test]
    fn dropdown_scroll_clamps_to_bounds() {
        let mut editor = make_editor_many_options();
        let (dx, dy) = dropdown_center_many(&editor);

        editor.on_mouse_down(dx, dy);
        editor.on_mouse_up(dx, dy);

        // Scroll up past the top - should stay at 0
        editor.interaction.dropdown_scroll(-10);
        assert_eq!(
            editor.interaction.dropdown.as_ref().unwrap().scroll_offset,
            0
        );

        // Scroll down past the bottom - should clamp
        editor.interaction.dropdown_scroll(1000);
        let dd = editor.interaction.dropdown.as_ref().unwrap();
        let max_offset = dd.options.len().saturating_sub(dd.visible_count);
        assert_eq!(dd.scroll_offset, max_offset);
    }

    #[test]
    fn dropdown_selected_item_visible_on_open() {
        let mut editor = make_editor_many_options();
        // Set the value to option 15 out of 19 (normalized = 15/18)
        editor.params.set_normalized(0, 15.0 / 18.0);

        let (dx, dy) = dropdown_center_many(&editor);
        editor.on_mouse_down(dx, dy);
        editor.on_mouse_up(dx, dy);

        let dd = editor.interaction.dropdown.as_ref().unwrap();
        let selected = dd.selected;
        // The selected item should be within the visible window
        assert!(
            selected >= dd.scroll_offset && selected < dd.scroll_offset + dd.visible_count,
            "selected={selected} not in visible range {}..{}",
            dd.scroll_offset,
            dd.scroll_offset + dd.visible_count
        );
    }

    #[test]
    fn dropdown_scroll_then_select_correct_index() {
        let mut editor = make_editor_many_options();
        let (dx, dy) = dropdown_center_many(&editor);

        editor.on_mouse_down(dx, dy);
        editor.on_mouse_up(dx, dy);

        // Scroll down by 3
        editor.interaction.dropdown_scroll(3);
        assert_eq!(
            editor.interaction.dropdown.as_ref().unwrap().scroll_offset,
            3
        );

        // Click the second visible item (local index 1 → absolute index 4)
        let dd = editor.interaction.dropdown.as_ref().unwrap();
        let (px, py, _, _) = dd.popup_rect;
        let item_h = 18.0f32;
        let padding = 4.0f32;
        let click_y = py + padding + item_h + item_h / 2.0; // middle of second visible item

        editor.on_mouse_down(px + 10.0, click_y);
        editor.on_mouse_up(px + 10.0, click_y);

        assert!(!editor.interaction.dropdown_is_open());
        // Absolute index = scroll_offset(3) + local(1) = 4
        // 20 options → norm = 4/19
        let norm = editor.params.get_normalized(0).unwrap();
        let expected = 4.0 / 19.0;
        assert!(
            (norm - expected).abs() < 0.01,
            "expected {expected:.4}, got {norm:.4}"
        );
    }

    #[test]
    fn dropdown_click_different_dropdown_closes_first() {
        let mut editor = make_editor_two_dropdowns();
        let r0 = &editor.interaction.knob_regions[0];
        let r1 = &editor.interaction.knob_regions[1];
        let (ax, ay) = (r0.x + r0.w / 2.0, r0.y + r0.h / 2.0);
        let (bx, by) = (r1.x + r1.w / 2.0, r1.y + r1.h / 2.0);

        // Open dropdown A
        editor.on_mouse_down(ax, ay);
        editor.on_mouse_up(ax, ay);
        assert!(editor.interaction.dropdown_is_open());
        assert_eq!(editor.interaction.dropdown.as_ref().unwrap().region_idx, 0);

        // Click dropdown B - should close A and open B
        editor.on_mouse_down(bx, by);
        editor.on_mouse_up(bx, by);
        assert!(editor.interaction.dropdown_is_open());
        assert_eq!(editor.interaction.dropdown.as_ref().unwrap().region_idx, 1);
    }

    #[test]
    fn dropdown_hover_tracks_correct_option() {
        let mut editor = make_editor();
        let (dx, dy) = dropdown_center(&editor);

        editor.on_mouse_down(dx, dy);
        editor.on_mouse_up(dx, dy);

        let dd = editor.interaction.dropdown.as_ref().unwrap();
        let (px, py, pw, _) = dd.popup_rect;
        let item_h = 18.0f32;
        let padding = 4.0f32;
        let last_visible = dd.visible_count - 1;

        // Hover over the last visible item
        let hover_y = py + padding + last_visible as f32 * item_h + item_h / 2.0;
        editor.on_mouse_moved(px + pw / 2.0, hover_y);

        let dd = editor.interaction.dropdown.as_ref().unwrap();
        assert_eq!(
            dd.hover_option,
            Some(last_visible),
            "expected hover on last visible option"
        );

        // Move outside the popup
        editor.on_mouse_moved(0.0, 0.0);
        let dd = editor.interaction.dropdown.as_ref().unwrap();
        assert_eq!(dd.hover_option, None, "hover should clear outside popup");
    }

    #[test]
    fn dropdown_popup_within_window_bounds() {
        // Verify popup never exceeds window in any direction
        let mut editor = make_editor();
        let (dx, dy) = dropdown_center(&editor);

        editor.on_mouse_down(dx, dy);
        editor.on_mouse_up(dx, dy);

        let dd = editor.interaction.dropdown.as_ref().unwrap();
        let (px, py, pw, ph) = dd.popup_rect;
        let window_w = editor.layout.width() as f32;
        let window_h = editor.layout.height() as f32;

        assert!(px >= 0.0, "popup left edge {px} < 0");
        assert!(py >= 0.0, "popup top edge {py} < 0");
        assert!(
            px + pw <= window_w + 1.0,
            "popup right {} > window {window_w}",
            px + pw
        );
        assert!(
            py + ph <= window_h + 1.0,
            "popup bottom {} > window {window_h}",
            py + ph
        );
    }
}