truce-gui-types 0.49.13

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
//! Simple layout helpers for positioning widgets.

// ---------------------------------------------------------------------------
// Rows-layout shared constants
// ---------------------------------------------------------------------------
//
// Coordinates the rows-layout uses to step through `Row`s. `widgets::draw_rows`
// (paint side) and `interaction::build_regions` (hit-test side) walk the
// rows in lock-step, so they have to agree on these step sizes - drift
// would make hover / drag rectangles miss the painted widget.

/// Pixel height of the title-bar header `widgets::draw_header` paints
/// at the top of the editor.
pub const HEADER_HEIGHT: f32 = 20.0;

/// Y-offset of the first row below the header. The 4-pixel gap between
/// `HEADER_HEIGHT` and `ROWS_LAYOUT_TOP` is the breathing room between
/// the title bar and the first row of widgets.
pub const ROWS_LAYOUT_TOP: f32 = 24.0;

/// Vertical pixels reserved for a section label (`Row::label`) drawn
/// above its row.
pub const ROWS_SECTION_LABEL_HEIGHT: f32 = 14.0;

/// Horizontal gap between adjacent widgets in a row. The full pitch
/// between widget origins is `knob_size + ROWS_COLUMN_GAP`.
pub const ROWS_COLUMN_GAP: f32 = 7.0;

/// Vertical gap below a row. The full pitch between row origins is
/// `knob_size + ROWS_ROW_GAP`.
pub const ROWS_ROW_GAP: f32 = 19.0;

// ---------------------------------------------------------------------------
// Dropdown widget shared constants
// ---------------------------------------------------------------------------

/// Pixel height of the dropdown button box (the closed state - clicking
/// this opens the popup). Both `widgets::draw_dropdown` (paint side) and
/// `interaction::open_dropdown` (popup-anchor math) need to agree.
pub const DROPDOWN_BOX_HEIGHT: f32 = 20.0;

use truce_core::cast::len_u32;

/// A widget definition for the layout - either explicit type or auto-detected.
#[derive(Clone, Debug)]
pub struct KnobDef {
    pub param_id: u32,
    pub label: &'static str,
    /// Explicit widget type override. None = auto-detect from param range.
    pub widget: Option<WidgetKind>,
    /// How many grid columns this widget spans. Default = 1.
    pub span: u32,
    /// Second parameter ID for XY pad (Y axis). Ignored for other widgets.
    pub param_id_y: Option<u32>,
    /// Multiple meter IDs for multi-channel level meter. Ignored for other widgets.
    pub meter_ids: Option<Vec<u32>>,
}

/// Explicit widget type for layout overrides.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WidgetKind {
    Knob,
    Slider,
    Toggle,
    Selector,
    /// Dropdown list - click to open a popup showing all options.
    Dropdown,
    /// Level meter. Shows one bar per meter ID. Supports mono, stereo, or multi-channel.
    Meter,
    /// XY pad. Controls two params - X param stored in `param_id`, Y param in `xy_param_y`.
    XYPad,
}

impl KnobDef {
    /// Knob (default for continuous params, auto-detected anyway).
    pub fn knob(param_id: impl Into<u32>, label: &'static str) -> Self {
        Self {
            param_id: param_id.into(),
            label,
            widget: Some(WidgetKind::Knob),
            span: 1,
            param_id_y: None,
            meter_ids: None,
        }
    }

    /// Horizontal slider.
    pub fn slider(param_id: impl Into<u32>, label: &'static str) -> Self {
        Self {
            param_id: param_id.into(),
            label,
            widget: Some(WidgetKind::Slider),
            span: 1,
            param_id_y: None,
            meter_ids: None,
        }
    }

    /// Toggle button.
    pub fn toggle(param_id: impl Into<u32>, label: &'static str) -> Self {
        Self {
            param_id: param_id.into(),
            label,
            widget: Some(WidgetKind::Toggle),
            span: 1,
            param_id_y: None,
            meter_ids: None,
        }
    }

    /// Selector (click-to-cycle for enum params).
    pub fn selector(param_id: impl Into<u32>, label: &'static str) -> Self {
        Self {
            param_id: param_id.into(),
            label,
            widget: Some(WidgetKind::Selector),
            span: 1,
            param_id_y: None,
            meter_ids: None,
        }
    }

