quadraui 0.6.0

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
//! `PipelineView` primitive: a horizontal row of stage boxes connected by
//! arrows, each with a label, status indicator, and optional action button.
//!
//! Useful for CI/CD pipelines, multi-step wizards, deployment workflows, and
//! any sequential process where stages have discrete pass/fail status.
//!
//! ## Layout model
//!
//! ```text
//! ╭──────────╮      ╭──────────╮      ╭──────────╮
//! │  ✓ Build │ ───▶ │  ● Test  │ ───▶ │  Deploy  │
//! │          │      │  [Retry] │      │  [Go]    │
//! ╰──────────╯      ╰──────────╯      ╰──────────╯
//! ```
//!
//! Stage boxes have equal width (computed from the widest label + padding).
//! Arrow connectors sit between adjacent boxes. Click routing distinguishes
//! action-button vs. stage-body clicks. Keyboard focus moves with Left/Right;
//! Enter fires the focused stage's action if present.
//!
//! ## Event routing
//!
//! `PipelineView` owns layout and hit-testing; backends own painting.
//! After each paint the backend returns a [`PipelineViewLayout`] which the
//! host holds. On mouse events the host calls
//! [`PipelineViewLayout::hit_test`] to translate `(x, y)` into an
//! `Option<PipelineEvent>`. Keyboard events are handled by the host via
//! [`PipelineView::handle_key`].

use crate::event::Rect;
use crate::theme::Theme;
use crate::types::{Color, Modifiers, WidgetId};
use serde::{Deserialize, Serialize};

// ── Data model ───────────────────────────────────────────────────────────────

/// Status of a single pipeline stage.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum StageStatus {
    /// Waiting to run — rendered dim.
    Pending,
    /// Currently executing — rendered with accent colour (optional spinner).
    Active,
    /// Completed successfully — rendered with green checkmark (✓).
    Done,
    /// Execution failed — rendered with red X (✗).
    Failed,
    /// Intentionally bypassed — rendered with strikethrough / grey dash (─).
    Skipped,
    /// Previously completed (or failed), but an upstream stage has since been
    /// re-run — the result is against an older revision and should not
    /// be trusted. Distinct from Pending ("never run") and Done ("trustworthy").
    /// Rendered dim with an `↻` icon to suggest re-running.
    Stale,
}

/// The `status → glyph` table for a stage's status icon — shared by every
/// backend's rasteriser (gtk, macos, tui, win).
///
/// Every arm is a single-codepoint glyph, so callers needing a `char`
/// (e.g. code that paints one cell at a time) can take `.chars().next()` safely.
pub fn status_glyph(status: &StageStatus) -> &'static str {
    match status {
        StageStatus::Done => "✓",
        StageStatus::Active => "●",
        StageStatus::Failed => "✗",
        StageStatus::Pending => "·",
        StageStatus::Skipped => "─",
        StageStatus::Stale => "↻",
    }
}

/// The `status → colour` table for a stage — shared by every backend's
/// rasteriser. Used for **both** the status icon fill and the stage
/// box border: the two mappings were identical in all three pre-existing
/// copies (gtk, macos, tui), so this single table covers both call sites
/// rather than shipping as two near-duplicate tables that could drift.
pub fn status_color(status: &StageStatus, theme: &Theme) -> Color {
    match status {
        StageStatus::Done => theme.git_added,
        StageStatus::Active => theme.accent_bg,
        StageStatus::Failed => theme.error_fg,
        StageStatus::Pending | StageStatus::Skipped | StageStatus::Stale => theme.muted_fg,
    }
}

/// A single stage in a [`PipelineView`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PipelineStage {
    /// Display label for this stage (e.g. "Build", "Test", "Deploy").
    pub label: String,
    /// Execution status controlling colour and icon.
    pub status: StageStatus,
    /// Optional action button text shown at the bottom of the box
    /// (e.g. "Go", "Retry", "Skip"). `None` = no button rendered.
    #[serde(default)]
    pub action: Option<String>,
}

/// Declarative description of a horizontal pipeline widget.
///
/// # Examples
///
/// ```
/// use quadraui::{PipelineHit, PipelineStage, PipelineView, PipelineViewMeasure, StageStatus};
///
/// let pipeline = PipelineView {
///     id: quadraui::WidgetId::new("pipeline:deploy"),
///     stages: vec![
///         PipelineStage {
///             label: "Build".to_string(),
///             status: StageStatus::Done,
///             action: None,
///         },
///         PipelineStage {
///             label: "Deploy".to_string(),
///             status: StageStatus::Pending,
///             action: Some("Go".to_string()),
///         },
///     ],
///     focused_stage: None,
/// };
///
/// let measure = PipelineViewMeasure::new(80.0, 6.0, 4.0, 2.0);
/// let layout = pipeline.layout(0.0, 0.0, measure);
/// assert_eq!(layout.hit_test(1.0, 1.0), PipelineHit::Body(0));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PipelineView {
    pub id: WidgetId,
    /// Ordered list of stages rendered left-to-right.
    pub stages: Vec<PipelineStage>,
    /// Index of the keyboard-focused stage, if any.
    #[serde(default)]
    pub focused_stage: Option<usize>,
}

