cargo-port 0.1.2

A TUI for inspecting and managing Rust projects
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
use ratatui::style::Modifier;
use ratatui::style::Style;
use ratatui::text::Line;
use ratatui::text::Span;
pub(super) use tui_pane::ColumnSpec;
pub(super) use tui_pane::ColumnWidths;
use tui_pane::error_color;
use tui_pane::label_color;
use tui_pane::secondary_text_color;
use tui_pane::text_default;
use tui_pane::title_color;
use unicode_width::UnicodeWidthStr;

use super::render;
use super::theme_roles;
use crate::ci::CiStatus;
use crate::constants::IN_SYNC;
use crate::project::GitStatus;
use crate::project::WorktreeHealth;
use crate::project::WorktreeHealth::Normal;

// ── Column indices ──────────────────────────────────────────────────
pub(super) const COL_NAME: usize = 0;
pub(super) const COL_LINT: usize = 1;
pub(super) const COL_CI: usize = 2;
pub(super) const COL_LANG: usize = 3;
pub(super) const COL_GIT_PATH: usize = 4;
pub(super) const COL_SYNC: usize = 5;
pub(super) const COL_MAIN: usize = 6;
pub(super) const COL_DISK: usize = 7;
pub(super) const NUM_COLS: usize = 8;

// ── Column definition types ─────────────────────────────────────────

#[derive(Clone, Copy)]
pub(super) enum ColumnWidth {
    Fixed(usize),
    Fit { min: usize },
}

#[derive(Clone, Copy)]
pub(super) enum Align {
    Left,
    Right,
    Center,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum HeaderMode {
    Standard,
    BorrowLeft,
    Hidden,
}

#[derive(Clone, Copy)]
pub(super) struct ColumnDef {
    /// Header labels in ascending width order. The renderer picks the longest
    /// label whose display width fits the resolved column. Single-element
    /// slices behave like a static header.
    pub header_levels: &'static [&'static str],
    pub width:         ColumnWidth,
    pub align:         Align,
    pub gap:           usize,
    pub header_mode:   HeaderMode,
}

impl ColumnDef {
    /// Shortest label — defines the column's minimum header footprint.
    pub(super) fn header_min(&self) -> &'static str {
        self.header_levels.first().copied().unwrap_or("")
    }

    /// Longest label — used by `BorrowLeft` columns when computing how much
    /// space to borrow from neighbors.
    pub(super) fn header_max(&self) -> &'static str {
        self.header_levels.last().copied().unwrap_or("")
    }

    /// Pick the longest label whose display width fits `width`. Falls back to
    /// the shortest label so the header is never empty when a label exists.
    pub(super) fn header_for_width(&self, width: usize) -> &'static str {
        self.header_levels
            .iter()
            .rev()
            .copied()
            .find(|label| display_width(label) <= width)
            .unwrap_or_else(|| self.header_min())
    }

    pub(super) fn seed_width(&self) -> usize {
        let base = match self.width {
            ColumnWidth::Fixed(width) | ColumnWidth::Fit { min: width } => width,
        };
        if matches!(self.width, ColumnWidth::Fit { .. }) && self.header_mode == HeaderMode::Standard
        {
            base.max(display_width(self.header_min()))
        } else {
            base
        }
    }
}

/// The canonical column layout — single source of truth.
pub(super) const fn column_defs(lint_enabled: bool) -> [ColumnDef; NUM_COLS] {
    [
        // 0: Name
        ColumnDef {
            header_levels: &[""],
            width:         ColumnWidth::Fit { min: 10 },
            align:         Align::Left,
            gap:           0,
            header_mode:   HeaderMode::Standard,
        },
        // 1: Lint — borrows "Li" from Name padding
        ColumnDef {
            header_levels: if lint_enabled { &["Lint"] } else { &[""] },
            width:         ColumnWidth::Fixed(if lint_enabled { 2 } else { 0 }),
            align:         Align::Left,
            gap:           0,
            header_mode:   if lint_enabled {
                HeaderMode::BorrowLeft
            } else {
                HeaderMode::Hidden
            },
        },
        // 2: CI
        ColumnDef {
            header_levels: &["CI"],
            width:         ColumnWidth::Fixed(2),
            align:         Align::Left,
            gap:           1,
            header_mode:   HeaderMode::Standard,
        },
        // 3: Lang
        ColumnDef {
            header_levels: &[""],
            width:         ColumnWidth::Fixed(2),
            align:         Align::Left,
            gap:           1,
            header_mode:   HeaderMode::Hidden,
        },
        // 4: Git path status glyph, labeled as Git in the header.
        // Right-align so "t" sits above the right edge of the 2-wide emoji.
        ColumnDef {
            header_levels: &["Git"],
            width:         ColumnWidth::Fixed(2),
            align:         Align::Right,
            gap:           1,
            header_mode:   HeaderMode::BorrowLeft,
        },
        // 5: Origin/upstream sync status — promotes Og → Orig → Origin
        // as the column widens to fit cell content.
        ColumnDef {
            header_levels: &["Og", "Orig", "Origin"],
            width:         ColumnWidth::Fit { min: 0 },
            align:         Align::Right,
            gap:           1,
            header_mode:   HeaderMode::Standard,
        },
        // 6: Local main delta — promotes M → Mn → Main as the column widens.
        ColumnDef {
            header_levels: &["M", "Mn", "Main"],
            width:         ColumnWidth::Fit { min: 0 },
            align:         Align::Right,
            gap:           1,
            header_mode:   HeaderMode::Standard,
        },
        // 7: Disk — leading gap keeps a space before the size even when the
        // Main delta column is non-empty (e.g. "↑5" abutting "107.7 GiB").
        ColumnDef {
            header_levels: &["Disk"],
            width:         ColumnWidth::Fit { min: 4 },
            align:         Align::Right,
            gap:           1,
            header_mode:   HeaderMode::Standard,
        },
    ]
}

