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
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
//! Backend-agnostic [`Theme`] struct consumed by the per-backend rasterisers
//! in [`crate::tui`] and [`crate::gtk`].
//!
//! `Theme` is intentionally small. Apps with rich theme systems (vimcode's
//! `render::Theme` carries dozens of LSP / git / markdown colours; kubeui
//! has its own palette) build a `quadraui::Theme` at the call site by
//! picking the relevant fields out of their app-specific theme. Adding a
//! field here means every primitive rasteriser can read it; field count
//! grows as more primitives migrate from vimcode-private rasterisers into
//! `quadraui::tui` / `quadraui::gtk`.
//!
//! This is the **first** field set — driven by the StatusBar pilot.
//! Future migrations (TabBar, ListView, TreeView, …) will
//! extend the struct.

use crate::types::Color;
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Minimal backend-agnostic colour palette consumed by the public
/// `quadraui::tui` / `quadraui::gtk` rasterisers.
///
/// Apps that want the rasterisers to draw with their own colours
/// build a `Theme` at the call site (vimcode does this from
/// `render::Theme`; kubeui does it from its own palette). All fields
/// are required so every rasteriser has a reasonable fallback for
/// regions a primitive doesn't fully cover (e.g. the `StatusBar`
/// background fill when no segments are present).
///
/// **Field set is incremental.** Each migrated primitive adds the
/// fields it needs. The `Default` impl keeps a coherent dark palette
/// so apps can spread `..Default::default()` after specifying the
/// fields they care about. Building a *light* theme the same way?
/// Spread `..Theme::light_default()` instead — `Default::default()`
/// is dark, so every field a light theme leaves unmapped would
/// otherwise arrive dark.
///
/// # Adding a field here is a BREAKING change — prefer a method
///
/// The paragraph above describes how in-tree callers *should* build a
/// `Theme`. `Theme` is a plain struct (not `#[non_exhaustive]`, and it
/// must stay that way — `#[non_exhaustive]` would forbid
/// struct-literal syntax downstream, breaking both consumers harder
/// than any field ever could). A new field lands as `error[E0063]:
/// missing field` in downstream builds, and unlike a rename there is
/// no `#[deprecated]` shim that can soften a field *addition*.
///
/// So, before adding a `pub` field here:
///
/// 1. Can the value be **derived from an existing field**? Then add an
///    inherent method (`fn tab_active_border_top(&self) -> Color`),
///    which is purely additive and still themeable, since the field it
///    derives from is one the app already sets.
/// 2. If it genuinely needs independent storage, it is a real breaking
///    change: one field per PR, with a `## Downstream impact` section
///    naming each consumer literal that must gain the field.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Theme {
    // ── StatusBar pilot ─────────────────────────────────────────
    /// Default surface background. Used as a fallback fill when the
    /// primitive has no opinion (e.g. an empty `StatusBar`).
    pub background: Color,
    /// Default surface foreground. Available for primitives that need
    /// a generic text colour; consumed by `TabBar` for the dirty-tab
    /// `●` glyph.
    pub foreground: Color,

    // ── TabBar pilot ────────────────────────────────────────────
    /// Tab bar row background — also reused by inactive tab rows.
    pub tab_bar_bg: Color,
    /// Active tab background.
    pub tab_active_bg: Color,
    /// Active tab text colour.
    pub tab_active_fg: Color,
    /// Inactive tab text colour. Also used for right-segment text when
    /// the segment isn't `is_active`.
    pub tab_inactive_fg: Color,
    /// Active *preview* tab text colour (italicised in TUI).
    pub tab_preview_active_fg: Color,
    /// Inactive *preview* tab text colour.
    pub tab_preview_inactive_fg: Color,
    /// Window / panel separator colour. Used by `TabBar` for the
    /// close-button `×` on inactive tabs.
    pub separator: Color,

    // ── ListView pilot ──────────────────────────────────────────
    /// Background fill for surfaces drawn with a border (e.g. a
    /// bordered `ListView` modal). Distinct from `background` because
    /// modal-style panels typically tint slightly off the editor bg.
    pub surface_bg: Color,
    /// Default text colour on `surface_bg`.
    pub surface_fg: Color,
    /// Background of the selected row in a `ListView`.
    pub selected_bg: Color,
    /// Dimmed selection background for unfocused trees / lists. Indicates
    /// the selected row without implying keyboard focus (e.g. explorer
    /// tree highlighting the file matching the active editor tab).
    pub inactive_selected_bg: Color,
    /// Border-glyph colour for bordered surfaces.
    pub border_fg: Color,
    /// Title text colour drawn over a top border (bordered `ListView`).
    pub title_fg: Color,
    /// Background of a flat (non-bordered) header strip.
    pub header_bg: Color,
    /// Foreground of a flat (non-bordered) header strip.
    ///
    /// Doubles as the **on-selection foreground**: the text colour
    /// paired with `selected_bg` for a focused row, in any primitive
    /// (`Tree`, `Form`, …). There is no separate `selected_fg` field —
    /// `theme.foreground` has no guaranteed contrast against
    /// `selected_bg`, so every primitive's focused-row paint should
    /// pair `(header_fg, selected_bg)` the same way, not
    /// `(foreground, selected_bg)`.
    pub header_fg: Color,
    /// Dim / muted foreground for less-important text (line numbers,
    /// detail columns, `Decoration::Muted`).
    pub muted_fg: Color,
    /// Error / `Decoration::Error` foreground.
    pub error_fg: Color,
    /// Warning / `Decoration::Warning` foreground.
    pub warning_fg: Color,

    // ── Palette pilot ───────────────────────────────────────────
    /// Query-input text colour and cursor block fg in a `Palette`
    /// modal. Distinct from `surface_fg` — the query line is
    /// emphasised, item rows are not.
    pub query_fg: Color,
    /// Per-character highlight colour for fuzzy-match positions in
    /// `Palette` items.
    pub match_fg: Color,

    // ── Form pilot ──────────────────────────────────────────────
    /// Accent foreground used by `Form` for active-state visual cues
    /// (toggle "[x]" when on, slider filled track, button frame when
    /// focused). Typically the editor cursor / caret colour.
    pub accent_fg: Color,

    // ── Tooltip pilot ───────────────────────────────────────────
    /// Background fill for `Tooltip` popups (LSP hover, signature help,
    /// diff peek). Distinct from `surface_bg` so apps can tint hover
    /// popups differently from modal lists.
    pub hover_bg: Color,
    /// Default text colour for `Tooltip` popups.
    pub hover_fg: Color,
    /// Border-glyph / stroke colour for `Tooltip` popups.
    pub hover_border: Color,

    // ── Dialog pilot ────────────────────────────────────────────
    /// Background of the input field in a `Dialog` (e.g. the rename
    /// prompt's text entry). Distinct from `surface_bg` so the input
    /// reads as a separate sub-region.
    pub input_bg: Color,

    // ── ActivityBar / Terminal lift (B5c.5) ────────────────────────────
    /// Foreground for inactive entries in dim-out-when-not-focused
    /// chrome (activity-bar inactive icons, similar surfaces). Distinct
    /// from `muted_fg` because activity-bar icons typically use the
    /// status-bar's inactive colour, not the line-number / detail tone.
    pub inactive_fg: Color,
    /// Selection-region background. Used by the `Terminal` rasteriser
    /// to highlight selected cells. Distinct from `selected_bg` (which
    /// is the listview row highlight).
    pub selection_bg: Color,

    // ── RichTextPopup / Completions lift ───────────────────────────────
    /// Link / focus accent foreground. Used by `RichTextPopup` for the
    /// focused-popup border colour and the scrollbar thumb when the
    /// popup has keyboard focus. Typically the editor's markdown link
    /// colour.
    pub link_fg: Color,
    /// Background fill for the `Completions` popup (and similar typeahead
    /// menus). Distinct from `surface_bg` so apps can tint completion
    /// menus differently from modal lists.
    pub completion_bg: Color,
    /// Default text colour for completion items.
    pub completion_fg: Color,
    /// Border-glyph / stroke colour for completion popup chrome.
    pub completion_border: Color,
    /// Background of the selected row in a completion popup.
    pub completion_selected_bg: Color,

    // ── FindReplace lift ───────────────────────────────────────────────
    /// Accent background used for "this toggle button is on" states
    /// (e.g. case-sensitive / regex / preserve-case toggles in the
    /// find-replace overlay). Typically the editor's tab-active-accent
    /// colour. Distinct from `selected_bg` (list highlight) and
    /// `accent_fg` (text-cursor accent).
    pub accent_bg: Color,

    // ── Scrollbar lift ─────────────────────────────────────────────────
    /// Track colour for `Scrollbar`. The TUI rasteriser draws this on
    /// the entire track (typically a dim shade visible against the
    /// editor background); the GTK rasteriser uses it with a low alpha
    /// for the overlay-style track on the right/bottom of the editor.
    pub scrollbar_track: Color,
    /// Thumb colour for `Scrollbar`. Both rasterisers use this for the
    /// thumb glyph / rectangle, with backend-specific brightness
    /// modulation when the scrollbar is hovered or being dragged.
    pub scrollbar_thumb: Color,

    // ── Editor lift ─────────────────────────────────────────────
    /// Slightly tinted background of the focused editor window when
    /// multiple windows are visible. Distinct from `background` so the
    /// active pane is visually distinguishable. Vimcode's
    /// `RenderedWindow.show_active_bg` selects between this and
    /// `background`.
    pub editor_active_background: Color,
    /// Background tint of the cursor's current line when the
    /// `cursorline` setting is on. Lower priority than diff backgrounds
    /// and the DAP-stopped highlight.
    pub cursorline_bg: Color,
    /// Background highlight of the line where the DAP adapter is
    /// currently stopped. Highest priority — overrides cursorline +
    /// diff backgrounds.
    pub dap_stopped_bg: Color,
    /// Background tint applied at colorcolumn positions
    /// (`settings.colorcolumn`).
    pub colorcolumn_bg: Color,

    // Diff backgrounds (two-way `:diffthis` mode).
    pub diff_added_bg: Color,
    pub diff_removed_bg: Color,
    /// Background of synthetic alignment-padding rows (no buffer
    /// content) inserted to keep diff panes line-aligned.
    pub diff_padding_bg: Color,

    // Gutter line numbers.
    /// Foreground of inactive line numbers in the gutter.
    pub line_number_fg: Color,
    /// Foreground of the line number on the cursor's current line.
    pub line_number_active_fg: Color,

    // Diagnostic foregrounds (drive squiggle / underline + gutter icon).
    pub diagnostic_error: Color,
    pub diagnostic_warning: Color,
    pub diagnostic_info: Color,
    pub diagnostic_hint: Color,

    // Git diff gutter markers.
    pub git_added: Color,
    pub git_modified: Color,
    pub git_deleted: Color,

    // Code-action lightbulb + spell-checker.
    /// Foreground of the code-action lightbulb gutter glyph.
    pub lightbulb: Color,
    /// Foreground of the spell-checker underline.
    pub spell_error: Color,

    // Cursor / selection / yank flash.
    /// Editor cursor base colour. TUI inverts fg/bg at the cell using
    /// this; GTK paints a rect with `cursor_normal_alpha`.
    pub cursor: Color,
    /// Alpha (0.0..1.0) applied to the GTK cursor rectangle in Normal
    /// mode. TUI ignores (no alpha on cells).
    pub cursor_normal_alpha: f32,
    /// Selection background colour. Both backends mix this with the
    /// underlying line bg (TUI via cell bg overwrite, GTK via alpha
    /// rect).
    pub selection: Color,
    /// Alpha (0.0..1.0) applied to the GTK selection rectangles.
    pub selection_alpha: f32,
    /// Background flash painted briefly after a yank.
    pub yank_highlight_bg: Color,
    /// Alpha (0.0..1.0) applied to the GTK yank-flash rectangles.
    pub yank_highlight_alpha: f32,

    // Bracket-match + indent-guides.
    /// Background highlight on the cursor's bracket and its match.
    pub bracket_match_bg: Color,
    /// Foreground of inactive indent-guide rules.
    pub indent_guide_fg: Color,
    /// Foreground of the active indent-guide column (cursor's scope).
    pub indent_guide_active_fg: Color,

    // Inline annotations + AI ghost text.
    /// Foreground of inline annotations (Lua-plugin virtual text, git
    /// blame). Muted by convention.
    pub annotation_fg: Color,
    /// Foreground of AI-completion ghost text. Muted by convention.
    pub ghost_text_fg: Color,

    // Command line (`:`, `/`, `?` prompt + message output).
    /// Background of the command line bar.
    pub command_line_bg: Color,
    /// Text colour of the command line bar.
    pub command_line_fg: Color,

    // ── Board / kanban ─────────────────────────────────────────────────
    /// Background of the selected card in a `Board`.
    pub board_selected_card_bg: Color,
    /// Background of the focused column header in a `Board`.
    pub board_col_header_bg: Color,
    /// `BadgeStatus::Running` colour (typically accent yellow / orange).
    pub badge_running: Color,
    /// `BadgeStatus::Passed` colour (green).
    pub badge_passed: Color,
    /// `BadgeStatus::Warning` colour (warning orange).
    pub badge_warning: Color,
    /// `BadgeStatus::Blocked` colour (red).
    pub badge_blocked: Color,
    /// Background of the `BoardCard::hint` callout strip at the bottom of a card.
    pub card_hint_bg: Color,
    /// Text colour of the `BoardCard::hint` callout.
    pub card_hint_fg: Color,
}