/// Events emitted by a [`PipelineView`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PipelineEvent {
    /// User clicked (or pressed Enter on) the action button of a stage.
    StageAction { index: usize },
    /// User clicked the body of a stage box (not the action button).
    StageSelected { index: usize },
    /// Key pressed while the widget has focus but not consumed by nav.
    KeyPressed { key: String, modifiers: Modifiers },
}

// ── Layout + hit-testing ─────────────────────────────────────────────────────

/// Resolved layout for a single stage (coordinates in backend-native units).
#[derive(Debug, Clone, PartialEq)]
pub struct StageBounds {
    /// Index into [`PipelineView::stages`].
    pub index: usize,
    /// Full stage-box bounds.
    pub box_bounds: Rect,
    /// Bounds of the status icon area (top half of box).
    pub icon_bounds: Rect,
    /// Bounds of the label area.
    pub label_bounds: Rect,
    /// Bounds of the action button, if this stage has one.
    pub action_bounds: Option<Rect>,
    /// Bounds of the arrow connector leading **to** the *next* stage.
    /// `None` for the last stage.
    pub arrow_bounds: Option<Rect>,
}

/// Classification of a hit-test result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PipelineHit {
    /// Click landed on a stage's action button.
    Action(usize),
    /// Click landed on a stage body (not the action button).
    Body(usize),
    /// Click missed all interactive regions.
    Empty,
}

/// Fully-resolved pipeline layout.
#[derive(Debug, Clone, PartialEq)]
pub struct PipelineViewLayout {
    /// Overall bounding rect of the entire widget.
    pub bounds: Rect,
    /// Per-stage resolved positions.
    pub stages: Vec<StageBounds>,
    /// Uniform stage-box width (all stages share this).
    pub stage_width: f32,
    /// Uniform stage-box height.
    pub stage_height: f32,
    /// Width of each arrow connector between boxes.
    pub arrow_width: f32,
}

impl PipelineViewLayout {
    /// Hit-test a click at `(x, y)`. Returns [`PipelineHit::Action`] if the
    /// click falls inside a stage's action-button bounds, [`PipelineHit::Body`]
    /// for the rest of a stage box, or [`PipelineHit::Empty`] otherwise.
    ///
    /// Action bounds are checked first so they win over the stage body on any
    /// overlap.
    pub fn hit_test(&self, x: f32, y: f32) -> PipelineHit {
        for sb in &self.stages {
            // Action button takes priority.
            if let Some(ab) = sb.action_bounds {
                if contains(ab, x, y) {
                    return PipelineHit::Action(sb.index);
                }
            }
            if contains(sb.box_bounds, x, y) {
                return PipelineHit::Body(sb.index);
            }
        }
        PipelineHit::Empty
    }
}

fn contains(r: Rect, x: f32, y: f32) -> bool {
    x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height
}

// ── Measurement ──────────────────────────────────────────────────────────────

/// Caller-supplied measurements for computing a [`PipelineViewLayout`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PipelineViewMeasure {
    /// Width of the whole widget in backend-native units.
    pub width: f32,
    /// Height of the whole widget.
    pub height: f32,
    /// Width of each arrow connector between boxes.
    pub arrow_width: f32,
    /// Height reserved for the action button at the bottom of each box.
    /// `0` if no stages have actions.
    pub action_height: f32,
}

impl PipelineViewMeasure {
    pub fn new(width: f32, height: f32, arrow_width: f32, action_height: f32) -> Self {
        Self {
            width,
            height,
            arrow_width,
            action_height,
        }
    }
}