// ── Cell / row types ────────────────────────────────────────────────

#[derive(Default)]
pub(super) struct CellContent {
    pub text:           String,
    pub style:          Style,
    pub segments:       Option<Vec<StyledSegment>>,
    pub align_override: Option<Align>,
    pub suffix:         Option<String>,
    pub suffix_style:   Option<Style>,
}

#[derive(Clone)]
pub(super) struct StyledSegment {
    pub text:  String,
    pub style: Style,
}

/// Resolved Lint column cell — bundles the icon glyph and its style so the
/// two cannot drift. Production code constructs one via `App::lint_cell`
/// (see `tui/app/lint.rs`), which derives both fields from a single
/// [`LintStatus`](crate::lint::LintStatus). Non-Rust child rows use
/// [`Self::hidden`]; tests/fixtures that just need a glyph use
/// `Self::with_icon`.
#[derive(Clone, Copy)]
pub(super) struct LintCell {
    icon:  &'static str,
    style: Style,
}

impl LintCell {
    /// Empty cell — used for non-Rust child rows that have no lint state.
    pub(super) const fn hidden() -> Self {
        Self {
            icon:  " ",
            style: Style::new(),
        }
    }

    /// Test/fixture helper: a specific icon with the default style.
    /// Production code should use `App::lint_cell` instead so the style
    /// stays in sync with the status.
    #[cfg(test)]
    pub(super) const fn with_icon(icon: &'static str) -> Self {
        Self {
            icon,
            style: Style::new(),
        }
    }

    /// Construct from already-resolved icon + style. Visible to the App
    /// layer so `App::lint_cell` can populate both fields from a single
    /// [`LintStatus`](crate::lint::LintStatus).
    pub(super) const fn from_parts(icon: &'static str, style: Style) -> Self {
        Self { icon, style }
    }

    pub(super) const fn icon(&self) -> &'static str { self.icon }
    pub(super) const fn style(&self) -> Style { self.style }
}

#[derive(Clone)]
pub(super) struct ProjectRow<'a> {
    pub prefix:            &'a str,
    pub name:              &'a str,
    pub name_segments:     Option<Vec<StyledSegment>>,
    pub git_status:        Option<GitStatus>,
    pub lint:              LintCell,
    pub disk:              &'a str,
    pub disk_style:        Style,
    pub disk_suffix:       Option<&'a str>,
    pub disk_suffix_style: Option<Style>,
    pub lang_icon:         &'a str,
    pub git_origin_sync:   &'a str,
    pub git_main:          &'a str,
    pub ci:                Option<CiStatus>,
    pub deleted:           bool,
    pub worktree_health:   WorktreeHealth,
}

pub(super) struct RowCells {
    pub cells:           [CellContent; NUM_COLS],
    pub prefix:          String,
    pub deleted:         bool,
    pub worktree_health: WorktreeHealth,
}

// ── Resolved widths ─────────────────────────────────────────────────

/// Project-list column widths. Thin wrapper around the generic
/// [`ColumnWidths`] primitive that adds the lint-enabled flag,
/// the generation counter App uses to invalidate cached widths
/// after tree changes, and the project-list-specific seeding
/// from `column_defs`.
pub(super) struct ProjectListWidths {
    inner:          ColumnWidths,
    lint_enabled:   bool,
    pub generation: u64,
}

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

impl ProjectListWidths {
    /// Seed from column definitions: Fixed columns get their width,
    /// Fit columns get their minimum.
    pub(super) fn new(lint_enabled: bool) -> Self {
        Self {
            inner: ColumnWidths::new(project_list_specs(lint_enabled)),
            lint_enabled,
            generation: u64::MAX,
        }
    }

    /// Update a Fit column with observed content width. No-op for
    /// Fixed columns (`ColumnSpec::fixed` caps `max == min`).
    pub(super) fn observe(&mut self, col: usize, width: usize) {
        self.inner.observe_cell_usize(col, width);
    }

    /// Resolved width for a column.
    pub(super) fn get(&self, col: usize) -> usize { usize::from(self.inner.get(col)) }

    /// Total display width of all columns including gaps.
    pub(super) fn total_width(&self) -> usize {
        let defs = column_defs(self.lint_enabled);
        let mut total = 0;
        for (i, def) in defs.iter().enumerate() {
            total += def.gap + self.get(i);
        }
        total
    }