    /// Dropdown list (click to open a popup showing all options).
    pub fn dropdown(param_id: impl Into<u32>, label: &'static str) -> Self {
        Self {
            param_id: param_id.into(),
            label,
            widget: Some(WidgetKind::Dropdown),
            span: 1,
            param_id_y: None,
            meter_ids: None,
        }
    }

    /// Level meter with one or more channels (display-only, reads from `Plugin::get_meter()`).
    #[must_use]
    pub fn meter(ids: &[u32], label: &'static str) -> Self {
        Self {
            param_id: ids.first().copied().unwrap_or(0),
            label,
            widget: Some(WidgetKind::Meter),
            span: 1,
            param_id_y: None,
            meter_ids: Some(ids.to_vec()),
        }
    }

    /// XY pad controlling two parameters.
    pub fn xy_pad(param_x: impl Into<u32>, param_y: impl Into<u32>, label: &'static str) -> Self {
        Self {
            param_id: param_x.into(),
            label,
            widget: Some(WidgetKind::XYPad),
            span: 2,
            param_id_y: Some(param_y.into()),
            meter_ids: None,
        }
    }

    /// Set the column span for this widget (default 1).
    #[must_use]
    pub fn with_span(mut self, span: u32) -> Self {
        self.span = span;
        self
    }
}

/// A row of widgets with an optional section label.
#[derive(Clone, Debug)]
pub struct KnobRow {
    pub label: Option<&'static str>,
    pub knobs: Vec<KnobDef>,
}

/// Layout configuration for a plugin UI.
#[derive(Clone, Debug)]
pub struct PluginLayout {
    pub titles: HeaderTitles,
    pub rows: Vec<KnobRow>,
    pub width: u32,
    pub height: u32,
    pub knob_size: f32,
}

impl PluginLayout {
    /// Calculate default window size based on the layout.
    // Window dimensions in logical pixels stay well below 2^23, so the
    // f32 ↔ u32 narrowings are invisible in practice.
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::cast_precision_loss
    )]
    #[must_use]
    pub fn compute_size(rows: &[KnobRow], knob_size: f32, titles: &HeaderTitles) -> (u32, u32) {
        let header_h = if titles.is_empty() { 0.0 } else { 21.0 };
        let row_h = knob_size + 19.0;
        let section_label_h = 14.0;
        let padding = 7.0;

        let max_knobs = rows
            .iter()
            .map(|r| {
                r.knobs
                    .iter()
                    .map(|k| k.span.max(1) as usize)
                    .sum::<usize>()
            })
            .max()
            .unwrap_or(1);
        let w = max_knobs as f32 * (knob_size + 7.0) + 13.0;

        let mut h = header_h + padding;
        for row in rows {
            if row.label.is_some() {
                h += section_label_h;
            }
            h += row_h + padding;
        }

        (w as u32, h as u32)
    }

    /// Build a Rows-style layout with the given header titles.
    /// Either or both [`HeaderTitles`] slots can be empty (use
    /// [`HeaderTitles::none`] for a layout with no header band).
    #[must_use]
    pub fn build(titles: HeaderTitles, rows: Vec<KnobRow>, knob_size: f32) -> Self {
        let (w, h) = Self::compute_size(&rows, knob_size, &titles);
        Self {
            titles,
            rows,
            width: w,
            height: h,
            knob_size,
        }
    }
}

// ---------------------------------------------------------------------------
// Grid Layout
// ---------------------------------------------------------------------------

/// Sentinel value for auto-placed grid widgets.
pub const AUTO: u32 = u32::MAX;

// Grid spacing constants. All dimensions in this module are in logical
// points - the rendering backend (`CpuBackend` / `WgpuBackend`)
// multiplies by the display scale factor at raster time.
pub const GRID_GAP: f32 = 19.0;
pub const GRID_PADDING: f32 = 10.0;
pub const GRID_HEADER_H: f32 = 21.0;
pub const GRID_SECTION_H: f32 = 14.0;

/// A widget placed in a grid layout.
#[derive(Clone, Debug)]
pub struct GridWidget {
    /// Grid column (0-indexed, or AUTO for auto-flow).
    pub col: u32,
    /// Grid row (0-indexed, or AUTO for auto-flow).
    pub row: u32,
    /// Columns spanned (default 1).
    pub col_span: u32,
    /// Rows spanned (default 1).
    pub row_span: u32,
    /// Parameter ID (or first meter ID for meters).
    pub param_id: u32,
    /// Display label.
    pub label: &'static str,
    /// Widget type override. None = auto-detect from param range.
    pub widget: Option<WidgetKind>,
    /// Second param for XY pad (Y axis).
    pub param_id_y: Option<u32>,
    /// Multiple meter IDs for multi-channel level meter.
    pub meter_ids: Option<Vec<u32>>,
}