/// The six-colour categorical palette returned by
/// [`Theme::chart_series`] — the single in-crate definition used by
/// the chart backends.
///
/// `pub(crate)` so the backend rasteriser tests can name it as a
/// constant (a `const` can't call the accessor method); everything
/// that *paints* goes through [`Theme::chart_series`].
pub(crate) const CHART_SERIES: [Color; 6] = [
    Color::rgb(80, 160, 255),
    Color::rgb(255, 120, 80),
    Color::rgb(80, 220, 120),
    Color::rgb(220, 180, 60),
    Color::rgb(180, 100, 240),
    Color::rgb(240, 100, 180),
];

impl Theme {
    /// Parse a VS Code theme JSON (or JSONC — VS Code theme files commonly
    /// carry `//` / `/* */` comments) file and map its `colors` object
    /// onto a [`Theme`]. Keys the file doesn't set leave the corresponding
    /// [`Theme::default`] field untouched, so even a minimal theme (a
    /// handful of `colors` keys) produces a fully-populated, usable
    /// palette rather than a partially-black one. Returns `None` if the
    /// file cannot be read or does not parse as JSON.
    ///
    /// Lifted from vimcode's `render::Theme::from_vscode_json`.
    /// vimcode's own theme carries dozens of syntax/LSP/semantic-token
    /// fields (`keyword`, `string_lit`, `semantic_namespace`, …) that
    /// this crate's [`Theme`] has no equivalent for — those stay
    /// app-side, built by app-specific code from the same theme file's
    /// `tokenColors` array, which this function does not touch.
    ///
    /// Colours that VS Code themes commonly express as a translucent
    /// `#rrggbbaa` overlay (e.g. `editor.lineHighlightBackground`, diff
    /// backgrounds, bracket-match highlight) are alpha-composited over
    /// `editor.background` via [`Color::try_from_hex_over`] rather than
    /// taken at face value, so a rasteriser that draws an opaque rect
    /// still gets the intended blended colour.
    pub fn from_vscode_json(path: &Path) -> Option<Self> {
        let data = std::fs::read_to_string(path).ok()?;
        Self::from_vscode_json_str(&data)
    }