impl PipelineView {
    /// Compute the layout for this pipeline.
    ///
    /// Stage width is allocated uniformly: each box gets an equal share of
    /// `measure.width` after subtracting the `(n-1) * arrow_width` connectors.
    /// Callers supply `measure.width` from their known widget rect.
    ///
    /// `origin_x`, `origin_y` are the top-left of the widget in backend-native
    /// coordinates.
    pub fn layout(
        &self,
        origin_x: f32,
        origin_y: f32,
        measure: PipelineViewMeasure,
    ) -> PipelineViewLayout {
        let n = self.stages.len();
        let bounds = Rect::new(origin_x, origin_y, measure.width, measure.height);

        if n == 0 {
            return PipelineViewLayout {
                bounds,
                stages: vec![],
                stage_width: 0.0,
                stage_height: measure.height,
                arrow_width: measure.arrow_width,
            };
        }

        let arrow_total = measure.arrow_width * (n as f32 - 1.0).max(0.0);
        let stage_width = ((measure.width - arrow_total) / n as f32).max(1.0);
        let stage_height = measure.height;

        let mut stages = Vec::with_capacity(n);
        let mut x = origin_x;

        for (i, _stage) in self.stages.iter().enumerate() {
            let box_bounds = Rect::new(x, origin_y, stage_width, stage_height);

            // Icon occupies the top 40% of the box (min 1 unit).
            let icon_h = (stage_height * 0.4).max(1.0);
            let icon_bounds = Rect::new(x, origin_y, stage_width, icon_h);

            // Label sits below the icon.
            let label_y = origin_y + icon_h;
            let label_h = if measure.action_height > 0.0 {
                (stage_height - icon_h - measure.action_height).max(0.0)
            } else {
                (stage_height - icon_h).max(0.0)
            };
            let label_bounds = Rect::new(x, label_y, stage_width, label_h);

            // Action button at the bottom of the box.
            let action_bounds = if self.stages[i].action.is_some() && measure.action_height > 0.0 {
                let ay = origin_y + stage_height - measure.action_height;
                Some(Rect::new(x, ay, stage_width, measure.action_height))
            } else {
                None
            };

            // Arrow connector to the right (not on the last stage).
            let arrow_bounds = if i + 1 < n {
                Some(Rect::new(
                    x + stage_width,
                    origin_y,
                    measure.arrow_width,
                    stage_height,
                ))
            } else {
                None
            };

            stages.push(StageBounds {
                index: i,
                box_bounds,
                icon_bounds,
                label_bounds,
                action_bounds,
                arrow_bounds,
            });

            x += stage_width + measure.arrow_width;
        }

        PipelineViewLayout {
            bounds,
            stages,
            stage_width,
            stage_height,
            arrow_width: measure.arrow_width,
        }
    }

    /// Handle a keyboard event on the focused pipeline.
    ///
    /// - `ArrowLeft` / `ArrowRight` move `focused_stage`.
    /// - `Enter` fires [`PipelineEvent::StageAction`] for the focused stage if
    ///   it has an action, or [`PipelineEvent::StageSelected`] otherwise.
    ///
    /// Returns `Some(event)` if the key was consumed, `None` if the caller
    /// should handle it.
    pub fn handle_key(&mut self, key: &str, modifiers: Modifiers) -> Option<PipelineEvent> {
        let n = self.stages.len();
        if n == 0 {
            return None;
        }
        match key {
            "ArrowLeft" | "Left" => {
                let cur = self.focused_stage.unwrap_or(0);
                self.focused_stage = Some(cur.saturating_sub(1));
                None
            }
            "ArrowRight" | "Right" => {
                let cur = self.focused_stage.unwrap_or(0);
                self.focused_stage = Some((cur + 1).min(n - 1));
                None
            }
            "Enter" => {
                if let Some(idx) = self.focused_stage {
                    if idx < n {
                        if self.stages[idx].action.is_some() {
                            return Some(PipelineEvent::StageAction { index: idx });
                        } else {
                            return Some(PipelineEvent::StageSelected { index: idx });
                        }
                    }
                }
                None
            }
            _ => Some(PipelineEvent::KeyPressed {
                key: key.to_string(),
                modifiers,
            }),
        }
    }
}

// Shared implementation of pipeline-view painting (gtk/macos/win).
// Before this, each backend independently painted the same stage/arrow
// geometry with its own drawing API. This implementation is written against
// [`crate::paint_surface::PaintSurface`] instead of any one backend's drawing
// API, normalizing behavior across backends.
//
// ## Implementation notes for backend unification:
//
// 1. **Status icon vertical position.** Centred within the top third of the
//    box (`icon_h = bh / 3.0`, then `by + icon_h / 2.0 - ih / 2.0`).
// 2. **Label vertical position.** Centred using its own measured height
//    (`by + bh / 2.0 - lh / 2.0`).
// 3. **Label overflow handling.** Drawn width is clamped to
//    `bb.width - 2 * PIPELINE_H_PAD` and the whole box is hard-clipped to
//    `box_bounds`. `PaintSurface` has no ellipsize verb.
// 4. **Action-button tint background.** Fills `action_bounds` with a real
//    alpha composite using `surface_fill_rect_alpha` at `0.15` alpha over
//    `theme.accent_bg`.
// 5. **Action-button label vertical position.** Centred vertically within
//    `action_bounds` (`ab.y + ab.height / 2.0 - bh2 / 2.0`).
// 6. **Focus indicator / arrow-head shape.** Both drawn as two stroked line
//    segments (open chevron). `PaintSurface` has no fill-path primitive.
// 7. **Stage-box border shape.** Stroked as a straight rectangle
//    (`PaintSurface::surface_stroke_rect` is axis-aligned only).
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
#[allow(dead_code)]
pub(crate) mod native_surface_paint {
    use super::{status_color, status_glyph, PipelineView, PipelineViewLayout};
    use crate::event::{Point, Rect};
    use crate::paint_surface::PaintSurface;
    use crate::primitives::layout_metrics::{pixel, pixel_pipeline_view_layout};
    use crate::theme::Theme;