impl GridWidget {
    pub fn knob(param_id: impl Into<u32>, label: &'static str) -> Self {
        Self {
            col: AUTO,
            row: AUTO,
            col_span: 1,
            row_span: 1,
            param_id: param_id.into(),
            label,
            widget: Some(WidgetKind::Knob),
            param_id_y: None,
            meter_ids: None,
        }
    }

    pub fn slider(param_id: impl Into<u32>, label: &'static str) -> Self {
        Self {
            col: AUTO,
            row: AUTO,
            col_span: 1,
            row_span: 1,
            param_id: param_id.into(),
            label,
            widget: Some(WidgetKind::Slider),
            param_id_y: None,
            meter_ids: None,
        }
    }

    pub fn toggle(param_id: impl Into<u32>, label: &'static str) -> Self {
        Self {
            col: AUTO,
            row: AUTO,
            col_span: 1,
            row_span: 1,
            param_id: param_id.into(),
            label,
            widget: Some(WidgetKind::Toggle),
            param_id_y: None,
            meter_ids: None,
        }
    }

    pub fn selector(param_id: impl Into<u32>, label: &'static str) -> Self {
        Self {
            col: AUTO,
            row: AUTO,
            col_span: 1,
            row_span: 1,
            param_id: param_id.into(),
            label,
            widget: Some(WidgetKind::Selector),
            param_id_y: None,
            meter_ids: None,
        }
    }

    pub fn dropdown(param_id: impl Into<u32>, label: &'static str) -> Self {
        Self {
            col: AUTO,
            row: AUTO,
            col_span: 1,
            row_span: 1,
            param_id: param_id.into(),
            label,
            widget: Some(WidgetKind::Dropdown),
            param_id_y: None,
            meter_ids: None,
        }
    }

    #[must_use]
    pub fn meter(ids: &[u32], label: &'static str) -> Self {
        Self {
            col: AUTO,
            row: AUTO,
            col_span: 1,
            row_span: 1,
            param_id: ids.first().copied().unwrap_or(0),
            label,
            widget: Some(WidgetKind::Meter),
            param_id_y: None,
            meter_ids: Some(ids.to_vec()),
        }
    }

    pub fn xy_pad(param_x: impl Into<u32>, param_y: impl Into<u32>, label: &'static str) -> Self {
        Self {
            col: AUTO,
            row: AUTO,
            col_span: 2,
            row_span: 2,
            param_id: param_x.into(),
            label,
            widget: Some(WidgetKind::XYPad),
            param_id_y: Some(param_y.into()),
            meter_ids: None,
        }
    }

    /// Set the column span.
    #[must_use]
    pub fn cols(mut self, n: u32) -> Self {
        self.col_span = n;
        self
    }

    /// Set the row span.
    #[must_use]
    pub fn rows(mut self, n: u32) -> Self {
        self.row_span = n;
        self
    }

    /// Set explicit grid position (overrides auto-flow for this widget).
    #[must_use]
    pub fn at(mut self, col: u32, row: u32) -> Self {
        self.col = col;
        self.row = row;
        self
    }
}

/// A group of widgets with an optional section label.
///
/// Used as input to `GridLayout::build()`. Bare `GridWidget`s convert into
/// ungrouped sections via `From`, so orphan widgets only need `.into()`.
#[derive(Clone, Debug)]
pub struct Section {
    pub label: Option<&'static str>,
    pub widgets: Vec<GridWidget>,
}

/// Create a labeled section of widgets for `GridLayout::build()`.
#[must_use]
pub fn section(label: &'static str, widgets: Vec<GridWidget>) -> Section {
    Section {
        label: Some(label),
        widgets,
    }
}

/// Wrap bare widgets into an unlabeled section (no section header).
#[must_use]
pub fn widgets(widgets: Vec<GridWidget>) -> Section {
    Section {
        label: None,
        widgets,
    }
}

// -- Short constructors for GridWidget (free functions) --

/// Rotary knob widget.
pub fn knob(param_id: impl Into<u32>, label: &'static str) -> GridWidget {
    GridWidget::knob(param_id, label)
}

