truce-gui-types 0.48.7

Lightweight GUI types for truce - layout, render trait, widget regions. No rasterization, no windowing.
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
//! Audio plugin UI widgets: knobs, sliders, toggles, labels, headers.

use std::f32::consts::PI;

use crate::interaction::InteractionState;
use crate::layout::{
    DROPDOWN_BOX_HEIGHT, GRID_GAP, GRID_PADDING, GRID_SECTION_H, GridLayout, HEADER_HEIGHT, Layout,
    PluginLayout, ROWS_COLUMN_GAP, ROWS_LAYOUT_TOP, ROWS_ROW_GAP, ROWS_SECTION_LABEL_HEIGHT,
    WidgetKind, compute_section_offsets,
};
use crate::render::RenderBackend;
use crate::snapshot::ParamSnapshot;
use crate::theme::{Color, Theme};

/// Widget type for interaction state tracking.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WidgetType {
    Knob,
    Slider,
    Toggle,
    Selector,
    /// Dropdown list - click to open a popup of all options.
    Dropdown,
    Meter,
    XYPad,
}

/// Draw a rotary knob.
///
/// `value` is normalized 0.0–1.0.
/// `label` is shown below the knob.
/// `value_text` is shown below the label.
pub fn draw_knob(
    ctx: &mut dyn RenderBackend,
    x: f32,
    y: f32,
    size: f32,
    value: f32,
    label: &str,
    value_text: &str,
    theme: &Theme,
    highlighted: bool,
) {
    let cx = x + size / 2.0;
    let cy = y + size / 2.0 - 5.0; // leave room for label below
    let radius = size / 2.0 - 4.0;

    // Knob range: from 225° (bottom-left) to -45° (bottom-right), going clockwise
    // In radians: 225° = 5π/4, -45° = -π/4 (or 315° = 7π/4)
    let start_angle = 0.75 * PI; // 135° from 12 o'clock → 225° in standard math
    let end_angle = 2.25 * PI; // 405° = 45° past full rotation
    let arc_start = start_angle;
    let arc_end = end_angle;

    // Track arc (full range background)
    ctx.stroke_arc(cx, cy, radius, arc_start, arc_end, theme.knob_track, 2.0);

    // Value arc (filled portion)
    let value_angle = arc_start + value * (arc_end - arc_start);
    if value > 0.01 {
        ctx.stroke_arc(cx, cy, radius, arc_start, value_angle, theme.knob_fill, 2.0);
    }

    // Pointer line from center to current position
    let pointer_len = radius * 0.6;
    let px = cx + pointer_len * value_angle.cos();
    let py = cy + pointer_len * value_angle.sin();
    ctx.draw_line(cx, cy, px, py, theme.knob_pointer, 1.5);

    // Hover highlight ring
    if highlighted {
        ctx.stroke_arc(cx, cy, radius + 2.0, arc_start, arc_end, theme.accent, 1.0);
    }

    // Value text (below knob)
    let val_size = 10.0;
    let val_w = ctx.text_width(value_text, val_size);
    ctx.draw_text(
        value_text,
        cx - val_w / 2.0,
        y + size - 9.0,
        val_size,
        theme.text,
    );

    // Label text (below value)
    let label_size = 9.0;
    let label_w = ctx.text_width(label, label_size);
    ctx.draw_text(
        label,
        cx - label_w / 2.0,
        y + size + 2.0,
        label_size,
        theme.text_dim,
    );
}

/// Draw a header bar. Each slot is independently optional - passing
/// `None` for both should be avoided (the caller is expected to skip
/// `draw_header` entirely when the layout has no header).
pub fn draw_header(
    ctx: &mut dyn RenderBackend,
    x: f32,
    y: f32,
    w: f32,
    h: f32,
    title: Option<&str>,
    subtitle: Option<&str>,
    theme: &Theme,
) {
    ctx.fill_rect(x, y, w, h, theme.header_bg);

    if let Some(title) = title {
        let title_size = 12.0;
        ctx.draw_text(
            title,
            x + 10.0,
            y + (h - title_size) / 2.0 - 1.0,
            title_size,
            theme.header_text,
        );
    }

    if let Some(subtitle) = subtitle {
        let sub_size = 9.0;
        let sub_w = ctx.text_width(subtitle, sub_size);
        ctx.draw_text(
            subtitle,
            x + w - sub_w - 10.0,
            y + (h - sub_size) / 2.0 - 1.0,
            sub_size,
            theme.text_dim,
        );
    }
}