    /// Alpha applied to the action button's tint background — the value
    /// every pre-port backend already agreed on (GTK's `set_source_rgba`
    /// alpha, Windows's `Color::blend` factor). See divergence 4 above.
    const ACTION_TINT_ALPHA: f32 = 0.15;

    /// Paint a [`PipelineView`] into `rect` on `surface`, returning
    /// [`PipelineViewLayout`] for host click dispatch — same contract as
    /// every deleted per-backend `draw_pipeline_view`.
    pub(crate) fn paint(
        view: &PipelineView,
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        rect: Rect,
    ) -> PipelineViewLayout {
        let layout = pixel_pipeline_view_layout(view, rect.x, rect.y, rect.width, rect.height);

        if rect.width <= 0.0 || rect.height <= 0.0 {
            return layout;
        }

        for sb in &layout.stages {
            let stage = &view.stages[sb.index];
            let is_focused = view.focused_stage == Some(sb.index);
            let bb = sb.box_bounds;

            if bb.width <= 0.0 || bb.height <= 0.0 {
                continue;
            }

            // ── Box fill + border (straight rect on every backend — see
            // divergence 7 above) ───────────────────────────────────────
            surface.surface_fill_rect(bb, theme.surface_bg);
            let border_color = status_color(&stage.status, theme);
            surface.surface_stroke_rect(bb, border_color, pixel::PIPELINE_BORDER_WIDTH as f32);

            // ── Focus indicator (▼ chevron above the box — divergence 6) ──
            if is_focused {
                let ind_x = bb.x + bb.width / 2.0;
                let tri_tip_y = bb.y - 1.0;
                let tri_base_y = bb.y - pixel::PIPELINE_FOCUS_INDICATOR_H + 1.0;
                let half_w = 5.0;
                surface.surface_draw_line(
                    Point::new(ind_x - half_w, tri_base_y),
                    Point::new(ind_x, tri_tip_y),
                    theme.muted_fg,
                    1.5,
                );
                surface.surface_draw_line(
                    Point::new(ind_x, tri_tip_y),
                    Point::new(ind_x + half_w, tri_base_y),
                    theme.muted_fg,
                    1.5,
                );
            }

            // Icon + label + action are all clipped to the box — see
            // divergence 3 above for why every backend now hard-clips.
            surface.surface_push_clip(bb);

            // ── Status icon (top third of box — divergence 1) ────────────
            let icon_text = status_glyph(&stage.status);
            let icon_color = status_color(&stage.status, theme);
            let (iw, ih) = surface.surface_measure_text(icon_text);
            let icon_h = bb.height / 3.0;
            let icon_cx = bb.x + bb.width / 2.0 - iw / 2.0;
            let icon_cy = bb.y + icon_h / 2.0 - ih / 2.0;
            surface.surface_draw_text_run(
                Rect::new(icon_cx, icon_cy, iw.max(1.0), ih.max(1.0)),
                icon_text,
                icon_color,
            );

            // ── Label (centred, clamped + hard-clipped — divergences 2/3) ──
            if !stage.label.is_empty() {
                let (lw, lh) = surface.surface_measure_text(&stage.label);
                let avail_w = (bb.width - 2.0 * pixel::PIPELINE_H_PAD as f32).max(0.0);
                let draw_w = lw.min(avail_w).max(1.0);
                let label_cx = bb.x + bb.width / 2.0 - draw_w / 2.0;
                let label_cy = bb.y + bb.height / 2.0 - lh / 2.0;
                surface.surface_draw_text_run(
                    Rect::new(label_cx, label_cy, draw_w, lh.max(1.0)),
                    &stage.label,
                    theme.foreground,
                );
            }

            // ── Action button (bottom strip — divergences 4/5) ────────────
            // A tinted, bordered button — not a `[label]` glyph, which
            // reads as a terminal affordance on a pixel canvas (the TUI
            // painter still brackets its own action label).
            if let (Some(ab), Some(action_text)) = (sb.action_bounds, &stage.action) {
                surface.surface_fill_rect_alpha(ab, theme.accent_bg, ACTION_TINT_ALPHA);
                surface.surface_stroke_rect(ab, theme.accent_bg, 1.0);

                let (bw2, bh2) = surface.surface_measure_text(action_text);
                let btn_cx = ab.x + ab.width / 2.0 - bw2 / 2.0;
                let btn_cy = ab.y + ab.height / 2.0 - bh2 / 2.0;
                surface.surface_draw_text_run(
                    Rect::new(btn_cx, btn_cy, bw2.max(1.0), bh2.max(1.0)),
                    action_text,
                    theme.accent_bg,
                );
            }

            surface.surface_pop_clip();

            // ── Arrow connector (line + chevron head — divergence 6) ──────
            if let Some(arrow) = sb.arrow_bounds {
                let ax = arrow.x;
                let mid_y = arrow.y + arrow.height / 2.0;
                let aw = arrow.width;

                surface.surface_draw_line(
                    Point::new(ax, mid_y),
                    Point::new(ax + aw - 6.0, mid_y),
                    theme.muted_fg,
                    1.0,
                );

                let tip_x = ax + aw - 1.0;
                let tail_x = ax + aw - 7.0;
                let half_h = 4.0;
                surface.surface_draw_line(
                    Point::new(tail_x, mid_y - half_h),
                    Point::new(tip_x, mid_y),
                    theme.muted_fg,
                    1.0,
                );
                surface.surface_draw_line(
                    Point::new(tip_x, mid_y),
                    Point::new(tail_x, mid_y + half_h),
                    theme.muted_fg,
                    1.0,
                );
            }
        }

        layout
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::backend::ImagePaintResult;
        use crate::event::Viewport;
        use crate::primitives::pipeline_view::{PipelineStage, StageStatus};
        use crate::types::{Color, WidgetId};
        use crate::Image;

        /// Records every drawing verb `paint` issues — mirrors
        /// `primitives::diff_view`'s own `RecordingSurface`.
        #[derive(Default)]
        struct RecordingSurface {
            fills: Vec<(Rect, Color)>,
            strokes: Vec<(Rect, Color)>,
            text_runs: Vec<(Rect, String, Color)>,
            lines: Vec<(Point, Point, Color)>,
            clip_pushes: Vec<Rect>,
            clip_pops: usize,
        }

        impl PaintSurface for RecordingSurface {
            fn surface_begin_frame(&mut self, _viewport: Viewport) {}
            fn surface_end_frame(&mut self) {}
            fn surface_viewport(&self) -> Viewport {
                Viewport::new(300.0, 80.0, 1.0)
            }
            fn surface_line_height(&self) -> f32 {
                16.0
            }
            fn surface_char_width(&self) -> f32 {
                8.0
            }
            fn surface_measure_text(&self, text: &str) -> (f32, f32) {
                (text.chars().count() as f32 * 8.0, 14.0)
            }
            fn surface_fill_rect(&mut self, rect: Rect, color: Color) {
                self.fills.push((rect, color));
            }
            fn surface_fill_rounded_rect(&mut self, rect: Rect, _radius: f32, color: Color) {
                self.fills.push((rect, color));
            }
            fn surface_stroke_rect(&mut self, rect: Rect, color: Color, _stroke_width: f32) {
                self.strokes.push((rect, color));
            }
            fn surface_stroke_rounded_rect(
                &mut self,
                rect: Rect,
                _radius: f32,
                color: Color,
                _stroke_width: f32,
            ) {
                self.strokes.push((rect, color));
            }
            fn surface_draw_text_run(&mut self, rect: Rect, text: &str, color: Color) {
                self.text_runs.push((rect, text.to_string(), color));
            }
            fn surface_draw_line(
                &mut self,
                from: crate::Point,
                to: crate::Point,
                color: Color,
                _stroke_width: f32,
            ) {
                self.lines.push((from, to, color));
            }
            fn surface_push_clip(&mut self, rect: Rect) {
                self.clip_pushes.push(rect);
            }
            fn surface_pop_clip(&mut self) {
                self.clip_pops += 1;
            }
            fn surface_draw_image(&mut self, _rect: Rect, _image: &Image) -> ImagePaintResult {
                ImagePaintResult::Unsupported
            }
        }

        fn make_view() -> PipelineView {
            PipelineView {
                id: WidgetId::new("pipe"),
                stages: vec![
                    PipelineStage {
                        label: "Build".into(),
                        status: StageStatus::Done,
                        action: None,
                    },
                    PipelineStage {
                        label: "Test".into(),
                        status: StageStatus::Active,
                        action: Some("Retry".into()),
                    },
                ],
                focused_stage: Some(0),
            }
        }

        #[test]
        fn zero_size_rect_paints_nothing() {
            let view = make_view();
            let mut surface = RecordingSurface::default();
            paint(
                &view,
                &mut surface,
                &Theme::default(),
                Rect::new(0.0, 0.0, 0.0, 0.0),
            );
            assert!(surface.fills.is_empty());
            assert!(surface.text_runs.is_empty());
        }

        /// Regression for divergence 7: the stage-box border is a
        /// straight `surface_stroke_rect`, never a rounded fill/stroke.
        #[test]
        fn stage_box_border_is_a_straight_rect() {
            let view = make_view();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &view,
                &mut surface,
                &Theme::default(),
                Rect::new(0.0, 0.0, 300.0, 80.0),
            );
            let bb = layout.stages[0].box_bounds;
            assert!(surface.strokes.iter().any(|(r, _)| *r == bb));
        }