    pub const fn lint_enabled(&self) -> bool { self.lint_enabled }
}

/// Map the project-list `column_defs` into [`ColumnSpec`]s for
/// `ColumnWidths`.
fn project_list_specs(lint_enabled: bool) -> Vec<ColumnSpec> {
    column_defs(lint_enabled)
        .iter()
        .map(|def| {
            let seed = u16::try_from(def.seed_width()).unwrap_or(u16::MAX);
            match def.width {
                ColumnWidth::Fixed(_) => ColumnSpec::fixed(seed),
                ColumnWidth::Fit { .. } => ColumnSpec::fit(seed),
            }
        })
        .collect()
}

// ── Display-width helpers ───────────────────────────────────────────

/// Terminal display width of a string, accounting for multi-byte and wide
/// characters. Use this for ALL layout calculations — never `.len()`.
pub(super) fn display_width(s: &str) -> usize { UnicodeWidthStr::width(s) }

/// Pad a string to a target display width using trailing spaces (left-aligned).
pub(super) fn pad_right(s: &str, target: usize) -> String {
    let w = display_width(s);
    let pad = target.saturating_sub(w);
    format!("{s}{}", " ".repeat(pad))
}

/// Pad a string to a target display width using leading spaces (right-aligned).
pub(super) fn pad_left(s: &str, target: usize) -> String {
    let w = display_width(s);
    let pad = target.saturating_sub(w);
    format!("{}{s}", " ".repeat(pad))
}

/// Pad a string to a target display width, centered.
fn pad_center(s: &str, target: usize) -> String {
    let w = display_width(s);
    let total_pad = target.saturating_sub(w);
    let left = total_pad / 2;
    let right = total_pad - left;
    format!("{}{s}{}", " ".repeat(left), " ".repeat(right))
}

// ── Row rendering ───────────────────────────────────────────────────

/// Render a `RowCells` into a styled `Line` using the column definitions and
/// resolved widths. Replaces `project_row_spans`.
pub(super) fn row_to_line(row: &RowCells, widths: &ProjectListWidths) -> Line<'static> {
    let defs = column_defs(widths.lint_enabled());
    let mut spans = Vec::with_capacity(NUM_COLS);
    // Track which span indices are suffix spans (exempt from strikethrough).
    let mut suffix_indices: Vec<usize> = Vec::new();

    for (i, cell) in row.cells.iter().enumerate() {
        let col_width = widths.get(i);
        let align = cell.align_override.unwrap_or(defs[i].align);

        if col_width == 0 {
            spans.push(Span::styled(String::new(), cell.style));
            continue;
        }

        // Suffix handling: split the column into text + suffix spans.
        if let Some(suffix) = &cell.suffix {
            let suffix_w = display_width(suffix);
            let text_w = col_width.saturating_sub(suffix_w);
            let text_padded = pad_left(&cell.text, text_w);
            let gap = " ".repeat(defs[i].gap);
            spans.push(Span::styled(format!("{gap}{text_padded}"), cell.style));
            let suffix_style = cell.suffix_style.unwrap_or(cell.style);
            suffix_indices.push(spans.len());
            spans.push(Span::styled(suffix.clone(), suffix_style));
            continue;
        }

        if i == COL_NAME
            && let Some(segments) = &cell.segments
        {
            let prefix_w = display_width(&row.prefix);
            let available = col_width.saturating_sub(prefix_w);
            let content_w = segments
                .iter()
                .map(|segment| display_width(&segment.text))
                .sum();
            spans.push(Span::styled(row.prefix.clone(), cell.style));
            for segment in segments {
                spans.push(Span::styled(segment.text.clone(), segment.style));
            }
            let padding = available.saturating_sub(content_w);
            if padding > 0 {
                spans.push(Span::styled(" ".repeat(padding), cell.style));
            }
            continue;
        }

        let content = if i == COL_NAME {
            let prefix_w = display_width(&row.prefix);
            let available = col_width.saturating_sub(prefix_w);
            format!("{}{}", row.prefix, pad_right(&cell.text, available))
        } else if (i == COL_SYNC || i == COL_MAIN) && cell.text == IN_SYNC {
            let padded = pad_left(&cell.text, col_width);
            format!("{}{padded}", " ".repeat(defs[i].gap))
        } else {
            let padded = match align {
                Align::Left => pad_right(&cell.text, col_width),
                Align::Right => pad_left(&cell.text, col_width),
                Align::Center => pad_center(&cell.text, col_width),
            };
            format!("{}{padded}", " ".repeat(defs[i].gap))
        };

        spans.push(Span::styled(content, cell.style));
    }

    if row.deleted {
        let strike = Style::default()
            .fg(label_color())
            .add_modifier(Modifier::CROSSED_OUT);
        for (i, span) in spans.iter_mut().enumerate() {
            if !suffix_indices.contains(&i) {
                span.style = strike;
            }
        }
    } else if matches!(row.worktree_health, WorktreeHealth::Broken) {
        let broken_style = Style::default().fg(text_default()).bg(error_color());
        for span in &mut spans {
            span.style = broken_style;
        }
    }

    Line::from(spans)
}