/// Draw a horizontal slider.
///
/// `value` is normalized 0.0–1.0.
pub fn draw_slider(
    ctx: &mut dyn RenderBackend,
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    value: f32,
    label: &str,
    value_text: &str,
    theme: &Theme,
    highlighted: bool,
) {
    let track_y = y + height / 2.0 - 5.0;
    let track_h = 3.0;
    let margin = 4.0;
    let track_w = width - margin * 2.0;

    // Track background
    ctx.fill_rect(x + margin, track_y, track_w, track_h, theme.knob_track);

    // Filled portion
    let fill_w = track_w * value;
    if fill_w > 0.5 {
        ctx.fill_rect(x + margin, track_y, fill_w, track_h, theme.knob_fill);
    }

    // Thumb
    let thumb_x = x + margin + fill_w;
    let thumb_r = 4.0;
    ctx.fill_circle(
        thumb_x,
        track_y + track_h / 2.0,
        thumb_r,
        theme.knob_pointer,
    );
    if highlighted {
        ctx.fill_circle(
            thumb_x,
            track_y + track_h / 2.0,
            thumb_r + 1.5,
            theme.accent,
        );
        ctx.fill_circle(
            thumb_x,
            track_y + track_h / 2.0,
            thumb_r,
            theme.knob_pointer,
        );
    }

    // Value text
    let val_size = 10.0;
    let cx = x + width / 2.0;
    let val_w = ctx.text_width(value_text, val_size);
    ctx.draw_text(
        value_text,
        cx - val_w / 2.0,
        y + height - 9.0,
        val_size,
        theme.text,
    );

    // Label
    let label_size = 9.0;
    let label_w = ctx.text_width(label, label_size);
    ctx.draw_text(
        label,
        cx - label_w / 2.0,
        y + height + 2.0,
        label_size,
        theme.text_dim,
    );
}

/// Draw a toggle button (on/off).
///
/// `value` > 0.5 = on, <= 0.5 = off.
pub fn draw_toggle(
    ctx: &mut dyn RenderBackend,
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    value: f32,
    label: &str,
    value_text: &str,
    theme: &Theme,
    highlighted: bool,
) {
    let is_on = value > 0.5;
    let cx = x + width / 2.0;
    let cy = y + height / 2.0 - 5.0;

    // Toggle track (pill shape)
    let track_w = 20.0;
    let track_h = 10.0;
    let track_x = cx - track_w / 2.0;
    let track_y = cy - track_h / 2.0;
    let bg = if is_on {
        theme.knob_fill
    } else {
        theme.knob_track
    };
    ctx.fill_rect(track_x, track_y, track_w, track_h, bg);

    // Thumb circle
    let thumb_x = if is_on {
        track_x + track_w - track_h / 2.0
    } else {
        track_x + track_h / 2.0
    };
    ctx.fill_circle(thumb_x, cy, track_h / 2.0 - 1.0, theme.knob_pointer);

    if highlighted {
        ctx.fill_rect(
            track_x - 1.0,
            track_y - 1.0,
            track_w + 2.0,
            track_h + 2.0,
            theme.accent,
        );
        ctx.fill_rect(track_x, track_y, track_w, track_h, bg);
        ctx.fill_circle(thumb_x, cy, track_h / 2.0 - 1.0, theme.knob_pointer);
    }

    // Value text
    let val_size = 10.0;
    let val_w = ctx.text_width(value_text, val_size);
    ctx.draw_text(
        value_text,
        cx - val_w / 2.0,
        y + height - 9.0,
        val_size,
        theme.text,
    );

    // Label
    let label_size = 9.0;
    let label_w = ctx.text_width(label, label_size);
    ctx.draw_text(
        label,
        cx - label_w / 2.0,
        y + height + 2.0,
        label_size,
        theme.text_dim,
    );
}