    /// The parsing half of [`Self::from_vscode_json`], split out so it
    /// can be driven directly by property tests without
    /// touching the filesystem for every case. No I/O, no `pub`
    /// surface added — same fallibility contract as the path-taking
    /// wrapper: `None` on anything that isn't valid JSONC or doesn't
    /// parse as a JSON object.
    fn from_vscode_json_str(data: &str) -> Option<Self> {
        let data = crate::text_util::strip_json_comments(data);
        let val: serde_json::Value = serde_json::from_str(&data).ok()?;
        let colors = val.get("colors");

        let mut theme = Self::default();

        // Plain (non-composited) colour lookup.
        let color =
            |key: &str| -> Option<Color> { colors?.get(key)?.as_str().and_then(Color::from_hex) };
        // Alpha-composited lookup, blended over `bg`.
        let color_over = |key: &str, bg: Color| -> Option<Color> {
            colors?
                .get(key)?
                .as_str()
                .and_then(|s| Color::try_from_hex_over(s, bg))
        };

        // ── Editor core ──────────────────────────────────────────────
        if let Some(c) = color("editor.background") {
            theme.background = c;
            theme.editor_active_background = c.lighten(0.02);
            theme.scrollbar_track = c;
            theme.command_line_bg = c;
        }
        if let Some(c) = color("editor.foreground") {
            theme.foreground = c;
            theme.command_line_fg = c;
        }

        // ── Selection / cursor ───────────────────────────────────────
        if let Some(c) = color("editor.selectionBackground") {
            theme.selection_bg = c;
            theme.selection = c;
        }
        if let Some(c) = color("editorCursor.foreground") {
            theme.cursor = c;
        }
        if let Some(c) = color_over("editor.lineHighlightBackground", theme.background) {
            theme.cursorline_bg = c;
        }
        if let Some(c) = color_over("editor.stackFrameHighlightBackground", theme.background) {
            theme.dap_stopped_bg = c;
        }

        // ── Tab bar ──────────────────────────────────────────────────
        if let Some(c) = color("editorGroupHeader.tabsBackground") {
            theme.tab_bar_bg = c;
        }
        if let Some(c) = color("tab.activeBackground") {
            theme.tab_active_bg = c;
        }
        if let Some(c) = color("tab.activeForeground") {
            theme.tab_active_fg = c;
        }
        if let Some(c) = color("tab.inactiveForeground") {
            theme.tab_inactive_fg = c;
            theme.tab_preview_active_fg = c.lighten(0.2);
            theme.tab_preview_inactive_fg = c.darken(0.3);
        }
        if let Some(c) = color("editorGroup.border") {
            theme.separator = c;
        }

        // ── Surfaces / lists (Palette, ListView) ────────────────────
        if let Some(c) = color("editorWidget.background") {
            theme.surface_bg = c;
        }
        if let Some(c) = color("editorWidget.foreground").or_else(|| color("editor.foreground")) {
            theme.surface_fg = c;
        }
        if let Some(c) = color("list.activeSelectionBackground") {
            theme.selected_bg = c;
        }
        if let Some(c) = color("list.inactiveSelectionBackground") {
            theme.inactive_selected_bg = c;
        }
        if let Some(c) = color("editorWidget.border") {
            theme.border_fg = c;
        }
        if let Some(c) = color("titleBar.activeForeground") {
            theme.title_fg = c;
        }
        if let Some(c) = color("sideBarSectionHeader.background") {
            theme.header_bg = c;
        }
        if let Some(c) = color("sideBarSectionHeader.foreground") {
            theme.header_fg = c;
        }
        if let Some(c) = color("descriptionForeground") {
            theme.muted_fg = c;
        }
        if let Some(c) = color("editorError.foreground") {
            theme.error_fg = c;
            theme.diagnostic_error = c;
        }
        if let Some(c) = color("editorWarning.foreground") {
            theme.warning_fg = c;
            theme.diagnostic_warning = c;
        }
        if let Some(c) = color("editorInfo.foreground") {
            theme.diagnostic_info = c;
        }
        if let Some(c) = color("editorHint.foreground") {
            theme.diagnostic_hint = c;
        }

        // ── Palette ──────────────────────────────────────────────────
        if let Some(c) = color("input.foreground") {
            theme.query_fg = c;
        }
        if let Some(c) = color("list.highlightForeground")
            .or_else(|| color("editorSuggestWidget.highlightForeground"))
        {
            theme.match_fg = c;
        }

        // ── Form / accent ────────────────────────────────────────────
        if let Some(c) = color("focusBorder") {
            theme.accent_fg = c;
        }
        if let Some(c) = color("button.background") {
            theme.accent_bg = c;
        }

        // ── Tooltip ──────────────────────────────────────────────────
        if let Some(c) =
            color("editorHoverWidget.background").or_else(|| color("editorWidget.background"))
        {
            theme.hover_bg = c;
        }
        if let Some(c) =
            color("editorHoverWidget.foreground").or_else(|| color("editor.foreground"))
        {
            theme.hover_fg = c;
        }
        if let Some(c) = color("editorHoverWidget.border").or_else(|| color("editorWidget.border"))
        {
            theme.hover_border = c;
        }

        // ── Dialog ───────────────────────────────────────────────────
        if let Some(c) = color("input.background") {
            theme.input_bg = c;
        }

        // ── ActivityBar ──────────────────────────────────────────────
        if let Some(c) =
            color("activityBar.inactiveForeground").or_else(|| color("descriptionForeground"))
        {
            theme.inactive_fg = c;
        }

        // ── Completions / links ──────────────────────────────────────
        if let Some(c) = color("textLink.foreground") {
            theme.link_fg = c;
        }
        if let Some(c) =
            color("editorSuggestWidget.background").or_else(|| color("editorWidget.background"))
        {
            theme.completion_bg = c;
        }
        if let Some(c) =
            color("editorSuggestWidget.foreground").or_else(|| color("editor.foreground"))
        {
            theme.completion_fg = c;
        }
        if let Some(c) =
            color("editorSuggestWidget.border").or_else(|| color("editorWidget.border"))
        {
            theme.completion_border = c;
        }
        if let Some(c) = color("editorSuggestWidget.selectedBackground") {
            theme.completion_selected_bg = c;
        }

        // ── Scrollbar ────────────────────────────────────────────────
        // VS Code doesn't have a separate track colour — the slider
        // itself is drawn translucent over the editor background, so
        // composite it the same way and reuse `editor.background` (set
        // above) as the track.
        if let Some(c) = color_over("scrollbarSlider.background", theme.background) {
            theme.scrollbar_thumb = c;
        }

        // ── Gutter line numbers ──────────────────────────────────────
        if let Some(c) = color("editorLineNumber.foreground") {
            theme.line_number_fg = c;
        }
        if let Some(c) = color("editorLineNumber.activeForeground") {
            theme.line_number_active_fg = c;
        }

        // ── Git gutter ───────────────────────────────────────────────
        if let Some(c) = color("gitDecoration.addedResourceForeground")
            .or_else(|| color("editorGutter.addedBackground"))
        {
            theme.git_added = c;
        }
        if let Some(c) = color("gitDecoration.modifiedResourceForeground")
            .or_else(|| color("editorGutter.modifiedBackground"))
        {
            theme.git_modified = c;
        }
        if let Some(c) = color("gitDecoration.deletedResourceForeground")
            .or_else(|| color("editorGutter.deletedBackground"))
        {
            theme.git_deleted = c;
        }

        // ── Code-action lightbulb ────────────────────────────────────
        if let Some(c) = color("editorLightBulb.foreground") {
            theme.lightbulb = c;
        }

        // ── Diff ─────────────────────────────────────────────────────
        if let Some(c) = color_over("diffEditor.insertedTextBackground", theme.background) {
            theme.diff_added_bg = c;
        }
        if let Some(c) = color_over("diffEditor.removedTextBackground", theme.background) {
            theme.diff_removed_bg = c;
        }

        // ── Bracket-match + indent guides ────────────────────────────
        if let Some(c) = color_over("editorBracketMatch.background", theme.background) {
            theme.bracket_match_bg = c;
        }
        if let Some(c) = color("editorIndentGuide.background") {
            theme.indent_guide_fg = c;
        }
        if let Some(c) = color("editorIndentGuide.activeBackground") {
            theme.indent_guide_active_fg = c;
        }

        // ── Annotations / ghost text ─────────────────────────────────
        if let Some(c) = color("editorCodeLens.foreground") {
            theme.annotation_fg = c;
        }
        if let Some(c) = color("editorGhostText.foreground") {
            theme.ghost_text_fg = c;
        }

        Some(theme)
    }