        /// Regression for divergence 6: the focused stage's indicator is
        /// two line strokes (a chevron), not a filled path.
        #[test]
        fn focused_stage_paints_a_two_line_chevron() {
            let view = make_view();
            let mut surface = RecordingSurface::default();
            paint(
                &view,
                &mut surface,
                &Theme::default(),
                Rect::new(0.0, 0.0, 300.0, 80.0),
            );
            assert_eq!(
                surface.lines.len(),
                2 + 3,
                "1 focus chevron (2 lines) + 1 arrow connector (3 lines)"
            );
        }

        /// Regression for divergence 3: icon + label + action are all
        /// clipped to the stage box (one push/pop bracket per stage).
        #[test]
        fn each_stage_clips_its_content_to_the_box() {
            let view = make_view();
            let mut surface = RecordingSurface::default();
            paint(
                &view,
                &mut surface,
                &Theme::default(),
                Rect::new(0.0, 0.0, 300.0, 80.0),
            );
            assert_eq!(surface.clip_pushes.len(), surface.clip_pops);
            assert_eq!(surface.clip_pushes.len(), view.stages.len());
        }

        /// The action button paints a translucent `accent_bg` tint (via
        /// `surface_fill_rect_alpha` at `0.15` alpha), covering the whole
        /// `action_bounds` — every backend gets this now.
        #[test]
        fn action_button_paints_a_translucent_tint_over_the_full_bounds() {
            let view = make_view();
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &view,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 300.0, 80.0),
            );
            let ab = layout.stages[1]
                .action_bounds
                .expect("stage 1 has an action button");
            let tint = surface
                .fills
                .iter()
                .find(|(r, _)| *r == ab)
                .map(|(_, c)| *c)
                .expect("action tint fill over the full action_bounds");
            assert_eq!(tint.r, theme.accent_bg.r);
            assert_eq!(tint.g, theme.accent_bg.g);
            assert_eq!(tint.b, theme.accent_bg.b);
            assert!(
                tint.a < theme.accent_bg.a,
                "tint alpha ({}) must be lower than accent_bg's own opaque alpha ({})",
                tint.a,
                theme.accent_bg.a,
            );
        }

        /// The action button's label paints as plain text inside a
        /// stroked border, not a `[label]` bracket glyph — the TUI
        /// painter keeps the brackets.
        #[test]
        fn action_button_paints_a_border_not_bracket_text() {
            let view = make_view();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &view,
                &mut surface,
                &Theme::default(),
                Rect::new(0.0, 0.0, 300.0, 80.0),
            );
            let ab = layout.stages[1]
                .action_bounds
                .expect("stage 1 has an action button");

            assert!(
                surface.text_runs.iter().any(|(_, t, _)| t == "Retry"),
                "the action label itself must still be painted; text_runs \
                 were {:?}",
                surface.text_runs,
            );
            assert!(
                !surface.text_runs.iter().any(|(_, t, _)| t.contains('[')),
                "no bracket glyph should be painted for the action label; \
                 text_runs were {:?}",
                surface.text_runs,
            );
            assert!(
                surface.strokes.iter().any(|(r, _)| *r == ab),
                "the action button must stroke a border around its full \
                 bounds; strokes were {:?}",
                surface.strokes,
            );
        }

        /// Icon and label are both centred using their measured size:
        #[test]
        fn icon_and_label_are_centred_using_their_measured_size() {
            let view = make_view();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &view,
                &mut surface,
                &Theme::default(),
                Rect::new(0.0, 0.0, 300.0, 80.0),
            );
            let bb = layout.stages[0].box_bounds;
            let (_, icon_text, _) = surface
                .text_runs
                .iter()
                .find(|(_, t, _)| t == status_glyph(&StageStatus::Done))
                .expect("icon text painted");
            assert_eq!(icon_text, status_glyph(&StageStatus::Done));
            let (label_rect, _, _) = surface
                .text_runs
                .iter()
                .find(|(_, t, _)| t == "Build")
                .expect("label text painted");
            let (lw, lh) = surface.surface_measure_text("Build");
            assert!((label_rect.width - lw).abs() < 0.01);
            let expected_cy = bb.y + bb.height / 2.0 - lh / 2.0;
            assert!((label_rect.y - expected_cy).abs() < 0.01);
        }
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::WidgetId;

    fn make_pipeline() -> PipelineView {
        PipelineView {
            id: WidgetId::new("pipe"),
            stages: vec![
                PipelineStage {
                    label: "Build".into(),
                    status: StageStatus::Done,
                    action: None,
                },
                PipelineStage {
                    label: "Test".into(),
                    status: StageStatus::Active,
                    action: Some("Retry".into()),
                },
                PipelineStage {
                    label: "Deploy".into(),
                    status: StageStatus::Pending,
                    action: Some("Go".into()),
                },
            ],
            focused_stage: None,
        }
    }

    fn measure() -> PipelineViewMeasure {
        // 300 wide, 4 arrow units each side, action area 10 units tall.
        PipelineViewMeasure::new(300.0, 60.0, 4.0, 10.0)
    }

    // ── Construction ────────────────────────────────────────────────────

    #[test]
    fn construction_and_stage_count() {
        let p = make_pipeline();
        assert_eq!(p.stages.len(), 3);
        assert_eq!(p.stages[0].label, "Build");
        assert_eq!(p.stages[1].status, StageStatus::Active);
        assert!(p.stages[2].action.is_some());
    }

    #[test]
    fn stage_mutation() {
        let mut p = make_pipeline();
        p.stages[0].status = StageStatus::Failed;
        assert_eq!(p.stages[0].status, StageStatus::Failed);
        p.stages.push(PipelineStage {
            label: "Notify".into(),
            status: StageStatus::Pending,
            action: None,
        });
        assert_eq!(p.stages.len(), 4);
    }

    // ── Layout ──────────────────────────────────────────────────────────

    #[test]
    fn layout_equal_width_boxes() {
        let p = make_pipeline();
        let layout = p.layout(0.0, 0.0, measure());
        // 3 stages, 2 arrows × 4.0 = 8.0; (300 - 8) / 3 ≈ 97.33
        let expected_w = (300.0 - 8.0) / 3.0;
        assert!(
            (layout.stage_width - expected_w).abs() < 0.01,
            "stage_width = {}, expected ~{}",
            layout.stage_width,
            expected_w
        );
        for sb in &layout.stages {
            assert!(
                (sb.box_bounds.width - expected_w).abs() < 0.01,
                "stage {} box width = {}, expected {}",
                sb.index,
                sb.box_bounds.width,
                expected_w
            );
        }
    }

    #[test]
    fn layout_origin_offset() {
        let p = make_pipeline();
        let layout = p.layout(10.0, 5.0, measure());
        assert_eq!(layout.bounds.x, 10.0);
        assert_eq!(layout.bounds.y, 5.0);
        assert_eq!(layout.stages[0].box_bounds.x, 10.0);
        assert_eq!(layout.stages[0].box_bounds.y, 5.0);
    }

    #[test]
    fn layout_arrow_between_stages() {
        let p = make_pipeline();
        let layout = p.layout(0.0, 0.0, measure());
        // Arrow after stage 0.
        let arrow = layout.stages[0].arrow_bounds.expect("arrow after stage 0");
        assert_eq!(arrow.x, layout.stages[0].box_bounds.x + layout.stage_width);
        assert_eq!(arrow.width, 4.0);
        // No arrow after last stage.
        assert!(layout.stages[2].arrow_bounds.is_none());
    }

    #[test]
    fn layout_action_bounds_present_when_action_set() {
        let p = make_pipeline();
        let layout = p.layout(0.0, 0.0, measure());
        // Stage 0 has no action.
        assert!(layout.stages[0].action_bounds.is_none());
        // Stage 1 has "Retry".
        let ab = layout.stages[1]
            .action_bounds
            .expect("action bounds for stage 1");
        assert_eq!(ab.height, 10.0);
        // Stage 2 has "Go".
        assert!(layout.stages[2].action_bounds.is_some());
    }

    #[test]
    fn layout_empty_pipeline_is_safe() {
        let p = PipelineView {
            id: WidgetId::new("empty"),
            stages: vec![],
            focused_stage: None,
        };
        let layout = p.layout(0.0, 0.0, PipelineViewMeasure::new(300.0, 60.0, 4.0, 10.0));
        assert_eq!(layout.stages.len(), 0);
        assert_eq!(layout.stage_width, 0.0);
    }

    // ── Hit-testing ─────────────────────────────────────────────────────

    #[test]
    fn hit_test_action_button_returns_action_event() {
        let p = make_pipeline();
        let layout = p.layout(0.0, 0.0, measure());
        // Stage 1 has action bounds.
        let ab = layout.stages[1].action_bounds.unwrap();
        let cx = ab.x + ab.width / 2.0;
        let cy = ab.y + ab.height / 2.0;
        assert_eq!(layout.hit_test(cx, cy), PipelineHit::Action(1));
    }

    #[test]
    fn hit_test_stage_body_returns_body_event() {
        let p = make_pipeline();
        let layout = p.layout(0.0, 0.0, measure());
        let bb = layout.stages[0].box_bounds;
        // Click in the top half of stage 0 (no action there).
        let cx = bb.x + bb.width / 2.0;
        let cy = bb.y + bb.height / 4.0;
        assert_eq!(layout.hit_test(cx, cy), PipelineHit::Body(0));
    }

    #[test]
    fn hit_test_miss_returns_empty() {
        let p = make_pipeline();
        let layout = p.layout(0.0, 0.0, measure());
        // Click past the right edge.
        assert_eq!(layout.hit_test(500.0, 30.0), PipelineHit::Empty);
        // Click above the widget.
        assert_eq!(layout.hit_test(50.0, -1.0), PipelineHit::Empty);
    }

    #[test]
    fn hit_test_arrow_region_returns_empty() {
        let p = make_pipeline();
        let layout = p.layout(0.0, 0.0, measure());
        let arrow = layout.stages[0].arrow_bounds.unwrap();
        // Arrow connector is non-interactive — no PipelineHit returned for it.
        let hit = layout.hit_test(arrow.x + arrow.width / 2.0, arrow.y + arrow.height / 2.0);
        assert_eq!(hit, PipelineHit::Empty);
    }

    // ── Keyboard navigation ─────────────────────────────────────────────

    #[test]
    fn keyboard_right_moves_focus() {
        let mut p = make_pipeline();
        p.focused_stage = Some(0);
        p.handle_key("Right", Modifiers::default());
        assert_eq!(p.focused_stage, Some(1));
        p.handle_key("ArrowRight", Modifiers::default());
        assert_eq!(p.focused_stage, Some(2));
    }

    #[test]
    fn keyboard_right_clamps_at_last() {
        let mut p = make_pipeline();
        p.focused_stage = Some(2); // last
        p.handle_key("Right", Modifiers::default());
        assert_eq!(p.focused_stage, Some(2));
    }

    #[test]
    fn keyboard_left_moves_focus() {
        let mut p = make_pipeline();
        p.focused_stage = Some(2);
        p.handle_key("Left", Modifiers::default());
        assert_eq!(p.focused_stage, Some(1));
        p.handle_key("ArrowLeft", Modifiers::default());
        assert_eq!(p.focused_stage, Some(0));
    }

    #[test]
    fn keyboard_left_clamps_at_zero() {
        let mut p = make_pipeline();
        p.focused_stage = Some(0);
        p.handle_key("Left", Modifiers::default());
        assert_eq!(p.focused_stage, Some(0));
    }

    #[test]
    fn keyboard_enter_fires_action_when_present() {
        let mut p = make_pipeline();
        p.focused_stage = Some(1); // has "Retry" action
        let event = p.handle_key("Enter", Modifiers::default());
        assert_eq!(event, Some(PipelineEvent::StageAction { index: 1 }));
    }

    #[test]
    fn keyboard_enter_fires_selected_when_no_action() {
        let mut p = make_pipeline();
        p.focused_stage = Some(0); // no action
        let event = p.handle_key("Enter", Modifiers::default());
        assert_eq!(event, Some(PipelineEvent::StageSelected { index: 0 }));
    }

    #[test]
    fn keyboard_enter_no_focus_is_noop() {
        let mut p = make_pipeline();
        p.focused_stage = None;
        let event = p.handle_key("Enter", Modifiers::default());
        assert_eq!(event, None);
    }

    #[test]
    fn keyboard_unknown_key_passes_through() {
        let mut p = make_pipeline();
        p.focused_stage = Some(0);
        let event = p.handle_key("Escape", Modifiers::default());
        assert!(matches!(event, Some(PipelineEvent::KeyPressed { .. })));
    }

    // ── Serde ────────────────────────────────────────────────────────────

    #[test]
    fn serde_roundtrip() {
        let p = make_pipeline();
        let json = serde_json::to_string(&p).unwrap();
        let back: PipelineView = serde_json::from_str(&json).unwrap();
        assert_eq!(p, back);
    }

    #[test]
    fn event_serde_roundtrip() {
        let events = vec![
            PipelineEvent::StageAction { index: 2 },
            PipelineEvent::StageSelected { index: 0 },
            PipelineEvent::KeyPressed {
                key: "Escape".into(),
                modifiers: Modifiers::default(),
            },
        ];
        for e in &events {
            let json = serde_json::to_string(e).unwrap();
            let back: PipelineEvent = serde_json::from_str(&json).unwrap();
            assert_eq!(e, &back);
        }
    }
}