/// Draw a selector (enum parameter - click to cycle through values).
///
/// Shows the current value name with < > arrows.
pub fn draw_selector(
    ctx: &mut dyn RenderBackend,
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    _value: f32,
    label: &str,
    value_text: &str,
    theme: &Theme,
    highlighted: bool,
) {
    let cx = x + width / 2.0;
    let cy = y + height / 2.0 - 5.0;

    // Background box - size to fit content
    let val_size = 10.0;
    let arrow_size = 8.0;
    let arrow_pad = 9.0; // space for arrow on each side
    let val_w = ctx.text_width(value_text, val_size);
    let box_w = (val_w + arrow_pad * 2.0 + 5.0).max(width - 8.0);
    let box_h = 13.0;
    let box_x = cx - box_w / 2.0;
    let box_y = cy - box_h / 2.0;
    let bg = if highlighted {
        theme.accent
    } else {
        theme.knob_track
    };
    ctx.fill_rect(box_x, box_y, box_w, box_h, bg);

    // Value text (centered)
    ctx.draw_text(
        value_text,
        cx - val_w / 2.0,
        cy - val_size / 2.0,
        val_size,
        theme.text,
    );

    // Left/right arrows
    ctx.draw_text(
        "<",
        box_x + 3.0,
        cy - arrow_size / 2.0,
        arrow_size,
        theme.text_dim,
    );
    let gt_w = ctx.text_width(">", arrow_size);
    ctx.draw_text(
        ">",
        box_x + box_w - gt_w - 3.0,
        cy - arrow_size / 2.0,
        arrow_size,
        theme.text_dim,
    );

    // Label (below)
    let label_size = 9.0;
    let label_w = ctx.text_width(label, label_size);
    ctx.draw_text(
        label,
        cx - label_w / 2.0,
        y + height + 2.0,
        label_size,
        theme.text_dim,
    );
}

/// Draw a dropdown (closed state) - shows current value with a down arrow.
///
/// When open, `draw_dropdown_popup` renders the option list as an overlay.
pub fn draw_dropdown(
    ctx: &mut dyn RenderBackend,
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    _value: f32,
    label: &str,
    value_text: &str,
    theme: &Theme,
    highlighted: bool,
    is_open: bool,
) {
    let cx = x + width / 2.0;
    let cy = y + height / 2.0 - 8.0;

    let val_size = 10.0;
    let arrow_pad = 14.0;
    let val_w = ctx.text_width(value_text, val_size);
    let box_w = (val_w + arrow_pad + 12.0).max(width - 12.0);
    let box_h = DROPDOWN_BOX_HEIGHT;
    let box_x = cx - box_w / 2.0;
    let box_y = cy - box_h / 2.0;
    let bg = if is_open || highlighted {
        theme.accent
    } else {
        theme.knob_track
    };
    ctx.fill_rect(box_x, box_y, box_w, box_h, bg);

    // Value text (left-aligned with padding)
    ctx.draw_text(
        value_text,
        box_x + 6.0,
        cy - val_size / 2.0,
        val_size,
        theme.text,
    );

    // Down arrow on the right
    let arrow_size = 8.0;
    let arrow = if is_open { "\u{25B2}" } else { "\u{25BC}" }; // ▲ / ▼
    let aw = ctx.text_width(arrow, arrow_size);
    ctx.draw_text(
        arrow,
        box_x + box_w - aw - 4.0,
        cy - arrow_size / 2.0,
        arrow_size,
        theme.text_dim,
    );

    // Label (below)
    let label_size = 9.0;
    let label_w = ctx.text_width(label, label_size);
    ctx.draw_text(
        label,
        cx - label_w / 2.0,
        y + height + 2.0,
        label_size,
        theme.text_dim,
    );
}