    /// Colour of the 1 px accent line along the top edge of the active
    /// tab — VS Code Dark Modern's `tab.activeBorderTop`.
    ///
    /// Never applied automatically. A caller opts in per bar by passing
    /// `active_accent: Some(theme.tab_active_border_top())`, mirroring VS
    /// Code's own split between `tab.activeBorderTop` (focused group) and
    /// `tab.unfocusedActiveBorderTop` (typically unset). Leaving
    /// [`crate::TabBar::active_accent`] as `None` paints no accent at all
    /// on every backend (TUI, GTK, macOS) — e.g. for a bottom-panel tab
    /// strip, a terminal toolbar, or an unfocused split's tab bar.
    ///
    /// **This is a method, not a `Theme` field, on purpose** — deriving
    /// it from [`Self::accent_fg`] loses nothing: a palette that already
    /// sets its accent colour gets a matching tab accent for free, and
    /// the built-in dark default is unchanged (`accent_fg` defaults to
    /// `rgb(140, 200, 240)`). A method with a hardcoded literal or
    /// derived value is purely additive: it adds no new field for
    /// downstream consumers' exhaustive palette literals to miss.
    pub fn tab_active_border_top(&self) -> Color {
        self.accent_fg
    }

    // ── Terminal find-highlight lift ────────────────────────────
    //
    // `tui/terminal.rs`, `gtk/terminal.rs`, and `macos/terminal.rs`
    // each hardcoded the same two RGB literals for the find-match
    // overlay. The shared ladder in
    // `crate::terminal_style::resolve_cell_style` reads them from here
    // instead.
    //
    // **These are methods, not `Theme` fields, on purpose** — purely
    // additive, so they cost nothing in downstream exhaustive palette
    // literals. Promote to real fields only if a consumer asks to theme
    // these independently.

    /// Background painted over the currently-active find match —
    /// terminal find-highlight convention (bright orange).
    pub fn find_active_bg(&self) -> Color {
        Color::rgb(255, 165, 0)
    }

    /// Foreground painted over [`Self::find_active_bg`] (black, for
    /// contrast against the bright orange).
    pub fn find_active_fg(&self) -> Color {
        Color::rgb(0, 0, 0)
    }

    /// Background painted over non-active find matches (dim highlight).
    pub fn find_match_bg(&self) -> Color {
        Color::rgb(100, 80, 20)
    }

    // ── Chart series lift ───────────────────────────────────────────────

    /// Default per-series palette for `Chart`, used when a `Series`
    /// doesn't set its own `color`. Callers cycle by index:
    /// `theme.chart_series()[idx % 6]`.
    ///
    /// This six-colour table has one definition here, and every
    /// rasteriser resolves through this accessor, so the backends stay
    /// consistent.
    ///
    /// **This is a method, not a `Theme` field, on purpose** — purely
    /// additive, so it costs nothing in downstream exhaustive palette
    /// literals. Unlike some other methods, this can't derive from an
    /// existing field: a chart legend needs six *mutually distinct*
    /// categorical colours, and `Theme` has no six semantically-unrelated
    /// hues to borrow. Per-`Series` `color: Some(..)` remains the
    /// supported way for an app to choose its own chart colours.
    pub fn chart_series(&self) -> [Color; 6] {
        CHART_SERIES
    }

    // ── Text-selection highlight lift ───────────────────────────────────

    /// Translucent-blue fill painted over the active drag-selected range
    /// of a [`crate::dispatch::TextRegion`] — the generic, cross-widget
    /// text-selection mechanism every `text_selection: true` backend
    /// embeds via `crate::text_selection::TextSelectionState`. **Not**
    /// the same concept as [`Self::selection`]/
    /// [`Self::selection_alpha`], which tint the *editor primitive's own*
    /// in-buffer selection — the two were already visually distinct
    /// before this method existed and stay that way here.
    ///
    /// This method reproduces the exact shared value; GTK/macOS paint
    /// `rgba(0.39, 0.58, 1.0, 0.30)` (float, `round(x*255)` per channel),
    /// and all backends now read it from here instead of hard-coding it.
    ///
    /// **A method, not a `Theme` field, on purpose** — purely additive,
    /// so it costs nothing in downstream exhaustive palette literals.
    pub fn text_selection_highlight(&self) -> Color {
        Color::rgba(99, 148, 255, 77)
    }

    // ── Light default palette ───────────────────────────────────────────