/// Build the header `Line` from column definitions and resolved widths.
/// `name_text` is the dynamic header for the Name column (e.g. "~/rust (42)").
pub(super) fn header_line(widths: &ProjectListWidths, name_text: &str) -> Line<'static> {
    let defs = column_defs(widths.lint_enabled());
    let header_style = Style::default()
        .fg(theme_roles::column_header_color())
        .add_modifier(Modifier::BOLD);

    let mut spans = Vec::with_capacity(NUM_COLS);
    let mut slot_widths =
        std::array::from_fn::<usize, NUM_COLS, _>(|i| defs[i].gap + widths.get(i));

    for (i, def) in defs.iter().enumerate() {
        if def.header_mode != HeaderMode::BorrowLeft {
            continue;
        }

        // Borrow overflow from the nearest columns on the left so headers can
        // stretch without shifting unrelated columns further left.
        let mut borrow_needed = display_width(def.header_max()).saturating_sub(widths.get(i));
        let mut donor = i;
        while borrow_needed > 0 && donor > 0 {
            donor -= 1;
            let borrowed = slot_widths[donor].min(borrow_needed);
            slot_widths[donor] -= borrowed;
            slot_widths[i] += borrowed;
            borrow_needed -= borrowed;
        }
    }

    for (i, def) in defs.iter().enumerate() {
        let slot_width = slot_widths[i];

        let content = if i == COL_NAME {
            pad_right(name_text, slot_width)
        } else if def.header_mode == HeaderMode::BorrowLeft {
            let header = def.header_for_width(slot_width);
            match def.align {
                Align::Left => pad_right(header, slot_width),
                Align::Right => pad_left(header, slot_width),
                Align::Center => pad_center(header, slot_width),
            }
        } else if def.header_mode == HeaderMode::Hidden {
            " ".repeat(slot_width)
        } else {
            let gap = def.gap.min(slot_width);
            let content_width = slot_width.saturating_sub(gap);
            let header = def.header_for_width(content_width);
            let padded = match def.align {
                Align::Left => pad_right(header, content_width),
                Align::Right => pad_left(header, content_width),
                Align::Center => pad_center(header, content_width),
            };
            format!("{}{padded}", " ".repeat(gap))
        };

        spans.push(Span::styled(content, header_style));
    }

    Line::from(spans)
}

// ── Row construction helpers ────────────────────────────────────────

/// Build a `RowCells` for a project row. Single construction site replaces all
/// scattered project row literals.
pub(super) fn build_row_cells(row: ProjectRow<'_>) -> RowCells {
    let ci_text = row
        .ci
        .map_or(String::new(), |conclusion| String::from(conclusion.icon()));
    let git_path_icon = row.git_status.map_or("", GitStatus::icon);

    let compact_status_style = |value: &str| {
        if value == IN_SYNC {
            Style::default().fg(theme_roles::git_untracked_color())
        } else {
            Style::default().fg(text_default())
        }
    };

    let compact_status_align = |value: &str| {
        if value == IN_SYNC {
            Some(Align::Center)
        } else {
            None
        }
    };

    let origin_sync_style = compact_status_style(row.git_origin_sync);
    let main_style = compact_status_style(row.git_main);
    let origin_sync_align = compact_status_align(row.git_origin_sync);
    let main_align = compact_status_align(row.git_main);

    let name_style = project_name_style(row.git_status);
    let ci_style = render::conclusion_style(row.ci);
    let git_path_style = Style::default();

    let mut cells = std::array::from_fn::<CellContent, NUM_COLS, _>(|_| CellContent::default());
    cells[COL_NAME] = CellContent {
        text: String::from(row.name),
        style: name_style,
        segments: row.name_segments,
        align_override: None,
        ..CellContent::default()
    };
    cells[COL_LINT] = CellContent {
        text: String::from(row.lint.icon()),
        style: row.lint.style(),
        align_override: None,
        ..CellContent::default()
    };
    cells[COL_CI] = CellContent {
        text: ci_text,
        style: ci_style,
        align_override: None,
        ..CellContent::default()
    };
    cells[COL_LANG] = CellContent {
        text: String::from(row.lang_icon),
        style: Style::default(),
        align_override: None,
        ..CellContent::default()
    };
    cells[COL_GIT_PATH] = CellContent {
        text: String::from(git_path_icon),
        style: git_path_style,
        align_override: Some(Align::Center),
        ..CellContent::default()
    };
    cells[COL_SYNC] = CellContent {
        text: String::from(row.git_origin_sync),
        style: origin_sync_style,
        align_override: origin_sync_align,
        ..CellContent::default()
    };
    cells[COL_MAIN] = CellContent {
        text: String::from(row.git_main),
        style: main_style,
        align_override: main_align,
        ..CellContent::default()
    };
    cells[COL_DISK] = CellContent {
        text: String::from(row.disk),
        style: row.disk_style,
        align_override: None,
        suffix: row.disk_suffix.map(String::from),
        suffix_style: row.disk_suffix_style,
        ..CellContent::default()
    };

    RowCells {
        cells,
        prefix: String::from(row.prefix),
        deleted: row.deleted,
        worktree_health: row.worktree_health,
    }
}