/// Draw the dropdown popup overlay showing visible options.
///
/// `scroll_offset` is the index of the first visible option.
/// `visible_count` is how many options to draw (may be less than total).
// Visible-count and option-index → f32 for geometry; both are
// bounded by the popup item count (typically < 100).
#[allow(clippy::cast_precision_loss)]
pub fn draw_dropdown_popup(
    ctx: &mut dyn RenderBackend,
    x: f32,
    y: f32,
    width: f32,
    options: &[String],
    selected_index: usize,
    hover_index: Option<usize>,
    scroll_offset: usize,
    visible_count: usize,
    theme: &Theme,
) {
    let item_h = 18.0;
    let padding = 4.0;
    let popup_w = width.max(80.0);
    let popup_h = visible_count as f32 * item_h + padding * 2.0;
    let popup_x = x;
    let popup_y = y;

    // Background
    ctx.fill_rect(popup_x, popup_y, popup_w, popup_h, theme.surface);
    // Border
    ctx.draw_line(
        popup_x,
        popup_y,
        popup_x + popup_w,
        popup_y,
        theme.text_dim,
        1.0,
    );
    ctx.draw_line(
        popup_x + popup_w,
        popup_y,
        popup_x + popup_w,
        popup_y + popup_h,
        theme.text_dim,
        1.0,
    );
    ctx.draw_line(
        popup_x + popup_w,
        popup_y + popup_h,
        popup_x,
        popup_y + popup_h,
        theme.text_dim,
        1.0,
    );
    ctx.draw_line(
        popup_x,
        popup_y + popup_h,
        popup_x,
        popup_y,
        theme.text_dim,
        1.0,
    );

    let text_size = 10.0;
    let visible_end = (scroll_offset + visible_count).min(options.len());
    for (vis_i, abs_i) in (scroll_offset..visible_end).enumerate() {
        let iy = popup_y + padding + vis_i as f32 * item_h;

        // Highlight selected or hovered item
        if hover_index == Some(abs_i) {
            ctx.fill_rect(popup_x + 1.0, iy, popup_w - 2.0, item_h, theme.accent);
        } else if abs_i == selected_index {
            ctx.fill_rect(popup_x + 1.0, iy, popup_w - 2.0, item_h, theme.knob_track);
        }

        ctx.draw_text(
            &options[abs_i],
            popup_x + 6.0,
            iy + (item_h - text_size) / 2.0,
            text_size,
            theme.text,
        );
    }

    // Scroll indicators
    let arrow_size = 8.0;
    let cx = popup_x + popup_w / 2.0;
    if scroll_offset > 0 {
        let aw = ctx.text_width("\u{25B2}", arrow_size);
        ctx.draw_text(
            "\u{25B2}",
            cx - aw / 2.0,
            popup_y + 1.0,
            arrow_size,
            theme.text_dim,
        );
    }
    if visible_end < options.len() {
        let aw = ctx.text_width("\u{25BC}", arrow_size);
        ctx.draw_text(
            "\u{25BC}",
            cx - aw / 2.0,
            popup_y + popup_h - arrow_size - 1.0,
            arrow_size,
            theme.text_dim,
        );
    }
}

/// Draw a vertical level meter with one or more channels.
///
/// Each level is 0.0–1.0 (linear, not dB).
// Channel counts and indices → f32 for geometry; both are bounded
// by `num_channels` (typically ≤ 8).
#[allow(clippy::cast_precision_loss)]
pub fn draw_meter(
    ctx: &mut dyn RenderBackend,
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    levels: &[f32],
    label: &str,
    theme: &Theme,
) {
    let cx = x + width / 2.0;
    let num = levels.len().max(1);
    let bar_w = 4.0f32;
    let gap = 2.0f32;
    let total_bar_w = num as f32 * bar_w + (num as f32 - 1.0).max(0.0) * gap;
    let bar_h = height - 4.0; // fill nearly full height
    let bar_start_x = cx - total_bar_w / 2.0;
    let bar_y = y + 2.0;

    for (i, &level) in levels.iter().enumerate() {
        let bx = bar_start_x + i as f32 * (bar_w + gap);

        // Background
        ctx.fill_rect(bx, bar_y, bar_w, bar_h, theme.knob_track);

        // dB-scaled fill from bottom
        let display = truce_core::meter_display(level);
        let fill_h = bar_h * display;
        if fill_h > 0.5 {
            // Blue normally, red when clipping (> -3 dB ≈ display > 0.95)
            let color = if display > 0.95 {
                Color::rgb(0.88, 0.27, 0.27)
            } else {
                theme.knob_fill
            };
            ctx.fill_rect(bx, bar_y + bar_h - fill_h, bar_w, fill_h, color);
        }
    }

    // Label (below the widget, same position as knob labels)
    let label_size = 8.0;
    let label_w = ctx.text_width(label, label_size);
    ctx.draw_text(
        label,
        cx - label_w / 2.0,
        y + height + 4.0,
        label_size,
        theme.text_dim,
    );
}