    /// A coherent **light** palette, structured field-for-field like
    /// [`Theme::default`]'s dark one.
    ///
    /// [`Theme::default`] is dark, so an app that spreads
    /// `..Theme::default()` after picking its own light `background` /
    /// `foreground` gets every *unmapped* field — including any field
    /// this crate adds later — at its dark value.
    ///
    /// `light_default()` is a **separate associated function, not a
    /// change to `Default`** — flipping `Default` itself would be just
    /// as one-sided a trap in the other direction, and `Default::default()`
    /// can't take a caller-supplied background anyway. An app building a
    /// light theme spreads `..Theme::light_default()` instead of
    /// `..Theme::default()`; an app building a dark theme keeps
    /// `..Theme::default()` unchanged. Being a plain function it is
    /// purely additive — nothing downstream can miss it.
    pub fn light_default() -> Self {
        let bg = Color::rgb(250, 250, 248);
        let fg = Color::rgb(30, 30, 35);
        let muted = Color::rgb(120, 122, 130);
        Self {
            background: bg,
            foreground: fg,
            tab_bar_bg: Color::rgb(238, 238, 235),
            tab_active_bg: Color::rgb(255, 255, 255),
            tab_active_fg: fg,
            tab_inactive_fg: Color::rgb(110, 110, 120),
            tab_preview_active_fg: Color::rgb(70, 70, 85),
            tab_preview_inactive_fg: Color::rgb(150, 150, 160),
            separator: Color::rgb(210, 210, 215),
            surface_bg: Color::rgb(255, 255, 255),
            surface_fg: fg,
            selected_bg: Color::rgb(200, 220, 250),
            inactive_selected_bg: Color::rgb(225, 230, 240),
            border_fg: Color::rgb(180, 190, 200),
            title_fg: Color::rgb(40, 55, 80),
            header_bg: Color::rgb(235, 235, 232),
            header_fg: fg,
            muted_fg: muted,
            error_fg: Color::rgb(180, 30, 30),
            warning_fg: Color::rgb(170, 110, 10),
            query_fg: fg,
            match_fg: Color::rgb(180, 120, 0),
            accent_fg: Color::rgb(20, 110, 190),
            hover_bg: Color::rgb(250, 250, 240),
            hover_fg: fg,
            hover_border: Color::rgb(190, 195, 205),
            input_bg: Color::rgb(255, 255, 255),
            inactive_fg: Color::rgb(140, 142, 150),
            selection_bg: Color::rgb(190, 215, 245),
            link_fg: Color::rgb(20, 100, 180),
            completion_bg: Color::rgb(255, 255, 255),
            completion_fg: fg,
            completion_border: Color::rgb(190, 195, 205),
            completion_selected_bg: Color::rgb(200, 220, 250),
            accent_bg: Color::rgb(30, 120, 215),
            scrollbar_track: Color::rgb(235, 235, 232),
            scrollbar_thumb: Color::rgb(180, 180, 190),

            // Light-theme defaults for editor backgrounds.
            editor_active_background: Color::rgb(255, 255, 255),
            cursorline_bg: Color::rgb(240, 240, 222),
            dap_stopped_bg: Color::rgb(255, 235, 190),
            colorcolumn_bg: Color::rgb(240, 240, 236),
            diff_added_bg: Color::rgb(220, 245, 220),
            diff_removed_bg: Color::rgb(250, 220, 220),
            diff_padding_bg: Color::rgb(240, 240, 236),
            line_number_fg: muted,
            line_number_active_fg: Color::rgb(40, 40, 50),
            diagnostic_error: Color::rgb(180, 30, 30),
            diagnostic_warning: Color::rgb(170, 110, 10),
            diagnostic_info: Color::rgb(20, 100, 180),
            diagnostic_hint: Color::rgb(20, 110, 190),
            git_added: Color::rgb(30, 140, 30),
            git_modified: Color::rgb(170, 110, 10),
            git_deleted: Color::rgb(180, 30, 30),
            lightbulb: Color::rgb(180, 140, 0),
            spell_error: Color::rgb(0, 130, 130),
            cursor: Color::rgb(20, 20, 25),
            cursor_normal_alpha: 0.40,
            selection: Color::rgb(190, 215, 245),
            selection_alpha: 0.50,
            yank_highlight_bg: Color::rgb(255, 230, 120),
            yank_highlight_alpha: 0.30,
            bracket_match_bg: Color::rgb(210, 215, 225),
            indent_guide_fg: Color::rgb(222, 222, 218),
            indent_guide_active_fg: Color::rgb(170, 170, 180),
            annotation_fg: Color::rgb(150, 150, 160),
            ghost_text_fg: Color::rgb(150, 150, 160),
            command_line_bg: bg,
            command_line_fg: fg,

            // Board / kanban
            board_selected_card_bg: Color::rgb(200, 220, 250),
            board_col_header_bg: Color::rgb(235, 235, 232),
            badge_running: Color::rgb(170, 110, 10),
            badge_passed: Color::rgb(30, 140, 30),
            badge_warning: Color::rgb(190, 110, 20),
            badge_blocked: Color::rgb(180, 30, 30),
            card_hint_bg: Color::rgb(225, 230, 240),
            card_hint_fg: Color::rgb(60, 70, 90),
        }
    }
}