pub(super) fn project_name_style(git_status: Option<GitStatus>) -> Style {
    match git_status {
        Some(GitStatus::Modified) => Style::default().fg(theme_roles::git_modified_color()),
        Some(GitStatus::Untracked) => Style::default().fg(theme_roles::git_untracked_color()),
        Some(GitStatus::Ignored) => Style::default().fg(theme_roles::git_ignored_color()),
        Some(GitStatus::Clean) | None => Style::default(),
    }
}

pub(super) fn project_name_shimmer_style(git_status: Option<GitStatus>) -> Style {
    match git_status {
        Some(GitStatus::Modified) => Style::default().fg(theme_roles::git_modified_color()),
        Some(GitStatus::Untracked) => Style::default().fg(theme_roles::git_untracked_color()),
        Some(GitStatus::Ignored) => Style::default().fg(secondary_text_color()),
        Some(GitStatus::Clean) | None => {
            Style::default().fg(theme_roles::discovery_shimmer_color())
        },
    }
}

pub(super) fn build_shimmer_segments(
    name: &str,
    base_style: Style,
    accent_style: Style,
    head: usize,
    window_len: usize,
) -> Vec<StyledSegment> {
    let chars: Vec<char> = name.chars().collect();
    if chars.is_empty() || window_len == 0 {
        return vec![StyledSegment {
            text:  name.to_string(),
            style: base_style,
        }];
    }
    let len = chars.len();
    let head = head % len;
    let window_len = window_len.min(len);
    let mut segments = Vec::new();
    let mut current = String::new();
    let mut highlighted = false;

    for (index, ch) in chars.iter().enumerate() {
        let is_highlighted = (index + len - head) % len < window_len;
        if current.is_empty() {
            highlighted = is_highlighted;
        } else if is_highlighted != highlighted {
            segments.push(StyledSegment {
                text:  std::mem::take(&mut current),
                style: if highlighted {
                    accent_style
                } else {
                    base_style
                },
            });
            highlighted = is_highlighted;
        }
        current.push(*ch);
    }

    if !current.is_empty() {
        segments.push(StyledSegment {
            text:  current,
            style: if highlighted {
                accent_style
            } else {
                base_style
            },
        });
    }

    segments
}

/// Build a `RowCells` for a group header (only Name column has content).
pub(super) fn build_group_header_cells(prefix: &str, label: &str) -> RowCells {
    let mut cells = std::array::from_fn::<CellContent, NUM_COLS, _>(|_| CellContent::default());
    cells[COL_NAME] = CellContent {
        text: String::from(label),
        style: Style::default().fg(title_color()),
        align_override: None,
        ..CellContent::default()
    };
    RowCells {
        cells,
        prefix: String::from(prefix),
        deleted: false,
        worktree_health: Normal,
    }
}

fn summary_label_col(widths: &ProjectListWidths) -> usize {
    (0..COL_DISK)
        .rev()
        .find(|&col| widths.get(col) > 0)
        .unwrap_or(COL_NAME)
}