/// Horizontal slider widget.
pub fn slider(param_id: impl Into<u32>, label: &'static str) -> GridWidget {
    GridWidget::slider(param_id, label)
}

/// Toggle switch widget.
pub fn toggle(param_id: impl Into<u32>, label: &'static str) -> GridWidget {
    GridWidget::toggle(param_id, label)
}

/// Click-to-cycle selector widget.
pub fn selector(param_id: impl Into<u32>, label: &'static str) -> GridWidget {
    GridWidget::selector(param_id, label)
}

/// Dropdown list widget.
pub fn dropdown(param_id: impl Into<u32>, label: &'static str) -> GridWidget {
    GridWidget::dropdown(param_id, label)
}

/// Level meter widget.
pub fn meter<I: Into<u32> + Copy>(ids: &[I], label: &'static str) -> GridWidget {
    let u32_ids: Vec<u32> = ids.iter().map(|id| (*id).into()).collect();
    GridWidget::meter(&u32_ids, label)
}

/// XY pad controlling two parameters.
pub fn xy_pad(param_x: impl Into<u32>, param_y: impl Into<u32>, label: &'static str) -> GridWidget {
    GridWidget::xy_pad(param_x, param_y, label)
}

impl From<GridWidget> for Section {
    fn from(w: GridWidget) -> Self {
        Section {
            label: None,
            widgets: vec![w],
        }
    }
}

/// Title band drawn above a layout. The `title` slot renders
/// larger / brighter on the left of the band; the `subtitle` slot
/// renders smaller / dimmer on the right. Each slot is independently
/// optional - set either, both, or neither.
///
/// Use [`HeaderTitles::title`] / [`HeaderTitles::subtitle`] /
/// [`HeaderTitles::pair`] for the common cases; build the struct
/// directly only when you want to set a non-default combination
/// (e.g. via `..` syntax over an existing instance).
#[derive(Clone, Debug, Default)]
pub struct HeaderTitles {
    pub title: Option<&'static str>,
    pub subtitle: Option<&'static str>,
}

impl HeaderTitles {
    /// Both slots empty - no header band is drawn.
    #[must_use]
    pub const fn none() -> Self {
        Self {
            title: None,
            subtitle: None,
        }
    }

    /// Title only; subtitle slot stays empty.
    #[must_use]
    pub const fn title(s: &'static str) -> Self {
        Self {
            title: Some(s),
            subtitle: None,
        }
    }

    /// Subtitle only; title slot stays empty.
    #[must_use]
    pub const fn subtitle(s: &'static str) -> Self {
        Self {
            title: None,
            subtitle: Some(s),
        }
    }

    /// Both slots set.
    #[must_use]
    pub const fn pair(title: &'static str, subtitle: &'static str) -> Self {
        Self {
            title: Some(title),
            subtitle: Some(subtitle),
        }
    }

    /// `true` when neither slot is set - caller should skip the
    /// header band entirely.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.title.is_none() && self.subtitle.is_none()
    }
}