impl Default for Theme {
    /// Neutral dark palette so the rasterisers produce something visible
    /// when an app forgets to populate the theme. Apps almost always
    /// override this.
    ///
    /// **This is a dark palette.** An app building a *light* theme that
    /// spreads `..Theme::default()` after setting its own `background`
    /// / `foreground` will get every other, unmapped field at its dark
    /// value — see [`Theme::light_default`] for a base
    /// that doesn't have that failure mode.
    fn default() -> Self {
        let bg = Color::rgb(20, 22, 30);
        let fg = Color::rgb(220, 220, 220);
        let muted = Color::rgb(120, 122, 135);
        Self {
            background: bg,
            foreground: fg,
            tab_bar_bg: bg,
            tab_active_bg: Color::rgb(40, 44, 56),
            tab_active_fg: fg,
            tab_inactive_fg: Color::rgb(140, 140, 150),
            tab_preview_active_fg: Color::rgb(180, 180, 200),
            tab_preview_inactive_fg: Color::rgb(110, 110, 125),
            separator: Color::rgb(60, 62, 72),
            surface_bg: Color::rgb(28, 32, 44),
            surface_fg: fg,
            selected_bg: Color::rgb(50, 60, 90),
            inactive_selected_bg: Color::rgb(35, 40, 58),
            border_fg: Color::rgb(120, 160, 200),
            title_fg: Color::rgb(180, 200, 230),
            header_bg: Color::rgb(40, 44, 56),
            header_fg: fg,
            muted_fg: muted,
            error_fg: Color::rgb(220, 80, 80),
            warning_fg: Color::rgb(220, 180, 80),
            query_fg: fg,
            match_fg: Color::rgb(255, 200, 80),
            accent_fg: Color::rgb(140, 200, 240),
            hover_bg: Color::rgb(36, 40, 52),
            hover_fg: fg,
            hover_border: Color::rgb(120, 140, 175),
            input_bg: Color::rgb(48, 52, 64),
            inactive_fg: Color::rgb(120, 122, 135),
            selection_bg: Color::rgb(60, 80, 120),
            link_fg: Color::rgb(110, 175, 230),
            completion_bg: Color::rgb(36, 40, 52),
            completion_fg: fg,
            completion_border: Color::rgb(120, 140, 175),
            completion_selected_bg: Color::rgb(50, 60, 90),
            accent_bg: Color::rgb(80, 160, 240),
            scrollbar_track: Color::rgb(40, 44, 56),
            scrollbar_thumb: Color::rgb(110, 115, 130),

            // Neutral defaults for editor backgrounds.
            editor_active_background: bg,
            cursorline_bg: Color::rgb(30, 33, 45),
            dap_stopped_bg: Color::rgb(80, 70, 30),
            colorcolumn_bg: Color::rgb(30, 32, 42),
            diff_added_bg: Color::rgb(28, 50, 32),
            diff_removed_bg: Color::rgb(60, 30, 30),
            diff_padding_bg: Color::rgb(28, 30, 38),
            line_number_fg: muted,
            line_number_active_fg: Color::rgb(200, 200, 210),
            diagnostic_error: Color::rgb(220, 80, 80),
            diagnostic_warning: Color::rgb(220, 180, 80),
            diagnostic_info: Color::rgb(110, 175, 230),
            diagnostic_hint: Color::rgb(140, 200, 240),
            git_added: Color::rgb(120, 200, 120),
            git_modified: Color::rgb(220, 180, 80),
            git_deleted: Color::rgb(220, 80, 80),
            lightbulb: Color::rgb(220, 200, 80),
            spell_error: Color::rgb(110, 200, 200),
            cursor: Color::rgb(220, 220, 220),
            cursor_normal_alpha: 0.40,
            selection: Color::rgb(60, 80, 120),
            selection_alpha: 0.50,
            yank_highlight_bg: Color::rgb(220, 200, 80),
            yank_highlight_alpha: 0.30,
            bracket_match_bg: Color::rgb(80, 90, 110),
            indent_guide_fg: Color::rgb(50, 54, 66),
            indent_guide_active_fg: Color::rgb(110, 115, 130),
            annotation_fg: Color::rgb(110, 115, 130),
            ghost_text_fg: Color::rgb(110, 115, 130),
            command_line_bg: bg,
            command_line_fg: fg,

            // Board / kanban
            board_selected_card_bg: Color::rgb(50, 60, 90),
            board_col_header_bg: Color::rgb(40, 44, 56),
            badge_running: Color::rgb(220, 180, 80),
            badge_passed: Color::rgb(120, 200, 120),
            badge_warning: Color::rgb(220, 140, 60),
            badge_blocked: Color::rgb(220, 80, 80),
            card_hint_bg: Color::rgb(35, 40, 55),
            card_hint_fg: Color::rgb(180, 190, 210),
        }
    }
}

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

    fn write_theme_json(dir: &std::path::Path, name: &str, contents: &str) -> std::path::PathBuf {
        let path = dir.join(name);
        std::fs::write(&path, contents).expect("write fixture theme json");
        path
    }

    // `strip_json_comments` moved to `crate::text_util`; its
    // unit tests moved with it.

    #[test]
    fn from_vscode_json_maps_colors_onto_theme_fields() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = write_theme_json(
            dir.path(),
            "sample.json",
            r##"{
                "colors": {
                    "editor.background": "#101820",
                    "editor.foreground": "#f0f0f0",
                    "tab.activeBackground": "#202830",
                    "tab.activeForeground": "#ffffff",
                    "editorError.foreground": "#ff0000",
                    "editorLineNumber.foreground": "#808080"
                }
            }"##,
        );
        let theme = Theme::from_vscode_json(&path).expect("parse fixture theme");
        assert_eq!(theme.background, Color::from_hex("#101820").unwrap());
        assert_eq!(theme.foreground, Color::from_hex("#f0f0f0").unwrap());
        assert_eq!(theme.tab_active_bg, Color::from_hex("#202830").unwrap());
        assert_eq!(theme.tab_active_fg, Color::from_hex("#ffffff").unwrap());
        assert_eq!(theme.error_fg, Color::from_hex("#ff0000").unwrap());
        assert_eq!(theme.diagnostic_error, Color::from_hex("#ff0000").unwrap());
        assert_eq!(theme.line_number_fg, Color::from_hex("#808080").unwrap());
    }

    /// Keys the theme file doesn't set must leave `Theme::default()`'s
    /// value in place — a minimal theme should still be fully usable,
    /// not partially black/undefined.
    #[test]
    fn from_vscode_json_leaves_unset_fields_at_default() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = write_theme_json(
            dir.path(),
            "minimal.json",
            r##"{ "colors": { "editor.background": "#000000" } }"##,
        );
        let theme = Theme::from_vscode_json(&path).expect("parse fixture theme");
        let default = Theme::default();
        assert_eq!(theme.background, Color::rgb(0, 0, 0));
        // Untouched field keeps the default's value.
        assert_eq!(theme.badge_passed, default.badge_passed);
        assert_eq!(theme.accent_fg, default.accent_fg);
    }

    /// VS Code theme files are JSONC — comments must not break parsing.
    #[test]
    fn from_vscode_json_strips_comments_before_parsing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = write_theme_json(
            dir.path(),
            "commented.json",
            "{\n  // top-level comment\n  \"colors\": {\n    \"editor.background\": \"#123456\" /* trailing */\n  }\n}",
        );
        let theme = Theme::from_vscode_json(&path).expect("parse commented fixture theme");
        assert_eq!(theme.background, Color::from_hex("#123456").unwrap());
    }

    /// `editor.lineHighlightBackground` is commonly a translucent
    /// `#rrggbbaa` overlay in real VS Code themes — it must be
    /// alpha-composited over `editor.background`, not taken at face
    /// value with its original (translucent) alpha.
    #[test]
    fn from_vscode_json_composites_translucent_line_highlight_over_background() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = write_theme_json(
            dir.path(),
            "translucent.json",
            r##"{
                "colors": {
                    "editor.background": "#000000",
                    "editor.lineHighlightBackground": "#ffffff80"
                }
            }"##,
        );
        let theme = Theme::from_vscode_json(&path).expect("parse fixture theme");
        let bg = Color::from_hex("#000000").unwrap();
        let expected = Color::try_from_hex_over("#ffffff80", bg).unwrap();
        assert_eq!(theme.cursorline_bg, expected);
        // Fully opaque against black should be pure white, and fully
        // transparent should stay black — sanity-check the direction of
        // the blend rather than just re-deriving the same computation.
        assert_ne!(theme.cursorline_bg, Color::rgb(255, 255, 255));
        assert_ne!(theme.cursorline_bg, Color::rgb(0, 0, 0));
    }

    #[test]
    fn from_vscode_json_returns_none_for_missing_file() {
        let path = std::path::Path::new("/nonexistent/path/does-not-exist.json");
        assert_eq!(Theme::from_vscode_json(path), None);
    }

    #[test]
    fn from_vscode_json_returns_none_for_malformed_json() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = write_theme_json(dir.path(), "broken.json", "{ not json at all");
        assert_eq!(Theme::from_vscode_json(&path), None);
    }

    /// The active-tab top accent is exposed as a *method* derived
    /// from `accent_fg`, not as its own `Theme` field — a field addition
    /// is `error[E0063]` in coord-tui's three exhaustive palette literals
    /// (`tui/src/settings.rs`), which is exactly what reddened the
    /// `downstream consumers (compile truth)` gate. The default value is
    /// unchanged from the field version it replaced.
    #[test]
    fn tab_active_border_top_defaults_to_the_accent_colour() {
        let theme = Theme::default();
        assert_eq!(
            theme.tab_active_border_top(),
            theme.accent_fg,
            "the tab accent line must track the palette's accent colour"
        );
        assert_eq!(
            theme.tab_active_border_top(),
            Color::rgb(140, 200, 240),
            "default accent must match the value #620 originally shipped as a field"
        );
    }

    /// The terminal find-highlight colours are exposed as
    /// *methods*, not `Theme` fields, for the same reason as
    /// `tab_active_border_top` above — see
    /// `exhaustive_theme_literal_still_compiles` below.
    #[test]
    fn terminal_find_highlight_colours_match_the_pre_shared_literals() {
        let theme = Theme::default();
        // Same RGB literals all backends hardcoded independently
        // before being moved here — the shared ladder must not change
        assert_eq!(theme.find_active_bg(), Color::rgb(255, 165, 0));
        assert_eq!(theme.find_active_fg(), Color::rgb(0, 0, 0));
        assert_eq!(theme.find_match_bg(), Color::rgb(100, 80, 20));
    }

    /// The accent stays *themeable* despite not having its own field: an
    /// app that recolours `accent_fg` recolours the tab accent with it,
    /// which is what makes the method a lossless replacement rather than
    /// a hardcoded constant.
    #[test]
    fn tab_active_border_top_follows_a_custom_accent() {
        let theme = Theme {
            accent_fg: Color::rgb(255, 100, 0),
            ..Theme::default()
        };
        assert_eq!(theme.tab_active_border_top(), Color::rgb(255, 100, 0));
    }

    /// The regression this whole change is about: a `Theme` built with an
    /// **exhaustive literal and no `..Default::default()` spread** — the
    /// shape coord-tui's `light_palette` / `high_contrast_palette` /
    /// `solarized_palette` (`tui/src/settings.rs`) use — must keep
    /// compiling. This test is that consumer shape in miniature, and it
    /// is deliberately verbose: the `..` spread is the one thing it must
    /// NOT have, because the spread is exactly what would let a new
    /// `pub` field slip through here and surface as `error[E0063]` in a
    /// consumer's CI instead.
    ///
    /// **If you added a field to `Theme` and this stopped compiling,
    /// that is the test working.** Re-read [`Theme`]'s "adding a field
    /// here is a BREAKING change" section before adding the field below:
    /// a value derivable from an existing field belongs in a method (see
    /// [`Theme::tab_active_border_top`]), and a field that genuinely
    /// needs its own storage needs consumer migrations landed alongside.
    #[test]
    fn exhaustive_theme_literal_still_compiles() {
        // Values come from `Default` so this asserts the struct's
        // *shape*, not ~80 hardcoded colours.
        let d = Theme::default();
        let exhaustive = Theme {
            background: d.background,
            foreground: d.foreground,
            tab_bar_bg: d.tab_bar_bg,
            tab_active_bg: d.tab_active_bg,
            tab_active_fg: d.tab_active_fg,
            tab_inactive_fg: d.tab_inactive_fg,
            tab_preview_active_fg: d.tab_preview_active_fg,
            tab_preview_inactive_fg: d.tab_preview_inactive_fg,
            separator: d.separator,
            surface_bg: d.surface_bg,
            surface_fg: d.surface_fg,
            selected_bg: d.selected_bg,
            inactive_selected_bg: d.inactive_selected_bg,
            border_fg: d.border_fg,
            title_fg: d.title_fg,
            header_bg: d.header_bg,
            header_fg: d.header_fg,
            muted_fg: d.muted_fg,
            error_fg: d.error_fg,
            warning_fg: d.warning_fg,
            query_fg: d.query_fg,
            match_fg: d.match_fg,
            accent_fg: d.accent_fg,
            hover_bg: d.hover_bg,
            hover_fg: d.hover_fg,
            hover_border: d.hover_border,
            input_bg: d.input_bg,
            inactive_fg: d.inactive_fg,
            selection_bg: d.selection_bg,
            link_fg: d.link_fg,
            completion_bg: d.completion_bg,
            completion_fg: d.completion_fg,
            completion_border: d.completion_border,
            completion_selected_bg: d.completion_selected_bg,
            accent_bg: d.accent_bg,
            scrollbar_track: d.scrollbar_track,
            scrollbar_thumb: d.scrollbar_thumb,
            editor_active_background: d.editor_active_background,
            cursorline_bg: d.cursorline_bg,
            dap_stopped_bg: d.dap_stopped_bg,
            colorcolumn_bg: d.colorcolumn_bg,
            diff_added_bg: d.diff_added_bg,
            diff_removed_bg: d.diff_removed_bg,
            diff_padding_bg: d.diff_padding_bg,
            line_number_fg: d.line_number_fg,
            line_number_active_fg: d.line_number_active_fg,
            diagnostic_error: d.diagnostic_error,
            diagnostic_warning: d.diagnostic_warning,
            diagnostic_info: d.diagnostic_info,
            diagnostic_hint: d.diagnostic_hint,
            git_added: d.git_added,
            git_modified: d.git_modified,
            git_deleted: d.git_deleted,
            lightbulb: d.lightbulb,
            spell_error: d.spell_error,
            cursor: d.cursor,
            cursor_normal_alpha: d.cursor_normal_alpha,
            selection: d.selection,
            selection_alpha: d.selection_alpha,
            yank_highlight_bg: d.yank_highlight_bg,
            yank_highlight_alpha: d.yank_highlight_alpha,
            bracket_match_bg: d.bracket_match_bg,
            indent_guide_fg: d.indent_guide_fg,
            indent_guide_active_fg: d.indent_guide_active_fg,
            annotation_fg: d.annotation_fg,
            ghost_text_fg: d.ghost_text_fg,
            command_line_bg: d.command_line_bg,
            command_line_fg: d.command_line_fg,
            board_selected_card_bg: d.board_selected_card_bg,
            board_col_header_bg: d.board_col_header_bg,
            badge_running: d.badge_running,
            badge_passed: d.badge_passed,
            badge_warning: d.badge_warning,
            badge_blocked: d.badge_blocked,
            card_hint_bg: d.card_hint_bg,
            card_hint_fg: d.card_hint_fg,
        };
        assert_eq!(exhaustive, d);
    }

    /// The chart series palette must be reachable off any `Theme`,
    /// including one an app built field-by-field rather than by
    /// spreading `..Default::default()`. It is an accessor, not a
    /// field, precisely so that call shape keeps compiling —
    /// `exhaustive_literal_is_still_valid` above is the compile-time
    /// half of that guarantee (it is the literal `coord-tui`'s
    /// `light_palette` / `high_contrast_palette` / `solarized_palette`
    /// use, and a new `pub` field would fail it with `E0063`); this is
    /// the runtime half.
    #[test]
    fn chart_series_is_reachable_off_a_non_default_theme() {
        let themed = Theme {
            background: Color::rgb(250, 250, 250),
            foreground: Color::rgb(10, 10, 10),
            ..Theme::default()
        };

        assert_eq!(themed.chart_series(), Theme::default().chart_series());
        assert_eq!(themed.chart_series().len(), 6);
    }

    /// The six series colours must be mutually distinct — they are
    /// a *categorical* palette, so two equal entries would render two
    /// different chart series indistinguishable in the legend.
    #[test]
    fn chart_series_colours_are_mutually_distinct() {
        let series = Theme::default().chart_series();
        for (i, a) in series.iter().enumerate() {
            for (j, b) in series.iter().enumerate() {
                if i != j {
                    assert_ne!(
                        a, b,
                        "chart_series[{i}] and chart_series[{j}] are identical"
                    );
                }
            }
        }
    }

    // ── Text-selection highlight lift ───────────────────────────────────

    /// Reproduces the exact pre-shared literal — GTK/macOS painted
    /// `rgba(0.39, 0.58, 1.0, 0.30)` (float), and this is the one value
    /// every backend now reads instead of three independently hard-coded
    /// copies.
    #[test]
    fn text_selection_highlight_matches_the_pre_shared_literal() {
        assert_eq!(
            Theme::default().text_selection_highlight(),
            Color::rgba(99, 148, 255, 77)
        );
    }

    /// Translucent, like every other adopter of this shared look — a
    /// fully opaque highlight would hide the selected text underneath.
    #[test]
    fn text_selection_highlight_is_translucent() {
        let a = Theme::default().text_selection_highlight().a;
        assert!(a > 0 && a < 255);
    }

    /// A method, not a field (see the doc comment) — reachable off any
    /// `Theme` value, not just the default one, same shape as
    /// [`chart_series_is_reachable_off_a_non_default_theme`].
    #[test]
    fn text_selection_highlight_is_reachable_off_a_non_default_theme() {
        let themed = Theme {
            background: Color::rgb(250, 250, 250),
            foreground: Color::rgb(10, 10, 10),
            ..Theme::default()
        };
        assert_eq!(
            themed.text_selection_highlight(),
            Theme::default().text_selection_highlight()
        );
    }

    // ── Light default palette ───────────────────────────────────────────

    /// Perceptual luminance (ITU-R BT.601), `0.0` (black) .. `255.0`
    /// (white). Test-only — good enough to distinguish "reads as light"
    /// from "reads as dark" without pulling in a colour-science crate.
    fn luminance(c: Color) -> f64 {
        0.299 * c.r as f64 + 0.587 * c.g as f64 + 0.114 * c.b as f64
    }

    /// Every background-type field on [`Theme::light_default`] must read
    /// as light. This is the failure mode a dark `Theme::default()` leak
    /// produces: an app spreads `..Theme::default()` over a
    /// light `background`/`foreground` pair and every *other*
    /// background-type key stays dark. Asserting this on
    /// `light_default()` is what makes it a safe base for that spread.
    #[test]
    fn light_default_background_type_keys_are_light() {
        let t = Theme::light_default();
        let backgrounds = [
            ("background", t.background),
            ("tab_bar_bg", t.tab_bar_bg),
            ("tab_active_bg", t.tab_active_bg),
            ("surface_bg", t.surface_bg),
            ("selected_bg", t.selected_bg),
            ("inactive_selected_bg", t.inactive_selected_bg),
            ("header_bg", t.header_bg),
            ("hover_bg", t.hover_bg),
            ("input_bg", t.input_bg),
            ("selection_bg", t.selection_bg),
            ("completion_bg", t.completion_bg),
            ("completion_selected_bg", t.completion_selected_bg),
            ("scrollbar_track", t.scrollbar_track),
            ("editor_active_background", t.editor_active_background),
            ("cursorline_bg", t.cursorline_bg),
            ("colorcolumn_bg", t.colorcolumn_bg),
            ("diff_added_bg", t.diff_added_bg),
            ("diff_removed_bg", t.diff_removed_bg),
            ("diff_padding_bg", t.diff_padding_bg),
            ("command_line_bg", t.command_line_bg),
            ("board_selected_card_bg", t.board_selected_card_bg),
            ("board_col_header_bg", t.board_col_header_bg),
            ("card_hint_bg", t.card_hint_bg),
        ];
        for (name, c) in backgrounds {
            let l = luminance(c);
            assert!(
                l > 180.0,
                "{name} = {c:?} reads as dark (luminance {l:.1}) in the light palette"
            );
        }
    }

    /// Symmetric check on the text-ish fields: they must stay dark
    /// enough to read against the light backgrounds asserted above.
    #[test]
    fn light_default_foreground_type_keys_are_dark() {
        let t = Theme::light_default();
        let foregrounds = [
            ("foreground", t.foreground),
            ("tab_active_fg", t.tab_active_fg),
            ("surface_fg", t.surface_fg),
            ("header_fg", t.header_fg),
            ("muted_fg", t.muted_fg),
            ("query_fg", t.query_fg),
            ("hover_fg", t.hover_fg),
            ("completion_fg", t.completion_fg),
            ("line_number_fg", t.line_number_fg),
            ("line_number_active_fg", t.line_number_active_fg),
            ("command_line_fg", t.command_line_fg),
            ("cursor", t.cursor),
        ];
        for (name, c) in foregrounds {
            let l = luminance(c);
            assert!(
                l < 140.0,
                "{name} = {c:?} reads as light (luminance {l:.1}) — too low \
                 contrast against a light background"
            );
        }
    }

    /// Verifies that a light theme built from `light_default()` produces
    /// light colours for all selection and background-type keys, not dark
    /// leaks from spreading `..Theme::default()`.
    #[test]
    fn light_theme_built_from_light_default_does_not_leak_dark_keys() {
        let light = Theme {
            background: Color::rgb(255, 255, 255),
            foreground: Color::rgb(30, 30, 30),
            ..Theme::light_default()
        };
        assert!(
            luminance(light.inactive_selected_bg) > 180.0,
            "inactive_selected_bg leaked a dark default: {:?}",
            light.inactive_selected_bg
        );
        assert!(
            luminance(light.selected_bg) > 180.0,
            "selected_bg leaked a dark default: {:?}",
            light.selected_bg
        );

        // Negative control: the *old* dark `Theme::default()` spread
        // must still fail the same assertion — proving this test
        // actually distinguishes the two palettes rather than passing
        // unconditionally.
        let dark_leak = Theme {
            background: Color::rgb(255, 255, 255),
            foreground: Color::rgb(30, 30, 30),
            ..Theme::default()
        };
        assert!(
            luminance(dark_leak.inactive_selected_bg) < 180.0,
            "negative control: Theme::default()'s inactive_selected_bg should \
             still be dark ({:?}) — if this fails, the fixture changed",
            dark_leak.inactive_selected_bg
        );
    }

    /// `light_default()` is a genuinely distinct palette from
    /// `default()`, not an accidental alias — otherwise it would fix
    /// nothing.
    #[test]
    fn light_default_differs_from_dark_default() {
        assert_ne!(
            Theme::light_default().background,
            Theme::default().background
        );
        assert_ne!(
            Theme::light_default().inactive_selected_bg,
            Theme::default().inactive_selected_bg
        );
    }
}