/// Draw an XY pad (2D control for two parameters).
///
/// `value_x` and `value_y` are normalized 0.0–1.0.
pub fn draw_xy_pad(
    ctx: &mut dyn RenderBackend,
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    value_x: f32,
    value_y: f32,
    label_x: &str,
    label_y: &str,
    theme: &Theme,
    highlighted: bool,
) {
    let pad_margin = 4.0;
    let pad_x = x + pad_margin;
    let pad_y = y + pad_margin;
    let pad_w = width - pad_margin * 2.0;
    let pad_h = height - pad_margin * 2.0;

    // Background
    ctx.fill_rect(pad_x, pad_y, pad_w, pad_h, theme.knob_track);

    // Crosshair lines
    let dot_x = pad_x + value_x.clamp(0.0, 1.0) * pad_w;
    let dot_y = pad_y + (1.0 - value_y.clamp(0.0, 1.0)) * pad_h; // invert Y
    let line_color = theme.text_dim;
    ctx.draw_line(dot_x, pad_y, dot_x, pad_y + pad_h, line_color, 1.0);
    ctx.draw_line(pad_x, dot_y, pad_x + pad_w, dot_y, line_color, 1.0);

    // Dot at intersection
    let dot_color = if highlighted {
        theme.accent
    } else {
        theme.knob_fill
    };
    ctx.fill_circle(dot_x, dot_y, 3.0, dot_color);
    ctx.fill_circle(dot_x, dot_y, 2.0, theme.knob_pointer);

    // Border
    if highlighted {
        ctx.draw_line(pad_x, pad_y, pad_x + pad_w, pad_y, theme.accent, 1.0);
        ctx.draw_line(
            pad_x + pad_w,
            pad_y,
            pad_x + pad_w,
            pad_y + pad_h,
            theme.accent,
            1.0,
        );
        ctx.draw_line(
            pad_x + pad_w,
            pad_y + pad_h,
            pad_x,
            pad_y + pad_h,
            theme.accent,
            1.0,
        );
        ctx.draw_line(pad_x, pad_y + pad_h, pad_x, pad_y, theme.accent, 1.0);
    }

    // Axis labels: X below the widget (like knob labels), Y at top-left inside pad
    let label_size = 8.0;
    let x_label_w = ctx.text_width(label_x, label_size);
    let cx = x + width / 2.0;
    ctx.draw_text(
        label_x,
        cx - x_label_w / 2.0,
        y + height + 3.0,
        label_size,
        theme.text_dim,
    );

    if !label_y.is_empty() {
        ctx.draw_text(
            label_y,
            pad_x + 2.0,
            pad_y + 1.0,
            label_size,
            theme.text_dim,
        );
    }
}

/// Draw a group/section label.
pub fn draw_section_label(
    ctx: &mut dyn RenderBackend,
    x: f32,
    y: f32,
    w: f32,
    label: &str,
    theme: &Theme,
) {
    let size = 9.0;
    let label_w = ctx.text_width(label, size);
    ctx.draw_text(label, x + (w - label_w) / 2.0, y, size, theme.text_dim);
}

// ---------------------------------------------------------------------------
// Public compositor - draws an entire layout in one call.
// ---------------------------------------------------------------------------