/// Build a `RowCells` for the summary (Σ) row.
pub(super) fn build_summary_cells(widths: &ProjectListWidths, disk: &str) -> RowCells {
    let total_style = Style::default()
        .fg(title_color())
        .add_modifier(Modifier::BOLD);

    let mut cells = std::array::from_fn::<CellContent, NUM_COLS, _>(|_| CellContent::default());
    let sigma_col = summary_label_col(widths);
    cells[sigma_col] = CellContent {
        text: String::from("Σ"),
        style: total_style,
        align_override: Some(Align::Right),
        ..CellContent::default()
    };
    cells[COL_DISK] = CellContent {
        text: String::from(disk),
        style: total_style,
        align_override: None,
        ..CellContent::default()
    };
    if sigma_col != COL_LANG {
        cells[COL_LANG] = CellContent {
            text: String::from("  "),
            style: Style::default(),
            align_override: None,
            ..CellContent::default()
        };
    }
    RowCells {
        cells,
        prefix: " ".repeat(widths.get(COL_NAME)),
        deleted: false,
        worktree_health: Normal,
    }
}

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

    fn seeded_width(index: usize) -> usize { column_defs(true)[index].seed_width() }

    #[test]
    fn resolved_widths_seeds_from_defs() {
        let widths = ProjectListWidths::new(true);
        // Fixed columns get their fixed width
        assert_eq!(widths.get(COL_LINT), seeded_width(COL_LINT));
        assert_eq!(widths.get(COL_LANG), seeded_width(COL_LANG));
        assert_eq!(widths.get(COL_CI), seeded_width(COL_CI));
        assert_eq!(widths.get(COL_GIT_PATH), seeded_width(COL_GIT_PATH));
        // Fit columns get their min
        assert_eq!(widths.get(COL_NAME), seeded_width(COL_NAME));
        assert_eq!(widths.get(COL_DISK), seeded_width(COL_DISK));
        assert_eq!(widths.get(COL_SYNC), seeded_width(COL_SYNC));
        assert_eq!(widths.get(COL_MAIN), seeded_width(COL_MAIN));
    }

    #[test]
    fn observe_grows_fit_columns() {
        let mut widths = ProjectListWidths::new(true);
        widths.observe(COL_NAME, 25);
        assert_eq!(widths.get(COL_NAME), 25);
        // Fixed column ignores observe
        widths.observe(COL_LINT, 99);
        assert_eq!(widths.get(COL_LINT), seeded_width(COL_LINT));
    }

    #[test]
    fn total_width_sums_gaps_and_widths() {
        let defs = column_defs(true);
        let widths = ProjectListWidths::new(true);
        let total = widths.total_width();
        let expected: usize = defs
            .iter()
            .enumerate()
            .map(|(i, d)| d.gap + widths.get(i))
            .sum();
        assert_eq!(total, expected);
    }

    #[test]
    fn header_line_borrows_only_overflow_from_name() {
        let mut widths = ProjectListWidths::new(true);
        widths.observe(COL_NAME, 30);
        widths.observe(COL_DISK, 8);
        widths.observe(COL_SYNC, 2);
        widths.observe(COL_MAIN, 2);

        let line = header_line(&widths, "Projects");

        assert_eq!(display_width(line.spans[COL_NAME].content.as_ref()), 28);
        assert_eq!(display_width(line.spans[COL_LINT].content.as_ref()), 4);
        assert_eq!(line.spans[COL_CI].content.as_ref(), " CI");
        assert_eq!(line.spans[COL_GIT_PATH].content.as_ref(), " Git");
        assert_eq!(line.spans[COL_SYNC].content.as_ref(), " Og");
        assert_eq!(line.spans[COL_MAIN].content.as_ref(), " Mn");
        assert_eq!(line.spans[COL_DISK].content.as_ref(), "     Disk");
        assert_eq!(line.width(), widths.total_width());
    }

    #[test]
    fn git_header_borrows_from_hidden_lang_column() {
        let mut widths = ProjectListWidths::new(true);
        widths.observe(COL_NAME, 30);
        widths.observe(COL_DISK, 8);
        widths.observe(COL_SYNC, 2);
        widths.observe(COL_MAIN, 2);

        let line = header_line(&widths, "Projects");

        assert_eq!(line.spans[COL_CI].content.as_ref(), " CI");
        assert_eq!(display_width(line.spans[COL_LANG].content.as_ref()), 2);
        assert_eq!(line.spans[COL_GIT_PATH].content.as_ref(), " Git");
        assert_eq!(line.spans[COL_SYNC].content.as_ref(), " Og");
        assert_eq!(line.spans[COL_MAIN].content.as_ref(), " Mn");
        assert_eq!(line.width(), widths.total_width());
    }

    #[test]
    fn header_levels_promote_with_observed_width() {
        // Empty: only the seed (1) for COL_MAIN, (2) for COL_SYNC.
        let widths = ProjectListWidths::new(true);
        let defs = column_defs(true);
        assert_eq!(defs[COL_MAIN].header_for_width(widths.get(COL_MAIN)), "M");
        assert_eq!(defs[COL_SYNC].header_for_width(widths.get(COL_SYNC)), "Og");

        // Mid widths promote to the 2nd level.
        let mut widths = ProjectListWidths::new(true);
        widths.observe(COL_MAIN, 3);
        widths.observe(COL_SYNC, 5);
        assert_eq!(defs[COL_MAIN].header_for_width(widths.get(COL_MAIN)), "Mn");
        assert_eq!(
            defs[COL_SYNC].header_for_width(widths.get(COL_SYNC)),
            "Orig"
        );

        // Wide enough for the longest level.
        let mut widths = ProjectListWidths::new(true);
        widths.observe(COL_MAIN, 4);
        widths.observe(COL_SYNC, 6);
        assert_eq!(
            defs[COL_MAIN].header_for_width(widths.get(COL_MAIN)),
            "Main"
        );
        assert_eq!(
            defs[COL_SYNC].header_for_width(widths.get(COL_SYNC)),
            "Origin"
        );
    }

    #[test]
    fn header_line_uses_widest_label_that_fits() {
        let mut widths = ProjectListWidths::new(true);
        widths.observe(COL_NAME, 30);
        widths.observe(COL_DISK, 8);
        widths.observe(COL_SYNC, 6);
        widths.observe(COL_MAIN, 4);

        let line = header_line(&widths, "Projects");

        assert_eq!(line.spans[COL_SYNC].content.as_ref(), " Origin");
        assert_eq!(line.spans[COL_MAIN].content.as_ref(), " Main");
    }

    #[test]
    fn emoji_display_widths() {
        assert_eq!(display_width("🌲"), 2);
        assert_eq!(display_width("🦀"), 2);
        assert_eq!(display_width("bevy_brp"), 8);
        assert_eq!(display_width("bevy_brp 🌲:2"), 13);

        let padded = pad_right("bevy_brp 🌲:2", 27);
        assert_eq!(display_width(&padded), 27, "padded display width");

        let padded_ascii = pad_right("bevy_brp", 27);
        assert_eq!(
            display_width(&padded_ascii),
            27,
            "ascii padded display width"
        );
    }

    #[test]
    fn row_to_line_same_width_with_and_without_emoji() {
        let mut widths = ProjectListWidths::new(true);
        widths.observe(COL_NAME, 32);
        widths.observe(COL_DISK, 8);
        widths.observe(COL_SYNC, 2);
        widths.observe(COL_MAIN, 2);

        let row_emoji = build_row_cells(ProjectRow {
            prefix:            "",
            name:              "bevy_brp 🌲:2",
            name_segments:     None,
            git_status:        Some(GitStatus::Clean),
            lint:              LintCell::with_icon(crate::constants::LINT_PASSED),
            disk:              "36.3 GiB",
            disk_style:        Style::default(),
            disk_suffix:       None,
            disk_suffix_style: None,
            lang_icon:         "🦀",
            git_origin_sync:   "↑2",
            git_main:          "",
            ci:                Some(CiStatus::Passed),
            deleted:           false,
            worktree_health:   WorktreeHealth::Normal,
        });
        let row_ascii = build_row_cells(ProjectRow {
            prefix:            "",
            name:              "bevy_mesh_outline_benchmark",
            name_segments:     None,
            git_status:        Some(GitStatus::Clean),
            lint:              LintCell::with_icon(crate::constants::LINT_PASSED),
            disk:              "36.3 GiB",
            disk_style:        Style::default(),
            disk_suffix:       None,
            disk_suffix_style: None,
            lang_icon:         "🦀",
            git_origin_sync:   "↑2",
            git_main:          "",
            ci:                Some(CiStatus::Passed),
            deleted:           false,
            worktree_health:   WorktreeHealth::Normal,
        });

        let line_emoji = row_to_line(&row_emoji, &widths);
        let line_ascii = row_to_line(&row_ascii, &widths);

        let emoji_spans: Vec<usize> = line_emoji
            .spans
            .iter()
            .map(|s| display_width(s.content.as_ref()))
            .collect();
        let ascii_spans: Vec<usize> = line_ascii
            .spans
            .iter()
            .map(|s| display_width(s.content.as_ref()))
            .collect();
        assert_eq!(
            emoji_spans, ascii_spans,
            "per-span widths should match\nemoji: {emoji_spans:?}\nascii: {ascii_spans:?}"
        );
    }

    #[test]
    fn summary_row_places_sigma_next_to_disk_total() {
        let mut widths = ProjectListWidths::new(true);
        widths.observe(COL_NAME, 30);
        widths.observe(COL_DISK, 8);
        widths.observe(COL_SYNC, 2);
        widths.observe(COL_MAIN, 2);

        let row = build_summary_cells(&widths, "36.3 GiB");
        let line = row_to_line(&row, &widths);

        assert_eq!(
            line.spans[COL_NAME].content.as_ref(),
            " ".repeat(widths.get(COL_NAME))
        );
        assert_eq!(line.spans[COL_MAIN].content.as_ref(), "  Σ");
        assert_eq!(line.spans[COL_CI].content.as_ref(), "   ");
        assert_eq!(line.spans[COL_DISK].content.as_ref(), " 36.3 GiB");
    }

    #[test]
    fn lint_column_collapses_when_disabled() {
        let defs = column_defs(false);
        let mut widths = ProjectListWidths::new(false);
        widths.observe(COL_NAME, 30);
        widths.observe(COL_DISK, 8);
        widths.observe(COL_SYNC, 2);
        widths.observe(COL_MAIN, 2);

        let header = header_line(&widths, "Projects");
        let row = build_summary_cells(&widths, "36.3 GiB");
        let line = row_to_line(&row, &widths);

        assert_eq!(defs[COL_LINT].header_max(), "");
        assert_eq!(widths.get(COL_LINT), 0);
        assert_eq!(display_width(header.spans[COL_LINT].content.as_ref()), 0);
        assert_eq!(defs[COL_CI].header_max(), "CI");
        assert_eq!(widths.get(COL_CI), 2);
        assert!(header.spans[COL_CI].content.as_ref().ends_with("CI"));
        assert_eq!(line.spans[COL_MAIN].content.as_ref(), "  Σ");
    }

    #[test]
    fn hidden_lint_column_does_not_shift_ci_cells() {
        let mut widths = ProjectListWidths::new(false);
        widths.observe(COL_NAME, 24);
        widths.observe(COL_DISK, 8);
        widths.observe(COL_SYNC, 2);
        widths.observe(COL_MAIN, 2);

        let row = build_row_cells(ProjectRow {
            prefix:            "",
            name:              "demo",
            name_segments:     None,
            git_status:        Some(GitStatus::Clean),
            lint:              LintCell::with_icon(crate::constants::LINT_PASSED),
            disk:              "36.3 GiB",
            disk_style:        Style::default(),
            disk_suffix:       None,
            disk_suffix_style: None,
            lang_icon:         "🦀",
            git_origin_sync:   "↑2",
            git_main:          "",
            ci:                Some(CiStatus::Passed),
            deleted:           false,
            worktree_health:   WorktreeHealth::Normal,
        });
        let line = row_to_line(&row, &widths);

        assert_eq!(display_width(line.spans[COL_LINT].content.as_ref()), 0);
        assert_eq!(
            line.spans[COL_CI].content.as_ref(),
            &format!(" {}", CiStatus::Passed.icon())
        );
        assert_eq!(line.width(), widths.total_width());
    }

    #[test]
    fn git_status_changes_name_style() {
        let modified = build_row_cells(ProjectRow {
            prefix:            "  ",
            name:              "demo",
            name_segments:     None,
            git_status:        Some(GitStatus::Modified),
            lint:              LintCell::hidden(),
            disk:              "",
            disk_style:        Style::default(),
            disk_suffix:       None,
            disk_suffix_style: None,
            lang_icon:         "🦀",
            git_origin_sync:   "",
            git_main:          "",
            ci:                None,
            deleted:           false,
            worktree_health:   WorktreeHealth::Normal,
        });
        assert_eq!(
            modified.cells[COL_NAME].style.fg,
            Some(theme_roles::git_modified_color())
        );
        assert_eq!(
            modified.cells[COL_GIT_PATH].text,
            crate::constants::GIT_STATUS_MODIFIED
        );

        let untracked = build_row_cells(ProjectRow {
            prefix:            "  ",
            name:              "demo",
            name_segments:     None,
            git_status:        Some(GitStatus::Untracked),
            lint:              LintCell::hidden(),
            disk:              "",
            disk_style:        Style::default(),
            disk_suffix:       None,
            disk_suffix_style: None,
            lang_icon:         "🦀",
            git_origin_sync:   "",
            git_main:          "",
            ci:                None,
            deleted:           false,
            worktree_health:   WorktreeHealth::Normal,
        });
        assert_eq!(
            untracked.cells[COL_NAME].style.fg,
            Some(theme_roles::git_untracked_color())
        );
        assert_eq!(
            untracked.cells[COL_GIT_PATH].text,
            crate::constants::GIT_STATUS_UNTRACKED
        );

        let clean = build_row_cells(ProjectRow {
            prefix:            "  ",
            name:              "demo",
            name_segments:     None,
            git_status:        Some(GitStatus::Clean),
            lint:              LintCell::hidden(),
            disk:              "",
            disk_style:        Style::default(),
            disk_suffix:       None,
            disk_suffix_style: None,
            lang_icon:         "🦀",
            git_origin_sync:   "",
            git_main:          "",
            ci:                None,
            deleted:           false,
            worktree_health:   WorktreeHealth::Normal,
        });
        assert_eq!(
            clean.cells[COL_GIT_PATH].text,
            crate::constants::GIT_STATUS_CLEAN
        );

        let ignored = build_row_cells(ProjectRow {
            prefix:            "  ",
            name:              "demo",
            name_segments:     None,
            git_status:        Some(GitStatus::Ignored),
            lint:              LintCell::hidden(),
            disk:              "",
            disk_style:        Style::default(),
            disk_suffix:       None,
            disk_suffix_style: None,
            lang_icon:         "🦀",
            git_origin_sync:   "",
            git_main:          "",
            ci:                None,
            deleted:           false,
            worktree_health:   WorktreeHealth::Normal,
        });
        assert_eq!(
            ignored.cells[COL_NAME].style.fg,
            Some(theme_roles::git_ignored_color())
        );
        assert!(ignored.cells[COL_GIT_PATH].text.is_empty());
    }

    #[test]
    fn build_shimmer_segments_wraps_around_name_end() {
        let segments = build_shimmer_segments(
            "abcd",
            Style::default(),
            Style::default().fg(title_color()),
            3,
            2,
        );

        let actual: Vec<_> = segments
            .iter()
            .map(|segment| (segment.text.as_str(), segment.style.fg))
            .collect();
        assert_eq!(
            actual,
            vec![
                ("a", Some(title_color())),
                ("bc", None),
                ("d", Some(title_color())),
            ]
        );
    }

    #[test]
    fn shimmer_style_never_uses_bold() {
        for state in [
            Some(GitStatus::Clean),
            Some(GitStatus::Modified),
            Some(GitStatus::Untracked),
            Some(GitStatus::Ignored),
            None,
        ] {
            assert!(
                !project_name_shimmer_style(state)
                    .add_modifier
                    .contains(Modifier::BOLD)
            );
        }
    }

    #[test]
    fn clean_shimmer_style_uses_explicit_high_contrast_foreground() {
        assert_eq!(
            project_name_shimmer_style(Some(GitStatus::Clean)).fg,
            Some(theme_roles::discovery_shimmer_color())
        );
        assert_eq!(
            project_name_shimmer_style(None).fg,
            Some(theme_roles::discovery_shimmer_color())
        );
    }
}