/// Property tests: `from_vscode_json_str` parses arbitrary (foreign,
/// untrusted) file content — a VS Code theme is just a JSON file someone
/// downloaded — so it must degrade to `None` rather than panic on any
/// input whatsoever, not just the hand-picked fixtures above.
#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        /// No input string, however malformed, may panic — this is the
        /// crate's only exposure to a VS Code theme file, and a theme
        /// file is exactly the kind of thing a user downloads from a
        /// marketplace and hands to us without vetting it first.
        #[test]
        fn from_vscode_json_str_never_panics(s in ".{0,2000}") {
            let _ = Theme::from_vscode_json_str(&s);
        }

        /// Same, but seeded from bytes reinterpreted with `from_utf8_lossy`
        /// rather than `proptest`'s own (valid-UTF8-only) string strategy,
        /// so invalid/truncated multi-byte sequences — the shape a
        /// genuinely hostile or corrupted file would take — are covered
        /// too, not just well-formed-but-weird Unicode.
        #[test]
        fn from_vscode_json_str_never_panics_on_lossy_bytes(bytes in prop::collection::vec(any::<u8>(), 0..2000)) {
            let s = String::from_utf8_lossy(&bytes);
            let _ = Theme::from_vscode_json_str(&s);
        }

        /// A well-formed JSON object whose `colors` values are arbitrary
        /// strings (not necessarily valid `#rrggbb[aa]` hex) must still
        /// parse without panicking — `Color::from_hex` /
        /// `Color::try_from_hex_over` reject anything malformed by
        /// returning `None`, which `from_vscode_json_str` must tolerate
        /// per-key rather than aborting the whole theme.
        #[test]
        fn from_vscode_json_str_tolerates_garbage_colour_values(
            bg in ".{0,20}",
            fg in ".{0,20}",
            sel in ".{0,20}",
        ) {
            let json = serde_json::json!({
                "colors": {
                    "editor.background": bg,
                    "editor.foreground": fg,
                    "editor.selectionBackground": sel,
                }
            })
            .to_string();
            let _ = Theme::from_vscode_json_str(&json);
        }
    }
}