/// Render every widget in `layout` onto `backend` using `theme`,
/// reading live values from `snapshot` and interaction flags from
/// `state`.
///
/// Does not call `backend.clear()` or `backend.present()` - the caller
/// owns the surrounding frame. This lets plugins with custom renderers
/// draw their own content first (or last) and still get the same widget
/// chrome as `BuiltinEditor`.
///
/// `state.knob_regions` is expected to be up to date for `layout`;
/// callers typically call `state.build_regions_any(layout)` after any
/// layout change. `draw` updates `dropdown_anchor_y` on each region it
/// draws so that subsequent dropdown opens via `interaction::dispatch`
/// position the popup under the current button.
pub fn draw(
    backend: &mut dyn RenderBackend,
    layout: &Layout,
    theme: &Theme,
    snapshot: &ParamSnapshot<'_>,
    state: &mut InteractionState,
) {
    match layout {
        Layout::Rows(pl) => draw_rows(backend, pl, theme, snapshot, state),
        Layout::Grid(gl) => draw_grid(backend, gl, theme, snapshot, state),
    }
    draw_dropdown_overlay(backend, theme, state);
}

fn resolve_wkind_to_type(
    kind: Option<WidgetKind>,
    param_id: u32,
    snapshot: &ParamSnapshot<'_>,
) -> WidgetType {
    match kind {
        Some(WidgetKind::Knob) => WidgetType::Knob,
        Some(WidgetKind::Slider) => WidgetType::Slider,
        Some(WidgetKind::Toggle) => WidgetType::Toggle,
        Some(WidgetKind::Selector) => WidgetType::Selector,
        Some(WidgetKind::Dropdown) => WidgetType::Dropdown,
        Some(WidgetKind::Meter) => WidgetType::Meter,
        Some(WidgetKind::XYPad) => WidgetType::XYPad,
        None => (snapshot.widget_type)(param_id),
    }
}

// Window dimensions and widget indices → f32 for geometry; bounded
// by widget count (< 1000) and pixel dimensions (< 16384).
#[allow(clippy::cast_precision_loss)]
fn draw_rows(
    backend: &mut dyn RenderBackend,
    pl: &PluginLayout,
    theme: &Theme,
    snapshot: &ParamSnapshot<'_>,
    state: &mut InteractionState,
) {
    let w = pl.width;
    let knob_size = pl.knob_size;
    let pitch = knob_size + ROWS_COLUMN_GAP;
    if !pl.titles.is_empty() {
        draw_header(
            backend,
            0.0,
            0.0,
            w as f32,
            HEADER_HEIGHT,
            pl.titles.title,
            pl.titles.subtitle,
            theme,
        );
    }

    let mut y = ROWS_LAYOUT_TOP;
    let mut region_idx = 0usize;

    for row in &pl.rows {
        if let Some(label) = row.label {
            draw_section_label(backend, 0.0, y, w as f32, label, theme);
            y += ROWS_SECTION_LABEL_HEIGHT;
        }

        let total_cols: u32 = row.knobs.iter().map(|k| k.span.max(1)).sum();
        let total_w = total_cols as f32 * pitch - ROWS_COLUMN_GAP;
        let start_x = (w as f32 - total_w) / 2.0;

        let mut col = 0u32;
        for kd in &row.knobs {
            let span = kd.span.max(1);
            let x = start_x + col as f32 * pitch;
            let widget_w = span as f32 * pitch - ROWS_COLUMN_GAP;
            let widget_h = knob_size;

            draw_widget_entry(
                &mut WidgetDrawCtx {
                    backend,
                    theme,
                    snapshot,
                    state,
                },
                &WidgetDraw {
                    region_idx,
                    x,
                    y,
                    w: widget_w,
                    h: widget_h,
                    param_id: kd.param_id,
                    param_id_y: kd.param_id_y,
                    meter_ids: kd.meter_ids.as_deref(),
                    label: kd.label,
                    explicit_kind: kd.widget,
                    center_knob_in_cell: false, // rows: never center the knob in its cell
                },
            );

            region_idx += 1;
            col += span;
        }

        y += knob_size + ROWS_ROW_GAP;
    }
}