/// Grid-based layout for a plugin UI.
#[derive(Clone, Debug)]
pub struct GridLayout {
    /// Header band titles. Both slots default to `None`, in which
    /// case no header is drawn and the grid starts at `y = 0`
    /// (plus padding).
    pub titles: HeaderTitles,
    /// Number of columns in the grid.
    pub cols: u32,
    /// Section labels positioned above specific rows: (`row_index`, label).
    pub sections: Vec<(u32, &'static str)>,
    /// All widgets placed in the grid.
    pub widgets: Vec<GridWidget>,
    /// Cell size in logical points (width and height of one grid cell).
    pub cell_size: f32,
    /// Computed width in logical points.
    pub width: u32,
    /// Computed height in logical points.
    pub height: u32,
    /// Pre-flow widget snapshot - copy of `widgets` before
    /// `auto_flow_with_breaks` ran. Lets [`Self::with_cols`] reset
    /// and re-flow against a different column count without
    /// losing AUTO-vs-explicit placement.
    original_widgets: Vec<GridWidget>,
    /// Pre-flow section breaks - `(widget_index, label)` pairs as
    /// passed to `auto_flow_with_breaks` originally. Stored so
    /// re-flow recovers the same section labels.
    original_breaks: Vec<(usize, &'static str)>,
}

/// Default cell size in logical points when `GridLayout::build` is
/// called without `.with_cell_size(...)`. Matches the scaffolded
/// plugin's pre-refactor value so untouched scaffolds render the
/// same as before.
pub const GRID_DEFAULT_CELL_SIZE: f32 = 50.0;

impl GridLayout {
    /// Build a grid layout from sections containing widgets. No
    /// header is drawn, `cols` defaults to the widest section's
    /// widget count (extended to fit any explicitly-positioned
    /// widget), and `cell_size` defaults to
    /// [`GRID_DEFAULT_CELL_SIZE`]. Override any of those via
    /// [`Self::with_titles`] / [`Self::with_cols`] /
    /// [`Self::with_cell_size`].
    ///
    /// Each entry is either a `Section` (created with `section("LABEL", vec![...])`)
    /// or a bare `GridWidget` (auto-wrapped via `From`). Example:
    ///
    /// ```ignore
    /// GridLayout::build(vec![
    ///     section("LOW", vec![
    ///         GridWidget::knob(P::Freq, "Freq"),
    ///         GridWidget::knob(P::Gain, "Gain"),
    ///     ]),
    ///     GridWidget::knob(P::Output, "Output").into(),
    /// ])
    /// ```
    #[must_use]
    pub fn build(entries: Vec<Section>) -> Self {
        let mut widgets = Vec::new();
        let mut breaks = Vec::new();
        let mut max_widgets_per_section = 0usize;
        for s in entries {
            if let Some(label) = s.label {
                breaks.push((widgets.len(), label));
            }
            max_widgets_per_section = max_widgets_per_section.max(s.widgets.len());
            widgets.extend(s.widgets);
        }
        // Account for explicitly-positioned widgets that reach
        // beyond the widest auto-flow row - the grid still has to
        // be wide enough to seat them.
        let max_explicit_col = widgets
            .iter()
            .filter(|w| w.col != AUTO)
            .map(|w| w.col + w.col_span)
            .max()
            .unwrap_or(0);
        let cols = len_u32(max_widgets_per_section)
            .max(max_explicit_col)
            .max(1);

        let mut layout = Self {
            titles: HeaderTitles::none(),
            cols,
            sections: Vec::new(),
            widgets: widgets.clone(),
            cell_size: GRID_DEFAULT_CELL_SIZE,
            width: 0,
            height: 0,
            original_widgets: widgets,
            original_breaks: breaks,
        };
        layout.flow_and_size();
        layout
    }

    /// Override the default column count (which is the widest
    /// section's widget count, or whatever explicit positions
    /// require - whichever is larger). Use to force wrapping:
    /// `.with_cols(2)` on a 4-widget section produces a 2×2 grid.
    /// Recomputes auto-flow placement and window size.
    #[must_use]
    pub fn with_cols(mut self, cols: u32) -> Self {
        self.cols = cols.max(1);
        self.flow_and_size();
        self
    }

    /// Override the default cell size ([`GRID_DEFAULT_CELL_SIZE`]).
    /// The cell is square - this is both the width and height of
    /// one grid cell in logical points.
    #[must_use]
    pub fn with_cell_size(mut self, cell_size: f32) -> Self {
        self.cell_size = cell_size;
        let (w, h) = self.compute_size();
        self.width = w;
        self.height = h;
        self
    }

    /// Like [`Self::with_cols`] but accepts the cell size in the
    /// same call - useful when both are non-default. Equivalent to
    /// `.with_cell_size(s).with_cols(c)`.
    #[must_use]
    pub fn with_grid(mut self, cols: u32, cell_size: f32) -> Self {
        self = self.with_cell_size(cell_size);
        self.with_cols(cols)
    }

    /// Set both header slots at once. Replaces any previously
    /// configured titles. Recomputes the height to account for the
    /// extra band - width stays the same since the header spans the
    /// full grid width.
    ///
    /// ```ignore
    /// use truce_gui_types::layout::{GridLayout, HeaderTitles};
    /// GridLayout::build(sections).with_titles(HeaderTitles::pair("EQ", "v0.1"))
    /// ```
    #[must_use]
    pub fn with_titles(mut self, titles: HeaderTitles) -> Self {
        self.titles = titles;
        let (w, h) = self.compute_size();
        self.width = w;
        self.height = h;
        self
    }

    /// Set the title slot (left, larger / brighter), preserving any
    /// previously configured subtitle.
    ///
    /// ```ignore
    /// GridLayout::build(sections).with_title("EQ")
    /// ```
    #[must_use]
    pub fn with_title(mut self, title: &'static str) -> Self {
        self.titles.title = Some(title);
        let (w, h) = self.compute_size();
        self.width = w;
        self.height = h;
        self
    }

    /// Set the subtitle slot (right, smaller / dimmer), preserving
    /// any previously configured title.
    ///
    /// ```ignore
    /// GridLayout::build(sections).with_subtitle("v0.1")
    /// ```
    #[must_use]
    pub fn with_subtitle(mut self, subtitle: &'static str) -> Self {
        self.titles.subtitle = Some(subtitle);
        let (w, h) = self.compute_size();
        self.width = w;
        self.height = h;
        self
    }

    /// Pixel height of the header band, or `0.0` when neither
    /// title slot is set. Internal helper used by `compute_size`,
    /// `widgets::draw_grid`, and `interaction::build_regions_grid`
    /// to keep the "is there a header?" check in one place.
    pub(crate) fn header_height(&self) -> f32 {
        if self.titles.is_empty() {
            0.0
        } else {
            GRID_HEADER_H
        }
    }

    /// Reset to the pre-flow widget snapshot, run `auto_flow_with_breaks`
    /// against `self.cols`, then recompute window size. Used by
    /// `build`, `with_cols`, and `with_cell_size` so the layout
    /// stays consistent after any configuration change.
    fn flow_and_size(&mut self) {
        self.widgets = self.original_widgets.clone();
        self.sections.clear();
        let breaks: Vec<(usize, &'static str)> = self.original_breaks.clone();
        self.auto_flow_with_breaks(&breaks);
        let (w, h) = self.compute_size();
        self.width = w;
        self.height = h;
    }

    /// Compute the window size from the grid.
    // Window dimensions in logical pixels stay well below 2^23.
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::cast_precision_loss
    )]
    #[must_use]
    pub fn compute_size(&self) -> (u32, u32) {
        let max_col = self
            .widgets
            .iter()
            .map(|w| w.col + w.col_span)
            .max()
            .unwrap_or(1);
        let max_row = self
            .widgets
            .iter()
            .map(|w| w.row + w.row_span)
            .max()
            .unwrap_or(1);
        let section_count = self.sections.len() as f32;

        let w = GRID_PADDING * 2.0 + max_col as f32 * (self.cell_size + GRID_GAP) - GRID_GAP;
        let bottom_label_h = 22.0; // label + value text below the last row of widgets
        let h = self.header_height() + GRID_PADDING + max_row as f32 * (self.cell_size + GRID_GAP)
            - GRID_GAP
            + section_count * GRID_SECTION_H
            + bottom_label_h
            + GRID_PADDING;

        (w as u32, h as u32)
    }

    /// Auto-flow placement with section breaks. Internal helper:
    /// the public builder API exposes [`Self::with_cols`] /
    /// [`Self::with_cell_size`] / [`Self::with_grid`] which call
    /// `flow_and_size` after their field mutation. Previously
    /// exposed as `pub` (along with a `pub auto_flow()` wrapper for
    /// the no-breaks case), which mixed in-place mutation into the
    /// chainable `mut self -> Self` builder surface - confusing.
    /// Now `pub(crate)`; the no-breaks wrapper is gone since
    /// internal callers always pass an explicit slice.
    ///
    /// Each break is `(widget_index, label)`: when the cursor reaches that
    /// widget index, it advances to the next row and records a section label.
    pub(crate) fn auto_flow_with_breaks(&mut self, breaks: &[(usize, &'static str)]) {
        let mut occupied = std::collections::HashSet::new();
        let mut cursor_col: u32 = 0;
        let mut cursor_row: u32 = 0;
        let mut any_emitted = false;

        // First pass: mark cells occupied by explicitly-placed widgets.
        for w in &self.widgets {
            if w.col != AUTO && w.row != AUTO {
                for c in w.col..w.col + w.col_span {
                    for r in w.row..w.row + w.row_span {
                        occupied.insert((c, r));
                    }
                }
            }
        }

        // Second pass: auto-place widgets.
        for (i, w) in self.widgets.iter_mut().enumerate() {
            // Check for section breaks at this widget index.
            for &(break_idx, label) in breaks {
                if break_idx == i {
                    if any_emitted || cursor_col > 0 {
                        cursor_row += 1;
                        cursor_col = 0;
                    }
                    self.sections.push((cursor_row, label));
                    any_emitted = true;
                }
            }

            if w.col != AUTO && w.row != AUTO {
                // Explicitly placed - already marked in first pass.
                any_emitted = true;
                continue;
            }

            // Find next free position that fits this widget.
            loop {
                if cursor_col + w.col_span > self.cols {
                    cursor_col = 0;
                    cursor_row += 1;
                }
                let fits = (0..w.col_span).all(|dc| {
                    (0..w.row_span)
                        .all(|dr| !occupied.contains(&(cursor_col + dc, cursor_row + dr)))
                });
                if fits {
                    break;
                }
                cursor_col += 1;
            }

            w.col = cursor_col;
            w.row = cursor_row;

            for c in w.col..w.col + w.col_span {
                for r in w.row..w.row + w.row_span {
                    occupied.insert((c, r));
                }
            }

            cursor_col += w.col_span;
            any_emitted = true;
        }
    }
}

/// Compute cumulative section-label pixel offsets per row.
///
/// `offsets[r]` is the total vertical shift (from section labels) for row `r`.
#[must_use]
pub fn compute_section_offsets(layout: &GridLayout) -> Vec<f32> {
    let max_row = layout
        .widgets
        .iter()
        .map(|w| w.row + w.row_span)
        .max()
        .unwrap_or(1);
    let mut offsets = vec![0.0f32; max_row as usize + 1];
    let mut cumulative = 0.0;

    for row in 0..=max_row {
        if layout.sections.iter().any(|(r, _)| *r == row) {
            cumulative += GRID_SECTION_H;
        }
        if (row as usize) < offsets.len() {
            offsets[row as usize] = cumulative;
        }
    }
    offsets
}

impl From<PluginLayout> for GridLayout {
    fn from(pl: PluginLayout) -> Self {
        let cols = pl
            .rows
            .iter()
            .map(|r| r.knobs.iter().map(|k| k.span.max(1)).sum::<u32>())
            .max()
            .unwrap_or(1);

        let mut widgets = Vec::new();
        let mut sections = Vec::new();

        for (grid_row, row) in pl.rows.iter().enumerate() {
            let grid_row = len_u32(grid_row);
            if let Some(label) = row.label {
                sections.push((grid_row, label));
            }
            let mut col = 0u32;
            for knob in &row.knobs {
                widgets.push(GridWidget {
                    col,
                    row: grid_row,
                    col_span: knob.span.max(1),
                    row_span: 1,
                    param_id: knob.param_id,
                    label: knob.label,
                    widget: knob.widget,
                    param_id_y: knob.param_id_y,
                    meter_ids: knob.meter_ids.clone(),
                });
                col += knob.span.max(1);
            }
        }

        let mut gl = GridLayout {
            titles: pl.titles.clone(),
            cols,
            sections,
            widgets: widgets.clone(),
            cell_size: pl.knob_size,
            width: 0,
            height: 0,
            // PluginLayout drives placement from `rows` directly,
            // so widgets are already explicitly positioned. The
            // re-flow stash is the same widgets with no breaks -
            // calling `with_cols` would re-run auto-flow against
            // explicit (col,row) values, which is a no-op.
            original_widgets: widgets,
            original_breaks: Vec::new(),
        };
        let (w, h) = gl.compute_size();
        gl.width = w;
        gl.height = h;
        gl
    }
}

/// Layout variant for editor dispatch.
#[derive(Clone, Debug)]
pub enum Layout {
    Rows(PluginLayout),
    Grid(GridLayout),
}

impl Layout {
    #[must_use]
    pub fn width(&self) -> u32 {
        match self {
            Layout::Rows(l) => l.width,
            Layout::Grid(g) => g.width,
        }
    }
    #[must_use]
    pub fn height(&self) -> u32 {
        match self {
            Layout::Rows(l) => l.height,
            Layout::Grid(g) => g.height,
        }
    }
    /// Title slot of the editor's header band - left, larger /
    /// brighter - or `None` when the layout doesn't set one.
    #[must_use]
    pub fn title(&self) -> Option<&str> {
        match self {
            Layout::Rows(l) => l.titles.title,
            Layout::Grid(g) => g.titles.title,
        }
    }
    /// Subtitle slot of the editor's header band - right, smaller /
    /// dimmer - or `None` when the layout doesn't set one.
    #[must_use]
    pub fn subtitle(&self) -> Option<&str> {
        match self {
            Layout::Rows(l) => l.titles.subtitle,
            Layout::Grid(g) => g.titles.subtitle,
        }
    }
}