// Window dimensions and grid indices → f32 for geometry; bounded
// by grid size (< 1000 cells) and pixel dimensions (< 16384).
#[allow(clippy::cast_precision_loss)]
fn draw_grid(
    backend: &mut dyn RenderBackend,
    grid: &GridLayout,
    theme: &Theme,
    snapshot: &ParamSnapshot<'_>,
    state: &mut InteractionState,
) {
    let w = grid.width;
    if !grid.titles.is_empty() {
        draw_header(
            backend,
            0.0,
            0.0,
            w as f32,
            HEADER_HEIGHT,
            grid.titles.title,
            grid.titles.subtitle,
            theme,
        );
    }

    let header_h = grid.header_height();
    let section_offsets = compute_section_offsets(grid);

    for &(row_idx, label) in &grid.sections {
        let y = header_h
            + GRID_PADDING
            + row_idx as f32 * (grid.cell_size + GRID_GAP)
            + section_offsets[row_idx as usize]
            - GRID_SECTION_H;
        draw_section_label(backend, 0.0, y, w as f32, label, theme);
    }

    for (idx, gw) in grid.widgets.iter().enumerate() {
        let x = GRID_PADDING + gw.col as f32 * (grid.cell_size + GRID_GAP);
        let y = header_h
            + GRID_PADDING
            + gw.row as f32 * (grid.cell_size + GRID_GAP)
            + section_offsets[gw.row as usize];
        let widget_w = gw.col_span as f32 * (grid.cell_size + GRID_GAP) - GRID_GAP;
        let widget_h = gw.row_span as f32 * (grid.cell_size + GRID_GAP) - GRID_GAP;

        draw_widget_entry(
            &mut WidgetDrawCtx {
                backend,
                theme,
                snapshot,
                state,
            },
            &WidgetDraw {
                region_idx: idx,
                x,
                y,
                w: widget_w,
                h: widget_h,
                param_id: gw.param_id,
                param_id_y: gw.param_id_y,
                meter_ids: gw.meter_ids.as_deref(),
                label: gw.label,
                explicit_kind: gw.widget,
                center_knob_in_cell: true, // grid: center knobs within their cell
            },
        );
    }
}

/// Per-call arguments to [`draw_widget_entry`] - what's being
/// drawn, where, and which `InteractionState` region it owns.
/// Splits cleanly from [`WidgetDrawCtx`] (the rendering
/// infrastructure) so the function signature reads as
/// `(ctx, widget)` rather than 14 positional parameters.
struct WidgetDraw<'a> {
    region_idx: usize,
    /// Top-left of the widget's rect, in logical points.
    x: f32,
    y: f32,
    w: f32,
    h: f32,
    param_id: u32,
    /// Only `WidgetType::XYPad` reads this - the second axis's
    /// param. `None` falls back to `param_id` for one-axis widgets
    /// that accidentally route through the XY path.
    param_id_y: Option<u32>,
    /// Only `WidgetType::Meter` reads this - the meter IDs to
    /// sample. `None` falls back to `[param_id]`.
    meter_ids: Option<&'a [u32]>,
    label: &'static str,
    explicit_kind: Option<WidgetKind>,
    /// When `true`, knobs are centered inside their cell (grid
    /// layout). When `false`, knobs left-align (row layout).
    center_knob_in_cell: bool,
}

/// Rendering infrastructure shared across every widget in a frame:
/// the rendering backend, theme, snapshot of parameter values, and
/// the running interaction state.
struct WidgetDrawCtx<'a> {
    backend: &'a mut dyn RenderBackend,
    theme: &'a Theme,
    snapshot: &'a ParamSnapshot<'a>,
    state: &'a mut InteractionState,
}

fn draw_widget_entry(ctx: &mut WidgetDrawCtx<'_>, w: &WidgetDraw<'_>) {
    let normalized = (ctx.snapshot.get_param)(w.param_id);
    let value_text = (ctx.snapshot.format_param)(w.param_id);
    let is_hovered = ctx.state.hover_idx == Some(w.region_idx);
    let wtype = resolve_wkind_to_type(w.explicit_kind, w.param_id, ctx.snapshot);

    match wtype {
        WidgetType::Toggle => draw_toggle(
            ctx.backend,
            w.x,
            w.y,
            w.w,
            w.h,
            normalized,
            w.label,
            &value_text,
            ctx.theme,
            is_hovered,
        ),
        WidgetType::Slider => draw_slider(
            ctx.backend,
            w.x,
            w.y,
            w.w,
            w.h,
            normalized,
            w.label,
            &value_text,
            ctx.theme,
            is_hovered,
        ),
        WidgetType::Selector => draw_selector(
            ctx.backend,
            w.x,
            w.y,
            w.w,
            w.h,
            normalized,
            w.label,
            &value_text,
            ctx.theme,
            is_hovered,
        ),
        WidgetType::Dropdown => {
            let is_open = ctx
                .state
                .dropdown
                .as_ref()
                .is_some_and(|dd| dd.region_idx == w.region_idx);
            draw_dropdown(
                ctx.backend,
                w.x,
                w.y,
                w.w,
                w.h,
                normalized,
                w.label,
                &value_text,
                ctx.theme,
                is_hovered,
                is_open,
            );
            // The visible button box is `DROPDOWN_BOX_HEIGHT` tall,
            // centered on `cy = y + h/2 - 8`. Store the *bottom* of
            // that box so `open_dropdown` can anchor the popup
            // directly underneath.
            let anchor_cy = w.y + w.h / 2.0 - 8.0;
            if let Some(region) = ctx.state.knob_regions.get_mut(w.region_idx) {
                region.dropdown_anchor_y = anchor_cy + DROPDOWN_BOX_HEIGHT / 2.0;
            }
        }
        WidgetType::Meter => {
            let fallback = [w.param_id];
            let ids = w.meter_ids.unwrap_or(&fallback);
            let levels: Vec<f32> = ids.iter().map(|&id| (ctx.snapshot.get_meter)(id)).collect();
            draw_meter(ctx.backend, w.x, w.y, w.w, w.h, &levels, w.label, ctx.theme);
        }
        WidgetType::XYPad => {
            let val_y_id = w.param_id_y.unwrap_or(w.param_id);
            let vx = (ctx.snapshot.get_param)(w.param_id);
            let vy = (ctx.snapshot.get_param)(val_y_id);
            let x_name_str = (ctx.snapshot.param_name)(w.param_id);
            let y_name_str = (ctx.snapshot.param_name)(val_y_id);
            let x_name: &str = if x_name_str.is_empty() {
                w.label
            } else {
                &x_name_str
            };
            let y_name: &str = &y_name_str;
            draw_xy_pad(
                ctx.backend,
                w.x,
                w.y,
                w.w,
                w.h,
                vx,
                vy,
                x_name,
                y_name,
                ctx.theme,
                is_hovered,
            );
        }
        WidgetType::Knob => {
            if w.center_knob_in_cell {
                let knob_size = w.w.min(w.h);
                let kx = w.x + (w.w - knob_size) / 2.0;
                let ky = w.y + (w.h - knob_size) / 2.0;
                draw_knob(
                    ctx.backend,
                    kx,
                    ky,
                    knob_size,
                    normalized,
                    w.label,
                    &value_text,
                    ctx.theme,
                    is_hovered,
                );
            } else {
                draw_knob(
                    ctx.backend,
                    w.x,
                    w.y,
                    w.h,
                    normalized,
                    w.label,
                    &value_text,
                    ctx.theme,
                    is_hovered,
                );
            }
        }
    }
}

fn draw_dropdown_overlay(backend: &mut dyn RenderBackend, theme: &Theme, state: &InteractionState) {
    if let Some(ref dd) = state.dropdown {
        let (px, py, pw, _) = dd.popup_rect;
        draw_dropdown_popup(
            backend,
            px,
            py,
            pw,
            &dd.options,
            dd.selected,
            dd.hover_option,
            dd.scroll_offset,
            dd.visible_count,
            theme,
        );
    }
}